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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/src/main/java/de/bwaldvogel/mongo/MongoServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public void bind(SocketAddress socketAddress, int numberOfBossThreads, int numbe
.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
public void initChannel(SocketChannel ch) {
MongoServer.this.initChannel(ch);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@ protected Document handleKillCursors(Document query) {
}

protected Document handleGetMore(String databaseName, String command, Document query) {
MongoDatabase mongoDatabase = resolveDatabase(databaseName);
String collectionName = (String) query.get("collection");
long cursorId = ((Number) query.get(command)).longValue();
int batchSize = ((Number) query.getOrDefault("batchSize", 0)).intValue();
Expand Down Expand Up @@ -400,7 +399,7 @@ protected Document handleDropDatabase(String databaseName) {
public Document handleMessage(MongoMessage message) {
String databaseName = message.getDatabaseName();
Document query = message.getDocument();
DatabaseCommand command = DatabaseCommand.of(query.keySet().iterator().next());
DatabaseCommand command = DatabaseCommand.of(query.getFirstKey());
return handleCommand(databaseName, command, query);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -110,7 +109,7 @@ protected QueryResult matchDocumentsFromStream(Document query, Stream<Document>
documentStream = documentStream.limit(limit);
}

if (fieldSelector != null && !fieldSelector.keySet().isEmpty()) {
if (fieldSelector != null && !fieldSelector.isEmpty()) {
Projection projection = new Projection(fieldSelector, getIdField());
documentStream = documentStream.map(projection::projectDocument);
}
Expand All @@ -129,8 +128,8 @@ protected QueryResult matchDocuments(Document query, Iterable<P> positions, Docu
}

protected static boolean isNaturalDescending(Document orderBy) {
if (orderBy != null && !orderBy.keySet().isEmpty()) {
if (orderBy.keySet().iterator().next().equals("$natural")) {
if (orderBy != null && !orderBy.isEmpty()) {
if (orderBy.getFirstKey().equals("$natural")) {
Number sortValue = (Number) orderBy.get("$natural");
if (sortValue.intValue() == -1) {
return true;
Expand All @@ -145,8 +144,8 @@ protected static boolean isNaturalDescending(Document orderBy) {
}

protected static DocumentComparator deriveComparator(Document orderBy) {
if (orderBy != null && !orderBy.keySet().isEmpty()) {
if (orderBy.keySet().iterator().next().equals("$natural")) {
if (orderBy != null && !orderBy.isEmpty()) {
if (orderBy.getFirstKey().equals("$natural")) {
// already sorted
} else {
return new DocumentComparator(orderBy);
Expand Down Expand Up @@ -218,12 +217,12 @@ public void addIndex(Index<P> index) {
if (index.isEmpty()) {
try {
streamAllDocumentsWithPosition().forEach(documentWithPosition -> {
Document document = documentWithPosition.getDocument();
Document document = documentWithPosition.document();
index.checkAdd(document, this);
});
streamAllDocumentsWithPosition().forEach(documentWithPosition -> {
Document document = documentWithPosition.getDocument();
P position = documentWithPosition.getPosition();
Document document = documentWithPosition.document();
P position = documentWithPosition.position();
index.add(document, position, this);
});
} catch (MongoServerError e) {
Expand Down Expand Up @@ -265,7 +264,7 @@ public void dropIndex(String indexName) {
private void modifyField(Document document, String modifier, Document update, ArrayFilters arrayFilters,
Integer matchPos, boolean isUpsert) {
Document change = (Document) update.get(modifier);
UpdateOperator updateOperator = getUpdateOperator(modifier, change);
UpdateOperator updateOperator = getUpdateOperator(modifier);
FieldUpdates updates = new FieldUpdates(document, updateOperator, getIdField(), isUpsert, matchPos, arrayFilters);
updates.apply(change, modifier);
}
Expand All @@ -274,7 +273,7 @@ protected String getIdField() {
return options.getIdField();
}

private UpdateOperator getUpdateOperator(String modifier, Document change) {
private UpdateOperator getUpdateOperator(String modifier) {
final UpdateOperator op;
try {
op = UpdateOperator.fromValue(modifier);
Expand Down Expand Up @@ -348,7 +347,7 @@ private Document calculateUpdateDocument(Document oldDocument, Document update,

if (numStartsWithDollar == 0) {
applyUpdate(newDocument, update);
} else if (numStartsWithDollar == update.keySet().size()) {
} else if (numStartsWithDollar == update.size()) {
validateUpdateQuery(update);
oldDocument.cloneInto(newDocument);
for (String key : update.keySet()) {
Expand Down Expand Up @@ -482,7 +481,7 @@ public synchronized MongoServerError getCause() {
public QueryResult handleQuery(QueryParameters queryParameters) {
final Document query;
final Document orderBy;
Document querySelector = queryParameters.getQuerySelector();
Document querySelector = queryParameters.querySelector();
if (querySelector.containsKey("query")) {
query = (Document) querySelector.get("query");
orderBy = (Document) querySelector.get("orderby");
Expand All @@ -494,8 +493,8 @@ public QueryResult handleQuery(QueryParameters queryParameters) {
orderBy = null;
}

return queryDocuments(query, orderBy, queryParameters.getNumberToSkip(), queryParameters.getLimit(),
queryParameters.getBatchSize(), queryParameters.getProjection());
return queryDocuments(query, orderBy, queryParameters.numberToSkip(), queryParameters.limit(),
queryParameters.batchSize(), queryParameters.projection());
}

@Override
Expand Down Expand Up @@ -688,7 +687,7 @@ private void convertSelectorToDocument(Document selector, Document document) {
} else if (key.equals("$or")) {
List<?> orValues = (List<?>) value;
if (orValues.size() == 1) {
convertSelectorToDocument((Document) orValues.get(0), document);
convertSelectorToDocument((Document) orValues.getFirst(), document);
}
continue;
} else if (key.startsWith("$")) {
Expand Down Expand Up @@ -728,7 +727,7 @@ public List<Index<P>> getIndexes() {

@Override
public int count(Document query, int skip, int limit) {
if (query == null || query.keySet().isEmpty()) {
if (query == null || query.isEmpty()) {
int count = count();
if (skip > 0) {
count = Math.max(0, count - skip);
Expand All @@ -740,13 +739,9 @@ public int count(Document query, int skip, int limit) {
}

int numberToReturn = Math.max(limit, 0);
int count = 0;
Iterator<?> it = queryDocuments(query, null, skip, numberToReturn, 0, new Document(getIdField(), 1)).iterator();
while (it.hasNext()) {
it.next();
count++;
}
return count;
Document fieldSelector = new Document(getIdField(), 1);
long count = queryDocuments(query, null, skip, numberToReturn, 0, fieldSelector).stream().count();
return Math.toIntExact(count);
}

@Override
Expand Down Expand Up @@ -846,8 +841,8 @@ public void renameTo(MongoDatabase newDatabase, String newCollectionName) {

protected P findDocumentPosition(Document document) {
return streamAllDocumentsWithPosition()
.filter(match -> documentMatchesQuery(match.getDocument(), document))
.map(DocumentWithPosition::getPosition)
.filter(match -> documentMatchesQuery(match.document(), document))
.map(DocumentWithPosition::position)
.findFirst()
.orElse(null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ private void dropIndexes(MongoCollection<P> collection, Document query) {
if (index instanceof String indexName) {
nsQuery.append("name", indexName);
} else {
nsQuery.append("key", (Document) index);
nsQuery.append("key", index);
}
Document indexToDrop = CollectionUtils.getSingleElement(indexCollection.handleQuery(nsQuery),
() -> createIndexNotFoundException(index));
Expand Down Expand Up @@ -525,7 +525,7 @@ private Document commandAggregate(String command, Document query, DatabaseResolv
Object pipelineObject = Aggregation.parse(query.get("pipeline"));
List<Document> pipeline = Aggregation.parse(pipelineObject);
if (!pipeline.isEmpty()) {
Document changeStream = (Document) pipeline.get(0).get("$changeStream");
Document changeStream = (Document) pipeline.getFirst().get("$changeStream");
if (changeStream != null) {
Aggregation aggregation = getAggregation(pipeline.subList(1, pipeline.size()), query, databaseResolver, collection, oplog);
aggregation.validate(query);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ public synchronized Iterable<P> getPositions(Document query) {
for (Entry<KeyValue, P> entry : getIterable()) {
KeyValue obj = entry.getKey();
if (obj.size() == 1) {
Object o = obj.get(0);
Object o = obj.getFirst();
if (o instanceof String) {
BsonRegularExpression regularExpression = BsonRegularExpression.convertToRegularExpression(queriedValue);
Matcher matcher = regularExpression.matcher(o.toString());
Expand Down
13 changes: 2 additions & 11 deletions core/src/main/java/de/bwaldvogel/mongo/backend/ArrayFilters.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ private static ArrayFilters parse(List<Document> arrayFilters, Document updateQu

if (topLevelFieldNames.size() > 1) {
throw new FailedToParseException("Error parsing array filter :: caused by ::" +
" Expected a single top-level field name, found '" + topLevelFieldNames.get(0) + "' and '" + topLevelFieldNames.get(1) + "'");
" Expected a single top-level field name, found '" + topLevelFieldNames.getFirst() + "' and '" + topLevelFieldNames.get(1) + "'");
}

String topLevelFieldName = CollectionUtils.getSingleElement(topLevelFieldNames);
Expand Down Expand Up @@ -80,15 +80,6 @@ private static Object createFilter(Document arrayFilter) {
return filter;
}

private static Object createFilter(List<String> pathFragments, Object query) {
List<String> tail = Utils.getTail(pathFragments);
if (tail.isEmpty()) {
return query;
} else {
return new Document(Utils.joinPath(tail), query);
}
}

private static void validate(Document updateQuery, Map<String, ?> arrayFilterMap) {
Set<String> allKeys = updateQuery.values().stream()
.filter(Document.class::isInstance)
Expand Down Expand Up @@ -153,7 +144,7 @@ private List<String> calculateKeys(Object object, List<String> pathFragments, St
if (pathFragments.isEmpty()) {
return List.of(path);
}
String fragment = pathFragments.get(0);
String fragment = pathFragments.getFirst();

if (!isPositionalOperator(fragment)) {
String nextPath = Utils.joinPath(path, fragment);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private void validateQueryValue(Object queryValue, String key) {
if (BsonRegularExpression.isRegularExpression(queryValue)) {
return;
}
if (!queryObject.keySet().isEmpty() && queryObject.keySet().iterator().next().startsWith("$")) {
if (!queryObject.isEmpty() && queryObject.getFirstKey().startsWith("$")) {
for (String operator : queryObject.keySet()) {
if (Constants.REFERENCE_KEYS.contains(operator)) {
continue;
Expand Down Expand Up @@ -99,7 +99,7 @@ private boolean checkMatch(Object queryValue, List<String> keys, Object value) {
throw new MongoServerException("illegal keys: " + keys);
}

String firstKey = keys.get(0);
String firstKey = keys.getFirst();

if (firstKey.equals("$comment")) {
log.debug("query comment: '{}'", queryValue);
Expand Down Expand Up @@ -265,26 +265,26 @@ private boolean checkMatch(Object queryValue, QueryFilter filter, Object documen
}
}

switch (filter) {
case AND:
return switch (filter) {
case AND -> {
for (Object subqueryValue : list) {
if (!matches((Document) document, (Document) subqueryValue)) {
return false;
yield false;
}
}
return true;
case OR:
yield true;
}
case OR -> {
for (Object subqueryValue : list) {
if (matches((Document) document, (Document) subqueryValue)) {
return true;
yield true;
}
}
return false;
case NOR:
return !checkMatch(queryValue, QueryFilter.OR, document);
default:
throw new MongoServerException("illegal query filter: " + filter + ". must not happen");
}
yield false;
}
case NOR -> !checkMatch(queryValue, QueryFilter.OR, document);
default -> throw new MongoServerException("illegal query filter: " + filter + ". must not happen");
};
}

@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -367,12 +367,11 @@ private boolean checkMatchesValue(Object queryValue, Object value, boolean requi
}

private boolean checkMatchesAllValues(Object queryValue, Object values) {
if (!(queryValue instanceof Collection)) {
if (!(queryValue instanceof Collection<?> queryValues)) {
return false;
}

Collection<?> list = (Collection<?>) values;
Collection<?> queryValues = (Collection<?>) queryValue;

if (queryValues.isEmpty()) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,11 @@

import de.bwaldvogel.mongo.bson.Document;

public class DocumentWithPosition<P> {

private final Document document;
private final P position;
public record DocumentWithPosition<P>(Document document, P position) {

public DocumentWithPosition(Document document, P position) {
this.document = Objects.requireNonNull(document);
this.position = Objects.requireNonNull(position);
}

public Document getDocument() {
return document;
}

public P getPosition() {
return position;
}

}
10 changes: 4 additions & 6 deletions core/src/main/java/de/bwaldvogel/mongo/backend/FieldUpdates.java
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ private void handleAddToSet(String key, Object changeValue) {
"Cannot apply $addToSet to non-array field. Field named '" + key + "' has non-array type " + describeType(value)));

Collection<Object> pushValues = new ArrayList<>();
if (changeValue instanceof Document addToSetDocument && addToSetDocument.keySet().iterator().next().equals("$each")) {
if (changeValue instanceof Document addToSetDocument && addToSetDocument.getFirstKey().equals("$each")) {
for (String modifier : addToSetDocument.keySet()) {
if (!modifier.equals("$each")) {
throw new BadValueException("Found unexpected fields after $each in $addToSet: " + addToSetDocument.toString(true, "{ ", " }"));
Expand Down Expand Up @@ -349,11 +349,10 @@ private void handleIncMul(Document change, String key, Object changeObject) {
" of non-numeric type " + describeType(value));
}

if (!(changeObject instanceof Number)) {
if (!(changeObject instanceof Number changeValue)) {
String operation = (updateOperator == UpdateOperator.INC) ? "increment" : "multiply";
throw new TypeMismatchException("Cannot " + operation + " with non-numeric argument: " + change.toString(true));
}
Number changeValue = (Number) changeObject;
final Number newValue;
if (updateOperator == UpdateOperator.INC) {
newValue = NumericUtils.addNumbers(number, changeValue);
Expand Down Expand Up @@ -410,10 +409,9 @@ private void handleCurrentDate(String key, Object typeSpecification) {

private void handleRename(String key, Object toField) {
assertNotKeyField(key);
if (!(toField instanceof String)) {
if (!(toField instanceof String newKey)) {
throw new BadValueException("The 'to' field for $rename must be a string: " + key + ": " + toField);
}
String newKey = (String) toField;
assertNotKeyField(newKey);

if (renames.containsKey(key) || renames.containsValue(key)) {
Expand Down Expand Up @@ -455,7 +453,7 @@ private Object getSubdocumentValue(Object document, String key) {

private static Object getSubdocumentValue(Object document, String key, AtomicReference<Integer> matchPos) {
List<String> pathFragments = splitPath(key);
String mainKey = pathFragments.get(0);
String mainKey = pathFragments.getFirst();
if (pathFragments.size() == 1) {
return Utils.getFieldValueListSafe(document, mainKey);
}
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/java/de/bwaldvogel/mongo/backend/Index.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Set<KeyValue> getKeyValues(Document document, boolean normalize) {
.map(value -> (Collection<?>) value)
.collect(Collectors.toList());

if (collectionValues.size() > 0) {
if (!collectionValues.isEmpty()) {
validateHasNoParallelArrays(document);
return CollectionUtils.multiplyWithOtherElements(valuesPerKey.values(), collectionValues).stream()
.map(KeyValue::new)
Expand Down Expand Up @@ -98,7 +98,7 @@ private void validateHasNoParallelArrays(Document document) {
private static List<String> getPathToFirstCollection(Document document, String key) {
List<String> fragments = Utils.splitPath(key);
List<String> remainingFragments = Utils.getTail(fragments);
return getPathToFirstCollection(document, remainingFragments, List.of(fragments.get(0)));
return getPathToFirstCollection(document, remainingFragments, List.of(fragments.getFirst()));
}

private static List<String> getPathToFirstCollection(Document document, List<String> remainingFragments, List<String> path) {
Expand All @@ -110,7 +110,7 @@ private static List<String> getPathToFirstCollection(Document document, List<Str
return null;
}
List<String> newPath = new ArrayList<>(path);
newPath.add(remainingFragments.get(0));
newPath.add(remainingFragments.getFirst());
return getPathToFirstCollection(document, Utils.getTail(remainingFragments), newPath);
}

Expand Down
Loading
Loading