Skip to content

Override Iterator#forEachRemaining in MongoCursor #1161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 27, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ import org.mockito.kotlin.whenever
class MongoCursorTest {
@Test
fun shouldHaveTheSameMethods() {
val jMongoCursorFunctions = JMongoCursor::class.declaredFunctions.map { it.name }.toSet()
val jMongoCursorFunctions =
JMongoCursor::class
.declaredFunctions
.map { it.name }
// exclude since this method has a default implementation in MongoCursor interface
.filterNot { it == "forEachRemaining" }
.toSet()
val kMongoCursorFunctions =
MongoCursorImpl::class.declaredFunctions.map { it.name }.toSet() +
MongoCursorImpl::class
Expand Down
10 changes: 10 additions & 0 deletions driver-sync/src/main/com/mongodb/client/MongoCursor.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import java.io.Closeable;
import java.util.Iterator;
import java.util.function.Consumer;

/**
* The Mongo Cursor interface implementing the iterator protocol.
Expand Down Expand Up @@ -96,4 +97,13 @@ public interface MongoCursor<TResult> extends Iterator<TResult>, Closeable {
* @return ServerAddress
*/
ServerAddress getServerAddress();

@Override
default void forEachRemaining(final Consumer<? super TResult> action) {
try {
Iterator.super.forEachRemaining(action);
} finally {
close();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,23 @@ class MongoBatchCursorAdapterSpecification extends Specification {
then:
cursor.available() == 0
}

def 'should close cursor in forEachRemaining if there is an exception'() {
given:
def firstBatch = [new Document('x', 1)]

def batchCursor = Mock(BatchCursor)
batchCursor.hasNext() >>> [true, true]
batchCursor.next() >>> [firstBatch]
def cursor = new MongoBatchCursorAdapter(batchCursor)

when:
cursor.forEachRemaining {
throw new IllegalStateException('test')
}

then:
thrown(IllegalStateException)
1 * batchCursor.close()
}
}