From 95aada560f21ea2d69de118daf9e746d53439477 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:05:42 +0100 Subject: [PATCH 01/12] Simplify BSON hex conversion and unsigned byte comparisons --- .../de/bwaldvogel/mongo/bson/BinData.java | 13 +-------- .../java/de/bwaldvogel/mongo/bson/Json.java | 27 ++++++------------- .../de/bwaldvogel/mongo/bson/ObjectId.java | 27 ++++--------------- 3 files changed, 14 insertions(+), 53 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java b/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java index 5cb2c6d1..a0a574e9 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java @@ -41,19 +41,8 @@ public int compareTo(BinData other) { if (bytes1.length != bytes2.length) { return Integer.compare(bytes1.length, bytes2.length); } else { - for (int i = 0; i < bytes1.length; i++) { - int compare = compareUnsigned(bytes1[i], bytes2[i]); - if (compare != 0) return compare; - } - return 0; + return Arrays.compareUnsigned(bytes1, bytes2); } } - // lexicographic byte comparison 0x00 < 0xFF - private static int compareUnsigned(byte b1, byte b2) { - int v1 = (int) b1 & 0xFF; - int v2 = (int) b2 & 0xFF; - return Integer.compare(v1, v2); - } - } diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/Json.java b/core/src/main/java/de/bwaldvogel/mongo/bson/Json.java index 0be9f48d..9c319881 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/Json.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/Json.java @@ -1,8 +1,8 @@ package de.bwaldvogel.mongo.bson; -import java.nio.ByteBuffer; import java.time.Instant; import java.util.Collection; +import java.util.HexFormat; import java.util.UUID; import java.util.stream.Collectors; @@ -76,28 +76,17 @@ static String escapeJson(String input) { return escaped; } - private static StringBuilder toHex(UUID uuid) { - byte[] bytes = toBytes(uuid); - StringBuilder hex = new StringBuilder(); - for (int i = bytes.length; i > 0; i--) { - hex.append(String.format("%02X", bytes[i - 1])); - } - return hex; + private static String toHex(UUID uuid) { + return toLittleEndianHex(uuid.getMostSignificantBits()) + + toLittleEndianHex(uuid.getLeastSignificantBits()); } - private static StringBuilder toHex(byte[] bytes) { - StringBuilder hex = new StringBuilder(); - for (byte aByte : bytes) { - hex.append(String.format("%02X", aByte)); - } - return hex; + private static String toLittleEndianHex(long value) { + return HexFormat.of().withUpperCase().toHexDigits(Long.reverseBytes(value)); } - private static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - byteBuffer.putLong(uuid.getMostSignificantBits()); - return byteBuffer.array(); + private static String toHex(byte[] bytes) { + return HexFormat.of().withUpperCase().formatHex(bytes); } } diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java b/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java index 21f4dea4..1e8c1c4a 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/ObjectId.java @@ -4,6 +4,7 @@ import java.security.SecureRandom; import java.util.Arrays; +import java.util.HexFormat; import java.util.regex.Pattern; import de.bwaldvogel.mongo.backend.Assert; @@ -26,13 +27,8 @@ public ObjectId(String hexString) { if (!PATTERN.matcher(hexString).matches()) { throw new IllegalArgumentException("Failed to parse '" + hexString + "'"); } - int len = hexString.length(); - Assert.equals(hexString.length(), data.length * 2L); - for (int i = 0; i < len; i += 2) { - int first = Character.digit(hexString.charAt(i), 16) << 4; - int second = Character.digit(hexString.charAt(i + 1), 16); - data[i / 2] = (byte) (first + second); - } + byte[] parsed = HexFormat.of().parseHex(hexString); + System.arraycopy(parsed, 0, data, 0, data.length); } public ObjectId(byte[] data) { @@ -46,16 +42,7 @@ public byte[] toByteArray() { @Override public int compareTo(final ObjectId other) { - byte[] byteArray = toByteArray(); - byte[] otherByteArray = other.toByteArray(); - for (int i = 0; i < LENGTH_OBJECTID; i++) { - if (byteArray[i] != otherByteArray[i]) { - int thisByte = byteArray[i] & 0xFF; - int otherByte = otherByteArray[i] & 0xFF; - return (thisByte < otherByte) ? -1 : 1; - } - } - return 0; + return Arrays.compareUnsigned(toByteArray(), other.toByteArray()); } @Override @@ -84,11 +71,7 @@ public String toString() { } public String getHexData() { - StringBuilder sb = new StringBuilder(); - for (byte b : data) { - sb.append(String.format("%02x", b)); - } - return sb.toString(); + return HexFormat.of().formatHex(data); } } From 5a2a4c07c342c5029e1d2f49b33dffccc627fc1c Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:08:38 +0100 Subject: [PATCH 02/12] Modernize collection constants and sequenced collection access --- .../de/bwaldvogel/mongo/ServerVersion.java | 3 +- .../mongo/backend/AbstractMongoDatabase.java | 4 +- .../mongo/backend/ArrayFilters.java | 2 +- .../mongo/backend/CollectionUtils.java | 2 +- .../mongo/backend/FieldUpdates.java | 4 +- .../de/bwaldvogel/mongo/backend/Index.java | 2 +- .../de/bwaldvogel/mongo/backend/KeyValue.java | 2 +- .../de/bwaldvogel/mongo/backend/Utils.java | 2 +- .../mongo/backend/ValueComparator.java | 37 ++++++++----------- .../mongo/backend/aggregation/Expression.java | 3 +- .../accumulator/AddToSetAccumulator.java | 9 ++--- .../backend/aggregation/stage/FacetStage.java | 3 +- .../aggregation/stage/GraphLookupStage.java | 14 +------ .../aggregation/stage/LookupStage.java | 11 +----- .../stage/LookupWithPipelineStage.java | 12 +----- 15 files changed, 37 insertions(+), 73 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/ServerVersion.java b/core/src/main/java/de/bwaldvogel/mongo/ServerVersion.java index 387575b4..19225416 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/ServerVersion.java +++ b/core/src/main/java/de/bwaldvogel/mongo/ServerVersion.java @@ -1,6 +1,5 @@ package de.bwaldvogel.mongo; -import java.util.Collections; import java.util.List; public enum ServerVersion implements MongoVersion { @@ -32,7 +31,7 @@ public enum ServerVersion implements MongoVersion { @Override public List getVersionArray() { - return Collections.unmodifiableList(versionArray); + return versionArray; } @Override diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java index 5beab0f0..710286da 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java @@ -553,7 +553,7 @@ private Document commandGetLastError(Channel channel, String command, Document q Document result; if (results != null && !results.isEmpty()) { - result = results.get(results.size() - 1); + result = results.getLast(); if (result == null) { result = new Document(); } @@ -891,7 +891,7 @@ private Document toError(Channel channel, MongoServerException ex) { protected void putLastResult(Channel channel, Document result) { List results = lastResults.get(channel); // list must not be empty - Document last = results.get(results.size() - 1); + Document last = results.getLast(); Assert.isNull(last, () -> "last result already set: " + last); results.set(results.size() - 1, result); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/ArrayFilters.java b/core/src/main/java/de/bwaldvogel/mongo/backend/ArrayFilters.java index f1b68b41..db52147b 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/ArrayFilters.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/ArrayFilters.java @@ -38,7 +38,7 @@ private static ArrayFilters parse(List arrayFilters, Document updateQu List topLevelFieldNames = arrayFilter.keySet().stream() .map(Utils::firstFragment) .distinct() - .collect(Collectors.toList()); + .toList(); if (topLevelFieldNames.size() > 1) { throw new FailedToParseException("Error parsing array filter :: caused by ::" + diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java b/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java index 8925ba29..e9932956 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java @@ -22,7 +22,7 @@ public static T getSingleElement(Iterable iterable) { public static T getLastElement(List list) { Assert.notEmpty(list); - return list.get(list.size() - 1); + return list.getLast(); } public static T getSingleElement(Iterable iterable, Supplier exceptionSupplier) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java b/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java index 21980f6a..d60edfb0 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java @@ -325,9 +325,9 @@ private void handlePop(String modifier, String key, Object popValue) { if (!list.isEmpty()) { if (Utils.nullAwareEquals(normalizedValue, -1)) { - list.remove(0); + list.removeFirst(); } else { - list.remove(list.size() - 1); + list.removeLast(); } } } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java index 56ea5e3b..9e8fd24e 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java @@ -89,7 +89,7 @@ private void validateHasNoParallelArrays(Document document) { } if (arrayPaths.size() > 1) { List parallelArraysPaths = arrayPaths.stream() - .map(path -> path.get(path.size() - 1)) + .map(List::getLast) .collect(Collectors.toList()); throw new CannotIndexParallelArraysError(parallelArraysPaths); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java index 1c48b73f..f9b99527 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java @@ -71,7 +71,7 @@ public Stream stream() { public KeyValue normalized() { return new KeyValue(values.stream() .map(Utils::normalizeValue) - .collect(Collectors.toList())); + .toList()); } } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Utils.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Utils.java index b464c7dc..d703afba 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Utils.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Utils.java @@ -602,7 +602,7 @@ private static List collectCommonPathFragments(List fragments1, static String getLastFragment(String path) { List fragments = splitPath(path); - return fragments.get(fragments.size() - 1); + return fragments.getLast(); } public static String getHostName() { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java b/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java index c25a5cff..a20466c1 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java @@ -19,7 +19,22 @@ public class ValueComparator implements Comparator { - private static final List> SORT_PRIORITY = new ArrayList<>(); + // https://docs.mongodb.com/manual/reference/bson-type-comparison-order/ + private static final List> SORT_PRIORITY = List.of( + MinKey.class, + Number.class, + String.class, + Document.class, + List.class, + BinData.class, + LegacyUUID.class, + UUID.class, + ObjectId.class, + Boolean.class, + Instant.class, + BsonTimestamp.class, + BsonRegularExpression.class, + MaxKey.class); private static final ValueComparator ASCENDING = new ValueComparator(true); private static final ValueComparator DESCENDING = new ValueComparator(false); @@ -40,26 +55,6 @@ public static ValueComparator desc() { return DESCENDING; } - static { - /* - * https://docs.mongodb.com/manual/reference/bson-type-comparison-order/ - */ - SORT_PRIORITY.add(MinKey.class); - SORT_PRIORITY.add(Number.class); - SORT_PRIORITY.add(String.class); - SORT_PRIORITY.add(Document.class); - SORT_PRIORITY.add(List.class); - SORT_PRIORITY.add(BinData.class); - SORT_PRIORITY.add(LegacyUUID.class); - SORT_PRIORITY.add(UUID.class); - SORT_PRIORITY.add(ObjectId.class); - SORT_PRIORITY.add(Boolean.class); - SORT_PRIORITY.add(Instant.class); - SORT_PRIORITY.add(BsonTimestamp.class); - SORT_PRIORITY.add(BsonRegularExpression.class); - SORT_PRIORITY.add(MaxKey.class); - } - private ValueComparator(boolean ascending) { this(ascending, true); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java index ef9bb33f..f06dd396 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map.Entry; @@ -1776,7 +1775,7 @@ Object apply(List expressionValue, Document document) { } }; - private static final Set KEYWORD_EXPRESSIONS = new HashSet<>(asList("$$PRUNE", "$$KEEP", "$$DESCEND")); + private static final Set KEYWORD_EXPRESSIONS = Set.of("$$PRUNE", "$$KEEP", "$$DESCEND"); private static final SecureRandom random = new SecureRandom(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/accumulator/AddToSetAccumulator.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/accumulator/AddToSetAccumulator.java index ced929af..589af2f7 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/accumulator/AddToSetAccumulator.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/accumulator/AddToSetAccumulator.java @@ -1,16 +1,15 @@ package de.bwaldvogel.mongo.backend.aggregation.accumulator; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; -import java.util.Set; +import java.util.SequencedSet; import de.bwaldvogel.mongo.backend.Missing; public class AddToSetAccumulator extends Accumulator { - private final Set result = new LinkedHashSet<>(); + private final SequencedSet result = new LinkedHashSet<>(); public AddToSetAccumulator(String field, Object expression) { super(field, expression); @@ -26,8 +25,6 @@ public void aggregate(Object value) { @Override public List getResult() { - List list = new ArrayList<>(result); - Collections.reverse(list); - return list; + return new ArrayList<>(result.reversed()); } } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/FacetStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/FacetStage.java index eae8e8cb..bdf4fd7c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/FacetStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/FacetStage.java @@ -4,7 +4,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.stream.Collectors; import java.util.stream.Stream; import de.bwaldvogel.mongo.MongoCollection; @@ -33,7 +32,7 @@ public String name() { @Override public Stream apply(Stream stream) { - List allDocuments = stream.collect(Collectors.toList()); + List allDocuments = stream.toList(); Document result = new Document(); for (Entry entry : facets.entrySet()) { Aggregation aggregation = entry.getValue(); diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java index 40c88441..aec891a3 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java @@ -3,7 +3,6 @@ import static java.util.stream.Collectors.toList; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; @@ -22,17 +21,8 @@ public class GraphLookupStage extends AbstractLookupStage { private static final String MAX_DEPTH = "maxDepth"; private static final String DEPTH_FIELD = "depthField"; - private static final Set CONFIGURATION_KEYS; - static { - CONFIGURATION_KEYS = new HashSet<>(); - CONFIGURATION_KEYS.add(FROM); - CONFIGURATION_KEYS.add(START_WITH); - CONFIGURATION_KEYS.add(CONNECT_FROM_FIELD); - CONFIGURATION_KEYS.add(CONNECT_TO_FIELD); - CONFIGURATION_KEYS.add(AS); - CONFIGURATION_KEYS.add(MAX_DEPTH); - CONFIGURATION_KEYS.add(DEPTH_FIELD); - } + private static final Set CONFIGURATION_KEYS = Set.of( + FROM, START_WITH, CONNECT_FROM_FIELD, CONNECT_TO_FIELD, AS, MAX_DEPTH, DEPTH_FIELD); private final String connectFromField; private final String connectToField; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java index 03b3b39a..5cbfe365 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java @@ -3,7 +3,6 @@ import static java.util.stream.Collectors.toList; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; @@ -19,14 +18,8 @@ public class LookupStage extends AbstractLookupStage { private static final String LOCAL_FIELD = "localField"; private static final String FOREIGN_FIELD = "foreignField"; - private static final Set CONFIGURATION_KEYS; - static { - CONFIGURATION_KEYS = new HashSet<>(); - CONFIGURATION_KEYS.add(FROM); - CONFIGURATION_KEYS.add(LOCAL_FIELD); - CONFIGURATION_KEYS.add(FOREIGN_FIELD); - CONFIGURATION_KEYS.add(AS); - } + private static final Set CONFIGURATION_KEYS = Set.of( + FROM, LOCAL_FIELD, FOREIGN_FIELD, AS); private final String localField; private final String foreignField; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStage.java index 75cd4323..39510b7f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStage.java @@ -1,6 +1,5 @@ package de.bwaldvogel.mongo.backend.aggregation.stage; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -20,15 +19,8 @@ public class LookupWithPipelineStage extends AbstractLookupStage { private static final String LET_FIELD = "let"; public static final String PIPELINE_FIELD = "pipeline"; - private static final Set CONFIGURATION_KEYS; - - static { - CONFIGURATION_KEYS = new HashSet<>(); - CONFIGURATION_KEYS.add(FROM); - CONFIGURATION_KEYS.add(LET_FIELD); - CONFIGURATION_KEYS.add(PIPELINE_FIELD); - CONFIGURATION_KEYS.add(AS); - } + private static final Set CONFIGURATION_KEYS = Set.of( + FROM, LET_FIELD, PIPELINE_FIELD, AS); private final MongoDatabase mongoDatabase; private final DatabaseResolver databaseResolver; From e06b4ec0b6fbcc281a9e5977345905beab676704 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:09:20 +0100 Subject: [PATCH 03/12] Simplify type checks and BSON switches with pattern matching --- .../mongo/backend/DefaultQueryMatcher.java | 3 +- .../mongo/backend/LinkedTreeSet.java | 3 +- .../backend/aggregation/ExpressionTraits.java | 41 ++--- .../de/bwaldvogel/mongo/bson/Document.java | 4 +- .../mongo/wire/bson/BsonDecoder.java | 61 +++---- .../mongo/wire/bson/BsonEncoder.java | 170 ++++++++---------- 6 files changed, 116 insertions(+), 166 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/DefaultQueryMatcher.java b/core/src/main/java/de/bwaldvogel/mongo/backend/DefaultQueryMatcher.java index a4048389..4d81d39b 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/DefaultQueryMatcher.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/DefaultQueryMatcher.java @@ -44,13 +44,12 @@ public boolean matches(Document document, Document query) { } private void validateQueryValue(Object queryValue, String key) { - if (!(queryValue instanceof Document)) { + if (!(queryValue instanceof Document queryObject)) { return; } if (BsonRegularExpression.isRegularExpression(queryValue)) { return; } - Document queryObject = (Document) queryValue; if (!queryObject.keySet().isEmpty() && queryObject.keySet().iterator().next().startsWith("$")) { for (String operator : queryObject.keySet()) { if (Constants.REFERENCE_KEYS.contains(operator)) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/LinkedTreeSet.java b/core/src/main/java/de/bwaldvogel/mongo/backend/LinkedTreeSet.java index aa184a0a..adb05c59 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/LinkedTreeSet.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/LinkedTreeSet.java @@ -99,10 +99,9 @@ public boolean equals(Object o) { if (o == null) { return false; } - if (!(o instanceof LinkedTreeSet)) { + if (!(o instanceof LinkedTreeSet otherSet)) { return false; } - LinkedTreeSet otherSet = (LinkedTreeSet) o; return orderedElements.equals(otherSet.orderedElements); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java index 4387d43d..58c36e74 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java @@ -33,10 +33,10 @@ default Object requireSingleValue(List list) { default String requireSingleStringValue(List expressionValue) { Object value = requireSingleValue(expressionValue); - if (!(value instanceof String)) { + if (!(value instanceof String string)) { throw new MongoServerError(ErrorCode._34471, name() + " requires a string argument, found: " + describeType(value)); } - return (String) value; + return string; } default Number evaluateNumericValue(List expressionValue, Function function) { @@ -44,11 +44,10 @@ default Number evaluateNumericValue(List expressionValue, Function value, int erro return null; } - if (!(one instanceof Number && other instanceof Number)) { + if (!(one instanceof Number firstNumber && other instanceof Number secondNumber)) { throw new MongoServerError(errorCode, name() + " only supports numeric types, not " + describeType(one) + " and " + describeType(other)); } - return new TwoNumericParameters((Number) one, (Number) other); + return new TwoNumericParameters(firstNumber, secondNumber); } default ZonedDateTime getZonedDateTime(Object value, Document document) { @@ -124,20 +123,18 @@ default ZonedDateTime getZonedDateTime(Object value, Document document) { timezone = ZoneId.of(timezoneExpression.toString()); } } - if (!(value instanceof Instant)) { + if (!(value instanceof Instant instant)) { throw new MongoServerError(16006, "can't convert from " + describeType(value) + " to Date"); } - Instant instant = (Instant) value; return ZonedDateTime.ofInstant(instant, timezone); } default int requireIntegral(Object value, String name) { - if (!(value instanceof Number)) { + if (!(value instanceof Number number)) { throw new MongoServerError(40096, name() + " requires an integral " + name + ", found a value of type: " + describeType(value) + ", with value: \"" + value + "\""); } - Number number = (Number) value; int intValue = number.intValue(); if (intValue < 0) { throw new MongoServerError(40097, name() + " requires a nonnegative " + name + ", found: " + intValue); @@ -166,18 +163,18 @@ default Object evaluateIndexOf(List expressionValue, if (first == null) { return null; } - if (!(first instanceof String)) { + if (!(first instanceof String firstString)) { throw new MongoServerError(errorCodeFirstParameterTypeMismatch, name() + " requires a string as the first argument, found: " + describeType(first)); } - List elementsToSearchIn = toList.apply((String) first); + List elementsToSearchIn = toList.apply(firstString); Object searchValue = expressionValue.get(1); - if (!(searchValue instanceof String)) { + if (!(searchValue instanceof String searchString)) { throw new MongoServerError(errorCodeSecondParameterTypeMismatch, name() + " requires a string as the second argument, found: " + describeType(searchValue)); } - List search = toList.apply((String) searchValue); + List search = toList.apply(searchString); Range range = indexOf(expressionValue, elementsToSearchIn.size()); @@ -207,18 +204,18 @@ default Range indexOf(List expressionValue, int size) { } default Collection requireArray(int errorCode, Object value) { - if (!(value instanceof Collection)) { + if (!(value instanceof Collection collection)) { throw new MongoServerError(errorCode, "The argument to " + name() + " must be an array, but was of type: " + describeType(value)); } - return (Collection) value; + return collection; } default Document requireDocument(Object expressionValue, int errorCode) { - if (!(expressionValue instanceof Document)) { + if (!(expressionValue instanceof Document document)) { throw new MongoServerError(errorCode, name() + " only supports an object as its argument"); } - return (Document) expressionValue; + return document; } default String evaluateString(List expressionValue, Function function) { @@ -231,12 +228,12 @@ default String evaluateString(List expressionValue, Function default String convertToString(Object value) { if (isNullOrMissing(value)) { return null; - } else if (value instanceof String) { - return (String) value; + } else if (value instanceof String string) { + return string; } else if (value instanceof Number) { return value.toString(); - } else if (value instanceof ObjectId) { - return ((ObjectId) value).getHexData(); + } else if (value instanceof ObjectId objectId) { + return objectId.getHexData(); } throw new MongoServerError(16007, "can't convert from BSON type " + describeType(value) + " to String"); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java b/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java index c92c945a..985e8a38 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java +++ b/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java @@ -159,11 +159,11 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (!(o instanceof Document)) { + if (!(o instanceof Document other)) { return false; } List keys = new ArrayList<>(keySet()); - List otherKeys = new ArrayList<>(((Document) o).keySet()); + List otherKeys = new ArrayList<>(other.keySet()); if (!keys.equals(otherKeys)) { return false; } diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonDecoder.java b/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonDecoder.java index 027c69cd..8cbb581c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonDecoder.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonDecoder.java @@ -51,47 +51,28 @@ public static Document decodeBson(ByteBuf buffer) { } public static Object decodeValue(byte type, ByteBuf buffer) { - switch (type) { - case BsonConstants.TYPE_DOUBLE: - return Double.valueOf(Double.longBitsToDouble(buffer.readLongLE())); - case BsonConstants.TYPE_UTF8_STRING: - return decodeString(buffer); - case BsonConstants.TYPE_EMBEDDED_DOCUMENT: - return decodeBson(buffer); - case BsonConstants.TYPE_ARRAY: - return decodeArray(buffer); - case BsonConstants.TYPE_DATA: - return decodeBinary(buffer); - case BsonConstants.TYPE_UNDEFINED: - case BsonConstants.TYPE_NULL: - return null; - case BsonConstants.TYPE_OBJECT_ID: - return decodeObjectId(buffer); - case BsonConstants.TYPE_BOOLEAN: - return decodeBoolean(buffer); - case BsonConstants.TYPE_UTC_DATETIME: - return Instant.ofEpochMilli(buffer.readLongLE()); - case BsonConstants.TYPE_REGEX: - return decodePattern(buffer); - case BsonConstants.TYPE_INT32: - return Integer.valueOf(buffer.readIntLE()); - case BsonConstants.TYPE_TIMESTAMP: - return new BsonTimestamp(buffer.readLongLE()); - case BsonConstants.TYPE_INT64: - return Long.valueOf(buffer.readLongLE()); - case BsonConstants.TYPE_DECIMAL128: - return new Decimal128(buffer.readLongLE(), buffer.readLongLE()); - case BsonConstants.TYPE_MAX_KEY: - return MaxKey.getInstance(); - case BsonConstants.TYPE_MIN_KEY: - return MinKey.getInstance(); - case BsonConstants.TYPE_JAVASCRIPT_CODE: - return new BsonJavaScript(decodeString(buffer)); - case BsonConstants.TYPE_JAVASCRIPT_CODE_WITH_SCOPE: + return switch (type) { + case BsonConstants.TYPE_DOUBLE -> Double.valueOf(Double.longBitsToDouble(buffer.readLongLE())); + case BsonConstants.TYPE_UTF8_STRING -> decodeString(buffer); + case BsonConstants.TYPE_EMBEDDED_DOCUMENT -> decodeBson(buffer); + case BsonConstants.TYPE_ARRAY -> decodeArray(buffer); + case BsonConstants.TYPE_DATA -> decodeBinary(buffer); + case BsonConstants.TYPE_UNDEFINED, BsonConstants.TYPE_NULL -> null; + case BsonConstants.TYPE_OBJECT_ID -> decodeObjectId(buffer); + case BsonConstants.TYPE_BOOLEAN -> decodeBoolean(buffer); + case BsonConstants.TYPE_UTC_DATETIME -> Instant.ofEpochMilli(buffer.readLongLE()); + case BsonConstants.TYPE_REGEX -> decodePattern(buffer); + case BsonConstants.TYPE_INT32 -> Integer.valueOf(buffer.readIntLE()); + case BsonConstants.TYPE_TIMESTAMP -> new BsonTimestamp(buffer.readLongLE()); + case BsonConstants.TYPE_INT64 -> Long.valueOf(buffer.readLongLE()); + case BsonConstants.TYPE_DECIMAL128 -> new Decimal128(buffer.readLongLE(), buffer.readLongLE()); + case BsonConstants.TYPE_MAX_KEY -> MaxKey.getInstance(); + case BsonConstants.TYPE_MIN_KEY -> MinKey.getInstance(); + case BsonConstants.TYPE_JAVASCRIPT_CODE -> new BsonJavaScript(decodeString(buffer)); + case BsonConstants.TYPE_JAVASCRIPT_CODE_WITH_SCOPE -> throw new IllegalArgumentException("unhandled type: 0x" + Integer.toHexString(type)); - default: - throw new IllegalArgumentException("unknown type: 0x" + Integer.toHexString(type)); - } + default -> throw new IllegalArgumentException("unknown type: 0x" + Integer.toHexString(type)); + }; } private static BsonRegularExpression decodePattern(ByteBuf buffer) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonEncoder.java b/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonEncoder.java index 2f4dea3a..f2fb8edc 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonEncoder.java +++ b/core/src/main/java/de/bwaldvogel/mongo/wire/bson/BsonEncoder.java @@ -64,150 +64,124 @@ private static void encodeValue(String key, Object value, ByteBuf buffer) { public static void encodeValue(byte type, Object value, ByteBuf buffer) { switch (type) { - case BsonConstants.TYPE_DOUBLE: + case BsonConstants.TYPE_DOUBLE -> buffer.writeLongLE(Double.doubleToRawLongBits(((Double) value).doubleValue())); - break; - case BsonConstants.TYPE_UTF8_STRING: - encodeString(value.toString(), buffer); - break; - case BsonConstants.TYPE_EMBEDDED_DOCUMENT: + case BsonConstants.TYPE_UTF8_STRING -> encodeString(value.toString(), buffer); + case BsonConstants.TYPE_EMBEDDED_DOCUMENT -> { @SuppressWarnings("unchecked") Map valueAsMap = (Map) value; encodeDocument(valueAsMap, buffer); - break; - case BsonConstants.TYPE_ARRAY: + } + case BsonConstants.TYPE_ARRAY -> { Document document = new Document(); List array = collectionToList(value); for (int i = 0; i < array.size(); i++) { document.put(String.valueOf(i), array.get(i)); } encodeDocument(document, buffer); - break; - case BsonConstants.TYPE_DATA: - if (value instanceof BinData) { - byte[] data = ((BinData) value).getData(); - buffer.writeIntLE(data.length); - buffer.writeByte(BsonConstants.BINARY_SUBTYPE_GENERIC); - buffer.writeBytes(data); - } else if (value instanceof UUID || value instanceof LegacyUUID) { - buffer.writeIntLE(BsonConstants.LENGTH_UUID); - - final UUID uuid; - if (value instanceof LegacyUUID) { - buffer.writeByte(BsonConstants.BINARY_SUBTYPE_OLD_UUID); - uuid = ((LegacyUUID) value).getUuid(); - buffer.writeLongLE(uuid.getMostSignificantBits()); - buffer.writeLongLE(uuid.getLeastSignificantBits()); - } else { + } + case BsonConstants.TYPE_DATA -> { + switch (value) { + case BinData binData -> { + byte[] data = binData.getData(); + buffer.writeIntLE(data.length); + buffer.writeByte(BsonConstants.BINARY_SUBTYPE_GENERIC); + buffer.writeBytes(data); + } + case UUID uuid -> { + buffer.writeIntLE(BsonConstants.LENGTH_UUID); buffer.writeByte(BsonConstants.BINARY_SUBTYPE_UUID); - uuid = (UUID) value; buffer.writeLong(uuid.getMostSignificantBits()); buffer.writeLong(uuid.getLeastSignificantBits()); } - } else { - throw new IllegalArgumentException("Unknown data: " + value.getClass()); + case LegacyUUID legacyUUID -> { + UUID uuid = legacyUUID.getUuid(); + buffer.writeIntLE(BsonConstants.LENGTH_UUID); + buffer.writeByte(BsonConstants.BINARY_SUBTYPE_OLD_UUID); + buffer.writeLongLE(uuid.getMostSignificantBits()); + buffer.writeLongLE(uuid.getLeastSignificantBits()); + } + default -> throw new IllegalArgumentException("Unknown data: " + value.getClass()); } - break; - case BsonConstants.TYPE_OBJECT_ID: + } + case BsonConstants.TYPE_OBJECT_ID -> { byte[] bytes = ((ObjectId) value).toByteArray(); if (bytes.length != BsonConstants.LENGTH_OBJECTID) { throw new IllegalArgumentException("Illegal ObjectId: " + value); } buffer.writeBytes(bytes); - break; - case BsonConstants.TYPE_BOOLEAN: + } + case BsonConstants.TYPE_BOOLEAN -> { if (((Boolean) value).booleanValue()) { buffer.writeByte(BsonConstants.BOOLEAN_VALUE_TRUE); } else { buffer.writeByte(BsonConstants.BOOLEAN_VALUE_FALSE); } - break; - case BsonConstants.TYPE_UTC_DATETIME: + } + case BsonConstants.TYPE_UTC_DATETIME -> { Instant instant = (Instant) value; buffer.writeLongLE(instant.toEpochMilli()); - break; - case BsonConstants.TYPE_REGEX: + } + case BsonConstants.TYPE_REGEX -> { BsonRegularExpression pattern = (BsonRegularExpression) value; encodeCString(pattern.getPattern(), buffer); encodeCString(pattern.getOptions(), buffer); - break; - case BsonConstants.TYPE_INT32: - buffer.writeIntLE(((Integer) value).intValue()); - break; - case BsonConstants.TYPE_TIMESTAMP: + } + case BsonConstants.TYPE_INT32 -> buffer.writeIntLE(((Integer) value).intValue()); + case BsonConstants.TYPE_TIMESTAMP -> { BsonTimestamp timestamp = (BsonTimestamp) value; buffer.writeLongLE(timestamp.getValue()); - break; - case BsonConstants.TYPE_INT64: - buffer.writeLongLE(((Long) value).longValue()); - break; - case BsonConstants.TYPE_DECIMAL128: + } + case BsonConstants.TYPE_INT64 -> buffer.writeLongLE(((Long) value).longValue()); + case BsonConstants.TYPE_DECIMAL128 -> { Decimal128 decimal128 = (Decimal128) value; buffer.writeLongLE(decimal128.getLow()); buffer.writeLongLE(decimal128.getHigh()); - break; - case BsonConstants.TYPE_MAX_KEY: - case BsonConstants.TYPE_MIN_KEY: - case BsonConstants.TYPE_UNDEFINED: - case BsonConstants.TYPE_NULL: + } + case BsonConstants.TYPE_MAX_KEY, BsonConstants.TYPE_MIN_KEY, + BsonConstants.TYPE_UNDEFINED, BsonConstants.TYPE_NULL -> { // empty - break; - case BsonConstants.TYPE_JAVASCRIPT_CODE: + } + case BsonConstants.TYPE_JAVASCRIPT_CODE -> { BsonJavaScript javaScript = (BsonJavaScript) value; encodeString(javaScript.getCode(), buffer); - break; - case BsonConstants.TYPE_JAVASCRIPT_CODE_WITH_SCOPE: + } + case BsonConstants.TYPE_JAVASCRIPT_CODE_WITH_SCOPE -> throw new IllegalArgumentException("unhandled type: " + value.getClass()); - default: - throw new IllegalArgumentException("unknown type: " + value.getClass()); + default -> throw new IllegalArgumentException("unknown type: " + value.getClass()); } } public static byte determineType(Object value) { - if (value == null) { - return BsonConstants.TYPE_NULL; - } else if (value instanceof Map) { - return BsonConstants.TYPE_EMBEDDED_DOCUMENT; - } else if (value instanceof ObjectId) { - return BsonConstants.TYPE_OBJECT_ID; - } else if (value instanceof Integer) { - return BsonConstants.TYPE_INT32; - } else if (value instanceof Long) { - return BsonConstants.TYPE_INT64; - } else if (value instanceof Decimal128) { - return BsonConstants.TYPE_DECIMAL128; - } else if (value instanceof Double) { - return BsonConstants.TYPE_DOUBLE; - } else if (value instanceof String) { - return BsonConstants.TYPE_UTF8_STRING; - } else if (value instanceof Boolean) { - return BsonConstants.TYPE_BOOLEAN; - } else if (value instanceof BinData || value instanceof UUID || value instanceof LegacyUUID) { - return BsonConstants.TYPE_DATA; - } else if (value instanceof Collection) { - return BsonConstants.TYPE_ARRAY; - } else if (value instanceof Instant) { - return BsonConstants.TYPE_UTC_DATETIME; - } else if (value instanceof BsonTimestamp) { - return BsonConstants.TYPE_TIMESTAMP; - } else if (value instanceof BsonRegularExpression) { - return BsonConstants.TYPE_REGEX; - } else if (value instanceof MaxKey) { - return BsonConstants.TYPE_MAX_KEY; - } else if (value instanceof MinKey) { - return BsonConstants.TYPE_MIN_KEY; - } else if (value instanceof BsonJavaScript) { - return BsonConstants.TYPE_JAVASCRIPT_CODE; - } else if (value instanceof Missing) { - throw new IllegalArgumentException("Unexpected missing value. This must not happen. Please report a bug."); - } else { - throw new IllegalArgumentException("Unknown type: " + value.getClass()); - } + return switch (value) { + case null -> BsonConstants.TYPE_NULL; + case Map map -> BsonConstants.TYPE_EMBEDDED_DOCUMENT; + case ObjectId objectId -> BsonConstants.TYPE_OBJECT_ID; + case Integer integer -> BsonConstants.TYPE_INT32; + case Long longValue -> BsonConstants.TYPE_INT64; + case Decimal128 decimal128 -> BsonConstants.TYPE_DECIMAL128; + case Double doubleValue -> BsonConstants.TYPE_DOUBLE; + case String string -> BsonConstants.TYPE_UTF8_STRING; + case Boolean booleanValue -> BsonConstants.TYPE_BOOLEAN; + case BinData binData -> BsonConstants.TYPE_DATA; + case UUID uuid -> BsonConstants.TYPE_DATA; + case LegacyUUID legacyUUID -> BsonConstants.TYPE_DATA; + case Collection collection -> BsonConstants.TYPE_ARRAY; + case Instant instant -> BsonConstants.TYPE_UTC_DATETIME; + case BsonTimestamp timestamp -> BsonConstants.TYPE_TIMESTAMP; + case BsonRegularExpression pattern -> BsonConstants.TYPE_REGEX; + case MaxKey maxKey -> BsonConstants.TYPE_MAX_KEY; + case MinKey minKey -> BsonConstants.TYPE_MIN_KEY; + case BsonJavaScript javaScript -> BsonConstants.TYPE_JAVASCRIPT_CODE; + case Missing missing -> throw new IllegalArgumentException( + "Unexpected missing value. This must not happen. Please report a bug."); + default -> throw new IllegalArgumentException("Unknown type: " + value.getClass()); + }; } private static List collectionToList(Object value) { - if (value instanceof List) { - return (List) value; + if (value instanceof List list) { + return list; } else { return new ArrayList<>((Collection) value); } From 440882c3d61b48ac2865e7c4c8caf41d058afb09 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:10:17 +0100 Subject: [PATCH 04/12] Use records for internal aggregation parameters --- .../mongo/backend/aggregation/Expression.java | 44 +++++++++---------- .../backend/aggregation/ExpressionTraits.java | 6 +-- .../aggregation/TwoNumericParameters.java | 23 ++-------- .../backend/aggregation/TwoParameters.java | 17 +------ 4 files changed, 29 insertions(+), 61 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java index f06dd396..847e50f5 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java @@ -146,8 +146,8 @@ Object apply(List expressionValue, Document document) { return null; } - Object firstValue = parameters.getFirst(); - Object secondValue = parameters.getSecond(); + Object firstValue = parameters.first(); + Object secondValue = parameters.second(); if (!(firstValue instanceof List)) { throw new MongoServerError(28689, name() + "'s first argument must be an array, but is " + describeType(firstValue)); @@ -557,8 +557,8 @@ Object apply(List expressionValue, Document document) { return null; } - double a = parameters.getFirstAsDouble(); - double b = parameters.getSecondAsDouble(); + double a = parameters.firstAsDouble(); + double b = parameters.secondAsDouble(); if (Double.compare(b, 0.0) == 0) { throw new MongoServerError(16608, "can't " + name() + " by zero"); } @@ -664,11 +664,11 @@ Object apply(List expressionValue, Document document) { @Override Object apply(List expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); - Object expression = parameters.getFirst(); + Object expression = parameters.first(); if (isNeitherNullNorMissing(expression)) { return expression; } else { - return parameters.getSecond(); + return parameters.second(); } } }, @@ -677,8 +677,8 @@ Object apply(List expressionValue, Document document) { @Override Object apply(List expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); - Object needle = parameters.getFirst(); - Object haystack = parameters.getSecond(); + Object needle = parameters.first(); + Object haystack = parameters.second(); if (!(haystack instanceof Collection)) { throw new MongoServerError(40081, name() + " requires an array as a second argument, found: " + describeType(haystack)); @@ -970,8 +970,8 @@ Object apply(List expressionValue, Document document) { if (parameters == null) { return null; } - double a = parameters.getFirstAsDouble(); - double b = parameters.getSecondAsDouble(); + double a = parameters.firstAsDouble(); + double b = parameters.secondAsDouble(); return a % b; } }, @@ -992,8 +992,8 @@ Number apply(List expressionValue, Document document) { return null; } - Number first = parameters.getFirst(); - Number second = parameters.getSecond(); + Number first = parameters.first(); + Number second = parameters.second(); return NumericUtils.multiplyNumbers(first, second); } @@ -1053,8 +1053,8 @@ Object apply(List expressionValue, Document document) { return null; } - Object base = parameters.getFirst(); - Object exponent = parameters.getSecond(); + Object base = parameters.first(); + Object exponent = parameters.second(); if (!(base instanceof Number)) { throw new MongoServerError(28762, @@ -1176,8 +1176,8 @@ Object apply(List expressionValue, Document document) { return null; } - Object first = parameters.getFirst(); - Object second = parameters.getSecond(); + Object first = parameters.first(); + Object second = parameters.second(); if (!(first instanceof Collection)) { throw new MongoServerError(17048, @@ -1250,8 +1250,8 @@ Object apply(List expressionValue, Document document) { @Override Object apply(List expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); - Object first = parameters.getFirst(); - Object second = parameters.getSecond(); + Object first = parameters.first(); + Object second = parameters.second(); if (!(first instanceof Collection)) { throw new MongoServerError(17046, "both operands of " + name() + " must be arrays. First argument is of type: " + describeType(first)); @@ -1353,8 +1353,8 @@ Object apply(List expressionValue, Document document) { @Override Object apply(List expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); - Object string = parameters.getFirst(); - Object delimiter = parameters.getSecond(); + Object string = parameters.first(); + Object delimiter = parameters.second(); if (isNullOrMissing(string)) { return null; @@ -1378,8 +1378,8 @@ Object apply(List expressionValue, Document document) { @Override Object apply(List expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); - Object first = parameters.getFirst(); - Object second = parameters.getSecond(); + Object first = parameters.first(); + Object second = parameters.second(); if (isNullOrMissing(first) || isNullOrMissing(second)) { return null; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java index 58c36e74..796dffa1 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java @@ -56,7 +56,7 @@ default Number evaluateNumericValue(List expressionValue, Function expressionValue) { TwoParameters parameters = requireTwoParameters(expressionValue); - return ValueComparator.ascWithoutListHandling().compare(parameters.getFirst(), parameters.getSecond()); + return ValueComparator.ascWithoutListHandling().compare(parameters.first(), parameters.second()); } default boolean evaluateComparison(List expressionValue, IntPredicate comparison) { @@ -95,8 +95,8 @@ default TwoParameters requireTwoParameters(List parameters) { default TwoNumericParameters requireTwoNumericParameters(List value, int errorCode) { TwoParameters parameters = requireTwoParameters(value); - Object one = parameters.getFirst(); - Object other = parameters.getSecond(); + Object one = parameters.first(); + Object other = parameters.second(); if (parameters.isAnyNull()) { return null; diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoNumericParameters.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoNumericParameters.java index 93625c72..6d5f93c2 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoNumericParameters.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoNumericParameters.java @@ -1,29 +1,12 @@ package de.bwaldvogel.mongo.backend.aggregation; -class TwoNumericParameters { +record TwoNumericParameters(Number first, Number second) { - private final Number first; - private final Number second; - - TwoNumericParameters(Number first, Number second) { - this.first = first; - this.second = second; - } - - Number getFirst() { - return first; - } - - Number getSecond() { - return second; - } - - double getFirstAsDouble() { + double firstAsDouble() { return first.doubleValue(); } - double getSecondAsDouble() { + double secondAsDouble() { return second.doubleValue(); } - } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoParameters.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoParameters.java index 65a3051e..eb26db7f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoParameters.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/TwoParameters.java @@ -2,24 +2,9 @@ import de.bwaldvogel.mongo.backend.Missing; -class TwoParameters { - private final Object first; - private final Object second; - - TwoParameters(Object first, Object second) { - this.first = first; - this.second = second; - } +record TwoParameters(Object first, Object second) { boolean isAnyNull() { return Missing.isNullOrMissing(first) || Missing.isNullOrMissing(second); } - - Object getFirst() { - return first; - } - - Object getSecond() { - return second; - } } From 72c7e832fd5ba236a74740695e36dc6395feefe8 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:12:12 +0100 Subject: [PATCH 05/12] Use text blocks for multiline JSON test data --- .../mongo/backend/ProjectionTest.java | 48 ++-- .../backend/AbstractAggregationTest.java | 228 ++++++++++-------- 2 files changed, 153 insertions(+), 123 deletions(-) diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/ProjectionTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/ProjectionTest.java index 7eefdf56..0cc2157f 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/ProjectionTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/ProjectionTest.java @@ -66,11 +66,13 @@ void testInvalidMixedProjections() throws Exception { @Test void testProjectIn() { - Document document = json("_id: 1, students: [" + - "{name: 'john', school: 'A', age: 10}, " + - "{name: 'jess', school: 'B', age: 12}, " + - "{name: 'jeff', school: 'A', age: 12}" + - "]"); + Document document = json(""" + _id: 1, students: [ + {name: 'john', school: 'A', age: 10}, + {name: 'jess', school: 'B', age: 12}, + {name: 'jeff', school: 'A', age: 12} + ] + """); assertThat(projectDocument(document, json("_id: 1, \"students.name\": 1"))) .isEqualTo(json("_id:1, students: [{name: 'john'}, {name: 'jess'}, {name: 'jeff'}]")); @@ -83,11 +85,13 @@ void testProjectIn() { @Test void testProjectOut() { - Document document = json("_id: 1, students: [" + - "{name: 'john', school: 'A', age: 10}, " + - "{name: 'jess', school: 'B', age: 12}, " + - "{name: 'jeff', school: 'A', age: 12}" + - "]"); + Document document = json(""" + _id: 1, students: [ + {name: 'john', school: 'A', age: 10}, + {name: 'jess', school: 'B', age: 12}, + {name: 'jeff', school: 'A', age: 12} + ] + """); assertThat(projectDocument(document, json("\"students.school\": 0, \"students.age\": 0"))) .isEqualTo(json("_id:1, students: [{name: 'john'}, {name: 'jess'}, {name: 'jeff'}]")); @@ -141,11 +145,13 @@ void testProjectListValues() throws Exception { @Test void testProjectListValuesWithPositionalOperator() throws Exception { - Document document = json("_id: 1, students: [" + - "{name: 'john', school: 'A', age: 10}, " + - "{name: 'jess', school: 'B', age: 12}, " + - "{name: 'jeff', school: 'A', age: 12}" + - "]"); + Document document = json(""" + _id: 1, students: [ + {name: 'john', school: 'A', age: 10}, + {name: 'jess', school: 'B', age: 12}, + {name: 'jeff', school: 'A', age: 12} + ] + """); assertThat(projectDocument(document, json("'students.$': 1"), "_id")) .isEqualTo(json("_id: 1, students: [{name: 'john', school: 'A', age: 10}]")); @@ -156,11 +162,13 @@ void testProjectListValuesWithPositionalOperator() throws Exception { @Test void testProjectWithElemMatch() throws Exception { - Document document = json("_id: 1, students: [" + - "{name: 'john', school: 'A', age: 10}, " + - "{name: 'jess', school: 'B', age: 12}, " + - "{name: 'jeff', school: 'A', age: 12}" + - "]"); + Document document = json(""" + _id: 1, students: [ + {name: 'john', school: 'A', age: 10}, + {name: 'jess', school: 'B', age: 12}, + {name: 'jeff', school: 'A', age: 12} + ] + """); assertThat(projectDocument(document, json("students: {$elemMatch: {school: 'B'}}"), "_id")) .isEqualTo(json("_id: 1, students: [{name: 'jess', school: 'B', age: 12}]")); diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java index abca2406..049c1784 100644 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java @@ -497,15 +497,17 @@ void testAggregateWithEmptyAddToSet() throws Exception { // https://github.com/bwaldvogel/mongo-java-server/issues/111 @Test void testAggregateWithAddToSetAndMissingValue() throws Exception { - List pipeline = jsonList("$group: {\n" + - " _id: '$_id', \n" + - " sources: {\n" + - " $addToSet: {\n" + - " key: '$content.key',\n" + - " missing: '$content.missing'\n" + - " }\n" + - " }\n" + - "}"); + List pipeline = jsonList(""" + $group: { + _id: '$_id', + sources: { + $addToSet: { + key: '$content.key', + missing: '$content.missing' + } + } + } + """); assertThat(collection.aggregate(pipeline)).isEmpty(); @@ -1519,20 +1521,24 @@ void testAggregateWithLookupAndUncorrelatedSubqueries() { MongoCollection ordersCollection = db.getCollection("orders"); MongoCollection warehousesCollection = db.getCollection("warehouses"); - List pipeline = jsonList("$lookup: {from: 'warehouses'," + - " let: { order_item: '$item', order_qty: '$ordered' }," + - " pipeline: [{$match:\n" + - " {$expr:\n" + - " {$and:\n" + - " [\n" + - " {$eq: ['$stock_item', '$$order_item']},\n" + - " {$gte: ['$instock', '$$order_qty']}\n" + - " ]\n" + - " }\n" + - " }\n" + - " },\n" + - " {$project: {stock_item: 0, _id: 0}}]," + - " as: 'stockdata'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'warehouses', + let: {order_item: '$item', order_qty: '$ordered'}, + pipeline: [ + {$match: { + $expr: { + $and: [ + {$eq: ['$stock_item', '$$order_item']}, + {$gte: ['$instock', '$$order_qty']} + ] + } + }}, + {$project: {stock_item: 0, _id: 0}} + ], + as: 'stockdata' + } + """); assertThat(ordersCollection.aggregate(pipeline)).isEmpty(); @@ -1787,12 +1793,16 @@ void testAggregateWithReduceOperation() throws Exception { .containsExactly(json("_id: 1, res: 'abc'")); Utils.changeSubdocumentValue(pipeline.get(0), "$project.res", - json("$reduce: {input: [1, 2, 3, 4]," + - " initialValue: { sum: 5, product: 2 }," + - " in: {\n" + - " sum: {$add: ['$$value.sum', '$$this']},\n" + - " product: {$multiply: ['$$value.product', '$$this']}\n" + - " }}")); + json(""" + $reduce: { + input: [1, 2, 3, 4], + initialValue: {sum: 5, product: 2}, + in: { + sum: {$add: ['$$value.sum', '$$this']}, + product: {$multiply: ['$$value.product', '$$this']} + } + } + """)); assertThat(collection.aggregate(pipeline)) .containsExactly(json("_id: 1, res: {sum: 15, product: 48}")); @@ -1808,28 +1818,30 @@ void testAggregateWithMatchProjectReduceConcatAndCond() throws Exception { collection.insertOne(json("_id: 6, name: 'Claire'")); List pipeline = jsonList("$match: {hobbies: {$gt: []}}", - "$project: {\n" + - " name: 1,\n" + - " bio: {\n" + - " $reduce: {\n" + - " input: '$hobbies',\n" + - " initialValue: 'My hobbies include:',\n" + - " in: {\n" + - " $concat: [\n" + - " '$$value',\n" + - " {\n" + - " $cond: {\n" + - " if: { $eq: ['$$value', 'My hobbies include:']},\n" + - " then: ' ',\n" + - " else: ', '\n" + - " }\n" + - " },\n" + - " '$$this'\n" + - " ]\n" + - " }\n" + - " }\n" + - " }\n" + - "}"); + """ + $project: { + name: 1, + bio: { + $reduce: { + input: '$hobbies', + initialValue: 'My hobbies include:', + in: { + $concat: [ + '$$value', + { + $cond: { + if: { $eq: ['$$value', 'My hobbies include:']}, + then: ' ', + else: ', ' + } + }, + '$$this' + ] + } + } + } + } + """); assertThat(collection.aggregate(pipeline)) .containsExactly( @@ -1852,15 +1864,17 @@ void testAggregateWithBucketStage() throws Exception { collection.insertOne(json("_id: 7, title: 'The Scream', artist: 'Munch', year: 1893")); collection.insertOne(json("_id: 8, title: 'Blue Flower', artist: 'O’Keefe', year: 1918, price: 118.42")); - List pipeline = jsonList("$bucket: {\n" + - " groupBy: '$price',\n" + - " boundaries: [0, 200, 400],\n" + - " default: 'Other',\n" + - " output: {\n" + - " count: { $sum: 1 },\n" + - " titles: { $push: '$title' }\n" + - " }\n" + - "}"); + List pipeline = jsonList(""" + $bucket: { + groupBy: '$price', + boundaries: [0, 200, 400], + default: 'Other', + output: { + count: { $sum: 1 }, + titles: { $push: '$title' } + } + } + """); assertThat(collection.aggregate(pipeline)) .containsExactly( @@ -1870,11 +1884,13 @@ void testAggregateWithBucketStage() throws Exception { ); List pipelineWithoutDefault = jsonList("$match: {price: {$lt: 400}}", - "$bucket: {\n" + - " groupBy: '$price',\n" + - " boundaries: [0, 200, 400],\n" + - " output: {count: { $sum: 1 }}\n" + - "}"); + """ + $bucket: { + groupBy: '$price', + boundaries: [0, 200, 400], + output: {count: { $sum: 1 }} + } + """); assertThat(collection.aggregate(pipelineWithoutDefault)) .containsExactly( @@ -1883,10 +1899,11 @@ void testAggregateWithBucketStage() throws Exception { ); List pipelineWithoutOutput = jsonList("$match: {price: {$lt: 400}}", - "$bucket: {\n" + - " groupBy: '$price',\n" + - " boundaries: [0, 200.0, 400]" + - "}"); + """ + $bucket: { + groupBy: '$price', + boundaries: [0, 200.0, 400]} + """); assertThat(collection.aggregate(pipelineWithoutOutput)) .containsExactly( @@ -1894,11 +1911,12 @@ void testAggregateWithBucketStage() throws Exception { json("_id: 200.0, count: 2") ); - List pipelineWithAlphabeticBoundaries = jsonList("$bucket: {\n" + - " groupBy: {$toLower: '$artist'},\n" + - " boundaries: ['a', 'd', 'g', 'j'],\n" + - " default: null" + - "}"); + List pipelineWithAlphabeticBoundaries = jsonList(""" + $bucket: { + groupBy: {$toLower: '$artist'}, + boundaries: ['a', 'd', 'g', 'j'], + default: null} + """); assertThat(collection.aggregate(pipelineWithAlphabeticBoundaries)) .containsExactly( @@ -1968,26 +1986,28 @@ void testAggregateWithFacetStage() throws Exception { collection.insertOne(json("_id: 7, title: 'The Scream', tags: ['Expressionism', 'painting', 'oil']")); collection.insertOne(json("_id: 8, title: 'Blue Flower', price: 118.42, tags: ['abstract', 'painting']")); - List pipeline = jsonList("$facet: {\n" + - " 'categorizedByTags': [\n" + - " { $unwind: '$tags' },\n" + - " { $sortByCount: '$tags' }\n" + - " ],\n" + - " 'categorizedByPrice': [\n" + - " { $match: { price: { $exists: 1 } } },\n" + - " {\n" + - " $bucket: {\n" + - " groupBy: '$price',\n" + - " boundaries: [0, 150, 200, 300, 400],\n" + - " default: 'Other',\n" + - " output: {\n" + - " 'count': { $sum: 1 },\n" + - " 'titles': { $push: '$title' }\n" + - " }\n" + - " }\n" + - " }\n" + - " ]\n" + - "}"); + List pipeline = jsonList(""" + $facet: { + 'categorizedByTags': [ + { $unwind: '$tags' }, + { $sortByCount: '$tags' } + ], + 'categorizedByPrice': [ + { $match: { price: { $exists: 1 } } }, + { + $bucket: { + groupBy: '$price', + boundaries: [0, 150, 200, 300, 400], + default: 'Other', + output: { + 'count': { $sum: 1 }, + 'titles': { $push: '$title' } + } + } + } + ] + } + """); assertThat(collection.aggregate(pipeline)) .containsExactly( @@ -2041,15 +2061,17 @@ void testAggregateWithMatchAndFacetStage() throws Exception { List pipeline = jsonList( "$match: {price: {$gt: 300}}", - "$facet: {\n" + - " 'categorizedByTags': [\n" + - " { $unwind: '$tags' },\n" + - " { $sortByCount: '$tags' }\n" + - " ],\n" + - " 'categorizedByPrice': [\n" + - " {$bucket: {groupBy: '$price', boundaries: [300, 400, 500]}}\n" + - " ]\n" + - "}"); + """ + $facet: { + 'categorizedByTags': [ + { $unwind: '$tags' }, + { $sortByCount: '$tags' } + ], + 'categorizedByPrice': [ + {$bucket: {groupBy: '$price', boundaries: [300, 400, 500]}} + ] + } + """); assertThat(collection.aggregate(pipeline)) .containsExactly( From cf2550add5b01880dd2aa22244818ad4de2ae669 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:15:32 +0100 Subject: [PATCH 06/12] Fix flaky timestamp bounds in merge aggregation test --- .../de/bwaldvogel/mongo/backend/AbstractAggregationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java index 049c1784..ca01f57b 100644 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java @@ -2663,8 +2663,7 @@ void testAggregateWithMerge_pipeline_nowVariable() throws Exception { Instant instantAfter = Instant.now(); assertThat(result).containsOnlyKeys("_id", "timestamp"); - System.out.println(result.get("timestamp")); - assertThat(result.getDate("timestamp")).isBetween(instantBefore, instantAfter); + assertThat(result.getDate("timestamp")).isBetween(instantBefore, instantAfter, true, true); } private static Stream aggregateWithMerge_illegalParametersArguments() { From 0cbcdc84054165b41c8f437072ee46c286060193 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:29:31 +0100 Subject: [PATCH 07/12] Replace deprecated Netty NioEventLoopGroup --- core/src/main/java/de/bwaldvogel/mongo/MongoServer.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java b/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java index 644e3c6d..fcaec38c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java +++ b/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java @@ -23,9 +23,10 @@ import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; +import io.netty.channel.MultiThreadIoEventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; -import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.nio.NioIoHandler; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.ssl.SslContext; @@ -76,8 +77,10 @@ public void bind(SocketAddress socketAddress) { public void bind(SocketAddress socketAddress, int numberOfBossThreads, int numberOfWorkerThreads) { - bossGroup = new NioEventLoopGroup(numberOfBossThreads, new MongoThreadFactory("mongo-server-boss")); - workerGroup = new NioEventLoopGroup(numberOfWorkerThreads, new MongoThreadFactory("mongo-server-worker")); + bossGroup = new MultiThreadIoEventLoopGroup(numberOfBossThreads, + new MongoThreadFactory("mongo-server-boss"), NioIoHandler.newFactory()); + workerGroup = new MultiThreadIoEventLoopGroup(numberOfWorkerThreads, + new MongoThreadFactory("mongo-server-worker"), NioIoHandler.newFactory()); channelGroup = new DefaultChannelGroup("mongodb-channels", workerGroup.next()); try { From 193b05df3c9cf40ac4b8e6705593f251932b3e38 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:43:55 +0100 Subject: [PATCH 08/12] Fix raw types and unchecked collection casts --- .../mongo/backend/AbstractMongoBackend.java | 9 +-- .../backend/AbstractMongoCollection.java | 10 +-- .../mongo/backend/CollectionUtils.java | 12 ++-- .../de/bwaldvogel/mongo/backend/Index.java | 4 +- .../bwaldvogel/mongo/backend/Projection.java | 2 + .../mongo/backend/ValueComparator.java | 4 +- .../backend/aggregation/stage/MergeStage.java | 2 +- .../mongo/oplog/CollectionBackedOplog.java | 4 +- .../backend/AbstractMongoDatabaseTest.java | 4 +- .../backend/aggregation/ExpressionTest.java | 66 +++++++++++++------ .../aggregation/stage/LookupStageTest.java | 5 +- .../bwaldvogel/mongo/bson/DocumentTest.java | 5 +- 12 files changed, 79 insertions(+), 48 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java index 10599961..456847de 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoBackend.java @@ -372,10 +372,11 @@ private Document handleBuildInfo() { } protected Document handleKillCursors(Document query) { - List cursorIds = (List) query.get("cursors"); + List cursorIds = (List) query.get("cursors"); List cursorsKilled = new ArrayList<>(); List cursorsNotFound = new ArrayList<>(); - for (Long cursorId : cursorIds) { + for (Object cursorIdValue : cursorIds) { + Long cursorId = (Long) cursorIdValue; if (cursorRegistry.remove(cursorId)) { log.info("Killed cursor {}", cursorId); cursorsKilled.add(cursorId); @@ -472,9 +473,9 @@ public void enableOplog() { protected Oplog createOplog() { MongoDatabase localDatabase = resolveDatabase("local"); - MongoCollection collection = (MongoCollection) localDatabase.resolveCollection(OPLOG_COLLECTION_NAME, false); + MongoCollection collection = localDatabase.resolveCollection(OPLOG_COLLECTION_NAME, false); if (collection == null) { - collection = (MongoCollection) localDatabase.createCollectionOrThrowIfExists(OPLOG_COLLECTION_NAME); + collection = localDatabase.createCollectionOrThrowIfExists(OPLOG_COLLECTION_NAME); } return new CollectionBackedOplog(this, collection, cursorRegistry); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java index bee4890d..043d67ee 100755 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java @@ -678,15 +678,15 @@ private void convertSelectorToDocument(Document selector, Document document) { Object value = entry.getValue(); if (key.equals("$and")) { - List andValues = (List) value; - for (Document andValue : andValues) { - convertSelectorToDocument(andValue, document); + List andValues = (List) value; + for (Object andValue : andValues) { + convertSelectorToDocument((Document) andValue, document); } continue; } else if (key.equals("$or")) { - List orValues = (List) value; + List orValues = (List) value; if (orValues.size() == 1) { - convertSelectorToDocument(orValues.get(0), document); + convertSelectorToDocument((Document) orValues.get(0), document); } continue; } else if (key.startsWith("$")) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java b/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java index e9932956..4c0b677f 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/CollectionUtils.java @@ -37,22 +37,22 @@ public static T getSingleElement(Iterable iterable, Supplier List> multiplyWithOtherElements(Collection allValues, Collection> collectionValues) { + static List> multiplyWithOtherElements(Collection allValues, Collection> collectionValues) { int collectionValueSize = CollectionUtils.getElementAtPosition(collectionValues, 0).size(); - for (Collection collectionValue : collectionValues) { + for (Collection collectionValue : collectionValues) { Assert.isTrue(allValues.contains(collectionValue), () -> "Expected " + collectionValue + " to be part of " + allValues); Assert.isTrue(collectionValue.size() == collectionValueSize, () -> "Expected " + collectionValue + " to be size " + collectionValueSize); } - List> result = new ArrayList<>(collectionValueSize); + List> result = new ArrayList<>(collectionValueSize); for (int i = 0; i < collectionValueSize; i++) { - List newValues = new ArrayList(); + List newValues = new ArrayList<>(); for (Object value : allValues) { if (collectionValues.contains(value)) { - newValues.add(CollectionUtils.getElementAtPosition((Collection) value, i)); + newValues.add(CollectionUtils.getElementAtPosition((Collection) value, i)); } else { - newValues.add((T) value); + newValues.add(value); } } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java index 9e8fd24e..89a94c8c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java @@ -64,9 +64,9 @@ Set getKeyValues(Document document, boolean normalize) { valuesPerKey.replaceAll((key, value) -> Utils.normalizeValue(value)); } - List> collectionValues = valuesPerKey.values().stream() + List> collectionValues = valuesPerKey.values().stream() .filter(value -> value instanceof Collection) - .map(value -> (Collection) value) + .map(value -> (Collection) value) .collect(Collectors.toList()); if (collectionValues.size() > 0) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/Projection.java b/core/src/main/java/de/bwaldvogel/mongo/backend/Projection.java index f1ea9db0..144e6607 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/Projection.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/Projection.java @@ -114,6 +114,8 @@ private static void projectField(Document document, Document newDocument, String Document newsubDocument = (Document) newDocument.computeIfAbsent(mainKey, k -> new Document()); projectField((Document) object, newsubDocument, subKey, projectionValue); } else if (object instanceof List values) { + // This list is created and populated only by this projection. + @SuppressWarnings("unchecked") List newprojectedValues = (List) newDocument.computeIfAbsent(mainKey, k -> new ArrayList<>()); if ("$".equals(subKey) && !values.isEmpty()) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java b/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java index a20466c1..b712342c 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/ValueComparator.java @@ -233,8 +233,8 @@ private int compareLists(Object value1, Object value2) { } private Object getListValueForComparison(Object value) { - if (value instanceof Collection) { - List values = new ArrayList<>((Collection) value); + if (value instanceof Collection collection) { + List values = new ArrayList<>(collection); if (values.isEmpty()) { return Missing.getInstance(); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java index eec4aa5b..b8db53bf 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java @@ -82,7 +82,7 @@ public MergeStage(DatabaseResolver databaseResolver, MongoDatabase database, Obj whenNotMatched = getWhenNotMatched(paramsDocument); if (whenMatched == null) { - Collection pipeline = (Collection) paramsDocument.get("whenMatched"); + Collection pipeline = (Collection) paramsDocument.get("whenMatched"); whenMatchedPipeline = Aggregation.fromPipeline(pipeline, databaseResolver, database, null, null); } else if (paramsDocument.containsKey("let")) { throw new MongoServerError(51199, "Cannot use 'let' variables with 'whenMatched: " + whenMatched + "' mode"); diff --git a/core/src/main/java/de/bwaldvogel/mongo/oplog/CollectionBackedOplog.java b/core/src/main/java/de/bwaldvogel/mongo/oplog/CollectionBackedOplog.java index 5fb0be01..63b89a6e 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/oplog/CollectionBackedOplog.java +++ b/core/src/main/java/de/bwaldvogel/mongo/oplog/CollectionBackedOplog.java @@ -27,12 +27,12 @@ public class CollectionBackedOplog implements Oplog { private static final String DOCUMENT_KEY = "documentKey"; private final OplogClock oplogClock; - private final MongoCollection collection; + private final MongoCollection collection; private final MongoBackend backend; private final CursorRegistry cursorRegistry; private final UUID ui = UUID.randomUUID(); - public CollectionBackedOplog(MongoBackend backend, MongoCollection collection, CursorRegistry cursorRegistry) { + public CollectionBackedOplog(MongoBackend backend, MongoCollection collection, CursorRegistry cursorRegistry) { this.oplogClock = new OplogClock(backend.getClock()); this.collection = collection; this.backend = backend; diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabaseTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabaseTest.java index 68473eee..b0aba019 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabaseTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabaseTest.java @@ -39,7 +39,9 @@ protected Index openOrCreateUniqueIndex(String collectionName, String in @Override protected MongoCollection openOrCreateCollection(String collectionName, CollectionOptions options) { - MongoCollection collection = (MongoCollection) Mockito.mock(MongoCollection.class); + // Class literals cannot retain the mock's collection position type. + @SuppressWarnings("unchecked") + MongoCollection collection = Mockito.mock(MongoCollection.class); when(collection.getCollectionName()).thenReturn("mockCollection"); QueryResult queryResult = new QueryResult(List.of(new Document("_id", 1))); diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTest.java index 028cccf8..1030fe52 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTest.java @@ -3,6 +3,8 @@ import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.InstanceOfAssertFactories.COLLECTION; +import static org.assertj.core.api.InstanceOfAssertFactories.LIST; import java.time.Instant; import java.util.Collection; @@ -362,14 +364,16 @@ void testEvaluateEq() throws Exception { @Test void testEvaluateMap() throws Exception { - assertThat((Collection) Expression.evaluate( + assertThat(Expression.evaluate( json("$map: {input: '$quizzes', as: 'grade', in: {$add: ['$$grade', 2]}}"), json("quizzes: [5, 6, 7]"))) + .asInstanceOf(COLLECTION) .containsExactly(7, 8, 9); - assertThat((Collection) Expression.evaluate( + assertThat(Expression.evaluate( json("$map: {input: '$quizzes', as: 'grade', in: {$add: ['$$grade', 2]}}"), json("quizzes: []"))) + .asInstanceOf(COLLECTION) .isEmpty(); assertThat(Expression.evaluate(json("$map: {input: '$q', in: '$this'}"), json(""))).isNull(); @@ -421,17 +425,19 @@ void testEvaluateReduce() throws Exception { json("quizzes: [ 1, 2, 3, 4 ]"))) .isEqualTo(expectedDocument); - assertThat((Collection) Expression.evaluate( + assertThat(Expression.evaluate( json("$reduce: {input: '$quizzes',initialValue: [ 1, 2 ],in: {$concatArrays : ['$$value', '$$this']}}"), json("quizzes: [ [ 3, 4 ], [ 5, 6 ] ]"))) + .asInstanceOf(COLLECTION) .containsExactly(1, 2, 3, 4, 5, 6); - assertThat((Collection) Expression.evaluate( + assertThat(Expression.evaluate( json("$reduce: {input: '$quizzes',initialValue: [],in: {$concatArrays : ['$$value', '$$this']}}"), json("quizzes: []"))) + .asInstanceOf(COLLECTION) .isEmpty(); - assertThat((Collection) Expression.evaluate( + assertThat(Expression.evaluate( json("$reduce: {input: '$quizzes', initialValue: [ 1, 2 ], in: '$$this'}"), json(""))) .isNull(); @@ -624,7 +630,8 @@ void testEvaluateOr() throws Exception { @Test void testEvaluateObjectToArray() throws Exception { - assertThat((List) Expression.evaluate(json("$objectToArray: '$v'"), json("v: {a: 1, b: 2}"))) + assertThat(Expression.evaluate(json("$objectToArray: '$v'"), json("v: {a: 1, b: 2}"))) + .asInstanceOf(LIST) .containsExactly( json("{k: 'a', v: 1}"), json("{k: 'b', v: 2}") @@ -864,19 +871,24 @@ void testEvaluateSetDifference() throws Exception { assertThat(Expression.evaluate(json("$setDifference: [[], null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setDifference: [null, []]"), json(""))).isNull(); - assertThat((Collection) Expression.evaluate(json("$setDifference: [['a', 'b', 'a'], ['b']]"), json(""))) + assertThat(Expression.evaluate(json("$setDifference: [['a', 'b', 'a'], ['b']]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly("a"); - assertThat((Collection) Expression.evaluate(json("$setDifference: [['a', 'b', 'a'], ['c', 'b', 'a']]"), json(""))) + assertThat(Expression.evaluate(json("$setDifference: [['a', 'b', 'a'], ['c', 'b', 'a']]"), json(""))) + .asInstanceOf(COLLECTION) .isEmpty(); - assertThat((Collection) Expression.evaluate(json("$setDifference: [['a', 'b'], [['a', 'b']]]"), json(""))) + assertThat(Expression.evaluate(json("$setDifference: [['a', 'b'], [['a', 'b']]]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly("a", "b"); - assertThat((Collection) Expression.evaluate(json("$setDifference: [[1.0, 0, 2], [-0.0]]"), json(""))) + assertThat(Expression.evaluate(json("$setDifference: [[1.0, 0, 2], [-0.0]]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly(1.0, 2); - assertThat((Collection) Expression.evaluate(json("$setDifference: [[1.0, -0.0, 2], [1, 0]]"), json(""))) + assertThat(Expression.evaluate(json("$setDifference: [[1.0, -0.0, 2], [1, 0]]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly(2); assertThatExceptionOfType(MongoServerError.class) @@ -939,22 +951,28 @@ void testEvaluateSetIntersection() throws Exception { assertThat(Expression.evaluate(json("$setIntersection: [['a'], null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setIntersection: ['$a', null]"), json(""))).isNull(); - assertThat((Collection) Expression.evaluate(json("$setIntersection: [['a', 'b', 'a'], ['b']]"), json(""))) + assertThat(Expression.evaluate(json("$setIntersection: [['a', 'b', 'a'], ['b']]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly("b"); - assertThat((Collection) Expression.evaluate(json("$setIntersection: [['a', 'b', 'a'], ['b', 'a']]"), json(""))) + assertThat(Expression.evaluate(json("$setIntersection: [['a', 'b', 'a'], ['b', 'a']]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly("a", "b"); - assertThat((Collection) Expression.evaluate(json("$setIntersection: ['$one', '$other']"), json("one: [1, 2, 3], other: [2, 3, 5]"))) + assertThat(Expression.evaluate(json("$setIntersection: ['$one', '$other']"), json("one: [1, 2, 3], other: [2, 3, 5]"))) + .asInstanceOf(COLLECTION) .containsExactly(2, 3); - assertThat((Collection) Expression.evaluate(json("$setIntersection: ['$one', '$other', [2]]"), json("one: [1, 2], other: [2, 1]"))) + assertThat(Expression.evaluate(json("$setIntersection: ['$one', '$other', [2]]"), json("one: [1, 2], other: [2, 1]"))) + .asInstanceOf(COLLECTION) .containsExactly(2); - assertThat((Collection) Expression.evaluate(json("$setIntersection: ['$one', '$other']"), json("one: [1, 2.0], other: [2, 1]"))) + assertThat(Expression.evaluate(json("$setIntersection: ['$one', '$other']"), json("one: [1, 2.0], other: [2, 1]"))) + .asInstanceOf(COLLECTION) .containsExactly(1, 2.0); - assertThat((Collection) Expression.evaluate(json("$setIntersection: ['$one', '$other', [2, 2, 1]]"), json("one: [], other: [2, 1]"))) + assertThat(Expression.evaluate(json("$setIntersection: ['$one', '$other', [2, 2, 1]]"), json("one: [], other: [2, 1]"))) + .asInstanceOf(COLLECTION) .isEmpty(); assertThatExceptionOfType(MongoServerError.class) @@ -1003,10 +1021,12 @@ void testEvaluateSetUnion() throws Exception { assertThat(Expression.evaluate(json("$setUnion: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setUnion: '$a'"), json(""))).isNull(); - assertThat((Collection) Expression.evaluate(json("$setUnion: [['a', 1], ['c', 'a']]"), json(""))) + assertThat(Expression.evaluate(json("$setUnion: [['a', 1], ['c', 'a']]"), json(""))) + .asInstanceOf(COLLECTION) .containsExactly(1, "a", "c"); - assertThat((Collection) Expression.evaluate(json("$setUnion: ['$a', '$b']"), json("a: [1, 2, 3], b: [3.0, 4]"))) + assertThat(Expression.evaluate(json("$setUnion: ['$a', '$b']"), json("a: [1, 2, 3], b: [3.0, 4]"))) + .asInstanceOf(COLLECTION) .containsExactly(1, 2, 3, 4); assertThatExceptionOfType(MongoServerError.class) @@ -1100,8 +1120,12 @@ void testEvaluateSlice() throws Exception { @Test void testEvaluateSplit() throws Exception { - assertThat((List) Expression.evaluate(json("$split: ['June-15-2013', '-']"), json(""))).containsExactly("June", "15", "2013"); - assertThat((List) Expression.evaluate(json("$split: ['$a', '$b']"), json("a: 'foo bar', b: ' '"))).containsExactly("foo", "bar"); + assertThat(Expression.evaluate(json("$split: ['June-15-2013', '-']"), json(""))) + .asInstanceOf(LIST) + .containsExactly("June", "15", "2013"); + assertThat(Expression.evaluate(json("$split: ['$a', '$b']"), json("a: 'foo bar', b: ' '"))) + .asInstanceOf(LIST) + .containsExactly("foo", "bar"); assertThat(Expression.evaluate(json("$split: [null, ' ']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$split: ['$doesNotExist', ' ']"), json(""))).isNull(); diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java index 8867d3ad..68cd1bdf 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java @@ -18,8 +18,7 @@ public class LookupStageTest extends AbstractLookupStageTest { @Mock - @SuppressWarnings("rawtypes") - private MongoCollection authorsCollection; + private MongoCollection authorsCollection; @Test void testMissingFromField() { @@ -170,7 +169,7 @@ private LookupStage buildLookupStage(String jsonDocument) { } private void prepareAuthorsCollectionMock() { - when(database.resolveCollection("authors", false)).thenReturn(authorsCollection); + when(database.resolveCollection("authors", false)).thenAnswer(invocation -> authorsCollection); } private void configureAuthorsCollection(String expectedJsonQuery, String... authors) { diff --git a/core/src/test/java/de/bwaldvogel/mongo/bson/DocumentTest.java b/core/src/test/java/de/bwaldvogel/mongo/bson/DocumentTest.java index f2b332ce..133261fc 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/bson/DocumentTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/bson/DocumentTest.java @@ -72,7 +72,10 @@ void testCloneDeeply() throws Exception { Utils.changeSubdocumentValue(deepClone, "sub.sub.1", 25); Utils.changeSubdocumentValue(deepClone, "subDocument._id", 2); deepClone.remove("null-value"); - ((Collection) deepClone.get("set")).add("more"); + // The original set and its deep clone both hold Objects. + @SuppressWarnings("unchecked") + Collection clonedSet = (Collection) deepClone.get("set"); + clonedSet.add("more"); assertThat(deepClone).hasToString("{\"subDocument\" : {\"_id\" : 2}, \"sub\" : {\"sub\" : [ 1, 25, 3 ]}, \"set\" : [ \"more\" ]}"); assertThat(original).hasToString(originalToString); From f7fd039b9e576695cf83697d8aae2ddc22fead7f Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:43:55 +0100 Subject: [PATCH 09/12] Document serializable backing list in KeyValue --- core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java index f9b99527..da7bb637 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java @@ -16,6 +16,8 @@ public final class KeyValue implements Serializable, Iterable { private static final long serialVersionUID = 1L; + // Every constructor stores a serializable ArrayList here. + @SuppressWarnings("serial") private final List values; public KeyValue(Object... values) { From 876fa8f1259ca339261c63d786f171690dd14745 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:43:55 +0100 Subject: [PATCH 10/12] Remove implicit fallthrough in field updates --- .../main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java b/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java index d60edfb0..ee4ff0c9 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java @@ -70,7 +70,8 @@ private void apply(Document change, String modifier, String key, Object value) { // no upsert → ignore return; } - //$FALL-THROUGH$ + handleSet(key, value); + break; case SET: handleSet(key, value); break; From b003814f1ad2ba9bc6cb7eb562336a7c9a6400d8 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:43:55 +0100 Subject: [PATCH 11/12] Reference socket resource in shutdown regression test --- .../test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java b/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java index b59aa936..01efe5dc 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/MongoServerShutdownTest.java @@ -47,6 +47,7 @@ void testShutdownNowAfterClientConnectedDuringShutdown() throws Exception { assertThat(workerHeld.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); try (Socket secondClient = new Socket(address.getHostString(), address.getPort())) { + assertThat(secondClient.isConnected()).isTrue(); assertThat(secondClientQueued.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); // the second client is registered after its event loop started to shut down, and stays open From cb4c70ce7413949505a8e584b20d01c1751ec8e7 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Sat, 14 Nov 2026 21:43:55 +0100 Subject: [PATCH 12/12] Enable strict javac lint checks except this-escape Enable -Xlint:all and -Werror for production and test sources in all modules. Leave this-escape disabled until constructor initialization is addressed in a follow-up. --- build.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build.gradle b/build.gradle index 052b0c84..11321b8d 100644 --- a/build.gradle +++ b/build.gradle @@ -26,6 +26,11 @@ allprojects { targetCompatibility = JavaVersion.VERSION_21 } + tasks.withType(JavaCompile).configureEach { + // TODO: Address constructor this-escape warnings and re-enable this check. + options.compilerArgs.addAll(['-Xlint:all,-this-escape', '-Werror']) + } + repositories { mavenCentral() }