This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch groovyism/grails-data-mongodb in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit e95034cbf17063a13c247a3bd4464a87c3a8f5ad Author: Walter Duque de Estrada <[email protected]> AuthorDate: Fri Oct 16 08:52:45 2026 -0500 refactor(data-mongodb): idiomatic Groovy pass on the java-to-groovy conversion output Behaviour-preserving idiom cleanup of the Java-to-Groovy conversion's output for grails-data-mongodb (bson/core/embedded/spring-data). No public API or behaviour change. Applied: - for (X x : coll) -> for (X x in coll): 69 sites across BsonQuery, MongoDatastore, MongoSession, MongoMappingContext, AbstractMongoObectEntityPersister, MongoEntityPersister, MongoQuery, AbstractMongoSession, EmbeddedMongoInitializer, JsonWriter (a plain colon for-each the converter had left as Java syntax). - Collection literals for no-arg constructors (new ArrayList() -> [], new HashMap<>() -> [:], new LinkedHashSet<>() -> [] as Set, declared type kept): ~40 sites in BsonQuery, MongoDatastore, MongoSession, MongoMappingContext, AbstractMongoObectEntityPersister, MongoEntityPersister, MongoQuery, EmbeddedMongoInitializer. Copy-constructor and sized-capacity call sites left alone. - String/boxed .equals( -> ==, Objects.equals(a, b) -> a == b: MongoDatastore (index name/connection-source/TTL/text-key comparisons), AbstractMongoObectEntityPersister (isDirty), MongoQuery (identity-property name check), ReplicaSetInitiator (errorCode, Boolean.TRUE primary check). Verified every operand pair is same-typed Strings or non-numeric before converting; left Arrays.asList/getKey().equals cases that touch raw Objects or fixed-size array views. - Property syntax for verified collision-free accessors: JsonReader/JsonWriter's inherited AbstractBsonReader/AbstractBsonWriter state/context/currentBsonType/name accessors (checked via javap against org.mongodb:bson for isX/getX pairs before touching any of them); BsonBinary.type/.data, BsonRegularExpression.pattern/options; RestartableMongoClient's five no-arg MongoClient/MongoCluster delegate getters; MongoCommandException.errorCode; Spring's ResourceHolderSupport (synchronizedWithTransaction, isX-only, no getX pair); MongoQuery.Near's redundant hand-written setMaxDistance(Distance) removed in favour of the property Groovy already generates for the field, with its two call sites in Near/NearSphere switched to property assignment. - instanceof + redundant cast on a local -> flow-typed call: WithinBox/WithinCircle's Box/Circle argument, Near/NearSphere's Number argument, MongoQuery's ToOne property. - Minor cleanup: dropped unneeded `this.` on unshadowed fields in AbstractMongoSession; `.getMessage()` -> `.message` (JsonReader, MongoTransaction). Deliberately left (Tier B exclusions, all confirmed by reading the accessor or by javap before deciding): - Every EmbeddedMongoSettings accessor (getPort/getVersion/getDatabaseDir/ getReplicaSet/isPersistent/isReplicaSet) kept as explicit method calls everywhere they're called (FlapdoodleMongoBackend, InMemoryMongoBackend): the class's own equals() documents that getReplicaSet()/isReplicaSet() is a genuine isX/getX collision, and each has javadoc that would be lost by converting to a property. - JsonReader/JsonWriter's getContext()/getContextType() re-declarations and the `this.@field` direct access in their Mark/Context inner classes: left exactly as converted, since each exists only to reach a protected member across the inner/outer class boundary the comments explain. - JsonWriter.Context is not @CompileStatic (confirmed by javap: its .hasElements write still compiles to ScriptBytecodeAdapter.setGroovyObjectProperty); pre-existing, not introduced by this pass, so left alone rather than papering over it with a cast. - JsonScanner, JsonTokenType, EmbeddedQueryEncoder, IndexBuildResult, MissingIndex, UndeclaredIndex, WithinPolygon, MongoIdCoercion, EmbeddedMongoBackend, EmbeddedMongoSettings, EmbeddedMongoLifecycle, FlapdoodleMongoBackend, InMemoryMongoBackend, RunningEmbeddedMongo, ContextStoppedServerApplication: read in full, already idiomatic (records, interfaces, or already using property syntax/collection literals/this.is() correctly) - left unchanged. - JsonReader/JsonScanner/JsonWriter's hand-rolled char-based tokenizer loops: no loop-level rewrites, per the hot-path rule; only null-safety/accessor idioms touched. - `MongoDatastore.options` ternary (new HashMap<>(rawOptions) : new HashMap<>()) left as-is rather than converting only one arm. - AbstractMongoObectEntityPersister's Arrays.asList(keys) kept: fixed-size array view passed to a method this file doesn't control. - No wholesale getter/setter property-syntax sweep of MongoDatastore (2.9k lines), MongoSession, MongoQuery (1.7k lines), AbstractMongoObectEntityPersister or MongoEntityPersister beyond the sites above: verifying every cross-module PersistentEntity/PersistentProperty/Criterion accessor for isX/getX collisions at that volume was out of scope for one pass: left as explicit method calls. Verification: - grails-data-mongodb-bson: compileGroovy/compileTestGroovy clean; test 323/0; codenarcMain/codenarcTest/checkstyleMain clean (0 violations, checkstyle NO-SOURCE: no Java sources). - grails-data-mongodb-core: compileGroovy/compileTestGroovy clean; test 413/0 (includes the TCK suite against the in-memory embedded backend); codenarcMain/codenarcTest/checkstyleMain clean (checkstyle NO-SOURCE). - grails-data-mongodb-embedded: compileGroovy/compileTestGroovy clean; test 161/0; codenarcMain/codenarcTest/checkstyleMain clean (checkstyle NO-SOURCE). - grails-data-mongodb-spring-data: compileGroovy/compileTestGroovy clean; test 60/0; codenarcMain/codenarcTest/checkstyleMain clean (1 file, 0 violations). - javap dynamic-dispatch audit on JsonReader, JsonWriter, RestartableMongoClient, MongoQuery, MongoDatastore, EmbeddedMongoInitializer: only initMetaClass/ compareEqual/compareNotEqual (harmless) plus the three pre-existing, unrelated setGroovyObjectProperty sites noted above; none in code this pass touched. Co-Authored-By: Claude Sonnet 5 <[email protected]> --- .../grails/datastore/bson/json/JsonReader.groovy | 118 ++++++++++----------- .../grails/datastore/bson/json/JsonToken.groovy | 12 +-- .../grails/datastore/bson/json/JsonWriter.groovy | 82 +++++++------- .../grails/datastore/bson/query/BsonQuery.groovy | 28 ++--- .../gorm/mongo/MongoCriteriaBuilder.groovy | 2 +- .../org/grails/datastore/gorm/mongo/Near.groovy | 4 +- .../grails/datastore/gorm/mongo/NearSphere.groovy | 4 +- .../grails/datastore/gorm/mongo/WithinBox.groovy | 2 +- .../datastore/gorm/mongo/WithinCircle.groovy | 2 +- .../mapping/mongo/AbstractMongoSession.groovy | 12 +-- .../datastore/mapping/mongo/MongoDatastore.groovy | 40 +++---- .../datastore/mapping/mongo/MongoSession.groovy | 40 +++---- .../mapping/mongo/MongoTransaction.groovy | 4 +- .../mongo/config/MongoMappingContext.groovy | 6 +- .../connections/RestartableMongoClient.groovy | 10 +- .../AbstractMongoObectEntityPersister.groovy | 30 +++--- .../mongo/engine/MongoEntityPersister.groovy | 18 ++-- .../mapping/mongo/query/MongoQuery.groovy | 64 ++++++----- .../embedded/EmbeddedMongoInitializer.groovy | 22 ++-- .../mongodb/embedded/ReplicaSetInitiator.groovy | 4 +- .../mongodb/GormSpringDataSessionSupport.groovy | 2 +- 21 files changed, 247 insertions(+), 259 deletions(-) diff --git a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonReader.groovy b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonReader.groovy index 2db09ab0c6..949dddb2ca 100644 --- a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonReader.groovy +++ b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonReader.groovy @@ -61,7 +61,7 @@ class JsonReader extends AbstractBsonReader { JsonReader(final Reader reader) { super() scanner = new JsonScanner(reader) - setContext(new Context(null, BsonContextType.TOP_LEVEL)) + context = new Context(null, BsonContextType.TOP_LEVEL) } @Override @@ -71,12 +71,12 @@ class JsonReader extends AbstractBsonReader { @Override protected byte doPeekBinarySubType() { - return doReadBinaryData().getType() + return doReadBinaryData().type } @Override protected int doPeekBinarySize() { - return doReadBinaryData().getData().length + return doReadBinaryData().data.length } @Override @@ -86,90 +86,90 @@ class JsonReader extends AbstractBsonReader { @Override BsonType readBsonType() { - if (isClosed()) { + if (closed) { throw new IllegalStateException('This instance has been closed') } - if (getState() == State.INITIAL || getState() == State.DONE || getState() == State.SCOPE_DOCUMENT) { + if (state == State.INITIAL || state == State.DONE || state == State.SCOPE_DOCUMENT) { // in JSON the top level value can be of any type so fall through - setState(State.TYPE) + state = State.TYPE } - if (getState() != State.TYPE) { + if (state != State.TYPE) { throwInvalidState('readBSONType', State.TYPE) } - if (getContext().getContextType() == BsonContextType.DOCUMENT) { + if (context.contextType == BsonContextType.DOCUMENT) { JsonToken nameToken = popToken() - switch (nameToken.getType()) { + switch (nameToken.type) { case JsonTokenType.STRING: case JsonTokenType.UNQUOTED_STRING: - setCurrentName(nameToken.getValue(String)) + currentName = nameToken.getValue(String) break case JsonTokenType.END_OBJECT: - setState(State.END_OF_DOCUMENT) + state = State.END_OF_DOCUMENT return BsonType.END_OF_DOCUMENT default: - throw new JsonParseException("JSON reader was expecting a name but found '%s'.", nameToken.getValue()) + throw new JsonParseException("JSON reader was expecting a name but found '%s'.", nameToken.value) } JsonToken colonToken = popToken() - if (colonToken.getType() != JsonTokenType.COLON) { - throw new JsonParseException("JSON reader was expecting ':' but found '%s'.", colonToken.getValue()) + if (colonToken.type != JsonTokenType.COLON) { + throw new JsonParseException("JSON reader was expecting ':' but found '%s'.", colonToken.value) } } JsonToken token = popToken() - if (getContext().getContextType() == BsonContextType.ARRAY && token.getType() == JsonTokenType.END_ARRAY) { - setState(State.END_OF_ARRAY) + if (context.contextType == BsonContextType.ARRAY && token.type == JsonTokenType.END_ARRAY) { + state = State.END_OF_ARRAY return BsonType.END_OF_DOCUMENT } boolean noValueFound = false - switch (token.getType()) { + switch (token.type) { case JsonTokenType.BEGIN_ARRAY: - setCurrentBsonType(BsonType.ARRAY) + currentBsonType = BsonType.ARRAY break case JsonTokenType.BEGIN_OBJECT: visitExtendedJSON() break case JsonTokenType.DOUBLE: - setCurrentBsonType(BsonType.DOUBLE) - currentValue = token.getValue() + currentBsonType = BsonType.DOUBLE + currentValue = token.value break case JsonTokenType.END_OF_FILE: - setCurrentBsonType(BsonType.END_OF_DOCUMENT) + currentBsonType = BsonType.END_OF_DOCUMENT break case JsonTokenType.INT32: - setCurrentBsonType(BsonType.INT32) - currentValue = token.getValue() + currentBsonType = BsonType.INT32 + currentValue = token.value break case JsonTokenType.INT64: - setCurrentBsonType(BsonType.INT64) - currentValue = token.getValue() + currentBsonType = BsonType.INT64 + currentValue = token.value break case JsonTokenType.REGULAR_EXPRESSION: - setCurrentBsonType(BsonType.REGULAR_EXPRESSION) - currentValue = token.getValue() + currentBsonType = BsonType.REGULAR_EXPRESSION + currentValue = token.value break case JsonTokenType.STRING: - setCurrentBsonType(BsonType.STRING) - currentValue = token.getValue() + currentBsonType = BsonType.STRING + currentValue = token.value break case JsonTokenType.UNQUOTED_STRING: String value = token.getValue(String) if (JsonToken.BOOLEAN_FALSE == value || JsonToken.BOOLEAN_TRUE == value) { - setCurrentBsonType(BsonType.BOOLEAN) + currentBsonType = BsonType.BOOLEAN currentValue = Boolean.parseBoolean(value) } else if ('Infinity' == value) { - setCurrentBsonType(BsonType.DOUBLE) + currentBsonType = BsonType.DOUBLE currentValue = Double.POSITIVE_INFINITY } else if ('NaN' == value) { - setCurrentBsonType(BsonType.DOUBLE) + currentBsonType = BsonType.DOUBLE currentValue = Double.NaN } else if (JsonToken.NULL == value) { - setCurrentBsonType(BsonType.NULL) + currentBsonType = BsonType.NULL } else if ('undefined' == value) { - setCurrentBsonType(BsonType.UNDEFINED) + currentBsonType = BsonType.UNDEFINED } else { noValueFound = true } @@ -179,28 +179,28 @@ class JsonReader extends AbstractBsonReader { break } if (noValueFound) { - throw new JsonParseException("JSON reader was expecting a value but found '%s'.", token.getValue()) + throw new JsonParseException("JSON reader was expecting a value but found '%s'.", token.value) } - if (getContext().getContextType() == BsonContextType.ARRAY || getContext().getContextType() == BsonContextType.DOCUMENT) { + if (context.contextType == BsonContextType.ARRAY || context.contextType == BsonContextType.DOCUMENT) { JsonToken commaToken = popToken() - if (commaToken.getType() != JsonTokenType.COMMA) { + if (commaToken.type != JsonTokenType.COMMA) { pushToken(commaToken) } } - switch (getContext().getContextType()) { + switch (context.contextType) { case BsonContextType.ARRAY: case BsonContextType.JAVASCRIPT_WITH_SCOPE: case BsonContextType.TOP_LEVEL: - setState(State.VALUE) + state = State.VALUE break default: // DOCUMENT, SCOPE_DOCUMENT and anything else - setState(State.NAME) + state = State.NAME break } - return getCurrentBsonType() + return currentBsonType } @Override @@ -215,11 +215,11 @@ class JsonReader extends AbstractBsonReader { @Override protected void doReadEndArray() { - setContext(getContext().getParentContext()) + context = context.parentContext - if (getContext().getContextType() == BsonContextType.ARRAY || getContext().getContextType() == BsonContextType.DOCUMENT) { + if (context.contextType == BsonContextType.ARRAY || context.contextType == BsonContextType.DOCUMENT) { JsonToken commaToken = popToken() - if (commaToken.getType() != JsonTokenType.COMMA) { + if (commaToken.type != JsonTokenType.COMMA) { pushToken(commaToken) } } @@ -227,19 +227,19 @@ class JsonReader extends AbstractBsonReader { @Override protected void doReadEndDocument() { - setContext(getContext().getParentContext()) - if (getContext() != null && getContext().getContextType() == BsonContextType.SCOPE_DOCUMENT) { - setContext(getContext().getParentContext()) // JavaScriptWithScope + context = context.parentContext + if (context != null && context.contextType == BsonContextType.SCOPE_DOCUMENT) { + context = context.parentContext // JavaScriptWithScope verifyToken(JsonToken.CLOSE_BRACE) // outermost closing bracket for JavaScriptWithScope } - if (getContext() == null) { + if (context == null) { throw new JsonParseException('Unexpected end of document.') } - if (getContext().getContextType() == BsonContextType.ARRAY || getContext().getContextType() == BsonContextType.DOCUMENT) { + if (context.contextType == BsonContextType.ARRAY || context.contextType == BsonContextType.DOCUMENT) { JsonToken commaToken = popToken() - if (commaToken.getType() != JsonTokenType.COMMA) { + if (commaToken.type != JsonTokenType.COMMA) { pushToken(commaToken) } } @@ -302,12 +302,12 @@ class JsonReader extends AbstractBsonReader { @Override protected void doReadStartArray() { - setContext(new Context(getContext(), BsonContextType.ARRAY)) + context = new Context(context, BsonContextType.ARRAY) } @Override protected void doReadStartDocument() { - setContext(new Context(getContext(), BsonContextType.DOCUMENT)) + context = new Context(context, BsonContextType.DOCUMENT) } @Override @@ -337,7 +337,7 @@ class JsonReader extends AbstractBsonReader { @Override protected void doSkipValue() { - switch (getCurrentBsonType()) { + switch (currentBsonType) { case BsonType.ARRAY: readStartArray() while (readBsonType() != BsonType.END_OF_DOCUMENT) { @@ -427,7 +427,7 @@ class JsonReader extends AbstractBsonReader { try { return scanner.nextToken() } catch (IOException e) { - throw new JsonParseException('Cannot parse JSON due to IO error: ' + e.getMessage(), e) + throw new JsonParseException('Cannot parse JSON due to IO error: ' + e.message, e) } } @@ -444,8 +444,8 @@ class JsonReader extends AbstractBsonReader { throw new IllegalArgumentException("Can't be null") } JsonToken token = popToken() - if (!expected.equals(token.getValue())) { - throw new JsonParseException("JSON reader expected '%s' but found '%s'.", expected, token.getValue()) + if (!expected.equals(token.value)) { + throw new JsonParseException("JSON reader expected '%s' but found '%s'.", expected, token.value) } } @@ -453,7 +453,7 @@ class JsonReader extends AbstractBsonReader { JsonToken nameToken = popToken() pushToken(nameToken) - setCurrentBsonType(BsonType.DOCUMENT) + currentBsonType = BsonType.DOCUMENT } @Override @@ -497,9 +497,9 @@ class JsonReader extends AbstractBsonReader { try { JsonReader.this.scanner.reader.reset() } catch (IOException e) { - throw new JsonParseException('Failed to reset reader: ' + e.getMessage(), e) + throw new JsonParseException('Failed to reset reader: ' + e.message, e) } - JsonReader.this.resetContext(getParentContext(), getContextType()) + JsonReader.this.resetContext(parentContext, contextType) } } diff --git a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonToken.groovy b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonToken.groovy index 26e98d3256..256405bf9e 100644 --- a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonToken.groovy +++ b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonToken.groovy @@ -43,18 +43,14 @@ class JsonToken { @PackageScope static final char NEW_LINE = '\n' @PackageScope static final char QUOTE = '"' - private final Object value - private final JsonTokenType type + final Object value + final JsonTokenType type JsonToken(final JsonTokenType type, final Object value) { this.value = value this.type = type } - Object getValue() { - return value - } - def <T> T getValue(final Class<T> clazz) { if (Long == clazz) { if (value instanceof Integer) { @@ -71,8 +67,4 @@ class JsonToken { } } - JsonTokenType getType() { - return type - } - } diff --git a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonWriter.groovy b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonWriter.groovy index bb607ced74..7eca6860a0 100644 --- a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonWriter.groovy +++ b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/json/JsonWriter.groovy @@ -63,11 +63,11 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteStartDocument() { try { - if (getState() == State.VALUE || getState() == State.SCOPE_DOCUMENT) { - writeNameHelper(getName()) + if (state == State.VALUE || state == State.SCOPE_DOCUMENT) { + writeNameHelper(name) } - BsonContextType contextType = (getState() == State.SCOPE_DOCUMENT) ? BsonContextType.SCOPE_DOCUMENT : BsonContextType.DOCUMENT - setContext(new Context(getContext(), contextType, settings.getIndentCharacters())) + BsonContextType contextType = (state == State.SCOPE_DOCUMENT) ? BsonContextType.SCOPE_DOCUMENT : BsonContextType.DOCUMENT + context = new Context(context, contextType, settings.indentCharacters) writer.write(JsonToken.OPEN_BRACE) } catch (IOException e) { @@ -79,11 +79,11 @@ class JsonWriter extends AbstractBsonWriter { protected void doWriteEndDocument() { try { writer.write(JsonToken.CLOSE_BRACE) - if (getContext().getContextType() == BsonContextType.SCOPE_DOCUMENT) { - setContext(getContext().getParentContext()) + if (context.contextType == BsonContextType.SCOPE_DOCUMENT) { + context = context.parentContext writeEndDocument() } else { - setContext(getContext().getParentContext()) + context = context.parentContext } } catch (IOException e) { throwBsonException(e) @@ -93,9 +93,9 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteStartArray() { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(JsonToken.OPEN_BRACKET) - setContext(new Context(getContext(), BsonContextType.ARRAY, settings.getIndentCharacters())) + context = new Context(context, BsonContextType.ARRAY, settings.indentCharacters) } catch (IOException e) { throwBsonException(e) } @@ -108,16 +108,16 @@ class JsonWriter extends AbstractBsonWriter { } catch (IOException e) { throwBsonException(e) } - setContext(getContext().getParentContext()) + context = context.parentContext } @Override protected void doWriteBinaryData(BsonBinary value) { try { - writeNameHelper(getName()) - byte[] data = value.getData() + writeNameHelper(name) + byte[] data = value.data writer.write(Base64.getEncoder().encodeToString(data)) - setState(getNextState()) + state = nextState } catch (IOException e) { throwBsonException(e) } @@ -126,9 +126,9 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteBoolean(boolean value) { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(value ? JsonToken.BOOLEAN_TRUE : JsonToken.BOOLEAN_FALSE) - setState(getNextState()) + state = nextState } catch (IOException e) { throwBsonException(e) } @@ -137,14 +137,14 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteDateTime(long value) { DateFormat df = new SimpleDateFormat(ISO_8601) - df.setTimeZone(UTC) + df.timeZone = UTC try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(JsonToken.QUOTE) Date date = new Date(value) writer.write(df.format(date)) writer.write(JsonToken.QUOTE) - setState(getNextState()) + state = nextState } catch (IOException e) { throwBsonException(e) } @@ -158,9 +158,9 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteDouble(double value) { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(Double.toString(value)) - setState(getNextState()) + state = nextState } catch (IOException e) { throwBsonException(e) } @@ -169,7 +169,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteInt32(int value) { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(Integer.toString(value)) } catch (IOException e) { throwBsonException(e) @@ -179,7 +179,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteInt64(long value) { try { - writeNameHelper(getName()) + writeNameHelper(name) if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) { writer.write(Long.toString(value)) } else { @@ -195,7 +195,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteDecimal128(Decimal128 value) { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(JsonToken.QUOTE) writer.write(value.toString()) writer.write(JsonToken.QUOTE) @@ -227,7 +227,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteNull() { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(JsonToken.NULL) } catch (IOException e) { throwBsonException(e) @@ -237,7 +237,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteObjectId(ObjectId value) { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write(value.toString()) } catch (IOException e) { throwBsonException(e) @@ -247,21 +247,21 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteRegularExpression(BsonRegularExpression regularExpression) { try { - switch (settings.getOutputMode()) { + switch (settings.outputMode) { case JsonMode.STRICT: writeStartDocument() - writeString('$regex', regularExpression.getPattern()) - writeString('$options', regularExpression.getOptions()) + writeString('$regex', regularExpression.pattern) + writeString('$options', regularExpression.options) writeEndDocument() break default: - writeNameHelper(getName()) + writeNameHelper(name) writer.write(JsonToken.FORWARD_SLASH) - String escaped = (regularExpression.getPattern() == '') ? '(?:)' : regularExpression.getPattern() + String escaped = (regularExpression.pattern == '') ? '(?:)' : regularExpression.pattern .replace('/', '\\/') writer.write(escaped) writer.write(JsonToken.FORWARD_SLASH) - writer.write(regularExpression.getOptions()) + writer.write(regularExpression.options) break } } catch (IOException e) { @@ -272,7 +272,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteString(final String value) { try { - writeNameHelper(getName()) + writeNameHelper(name) writeStringHelper(value) } catch (IOException e) { throwBsonException(e) @@ -292,7 +292,7 @@ class JsonWriter extends AbstractBsonWriter { @Override protected void doWriteUndefined() { try { - writeNameHelper(getName()) + writeNameHelper(name) writer.write('undefined') } catch (IOException e) { throwBsonException(e) @@ -309,21 +309,21 @@ class JsonWriter extends AbstractBsonWriter { } protected void writeNameHelper(final String name) throws IOException { - switch (getContext().getContextType()) { + switch (context.contextType) { case BsonContextType.ARRAY: // don't write Array element names in JSON - if (getContext().hasElements) { + if (context.hasElements) { writer.write(JsonToken.COMMA) } break case BsonContextType.DOCUMENT: case BsonContextType.SCOPE_DOCUMENT: - if (getContext().hasElements) { + if (context.hasElements) { writer.write(JsonToken.COMMA) } - if (settings.isIndent()) { - writer.write(settings.getNewLineCharacters()) - writer.write(getContext().indentation) + if (settings.indent) { + writer.write(settings.newLineCharacters) + writer.write(context.indentation) } writeStringHelper(name) writer.write(JsonToken.COLON) @@ -334,7 +334,7 @@ class JsonWriter extends AbstractBsonWriter { throw new BSONException('Invalid contextType.') } - getContext().hasElements = true + context.hasElements = true } private void throwBsonException(IOException e) { @@ -348,7 +348,7 @@ class JsonWriter extends AbstractBsonWriter { private void writeStringHelper(final String str) throws IOException { writer.write('"') - for (final char c : str.toCharArray()) { + for (final char c in str.toCharArray()) { switch (c) { case ('"' as char): writer.write('\\"') diff --git a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/query/BsonQuery.groovy b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/query/BsonQuery.groovy index 2d0ac3e202..482d966db9 100644 --- a/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/query/BsonQuery.groovy +++ b/grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/query/BsonQuery.groovy @@ -120,18 +120,18 @@ abstract class BsonQuery extends Query { private static final String THIS_PREFIX = 'this.' /** Matches MongoDB's own document nesting limit, so no value the server would accept is refused. */ private static final int MAX_CRITERION_VALUE_DEPTH = 100 - protected static Map<Class, QueryHandler> queryHandlers = new HashMap<>() - protected static Map<String, OperatorHandler> operatorHandlers = new HashMap<>() - protected static Map<Class, ProjectionHandler> groupByProjectionHandlers = new HashMap<>() + protected static Map<Class, QueryHandler> queryHandlers = [:] + protected static Map<String, OperatorHandler> operatorHandlers = [:] + protected static Map<Class, ProjectionHandler> groupByProjectionHandlers = [:] - protected static Map<Class, ProjectionHandler> projectProjectionHandlers = new HashMap<>() + protected static Map<Class, ProjectionHandler> projectProjectionHandlers = [:] /** * Criterion types whose values are shapes or nested queries by design and are therefore not * subject to {@link #validateCriterionValues(Criterion, PersistentEntity)}. Subclasses register * their own exemptions here, the same way they register query handlers. */ - protected static final Set<Class<? extends Criterion>> VALUE_VALIDATION_EXEMPT_CRITERIA = new HashSet<>() + protected static final Set<Class<? extends Criterion>> VALUE_VALIDATION_EXEMPT_CRITERIA = [] as Set static { VALUE_VALIDATION_EXEMPT_CRITERIA.add(SubqueryCriterion) @@ -326,9 +326,9 @@ abstract class BsonQuery extends Query { queryHandlers.put(Negation, new QueryHandler<Negation>() { void handle(EmbeddedQueryEncoder queryEncoder, Negation criteria, Document query, PersistentEntity entity) { - List nor = new ArrayList() + List nor = [] query.put(NOR_OPERATOR, nor) - for (Criterion criterion : criteria.getCriteria()) { + for (Criterion criterion in criteria.getCriteria()) { Document negatedQuery = new Document() nor.add(negatedQuery) if (criterion instanceof PropertyCriterion) { @@ -540,7 +540,7 @@ abstract class BsonQuery extends Query { @PackageScope static List readArrayOfValues(BsonReader queryReader) { - List values = new ArrayList() + List values = [] BsonType bsonType = queryReader.getCurrentBsonType() if (bsonType == BsonType.ARRAY) { queryReader.readStartArray() @@ -800,7 +800,7 @@ abstract class BsonQuery extends Query { protected static List<Object> getInListQueryValues(PersistentEntity entity, In inCriterion) { List<Object> values = new ArrayList<Object>(inCriterion.getValues().size()) final MappingContext mappingContext = entity.getMappingContext() - for (Object value : inCriterion.getValues()) { + for (Object value in inCriterion.getValues()) { if (mappingContext.isPersistentEntity(value)) { PersistentEntity pe = mappingContext.getPersistentEntity( value.getClass().getName()) @@ -987,7 +987,7 @@ abstract class BsonQuery extends Query { protected static void populateBsonQuery(final EmbeddedQueryEncoder queryEncoder, Document query, List<Criterion> criteria, final PersistentEntity entity) { // if a query combines more than 1 item, wrap the items in individual $and or $or arguments // so that property names can't clash (e.g. for an $and containing two $ors) - for (Criterion criterion : criteria) { + for (Criterion criterion in criteria) { validateCriterionValues(criterion, entity) final QueryHandler queryHandler = queryHandlers.get(criterion.getClass()) if (queryHandler != null) { @@ -1013,17 +1013,17 @@ abstract class BsonQuery extends Query { protected static void populateBsonQuery(final EmbeddedQueryEncoder queryEncoder, Document query, Junction criteria, final PersistentEntity entity) { List subList = null if (criteria instanceof Disjunction) { - subList = new ArrayList() + subList = [] query.put(OR_OPERATOR, subList) } else if (criteria instanceof Conjunction) { - subList = new ArrayList() + subList = [] query.put(AND_OPERATOR, subList) } else if (criteria instanceof Negation) { - subList = new ArrayList() + subList = [] query.put(NOT_OPERATOR, new Document(OR_OPERATOR, subList)) } - for (Criterion criterion : criteria.getCriteria()) { + for (Criterion criterion in criteria.getCriteria()) { validateCriterionValues(criterion, entity) final QueryHandler queryHandler = queryHandlers.get(criterion.getClass()) if (queryHandler != null) { diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/MongoCriteriaBuilder.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/MongoCriteriaBuilder.groovy index cf7d780f02..4a770f92cf 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/MongoCriteriaBuilder.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/MongoCriteriaBuilder.groovy @@ -274,7 +274,7 @@ class MongoCriteriaBuilder extends CriteriaBuilder { } Criteria arguments(Map arguments) { - ((QueryArgumentsAware) this.query).setArguments(arguments) + ((QueryArgumentsAware) query).arguments = arguments return this } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/Near.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/Near.groovy index 427f04369e..ab605c9664 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/Near.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/Near.groovy @@ -41,9 +41,9 @@ class Near extends MethodExpression { if (arguments.length > 1) { Object o = arguments[1] if (o instanceof Number) { - near.setMaxDistance(Distance.valueOf(((Number) o).doubleValue())) + near.maxDistance = Distance.valueOf(o.doubleValue()) } else { - near.setMaxDistance((Distance) o) + near.maxDistance = (Distance) o } } return near diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/NearSphere.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/NearSphere.groovy index bf3879e15c..e61501fd42 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/NearSphere.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/NearSphere.groovy @@ -40,9 +40,9 @@ class NearSphere extends Near { if (arguments.length > 1) { Object o = arguments[1] if (o instanceof Number) { - near.setMaxDistance(Distance.valueOf(((Number) o).doubleValue())) + near.maxDistance = Distance.valueOf(o.doubleValue()) } else { - near.setMaxDistance((Distance) o) + near.maxDistance = (Distance) o } } return near diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinBox.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinBox.groovy index 55ff6d0883..48483782ea 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinBox.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinBox.groovy @@ -40,7 +40,7 @@ class WithinBox extends MethodExpression { Criterion createCriterion() { Object argument = arguments[0] if (argument instanceof Box) { - return new MongoQuery.WithinBox(propertyName, ((Box) argument).asList()) + return new MongoQuery.WithinBox(propertyName, argument.asList()) } return new MongoQuery.WithinBox(propertyName, (List) argument) } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinCircle.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinCircle.groovy index 62b0326772..abde9b4ab0 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinCircle.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/gorm/mongo/WithinCircle.groovy @@ -44,7 +44,7 @@ class WithinCircle extends MethodExpression { Criterion createCriterion() { Object argument = arguments[0] if (argument instanceof Circle) { - return new MongoQuery.WithinCircle(propertyName, ((Circle) argument).asList()) + return new MongoQuery.WithinCircle(propertyName, argument.asList()) } return new MongoQuery.WithinCircle(propertyName, (List) argument) } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/AbstractMongoSession.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/AbstractMongoSession.groovy index 7afc00c4fc..3147d39625 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/AbstractMongoSession.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/AbstractMongoSession.groovy @@ -74,7 +74,7 @@ abstract class AbstractMongoSession extends AbstractSession<MongoClient> { AbstractMongoSession(MongoDatastore datastore, MappingContext mappingContext, ApplicationEventPublisher publisher, boolean stateless) { super(datastore, mappingContext, publisher, stateless) mongoDatastore = datastore - this.defaultDatabase = getDocumentMappingContext().getDefaultDatabaseName() + defaultDatabase = getDocumentMappingContext().getDefaultDatabaseName() } @Override @@ -90,7 +90,7 @@ abstract class AbstractMongoSession extends AbstractSession<MongoClient> { @Override void flush() { - flush(this.getWriteConcern()) + flush(getWriteConcern()) } abstract void flush(WriteConcern writeConcern) @@ -131,7 +131,7 @@ abstract class AbstractMongoSession extends AbstractSession<MongoClient> { } WriteConcern getDeclaredWriteConcern(PersistentEntity entity) { - return getDeclaredWriteConcern(this.writeConcern, entity) + return getDeclaredWriteConcern(writeConcern, entity) } private WriteConcern getDeclaredWriteConcern(WriteConcern defaultConcern, PersistentEntity entity) { @@ -233,7 +233,7 @@ abstract class AbstractMongoSession extends AbstractSession<MongoClient> { */ @PackageScope void clearClientSession() { - this.clientSession = null + clientSession = null } /** @@ -292,7 +292,7 @@ abstract class AbstractMongoSession extends AbstractSession<MongoClient> { session.close() throw e } - this.clientSession = session + clientSession = session return new MongoTransaction(this, session, readOnly) } if (readOnly && getDatastore().isTransactionsEnabled()) { @@ -360,7 +360,7 @@ abstract class AbstractMongoSession extends AbstractSession<MongoClient> { abstract <T> T decode(Class<T> type, Object nativeObject) protected void addPostFlushOperations(List<PendingOperation> cascadeOperations) { - for (PendingOperation cascadeOperation : cascadeOperations) { + for (PendingOperation cascadeOperation in cascadeOperations) { addPostFlushOperation(cascadeOperation) } } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoDatastore.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoDatastore.groovy index 9f3b705d52..d2dd064ee5 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoDatastore.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoDatastore.groovy @@ -301,13 +301,13 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene DatastoreTransactionManager datastoreTransactionManager = new DatastoreTransactionManager() datastoreTransactionManager.setDatastore(this) transactionManager = datastoreTransactionManager - for (PersistentEntity entity : mappingContext.getPersistentEntities()) { + for (PersistentEntity entity in mappingContext.getPersistentEntities()) { registerEntity(entity) } if (!(connectionSources instanceof SingletonConnectionSources)) { final MongoDatastore parent = this Iterable<ConnectionSource<MongoClient, MongoConnectionSourceSettings>> allConnectionSources = connectionSources.getAllConnectionSources() - for (final ConnectionSource<MongoClient, MongoConnectionSourceSettings> connectionSource : allConnectionSources) { + for (final ConnectionSource<MongoClient, MongoConnectionSourceSettings> connectionSource in allConnectionSources) { SingletonConnectionSources<MongoClient, MongoConnectionSourceSettings> singletonConnectionSources = new SingletonConnectionSources<MongoClient, MongoConnectionSourceSettings>(connectionSource, connectionSources.getBaseConfiguration()) MongoDatastore childDatastore @@ -874,7 +874,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene */ private String buildIndexesSettingName() { String connection = connectionName() - if (ConnectionSource.DEFAULT.equals(connection)) { + if (ConnectionSource.DEFAULT == connection) { return MongoSettings.SETTING_BUILD_INDEXES } return MongoSettings.SETTING_CONNECTIONS + '.' + connection + '.buildIndexes (or ' + @@ -1074,7 +1074,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene * can name the same one. */ private Map<MongoNamespace, CollectionDeclarations> declarationsByCollection() { - Map<MongoNamespace, CollectionDeclarations> collections = new LinkedHashMap<>() + Map<MongoNamespace, CollectionDeclarations> collections = [:] for (PersistentEntity entity in indexedEntities()) { com.mongodb.client.MongoCollection<Document> collection = getCollection(entity) CollectionDeclarations declarations = collections.get(collection.getNamespace()) @@ -1159,7 +1159,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene for (Map.Entry<MongoNamespace, CollectionDeclarations> entry in declarationsByCollection().entrySet()) { MongoNamespace namespace = entry.getKey() for (Document index in entry.getValue().collection().listIndexes()) { - if (ID_INDEX_NAME.equals(index.getString('name'))) { + if (ID_INDEX_NAME == index.getString('name')) { continue } Object key = index.get('key') @@ -1203,7 +1203,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene Map<MongoNamespace, CollectionDeclarations> mapped = declarationsByCollection() // Listed first, once per collection, rather than inferred from the drop: the driver answers a dropIndex on // a collection that no longer exists as a success, and a name can have been given to another index since. - Map<MongoNamespace, List<Document>> listed = new HashMap<>() + Map<MongoNamespace, List<Document>> listed = [:] for (UndeclaredIndex index in indexes) { MongoNamespace namespace = new MongoNamespace(index.database(), index.collection()) CollectionDeclarations declarations = mapped.get(namespace) @@ -1427,7 +1427,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene * to its root's collection, and several classes can name the same one. Sharing it also keeps them * consistent, so a second class declaring keys the first has just created sees them as present. */ - private final Map<MongoNamespace, ExistingIndexes> existingIndexes = new HashMap<>() + private final Map<MongoNamespace, ExistingIndexes> existingIndexes = [:] IndexBuildSummary(boolean classifying) { this.classifying = classifying @@ -1738,7 +1738,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene } protected void registerAllEntitiesWithEnhancer() { - for (PersistentEntity persistentEntity : getMappingContext().getPersistentEntities()) { + for (PersistentEntity persistentEntity in getMappingContext().getPersistentEntities()) { gormEnhancer.registerEntity(persistentEntity) } } @@ -1886,7 +1886,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene final MongoCollection mappedForm = classMapping.getMappedForm() if (mappedForm != null) { List<MongoCollection.Index> indices = mappedForm.getIndices() - for (MongoCollection.Index index : indices) { + for (MongoCollection.Index index in indices) { declarations.add(new IndexDeclaration(new Document(index.getDefinition()), index.getOptions(), 'with definition [' + index.getDefinition() + ']')) } @@ -1905,7 +1905,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene } } - for (PersistentProperty<MongoAttribute> property : entity.getPersistentProperties()) { + for (PersistentProperty<MongoAttribute> property in entity.getPersistentProperties()) { final boolean indexed = isIndexed(property) if (indexed) { @@ -1954,7 +1954,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene Map<String, Object> options = rawOptions != null ? new HashMap<>(rawOptions) : new HashMap<>() // Control flag — not a Mongo index option. - boolean recreateOnConflict = Boolean.TRUE.equals(options.remove(INDEX_RECREATE_ON_CONFLICT)) + boolean recreateOnConflict = Boolean.TRUE == options.remove(INDEX_RECREATE_ON_CONFLICT) Long expireAfterSeconds = null Object ttl = options.remove(INDEX_EXPIRE_AFTER_SECONDS) @@ -2067,7 +2067,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene // TTL change on an existing index — update in place, no rebuild, no gap. An index that merely holds the // name is a different index, so its expiry is not the declared one to update. - boolean ttlChange = !nameTaken && expireAfterSeconds != null && !expireAfterSeconds.equals(existingTtlSeconds) + boolean ttlChange = !nameTaken && expireAfterSeconds != null && expireAfterSeconds != existingTtlSeconds if (ttlChange) { try { getMongoClient().getDatabase(getDatabaseName(entity)) @@ -2139,7 +2139,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene */ private static Document findIndexByName(Iterable<Document> indexes, String name) { for (Document index in indexes) { - if (name.equals(index.getString('name'))) { + if (name == index.getString('name')) { return index } } @@ -2227,9 +2227,9 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene private static TextKeys declaredTextKeys(Document keys) { Document before = new Document() Document after = new Document() - Set<String> fields = new LinkedHashSet<>() + Set<String> fields = [] as Set for (Map.Entry<String, Object> entry in keys.entrySet()) { - if ('text'.equals(entry.getValue())) { + if ('text' == entry.getValue()) { fields.add(entry.getKey()) } else { @@ -2248,7 +2248,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene Document after = new Document() boolean pastText = false for (Map.Entry<String, Object> entry in key.entrySet()) { - if (TEXT_INDEX_KEY.equals(entry.getKey()) || TEXT_INDEX_TERM_KEY.equals(entry.getKey())) { + if (TEXT_INDEX_KEY == entry.getKey() || TEXT_INDEX_TERM_KEY == entry.getKey()) { pastText = true } else { @@ -2284,7 +2284,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene if (key.containsKey(TEXT_INDEX_KEY)) { return true } - for (Object v : key.values()) { + for (Object v in key.values()) { if ('text' == v) { return true } @@ -2303,7 +2303,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene Iterator<Map.Entry<String, Object>> existing = existingKey.entrySet().iterator() for (Map.Entry<String, Object> desired in desiredKey.entrySet()) { Map.Entry<String, Object> actual = existing.next() - if (!actual.getKey().equals(desired.getKey())) { + if (actual.getKey() != desired.getKey()) { return false } Object a = actual.getValue() @@ -2312,7 +2312,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene if (((Number) a).doubleValue() != ((Number) b).doubleValue()) { return false } - } else if (!Objects.equals(a, b)) { + } else if (a != b) { return false } } @@ -2894,7 +2894,7 @@ class MongoDatastore extends AbstractDatastore implements MappingContext.Listene class PersistentEntityCodeRegistry implements CodecProvider { - Map<String, PersistentEntityCodec> codecs = new HashMap<>() + Map<String, PersistentEntityCodec> codecs = [:] @Override def <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) { diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoSession.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoSession.groovy index 618f754230..27dc34bbc0 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoSession.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoSession.groovy @@ -114,15 +114,15 @@ class MongoSession extends AbstractMongoSession { return } - Map<String, Integer> numberOfOptimisticUpdates = new LinkedHashMap<>() - Map<String, Integer> numberOfPessimisticUpdates = new LinkedHashMap<>() + Map<String, Integer> numberOfOptimisticUpdates = [:] + Map<String, Integer> numberOfPessimisticUpdates = [:] - Map<PersistentEntity, List<WriteModel<Document>>> writeModels = new LinkedHashMap<>() - for (PersistentEntity persistentEntity : pendingInserts.keySet()) { + Map<PersistentEntity, List<WriteModel<Document>>> writeModels = [:] + for (PersistentEntity persistentEntity in pendingInserts.keySet()) { final Collection<PendingInsert> inserts = pendingInserts.get(persistentEntity) if (inserts != null && !inserts.isEmpty()) { List<WriteModel<Document>> entityWrites = getWriteModelsForEntity(persistentEntity, writeModels) - for (PendingInsert insert : inserts) { + for (PendingInsert insert in inserts) { insert.run() if (insert.isVetoed()) { @@ -137,7 +137,7 @@ class MongoSession extends AbstractMongoSession { } } - for (PersistentEntity persistentEntity : pendingUpdates.keySet()) { + for (PersistentEntity persistentEntity in pendingUpdates.keySet()) { final String name = persistentEntity.isRoot() ? persistentEntity.getName() : persistentEntity.getRootEntity().getName() int numberOfOptimistic = numberOfOptimisticUpdates.containsKey(name) ? numberOfOptimisticUpdates.get(name) : 0 int numberOfPessimistic = numberOfPessimisticUpdates.containsKey(name) ? numberOfPessimisticUpdates.get(name) : 0 @@ -145,7 +145,7 @@ class MongoSession extends AbstractMongoSession { final Collection<PendingUpdate> updates = pendingUpdates.get(persistentEntity) if (updates != null && !updates.isEmpty()) { List<WriteModel<Document>> entityWrites = getWriteModelsForEntity(persistentEntity, writeModels) - for (PendingUpdate update : updates) { + for (PendingUpdate update in updates) { update.run() if (update.isVetoed()) { @@ -184,12 +184,12 @@ class MongoSession extends AbstractMongoSession { numberOfPessimisticUpdates.put(name, numberOfPessimistic) } - for (PersistentEntity persistentEntity : pendingDeletes.keySet()) { + for (PersistentEntity persistentEntity in pendingDeletes.keySet()) { final Collection<PendingDelete> deletes = pendingDeletes.get(persistentEntity) if (deletes != null && !deletes.isEmpty()) { List<WriteModel<Document>> entityWrites = getWriteModelsForEntity(persistentEntity, writeModels) List<Object> nativeKeys = new ArrayList<>() - for (PendingDelete delete : deletes) { + for (PendingDelete delete in deletes) { delete.run() if (delete.isVetoed()) { @@ -213,7 +213,7 @@ class MongoSession extends AbstractMongoSession { } } - for (PersistentEntity persistentEntity : writeModels.keySet()) { + for (PersistentEntity persistentEntity in writeModels.keySet()) { com.mongodb.client.MongoCollection<Document> collection = getCollection(persistentEntity) final WriteConcern wc = getWriteConcern() if (wc != null) { @@ -240,7 +240,7 @@ class MongoSession extends AbstractMongoSession { } } - for (Runnable postFlushOperation : postFlushOperations) { + for (Runnable postFlushOperation in postFlushOperations) { postFlushOperation.run() } } finally { @@ -255,13 +255,13 @@ class MongoSession extends AbstractMongoSession { protected Document createSetAndUnsetDoc(Document updateDoc) { final Set<String> keys = updateDoc.keySet() final Document unsets = new Document() - for (String key : keys) { + for (String key in keys) { final Object v = updateDoc.get(key) if (v == null) { unsets.put(key, '') } } - for (String key : unsets.keySet()) { + for (String key in unsets.keySet()) { updateDoc.remove(key) } Document setAndUnsetDoc = new Document(MONGO_SET_OPERATOR, updateDoc) @@ -296,14 +296,14 @@ class MongoSession extends AbstractMongoSession { void delete(Iterable objects) { final Map<PersistentEntity, List> toDelete = getDeleteMap(objects) - for (PersistentEntity persistentEntity : toDelete.keySet()) { + for (PersistentEntity persistentEntity in toDelete.keySet()) { final PersistentEntity entity = persistentEntity final List objectsToDelete = toDelete.get(entity) final MongoQuery query = new MongoQuery(this, entity) // Filters on the literal "_id" field, not the logical identity name, so the // criterion preprocessing in MongoQuery does not recognise it as an id. final List<Object> deleteKeys = new ArrayList<Object>() - for (Object k : objectsToDelete) { + for (Object k in objectsToDelete) { deleteKeys.add(MongoIdCoercion.coerceIdToStoredType(k, entity)) } query.in(MongoEntityPersister.MONGO_ID_FIELD, deleteKeys) @@ -312,7 +312,7 @@ class MongoSession extends AbstractMongoSession { addPendingDelete(new PendingDeleteAdapter<Object, Object>(entity, mongoQuery, null) { @Override void run() { - for (Object o : objectsToDelete) { + for (Object o in objectsToDelete) { if (!persister.cancelDelete(entity, createEntityAccess(entity, o))) { clear(o) } @@ -324,8 +324,8 @@ class MongoSession extends AbstractMongoSession { protected Map<PersistentEntity, List> getDeleteMap(Iterable objects) { // sort the objects into sets by Persister, in case the objects are of different types. - Map<PersistentEntity, List> toDelete = new HashMap<>() - for (Object object : objects) { + Map<PersistentEntity, List> toDelete = [:] + for (Object object in objects) { if (object == null) { continue } @@ -335,7 +335,7 @@ class MongoSession extends AbstractMongoSession { } List listForPersister = toDelete.get(p) if (listForPersister == null) { - listForPersister = new ArrayList() + listForPersister = [] toDelete.put(p, listForPersister) } Serializable id = getObjectIdentifier(object) @@ -513,7 +513,7 @@ class MongoSession extends AbstractMongoSession { MongoQuery mongoQuery = new MongoQuery(this, entity) List<Query.Criterion> criteriaList = criteria.getCriteria() - for (Query.Criterion c : criteriaList) { + for (Query.Criterion c in criteriaList) { mongoQuery.add(c) } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoTransaction.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoTransaction.groovy index bb7237fdd6..2b06b95ae6 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoTransaction.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/MongoTransaction.groovy @@ -104,13 +104,13 @@ class MongoTransaction implements Transaction<ClientSession> { try { clientSession.abortTransaction() } catch (RuntimeException e) { - LOG.debug('Error aborting transaction after failed commit: {}', e.getMessage(), e) + LOG.debug('Error aborting transaction after failed commit: {}', e.message, e) } } try { session.clear() } catch (RuntimeException e) { - LOG.debug('Error clearing session after failed transaction commit: {}', e.getMessage(), e) + LOG.debug('Error clearing session after failed transaction commit: {}', e.message, e) } } close() diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/config/MongoMappingContext.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/config/MongoMappingContext.groovy index 81a14fa088..9f9b6b18d5 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/config/MongoMappingContext.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/config/MongoMappingContext.groovy @@ -126,7 +126,7 @@ class MongoMappingContext extends DocumentMappingContext { ]) @PackageScope CodecRegistry codecRegistry - @PackageScope Map<Class, Boolean> hasCodecCache = new HashMap<>() + @PackageScope Map<Class, Boolean> hasCodecCache = [:] /** * Storage type applied to {@code String id} domains that declare no explicit @@ -268,7 +268,7 @@ class MongoMappingContext extends DocumentMappingContext { codecs.add(new PeriodCodec()) codecs.add(new ZonedDateTimeCodec()) - for (Codec codec : codecList) { + for (Codec codec in codecList) { codecs.add(codec) } @@ -341,7 +341,7 @@ class MongoMappingContext extends DocumentMappingContext { } }) - for (Converter converter : CodecExtensions.getBsonConverters()) { + for (Converter converter in CodecExtensions.getBsonConverters()) { converterRegistry.addConverter(converter) } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/connections/RestartableMongoClient.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/connections/RestartableMongoClient.groovy index eb2fe066fb..e606b8e379 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/connections/RestartableMongoClient.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/connections/RestartableMongoClient.groovy @@ -207,7 +207,7 @@ final class RestartableMongoClient implements MongoClient { @Override ClusterDescription getClusterDescription() { - return driverClient().getClusterDescription() + return driverClient().clusterDescription } @Override @@ -217,22 +217,22 @@ final class RestartableMongoClient implements MongoClient { @Override CodecRegistry getCodecRegistry() { - return driverClient().getCodecRegistry() + return driverClient().codecRegistry } @Override ReadPreference getReadPreference() { - return driverClient().getReadPreference() + return driverClient().readPreference } @Override WriteConcern getWriteConcern() { - return driverClient().getWriteConcern() + return driverClient().writeConcern } @Override ReadConcern getReadConcern() { - return driverClient().getReadConcern() + return driverClient().readConcern } @Override diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/AbstractMongoObectEntityPersister.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/AbstractMongoObectEntityPersister.groovy index 8ce92e21fe..62316e2e90 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/AbstractMongoObectEntityPersister.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/AbstractMongoObectEntityPersister.groovy @@ -125,7 +125,7 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer T cached = (T) ((SessionImplementor<?>) getSession()).getCachedEntry( entity, (Serializable) entityAccess.getIdentifier(), true) - return !dbo.equals(cached) + return dbo != cached } @Override @@ -194,9 +194,9 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer @Override protected void setEmbeddedCollectionKeys(Association association, EntityAccess embeddedEntityAccess, T embeddedEntry, List<Serializable> keys) { - List dbRefs = new ArrayList() + List dbRefs = [] boolean reference = isReference(association) - for (Object foreignKey : keys) { + for (Object foreignKey in keys) { // Same as formulateDatabaseReference: the embedded collection's references must // carry the target's stored _id type. Object coerced = MongoIdCoercion.coerceIdToStoredType(foreignKey, association.getAssociatedEntity()) @@ -225,10 +225,10 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer final ValueRetrievalStrategy<T> valueRetrievalStrategy = getValueRetrievalStrategy() Object entry = valueRetrievalStrategy.getValue(nativeEntry, getPropertyKey(association)) - List keys = new ArrayList() + List keys = [] if (entry instanceof List) { List entries = (List) entry - for (Object o : entries) { + for (Object o in entries) { if (o instanceof DBRef) { DBRef dbref = (DBRef) o keys.add(dbref.getId()) @@ -249,7 +249,7 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer PersistentProperty identity = persistentEntity.getIdentity() if (keys instanceof List) { - List actualKeys = new ArrayList() + List actualKeys = [] Iterator iterator = keys.iterator() while (iterator.hasNext()) { Object key = iterator.next() @@ -259,7 +259,7 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer query.in(identity.getName(), actualKeys) } else { List<Serializable> keyList = new ArrayList<>() - for (Serializable key : keys) { + for (Serializable key in keys) { keyList.add(key) } query.in(identity.getName(), keyList) @@ -267,8 +267,8 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer List<Object> entityResults = new ArrayList<>() Iterator<Serializable> keyIterator = keys.iterator() - Map<Serializable, Object> resultMap = new HashMap<>() - for (Object o : query.list()) { + Map<Serializable, Object> resultMap = [:] + for (Object o in query.list()) { Object result = o if (isEmbeddedEntry(result)) { final ValueRetrievalStrategy<T> valueRetrievalStrategy = getValueRetrievalStrategy() @@ -379,9 +379,9 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer protected void setManyToMany(PersistentEntity persistentEntity, Object obj, T nativeEntry, ManyToMany manyToMany, Collection associatedObjects, Map<Association, List<Serializable>> toManyKeys) { - List ids = new ArrayList() + List ids = [] if (associatedObjects != null) { - for (Object o : associatedObjects) { + for (Object o in associatedObjects) { if (o == null) { ids.add(null) } else { @@ -442,8 +442,8 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer // if the association is a unidirectional one-to-many we store the keys // embedded in the owning entity, otherwise we use a foreign key if (!association.isBidirectional()) { - List dbRefs = new ArrayList() - for (Object foreignKey : foreignKeys) { + List dbRefs = [] + for (Object foreignKey in foreignKeys) { // Same as formulateDatabaseReference: the stored reference must carry the // target's _id type, or raw joins and DBRef consumers cannot match it. Object coerced = MongoIdCoercion.coerceIdToStoredType( @@ -502,8 +502,8 @@ abstract class AbstractMongoObectEntityPersister<T> extends NativeEntryEntityPer } private List extractIdsFromDbRefs(List indexedList) { - List resolvedDbRefs = new ArrayList() - for (Object indexedAssociation : indexedList) { + List resolvedDbRefs = [] + for (Object indexedAssociation in indexedList) { resolvedDbRefs.add(((DBRef) indexedAssociation).getId()) } return resolvedDbRefs diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/MongoEntityPersister.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/MongoEntityPersister.groovy index 870e75bf06..d0ad8a1211 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/MongoEntityPersister.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/engine/MongoEntityPersister.groovy @@ -87,7 +87,7 @@ class MongoEntityPersister extends AbstractMongoObectEntityPersister<Document> { if (embeddedInstances instanceof Document) { Map instances = new HashMap() Document embedded = (Document) embeddedInstances - for (String key : embedded.keySet()) { + for (String key in embedded.keySet()) { Object o = embedded.get(key) if (o instanceof Document) { Document nativeEntry = (Document) o @@ -105,7 +105,7 @@ class MongoEntityPersister extends AbstractMongoObectEntityPersister<Document> { if (embeddedInstances instanceof Collection) { Collection coll = (Collection) embeddedInstances - for (Object dbo : coll) { + for (Object dbo in coll) { if (dbo instanceof Document) { Document nativeEntry = (Document) dbo Object instance = @@ -240,21 +240,21 @@ class MongoEntityPersister extends AbstractMongoObectEntityPersister<Document> { } else if (value.getClass().isArray()) { Object[] array = (Object[]) value List<Object> nativeColl = new ArrayList<Object>(array.length) - for (Object item : array) { + for (Object item in array) { nativeColl.add(getSimpleNativePropertyValue(item, mappingContext)) } nativeValue = nativeColl } else if (value instanceof Collection) { Collection existingColl = (Collection) value List<Object> nativeColl = new ArrayList<Object>(existingColl.size()) - for (Object item : existingColl) { + for (Object item in existingColl) { nativeColl.add(getSimpleNativePropertyValue(item, mappingContext)) } nativeValue = nativeColl } else if (value instanceof Map) { Map<String, Object> existingMap = (Map) value - Map<String, Object> newMap = new LinkedHashMap<>() - for (Map.Entry<String, Object> entry : existingMap.entrySet()) { + Map<String, Object> newMap = [:] + for (Map.Entry<String, Object> entry in existingMap.entrySet()) { newMap.put(entry.getKey(), getSimpleNativePropertyValue(entry.getValue(), mappingContext)) } nativeValue = newMap @@ -301,18 +301,18 @@ class MongoEntityPersister extends AbstractMongoObectEntityPersister<Document> { } private Document removeNullEntries(Document nativeEntry) { - for (String key : new HashSet<String>(nativeEntry.keySet())) { + for (String key in new HashSet<String>(nativeEntry.keySet())) { Object o = nativeEntry.get(key) if (o == null) { nativeEntry.remove(key) } else if (o instanceof Object[]) { - for (Object o2 : (Object[]) o) { + for (Object o2 in (Object[]) o) { if (o2 instanceof Document) { removeNullEntries((Document) o2) } } } else if (o instanceof List) { - for (Object o2 : (List) o) { + for (Object o2 in (List) o) { if (o2 instanceof Document) { removeNullEntries((Document) o2) } diff --git a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/query/MongoQuery.groovy b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/query/MongoQuery.groovy index 7cb8782721..df51843b9c 100644 --- a/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/query/MongoQuery.groovy +++ b/grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/query/MongoQuery.groovy @@ -191,7 +191,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { PersistentEntity idTarget = resolveIdCriterionTarget(entity, inCriterion.getProperty()) if (idTarget != null && MongoIdCoercion.resolveStoredAs(idTarget) != null) { List<Object> coerced = new ArrayList<Object>(values.size()) - for (Object v : values) { + for (Object v in values) { coerced.add(MongoIdCoercion.coerceIdToStoredType(v, idTarget)) } values = coerced @@ -552,7 +552,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { List<Document> aggregationPipeline = aggregatePipeline.getAggregationPipeline() boolean singleResult = aggregatePipeline.isSingleResult() List<ProjectedProperty> projectedKeys = aggregatePipeline.getProjectedKeys() - List projectedResults = new ArrayList() + List projectedResults = [] AggregateIterable<Document> aggregatedResults = mongoSession.aggregate(collection, aggregationPipeline) aggregatedResults = (AggregateIterable<Document>) setHint(aggregatedResults) @@ -560,7 +560,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { if (singleResult && aggregateCursor.hasNext()) { Document dbo = aggregateCursor.next() - for (ProjectedProperty projectedProperty : projectedKeys) { + for (ProjectedProperty projectedProperty in projectedKeys) { Object value = dbo.get(projectedProperty.projectionKey) PersistentProperty property = projectedProperty.property if (value != null) { @@ -650,7 +650,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { if (!orderBy.isEmpty()) { Document orderObject = new Document() - for (Order order : orderBy) { + for (Order order in orderBy) { String property = order.getProperty() property = getPropertyName(entity, property) orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1) @@ -686,9 +686,9 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { Collection<PersistentEntity> childEntities = entity.getMappingContext().getChildEntities(entity) if (childEntities.size() > 0) { HashMap classValue = new HashMap() - ArrayList classes = new ArrayList() + ArrayList classes = [] classes.add(entity.getDiscriminator()) - for (PersistentEntity childEntity : childEntities) { + for (PersistentEntity childEntity in childEntities) { classes.add(childEntity.getDiscriminator()) } classValue.put(MONGO_IN_OPERATOR, classes) @@ -737,14 +737,14 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { // so that property names can't clash (e.g. for an $and containing two $ors) if (criteria.getCriteria().size() > 1) { if (criteria instanceof Disjunction) { - subList = new ArrayList() + subList = [] query.put(OR_OPERATOR, subList) } else if (criteria instanceof Conjunction) { - subList = new ArrayList() + subList = [] query.put(AND_OPERATOR, subList) } } - for (Criterion criterion : criteria.getCriteria()) { + for (Criterion criterion in criteria.getCriteria()) { final QueryHandler queryHandler = queryHandlers.get(criterion.getClass()) if (queryHandler != null) { Document dbo = query @@ -821,9 +821,9 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { private static PersistentEntity resolveIdCriterionTarget(PersistentEntity entity, String propertyName) { PersistentProperty property = entity.getPropertyByName(propertyName) if (property instanceof ToOne) { - return ((ToOne) property).getAssociatedEntity() + return property.getAssociatedEntity() } - if (entity.getIdentity() != null && entity.getIdentity().getName().equals(propertyName)) { + if (entity.getIdentity() != null && entity.getIdentity().getName() == propertyName) { return entity } return null @@ -837,7 +837,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { */ @PackageScope static void prefixEmbeddedQuery(String prefix, Document source, Document target) { - for (String key : source.keySet()) { + for (String key in source.keySet()) { Object value = source.get(key) if (key.charAt(0) == ('$' as char)) { if (!(value instanceof List)) { @@ -848,7 +848,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { '] is not supported inside an embedded association query') } List<Object> rewritten = new ArrayList<>() - for (Object element : (List) value) { + for (Object element in (List) value) { if (element instanceof Document) { Document rewrittenElement = new Document() prefixEmbeddedQuery(prefix, (Document) element, rewrittenElement) @@ -879,7 +879,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { } private List wrapObjectResultInList(Object object) { - List result = new ArrayList() + List result = [] result.add(object) return result } @@ -1122,10 +1122,6 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { this.maxDistance = Distance.valueOf(maxDistance.doubleValue()) } - void setMaxDistance(Distance maxDistance) { - this.maxDistance = maxDistance - } - } /** @@ -1250,7 +1246,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { @PackageScope MongoCursor cursor private List<ProjectedProperty> projectedProperties - private List initializedObjects = new ArrayList() + private List initializedObjects = [] private int internalIndex = 0 @PackageScope boolean initialized = false private boolean containsAssociations = false @@ -1260,7 +1256,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { this.cursor = cursor this.projectedProperties = projectedProperties this.session = session - for (ProjectedProperty projectedProperty : projectedProperties) { + for (ProjectedProperty projectedProperty in projectedProperties) { if (projectedProperty.property instanceof Association) { this.containsAssociations = true break @@ -1335,11 +1331,11 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { handleNoResults() } else if (property instanceof Embedded) { Embedded embedded = (Embedded) property - List embeddedList = new ArrayList() + List embeddedList = [] CodecRegistry codecRegistry = session.getDatastore().getCodecRegistry() PersistentEntityCodec codec = new PersistentEntityCodec(codecRegistry, embedded.getAssociatedEntity()) - for (Serializable embeddedDoc : identifiers) { + for (Serializable embeddedDoc in identifiers) { if (embeddedDoc instanceof Document) { Document documentObject = (Document) embeddedDoc @@ -1363,7 +1359,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { Document dbo = (Document) cursor.next() List<Object> projectedResult = new ArrayList<>() int index = 0 - for (ProjectedProperty projectedProperty : projectedProperties) { + for (ProjectedProperty projectedProperty in projectedProperties) { PersistentProperty property = projectedProperty.property Object value = getProjectedValue(dbo, projectedProperty.projectionKey) if (property instanceof Association) { @@ -1385,18 +1381,18 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { return } - Map<Integer, List> finalResults = new HashMap<>() - for (Integer index : associationMap.keySet()) { + Map<Integer, List> finalResults = [:] + for (Integer index in associationMap.keySet()) { Map<Class, List<Serializable>> associatedEntityIdentifiers = associationMap.get(index) - for (Class associationClass : associatedEntityIdentifiers.keySet()) { + for (Class associationClass in associatedEntityIdentifiers.keySet()) { List<Serializable> identifiers = associatedEntityIdentifiers.get(associationClass) finalResults.put(index, session.retrieveAll(associationClass, identifiers)) } } - for (Object initializedObject : initializedObjects) { + for (Object initializedObject in initializedObjects) { List projected = (List) initializedObject - for (Integer index : finalResults.keySet()) { + for (Integer index in finalResults.keySet()) { List resultsByIndex = finalResults.get(index) if (index < resultsByIndex.size()) { projected.set(index, resultsByIndex.get(index)) @@ -1428,9 +1424,9 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { } private Map<Integer, Map<Class, List<Serializable>>> createAssociationMap() { - Map<Integer, Map<Class, List<Serializable>>> associationMap = new HashMap<>() + Map<Integer, Map<Class, List<Serializable>>> associationMap = [:] associationMap = associationMap.withDefault { Object o -> - Map<Class, List<Serializable>> subMap = new HashMap<>() + Map<Class, List<Serializable>> subMap = [:] subMap = subMap.withDefault { Object k -> return new ArrayList<Serializable>() } @@ -1478,7 +1474,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { Object addInitializedObject(Document dbo) { if (projectedProperties.size() > 1) { List<Object> projected = new ArrayList<>() - for (ProjectedProperty projectedProperty : projectedProperties) { + for (ProjectedProperty projectedProperty in projectedProperties) { Object value value = getProjectedValue(dbo, projectedProperty.projectionKey) projected.add(value) @@ -1661,7 +1657,7 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { groupByObject.put(MongoEntityPersister.MONGO_ID_FIELD, 0) Document additionalGroupBy = null - for (Projection projection : projectionList) { + for (Projection projection in projectionList) { ProjectionHandler projectionHandler = resolveProjectProjectionHandlers().get(projection.getClass()) ProjectedProperty projectedProperty = new ProjectedProperty() projectedProperty.projection = projection @@ -1711,10 +1707,10 @@ class MongoQuery extends BsonQuery implements QueryArgumentsAware { List<Order> orderBy = mongoQuery.getOrderBy() if (!orderBy.isEmpty()) { Document sortBy = new Document() - for (Order order : orderBy) { + for (Order order in orderBy) { String prop = order.getProperty() String sortKey = prop - for (ProjectedProperty pp : projectedKeys) { + for (ProjectedProperty pp in projectedKeys) { if (pp.property != null && pp.property.getName() == prop) { sortKey = pp.projectionKey if (sortKey.startsWith('id.')) { diff --git a/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoInitializer.groovy b/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoInitializer.groovy index 99ac8e4b69..f829f9385f 100644 --- a/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoInitializer.groovy +++ b/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoInitializer.groovy @@ -190,7 +190,7 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur */ @PackageScope static List<EmbeddedMongoBackend> defaultBackends(ClassLoader classLoader) { - List<EmbeddedMongoBackend> backends = new ArrayList<>() + List<EmbeddedMongoBackend> backends = [] if (ClassUtils.isPresent(FLAPDOODLE_MONGOD_CLASS, classLoader)) { backends.add(new FlapdoodleMongoBackend()) } @@ -266,8 +266,8 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur url = start(backend, settings, database) } - Map<String, Object> published = new HashMap<>() - for (String propertyName : propertyNames) { + Map<String, Object> published = [:] + for (String propertyName in propertyNames) { published.put(propertyName, url) } environment.getPropertySources().addFirst(new MapPropertySource(PROPERTY_SOURCE_NAME, published)) @@ -381,7 +381,7 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur private EmbeddedMongoBackend selectBackend(ConfigurableEnvironment environment) { String requested = environment.getProperty(BACKEND) if (requested != null && !requested.isEmpty()) { - for (EmbeddedMongoBackend backend : this.backends) { + for (EmbeddedMongoBackend backend in this.backends) { if (backend.getName() == requested) { if (!backend.isAvailable()) { throw new IllegalStateException(BACKEND + '=' + requested + @@ -401,7 +401,7 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur '.') } - for (EmbeddedMongoBackend backend : this.backends) { + for (EmbeddedMongoBackend backend in this.backends) { if (backend.isAvailable()) { return backend } @@ -413,8 +413,8 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur } private List<String> availableNames() { - List<String> names = new ArrayList<>() - for (EmbeddedMongoBackend backend : this.backends) { + List<String> names = [] + for (EmbeddedMongoBackend backend in this.backends) { if (backend.isAvailable()) { names.add(backend.getName()) } @@ -423,8 +423,8 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur } private Set<String> propertyNames(ConfigurableEnvironment environment) { - Set<String> propertyNames = new LinkedHashSet<>() - for (String propertyName : environment.getProperty(PROPERTY_NAMES, DEFAULT_PROPERTY_NAME).split(',')) { + Set<String> propertyNames = [] as Set + for (String propertyName in environment.getProperty(PROPERTY_NAMES, DEFAULT_PROPERTY_NAME).split(',')) { String trimmed = propertyName.trim() if (!trimmed.isEmpty()) { propertyNames.add(trimmed) @@ -444,7 +444,7 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur * them rather than by which happened to be looked at first.</p> */ private Matcher firstAskingForEmbedded(ConfigurableEnvironment environment, Set<String> propertyNames) { - for (String propertyName : propertyNames) { + for (String propertyName in propertyNames) { String url = environment.getProperty(propertyName) if (url != null) { Matcher matcher = EMBEDDED_URL.matcher(url.trim()) @@ -486,7 +486,7 @@ class EmbeddedMongoInitializer implements ApplicationContextInitializer<Configur private static void stopEverythingAtExit() { if (SHUTDOWN_HOOK_ADDED.compareAndSet(false, true)) { Runtime.getRuntime().addShutdownHook(new Thread({ -> - for (StartedServer started : STARTED.values()) { + for (StartedServer started in STARTED.values()) { started.running().stop() } } as Runnable)) diff --git a/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/ReplicaSetInitiator.groovy b/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/ReplicaSetInitiator.groovy index 2ed50aefc0..930cf9249a 100644 --- a/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/ReplicaSetInitiator.groovy +++ b/grails-data-mongodb/embedded/src/main/groovy/org/grails/datastore/gorm/mongodb/embedded/ReplicaSetInitiator.groovy @@ -75,7 +75,7 @@ final class ReplicaSetInitiator { try { client.getDatabase('admin').runCommand(new Document('replSetInitiate', configuration)) } catch (MongoCommandException ex) { - if (ex.getErrorCode() != ALREADY_INITIALIZED) { + if (ex.errorCode != ALREADY_INITIALIZED) { throw new IllegalStateException('Could not initiate the replica set ' + replicaSet + ' on the embedded MongoDB at ' + address, ex) } @@ -108,7 +108,7 @@ final class ReplicaSetInitiator { private static boolean isPrimary(MongoClient client) { try { Document hello = client.getDatabase('admin').runCommand(new Document('hello', 1)) - return Boolean.TRUE.equals(hello.getBoolean('isWritablePrimary')) + return Boolean.TRUE == hello.getBoolean('isWritablePrimary') } catch (RuntimeException ex) { // The server closes connections as it transitions, so a failure here means "not yet". return false diff --git a/grails-data-mongodb/spring-data/src/main/groovy/org/springframework/data/mongodb/GormSpringDataSessionSupport.groovy b/grails-data-mongodb/spring-data/src/main/groovy/org/springframework/data/mongodb/GormSpringDataSessionSupport.groovy index e459f1d65a..655ad28713 100644 --- a/grails-data-mongodb/spring-data/src/main/groovy/org/springframework/data/mongodb/GormSpringDataSessionSupport.groovy +++ b/grails-data-mongodb/spring-data/src/main/groovy/org/springframework/data/mongodb/GormSpringDataSessionSupport.groovy @@ -58,7 +58,7 @@ final class GormSpringDataSessionSupport { static void bindClientSession(MongoDatabaseFactory databaseFactory, ClientSession clientSession) { if (!TransactionSynchronizationManager.hasResource(databaseFactory)) { MongoResourceHolder holder = new MongoResourceHolder(clientSession, databaseFactory) - holder.setSynchronizedWithTransaction(true) + holder.synchronizedWithTransaction = true TransactionSynchronizationManager.bindResource(databaseFactory, holder) } }
