feat(pipes): add filtering, input templates, batch sizes, and DLQ routing (#576)

This commit is contained in:
Christine Nguyen authored and GitHub committed 2026-04-23 22:56:05 -05:00
1 parent df58c71d8b
commit eed72e6222
12 files changed
+2070 -89

No files matched your search

@@ -0,0 +1,201 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@ApplicationScoped
public class PipesFilterMatcher {
private static final Logger LOG = Logger.getLogger(PipesFilterMatcher.class);
private final ObjectMapper objectMapper;
@Inject
public PipesFilterMatcher(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public List<JsonNode> applyFilterCriteria(List<JsonNode> records, JsonNode sourceParameters) {
if (sourceParameters == null) {
return records;
}
JsonNode filters = sourceParameters.path("FilterCriteria").path("Filters");
if (filters.isMissingNode() || !filters.isArray() || filters.isEmpty()) {
return records;
}
List<JsonNode> matched = new ArrayList<>();
for (JsonNode record : records) {
if (matchesAnyFilter(record, filters)) {
matched.add(record);
}
}
return matched;
}
private boolean matchesAnyFilter(JsonNode record, JsonNode filters) {
for (JsonNode filter : filters) {
JsonNode patternNode = filter.path("Pattern");
if (patternNode.isMissingNode()) {
continue;
}
String patternStr = patternNode.isTextual() ? patternNode.asText() : patternNode.toString();
if (matchesRecord(record, patternStr)) {
return true;
}
}
return false;
}
boolean matchesRecord(JsonNode record, String pattern) {
if (pattern == null || pattern.isBlank()) {
return true;
}
try {
JsonNode patternNode = objectMapper.readTree(pattern);
return matchesNode(record, patternNode);
} catch (Exception e) {
LOG.warnv("Failed to parse filter pattern: {0}", e.getMessage());
return false;
}
}
private boolean matchesNode(JsonNode actual, JsonNode pattern) {
if (!pattern.isObject()) {
return false;
}
var fields = pattern.fields();
while (fields.hasNext()) {
var field = fields.next();
String key = field.getKey();
JsonNode patternValue = field.getValue();
JsonNode actualValue = actual.path(key);
if (patternValue.isArray()) {
if (!matchesArrayField(patternValue, actualValue)) {
return false;
}
} else if (patternValue.isObject()) {
JsonNode resolvedActual = resolveActualForObject(actualValue);
if (!matchesNode(resolvedActual, patternValue)) {
return false;
}
} else {
LOG.warnv("Invalid filter pattern: scalar value for key \"{0}\". " +
"Pattern values must be arrays or objects.", key);
return false;
}
}
return true;
}
private JsonNode resolveActualForObject(JsonNode actualValue) {
if (actualValue.isTextual()) {
try {
JsonNode parsed = objectMapper.readTree(actualValue.asText());
if (parsed.isObject() || parsed.isArray()) {
return parsed;
}
} catch (Exception ignored) {
}
}
return actualValue;
}
private boolean matchesArrayField(JsonNode patternArray, JsonNode actualValue) {
for (JsonNode element : patternArray) {
if (matchesSingleElement(element, actualValue)) {
return true;
}
}
return false;
}
private boolean matchesSingleElement(JsonNode element, JsonNode actualValue) {
boolean valueExists = !actualValue.isMissingNode() && !actualValue.isNull();
String actualStr = valueExists && actualValue.isTextual() ? actualValue.asText() : null;
if (element.isTextual()) {
return actualStr != null && actualStr.equals(element.asText());
}
if (element.isNull()) {
return !valueExists;
}
if (element.isNumber()) {
return valueExists && actualValue.isNumber()
&& actualValue.decimalValue().compareTo(element.decimalValue()) == 0;
}
if (element.isObject()) {
if (element.has("prefix")) {
return actualStr != null && actualStr.startsWith(element.get("prefix").asText());
}
if (element.has("suffix")) {
return actualStr != null && actualStr.endsWith(element.get("suffix").asText());
}
if (element.has("equals-ignore-case")) {
return actualStr != null && actualStr.equalsIgnoreCase(element.get("equals-ignore-case").asText());
}
if (element.has("anything-but")) {
JsonNode anythingBut = element.get("anything-but");
if (anythingBut.isArray()) {
if (!valueExists) {
return true;
}
for (JsonNode v : anythingBut) {
if (v.isTextual() && v.asText().equals(actualStr)) {
return false;
}
if (v.isNumber() && actualValue.isNumber()
&& actualValue.decimalValue().compareTo(v.decimalValue()) == 0) {
return false;
}
}
return true;
}
if (anythingBut.isObject() && anythingBut.has("prefix")) {
return !valueExists || (actualStr != null && !actualStr.startsWith(anythingBut.get("prefix").asText()));
}
if (anythingBut.isTextual()) {
return !valueExists || (actualStr != null && !actualStr.equals(anythingBut.asText()));
}
}
if (element.has("exists")) {
boolean shouldExist = element.get("exists").asBoolean();
return shouldExist == valueExists;
}
if (element.has("numeric")) {
return matchesNumericFilter(element.get("numeric"), actualValue);
}
}
return false;
}
private boolean matchesNumericFilter(JsonNode numericArray, JsonNode actualValue) {
if (!actualValue.isNumber() || !numericArray.isArray()) {
return false;
}
BigDecimal actual = actualValue.decimalValue();
for (int i = 0; i + 1 < numericArray.size(); i += 2) {
String op = numericArray.get(i).asText();
BigDecimal operand = numericArray.get(i + 1).decimalValue();
boolean result = switch (op) {
case "=" -> actual.compareTo(operand) == 0;
case ">" -> actual.compareTo(operand) > 0;
case ">=" -> actual.compareTo(operand) >= 0;
case "<" -> actual.compareTo(operand) < 0;
case "<=" -> actual.compareTo(operand) <= 0;
default -> false;
};
if (!result) {
return false;
}
}
return true;
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -17,8 +18,11 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -35,6 +39,7 @@ public class PipesPoller {
private final KinesisService kinesisService;
private final DynamoDbStreamService dynamoDbStreamService;
private final PipesTargetInvoker targetInvoker;
private final PipesFilterMatcher filterMatcher;
private final ObjectMapper objectMapper;
private final String baseUrl;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
@@ -53,6 +58,7 @@ public class PipesPoller {
KinesisService kinesisService,
DynamoDbStreamService dynamoDbStreamService,
PipesTargetInvoker targetInvoker,
PipesFilterMatcher filterMatcher,
ObjectMapper objectMapper,
EmulatorConfig config) {
this.vertx = vertx;
@@ -60,6 +66,7 @@ public class PipesPoller {
this.kinesisService = kinesisService;
this.dynamoDbStreamService = dynamoDbStreamService;
this.targetInvoker = targetInvoker;
this.filterMatcher = filterMatcher;
this.objectMapper = objectMapper;
this.baseUrl = config.effectiveBaseUrl();
}
@@ -129,19 +136,54 @@ public class PipesPoller {
private void pollSqs(Pipe pipe, String region) {
String queueUrl = AwsArnUtils.arnToQueueUrl(pipe.getSource(), baseUrl);
List<Message> messages = sqsService.receiveMessage(queueUrl, DEFAULT_BATCH_SIZE, 30, 0, region);
int batchSize = getBatchSize(pipe, "SqsQueueParameters");
List<Message> messages = sqsService.receiveMessage(queueUrl, batchSize, 30, 0, region);
if (messages.isEmpty()) {
return;
}
LOG.infov("Pipe {0}: received {1} SQS message(s)", pipe.getName(), messages.size());
String eventJson = buildSqsEvent(messages, pipe);
targetInvoker.invoke(pipe, eventJson, region);
List<ObjectNode> recordNodes = buildSqsRecordNodes(messages, pipe);
List<JsonNode> filtered = filterMatcher.applyFilterCriteria(
new ArrayList<>(recordNodes), pipe.getSourceParameters());
// Build a set of messageIds that matched the filter
Set<String> matchedMessageIds = new HashSet<>();
for (JsonNode node : filtered) {
if (node.has("messageId")) {
matchedMessageIds.add(node.get("messageId").asText());
}
}
// Delete non-matching messages immediately (AWS behavior: filtered-out messages are consumed)
for (Message msg : messages) {
try {
sqsService.deleteMessage(queueUrl, msg.getReceiptHandle(), region);
} catch (Exception e) {
LOG.warnv("Pipe {0}: failed to delete SQS message {1}: {2}",
pipe.getName(), msg.getMessageId(), e.getMessage());
if (!matchedMessageIds.contains(msg.getMessageId())) {
try {
sqsService.deleteMessage(queueUrl, msg.getReceiptHandle(), region);
} catch (Exception e) {
LOG.warnv("Pipe {0}: failed to delete SQS message {1}: {2}",
pipe.getName(), msg.getMessageId(), e.getMessage());
}
}
}
if (filtered.isEmpty()) {
return;
}
// Attempt delivery; only delete matching messages after successful delivery or DLQ routing
String eventJson = wrapRecords(filtered);
boolean delivered = invokeWithDlq(pipe, eventJson, region);
if (delivered) {
for (Message msg : messages) {
if (matchedMessageIds.contains(msg.getMessageId())) {
try {
sqsService.deleteMessage(queueUrl, msg.getReceiptHandle(), region);
} catch (Exception e) {
LOG.warnv("Pipe {0}: failed to delete SQS message {1}: {2}",
pipe.getName(), msg.getMessageId(), e.getMessage());
}
}
}
}
}
@@ -149,14 +191,17 @@ public class PipesPoller {
private void pollKinesis(Pipe pipe, String region) {
String pipeKey = pipeKey(pipe);
String streamName = extractResourceName(pipe.getSource());
int batchSize = getBatchSize(pipe, "KinesisStreamParameters");
String iterator = kinesisIterators.get(pipeKey);
if (iterator == null) {
iterator = initKinesisIterator(streamName, region);
if (iterator == null) return;
if (iterator == null) {
return;
}
}
try {
@SuppressWarnings("unchecked")
Map<String, Object> result = kinesisService.getRecords(iterator, DEFAULT_BATCH_SIZE, region);
Map<String, Object> result = kinesisService.getRecords(iterator, batchSize, region);
String nextIterator = (String) result.get("NextShardIterator");
if (nextIterator != null) {
kinesisIterators.put(pipeKey, nextIterator);
@@ -167,8 +212,14 @@ public class PipesPoller {
return;
}
LOG.infov("Pipe {0}: received {1} Kinesis record(s)", pipe.getName(), records.size());
String eventJson = buildKinesisEvent(records, pipe, region);
targetInvoker.invoke(pipe, eventJson, region);
List<ObjectNode> recordNodes = buildKinesisRecordNodes(records, pipe, region);
List<JsonNode> filtered = filterMatcher.applyFilterCriteria(
new ArrayList<>(recordNodes), pipe.getSourceParameters());
if (filtered.isEmpty()) {
return;
}
String eventJson = wrapRecords(filtered);
invokeWithDlq(pipe, eventJson, region);
} catch (AwsException e) {
if ("ExpiredIteratorException".equals(e.getErrorCode())) {
kinesisIterators.remove(pipeKey);
@@ -190,13 +241,16 @@ public class PipesPoller {
private void pollDynamoDbStreams(Pipe pipe, String region) {
String pipeKey = pipeKey(pipe);
String streamArn = pipe.getSource();
int batchSize = getBatchSize(pipe, "DynamoDBStreamParameters");
String iterator = dynamoDbIterators.get(pipeKey);
if (iterator == null) {
iterator = initDynamoDbIterator(streamArn);
if (iterator == null) return;
if (iterator == null) {
return;
}
}
try {
var result = dynamoDbStreamService.getRecords(iterator, DEFAULT_BATCH_SIZE);
var result = dynamoDbStreamService.getRecords(iterator, batchSize);
String nextIterator = result.nextShardIterator();
if (nextIterator != null) {
dynamoDbIterators.put(pipeKey, nextIterator);
@@ -206,8 +260,14 @@ public class PipesPoller {
return;
}
LOG.infov("Pipe {0}: received {1} DynamoDB Stream record(s)", pipe.getName(), records.size());
String eventJson = buildDynamoDbEvent(records, pipe, region);
targetInvoker.invoke(pipe, eventJson, region);
List<ObjectNode> recordNodes = buildDynamoDbRecordNodes(records, pipe, region);
List<JsonNode> filtered = filterMatcher.applyFilterCriteria(
new ArrayList<>(recordNodes), pipe.getSourceParameters());
if (filtered.isEmpty()) {
return;
}
String eventJson = wrapRecords(filtered);
invokeWithDlq(pipe, eventJson, region);
} catch (AwsException e) {
if ("ExpiredIteratorException".equals(e.getErrorCode()) ||
"TrimmedDataAccessException".equals(e.getErrorCode())) {
@@ -227,54 +287,62 @@ public class PipesPoller {
}
}
// ──────────────────────────── Event Builders ────────────────────────────
// ──────────────────────────── Invocation & DLQ ────────────────────────────
private String buildSqsEvent(List<Message> messages, Pipe pipe) {
private boolean invokeWithDlq(Pipe pipe, String eventJson, String region) {
try {
var records = objectMapper.createArrayNode();
for (Message msg : messages) {
ObjectNode record = objectMapper.createObjectNode();
record.put("messageId", msg.getMessageId());
record.put("receiptHandle", msg.getReceiptHandle());
record.put("body", msg.getBody());
ObjectNode attrs = record.putObject("attributes");
attrs.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount()));
attrs.put("SentTimestamp", String.valueOf(System.currentTimeMillis()));
record.putObject("messageAttributes");
record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : "");
record.put("eventSource", "aws:sqs");
record.put("eventSourceARN", pipe.getSource());
record.put("awsRegion", extractRegionFromArn(pipe.getSource()));
records.add(record);
}
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", records);
return objectMapper.writeValueAsString(root);
targetInvoker.invoke(pipe, eventJson, region);
return true;
} catch (Exception e) {
return "{\"Records\":[]}";
LOG.warnv("Pipe {0}: delivery failed: {1} ({2})",
pipe.getName(), e.getMessage(), e.getClass().getSimpleName());
return sendToDeadLetterQueue(pipe, eventJson, region);
}
}
private String buildKinesisEvent(List<?> records, Pipe pipe, String region) {
private boolean sendToDeadLetterQueue(Pipe pipe, String payload, String region) {
String dlqArn = getDlqArn(pipe);
if (dlqArn == null) {
return false;
}
try {
String queueUrl = AwsArnUtils.arnToQueueUrl(dlqArn, baseUrl);
sqsService.sendMessage(queueUrl, payload, 0);
LOG.infov("Pipe {0}: sent failed records to DLQ {1}", pipe.getName(), dlqArn);
return true;
} catch (Exception e) {
LOG.errorv("Pipe {0}: failed to send to DLQ {1}: {2}",
pipe.getName(), dlqArn, e.getMessage());
return false;
}
}
private String getDlqArn(Pipe pipe) {
JsonNode sp = pipe.getSourceParameters();
if (sp == null) {
return null;
}
for (String key : List.of("SqsQueueParameters", "KinesisStreamParameters", "DynamoDBStreamParameters")) {
JsonNode dlq = sp.path(key).path("DeadLetterConfig").path("Arn");
if (!dlq.isMissingNode() && dlq.isTextual()) {
return dlq.asText();
}
}
return null;
}
private int getBatchSize(Pipe pipe, String sourceParamKey) {
JsonNode sp = pipe.getSourceParameters();
if (sp != null && sp.has(sourceParamKey)) {
return sp.path(sourceParamKey).path("BatchSize").asInt(DEFAULT_BATCH_SIZE);
}
return DEFAULT_BATCH_SIZE;
}
private String wrapRecords(List<JsonNode> records) {
try {
var recordsArray = objectMapper.createArrayNode();
for (Object record : records) {
ObjectNode node = objectMapper.valueToTree(record);
ObjectNode eventRecord = objectMapper.createObjectNode();
eventRecord.put("eventSource", "aws:kinesis");
eventRecord.put("eventSourceARN", pipe.getSource());
eventRecord.put("awsRegion", region);
eventRecord.put("eventID", pipe.getSource() + ":" +
node.path("SequenceNumber").asText());
ObjectNode kinesis = eventRecord.putObject("kinesis");
kinesis.put("partitionKey", node.path("PartitionKey").asText());
kinesis.put("sequenceNumber", node.path("SequenceNumber").asText());
kinesis.put("approximateArrivalTimestamp",
node.path("ApproximateArrivalTimestamp").asDouble());
String data = node.path("Data").asText();
kinesis.put("data", data);
recordsArray.add(eventRecord);
}
records.forEach(recordsArray::add);
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", recordsArray);
return objectMapper.writeValueAsString(root);
@@ -283,22 +351,59 @@ public class PipesPoller {
}
}
private String buildDynamoDbEvent(List<?> records, Pipe pipe, String region) {
try {
var recordsArray = objectMapper.createArrayNode();
for (Object record : records) {
ObjectNode node = objectMapper.valueToTree(record);
node.put("eventSource", "aws:dynamodb");
node.put("eventSourceARN", pipe.getSource());
node.put("awsRegion", region);
recordsArray.add(node);
}
ObjectNode root = objectMapper.createObjectNode();
root.set("Records", recordsArray);
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
return "{\"Records\":[]}";
// ──────────────────────────── Record Builders ────────────────────────────
private List<ObjectNode> buildSqsRecordNodes(List<Message> messages, Pipe pipe) {
List<ObjectNode> nodes = new ArrayList<>();
for (Message msg : messages) {
ObjectNode record = objectMapper.createObjectNode();
record.put("messageId", msg.getMessageId());
record.put("receiptHandle", msg.getReceiptHandle());
record.put("body", msg.getBody());
ObjectNode attrs = record.putObject("attributes");
attrs.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount()));
attrs.put("SentTimestamp", String.valueOf(System.currentTimeMillis()));
record.putObject("messageAttributes");
record.put("md5OfBody", msg.getMd5OfBody() != null ? msg.getMd5OfBody() : "");
record.put("eventSource", "aws:sqs");
record.put("eventSourceARN", pipe.getSource());
record.put("awsRegion", extractRegionFromArn(pipe.getSource()));
nodes.add(record);
}
return nodes;
}
private List<ObjectNode> buildKinesisRecordNodes(List<?> records, Pipe pipe, String region) {
List<ObjectNode> nodes = new ArrayList<>();
for (Object record : records) {
ObjectNode node = objectMapper.valueToTree(record);
ObjectNode eventRecord = objectMapper.createObjectNode();
eventRecord.put("eventSource", "aws:kinesis");
eventRecord.put("eventSourceARN", pipe.getSource());
eventRecord.put("awsRegion", region);
eventRecord.put("eventID", pipe.getSource() + ":" +
node.path("SequenceNumber").asText());
ObjectNode kinesis = eventRecord.putObject("kinesis");
kinesis.put("partitionKey", node.path("PartitionKey").asText());
kinesis.put("sequenceNumber", node.path("SequenceNumber").asText());
kinesis.put("approximateArrivalTimestamp",
node.path("ApproximateArrivalTimestamp").asDouble());
kinesis.put("data", node.path("Data").asText());
nodes.add(eventRecord);
}
return nodes;
}
private List<ObjectNode> buildDynamoDbRecordNodes(List<?> records, Pipe pipe, String region) {
List<ObjectNode> nodes = new ArrayList<>();
for (Object record : records) {
ObjectNode node = objectMapper.valueToTree(record);
node.put("eventSource", "aws:dynamodb");
node.put("eventSourceARN", pipe.getSource());
node.put("awsRegion", region);
nodes.add(node);
}
return nodes;
}
// ──────────────────────────── Utilities ────────────────────────────
@@ -314,7 +419,9 @@ public class PipesPoller {
private static String extractResourceName(String arn) {
int slashIdx = arn.lastIndexOf('/');
if (slashIdx >= 0) return arn.substring(slashIdx + 1);
if (slashIdx >= 0) {
return arn.substring(slashIdx + 1);
}
int colonIdx = arn.lastIndexOf(':');
return colonIdx >= 0 ? arn.substring(colonIdx + 1) : arn;
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
@@ -17,11 +18,14 @@ import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApplicationScoped
public class PipesTargetInvoker {
private static final Logger LOG = Logger.getLogger(PipesTargetInvoker.class);
private static final Pattern TEMPLATE_PLACEHOLDER = Pattern.compile("<(\\$[^>]+)>");
private final LambdaService lambdaService;
private final SqsService sqsService;
@@ -50,23 +54,24 @@ public class PipesTargetInvoker {
public void invoke(Pipe pipe, String payload, String region) {
String targetArn = pipe.getTarget();
try {
if (targetArn.contains(":lambda:") || targetArn.contains(":function:")) {
invokeLambda(targetArn, payload, region);
} else if (targetArn.contains(":sqs:")) {
invokeSqs(targetArn, payload);
} else if (targetArn.contains(":sns:")) {
invokeSns(targetArn, payload, region);
} else if (targetArn.contains(":events:")) {
invokeEventBridge(targetArn, payload, region);
} else if (targetArn.contains(":states:")) {
invokeStepFunctions(targetArn, payload, region);
} else {
LOG.warnv("Pipe {0}: unsupported target ARN type: {1}", pipe.getName(), targetArn);
}
} catch (Exception e) {
LOG.warnv("Pipe {0}: failed to deliver to target {1}: {2}",
pipe.getName(), targetArn, e.getMessage());
JsonNode tp = pipe.getTargetParameters();
if (tp != null && tp.has("InputTemplate")) {
payload = applyInputTemplate(tp.get("InputTemplate").asText(), payload);
}
if (targetArn.contains(":lambda:") || targetArn.contains(":function:")) {
invokeLambda(targetArn, payload, region);
} else if (targetArn.contains(":sqs:")) {
invokeSqs(targetArn, payload);
} else if (targetArn.contains(":sns:")) {
invokeSns(targetArn, payload, region);
} else if (targetArn.contains(":events:")) {
invokeEventBridge(targetArn, payload, region);
} else if (targetArn.contains(":states:")) {
invokeStepFunctions(targetArn, payload, region);
} else {
LOG.warnv("Pipe {0}: unsupported target ARN type: {1}", pipe.getName(), targetArn);
}
}
@@ -109,6 +114,41 @@ public class PipesTargetInvoker {
LOG.debugv("Pipe delivered to Step Functions: {0}", arn);
}
String applyInputTemplate(String template, String payload) {
Matcher m = TEMPLATE_PLACEHOLDER.matcher(template);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String jsonPath = m.group(1);
String value = extractJsonPath(jsonPath, payload);
m.appendReplacement(sb, Matcher.quoteReplacement(value != null ? value : ""));
}
m.appendTail(sb);
return sb.toString();
}
String extractJsonPath(String jsonPath, String json) {
if (jsonPath == null || json == null) {
return null;
}
try {
String path = jsonPath.startsWith("$") ? jsonPath.substring(1) : jsonPath;
// Translate array indices [N] to /N for Jackson JSON Pointer
path = path.replaceAll("\\[(\\d+)]", "/$1");
String pointer = path.replace('.', '/');
JsonNode node = objectMapper.readTree(json).at(pointer);
if (node.isMissingNode() || node.isNull()) {
return null;
}
if (node.isValueNode()) {
return objectMapper.writeValueAsString(node);
}
return node.toString();
} catch (Exception e) {
LOG.warnv("Failed to extract JSONPath {0}: {1}", jsonPath, e.getMessage());
return null;
}
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;