From 97221627bbafb506b977b3b709b50fdc178064fe Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 14 Sep 2023 14:22:18 -0400 Subject: [PATCH 01/28] Bump to 5.0.0-SNAPSHOT --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 5d75c92139b..c92919238b4 100644 --- a/build.gradle +++ b/build.gradle @@ -74,7 +74,7 @@ configure(coreProjects) { apply plugin: 'idea' group = 'org.mongodb' - version = '4.12.0-SNAPSHOT' + version = '5.0.0-SNAPSHOT' repositories { mavenLocal() From 9cb26b57a8aa15f67a203f2658b350f8032aa8be Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Tue, 12 Sep 2023 16:16:01 -0400 Subject: [PATCH 02/28] Remove Stream-related types from API MongoClientSettings#getStreamFactoryFactory() MongoClientSettings.Builder#streamFactoryFactory(StreamFactoryFactory) AsynchronousSocketChannelStreamFactory AsynchronousSocketChannelStreamFactoryFactory BufferProvider SocketStreamFactory Stream StreamFactory StreamFactoryFactory TlsChannelStreamFactoryFactory NettyStreamFactory NettyStreamFactoryFactory JAVA-5161 --- .../main/com/mongodb/MongoClientSettings.java | 41 +------------- .../com/mongodb/connection/ProxySettings.java | 3 +- .../com/mongodb/connection/SslSettings.java | 6 +-- .../connection/netty/package-info.java | 23 -------- .../connection/AsynchronousChannelStream.java | 2 - ...synchronousSocketChannelStreamFactory.java | 16 ++---- ...nousSocketChannelStreamFactoryFactory.java | 8 +-- .../connection/BufferProvider.java | 6 +-- .../connection/ByteBufferBsonOutput.java | 2 - .../connection/DefaultClusterFactory.java | 2 - .../DefaultClusterableServerFactory.java | 2 - .../connection/InternalConnection.java | 2 - .../connection/InternalStreamConnection.java | 3 -- .../InternalStreamConnectionFactory.java | 2 - .../LoadBalancedClusterableServerFactory.java | 2 - .../connection/PowerOfTwoBufferPool.java | 2 - .../internal/connection/SocketStream.java | 3 -- .../connection/SocketStreamFactory.java | 29 ++-------- .../{ => internal}/connection/Stream.java | 11 ++-- .../connection/StreamFactory.java | 6 +-- .../connection/StreamFactoryFactory.java | 9 ++-- .../connection/StreamFactoryHelper.java | 8 +-- .../TlsChannelStreamFactoryFactory.java | 38 +++---------- .../connection/UnixSocketChannelStream.java | 2 - .../connection/netty/NettyStream.java | 6 +-- .../connection/netty/NettyStreamFactory.java | 17 ++---- .../netty/NettyStreamFactoryFactory.java | 17 ++---- .../com/mongodb/ClusterFixture.java | 34 ++++++------ .../netty/NettyStreamSpecification.groovy | 1 + ...yncSocketChannelStreamSpecification.groovy | 1 - .../AsyncStreamTimeoutsSpecification.groovy | 3 +- .../AwsAuthenticationSpecification.groovy | 2 - .../CommandHelperSpecification.groovy | 2 +- .../GSSAPIAuthenticationSpecification.groovy | 3 +- .../GSSAPIAuthenticatorSpecification.groovy | 1 - .../PlainAuthenticationSpecification.groovy | 3 +- .../connection/PlainAuthenticatorTest.java | 3 -- .../ServerMonitorSpecification.groovy | 1 - .../connection/SingleServerClusterTest.java | 1 - .../StreamSocketAddressSpecification.groovy | 1 - .../MongoClientSettingsSpecification.groovy | 14 +---- .../NettyTransportSettingsTest.java | 11 ++-- .../AbstractConnectionPoolTest.java | 1 - ...elStreamFactoryFactorySpecification.groovy | 8 +-- .../connection/ByteBufSpecification.groovy | 2 +- .../connection/ConnectionPoolAsyncTest.java | 4 -- .../connection/ConnectionPoolTest.java | 3 -- ...ternalStreamConnectionSpecification.groovy | 2 - .../connection/SimpleBufferProvider.java | 2 - .../connection/StreamFactoryHelperTest.java | 15 +----- .../connection/TestInternalConnection.java | 2 - .../netty/ByteBufSpecification.groovy | 4 +- ...tyStreamFactoryFactorySpecification.groovy | 2 +- .../NettyStreamFactorySpecification.groovy | 2 +- .../main/com/mongodb/DBDecoderAdapter.java | 3 +- .../reactivestreams/client/MongoClients.java | 10 ++-- .../internal/crypt/KeyManagementService.java | 7 ++- .../reactivestreams/client/Fixture.java | 14 ----- .../client/MainTransactionsTest.java | 7 ++- ...ettySettingsSmokeTestSpecification.groovy} | 11 ++-- ...ousSocketChannelStreamFactoryFactory.scala | 49 ----------------- .../NettyStreamFactoryFactory.scala | 42 --------------- .../mongodb/scala/connection/package.scala | 53 ------------------- .../scala/ApiAliasAndCompanionSpec.scala | 20 +------ .../scala/connection/ConnectionSpec.scala | 13 +---- .../client/internal/MongoClientImpl.java | 7 ++- .../mongodb/client/AbstractUnifiedTest.java | 10 ++-- 67 files changed, 115 insertions(+), 527 deletions(-) delete mode 100644 driver-core/src/main/com/mongodb/connection/netty/package-info.java rename driver-core/src/main/com/mongodb/{ => internal}/connection/AsynchronousSocketChannelStreamFactory.java (81%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/AsynchronousSocketChannelStreamFactoryFactory.java (94%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/BufferProvider.java (89%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/SocketStreamFactory.java (70%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/Stream.java (95%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/StreamFactory.java (88%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/StreamFactoryFactory.java (88%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/TlsChannelStreamFactoryFactory.java (92%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/netty/NettyStream.java (99%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/netty/NettyStreamFactory.java (94%) rename driver-core/src/main/com/mongodb/{ => internal}/connection/netty/NettyStreamFactoryFactory.java (94%) rename driver-core/src/test/unit/com/mongodb/{ => internal}/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy (88%) rename driver-core/src/test/unit/com/mongodb/{ => internal}/connection/netty/ByteBufSpecification.groovy (97%) rename driver-core/src/test/unit/com/mongodb/{ => internal}/connection/netty/NettyStreamFactoryFactorySpecification.groovy (98%) rename driver-core/src/test/unit/com/mongodb/{ => internal}/connection/netty/NettyStreamFactorySpecification.groovy (98%) rename driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/{NettyStreamFactoryFactorySmokeTestSpecification.groovy => NettySettingsSmokeTestSpecification.groovy} (83%) delete mode 100644 driver-scala/src/main/scala/org/mongodb/scala/connection/AsynchronousSocketChannelStreamFactoryFactory.scala delete mode 100644 driver-scala/src/main/scala/org/mongodb/scala/connection/NettyStreamFactoryFactory.scala diff --git a/driver-core/src/main/com/mongodb/MongoClientSettings.java b/driver-core/src/main/com/mongodb/MongoClientSettings.java index 579a030cb75..74f813a3914 100644 --- a/driver-core/src/main/com/mongodb/MongoClientSettings.java +++ b/driver-core/src/main/com/mongodb/MongoClientSettings.java @@ -26,7 +26,6 @@ import com.mongodb.connection.ServerSettings; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.StreamFactoryFactory; import com.mongodb.connection.TransportSettings; import com.mongodb.event.CommandListener; import com.mongodb.lang.Nullable; @@ -63,7 +62,6 @@ * * @since 3.7 */ -@SuppressWarnings("deprecation") @Immutable public final class MongoClientSettings { private static final CodecRegistry DEFAULT_CODEC_REGISTRY = @@ -92,7 +90,6 @@ public final class MongoClientSettings { private final ReadConcern readConcern; private final MongoCredential credential; private final TransportSettings transportSettings; - private final StreamFactoryFactory streamFactoryFactory; private final List commandListeners; private final CodecRegistry codecRegistry; private final LoggerSettings loggerSettings; @@ -213,7 +210,6 @@ public static final class Builder { private ReadConcern readConcern = ReadConcern.DEFAULT; private CodecRegistry codecRegistry = MongoClientSettings.getDefaultCodecRegistry(); private TransportSettings transportSettings; - private StreamFactoryFactory streamFactoryFactory; private List commandListeners = new ArrayList<>(); private final LoggerSettings.Builder loggerSettingsBuilder = LoggerSettings.builder(); @@ -257,7 +253,6 @@ private Builder(final MongoClientSettings settings) { dnsClient = settings.getDnsClient(); inetAddressResolver = settings.getInetAddressResolver(); transportSettings = settings.getTransportSettings(); - streamFactoryFactory = settings.getStreamFactoryFactory(); autoEncryptionSettings = settings.getAutoEncryptionSettings(); contextProvider = settings.getContextProvider(); loggerSettingsBuilder.applySettings(settings.getLoggerSettings()); @@ -489,27 +484,9 @@ public Builder codecRegistry(final CodecRegistry codecRegistry) { return this; } - /** - * Sets the factory to use to create a {@code StreamFactory}. - * - * @param streamFactoryFactory the stream factory factory - * @return this - * @see #getStreamFactoryFactory() - * @deprecated Prefer {@link #transportSettings(TransportSettings)} - */ - @Deprecated - public Builder streamFactoryFactory(final StreamFactoryFactory streamFactoryFactory) { - this.streamFactoryFactory = notNull("streamFactoryFactory", streamFactoryFactory); - return this; - } - /** * Sets the {@link TransportSettings} to apply. * - *

- * If transport settings are applied, application of {@link #streamFactoryFactory} is ignored. - *

- * * @param transportSettings the transport settings * @return this * @see #getTransportSettings() @@ -789,19 +766,6 @@ public CodecRegistry getCodecRegistry() { return codecRegistry; } - /** - * Gets the factory to use to create a {@code StreamFactory}. - * - * @return the stream factory factory - * @see Builder#streamFactoryFactory(StreamFactoryFactory) - * @deprecated Prefer {@link #getTransportSettings()} - */ - @Deprecated - @Nullable - public StreamFactoryFactory getStreamFactoryFactory() { - return streamFactoryFactory; - } - /** * Gets the settings for the underlying transport implementation * @@ -1017,7 +981,6 @@ public boolean equals(final Object o) { && Objects.equals(readConcern, that.readConcern) && Objects.equals(credential, that.credential) && Objects.equals(transportSettings, that.transportSettings) - && Objects.equals(streamFactoryFactory, that.streamFactoryFactory) && Objects.equals(commandListeners, that.commandListeners) && Objects.equals(codecRegistry, that.codecRegistry) && Objects.equals(loggerSettings, that.loggerSettings) @@ -1040,7 +1003,7 @@ public boolean equals(final Object o) { @Override public int hashCode() { return Objects.hash(readPreference, writeConcern, retryWrites, retryReads, readConcern, credential, transportSettings, - streamFactoryFactory, commandListeners, codecRegistry, loggerSettings, clusterSettings, socketSettings, + commandListeners, codecRegistry, loggerSettings, clusterSettings, socketSettings, heartbeatSocketSettings, connectionPoolSettings, serverSettings, sslSettings, applicationName, compressorList, uuidRepresentation, serverApi, autoEncryptionSettings, heartbeatSocketTimeoutSetExplicitly, heartbeatConnectTimeoutSetExplicitly, dnsClient, inetAddressResolver, contextProvider); @@ -1056,7 +1019,6 @@ public String toString() { + ", readConcern=" + readConcern + ", credential=" + credential + ", transportSettings=" + transportSettings - + ", streamFactoryFactory=" + streamFactoryFactory + ", commandListeners=" + commandListeners + ", codecRegistry=" + codecRegistry + ", loggerSettings=" + loggerSettings @@ -1085,7 +1047,6 @@ private MongoClientSettings(final Builder builder) { readConcern = builder.readConcern; credential = builder.credential; transportSettings = builder.transportSettings; - streamFactoryFactory = builder.streamFactoryFactory; codecRegistry = builder.codecRegistry; commandListeners = builder.commandListeners; applicationName = builder.applicationName; diff --git a/driver-core/src/main/com/mongodb/connection/ProxySettings.java b/driver-core/src/main/com/mongodb/connection/ProxySettings.java index 1a4c793f875..494060c0f93 100644 --- a/driver-core/src/main/com/mongodb/connection/ProxySettings.java +++ b/driver-core/src/main/com/mongodb/connection/ProxySettings.java @@ -19,6 +19,7 @@ import com.mongodb.AutoEncryptionSettings; import com.mongodb.ClientEncryptionSettings; import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; import com.mongodb.annotations.Immutable; import com.mongodb.lang.Nullable; @@ -35,7 +36,7 @@ * This setting is furthermore ignored if: *
    *
  • the communication is via {@linkplain com.mongodb.UnixServerAddress Unix domain socket}.
  • - *
  • a {@link StreamFactoryFactory} is {@linkplain com.mongodb.MongoClientSettings.Builder#streamFactoryFactory(StreamFactoryFactory) + *
  • a {@link TransportSettings} is {@linkplain MongoClientSettings.Builder#transportSettings(TransportSettings)} * configured}.
  • *
* diff --git a/driver-core/src/main/com/mongodb/connection/SslSettings.java b/driver-core/src/main/com/mongodb/connection/SslSettings.java index fd3cb6a050b..58e2937a61b 100644 --- a/driver-core/src/main/com/mongodb/connection/SslSettings.java +++ b/driver-core/src/main/com/mongodb/connection/SslSettings.java @@ -112,10 +112,8 @@ public Builder invalidHostNameAllowed(final boolean invalidHostNameAllowed) { /** * Sets the SSLContext for use when SSL is enabled. * - * @param context the SSLContext to use for connections. Ignored if TLS/SSL is not {@linkplain #enabled(boolean) enabled}, - * or if a {@link StreamFactory} {@linkplain StreamFactoryFactory#create(SocketSettings, SslSettings) created} - * by the {@linkplain com.mongodb.MongoClientSettings.Builder#streamFactoryFactory(StreamFactoryFactory) specified} - * {@link StreamFactoryFactory} does not use {@link SSLContext}. + * @param context the SSLContext to use for connections. Ignored if TLS/SSL is not {@linkplain #enabled(boolean) enabled}, or if + * overridden by {@link NettyTransportSettings#getSslContext()}. * @return this * @since 3.5 */ diff --git a/driver-core/src/main/com/mongodb/connection/netty/package-info.java b/driver-core/src/main/com/mongodb/connection/netty/package-info.java deleted file mode 100644 index 77176c28d37..00000000000 --- a/driver-core/src/main/com/mongodb/connection/netty/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * This package contains netty specific classes - */ -@NonNullApi -package com.mongodb.connection.netty; - -import com.mongodb.lang.NonNullApi; diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java index bb0d5953bfb..dc652dab0d2 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java @@ -23,7 +23,6 @@ import com.mongodb.ServerAddress; import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.SocketSettings; -import com.mongodb.connection.Stream; import com.mongodb.lang.Nullable; import org.bson.ByteBuf; @@ -43,7 +42,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public abstract class AsynchronousChannelStream implements Stream { private final ServerAddress serverAddress; private final SocketSettings settings; diff --git a/driver-core/src/main/com/mongodb/connection/AsynchronousSocketChannelStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java similarity index 81% rename from driver-core/src/main/com/mongodb/connection/AsynchronousSocketChannelStreamFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java index f67c71ac90b..27ea5b70164 100644 --- a/driver-core/src/main/com/mongodb/connection/AsynchronousSocketChannelStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java @@ -14,24 +14,21 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; import com.mongodb.ServerAddress; -import com.mongodb.internal.connection.AsynchronousSocketChannelStream; -import com.mongodb.internal.connection.PowerOfTwoBufferPool; +import com.mongodb.connection.SocketSettings; +import com.mongodb.connection.SslSettings; import com.mongodb.lang.Nullable; import java.nio.channels.AsynchronousChannelGroup; +import static com.mongodb.assertions.Assertions.assertFalse; import static com.mongodb.assertions.Assertions.notNull; /** * Factory to create a Stream that's an AsynchronousSocketChannelStream. Throws an exception if SSL is enabled. - * - * @since 3.0 - * @deprecated There is no replacement for this class. */ -@Deprecated public class AsynchronousSocketChannelStreamFactory implements StreamFactory { private final PowerOfTwoBufferPool bufferProvider = PowerOfTwoBufferPool.DEFAULT; private final SocketSettings settings; @@ -58,10 +55,7 @@ public AsynchronousSocketChannelStreamFactory(final SocketSettings settings, fin */ public AsynchronousSocketChannelStreamFactory(final SocketSettings settings, final SslSettings sslSettings, @Nullable final AsynchronousChannelGroup group) { - if (sslSettings.isEnabled()) { - throw new UnsupportedOperationException("No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use " - + "com.mongodb.connection.TlsChannelStreamFactoryFactory"); - } + assertFalse(sslSettings.isEnabled()); this.settings = notNull("settings", settings); this.group = group; diff --git a/driver-core/src/main/com/mongodb/connection/AsynchronousSocketChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java similarity index 94% rename from driver-core/src/main/com/mongodb/connection/AsynchronousSocketChannelStreamFactoryFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java index 4dc7f437362..107330a844c 100644 --- a/driver-core/src/main/com/mongodb/connection/AsynchronousSocketChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java @@ -14,7 +14,10 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; + +import com.mongodb.connection.SocketSettings; +import com.mongodb.connection.SslSettings; import java.nio.channels.AsynchronousChannelGroup; @@ -22,10 +25,7 @@ * A {@code StreamFactoryFactory} implementation for AsynchronousSocketChannel-based streams. * * @see java.nio.channels.AsynchronousSocketChannel - * @since 3.1 - * @deprecated There is no replacement for this class. */ -@Deprecated public final class AsynchronousSocketChannelStreamFactoryFactory implements StreamFactoryFactory { private final AsynchronousChannelGroup group; diff --git a/driver-core/src/main/com/mongodb/connection/BufferProvider.java b/driver-core/src/main/com/mongodb/internal/connection/BufferProvider.java similarity index 89% rename from driver-core/src/main/com/mongodb/connection/BufferProvider.java rename to driver-core/src/main/com/mongodb/internal/connection/BufferProvider.java index 6a904c4ffd5..6d21322cd1b 100644 --- a/driver-core/src/main/com/mongodb/connection/BufferProvider.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BufferProvider.java @@ -14,18 +14,14 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; import com.mongodb.annotations.ThreadSafe; import org.bson.ByteBuf; /** * A provider of instances of ByteBuf. - * - * @since 3.0 - * @deprecated There is no replacement for this interface. */ -@Deprecated @ThreadSafe public interface BufferProvider { /** diff --git a/driver-core/src/main/com/mongodb/internal/connection/ByteBufferBsonOutput.java b/driver-core/src/main/com/mongodb/internal/connection/ByteBufferBsonOutput.java index 91fee075cf3..5cd2000d879 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ByteBufferBsonOutput.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ByteBufferBsonOutput.java @@ -16,7 +16,6 @@ package com.mongodb.internal.connection; -import com.mongodb.connection.BufferProvider; import org.bson.ByteBuf; import org.bson.io.OutputBuffer; @@ -31,7 +30,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public class ByteBufferBsonOutput extends OutputBuffer { private static final int MAX_SHIFT = 31; diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java index ee6b9449a2b..47b0868e13f 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java @@ -27,7 +27,6 @@ import com.mongodb.connection.ClusterSettings; import com.mongodb.connection.ConnectionPoolSettings; import com.mongodb.connection.ServerSettings; -import com.mongodb.connection.StreamFactory; import com.mongodb.event.ClusterListener; import com.mongodb.event.CommandListener; import com.mongodb.event.ServerListener; @@ -56,7 +55,6 @@ * *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public final class DefaultClusterFactory { private static final Logger LOGGER = Loggers.getLogger("client"); diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java index 9b8ac1399b3..1e27891babc 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java @@ -26,7 +26,6 @@ import com.mongodb.connection.ConnectionPoolSettings; import com.mongodb.connection.ServerId; import com.mongodb.connection.ServerSettings; -import com.mongodb.connection.StreamFactory; import com.mongodb.event.CommandListener; import com.mongodb.event.ServerListener; import com.mongodb.internal.inject.SameObjectProvider; @@ -41,7 +40,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public class DefaultClusterableServerFactory implements ClusterableServerFactory { private final ServerSettings serverSettings; private final ConnectionPoolSettings connectionPoolSettings; diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java index 735c5e25164..c14a816b525 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java @@ -17,7 +17,6 @@ package com.mongodb.internal.connection; import com.mongodb.RequestContext; -import com.mongodb.connection.BufferProvider; import com.mongodb.connection.ConnectionDescription; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.async.SingleResultCallback; @@ -31,7 +30,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public interface InternalConnection extends BufferProvider { int NOT_INITIALIZED_GENERATION = -1; diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index cfeeece6126..d4ea8a7be06 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -39,8 +39,6 @@ import com.mongodb.connection.ServerDescription; import com.mongodb.connection.ServerId; import com.mongodb.connection.ServerType; -import com.mongodb.connection.Stream; -import com.mongodb.connection.StreamFactory; import com.mongodb.event.CommandListener; import com.mongodb.internal.ResourceUtil; import com.mongodb.internal.VisibleForTesting; @@ -94,7 +92,6 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ @NotThreadSafe -@SuppressWarnings("deprecation") public class InternalStreamConnection implements InternalConnection { private static final Set SECURITY_SENSITIVE_COMMANDS = new HashSet<>(asList( diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java index c1b071baaff..a74be77a7d0 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java @@ -22,7 +22,6 @@ import com.mongodb.ServerApi; import com.mongodb.connection.ClusterConnectionMode; import com.mongodb.connection.ServerId; -import com.mongodb.connection.StreamFactory; import com.mongodb.event.CommandListener; import com.mongodb.lang.Nullable; import com.mongodb.spi.dns.InetAddressResolver; @@ -34,7 +33,6 @@ import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.connection.ClientMetadataHelper.createClientMetadataDocument; -@SuppressWarnings("deprecation") class InternalStreamConnectionFactory implements InternalConnectionFactory { private final ClusterConnectionMode clusterConnectionMode; private final boolean isMonitoringConnection; diff --git a/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java b/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java index 5752d41b9b6..418d7842088 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java @@ -27,7 +27,6 @@ import com.mongodb.connection.ConnectionPoolSettings; import com.mongodb.connection.ServerId; import com.mongodb.connection.ServerSettings; -import com.mongodb.connection.StreamFactory; import com.mongodb.event.CommandListener; import com.mongodb.internal.inject.EmptyProvider; import com.mongodb.lang.Nullable; @@ -41,7 +40,6 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ @ThreadSafe -@SuppressWarnings("deprecation") public class LoadBalancedClusterableServerFactory implements ClusterableServerFactory { private final ServerSettings serverSettings; private final ConnectionPoolSettings connectionPoolSettings; diff --git a/driver-core/src/main/com/mongodb/internal/connection/PowerOfTwoBufferPool.java b/driver-core/src/main/com/mongodb/internal/connection/PowerOfTwoBufferPool.java index 365cc7ebff2..15a319157d2 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/PowerOfTwoBufferPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/PowerOfTwoBufferPool.java @@ -16,7 +16,6 @@ package com.mongodb.internal.connection; -import com.mongodb.connection.BufferProvider; import com.mongodb.internal.thread.DaemonThreadFactory; import org.bson.ByteBuf; import org.bson.ByteBufNIO; @@ -34,7 +33,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public class PowerOfTwoBufferPool implements BufferProvider { /** diff --git a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java index 03580cc7c89..0e1824d7f8a 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java @@ -21,11 +21,9 @@ import com.mongodb.MongoSocketReadException; import com.mongodb.ServerAddress; import com.mongodb.connection.AsyncCompletionHandler; -import com.mongodb.connection.BufferProvider; import com.mongodb.connection.ProxySettings; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.Stream; import org.bson.ByteBuf; import javax.net.SocketFactory; @@ -51,7 +49,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public class SocketStream implements Stream { private final ServerAddress address; private final SocketSettings settings; diff --git a/driver-core/src/main/com/mongodb/connection/SocketStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java similarity index 70% rename from driver-core/src/main/com/mongodb/connection/SocketStreamFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java index 4bf1fcfd9da..d50e9c9313a 100644 --- a/driver-core/src/main/com/mongodb/connection/SocketStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java @@ -14,15 +14,13 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; import com.mongodb.MongoClientException; import com.mongodb.ServerAddress; import com.mongodb.UnixServerAddress; -import com.mongodb.internal.connection.PowerOfTwoBufferPool; -import com.mongodb.internal.connection.SocketStream; -import com.mongodb.internal.connection.UnixSocketChannelStream; -import com.mongodb.lang.Nullable; +import com.mongodb.connection.SocketSettings; +import com.mongodb.connection.SslSettings; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; @@ -33,15 +31,10 @@ /** * Factory for creating instances of {@code SocketStream}. - * - * @since 3.0 - * @deprecated There is no replacement for this class. */ -@Deprecated public class SocketStreamFactory implements StreamFactory { private final SocketSettings settings; private final SslSettings sslSettings; - private final SocketFactory socketFactory; private final BufferProvider bufferProvider = PowerOfTwoBufferPool.DEFAULT; /** @@ -51,20 +44,8 @@ public class SocketStreamFactory implements StreamFactory { * @param sslSettings whether SSL is enabled. */ public SocketStreamFactory(final SocketSettings settings, final SslSettings sslSettings) { - this(settings, sslSettings, null); - } - - /** - * Creates a new factory with the given settings for connecting to servers and a factory for creating connections. - * - * @param settings the SocketSettings for connecting to a MongoDB server - * @param sslSettings the SSL for connecting to a MongoDB server - * @param socketFactory a SocketFactory for creating connections to servers. - */ - public SocketStreamFactory(final SocketSettings settings, final SslSettings sslSettings, @Nullable final SocketFactory socketFactory) { this.settings = notNull("settings", settings); this.sslSettings = notNull("sslSettings", sslSettings); - this.socketFactory = socketFactory; } @Override @@ -76,9 +57,7 @@ public Stream create(final ServerAddress serverAddress) { } stream = new UnixSocketChannelStream((UnixServerAddress) serverAddress, settings, sslSettings, bufferProvider); } else { - if (socketFactory != null) { - stream = new SocketStream(serverAddress, settings, sslSettings, socketFactory, bufferProvider); - } else if (sslSettings.isEnabled()) { + if (sslSettings.isEnabled()) { stream = new SocketStream(serverAddress, settings, sslSettings, getSslContext().getSocketFactory(), bufferProvider); } else { stream = new SocketStream(serverAddress, settings, sslSettings, SocketFactory.getDefault(), bufferProvider); diff --git a/driver-core/src/main/com/mongodb/connection/Stream.java b/driver-core/src/main/com/mongodb/internal/connection/Stream.java similarity index 95% rename from driver-core/src/main/com/mongodb/connection/Stream.java rename to driver-core/src/main/com/mongodb/internal/connection/Stream.java index 9c8a3a03d20..bcce2bfabba 100644 --- a/driver-core/src/main/com/mongodb/connection/Stream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/Stream.java @@ -14,9 +14,10 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; import com.mongodb.ServerAddress; +import com.mongodb.connection.AsyncCompletionHandler; import org.bson.ByteBuf; import java.io.IOException; @@ -24,12 +25,8 @@ /** * A full duplex stream of bytes. - * - * @since 3.0 - * @deprecated There is no replacement for this interface. */ -@Deprecated -public interface Stream extends BufferProvider{ +public interface Stream extends BufferProvider { /** * Open the stream. @@ -71,7 +68,6 @@ public interface Stream extends BufferProvider{ * * @return true if this implementation supports specifying an additional timeouts for reads operations * @see #read(int, int) - * @since 4.1 */ default boolean supportsAdditionalTimeout() { return false; @@ -93,7 +89,6 @@ default boolean supportsAdditionalTimeout() { * @throws IOException if there are problems reading from the stream * @throws UnsupportedOperationException if this implementation does not support additional timeouts * @see #supportsAdditionalTimeout() - * @since 4.1 */ default ByteBuf read(int numBytes, int additionalTimeout) throws IOException { throw new UnsupportedOperationException(); diff --git a/driver-core/src/main/com/mongodb/connection/StreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/StreamFactory.java similarity index 88% rename from driver-core/src/main/com/mongodb/connection/StreamFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/StreamFactory.java index 7974b4d6f74..120a4584862 100644 --- a/driver-core/src/main/com/mongodb/connection/StreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/StreamFactory.java @@ -14,17 +14,13 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; import com.mongodb.ServerAddress; /** * A factory for streams. - * - * @since 3.0 - * @deprecated There is no replacement for this interface. */ -@Deprecated public interface StreamFactory { /** * Create a Stream to the given address diff --git a/driver-core/src/main/com/mongodb/connection/StreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java similarity index 88% rename from driver-core/src/main/com/mongodb/connection/StreamFactoryFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java index 8c81ef96fde..96df4c29348 100644 --- a/driver-core/src/main/com/mongodb/connection/StreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java @@ -14,15 +14,14 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; + +import com.mongodb.connection.SocketSettings; +import com.mongodb.connection.SslSettings; /** * A factory of {@code StreamFactory} instances. - * - * @since 3.1 - * @deprecated There is no replacement for this interface. */ -@Deprecated public interface StreamFactoryFactory { /** diff --git a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java index ccd05a17104..f7407f09ef9 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java @@ -19,19 +19,17 @@ import com.mongodb.MongoClientException; import com.mongodb.MongoClientSettings; import com.mongodb.connection.NettyTransportSettings; -import com.mongodb.connection.StreamFactoryFactory; import com.mongodb.connection.TransportSettings; -import com.mongodb.connection.netty.NettyStreamFactoryFactory; +import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; import com.mongodb.lang.Nullable; /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public final class StreamFactoryHelper { @Nullable public static StreamFactoryFactory getStreamFactoryFactoryFromSettings(final MongoClientSettings settings) { - StreamFactoryFactory streamFactoryFactory; + StreamFactoryFactory streamFactoryFactory = null; TransportSettings transportSettings = settings.getTransportSettings(); if (transportSettings != null) { if (transportSettings instanceof NettyTransportSettings) { @@ -40,8 +38,6 @@ public static StreamFactoryFactory getStreamFactoryFactoryFromSettings(final Mon } else { throw new MongoClientException("Unsupported transport settings: " + transportSettings.getClass().getName()); } - } else { - streamFactoryFactory = settings.getStreamFactoryFactory(); } return streamFactoryFactory; } diff --git a/driver-core/src/main/com/mongodb/connection/TlsChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java similarity index 92% rename from driver-core/src/main/com/mongodb/connection/TlsChannelStreamFactoryFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java index 90bc987272f..70db0cced2c 100644 --- a/driver-core/src/main/com/mongodb/connection/TlsChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java @@ -14,14 +14,14 @@ * limitations under the License. */ -package com.mongodb.connection; +package com.mongodb.internal.connection; import com.mongodb.MongoClientException; import com.mongodb.MongoSocketOpenException; import com.mongodb.ServerAddress; -import com.mongodb.internal.connection.AsynchronousChannelStream; -import com.mongodb.internal.connection.ExtendedAsynchronousByteChannel; -import com.mongodb.internal.connection.PowerOfTwoBufferPool; +import com.mongodb.connection.AsyncCompletionHandler; +import com.mongodb.connection.SocketSettings; +import com.mongodb.connection.SslSettings; import com.mongodb.internal.connection.tlschannel.BufferAllocator; import com.mongodb.internal.connection.tlschannel.ClientTlsChannel; import com.mongodb.internal.connection.tlschannel.TlsChannel; @@ -48,6 +48,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.isTrue; import static com.mongodb.internal.connection.SslHelper.enableHostNameVerification; import static com.mongodb.internal.connection.SslHelper.enableSni; @@ -55,57 +56,34 @@ /** * A {@code StreamFactoryFactory} that supports TLS/SSL. The implementation supports asynchronous usage. - * - * @since 3.10 - * @deprecated There is no replacement for this class. */ -@Deprecated public class TlsChannelStreamFactoryFactory implements StreamFactoryFactory, Closeable { private static final Logger LOGGER = Loggers.getLogger("connection.tls"); private final SelectorMonitor selectorMonitor; private final AsynchronousTlsChannelGroup group; - private final boolean ownsGroup; private final PowerOfTwoBufferPool bufferPool = PowerOfTwoBufferPool.DEFAULT; /** * Construct a new instance */ public TlsChannelStreamFactoryFactory() { - this(new AsynchronousTlsChannelGroup(), true); - } - - /** - * Construct a new instance with the given {@code AsynchronousTlsChannelGroup}. Callers are required to close the provided group - * in order to free up resources. - * - * @param group the group - * @deprecated Prefer {@link #TlsChannelStreamFactoryFactory()} - */ - @Deprecated - public TlsChannelStreamFactoryFactory(final AsynchronousTlsChannelGroup group) { - this(group, false); - } - - private TlsChannelStreamFactoryFactory(final AsynchronousTlsChannelGroup group, final boolean ownsGroup) { - this.group = group; - this.ownsGroup = ownsGroup; + this.group = new AsynchronousTlsChannelGroup(); selectorMonitor = new SelectorMonitor(); selectorMonitor.start(); } @Override public StreamFactory create(final SocketSettings socketSettings, final SslSettings sslSettings) { + assertTrue(sslSettings.isEnabled()); return serverAddress -> new TlsChannelStream(serverAddress, socketSettings, sslSettings, bufferPool, group, selectorMonitor); } @Override public void close() { selectorMonitor.close(); - if (ownsGroup) { - group.shutdown(); - } + group.shutdown(); } private static class SelectorMonitor implements Closeable { diff --git a/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java b/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java index f19c85740c7..1e776481bdd 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java @@ -17,7 +17,6 @@ package com.mongodb.internal.connection; import com.mongodb.UnixServerAddress; -import com.mongodb.connection.BufferProvider; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; import jnr.unixsocket.UnixSocketAddress; @@ -30,7 +29,6 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -@SuppressWarnings("deprecation") public class UnixSocketChannelStream extends SocketStream { private final UnixServerAddress address; diff --git a/driver-core/src/main/com/mongodb/connection/netty/NettyStream.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java similarity index 99% rename from driver-core/src/main/com/mongodb/connection/netty/NettyStream.java rename to driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java index bb971603ab5..786b191ffdc 100644 --- a/driver-core/src/main/com/mongodb/connection/netty/NettyStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.mongodb.connection.netty; +package com.mongodb.internal.connection.netty; import com.mongodb.MongoClientException; import com.mongodb.MongoException; @@ -27,8 +27,7 @@ import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.Stream; -import com.mongodb.internal.connection.netty.NettyByteBuf; +import com.mongodb.internal.connection.Stream; import com.mongodb.lang.Nullable; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBufAllocator; @@ -108,7 +107,6 @@ * itself in the example above. However, there are no concurrent pending readers because the second operation * is invoked after the first operation has completed reading despite the method has not returned yet. */ -@SuppressWarnings("deprecation") final class NettyStream implements Stream { private static final byte NO_SCHEDULE_TIME = 0; private final ServerAddress address; diff --git a/driver-core/src/main/com/mongodb/connection/netty/NettyStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java similarity index 94% rename from driver-core/src/main/com/mongodb/connection/netty/NettyStreamFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java index 22d33b8ce2b..91b5e11d863 100644 --- a/driver-core/src/main/com/mongodb/connection/netty/NettyStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java @@ -14,13 +14,13 @@ * limitations under the License. */ -package com.mongodb.connection.netty; +package com.mongodb.internal.connection.netty; import com.mongodb.ServerAddress; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.Stream; -import com.mongodb.connection.StreamFactory; +import com.mongodb.internal.connection.Stream; +import com.mongodb.internal.connection.StreamFactory; import com.mongodb.lang.Nullable; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.PooledByteBufAllocator; @@ -34,12 +34,7 @@ /** * A StreamFactory for Streams based on Netty 4.x. - * - * @since 3.0 - * @deprecated there is no replacement for this class */ -@SuppressWarnings("deprecation") -@Deprecated public class NettyStreamFactory implements StreamFactory { private final SocketSettings settings; private final SslSettings sslSettings; @@ -59,8 +54,6 @@ public class NettyStreamFactory implements StreamFactory { * @param allocator the allocator to use for ByteBuf instances * @param sslContext the Netty {@link SslContext} * as specified by {@link NettyStreamFactoryFactory.Builder#sslContext(SslContext)}. - * - * @since 4.3 */ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSettings, final EventLoopGroup eventLoopGroup, final Class socketChannelClass, @@ -82,8 +75,6 @@ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSe * @param eventLoopGroup the event loop group that all channels created by this factory will be a part of * @param socketChannelClass the socket channel class * @param allocator the allocator to use for ByteBuf instances - * - * @since 3.3 */ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSettings, final EventLoopGroup eventLoopGroup, final Class socketChannelClass, @@ -110,8 +101,6 @@ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSe * @param settings the socket settings * @param sslSettings the SSL settings * @param eventLoopGroup the event loop group that all channels created by this factory will be a part of - * - * @since 3.4 */ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSettings, final EventLoopGroup eventLoopGroup) { this(settings, sslSettings, eventLoopGroup, PooledByteBufAllocator.DEFAULT); diff --git a/driver-core/src/main/com/mongodb/connection/netty/NettyStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java similarity index 94% rename from driver-core/src/main/com/mongodb/connection/netty/NettyStreamFactoryFactory.java rename to driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java index 20995edde70..bc72e7514e9 100644 --- a/driver-core/src/main/com/mongodb/connection/netty/NettyStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java @@ -14,14 +14,13 @@ * limitations under the License. */ -package com.mongodb.connection.netty; +package com.mongodb.internal.connection.netty; import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.StreamFactory; -import com.mongodb.connection.StreamFactoryFactory; -import com.mongodb.connection.TransportSettings; +import com.mongodb.internal.connection.StreamFactory; +import com.mongodb.internal.connection.StreamFactoryFactory; import com.mongodb.internal.VisibleForTesting; import com.mongodb.lang.Nullable; import io.netty.buffer.ByteBufAllocator; @@ -43,12 +42,7 @@ /** * A {@code StreamFactoryFactory} implementation for Netty-based streams. - * - * @since 3.1 - * @deprecated Prefer {@link NettyTransportSettings}, creatable via {@link TransportSettings#nettyBuilder()} and applied via - * {@link com.mongodb.MongoClientSettings.Builder#transportSettings(TransportSettings)} */ -@Deprecated public final class NettyStreamFactoryFactory implements StreamFactoryFactory { private final EventLoopGroup eventLoopGroup; @@ -60,7 +54,6 @@ public final class NettyStreamFactoryFactory implements StreamFactoryFactory { /** * Gets a builder for an instance of {@code NettyStreamFactoryFactory}. * @return the builder - * @since 3.3 */ public static Builder builder() { return new Builder(); @@ -89,8 +82,6 @@ SslContext getSslContext() { /** * A builder for an instance of {@code NettyStreamFactoryFactory}. - * - * @since 3.3 */ public static final class Builder { private ByteBufAllocator allocator; @@ -178,8 +169,6 @@ public Builder eventLoopGroup(final EventLoopGroup eventLoopGroup) { * * @param sslContext The Netty {@link SslContext}, which must be created via {@linkplain SslContextBuilder#forClient()}. * @return {@code this}. - * - * @since 4.3 */ public Builder sslContext(final SslContext sslContext) { this.sslContext = notNull("sslContext", sslContext); diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index c97ac18a358..b9df4268735 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -17,7 +17,9 @@ package com.mongodb; import com.mongodb.async.FutureResultCallback; -import com.mongodb.connection.AsynchronousSocketChannelStreamFactory; +import com.mongodb.connection.NettyTransportSettings; +import com.mongodb.connection.TransportSettings; +import com.mongodb.internal.connection.AsynchronousSocketChannelStreamFactory; import com.mongodb.connection.ClusterConnectionMode; import com.mongodb.connection.ClusterDescription; import com.mongodb.connection.ClusterSettings; @@ -27,12 +29,11 @@ import com.mongodb.connection.ServerSettings; import com.mongodb.connection.ServerVersion; import com.mongodb.connection.SocketSettings; -import com.mongodb.connection.SocketStreamFactory; +import com.mongodb.internal.connection.SocketStreamFactory; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.StreamFactory; -import com.mongodb.connection.StreamFactoryFactory; -import com.mongodb.connection.TlsChannelStreamFactoryFactory; -import com.mongodb.connection.netty.NettyStreamFactoryFactory; +import com.mongodb.internal.connection.StreamFactory; +import com.mongodb.internal.connection.StreamFactoryFactory; +import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; @@ -53,6 +54,7 @@ import com.mongodb.internal.connection.DefaultClusterFactory; import com.mongodb.internal.connection.InternalConnectionPoolSettings; import com.mongodb.internal.connection.MongoCredentialWithCache; +import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; import com.mongodb.internal.operation.AsyncReadOperation; import com.mongodb.internal.operation.AsyncWriteOperation; import com.mongodb.internal.operation.BatchCursor; @@ -103,7 +105,6 @@ * Helper class for the acceptance tests. Used primarily by DatabaseTestCase and FunctionalSpecification. This fixture allows Test * super-classes to share functionality whilst minimising duplication. */ -@SuppressWarnings("deprecation") public final class ClusterFixture { public static final String DEFAULT_URI = "mongodb://localhost:27017"; public static final String MONGODB_URI_SYSTEM_PROPERTY_NAME = "org.mongodb.test.uri"; @@ -128,7 +129,7 @@ public final class ClusterFixture { private static ServerVersion serverVersion; private static BsonDocument serverParameters; - private static NettyStreamFactoryFactory nettyStreamFactoryFactory; + private static NettyTransportSettings nettyTransportSettings; static { Runtime.getRuntime().addShutdownHook(new ShutdownHook()); @@ -416,24 +417,27 @@ public static StreamFactory getStreamFactory() { } public static StreamFactory getAsyncStreamFactory() { - StreamFactoryFactory overriddenStreamFactoryFactory = getOverriddenStreamFactoryFactory(); - if (overriddenStreamFactoryFactory == null) { // use NIO2 + TransportSettings transportSettings = getOverriddenTransportSettings(); + if (transportSettings == null) { // use NIO2 if (getSslSettings().isEnabled()) { return new TlsChannelStreamFactoryFactory().create(getSocketSettings(), getSslSettings()); } else { return new AsynchronousSocketChannelStreamFactory(getSocketSettings(), getSslSettings()); } } else { + StreamFactoryFactory overriddenStreamFactoryFactory = NettyStreamFactoryFactory.builder() + .applySettings((NettyTransportSettings) transportSettings) + .build(); return assertNotNull(overriddenStreamFactoryFactory).create(getSocketSettings(), getSslSettings()); } } @Nullable - public static StreamFactoryFactory getOverriddenStreamFactoryFactory() { + public static TransportSettings getOverriddenTransportSettings() { String streamType = System.getProperty("org.mongodb.test.async.type", "nio2"); - if (nettyStreamFactoryFactory == null && streamType.equals("netty")) { - NettyStreamFactoryFactory.Builder builder = NettyStreamFactoryFactory.builder(); + if (nettyTransportSettings == null && streamType.equals("netty")) { + NettyTransportSettings.Builder builder = TransportSettings.nettyBuilder(); String sslProvider = System.getProperty("org.mongodb.test.netty.ssl.provider"); if (sslProvider != null) { SslContext sslContext; @@ -446,9 +450,9 @@ public static StreamFactoryFactory getOverriddenStreamFactoryFactory() { } builder.sslContext(sslContext); } - nettyStreamFactoryFactory = builder.build(); + nettyTransportSettings = builder.build(); } - return nettyStreamFactoryFactory; + return nettyTransportSettings; } private static SocketSettings getSocketSettings() { diff --git a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy index 6628dfb5625..7ce5e9dd72f 100644 --- a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy @@ -1,5 +1,6 @@ package com.mongodb.connection.netty +import com.mongodb.internal.connection.netty.NettyStreamFactory import util.spock.annotations.Slow import com.mongodb.MongoSocketException import com.mongodb.MongoSocketOpenException diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy index add5413f911..b700e297529 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy @@ -5,7 +5,6 @@ import com.mongodb.MongoSocketException import com.mongodb.MongoSocketOpenException import com.mongodb.ServerAddress import com.mongodb.connection.AsyncCompletionHandler -import com.mongodb.connection.AsynchronousSocketChannelStreamFactoryFactory import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings import spock.lang.IgnoreIf diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy index bfab5039181..aa8156dd88c 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy @@ -21,12 +21,11 @@ import com.mongodb.MongoSocketOpenException import com.mongodb.MongoSocketReadTimeoutException import com.mongodb.OperationFunctionalSpecification import com.mongodb.ServerAddress -import com.mongodb.connection.AsynchronousSocketChannelStreamFactory import com.mongodb.connection.ClusterConnectionMode import com.mongodb.connection.ClusterId import com.mongodb.connection.ServerId import com.mongodb.connection.SocketSettings -import com.mongodb.connection.netty.NettyStreamFactory +import com.mongodb.internal.connection.netty.NettyStreamFactory import org.bson.BsonDocument import org.bson.BsonInt32 import org.bson.BsonString diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy index 3c8920f98e7..e8cb470c604 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy @@ -7,11 +7,9 @@ import com.mongodb.MongoCredential import com.mongodb.MongoSecurityException import com.mongodb.ServerAddress import com.mongodb.async.FutureResultCallback -import com.mongodb.connection.AsynchronousSocketChannelStreamFactory import com.mongodb.connection.ClusterId import com.mongodb.connection.ServerId import com.mongodb.connection.SocketSettings -import com.mongodb.connection.SocketStreamFactory import com.mongodb.internal.authentication.AwsCredentialHelper import org.bson.BsonDocument import org.bson.BsonString diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy index 4f6f360d857..f8a662da88d 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy @@ -26,7 +26,7 @@ import com.mongodb.connection.ConnectionId import com.mongodb.connection.ServerId import com.mongodb.connection.ServerType import com.mongodb.connection.SocketSettings -import com.mongodb.connection.netty.NettyStreamFactory +import com.mongodb.internal.connection.netty.NettyStreamFactory import org.bson.BsonDocument import org.bson.BsonInt32 import org.bson.BsonTimestamp diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy index 5206c4983d3..ae8698aae88 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy @@ -26,8 +26,7 @@ import com.mongodb.async.FutureResultCallback import com.mongodb.connection.ClusterId import com.mongodb.connection.ServerId import com.mongodb.connection.SocketSettings -import com.mongodb.connection.SocketStreamFactory -import com.mongodb.connection.netty.NettyStreamFactory +import com.mongodb.internal.connection.netty.NettyStreamFactory import org.bson.BsonDocument import org.bson.BsonString import spock.lang.IgnoreIf diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy index 0339a0da38c..a0eb5ff12b9 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy @@ -23,7 +23,6 @@ import com.mongodb.SubjectProvider import com.mongodb.connection.ClusterId import com.mongodb.connection.ServerId import com.mongodb.connection.SocketSettings -import com.mongodb.connection.SocketStreamFactory import spock.lang.IgnoreIf import spock.lang.Specification diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy index 02dc14ed79b..a0e2571897f 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy @@ -25,8 +25,7 @@ import com.mongodb.async.FutureResultCallback import com.mongodb.connection.ClusterId import com.mongodb.connection.ServerId import com.mongodb.connection.SocketSettings -import com.mongodb.connection.SocketStreamFactory -import com.mongodb.connection.netty.NettyStreamFactory +import com.mongodb.internal.connection.netty.NettyStreamFactory import org.bson.BsonDocument import org.bson.BsonString import spock.lang.IgnoreIf diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java index f2230b92ca0..cd47dfb5182 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java @@ -25,8 +25,6 @@ import com.mongodb.connection.ConnectionDescription; import com.mongodb.connection.ServerId; import com.mongodb.connection.SocketSettings; -import com.mongodb.connection.SocketStreamFactory; -import com.mongodb.connection.StreamFactory; import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -39,7 +37,6 @@ import static com.mongodb.ClusterFixture.getSslSettings; @Ignore -@SuppressWarnings("deprecation") public class PlainAuthenticatorTest { private InternalConnection internalConnection; private ConnectionDescription connectionDescription; diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy index 6d1cb0133db..b8ea72dc246 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy @@ -28,7 +28,6 @@ import com.mongodb.connection.ServerId import com.mongodb.connection.ServerSettings import com.mongodb.connection.ServerType import com.mongodb.connection.SocketSettings -import com.mongodb.connection.SocketStreamFactory import com.mongodb.internal.inject.SameObjectProvider import org.bson.types.ObjectId diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java index af98ef2fc28..e25c433e3ec 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java @@ -25,7 +25,6 @@ import com.mongodb.connection.ConnectionPoolSettings; import com.mongodb.connection.ServerSettings; import com.mongodb.connection.SocketSettings; -import com.mongodb.connection.SocketStreamFactory; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.binding.StaticBindingContext; import com.mongodb.internal.selector.ServerAddressSelector; diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy index 831fe209f95..961b72ca0c8 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy @@ -3,7 +3,6 @@ package com.mongodb.internal.connection import util.spock.annotations.Slow import com.mongodb.MongoSocketOpenException import com.mongodb.ServerAddress -import com.mongodb.connection.BufferProvider import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings import spock.lang.Ignore diff --git a/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy index 6f1e01f2f5e..90f28833ba5 100644 --- a/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy @@ -24,7 +24,6 @@ import com.mongodb.connection.ServerSettings import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings import com.mongodb.connection.TransportSettings -import com.mongodb.connection.netty.NettyStreamFactoryFactory import com.mongodb.event.CommandListener import com.mongodb.spi.dns.DnsClient import com.mongodb.spi.dns.InetAddressResolver @@ -59,7 +58,6 @@ class MongoClientSettingsSpecification extends Specification { settings.heartbeatSocketSettings == SocketSettings.builder().readTimeout(10000, TimeUnit.MILLISECONDS).build() settings.serverSettings == ServerSettings.builder().build() settings.transportSettings == null - settings.streamFactoryFactory == null settings.compressorList == [] settings.credential == null settings.uuidRepresentation == UuidRepresentation.UNSPECIFIED @@ -103,11 +101,6 @@ class MongoClientSettingsSpecification extends Specification { then: thrown(IllegalArgumentException) - when: - builder.streamFactoryFactory(null) - then: - thrown(IllegalArgumentException) - when: builder.addCommandListener(null) then: @@ -127,7 +120,6 @@ class MongoClientSettingsSpecification extends Specification { def 'should build with set configuration'() { given: def transportSettings = TransportSettings.nettyBuilder().build() - def streamFactoryFactory = NettyStreamFactoryFactory.builder().build() def credential = MongoCredential.createMongoX509Credential('test') def codecRegistry = Stub(CodecRegistry) def commandListener = Stub(CommandListener) @@ -154,7 +146,6 @@ class MongoClientSettingsSpecification extends Specification { } }) .transportSettings(transportSettings) - .streamFactoryFactory(streamFactoryFactory) .compressorList([MongoCompressor.createZlibCompressor()]) .uuidRepresentation(UuidRepresentation.STANDARD) .contextProvider(contextProvider) @@ -176,7 +167,6 @@ class MongoClientSettingsSpecification extends Specification { settings.getCredential() == credential settings.getClusterSettings() == clusterSettings settings.getTransportSettings() == transportSettings - settings.getStreamFactoryFactory() == streamFactoryFactory settings.getCompressorList() == [MongoCompressor.createZlibCompressor()] settings.getUuidRepresentation() == UuidRepresentation.STANDARD settings.getContextProvider() == contextProvider @@ -535,7 +525,7 @@ class MongoClientSettingsSpecification extends Specification { 'heartbeatConnectTimeoutMS', 'heartbeatSocketTimeoutMS', 'inetAddressResolver', 'loggerSettingsBuilder', 'readConcern', 'readPreference', 'retryReads', 'retryWrites', 'serverApi', 'serverSettingsBuilder', 'socketSettingsBuilder', 'sslSettingsBuilder', - 'streamFactoryFactory', 'transportSettings', 'uuidRepresentation', 'writeConcern'] + 'transportSettings', 'uuidRepresentation', 'writeConcern'] then: actual == expected @@ -550,7 +540,7 @@ class MongoClientSettingsSpecification extends Specification { 'applyToSslSettings', 'autoEncryptionSettings', 'build', 'codecRegistry', 'commandListenerList', 'compressorList', 'contextProvider', 'credential', 'dnsClient', 'heartbeatConnectTimeoutMS', 'heartbeatSocketTimeoutMS', 'inetAddressResolver', 'readConcern', 'readPreference', 'retryReads', 'retryWrites', - 'serverApi', 'streamFactoryFactory', 'transportSettings', 'uuidRepresentation', 'writeConcern'] + 'serverApi', 'transportSettings', 'uuidRepresentation', 'writeConcern'] then: actual == expected } diff --git a/driver-core/src/test/unit/com/mongodb/connection/NettyTransportSettingsTest.java b/driver-core/src/test/unit/com/mongodb/connection/NettyTransportSettingsTest.java index 4030c0672bf..2a0fd590e1d 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/NettyTransportSettingsTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/NettyTransportSettingsTest.java @@ -17,9 +17,9 @@ package com.mongodb.connection; import io.netty.buffer.UnpooledByteBufAllocator; +import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoopGroup; -import io.netty.channel.oio.OioEventLoopGroup; -import io.netty.channel.socket.oio.OioSocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import org.junit.jupiter.api.Test; @@ -40,20 +40,19 @@ public void shouldDefaultAllValuesToNull() { assertNull(settings.getSocketChannelClass()); } - @SuppressWarnings("deprecation") @Test public void shouldApplySettingsFromBuilder() throws SSLException { - EventLoopGroup eventLoopGroup = new OioEventLoopGroup(); + EventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(); SslContext sslContext = SslContextBuilder.forClient().build(); NettyTransportSettings settings = TransportSettings.nettyBuilder() .allocator(UnpooledByteBufAllocator.DEFAULT) - .socketChannelClass(OioSocketChannel.class) + .socketChannelClass(NioSocketChannel.class) .eventLoopGroup(eventLoopGroup) .sslContext(sslContext) .build(); assertEquals(UnpooledByteBufAllocator.DEFAULT, settings.getAllocator()); - assertEquals(OioSocketChannel.class, settings.getSocketChannelClass()); + assertEquals(NioSocketChannel.class, settings.getSocketChannelClass()); assertEquals(eventLoopGroup, settings.getEventLoopGroup()); assertEquals(sslContext, settings.getSslContext()); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java index 6a3a54b91fd..0e832457b82 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java @@ -29,7 +29,6 @@ import com.mongodb.connection.ServerId; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.StreamFactory; import com.mongodb.event.ConnectionCheckOutFailedEvent; import com.mongodb.event.ConnectionCheckOutStartedEvent; import com.mongodb.event.ConnectionCheckedInEvent; diff --git a/driver-core/src/test/unit/com/mongodb/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy similarity index 88% rename from driver-core/src/test/unit/com/mongodb/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy rename to driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy index ace3c1aebbf..acb977ccb4a 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy @@ -14,13 +14,15 @@ * limitations under the License. */ -package com.mongodb.connection +package com.mongodb.internal.connection import com.mongodb.ServerAddress -import com.mongodb.internal.connection.AsynchronousSocketChannelStream +import com.mongodb.connection.SocketSettings +import com.mongodb.connection.SslSettings import spock.lang.Specification import spock.lang.Unroll +import java.nio.channels.AsynchronousChannelGroup import java.util.concurrent.ExecutorService import java.util.concurrent.Executors @@ -54,6 +56,6 @@ class AsynchronousSocketChannelStreamFactoryFactorySpecification extends Specifi ExecutorService service = Executors.newFixedThreadPool(1) static final DEFAULT_FACTORY = AsynchronousSocketChannelStreamFactoryFactory.builder().build() static final CUSTOM_FACTORY = AsynchronousSocketChannelStreamFactoryFactory.builder() - .group(java.nio.channels.AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(5))) + .group(AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(5))) .build() } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufSpecification.groovy index e8b2f27f618..0e0755f65bd 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufSpecification.groovy @@ -16,7 +16,7 @@ package com.mongodb.internal.connection -import com.mongodb.connection.BufferProvider + import com.mongodb.internal.connection.netty.NettyByteBuf import io.netty.buffer.ByteBufAllocator import io.netty.buffer.PooledByteBufAllocator diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java index 954ea0b714b..60d443fbc7e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java @@ -17,11 +17,8 @@ package com.mongodb.internal.connection; import com.mongodb.async.FutureResultCallback; -import com.mongodb.connection.AsynchronousSocketChannelStreamFactory; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.StreamFactory; -import com.mongodb.connection.TlsChannelStreamFactoryFactory; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import org.bson.BsonDocument; @@ -34,7 +31,6 @@ // https://github.com/mongodb/specifications/blob/master/source/connection-monitoring-and-pooling/connection-monitoring-and-pooling.rst // specification tests @RunWith(Parameterized.class) -@SuppressWarnings("deprecation") public class ConnectionPoolAsyncTest extends AbstractConnectionPoolTest { private static final Logger LOGGER = Loggers.getLogger(ConnectionPoolAsyncTest.class.getSimpleName()); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java index 5d2dd413eea..aecd88a50a9 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java @@ -17,9 +17,7 @@ package com.mongodb.internal.connection; import com.mongodb.connection.SocketSettings; -import com.mongodb.connection.SocketStreamFactory; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.StreamFactory; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import org.bson.BsonDocument; @@ -32,7 +30,6 @@ // https://github.com/mongodb/specifications/blob/master/source/connection-monitoring-and-pooling/connection-monitoring-and-pooling.rst // specification tests @RunWith(Parameterized.class) -@SuppressWarnings("deprecation") public class ConnectionPoolTest extends AbstractConnectionPoolTest { private static final Logger LOGGER = Loggers.getLogger(ConnectionPoolTest.class.getSimpleName()); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy index 216c73fd7f5..6c9263e940e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy @@ -35,8 +35,6 @@ import com.mongodb.connection.ServerConnectionState import com.mongodb.connection.ServerDescription import com.mongodb.connection.ServerId import com.mongodb.connection.ServerType -import com.mongodb.connection.Stream -import com.mongodb.connection.StreamFactory import com.mongodb.event.CommandFailedEvent import com.mongodb.event.CommandStartedEvent import com.mongodb.event.CommandSucceededEvent diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/SimpleBufferProvider.java b/driver-core/src/test/unit/com/mongodb/internal/connection/SimpleBufferProvider.java index ffb275d34be..e50f718a67c 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/SimpleBufferProvider.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/SimpleBufferProvider.java @@ -16,13 +16,11 @@ package com.mongodb.internal.connection; -import com.mongodb.connection.BufferProvider; import org.bson.ByteBuf; import org.bson.ByteBufNIO; import java.nio.ByteBuffer; -@SuppressWarnings("deprecation") public class SimpleBufferProvider implements BufferProvider { @Override public ByteBuf getBuffer(final int size) { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java index e71d9e10f5c..a5d9b6bb0c2 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java @@ -19,10 +19,9 @@ import com.mongodb.MongoClientSettings; import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.TransportSettings; -import com.mongodb.connection.netty.NettyStreamFactoryFactory; +import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.oio.OioSocketChannel; import org.junit.jupiter.api.Test; import static com.mongodb.assertions.Assertions.assertNull; @@ -36,22 +35,12 @@ void streamFactoryFactoryIsNullWithDefaultSettings() { MongoClientSettings settings = MongoClientSettings.builder().build(); assertNull(StreamFactoryHelper.getStreamFactoryFactoryFromSettings(settings)); } - - @Test - void streamFactoryFactoryIsEqualToSettingsStreamFactoryFactory() { - NettyStreamFactoryFactory streamFactoryFactory = NettyStreamFactoryFactory.builder().build(); - MongoClientSettings settings = MongoClientSettings.builder() - .streamFactoryFactory(streamFactoryFactory) - .build(); - assertEquals(streamFactoryFactory, StreamFactoryHelper.getStreamFactoryFactoryFromSettings(settings)); - } - @Test void streamFactoryFactoryIsDerivedFromTransportSettings() { NettyTransportSettings nettyTransportSettings = TransportSettings.nettyBuilder() .eventLoopGroup(new NioEventLoopGroup()) .allocator(PooledByteBufAllocator.DEFAULT) - .socketChannelClass(OioSocketChannel.class) + .socketChannelClass(io.netty.channel.socket.oio.OioSocketChannel.class) .build(); MongoClientSettings settings = MongoClientSettings.builder() .transportSettings(nettyTransportSettings) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java b/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java index d363dcc7cdb..ce8b109cd52 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java @@ -18,7 +18,6 @@ import com.mongodb.MongoException; import com.mongodb.RequestContext; -import com.mongodb.connection.BufferProvider; import com.mongodb.connection.ConnectionDescription; import com.mongodb.connection.ConnectionId; import com.mongodb.connection.ServerDescription; @@ -47,7 +46,6 @@ import static com.mongodb.internal.connection.ProtocolHelper.isCommandOk; import static com.mongodb.internal.operation.ServerVersionHelper.THREE_DOT_SIX_WIRE_VERSION; -@SuppressWarnings("deprecation") class TestInternalConnection implements InternalConnection { private static class Interaction { diff --git a/driver-core/src/test/unit/com/mongodb/connection/netty/ByteBufSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/ByteBufSpecification.groovy similarity index 97% rename from driver-core/src/test/unit/com/mongodb/connection/netty/ByteBufSpecification.groovy rename to driver-core/src/test/unit/com/mongodb/internal/connection/netty/ByteBufSpecification.groovy index d2ab8ebf9dc..0a59c4e8ad4 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/netty/ByteBufSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/ByteBufSpecification.groovy @@ -14,9 +14,9 @@ * limitations under the License. */ -package com.mongodb.connection.netty +package com.mongodb.internal.connection.netty + -import com.mongodb.internal.connection.netty.NettyByteBuf import io.netty.buffer.ByteBufAllocator import org.bson.ByteBufNIO import spock.lang.Specification diff --git a/driver-core/src/test/unit/com/mongodb/connection/netty/NettyStreamFactoryFactorySpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy similarity index 98% rename from driver-core/src/test/unit/com/mongodb/connection/netty/NettyStreamFactoryFactorySpecification.groovy rename to driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy index 99291dbe28c..59dd78f40e2 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/netty/NettyStreamFactoryFactorySpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.mongodb.connection.netty +package com.mongodb.internal.connection.netty import com.mongodb.ServerAddress import com.mongodb.connection.SocketSettings diff --git a/driver-core/src/test/unit/com/mongodb/connection/netty/NettyStreamFactorySpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactorySpecification.groovy similarity index 98% rename from driver-core/src/test/unit/com/mongodb/connection/netty/NettyStreamFactorySpecification.groovy rename to driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactorySpecification.groovy index 56f8bf2f8de..c60f9a838f3 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/netty/NettyStreamFactorySpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactorySpecification.groovy @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.mongodb.connection.netty +package com.mongodb.internal.connection.netty import com.mongodb.ClusterFixture import com.mongodb.connection.SocketSettings diff --git a/driver-legacy/src/main/com/mongodb/DBDecoderAdapter.java b/driver-legacy/src/main/com/mongodb/DBDecoderAdapter.java index 9710e3b6e51..dd761234df9 100644 --- a/driver-legacy/src/main/com/mongodb/DBDecoderAdapter.java +++ b/driver-legacy/src/main/com/mongodb/DBDecoderAdapter.java @@ -16,7 +16,7 @@ package com.mongodb; -import com.mongodb.connection.BufferProvider; +import com.mongodb.internal.connection.BufferProvider; import com.mongodb.internal.connection.ByteBufferBsonOutput; import org.bson.BsonBinaryWriter; import org.bson.BsonReader; @@ -26,7 +26,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -@SuppressWarnings("deprecation") class DBDecoderAdapter implements Decoder { private final DBDecoder decoder; private final DBCollection collection; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java index 388fca29180..56c57dd8b31 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java @@ -20,13 +20,13 @@ import com.mongodb.MongoClientException; import com.mongodb.MongoClientSettings; import com.mongodb.MongoDriverInformation; -import com.mongodb.connection.AsynchronousSocketChannelStreamFactoryFactory; -import com.mongodb.connection.StreamFactory; -import com.mongodb.connection.StreamFactoryFactory; -import com.mongodb.connection.TlsChannelStreamFactoryFactory; +import com.mongodb.internal.connection.AsynchronousSocketChannelStreamFactoryFactory; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.DefaultClusterFactory; import com.mongodb.internal.connection.InternalConnectionPoolSettings; +import com.mongodb.internal.connection.StreamFactory; +import com.mongodb.internal.connection.StreamFactoryFactory; +import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.internal.MongoClientImpl; import org.bson.codecs.configuration.CodecRegistry; @@ -42,7 +42,6 @@ * A factory for MongoClient instances. * */ -@SuppressWarnings("deprecation") public final class MongoClients { /** @@ -110,7 +109,6 @@ public static MongoClient create(final MongoClientSettings settings) { * @return the client * @since 1.8 */ - @SuppressWarnings("deprecation") public static MongoClient create(final MongoClientSettings settings, @Nullable final MongoDriverInformation mongoDriverInformation) { if (settings.getSocketSettings().getProxySettings().isProxyEnabled()) { throw new MongoClientException("Proxy is not supported for reactive clients"); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java index b01b63d4a64..c392b2a3f45 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java @@ -21,9 +21,9 @@ import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.connection.Stream; -import com.mongodb.connection.StreamFactory; -import com.mongodb.connection.TlsChannelStreamFactoryFactory; +import com.mongodb.internal.connection.Stream; +import com.mongodb.internal.connection.StreamFactory; +import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; import com.mongodb.crypt.capi.MongoKeyDecryptor; import com.mongodb.internal.connection.AsynchronousChannelStream; import com.mongodb.internal.diagnostics.logging.Logger; @@ -43,7 +43,6 @@ import static java.util.Collections.singletonList; import static java.util.concurrent.TimeUnit.MILLISECONDS; -@SuppressWarnings("deprecation") class KeyManagementService implements Closeable { private static final Logger LOGGER = Loggers.getLogger("client"); private final Map kmsProviderSslContextMap; diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/Fixture.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/Fixture.java index 8ec27fe0c87..2881b47e38e 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/Fixture.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/Fixture.java @@ -22,11 +22,8 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoNamespace; import com.mongodb.MongoTimeoutException; -import com.mongodb.connection.AsynchronousSocketChannelStreamFactoryFactory; import com.mongodb.connection.ClusterType; import com.mongodb.connection.ServerVersion; -import com.mongodb.connection.StreamFactoryFactory; -import com.mongodb.connection.TlsChannelStreamFactoryFactory; import com.mongodb.reactivestreams.client.internal.MongoClientImpl; import org.bson.Document; import org.bson.conversions.Bson; @@ -37,14 +34,12 @@ import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; import static com.mongodb.ClusterFixture.getServerApi; -import static com.mongodb.ClusterFixture.getSslSettings; import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException; import static java.lang.Thread.sleep; /** * Helper class for asynchronous tests. */ -@SuppressWarnings("deprecation") public final class Fixture { private static MongoClientImpl mongoClient; private static ServerVersion serverVersion; @@ -162,14 +157,6 @@ public static boolean isReplicaSet() { return clusterType == ClusterType.REPLICA_SET; } - public static StreamFactoryFactory getStreamFactoryFactory() { - if (getSslSettings().isEnabled()) { - return new TlsChannelStreamFactoryFactory(); - } else { - return AsynchronousSocketChannelStreamFactoryFactory.builder().build(); - } - } - public static synchronized ConnectionString getConnectionString() { return ClusterFixture.getConnectionString(); } @@ -177,7 +164,6 @@ public static synchronized ConnectionString getConnectionString() { public static MongoClientSettings.Builder getMongoClientBuilderFromConnectionString() { MongoClientSettings.Builder builder = MongoClientSettings.builder() .applyConnectionString(getConnectionString()); - builder.streamFactoryFactory(getStreamFactoryFactory()); if (getServerApi() != null) { builder.serverApi(getServerApi()); } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MainTransactionsTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MainTransactionsTest.java index c8e6625e920..444407cd471 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MainTransactionsTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MainTransactionsTest.java @@ -20,7 +20,7 @@ import com.mongodb.MongoClientSettings; import com.mongodb.client.AbstractMainTransactionsTest; import com.mongodb.client.MongoClient; -import com.mongodb.connection.StreamFactoryFactory; +import com.mongodb.connection.TransportSettings; import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; import org.bson.BsonArray; import org.bson.BsonDocument; @@ -35,7 +35,6 @@ import static com.mongodb.reactivestreams.client.syncadapter.ContextHelper.CONTEXT_PROVIDER; import static com.mongodb.reactivestreams.client.syncadapter.ContextHelper.assertContextPassedThrough; -@SuppressWarnings("deprecation") public class MainTransactionsTest extends AbstractMainTransactionsTest { public static final Set SESSION_CLOSE_TIMING_SENSITIVE_TESTS = new HashSet<>(Collections.singletonList( "implicit abort")); @@ -61,8 +60,8 @@ protected MongoClient createMongoClient(final MongoClientSettings settings) { } @Override - protected StreamFactoryFactory getStreamFactoryFactory() { - return ClusterFixture.getOverriddenStreamFactoryFactory(); + protected TransportSettings getTransportSettings() { + return ClusterFixture.getOverriddenTransportSettings(); } @Override diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/NettyStreamFactoryFactorySmokeTestSpecification.groovy b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/NettySettingsSmokeTestSpecification.groovy similarity index 83% rename from driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/NettyStreamFactoryFactorySmokeTestSpecification.groovy rename to driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/NettySettingsSmokeTestSpecification.groovy index 44f8f6e0919..7e35e9a183a 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/NettyStreamFactoryFactorySmokeTestSpecification.groovy +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/NettySettingsSmokeTestSpecification.groovy @@ -17,7 +17,7 @@ package com.mongodb.reactivestreams.client import com.mongodb.MongoClientSettings -import com.mongodb.connection.netty.NettyStreamFactoryFactory +import com.mongodb.connection.TransportSettings import io.netty.channel.oio.OioEventLoopGroup import io.netty.channel.socket.oio.OioSocketChannel import org.bson.Document @@ -27,18 +27,19 @@ import static Fixture.getMongoClientBuilderFromConnectionString import static com.mongodb.ClusterFixture.TIMEOUT_DURATION @SuppressWarnings('deprecation') -class NettyStreamFactoryFactorySmokeTestSpecification extends FunctionalSpecification { +class NettySettingsSmokeTestSpecification extends FunctionalSpecification { private MongoClient mongoClient def 'should allow a custom Event Loop Group and Socket Channel'() { given: def eventLoopGroup = new OioEventLoopGroup() - def streamFactoryFactory = NettyStreamFactoryFactory.builder() + def nettySettings = TransportSettings.nettyBuilder() .eventLoopGroup(eventLoopGroup) - .socketChannelClass(OioSocketChannel).build() + .socketChannelClass(OioSocketChannel) + .build() MongoClientSettings settings = getMongoClientBuilderFromConnectionString() - .streamFactoryFactory(streamFactoryFactory).build() + .transportSettings(nettySettings).build() def document = new Document('a', 1) when: diff --git a/driver-scala/src/main/scala/org/mongodb/scala/connection/AsynchronousSocketChannelStreamFactoryFactory.scala b/driver-scala/src/main/scala/org/mongodb/scala/connection/AsynchronousSocketChannelStreamFactoryFactory.scala deleted file mode 100644 index c887f3d211d..00000000000 --- a/driver-scala/src/main/scala/org/mongodb/scala/connection/AsynchronousSocketChannelStreamFactoryFactory.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.mongodb.scala.connection - -import com.mongodb.connection.{ - AsynchronousSocketChannelStreamFactoryFactory => JAsynchronousSocketChannelStreamFactoryFactory -} - -/** - * A `StreamFactoryFactory` implementation for AsynchronousSocketChannel-based streams. - * - * @see java.nio.channels.AsynchronousSocketChannel - * @since 1.0 - */ -@deprecated("For removal in 5.0", "4.11.0") -object AsynchronousSocketChannelStreamFactoryFactory { - - /** - * A `StreamFactoryFactory` implementation for AsynchronousSocketChannel-based streams. - */ - def apply(): StreamFactoryFactory = JAsynchronousSocketChannelStreamFactoryFactory.builder().build() - - /** - * Create a builder for AsynchronousSocketChannel-based streams - * - * @return the builder - * @since 2.2 - */ - def builder(): Builder = JAsynchronousSocketChannelStreamFactoryFactory.builder() - - /** - * AsynchronousSocketChannelStreamFactoryFactory builder type - */ - type Builder = JAsynchronousSocketChannelStreamFactoryFactory.Builder -} diff --git a/driver-scala/src/main/scala/org/mongodb/scala/connection/NettyStreamFactoryFactory.scala b/driver-scala/src/main/scala/org/mongodb/scala/connection/NettyStreamFactoryFactory.scala deleted file mode 100644 index 37a0a00b8e2..00000000000 --- a/driver-scala/src/main/scala/org/mongodb/scala/connection/NettyStreamFactoryFactory.scala +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.mongodb.scala.connection - -import com.mongodb.connection.netty.{ NettyStreamFactoryFactory => JNettyStreamFactoryFactory } - -/** - * A `StreamFactoryFactory` implementation for Netty-based streams. - * - * @since 1.0 - */ -@deprecated("For removal in 5.0", "4.11.0") -object NettyStreamFactoryFactory { - def apply(): StreamFactoryFactory = JNettyStreamFactoryFactory.builder().build() - - /** - * Create a builder for Netty-based streams - * - * @return the builder - * @since 2.2 - */ - def builder(): Builder = JNettyStreamFactoryFactory.builder() - - /** - * NettyStreamFactoryFactory builder type - */ - type Builder = JNettyStreamFactoryFactory.Builder -} diff --git a/driver-scala/src/main/scala/org/mongodb/scala/connection/package.scala b/driver-scala/src/main/scala/org/mongodb/scala/connection/package.scala index 7bdbef6a542..adfb8a02c04 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/connection/package.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/connection/package.scala @@ -75,57 +75,4 @@ package object connection { * @since 4.11 */ type NettyTransportSettings = com.mongodb.connection.NettyTransportSettings - - /** - * The factory for streams. - */ - @deprecated("For removal in 5.0", "4.11.0") - type StreamFactory = com.mongodb.connection.StreamFactory - - /** - * A factory of `StreamFactory` instances. - */ - @deprecated("For removal in 5.0", "4.11.0") - type StreamFactoryFactory = com.mongodb.connection.StreamFactoryFactory - - /** - * A `StreamFactoryFactory` implementation for AsynchronousSocketChannel-based streams. - * - * @see java.nio.channels.AsynchronousSocketChannel - */ - @deprecated("For removal in 5.0", "4.11.0") - type AsynchronousSocketChannelStreamFactoryFactory = - com.mongodb.connection.AsynchronousSocketChannelStreamFactoryFactory - - /** - * A `StreamFactoryFactory` builder for AsynchronousSocketChannel-based streams. - * - * @see java.nio.channels.AsynchronousSocketChannel - * @since 2.2 - */ - @deprecated("For removal in 5.0", "4.11.0") - type AsynchronousSocketChannelStreamFactoryFactoryBuilder = - com.mongodb.connection.AsynchronousSocketChannelStreamFactoryFactory.Builder - - /** - * A `StreamFactoryFactory` implementation for Netty-based streams. - * @since 2.2 - */ - @deprecated("For removal in 5.0", "4.11.0") - type NettyStreamFactoryFactory = com.mongodb.connection.netty.NettyStreamFactoryFactory - - /** - * A `StreamFactoryFactory` builder for Netty-based streams. - * @since 2.2 - */ - @deprecated("For removal in 5.0", "4.11.0") - type NettyStreamFactoryFactoryBuilder = com.mongodb.connection.netty.NettyStreamFactoryFactory.Builder - - /** - * A `StreamFactoryFactory` that supports TLS/SSL. - * - * @since 2.6 - */ - @deprecated("For removal in 5.0", "4.11.0") - type TlsChannelStreamFactoryFactory = com.mongodb.connection.TlsChannelStreamFactoryFactory } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala index 6f7430d4172..9d1a86ee75a 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala @@ -178,35 +178,17 @@ class ApiAliasAndCompanionSpec extends BaseSpec { diff(local, wrapped) shouldBe empty } - it should "mirror parts of com.mongodb.connection in org.mongdb.scala.connection" in { + it should "mirror parts of com.mongodb.connection in org.mongodb.scala.connection" in { val packageName = "com.mongodb.connection" val javaExclusions = Set( "AsyncCompletionHandler", - "AsyncConnection", - "AsynchronousSocketChannelStreamFactory", - "BufferProvider", - "Builder", - "BulkWriteBatchCombiner", - "ChangeEvent", - "ChangeListener", - "Cluster", "ClusterDescription", - "ClusterFactory", "ClusterId", - "Connection", "ConnectionDescription", "ConnectionId", - "DefaultClusterFactory", - "DefaultRandomStringGenerator", - "QueryResult", - "RandomStringGenerator", - "Server", "ServerDescription", "ServerId", "ServerVersion", - "SocketStreamFactory", - "Stream", - "SplittablePayload", "TopologyVersion" ) diff --git a/driver-scala/src/test/scala/org/mongodb/scala/connection/ConnectionSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/connection/ConnectionSpec.scala index 4435b9bc08c..9db7968fae7 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/connection/ConnectionSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/connection/ConnectionSpec.scala @@ -16,26 +16,15 @@ package org.mongodb.scala.connection -import java.net.{ InetAddress, InetSocketAddress } - import com.mongodb.{ ServerAddress => JServerAddress } import org.mongodb.scala.{ BaseSpec, ServerAddress } import org.scalatestplus.mockito.MockitoSugar +import java.net.{ InetAddress, InetSocketAddress } import scala.collection.JavaConverters._ class ConnectionSpec extends BaseSpec with MockitoSugar { - "The connection namespace" should "have a AsynchronousSocketChannelStreamFactoryFactory companion" in { - val asynchronousSocketChannelStreamFactoryFactory = AsynchronousSocketChannelStreamFactoryFactory() - asynchronousSocketChannelStreamFactoryFactory shouldBe a[StreamFactoryFactory] - } - - it should "have a NettyStreamFactoryFactory companion" in { - val nettyStreamFactoryFactory = NettyStreamFactoryFactory() - nettyStreamFactoryFactory shouldBe a[StreamFactoryFactory] - } - it should "have a ClusterSettings companion" in { val scalaSetting = ClusterSettings.builder().hosts(List(ServerAddress()).asJava).build() val javaSetting = com.mongodb.connection.ClusterSettings.builder().hosts(List(ServerAddress()).asJava).build() diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java index 414458a4302..63d551fc0a0 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java @@ -31,9 +31,9 @@ import com.mongodb.client.SynchronousContextProvider; import com.mongodb.connection.ClusterDescription; import com.mongodb.connection.SocketSettings; -import com.mongodb.connection.SocketStreamFactory; -import com.mongodb.connection.StreamFactory; -import com.mongodb.connection.StreamFactoryFactory; +import com.mongodb.internal.connection.SocketStreamFactory; +import com.mongodb.internal.connection.StreamFactory; +import com.mongodb.internal.connection.StreamFactoryFactory; import com.mongodb.internal.client.model.changestream.ChangeStreamLevel; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.DefaultClusterFactory; @@ -225,7 +225,6 @@ private static Cluster createCluster(final MongoClientSettings settings, settings.getDnsClient(), settings.getInetAddressResolver()); } - @SuppressWarnings("deprecation") private static StreamFactory getStreamFactory(final MongoClientSettings settings, final boolean isHeartbeat) { StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactoryFromSettings(settings); SocketSettings socketSettings = isHeartbeat ? settings.getHeartbeatSocketSettings() : settings.getSocketSettings(); diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractUnifiedTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractUnifiedTest.java index c8b31ce2bb8..cbfab4725bc 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractUnifiedTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractUnifiedTest.java @@ -33,7 +33,7 @@ import com.mongodb.client.test.CollectionHelper; import com.mongodb.connection.ServerDescription; import com.mongodb.connection.ServerType; -import com.mongodb.connection.StreamFactoryFactory; +import com.mongodb.connection.TransportSettings; import com.mongodb.event.CommandEvent; import com.mongodb.event.CommandStartedEvent; import com.mongodb.event.ConnectionPoolClearedEvent; @@ -146,7 +146,7 @@ public AbstractUnifiedTest(final String filename, final String description, fina protected abstract MongoClient createMongoClient(MongoClientSettings settings); @Nullable - protected StreamFactoryFactory getStreamFactoryFactory() { + protected TransportSettings getTransportSettings() { return null; } @@ -253,9 +253,9 @@ public void setUp() { builder.writeConcern(new WriteConcern(clientOptions.getNumber("w").intValue())); } } - StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactory(); - if (streamFactoryFactory != null) { - builder.streamFactoryFactory(streamFactoryFactory); + TransportSettings transportSettings = getTransportSettings(); + if (transportSettings != null) { + builder.transportSettings(transportSettings); } mongoClient = createMongoClient(builder.build()); From b1c89fbd9cfd841e1a8dbc110d3d96d51d3935c6 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Fri, 15 Sep 2023 14:52:58 -0400 Subject: [PATCH 03/28] Simplify StreamFactoryFactory implementations * Remove builders * Remove now-unused factory configuration * Simplify usage in MongoClient instantiation JAVA-5161 --- .../AsynchronousSocketChannelStream.java | 11 +--- ...synchronousSocketChannelStreamFactory.java | 22 +------- ...nousSocketChannelStreamFactoryFactory.java | 47 +--------------- .../connection/StreamFactoryHelper.java | 19 ++----- ...yncSocketChannelStreamSpecification.groovy | 13 ++--- ...elStreamFactoryFactorySpecification.groovy | 22 +------- .../connection/StreamFactoryHelperTest.java | 12 +---- .../reactivestreams/client/MongoClients.java | 53 ++++++------------- .../client/internal/MongoClientImpl.java | 10 ++-- .../client/internal/MongoClientImpl.java | 12 ++--- 10 files changed, 41 insertions(+), 180 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java index 6a956247ed3..5f8104047ca 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java @@ -27,7 +27,6 @@ import java.net.SocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.LinkedList; @@ -44,14 +43,12 @@ public final class AsynchronousSocketChannelStream extends AsynchronousChannelStream { private final ServerAddress serverAddress; private final SocketSettings settings; - private final AsynchronousChannelGroup group; public AsynchronousSocketChannelStream(final ServerAddress serverAddress, final SocketSettings settings, - final PowerOfTwoBufferPool bufferProvider, final AsynchronousChannelGroup group) { + final PowerOfTwoBufferPool bufferProvider) { super(serverAddress, settings, bufferProvider); this.serverAddress = serverAddress; this.settings = settings; - this.group = group; } @SuppressWarnings("deprecation") @@ -77,7 +74,7 @@ private void initializeSocketChannel(final AsyncCompletionHandler handler, SocketAddress socketAddress = socketAddressQueue.poll(); try { - AsynchronousSocketChannel attemptConnectionChannel = AsynchronousSocketChannel.open(group); + AsynchronousSocketChannel attemptConnectionChannel = AsynchronousSocketChannel.open(); attemptConnectionChannel.setOption(StandardSocketOptions.TCP_NODELAY, true); attemptConnectionChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); if (settings.getReceiveBufferSize() > 0) { @@ -97,10 +94,6 @@ private void initializeSocketChannel(final AsyncCompletionHandler handler, } } - public AsynchronousChannelGroup getGroup() { - return group; - } - private class OpenCompletionHandler implements CompletionHandler { private final AtomicReference> handlerReference; private final Queue socketAddressQueue; diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java index 27ea5b70164..546e6c7eba1 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java @@ -19,9 +19,6 @@ import com.mongodb.ServerAddress; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.lang.Nullable; - -import java.nio.channels.AsynchronousChannelGroup; import static com.mongodb.assertions.Assertions.assertFalse; import static com.mongodb.assertions.Assertions.notNull; @@ -32,7 +29,6 @@ public class AsynchronousSocketChannelStreamFactory implements StreamFactory { private final PowerOfTwoBufferPool bufferProvider = PowerOfTwoBufferPool.DEFAULT; private final SocketSettings settings; - private final AsynchronousChannelGroup group; /** * Create a new factory with the default {@code BufferProvider} and {@code AsynchronousChannelGroup}. @@ -41,29 +37,13 @@ public class AsynchronousSocketChannelStreamFactory implements StreamFactory { * @param sslSettings the settings for connecting via SSL */ public AsynchronousSocketChannelStreamFactory(final SocketSettings settings, final SslSettings sslSettings) { - this(settings, sslSettings, null); - } - - /** - * Create a new factory. - * - * @param settings the socket settings - * @param sslSettings the SSL settings - * @param group the {@code AsynchronousChannelGroup} to use or null for the default group - * - * @since 3.6 - */ - public AsynchronousSocketChannelStreamFactory(final SocketSettings settings, final SslSettings sslSettings, - @Nullable final AsynchronousChannelGroup group) { assertFalse(sslSettings.isEnabled()); - this.settings = notNull("settings", settings); - this.group = group; } @Override public Stream create(final ServerAddress serverAddress) { - return new AsynchronousSocketChannelStream(serverAddress, settings, bufferProvider, group); + return new AsynchronousSocketChannelStream(serverAddress, settings, bufferProvider); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java index 107330a844c..a26b990d838 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java @@ -19,59 +19,14 @@ import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import java.nio.channels.AsynchronousChannelGroup; - /** * A {@code StreamFactoryFactory} implementation for AsynchronousSocketChannel-based streams. * * @see java.nio.channels.AsynchronousSocketChannel */ public final class AsynchronousSocketChannelStreamFactoryFactory implements StreamFactoryFactory { - private final AsynchronousChannelGroup group; - - /** - * Gets a builder for an instance of {@code AsynchronousSocketChannelStreamFactoryFactory}. - * @return the builder - * @since 3.6 - */ - public static Builder builder() { - return new Builder(); - } - - /** - * A builder for an instance of {@code AsynchronousSocketChannelStreamFactoryFactory}. - * - * @since 3.6 - */ - public static final class Builder { - private AsynchronousChannelGroup group; - - /** - * Sets the {@code AsynchronousChannelGroup} - * - * @param group the {@code AsynchronousChannelGroup} - * @return this - */ - public Builder group(final AsynchronousChannelGroup group) { - this.group = group; - return this; - } - - /** - * Build an instance of {@code AsynchronousSocketChannelStreamFactoryFactory}. - * @return the AsynchronousSocketChannelStreamFactoryFactory - */ - public AsynchronousSocketChannelStreamFactoryFactory build() { - return new AsynchronousSocketChannelStreamFactoryFactory(this); - } - } - @Override public StreamFactory create(final SocketSettings socketSettings, final SslSettings sslSettings) { - return new AsynchronousSocketChannelStreamFactory(socketSettings, sslSettings, group); - } - - private AsynchronousSocketChannelStreamFactoryFactory(final Builder builder) { - group = builder.group; + return new AsynchronousSocketChannelStreamFactory(socketSettings, sslSettings); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java index f7407f09ef9..dd08aea9ace 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java @@ -17,29 +17,20 @@ package com.mongodb.internal.connection; import com.mongodb.MongoClientException; -import com.mongodb.MongoClientSettings; import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.TransportSettings; import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; -import com.mongodb.lang.Nullable; /** *

This class is not part of the public API and may be removed or changed at any time

*/ public final class StreamFactoryHelper { - @Nullable - public static StreamFactoryFactory getStreamFactoryFactoryFromSettings(final MongoClientSettings settings) { - StreamFactoryFactory streamFactoryFactory = null; - TransportSettings transportSettings = settings.getTransportSettings(); - if (transportSettings != null) { - if (transportSettings instanceof NettyTransportSettings) { - streamFactoryFactory = - NettyStreamFactoryFactory.builder().applySettings((NettyTransportSettings) transportSettings).build(); - } else { - throw new MongoClientException("Unsupported transport settings: " + transportSettings.getClass().getName()); - } + public static StreamFactoryFactory getStreamFactoryFactoryFromSettings(final TransportSettings transportSettings) { + if (transportSettings instanceof NettyTransportSettings) { + return NettyStreamFactoryFactory.builder().applySettings((NettyTransportSettings) transportSettings).build(); + } else { + throw new MongoClientException("Unsupported transport settings: " + transportSettings.getClass().getName()); } - return streamFactoryFactory; } private StreamFactoryHelper() { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy index b700e297529..2709aa09e16 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy @@ -1,6 +1,5 @@ package com.mongodb.internal.connection -import util.spock.annotations.Slow import com.mongodb.MongoSocketException import com.mongodb.MongoSocketOpenException import com.mongodb.ServerAddress @@ -9,10 +8,9 @@ import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings import spock.lang.IgnoreIf import spock.lang.Specification +import util.spock.annotations.Slow -import java.nio.channels.AsynchronousChannelGroup import java.util.concurrent.CountDownLatch -import java.util.concurrent.Executors import static com.mongodb.ClusterFixture.getSslSettings import static java.util.concurrent.TimeUnit.MILLISECONDS @@ -26,8 +24,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def port = 27017 def socketSettings = SocketSettings.builder().connectTimeout(100, MILLISECONDS).build() def sslSettings = SslSettings.builder().build() - def channelGroup = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(5)) - def factoryFactory = AsynchronousSocketChannelStreamFactoryFactory.builder().group(channelGroup).build() + def factoryFactory = new AsynchronousSocketChannelStreamFactoryFactory() def factory = factoryFactory.create(socketSettings, sslSettings) def inetAddresses = [new InetSocketAddress(InetAddress.getByName('192.168.255.255'), port), new InetSocketAddress(InetAddress.getByName('127.0.0.1'), port)] @@ -51,9 +48,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def port = 27017 def socketSettings = SocketSettings.builder().connectTimeout(100, MILLISECONDS).build() def sslSettings = SslSettings.builder().build() - def factoryFactory = AsynchronousSocketChannelStreamFactoryFactory.builder() - .group(AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(5))) - .build() + def factoryFactory = new AsynchronousSocketChannelStreamFactoryFactory() def factory = factoryFactory.create(socketSettings, sslSettings) @@ -81,7 +76,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def stream = new AsynchronousSocketChannelStream(serverAddress, SocketSettings.builder().connectTimeout(100, MILLISECONDS).build(), - new PowerOfTwoBufferPool(), null) + new PowerOfTwoBufferPool()) def callback = new CallbackErrorHolder() when: diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy index acb977ccb4a..6c8e117b4cf 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy @@ -22,40 +22,22 @@ import com.mongodb.connection.SslSettings import spock.lang.Specification import spock.lang.Unroll -import java.nio.channels.AsynchronousChannelGroup -import java.util.concurrent.ExecutorService -import java.util.concurrent.Executors - class AsynchronousSocketChannelStreamFactoryFactorySpecification extends Specification { @Unroll def 'should create the expected #description AsynchronousSocketChannelStream'() { given: - def factory = factoryFactory.create(socketSettings, sslSettings) + def factory = new AsynchronousSocketChannelStreamFactoryFactory().create(socketSettings, sslSettings) when: - AsynchronousSocketChannelStream stream = factory.create(serverAddress) + AsynchronousSocketChannelStream stream = factory.create(serverAddress) as AsynchronousSocketChannelStream then: stream.getSettings() == socketSettings stream.getAddress() == serverAddress - (stream.getGroup() == null) == hasCustomGroup - - cleanup: - stream.getGroup()?.shutdown() - - where: - description | factoryFactory | hasCustomGroup - 'default' | DEFAULT_FACTORY | true - 'custom' | CUSTOM_FACTORY | false } SocketSettings socketSettings = SocketSettings.builder().build() SslSettings sslSettings = SslSettings.builder().build() ServerAddress serverAddress = new ServerAddress() - ExecutorService service = Executors.newFixedThreadPool(1) - static final DEFAULT_FACTORY = AsynchronousSocketChannelStreamFactoryFactory.builder().build() - static final CUSTOM_FACTORY = AsynchronousSocketChannelStreamFactoryFactory.builder() - .group(AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(5))) - .build() } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java index a5d9b6bb0c2..24cf24f2890 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java @@ -16,7 +16,6 @@ package com.mongodb.internal.connection; -import com.mongodb.MongoClientSettings; import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.TransportSettings; import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; @@ -24,17 +23,11 @@ import io.netty.channel.nio.NioEventLoopGroup; import org.junit.jupiter.api.Test; -import static com.mongodb.assertions.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("deprecation") class StreamFactoryHelperTest { - @Test - void streamFactoryFactoryIsNullWithDefaultSettings() { - MongoClientSettings settings = MongoClientSettings.builder().build(); - assertNull(StreamFactoryHelper.getStreamFactoryFactoryFromSettings(settings)); - } @Test void streamFactoryFactoryIsDerivedFromTransportSettings() { NettyTransportSettings nettyTransportSettings = TransportSettings.nettyBuilder() @@ -42,10 +35,7 @@ void streamFactoryFactoryIsDerivedFromTransportSettings() { .allocator(PooledByteBufAllocator.DEFAULT) .socketChannelClass(io.netty.channel.socket.oio.OioSocketChannel.class) .build(); - MongoClientSettings settings = MongoClientSettings.builder() - .transportSettings(nettyTransportSettings) - .build(); assertEquals(NettyStreamFactoryFactory.builder().applySettings(nettyTransportSettings).build(), - StreamFactoryHelper.getStreamFactoryFactoryFromSettings(settings)); + StreamFactoryHelper.getStreamFactoryFactoryFromSettings(nettyTransportSettings)); } } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java index 56c57dd8b31..f22d3ab7c91 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java @@ -20,6 +20,7 @@ import com.mongodb.MongoClientException; import com.mongodb.MongoClientSettings; import com.mongodb.MongoDriverInformation; +import com.mongodb.connection.TransportSettings; import com.mongodb.internal.connection.AsynchronousSocketChannelStreamFactoryFactory; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.DefaultClusterFactory; @@ -31,8 +32,6 @@ import com.mongodb.reactivestreams.client.internal.MongoClientImpl; import org.bson.codecs.configuration.CodecRegistry; -import java.io.Closeable; - import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.connection.StreamFactoryHelper.getStreamFactoryFactoryFromSettings; import static com.mongodb.internal.event.EventListenerHelper.getCommandListener; @@ -113,18 +112,22 @@ public static MongoClient create(final MongoClientSettings settings, @Nullable f if (settings.getSocketSettings().getProxySettings().isProxyEnabled()) { throw new MongoClientException("Proxy is not supported for reactive clients"); } - StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactoryFromSettings(settings); - - if (streamFactoryFactory == null) { - if (settings.getSslSettings().isEnabled()) { - return createWithTlsChannel(settings, mongoDriverInformation); - } else { - return createWithAsynchronousSocketChannel(settings, mongoDriverInformation); - } + + StreamFactoryFactory streamFactoryFactory; + TransportSettings transportSettings = settings.getTransportSettings(); + if (transportSettings != null) { + streamFactoryFactory = getStreamFactoryFactoryFromSettings(transportSettings); + } else if (settings.getSslSettings().isEnabled()) { + streamFactoryFactory = new TlsChannelStreamFactoryFactory(); } else { - return createMongoClient(settings, mongoDriverInformation, getStreamFactory(streamFactoryFactory, settings, false), - getStreamFactory(streamFactoryFactory, settings, true), null); + streamFactoryFactory = new AsynchronousSocketChannelStreamFactoryFactory(); } + StreamFactory streamFactory = getStreamFactory(streamFactoryFactory, settings, false); + StreamFactory heartbeatStreamFactory = getStreamFactory(streamFactoryFactory, settings, true); + AutoCloseable externalResourceCloser = streamFactoryFactory instanceof AutoCloseable ? (AutoCloseable) streamFactoryFactory : null; + MongoDriverInformation wrappedMongoDriverInformation = wrapMongoDriverInformation(mongoDriverInformation); + Cluster cluster = createCluster(settings, wrappedMongoDriverInformation, streamFactory, heartbeatStreamFactory); + return new MongoClientImpl(settings, wrappedMongoDriverInformation, cluster, externalResourceCloser); } /** @@ -138,14 +141,6 @@ public static CodecRegistry getDefaultCodecRegistry() { return MongoClientSettings.getDefaultCodecRegistry(); } - private static MongoClient createMongoClient(final MongoClientSettings settings, - @Nullable final MongoDriverInformation mongoDriverInformation, final StreamFactory streamFactory, - final StreamFactory heartbeatStreamFactory, @Nullable final Closeable externalResourceCloser) { - MongoDriverInformation wrappedMongoDriverInformation = wrapMongoDriverInformation(mongoDriverInformation); - return new MongoClientImpl(settings, wrappedMongoDriverInformation, createCluster(settings, wrappedMongoDriverInformation, - streamFactory, heartbeatStreamFactory), externalResourceCloser); - } - private static Cluster createCluster(final MongoClientSettings settings, @Nullable final MongoDriverInformation mongoDriverInformation, final StreamFactory streamFactory, final StreamFactory heartbeatStreamFactory) { @@ -163,24 +158,6 @@ private static MongoDriverInformation wrapMongoDriverInformation(@Nullable final .driverName("reactive-streams").build(); } - private static MongoClient createWithTlsChannel(final MongoClientSettings settings, - @Nullable final MongoDriverInformation mongoDriverInformation) { - TlsChannelStreamFactoryFactory streamFactoryFactory = new TlsChannelStreamFactoryFactory(); - StreamFactory streamFactory = streamFactoryFactory.create(settings.getSocketSettings(), settings.getSslSettings()); - StreamFactory heartbeatStreamFactory = streamFactoryFactory.create(settings.getHeartbeatSocketSettings(), - settings.getSslSettings()); - return createMongoClient(settings, mongoDriverInformation, streamFactory, heartbeatStreamFactory, streamFactoryFactory); - } - - private static MongoClient createWithAsynchronousSocketChannel(final MongoClientSettings settings, - @Nullable final MongoDriverInformation mongoDriverInformation) { - StreamFactoryFactory streamFactoryFactory = AsynchronousSocketChannelStreamFactoryFactory.builder().build(); - StreamFactory streamFactory = streamFactoryFactory.create(settings.getSocketSettings(), settings.getSslSettings()); - StreamFactory heartbeatStreamFactory = streamFactoryFactory.create(settings.getHeartbeatSocketSettings(), - settings.getSslSettings()); - return createMongoClient(settings, mongoDriverInformation, streamFactory, heartbeatStreamFactory, null); - } - private static StreamFactory getStreamFactory(final StreamFactoryFactory streamFactoryFactory, final MongoClientSettings settings, final boolean isHeartbeat) { return streamFactoryFactory.create(isHeartbeat ? settings.getHeartbeatSocketSettings() : settings.getSocketSettings(), diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java index ff8c0692d0b..95526e86ea5 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java @@ -41,8 +41,6 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.io.Closeable; -import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -64,7 +62,7 @@ public final class MongoClientImpl implements MongoClient { private final Cluster cluster; private final MongoClientSettings settings; private final OperationExecutor executor; - private final Closeable externalResourceCloser; + private final AutoCloseable externalResourceCloser; private final ServerSessionPool serverSessionPool; private final ClientSessionHelper clientSessionHelper; private final MongoOperationPublisher mongoOperationPublisher; @@ -72,7 +70,7 @@ public final class MongoClientImpl implements MongoClient { private final AtomicBoolean closed; public MongoClientImpl(final MongoClientSettings settings, final MongoDriverInformation mongoDriverInformation, final Cluster cluster, - @Nullable final Closeable externalResourceCloser) { + @Nullable final AutoCloseable externalResourceCloser) { this(settings, mongoDriverInformation, cluster, null, externalResourceCloser); } @@ -82,7 +80,7 @@ public MongoClientImpl(final MongoClientSettings settings, final MongoDriverInfo } private MongoClientImpl(final MongoClientSettings settings, final MongoDriverInformation mongoDriverInformation, final Cluster cluster, - @Nullable final OperationExecutor executor, @Nullable final Closeable externalResourceCloser) { + @Nullable final OperationExecutor executor, @Nullable final AutoCloseable externalResourceCloser) { this.settings = notNull("settings", settings); this.cluster = notNull("cluster", cluster); this.serverSessionPool = new ServerSessionPool(cluster, settings.getServerApi()); @@ -146,7 +144,7 @@ public void close() { if (externalResourceCloser != null) { try { externalResourceCloser.close(); - } catch (IOException e) { + } catch (Exception e) { LOGGER.warn("Exception closing resource", e); } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java index 63d551fc0a0..70b767a7109 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java @@ -31,13 +31,13 @@ import com.mongodb.client.SynchronousContextProvider; import com.mongodb.connection.ClusterDescription; import com.mongodb.connection.SocketSettings; -import com.mongodb.internal.connection.SocketStreamFactory; -import com.mongodb.internal.connection.StreamFactory; -import com.mongodb.internal.connection.StreamFactoryFactory; +import com.mongodb.connection.TransportSettings; import com.mongodb.internal.client.model.changestream.ChangeStreamLevel; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.DefaultClusterFactory; import com.mongodb.internal.connection.InternalConnectionPoolSettings; +import com.mongodb.internal.connection.SocketStreamFactory; +import com.mongodb.internal.connection.StreamFactory; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.internal.session.ServerSessionPool; @@ -226,12 +226,12 @@ private static Cluster createCluster(final MongoClientSettings settings, } private static StreamFactory getStreamFactory(final MongoClientSettings settings, final boolean isHeartbeat) { - StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactoryFromSettings(settings); SocketSettings socketSettings = isHeartbeat ? settings.getHeartbeatSocketSettings() : settings.getSocketSettings(); - if (streamFactoryFactory == null) { + TransportSettings transportSettings = settings.getTransportSettings(); + if (transportSettings == null) { return new SocketStreamFactory(socketSettings, settings.getSslSettings()); } else { - return streamFactoryFactory.create(socketSettings, settings.getSslSettings()); + return getStreamFactoryFactoryFromSettings(transportSettings).create(socketSettings, settings.getSslSettings()); } } From 94c321f6a257aded1cb59536381d1e78dba8d800 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Fri, 20 Oct 2023 20:38:14 -0400 Subject: [PATCH 04/28] Remove deprecated ServerAddress methods (#1224) * ServerAddress#getSocketAddress * ServerAddress#getSocketAddresses * UnixServerAddress#getSocketAddress * UnixServerAddress#getUnixSocketAddress JAVA-4937 --- .../src/main/com/mongodb/ServerAddress.java | 41 -------- .../main/com/mongodb/UnixServerAddress.java | 20 ---- .../AsynchronousSocketChannelStream.java | 11 ++- ...synchronousSocketChannelStreamFactory.java | 8 +- ...nousSocketChannelStreamFactoryFactory.java | 9 +- .../connection/DefaultClusterFactory.java | 7 +- .../DefaultClusterableServerFactory.java | 11 +-- .../DefaultInetAddressResolver.java | 36 +++++++ .../connection/InternalStreamConnection.java | 25 +---- .../InternalStreamConnectionFactory.java | 13 +-- .../LoadBalancedClusterableServerFactory.java | 8 +- .../connection/ServerAddressHelper.java | 23 +++++ .../connection/ServerAddressWithResolver.java | 98 ------------------- .../internal/connection/SocketStream.java | 12 ++- .../connection/SocketStreamFactory.java | 17 +++- .../connection/StreamFactoryHelper.java | 8 +- .../TlsChannelStreamFactoryFactory.java | 20 ++-- .../connection/UnixSocketChannelStream.java | 5 +- .../connection/netty/NettyStream.java | 13 ++- .../connection/netty/NettyStreamFactory.java | 18 ++-- .../netty/NettyStreamFactoryFactory.java | 31 +++--- .../com/mongodb/ClusterFixture.java | 32 +++--- .../netty/NettyStreamSpecification.groovy | 63 +++++++----- ...yncSocketChannelStreamSpecification.groovy | 51 ++++++---- .../AsyncStreamTimeoutsSpecification.groovy | 13 +-- .../AwsAuthenticationSpecification.groovy | 9 +- .../CommandHelperSpecification.groovy | 2 +- .../GSSAPIAuthenticationSpecification.groovy | 6 +- .../GSSAPIAuthenticatorSpecification.groovy | 4 +- .../PlainAuthenticationSpecification.groovy | 6 +- .../connection/PlainAuthenticatorTest.java | 6 +- .../ServerMonitorSpecification.groovy | 11 +-- .../connection/SingleServerClusterTest.java | 5 +- .../SocketStreamHelperSpecification.groovy | 16 +-- .../StreamSocketAddressSpecification.groovy | 23 +++-- .../UnixServerAddressSpecification.groovy | 10 +- .../AbstractConnectionPoolTest.java | 4 +- ...elStreamFactoryFactorySpecification.groovy | 3 +- .../connection/ConnectionPoolAsyncTest.java | 4 +- .../connection/ConnectionPoolTest.java | 2 +- ...ternalStreamConnectionSpecification.groovy | 6 +- .../connection/StreamFactoryHelperTest.java | 7 +- ...tyStreamFactoryFactorySpecification.groovy | 7 +- .../reactivestreams/client/MongoClients.java | 11 ++- .../internal/crypt/KeyManagementService.java | 7 +- .../client/internal/MongoClientImpl.java | 10 +- 46 files changed, 354 insertions(+), 398 deletions(-) create mode 100644 driver-core/src/main/com/mongodb/internal/connection/DefaultInetAddressResolver.java delete mode 100644 driver-core/src/main/com/mongodb/internal/connection/ServerAddressWithResolver.java diff --git a/driver-core/src/main/com/mongodb/ServerAddress.java b/driver-core/src/main/com/mongodb/ServerAddress.java index cb9ec61bd51..a537cd775a2 100644 --- a/driver-core/src/main/com/mongodb/ServerAddress.java +++ b/driver-core/src/main/com/mongodb/ServerAddress.java @@ -22,9 +22,6 @@ import java.io.Serializable; import java.net.InetAddress; import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; /** * Represents the location of a Mongo server - i.e. server name and port number @@ -184,44 +181,6 @@ public int getPort() { return port; } - /** - * Gets the underlying socket address - * - * @return socket address - * @deprecated Prefer {@link InetAddress#getByName(String)} - */ - @Deprecated - public InetSocketAddress getSocketAddress() { - try { - return new InetSocketAddress(InetAddress.getByName(host), port); - } catch (UnknownHostException e) { - throw new MongoSocketException(e.getMessage(), this, e); - } - } - - /** - * Gets all underlying socket addresses - * - * @return array of socket addresses - * - * @since 3.9 - * @deprecated Prefer {@link InetAddress#getAllByName(String)} - */ - @Deprecated - public List getSocketAddresses() { - try { - InetAddress[] inetAddresses = InetAddress.getAllByName(host); - List inetSocketAddressList = new ArrayList<>(); - for (InetAddress inetAddress : inetAddresses) { - inetSocketAddressList.add(new InetSocketAddress(inetAddress, port)); - } - - return inetSocketAddressList; - } catch (UnknownHostException e) { - throw new MongoSocketException(e.getMessage(), this, e); - } - } - @Override public String toString() { return host + ":" + port; diff --git a/driver-core/src/main/com/mongodb/UnixServerAddress.java b/driver-core/src/main/com/mongodb/UnixServerAddress.java index 9f003a6cd48..bba882de794 100644 --- a/driver-core/src/main/com/mongodb/UnixServerAddress.java +++ b/driver-core/src/main/com/mongodb/UnixServerAddress.java @@ -17,10 +17,6 @@ package com.mongodb; import com.mongodb.annotations.Immutable; -import jnr.unixsocket.UnixSocketAddress; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; @@ -44,22 +40,6 @@ public UnixServerAddress(final String path) { isTrueArgument("The path must end in .sock", path.endsWith(".sock")); } - @SuppressWarnings("deprecation") - @Deprecated - @Override - public InetSocketAddress getSocketAddress() { - throw new UnsupportedOperationException("Cannot return a InetSocketAddress from a UnixServerAddress"); - } - - /** - * @return the SocketAddress for the MongoD unix domain socket. - * @deprecated Prefer {@link UnixSocketAddress#UnixSocketAddress(String)} - */ - @Deprecated - public SocketAddress getUnixSocketAddress() { - return new UnixSocketAddress(getHost()); - } - @Override public String toString() { return getHost(); diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java index 5f8104047ca..cb1e2a54868 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStream.java @@ -22,6 +22,7 @@ import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.SocketSettings; import com.mongodb.lang.Nullable; +import com.mongodb.spi.dns.InetAddressResolver; import java.io.IOException; import java.net.SocketAddress; @@ -36,29 +37,31 @@ import java.util.concurrent.atomic.AtomicReference; import static com.mongodb.assertions.Assertions.isTrue; +import static com.mongodb.internal.connection.ServerAddressHelper.getSocketAddresses; /** *

This class is not part of the public API and may be removed or changed at any time

*/ public final class AsynchronousSocketChannelStream extends AsynchronousChannelStream { private final ServerAddress serverAddress; + private final InetAddressResolver inetAddressResolver; private final SocketSettings settings; - public AsynchronousSocketChannelStream(final ServerAddress serverAddress, final SocketSettings settings, - final PowerOfTwoBufferPool bufferProvider) { + public AsynchronousSocketChannelStream(final ServerAddress serverAddress, final InetAddressResolver inetAddressResolver, + final SocketSettings settings, final PowerOfTwoBufferPool bufferProvider) { super(serverAddress, settings, bufferProvider); this.serverAddress = serverAddress; + this.inetAddressResolver = inetAddressResolver; this.settings = settings; } - @SuppressWarnings("deprecation") @Override public void openAsync(final AsyncCompletionHandler handler) { isTrue("unopened", getChannel() == null); Queue socketAddressQueue; try { - socketAddressQueue = new LinkedList<>(serverAddress.getSocketAddresses()); + socketAddressQueue = new LinkedList<>(getSocketAddresses(serverAddress, inetAddressResolver)); } catch (Throwable t) { handler.failed(t); return; diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java index 546e6c7eba1..65dd6194dcd 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactory.java @@ -19,6 +19,7 @@ import com.mongodb.ServerAddress; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.spi.dns.InetAddressResolver; import static com.mongodb.assertions.Assertions.assertFalse; import static com.mongodb.assertions.Assertions.notNull; @@ -29,6 +30,7 @@ public class AsynchronousSocketChannelStreamFactory implements StreamFactory { private final PowerOfTwoBufferPool bufferProvider = PowerOfTwoBufferPool.DEFAULT; private final SocketSettings settings; + private final InetAddressResolver inetAddressResolver; /** * Create a new factory with the default {@code BufferProvider} and {@code AsynchronousChannelGroup}. @@ -36,14 +38,16 @@ public class AsynchronousSocketChannelStreamFactory implements StreamFactory { * @param settings the settings for the connection to a MongoDB server * @param sslSettings the settings for connecting via SSL */ - public AsynchronousSocketChannelStreamFactory(final SocketSettings settings, final SslSettings sslSettings) { + public AsynchronousSocketChannelStreamFactory(final InetAddressResolver inetAddressResolver, final SocketSettings settings, + final SslSettings sslSettings) { assertFalse(sslSettings.isEnabled()); + this.inetAddressResolver = inetAddressResolver; this.settings = notNull("settings", settings); } @Override public Stream create(final ServerAddress serverAddress) { - return new AsynchronousSocketChannelStream(serverAddress, settings, bufferProvider); + return new AsynchronousSocketChannelStream(serverAddress, inetAddressResolver, settings, bufferProvider); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java index a26b990d838..8810272b90d 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java @@ -18,6 +18,7 @@ import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.spi.dns.InetAddressResolver; /** * A {@code StreamFactoryFactory} implementation for AsynchronousSocketChannel-based streams. @@ -25,8 +26,14 @@ * @see java.nio.channels.AsynchronousSocketChannel */ public final class AsynchronousSocketChannelStreamFactoryFactory implements StreamFactoryFactory { + private final InetAddressResolver inetAddressResolver; + + public AsynchronousSocketChannelStreamFactoryFactory(final InetAddressResolver inetAddressResolver) { + this.inetAddressResolver = inetAddressResolver; + } + @Override public StreamFactory create(final SocketSettings socketSettings, final SslSettings sslSettings) { - return new AsynchronousSocketChannelStreamFactory(socketSettings, sslSettings); + return new AsynchronousSocketChannelStreamFactory(inetAddressResolver, socketSettings, sslSettings); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java index 47b0868e13f..38fa28d3b3d 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterFactory.java @@ -36,7 +36,6 @@ import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.lang.Nullable; import com.mongodb.spi.dns.DnsClient; -import com.mongodb.spi.dns.InetAddressResolver; import java.util.List; @@ -68,7 +67,7 @@ public Cluster createCluster(final ClusterSettings originalClusterSettings, fina @Nullable final String applicationName, @Nullable final MongoDriverInformation mongoDriverInformation, final List compressorList, @Nullable final ServerApi serverApi, - @Nullable final DnsClient dnsClient, @Nullable final InetAddressResolver inetAddressResolver) { + @Nullable final DnsClient dnsClient) { detectAndLogClusterEnvironment(originalClusterSettings); @@ -104,14 +103,14 @@ public Cluster createCluster(final ClusterSettings originalClusterSettings, fina ClusterableServerFactory serverFactory = new LoadBalancedClusterableServerFactory(serverSettings, connectionPoolSettings, internalConnectionPoolSettings, streamFactory, credential, loggerSettings, commandListener, applicationName, mongoDriverInformation != null ? mongoDriverInformation : MongoDriverInformation.builder().build(), - compressorList, serverApi, inetAddressResolver); + compressorList, serverApi); return new LoadBalancedCluster(clusterId, clusterSettings, serverFactory, dnsSrvRecordMonitorFactory); } else { ClusterableServerFactory serverFactory = new DefaultClusterableServerFactory(serverSettings, connectionPoolSettings, internalConnectionPoolSettings, streamFactory, heartbeatStreamFactory, credential, loggerSettings, commandListener, applicationName, mongoDriverInformation != null ? mongoDriverInformation : MongoDriverInformation.builder().build(), compressorList, - serverApi, inetAddressResolver); + serverApi); if (clusterSettings.getMode() == ClusterConnectionMode.SINGLE) { return new SingleServerCluster(clusterId, clusterSettings, serverFactory); diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java index 1e27891babc..d1a3c41c2d4 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultClusterableServerFactory.java @@ -30,7 +30,6 @@ import com.mongodb.event.ServerListener; import com.mongodb.internal.inject.SameObjectProvider; import com.mongodb.lang.Nullable; -import com.mongodb.spi.dns.InetAddressResolver; import java.util.List; @@ -54,8 +53,6 @@ public class DefaultClusterableServerFactory implements ClusterableServerFactory private final List compressorList; @Nullable private final ServerApi serverApi; - @Nullable - private final InetAddressResolver inetAddressResolver; public DefaultClusterableServerFactory( final ServerSettings serverSettings, final ConnectionPoolSettings connectionPoolSettings, @@ -65,8 +62,7 @@ public DefaultClusterableServerFactory( final LoggerSettings loggerSettings, @Nullable final CommandListener commandListener, @Nullable final String applicationName, @Nullable final MongoDriverInformation mongoDriverInformation, - final List compressorList, @Nullable final ServerApi serverApi, - @Nullable final InetAddressResolver inetAddressResolver) { + final List compressorList, @Nullable final ServerApi serverApi) { this.serverSettings = serverSettings; this.connectionPoolSettings = connectionPoolSettings; this.internalConnectionPoolSettings = internalConnectionPoolSettings; @@ -79,7 +75,6 @@ public DefaultClusterableServerFactory( this.mongoDriverInformation = mongoDriverInformation; this.compressorList = compressorList; this.serverApi = serverApi; - this.inetAddressResolver = inetAddressResolver; } @Override @@ -90,11 +85,11 @@ public ClusterableServer create(final Cluster cluster, final ServerAddress serve ServerMonitor serverMonitor = new DefaultServerMonitor(serverId, serverSettings, cluster.getClock(), // no credentials, compressor list, or command listener for the server monitor factory new InternalStreamConnectionFactory(clusterMode, true, heartbeatStreamFactory, null, applicationName, - mongoDriverInformation, emptyList(), loggerSettings, null, serverApi, inetAddressResolver), + mongoDriverInformation, emptyList(), loggerSettings, null, serverApi), clusterMode, serverApi, sdamProvider); ConnectionPool connectionPool = new DefaultConnectionPool(serverId, new InternalStreamConnectionFactory(clusterMode, streamFactory, credential, applicationName, - mongoDriverInformation, compressorList, loggerSettings, commandListener, serverApi, inetAddressResolver), + mongoDriverInformation, compressorList, loggerSettings, commandListener, serverApi), connectionPoolSettings, internalConnectionPoolSettings, sdamProvider); ServerListener serverListener = singleServerListener(serverSettings); SdamServerDescriptionManager sdam = new DefaultSdamServerDescriptionManager(cluster, serverId, serverListener, serverMonitor, diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultInetAddressResolver.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultInetAddressResolver.java new file mode 100644 index 00000000000..0f8158cf7d2 --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultInetAddressResolver.java @@ -0,0 +1,36 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.connection; + +import com.mongodb.spi.dns.InetAddressResolver; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.List; + +import static java.util.Arrays.asList; + +/** + *

This class is not part of the public API and may be removed or changed at any time

+ */ +public class DefaultInetAddressResolver implements InetAddressResolver { + + @Override + public List lookupByName(final String host) throws UnknownHostException { + return asList(InetAddress.getAllByName(host)); + } +} diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index d4ea8a7be06..d3cd2eab867 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -28,7 +28,6 @@ import com.mongodb.MongoSocketWriteException; import com.mongodb.RequestContext; import com.mongodb.ServerAddress; -import com.mongodb.UnixServerAddress; import com.mongodb.annotations.NotThreadSafe; import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.ClusterConnectionMode; @@ -48,7 +47,6 @@ import com.mongodb.internal.logging.StructuredLogger; import com.mongodb.internal.session.SessionContext; import com.mongodb.lang.Nullable; -import com.mongodb.spi.dns.InetAddressResolver; import org.bson.BsonBinaryReader; import org.bson.BsonDocument; import org.bson.ByteBuf; @@ -118,8 +116,6 @@ public class InternalStreamConnection implements InternalConnection { private final ConnectionGenerationSupplier connectionGenerationSupplier; private final StreamFactory streamFactory; private final InternalConnectionInitializer connectionInitializer; - private final InetAddressResolver inetAddressResolver; - private volatile ConnectionDescription description; private volatile ServerDescription initialServerDescription; private volatile Stream stream; @@ -150,10 +146,9 @@ static Set getSecuritySensitiveHelloCommands() { public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMode, final ServerId serverId, final ConnectionGenerationSupplier connectionGenerationSupplier, final StreamFactory streamFactory, final List compressorList, - final CommandListener commandListener, final InternalConnectionInitializer connectionInitializer, - @Nullable final InetAddressResolver inetAddressResolver) { + final CommandListener commandListener, final InternalConnectionInitializer connectionInitializer) { this(clusterConnectionMode, false, serverId, connectionGenerationSupplier, streamFactory, compressorList, - LoggerSettings.builder().build(), commandListener, connectionInitializer, inetAddressResolver); + LoggerSettings.builder().build(), commandListener, connectionInitializer); } public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMode, final boolean isMonitoringConnection, @@ -161,8 +156,7 @@ public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMod final ConnectionGenerationSupplier connectionGenerationSupplier, final StreamFactory streamFactory, final List compressorList, final LoggerSettings loggerSettings, - final CommandListener commandListener, final InternalConnectionInitializer connectionInitializer, - @Nullable final InetAddressResolver inetAddressResolver) { + final CommandListener commandListener, final InternalConnectionInitializer connectionInitializer) { this.clusterConnectionMode = clusterConnectionMode; this.isMonitoringConnection = isMonitoringConnection; this.serverId = notNull("serverId", serverId); @@ -179,7 +173,6 @@ public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMod .type(ServerType.UNKNOWN) .state(ServerConnectionState.CONNECTING) .build(); - this.inetAddressResolver = inetAddressResolver; if (clusterConnectionMode != ClusterConnectionMode.LOAD_BALANCED) { generation = connectionGenerationSupplier.getGeneration(); } @@ -203,7 +196,7 @@ public int getGeneration() { @Override public void open() { isTrue("Open already called", stream == null); - stream = streamFactory.create(getServerAddressWithResolver()); + stream = streamFactory.create(serverId.getAddress()); try { stream.open(); @@ -226,7 +219,7 @@ public void open() { public void openAsync(final SingleResultCallback callback) { isTrue("Open already called", stream == null, callback); try { - stream = streamFactory.create(getServerAddressWithResolver()); + stream = streamFactory.create(serverId.getAddress()); stream.openAsync(new AsyncCompletionHandler() { @Override public void completed(@Nullable final Void aVoid) { @@ -265,14 +258,6 @@ public void failed(final Throwable t) { } } - private ServerAddress getServerAddressWithResolver() { - if (serverId.getAddress() instanceof UnixServerAddress) { - return serverId.getAddress(); - } else { - return new ServerAddressWithResolver(serverId.getAddress(), inetAddressResolver); - } - } - private void initAfterHandshakeStart(final InternalConnectionInitializationDescription initializationDescription) { description = initializationDescription.getConnectionDescription(); initialServerDescription = initializationDescription.getServerDescription(); diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java index a74be77a7d0..6cf2453c187 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnectionFactory.java @@ -24,7 +24,6 @@ import com.mongodb.connection.ServerId; import com.mongodb.event.CommandListener; import com.mongodb.lang.Nullable; -import com.mongodb.spi.dns.InetAddressResolver; import org.bson.BsonDocument; import java.util.List; @@ -43,7 +42,6 @@ class InternalStreamConnectionFactory implements InternalConnectionFactory { private final CommandListener commandListener; @Nullable private final ServerApi serverApi; - private final InetAddressResolver inetAddressResolver; private final MongoCredentialWithCache credential; InternalStreamConnectionFactory(final ClusterConnectionMode clusterConnectionMode, @@ -51,10 +49,9 @@ class InternalStreamConnectionFactory implements InternalConnectionFactory { @Nullable final MongoCredentialWithCache credential, @Nullable final String applicationName, @Nullable final MongoDriverInformation mongoDriverInformation, final List compressorList, - final LoggerSettings loggerSettings, @Nullable final CommandListener commandListener, @Nullable final ServerApi serverApi, - @Nullable final InetAddressResolver inetAddressResolver) { + final LoggerSettings loggerSettings, @Nullable final CommandListener commandListener, @Nullable final ServerApi serverApi) { this(clusterConnectionMode, false, streamFactory, credential, applicationName, mongoDriverInformation, compressorList, - loggerSettings, commandListener, serverApi, inetAddressResolver); + loggerSettings, commandListener, serverApi); } InternalStreamConnectionFactory(final ClusterConnectionMode clusterConnectionMode, final boolean isMonitoringConnection, @@ -62,8 +59,7 @@ class InternalStreamConnectionFactory implements InternalConnectionFactory { @Nullable final MongoCredentialWithCache credential, @Nullable final String applicationName, @Nullable final MongoDriverInformation mongoDriverInformation, final List compressorList, - final LoggerSettings loggerSettings, @Nullable final CommandListener commandListener, @Nullable final ServerApi serverApi, - @Nullable final InetAddressResolver inetAddressResolver) { + final LoggerSettings loggerSettings, @Nullable final CommandListener commandListener, @Nullable final ServerApi serverApi) { this.clusterConnectionMode = clusterConnectionMode; this.isMonitoringConnection = isMonitoringConnection; this.streamFactory = notNull("streamFactory", streamFactory); @@ -71,7 +67,6 @@ class InternalStreamConnectionFactory implements InternalConnectionFactory { this.loggerSettings = loggerSettings; this.commandListener = commandListener; this.serverApi = serverApi; - this.inetAddressResolver = inetAddressResolver; this.clientMetadataDocument = createClientMetadataDocument(applicationName, mongoDriverInformation); this.credential = credential; } @@ -82,7 +77,7 @@ public InternalConnection create(final ServerId serverId, final ConnectionGenera return new InternalStreamConnection(clusterConnectionMode, isMonitoringConnection, serverId, connectionGenerationSupplier, streamFactory, compressorList, loggerSettings, commandListener, new InternalStreamConnectionInitializer(clusterConnectionMode, authenticator, clientMetadataDocument, compressorList, - serverApi), inetAddressResolver); + serverApi)); } private Authenticator createAuthenticator(final MongoCredentialWithCache credential) { diff --git a/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java b/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java index 418d7842088..0521e094cb1 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedClusterableServerFactory.java @@ -30,7 +30,6 @@ import com.mongodb.event.CommandListener; import com.mongodb.internal.inject.EmptyProvider; import com.mongodb.lang.Nullable; -import com.mongodb.spi.dns.InetAddressResolver; import java.util.List; @@ -52,7 +51,6 @@ public class LoadBalancedClusterableServerFactory implements ClusterableServerFa private final MongoDriverInformation mongoDriverInformation; private final List compressorList; private final ServerApi serverApi; - private final InetAddressResolver inetAddressResolver; public LoadBalancedClusterableServerFactory(final ServerSettings serverSettings, final ConnectionPoolSettings connectionPoolSettings, @@ -61,8 +59,7 @@ public LoadBalancedClusterableServerFactory(final ServerSettings serverSettings, final LoggerSettings loggerSettings, @Nullable final CommandListener commandListener, @Nullable final String applicationName, final MongoDriverInformation mongoDriverInformation, - final List compressorList, @Nullable final ServerApi serverApi, - @Nullable final InetAddressResolver inetAddressResolver) { + final List compressorList, @Nullable final ServerApi serverApi) { this.serverSettings = serverSettings; this.connectionPoolSettings = connectionPoolSettings; this.internalConnectionPoolSettings = internalConnectionPoolSettings; @@ -74,14 +71,13 @@ public LoadBalancedClusterableServerFactory(final ServerSettings serverSettings, this.mongoDriverInformation = mongoDriverInformation; this.compressorList = compressorList; this.serverApi = serverApi; - this.inetAddressResolver = inetAddressResolver; } @Override public ClusterableServer create(final Cluster cluster, final ServerAddress serverAddress) { ConnectionPool connectionPool = new DefaultConnectionPool(new ServerId(cluster.getClusterId(), serverAddress), new InternalStreamConnectionFactory(ClusterConnectionMode.LOAD_BALANCED, streamFactory, credential, applicationName, - mongoDriverInformation, compressorList, loggerSettings, commandListener, serverApi, inetAddressResolver), + mongoDriverInformation, compressorList, loggerSettings, commandListener, serverApi), connectionPoolSettings, internalConnectionPoolSettings, EmptyProvider.instance()); connectionPool.ready(); diff --git a/driver-core/src/main/com/mongodb/internal/connection/ServerAddressHelper.java b/driver-core/src/main/com/mongodb/internal/connection/ServerAddressHelper.java index e080fd150da..de004b748ab 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ServerAddressHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ServerAddressHelper.java @@ -17,8 +17,16 @@ package com.mongodb.internal.connection; +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoSocketException; import com.mongodb.ServerAddress; import com.mongodb.UnixServerAddress; +import com.mongodb.spi.dns.InetAddressResolver; + +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.List; +import java.util.stream.Collectors; /** *

This class is not part of the public API and may be removed or changed at any time

@@ -37,6 +45,21 @@ public static ServerAddress createServerAddress(final String host, final int por } } + public static InetAddressResolver getInetAddressResolver(final MongoClientSettings settings) { + InetAddressResolver inetAddressResolver = settings.getInetAddressResolver(); + return inetAddressResolver == null ? new DefaultInetAddressResolver() : inetAddressResolver; + } + + public static List getSocketAddresses(final ServerAddress serverAddress, final InetAddressResolver resolver) { + try { + return resolver.lookupByName(serverAddress.getHost()) + .stream() + .map(inetAddress -> new InetSocketAddress(inetAddress, serverAddress.getPort())).collect(Collectors.toList()); + } catch (UnknownHostException e) { + throw new MongoSocketException(e.getMessage(), serverAddress, e); + } + } + private ServerAddressHelper() { } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/ServerAddressWithResolver.java b/driver-core/src/main/com/mongodb/internal/connection/ServerAddressWithResolver.java deleted file mode 100644 index e86d1fca189..00000000000 --- a/driver-core/src/main/com/mongodb/internal/connection/ServerAddressWithResolver.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.connection; - -import com.mongodb.MongoSocketException; -import com.mongodb.ServerAddress; -import com.mongodb.lang.Nullable; -import com.mongodb.spi.dns.InetAddressResolver; -import com.mongodb.spi.dns.InetAddressResolverProvider; - -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.util.List; -import java.util.Objects; -import java.util.ServiceLoader; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - -final class ServerAddressWithResolver extends ServerAddress { - private static final long serialVersionUID = 1; - - @Nullable - private static final InetAddressResolver DEFAULT_INET_ADDRESS_RESOLVER; - - static { - DEFAULT_INET_ADDRESS_RESOLVER = StreamSupport.stream(ServiceLoader.load(InetAddressResolverProvider.class).spliterator(), false) - .findFirst() - .map(InetAddressResolverProvider::create) - .orElse(null); - } - - @Nullable - private final transient InetAddressResolver resolver; - - ServerAddressWithResolver(final ServerAddress serverAddress, @Nullable final InetAddressResolver inetAddressResolver) { - super(serverAddress.getHost(), serverAddress.getPort()); - this.resolver = inetAddressResolver == null ? DEFAULT_INET_ADDRESS_RESOLVER : inetAddressResolver; - } - - @SuppressWarnings("deprecation") - @Override - public InetSocketAddress getSocketAddress() { - if (resolver == null) { - return super.getSocketAddress(); - } - - return getSocketAddresses().get(0); - } - - @SuppressWarnings("deprecation") - @Override - public List getSocketAddresses() { - if (resolver == null) { - return super.getSocketAddresses(); - } - try { - return resolver.lookupByName(getHost()) - .stream() - .map(inetAddress -> new InetSocketAddress(inetAddress, getPort())).collect(Collectors.toList()); - } catch (UnknownHostException e) { - throw new MongoSocketException(e.getMessage(), this, e); - } - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - ServerAddressWithResolver that = (ServerAddressWithResolver) o; - return Objects.equals(resolver, that.resolver); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), resolver); - } -} diff --git a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java index 0e1824d7f8a..a7f71314757 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java @@ -24,6 +24,7 @@ import com.mongodb.connection.ProxySettings; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.spi.dns.InetAddressResolver; import org.bson.ByteBuf; import javax.net.SocketFactory; @@ -41,6 +42,7 @@ import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.notNull; +import static com.mongodb.internal.connection.ServerAddressHelper.getSocketAddresses; import static com.mongodb.internal.connection.SocketStreamHelper.configureSocket; import static com.mongodb.internal.connection.SslHelper.configureSslSocket; import static com.mongodb.internal.thread.InterruptionUtil.translateInterruptedException; @@ -51,6 +53,7 @@ */ public class SocketStream implements Stream { private final ServerAddress address; + private final InetAddressResolver inetAddressResolver; private final SocketSettings settings; private final SslSettings sslSettings; private final SocketFactory socketFactory; @@ -60,13 +63,15 @@ public class SocketStream implements Stream { private volatile InputStream inputStream; private volatile boolean isClosed; - public SocketStream(final ServerAddress address, final SocketSettings settings, final SslSettings sslSettings, - final SocketFactory socketFactory, final BufferProvider bufferProvider) { + public SocketStream(final ServerAddress address, final InetAddressResolver inetAddressResolver, + final SocketSettings settings, final SslSettings sslSettings, + final SocketFactory socketFactory, final BufferProvider bufferProvider) { this.address = notNull("address", address); this.settings = notNull("settings", settings); this.sslSettings = notNull("sslSettings", sslSettings); this.socketFactory = notNull("socketFactory", socketFactory); this.bufferProvider = notNull("bufferProvider", bufferProvider); + this.inetAddressResolver = inetAddressResolver; } @Override @@ -82,7 +87,6 @@ public void open() { } } - @SuppressWarnings("deprecation") protected Socket initializeSocket() throws IOException { ProxySettings proxySettings = settings.getProxySettings(); if (proxySettings.isProxyEnabled()) { @@ -94,7 +98,7 @@ protected Socket initializeSocket() throws IOException { return initializeSocketOverSocksProxy(); } - Iterator inetSocketAddresses = address.getSocketAddresses().iterator(); + Iterator inetSocketAddresses = getSocketAddresses(address, inetAddressResolver).iterator(); while (inetSocketAddresses.hasNext()) { Socket socket = socketFactory.createSocket(); try { diff --git a/driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java index d50e9c9313a..793fc8b3dc4 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SocketStreamFactory.java @@ -21,6 +21,7 @@ import com.mongodb.UnixServerAddress; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.spi.dns.InetAddressResolver; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; @@ -33,6 +34,7 @@ * Factory for creating instances of {@code SocketStream}. */ public class SocketStreamFactory implements StreamFactory { + private final InetAddressResolver inetAddressResolver; private final SocketSettings settings; private final SslSettings sslSettings; private final BufferProvider bufferProvider = PowerOfTwoBufferPool.DEFAULT; @@ -40,10 +42,13 @@ public class SocketStreamFactory implements StreamFactory { /** * Creates a new factory with the given settings for connecting to servers and the given SSL settings * - * @param settings the SocketSettings for connecting to a MongoDB server - * @param sslSettings whether SSL is enabled. + * @param inetAddressResolver resolver + * @param settings the SocketSettings for connecting to a MongoDB server + * @param sslSettings whether SSL is enabled. */ - public SocketStreamFactory(final SocketSettings settings, final SslSettings sslSettings) { + public SocketStreamFactory(final InetAddressResolver inetAddressResolver, final SocketSettings settings, + final SslSettings sslSettings) { + this.inetAddressResolver = inetAddressResolver; this.settings = notNull("settings", settings); this.sslSettings = notNull("sslSettings", sslSettings); } @@ -58,9 +63,11 @@ public Stream create(final ServerAddress serverAddress) { stream = new UnixSocketChannelStream((UnixServerAddress) serverAddress, settings, sslSettings, bufferProvider); } else { if (sslSettings.isEnabled()) { - stream = new SocketStream(serverAddress, settings, sslSettings, getSslContext().getSocketFactory(), bufferProvider); + stream = new SocketStream(serverAddress, inetAddressResolver, settings, sslSettings, getSslContext().getSocketFactory(), + bufferProvider); } else { - stream = new SocketStream(serverAddress, settings, sslSettings, SocketFactory.getDefault(), bufferProvider); + stream = new SocketStream(serverAddress, inetAddressResolver, settings, sslSettings, SocketFactory.getDefault(), + bufferProvider); } } return stream; diff --git a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java index dd08aea9ace..ef40c164cba 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryHelper.java @@ -20,14 +20,18 @@ import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.TransportSettings; import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; +import com.mongodb.spi.dns.InetAddressResolver; /** *

This class is not part of the public API and may be removed or changed at any time

*/ public final class StreamFactoryHelper { - public static StreamFactoryFactory getStreamFactoryFactoryFromSettings(final TransportSettings transportSettings) { + public static StreamFactoryFactory getStreamFactoryFactoryFromSettings(final TransportSettings transportSettings, + final InetAddressResolver inetAddressResolver) { if (transportSettings instanceof NettyTransportSettings) { - return NettyStreamFactoryFactory.builder().applySettings((NettyTransportSettings) transportSettings).build(); + return NettyStreamFactoryFactory.builder().applySettings((NettyTransportSettings) transportSettings) + .inetAddressResolver(inetAddressResolver) + .build(); } else { throw new MongoClientException("Unsupported transport settings: " + transportSettings.getClass().getName()); } diff --git a/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java index 70db0cced2c..4f6bacef191 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java @@ -30,6 +30,7 @@ import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.lang.Nullable; +import com.mongodb.spi.dns.InetAddressResolver; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; @@ -50,6 +51,7 @@ import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.isTrue; +import static com.mongodb.internal.connection.ServerAddressHelper.getSocketAddresses; import static com.mongodb.internal.connection.SslHelper.enableHostNameVerification; import static com.mongodb.internal.connection.SslHelper.enableSni; import static java.util.Optional.ofNullable; @@ -64,11 +66,13 @@ public class TlsChannelStreamFactoryFactory implements StreamFactoryFactory, Clo private final SelectorMonitor selectorMonitor; private final AsynchronousTlsChannelGroup group; private final PowerOfTwoBufferPool bufferPool = PowerOfTwoBufferPool.DEFAULT; + private final InetAddressResolver inetAddressResolver; /** * Construct a new instance */ - public TlsChannelStreamFactoryFactory() { + public TlsChannelStreamFactoryFactory(final InetAddressResolver inetAddressResolver) { + this.inetAddressResolver = inetAddressResolver; this.group = new AsynchronousTlsChannelGroup(); selectorMonitor = new SelectorMonitor(); selectorMonitor.start(); @@ -77,7 +81,8 @@ public TlsChannelStreamFactoryFactory() { @Override public StreamFactory create(final SocketSettings socketSettings, final SslSettings sslSettings) { assertTrue(sslSettings.isEnabled()); - return serverAddress -> new TlsChannelStream(serverAddress, socketSettings, sslSettings, bufferPool, group, selectorMonitor); + return serverAddress -> new TlsChannelStream(serverAddress, inetAddressResolver, socketSettings, sslSettings, bufferPool, group, + selectorMonitor); } @Override @@ -161,12 +166,14 @@ private static class TlsChannelStream extends AsynchronousChannelStream { private final AsynchronousTlsChannelGroup group; private final SelectorMonitor selectorMonitor; + private final InetAddressResolver inetAddressResolver; private final SslSettings sslSettings; - TlsChannelStream(final ServerAddress serverAddress, final SocketSettings settings, final SslSettings sslSettings, - final PowerOfTwoBufferPool bufferProvider, final AsynchronousTlsChannelGroup group, - final SelectorMonitor selectorMonitor) { + TlsChannelStream(final ServerAddress serverAddress, final InetAddressResolver inetAddressResolver, + final SocketSettings settings, final SslSettings sslSettings, final PowerOfTwoBufferPool bufferProvider, + final AsynchronousTlsChannelGroup group, final SelectorMonitor selectorMonitor) { super(serverAddress, settings, bufferProvider); + this.inetAddressResolver = inetAddressResolver; this.sslSettings = sslSettings; this.group = group; this.selectorMonitor = selectorMonitor; @@ -177,7 +184,6 @@ public boolean supportsAdditionalTimeout() { return true; } - @SuppressWarnings("deprecation") @Override public void openAsync(final AsyncCompletionHandler handler) { isTrue("unopened", getChannel() == null); @@ -194,7 +200,7 @@ public void openAsync(final AsyncCompletionHandler handler) { socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, getSettings().getSendBufferSize()); } - socketChannel.connect(getServerAddress().getSocketAddress()); + socketChannel.connect(getSocketAddresses(getServerAddress(), inetAddressResolver).get(0)); selectorMonitor.register(socketChannel, () -> { try { diff --git a/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java b/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java index 1e776481bdd..e80909a2c79 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/UnixSocketChannelStream.java @@ -34,13 +34,12 @@ public class UnixSocketChannelStream extends SocketStream { public UnixSocketChannelStream(final UnixServerAddress address, final SocketSettings settings, final SslSettings sslSettings, final BufferProvider bufferProvider) { - super(address, settings, sslSettings, SocketFactory.getDefault(), bufferProvider); + super(address, new DefaultInetAddressResolver(), settings, sslSettings, SocketFactory.getDefault(), bufferProvider); this.address = address; } - @SuppressWarnings("deprecation") @Override protected Socket initializeSocket() throws IOException { - return UnixSocketChannel.open((UnixSocketAddress) address.getUnixSocketAddress()).socket(); + return UnixSocketChannel.open(new UnixSocketAddress(address.getHost())).socket(); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java index 786b191ffdc..8d9f9b65372 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java @@ -29,6 +29,7 @@ import com.mongodb.connection.SslSettings; import com.mongodb.internal.connection.Stream; import com.mongodb.lang.Nullable; +import com.mongodb.spi.dns.InetAddressResolver; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.CompositeByteBuf; @@ -68,6 +69,7 @@ import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.internal.Locks.withLock; +import static com.mongodb.internal.connection.ServerAddressHelper.getSocketAddresses; import static com.mongodb.internal.connection.SslHelper.enableHostNameVerification; import static com.mongodb.internal.connection.SslHelper.enableSni; import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException; @@ -110,6 +112,7 @@ final class NettyStream implements Stream { private static final byte NO_SCHEDULE_TIME = 0; private final ServerAddress address; + private final InetAddressResolver inetAddressResolver; private final SocketSettings settings; private final SslSettings sslSettings; private final EventLoopGroup workerGroup; @@ -136,10 +139,12 @@ final class NettyStream implements Stream { private ReadTimeoutTask readTimeoutTask; private long readTimeoutMillis = NO_SCHEDULE_TIME; - NettyStream(final ServerAddress address, final SocketSettings settings, final SslSettings sslSettings, final EventLoopGroup workerGroup, - final Class socketChannelClass, final ByteBufAllocator allocator, - @Nullable final SslContext sslContext) { + NettyStream(final ServerAddress address, final InetAddressResolver inetAddressResolver, final SocketSettings settings, + final SslSettings sslSettings, final EventLoopGroup workerGroup, + final Class socketChannelClass, final ByteBufAllocator allocator, + @Nullable final SslContext sslContext) { this.address = address; + this.inetAddressResolver = inetAddressResolver; this.settings = settings; this.sslSettings = sslSettings; this.workerGroup = workerGroup; @@ -166,7 +171,7 @@ public void openAsync(final AsyncCompletionHandler handler) { Queue socketAddressQueue; try { - socketAddressQueue = new LinkedList<>(address.getSocketAddresses()); + socketAddressQueue = new LinkedList<>(getSocketAddresses(address, inetAddressResolver)); } catch (Throwable t) { handler.failed(t); return; diff --git a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java index 91b5e11d863..ace80a347a2 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactory.java @@ -19,9 +19,11 @@ import com.mongodb.ServerAddress; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.internal.connection.DefaultInetAddressResolver; import com.mongodb.internal.connection.Stream; import com.mongodb.internal.connection.StreamFactory; import com.mongodb.lang.Nullable; +import com.mongodb.spi.dns.InetAddressResolver; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.EventLoopGroup; @@ -33,9 +35,10 @@ import static com.mongodb.assertions.Assertions.notNull; /** - * A StreamFactory for Streams based on Netty 4.x. + * A StreamFactory for Streams based on Netty 4.x. */ public class NettyStreamFactory implements StreamFactory { + private final InetAddressResolver inetAddressResolver; private final SocketSettings settings; private final SslSettings sslSettings; private final EventLoopGroup eventLoopGroup; @@ -55,10 +58,10 @@ public class NettyStreamFactory implements StreamFactory { * @param sslContext the Netty {@link SslContext} * as specified by {@link NettyStreamFactoryFactory.Builder#sslContext(SslContext)}. */ - public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSettings, - final EventLoopGroup eventLoopGroup, final Class socketChannelClass, - final ByteBufAllocator allocator, - @Nullable final SslContext sslContext) { + public NettyStreamFactory(final InetAddressResolver inetAddressResolver, final SocketSettings settings, + final SslSettings sslSettings, final EventLoopGroup eventLoopGroup, final Class socketChannelClass, + final ByteBufAllocator allocator, @Nullable final SslContext sslContext) { + this.inetAddressResolver = inetAddressResolver; this.settings = notNull("settings", settings); this.sslSettings = notNull("sslSettings", sslSettings); this.eventLoopGroup = notNull("eventLoopGroup", eventLoopGroup); @@ -79,7 +82,7 @@ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSe public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSettings, final EventLoopGroup eventLoopGroup, final Class socketChannelClass, final ByteBufAllocator allocator) { - this(settings, sslSettings, eventLoopGroup, socketChannelClass, allocator, null); + this(new DefaultInetAddressResolver(), settings, sslSettings, eventLoopGroup, socketChannelClass, allocator, null); } /** @@ -118,7 +121,8 @@ public NettyStreamFactory(final SocketSettings settings, final SslSettings sslSe @Override public Stream create(final ServerAddress serverAddress) { - return new NettyStream(serverAddress, settings, sslSettings, eventLoopGroup, socketChannelClass, allocator, sslContext); + return new NettyStream(serverAddress, inetAddressResolver, settings, sslSettings, eventLoopGroup, socketChannelClass, allocator, + sslContext); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java index bc72e7514e9..d1f6e52f356 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java @@ -19,10 +19,11 @@ import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.connection.StreamFactory; import com.mongodb.internal.connection.StreamFactoryFactory; -import com.mongodb.internal.VisibleForTesting; import com.mongodb.lang.Nullable; +import com.mongodb.spi.dns.InetAddressResolver; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; @@ -41,7 +42,7 @@ import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; /** - * A {@code StreamFactoryFactory} implementation for Netty-based streams. + * A {@code StreamFactoryFactory} implementation for Netty-based streams. */ public final class NettyStreamFactoryFactory implements StreamFactoryFactory { @@ -50,6 +51,7 @@ public final class NettyStreamFactoryFactory implements StreamFactoryFactory { private final ByteBufAllocator allocator; @Nullable private final SslContext sslContext; + private final InetAddressResolver inetAddressResolver; /** * Gets a builder for an instance of {@code NettyStreamFactoryFactory}. @@ -89,6 +91,7 @@ public static final class Builder { private EventLoopGroup eventLoopGroup; @Nullable private SslContext sslContext; + private InetAddressResolver inetAddressResolver; private Builder() { } @@ -179,6 +182,11 @@ public Builder sslContext(final SslContext sslContext) { return this; } + public Builder inetAddressResolver(final InetAddressResolver inetAddressResolver) { + this.inetAddressResolver = inetAddressResolver; + return this; + } + /** * Build an instance of {@code NettyStreamFactoryFactory}. * @return factory of the netty stream factory @@ -190,7 +198,8 @@ public NettyStreamFactoryFactory build() { @Override public StreamFactory create(final SocketSettings socketSettings, final SslSettings sslSettings) { - return new NettyStreamFactory(socketSettings, sslSettings, eventLoopGroup, socketChannelClass, allocator, sslContext); + return new NettyStreamFactory(inetAddressResolver, socketSettings, sslSettings, eventLoopGroup, socketChannelClass, allocator, + sslContext); } @Override @@ -203,22 +212,13 @@ public boolean equals(final Object o) { } NettyStreamFactoryFactory that = (NettyStreamFactoryFactory) o; return Objects.equals(eventLoopGroup, that.eventLoopGroup) && Objects.equals(socketChannelClass, that.socketChannelClass) - && Objects.equals(allocator, that.allocator) && Objects.equals(sslContext, that.sslContext); + && Objects.equals(allocator, that.allocator) && Objects.equals(sslContext, that.sslContext) + && Objects.equals(inetAddressResolver, that.inetAddressResolver); } @Override public int hashCode() { - return Objects.hash(eventLoopGroup, socketChannelClass, allocator, sslContext); - } - - @Override - public String toString() { - return "NettyStreamFactoryFactory{" - + "eventLoopGroup=" + eventLoopGroup - + ", socketChannelClass=" + socketChannelClass - + ", allocator=" + allocator - + ", sslContext=" + sslContext - + '}'; + return Objects.hash(eventLoopGroup, socketChannelClass, allocator, sslContext, inetAddressResolver); } private NettyStreamFactoryFactory(final Builder builder) { @@ -226,5 +226,6 @@ private NettyStreamFactoryFactory(final Builder builder) { socketChannelClass = builder.socketChannelClass == null ? NioSocketChannel.class : builder.socketChannelClass; eventLoopGroup = builder.eventLoopGroup == null ? new NioEventLoopGroup() : builder.eventLoopGroup; sslContext = builder.sslContext; + inetAddressResolver = builder.inetAddressResolver; } } diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index b9df4268735..fdf2edae906 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -17,23 +17,18 @@ package com.mongodb; import com.mongodb.async.FutureResultCallback; -import com.mongodb.connection.NettyTransportSettings; -import com.mongodb.connection.TransportSettings; -import com.mongodb.internal.connection.AsynchronousSocketChannelStreamFactory; import com.mongodb.connection.ClusterConnectionMode; import com.mongodb.connection.ClusterDescription; import com.mongodb.connection.ClusterSettings; import com.mongodb.connection.ClusterType; import com.mongodb.connection.ConnectionPoolSettings; +import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.ServerDescription; import com.mongodb.connection.ServerSettings; import com.mongodb.connection.ServerVersion; import com.mongodb.connection.SocketSettings; -import com.mongodb.internal.connection.SocketStreamFactory; import com.mongodb.connection.SslSettings; -import com.mongodb.internal.connection.StreamFactory; -import com.mongodb.internal.connection.StreamFactoryFactory; -import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; +import com.mongodb.connection.TransportSettings; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; @@ -50,10 +45,16 @@ import com.mongodb.internal.binding.SessionBinding; import com.mongodb.internal.binding.SingleConnectionBinding; import com.mongodb.internal.connection.AsyncConnection; +import com.mongodb.internal.connection.AsynchronousSocketChannelStreamFactory; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.DefaultClusterFactory; +import com.mongodb.internal.connection.DefaultInetAddressResolver; import com.mongodb.internal.connection.InternalConnectionPoolSettings; import com.mongodb.internal.connection.MongoCredentialWithCache; +import com.mongodb.internal.connection.SocketStreamFactory; +import com.mongodb.internal.connection.StreamFactory; +import com.mongodb.internal.connection.StreamFactoryFactory; +import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; import com.mongodb.internal.operation.AsyncReadOperation; import com.mongodb.internal.operation.AsyncWriteOperation; @@ -257,7 +258,7 @@ public static synchronized ConnectionString getConnectionString() { // Figure out what the connection string should be Cluster cluster = createCluster(new ConnectionString(DEFAULT_URI), - new SocketStreamFactory(SocketSettings.builder().build(), SslSettings.builder().build())); + new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), SslSettings.builder().build())); try { BsonDocument helloResult = new CommandReadOperation<>("admin", new BsonDocument(LEGACY_HELLO, new BsonInt32(1)), new BsonDocumentCodec()).execute(new ClusterBinding(cluster, @@ -367,7 +368,7 @@ public static AsyncReadWriteBinding getAsyncBinding(final Cluster cluster, final public static synchronized Cluster getCluster() { if (cluster == null) { - cluster = createCluster(new SocketStreamFactory(getSocketSettings(), getSslSettings())); + cluster = createCluster(new SocketStreamFactory(new DefaultInetAddressResolver(), getSocketSettings(), getSslSettings())); } return cluster; } @@ -397,7 +398,7 @@ private static Cluster createCluster(final MongoCredential credential, final Str ServerSettings.builder().build(), ConnectionPoolSettings.builder().maxSize(1).build(), InternalConnectionPoolSettings.builder().build(), streamFactory, streamFactory, credential, LoggerSettings.builder().build(), null, null, null, - Collections.emptyList(), getServerApi(), null, null); + Collections.emptyList(), getServerApi(), null); } private static Cluster createCluster(final ConnectionString connectionString, final StreamFactory streamFactory) { @@ -406,23 +407,24 @@ private static Cluster createCluster(final ConnectionString connectionString, fi ConnectionPoolSettings.builder().applyConnectionString(connectionString).build(), InternalConnectionPoolSettings.builder().build(), streamFactory, - new SocketStreamFactory(SocketSettings.builder().readTimeout(5, SECONDS).build(), getSslSettings(connectionString)), + new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().readTimeout(5, SECONDS).build(), + getSslSettings(connectionString)), connectionString.getCredential(), LoggerSettings.builder().build(), null, null, null, - connectionString.getCompressorList(), getServerApi(), null, null); + connectionString.getCompressorList(), getServerApi(), null); } public static StreamFactory getStreamFactory() { - return new SocketStreamFactory(SocketSettings.builder().build(), getSslSettings()); + return new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()); } public static StreamFactory getAsyncStreamFactory() { TransportSettings transportSettings = getOverriddenTransportSettings(); if (transportSettings == null) { // use NIO2 if (getSslSettings().isEnabled()) { - return new TlsChannelStreamFactoryFactory().create(getSocketSettings(), getSslSettings()); + return new TlsChannelStreamFactoryFactory(new DefaultInetAddressResolver()).create(getSocketSettings(), getSslSettings()); } else { - return new AsynchronousSocketChannelStreamFactory(getSocketSettings(), getSslSettings()); + return new AsynchronousSocketChannelStreamFactory(new DefaultInetAddressResolver(), getSocketSettings(), getSslSettings()); } } else { StreamFactoryFactory overriddenStreamFactoryFactory = NettyStreamFactoryFactory.builder() diff --git a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy index 7ce5e9dd72f..74dad9221c0 100644 --- a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy @@ -1,15 +1,19 @@ package com.mongodb.connection.netty -import com.mongodb.internal.connection.netty.NettyStreamFactory -import util.spock.annotations.Slow import com.mongodb.MongoSocketException import com.mongodb.MongoSocketOpenException import com.mongodb.ServerAddress import com.mongodb.connection.AsyncCompletionHandler import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings +import com.mongodb.internal.connection.netty.NettyStreamFactory +import com.mongodb.spi.dns.InetAddressResolver +import io.netty.buffer.PooledByteBufAllocator +import io.netty.channel.nio.NioEventLoopGroup +import io.netty.channel.socket.nio.NioSocketChannel import spock.lang.IgnoreIf import spock.lang.Specification +import util.spock.annotations.Slow import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @@ -22,19 +26,20 @@ class NettyStreamSpecification extends Specification { @IgnoreIf({ getSslSettings().isEnabled() }) def 'should successfully connect with working ip address group'() { given: - def port = 27017 SocketSettings socketSettings = SocketSettings.builder().connectTimeout(1000, TimeUnit.MILLISECONDS).build() SslSettings sslSettings = SslSettings.builder().build() - def factory = new NettyStreamFactory(socketSettings, sslSettings) - - def inetAddresses = [new InetSocketAddress(InetAddress.getByName('192.168.255.255'), port), - new InetSocketAddress(InetAddress.getByName('1.2.3.4'), port), - new InetSocketAddress(InetAddress.getByName('127.0.0.1'), port)] - - def serverAddress = Stub(ServerAddress) - serverAddress.getSocketAddresses() >> inetAddresses + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + [InetAddress.getByName('192.168.255.255'), + InetAddress.getByName('1.2.3.4'), + InetAddress.getByName('127.0.0.1')] + } + } + def factory = new NettyStreamFactory(inetAddressResolver, socketSettings, sslSettings, new NioEventLoopGroup(), + NioSocketChannel, PooledByteBufAllocator.DEFAULT, null) - def stream = factory.create(serverAddress) + def stream = factory.create(new ServerAddress()) when: stream.open() @@ -47,19 +52,20 @@ class NettyStreamSpecification extends Specification { @IgnoreIf({ getSslSettings().isEnabled() }) def 'should throw exception with non-working ip address group'() { given: - def port = 27017 SocketSettings socketSettings = SocketSettings.builder().connectTimeout(1000, TimeUnit.MILLISECONDS).build() SslSettings sslSettings = SslSettings.builder().build() - def factory = new NettyStreamFactory(socketSettings, sslSettings) - - def inetAddresses = [new InetSocketAddress(InetAddress.getByName('192.168.255.255'), port), - new InetSocketAddress(InetAddress.getByName('1.2.3.4'), port), - new InetSocketAddress(InetAddress.getByName('1.2.3.5'), port)] - - def serverAddress = Stub(ServerAddress) - serverAddress.getSocketAddresses() >> inetAddresses + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + [InetAddress.getByName('192.168.255.255'), + InetAddress.getByName('1.2.3.4'), + InetAddress.getByName('1.2.3.5')] + } + } + def factory = new NettyStreamFactory(inetAddressResolver, socketSettings, sslSettings, new NioEventLoopGroup(), + NioSocketChannel, PooledByteBufAllocator.DEFAULT, null) - def stream = factory.create(serverAddress) + def stream = factory.create(new ServerAddress()) when: stream.open() @@ -75,8 +81,17 @@ class NettyStreamSpecification extends Specification { def exception = new MongoSocketException('Temporary failure in name resolution', serverAddress) serverAddress.getSocketAddresses() >> { throw exception } - def stream = new NettyStreamFactory(SocketSettings.builder().connectTimeout(1000, TimeUnit.MILLISECONDS).build(), - SslSettings.builder().build()).create(serverAddress) + SocketSettings socketSettings = SocketSettings.builder().connectTimeout(1000, TimeUnit.MILLISECONDS).build() + SslSettings sslSettings = SslSettings.builder().build() + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + throw exception + } + } + def stream = new NettyStreamFactory(inetAddressResolver, socketSettings, sslSettings, new NioEventLoopGroup(), + NioSocketChannel, PooledByteBufAllocator.DEFAULT, null) + .create(new ServerAddress()) def callback = new CallbackErrorHolder() when: diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy index 2709aa09e16..b857c2574bd 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy @@ -6,6 +6,7 @@ import com.mongodb.ServerAddress import com.mongodb.connection.AsyncCompletionHandler import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings +import com.mongodb.spi.dns.InetAddressResolver import spock.lang.IgnoreIf import spock.lang.Specification import util.spock.annotations.Slow @@ -21,18 +22,21 @@ class AsyncSocketChannelStreamSpecification extends Specification { @IgnoreIf({ getSslSettings().isEnabled() }) def 'should successfully connect with working ip address list'() { given: - def port = 27017 def socketSettings = SocketSettings.builder().connectTimeout(100, MILLISECONDS).build() def sslSettings = SslSettings.builder().build() - def factoryFactory = new AsynchronousSocketChannelStreamFactoryFactory() - def factory = factoryFactory.create(socketSettings, sslSettings) - def inetAddresses = [new InetSocketAddress(InetAddress.getByName('192.168.255.255'), port), - new InetSocketAddress(InetAddress.getByName('127.0.0.1'), port)] - def serverAddress = Stub(ServerAddress) - serverAddress.getSocketAddresses() >> inetAddresses + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + [InetAddress.getByName('192.168.255.255'), + InetAddress.getByName('127.0.0.1')] + } + } - def stream = factory.create(serverAddress) + def factoryFactory = new AsynchronousSocketChannelStreamFactoryFactory(inetAddressResolver) + def factory = factoryFactory.create(socketSettings, sslSettings) + + def stream = factory.create(new ServerAddress('host1')) when: stream.open() @@ -45,20 +49,20 @@ class AsyncSocketChannelStreamSpecification extends Specification { @IgnoreIf({ getSslSettings().isEnabled() }) def 'should fail to connect with non-working ip address list'() { given: - def port = 27017 def socketSettings = SocketSettings.builder().connectTimeout(100, MILLISECONDS).build() def sslSettings = SslSettings.builder().build() - def factoryFactory = new AsynchronousSocketChannelStreamFactoryFactory() - - def factory = factoryFactory.create(socketSettings, sslSettings) - - def inetAddresses = [new InetSocketAddress(InetAddress.getByName('192.168.255.255'), port), - new InetSocketAddress(InetAddress.getByName('1.2.3.4'), port)] - def serverAddress = Stub(ServerAddress) - serverAddress.getSocketAddresses() >> inetAddresses + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + [InetAddress.getByName('192.168.255.255'), + InetAddress.getByName('1.2.3.4')] + } + } - def stream = factory.create(serverAddress) + def factoryFactory = new AsynchronousSocketChannelStreamFactoryFactory(inetAddressResolver) + def factory = factoryFactory.create(socketSettings, sslSettings) + def stream = factory.create(new ServerAddress()) when: stream.open() @@ -70,11 +74,16 @@ class AsyncSocketChannelStreamSpecification extends Specification { @IgnoreIf({ getSslSettings().isEnabled() }) def 'should fail AsyncCompletionHandler if name resolution fails'() { given: - def serverAddress = Stub(ServerAddress) + def serverAddress = new ServerAddress() def exception = new MongoSocketException('Temporary failure in name resolution', serverAddress) - serverAddress.getSocketAddresses() >> { throw exception } - def stream = new AsynchronousSocketChannelStream(serverAddress, + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + throw exception + } + } + def stream = new AsynchronousSocketChannelStream(serverAddress, inetAddressResolver, SocketSettings.builder().connectTimeout(100, MILLISECONDS).build(), new PowerOfTwoBufferPool()) def callback = new CallbackErrorHolder() diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy index aa8156dd88c..858b5ce6c84 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy @@ -51,8 +51,8 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification def 'should throw a MongoSocketOpenException when the AsynchronousSocket Stream fails to open'() { given: def connection = new InternalStreamConnectionFactory(ClusterConnectionMode.SINGLE, - new AsynchronousSocketChannelStreamFactory(openSocketSettings, getSslSettings()), getCredentialWithCache(), null, null, - [], LoggerSettings.builder().build(), null, getServerApi(), null) + new AsynchronousSocketChannelStreamFactory(new DefaultInetAddressResolver(), openSocketSettings, getSslSettings()), + getCredentialWithCache(), null, null, [], LoggerSettings.builder().build(), null, getServerApi()) .create(new ServerId(new ClusterId(), new ServerAddress(new InetSocketAddress('192.168.255.255', 27017)))) when: @@ -66,8 +66,9 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification def 'should throw a MongoSocketReadTimeoutException with the AsynchronousSocket stream'() { given: def connection = new InternalStreamConnectionFactory(ClusterConnectionMode.SINGLE, - new AsynchronousSocketChannelStreamFactory(readSocketSettings, getSslSettings()), getCredentialWithCache(), null, null, - [], LoggerSettings.builder().build(), null, getServerApi(), null).create(new ServerId(new ClusterId(), getPrimary())) + new AsynchronousSocketChannelStreamFactory(new DefaultInetAddressResolver(), readSocketSettings, getSslSettings()), + getCredentialWithCache(), null, null, + [], LoggerSettings.builder().build(), null, getServerApi()).create(new ServerId(new ClusterId(), getPrimary())) connection.open() getCollectionHelper().insertDocuments(new BsonDocument('_id', new BsonInt32(1))) @@ -88,7 +89,7 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification given: def connection = new InternalStreamConnectionFactory(ClusterConnectionMode.SINGLE, new NettyStreamFactory(openSocketSettings, getSslSettings()), getCredentialWithCache(), null, null, - [], LoggerSettings.builder().build(), null, getServerApi(), null).create(new ServerId(new ClusterId(), + [], LoggerSettings.builder().build(), null, getServerApi()).create(new ServerId(new ClusterId(), new ServerAddress(new InetSocketAddress('192.168.255.255', 27017)))) when: @@ -103,7 +104,7 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification given: def connection = new InternalStreamConnectionFactory(ClusterConnectionMode.SINGLE, new NettyStreamFactory(readSocketSettings, getSslSettings()), getCredentialWithCache(), null, null, - [], LoggerSettings.builder().build(), null, getServerApi(), null).create(new ServerId(new ClusterId(), getPrimary())) + [], LoggerSettings.builder().build(), null, getServerApi()).create(new ServerId(new ClusterId(), getPrimary())) connection.open() getCollectionHelper().insertDocuments(new BsonDocument('_id', new BsonInt32(1))) diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy index e8cb470c604..21979eb87ce 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy @@ -145,10 +145,11 @@ class AwsAuthenticationSpecification extends Specification { new InternalStreamConnection(SINGLE, new ServerId(new ClusterId(), new ServerAddress(getConnectionString().getHosts().get(0))), new TestConnectionGenerationSupplier(), - async ? new AsynchronousSocketChannelStreamFactory(SocketSettings.builder().build(), getSslSettings()) - : new SocketStreamFactory(SocketSettings.builder().build(), getSslSettings()), [], null, - new InternalStreamConnectionInitializer(SINGLE, createAuthenticator(credential), null, [], null), - null) + async ? new AsynchronousSocketChannelStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), + getSslSettings()) : new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), + getSslSettings()), [], null, new InternalStreamConnectionInitializer(SINGLE, createAuthenticator(credential), + null, [], null) + ) } private static Authenticator createAuthenticator(final MongoCredential credential) { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy index f8a662da88d..76eba8a0dac 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy @@ -49,7 +49,7 @@ class CommandHelperSpecification extends Specification { def setup() { connection = new InternalStreamConnectionFactory(ClusterConnectionMode.SINGLE, new NettyStreamFactory(SocketSettings.builder().build(), getSslSettings()), - getCredentialWithCache(), null, null, [], LoggerSettings.builder().build(), null, getServerApi(), null) + getCredentialWithCache(), null, null, [], LoggerSettings.builder().build(), null, getServerApi()) .create(new ServerId(new ClusterId(), getPrimary())) connection.open() } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy index ae8698aae88..6a78ce97f7c 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy @@ -206,9 +206,9 @@ class GSSAPIAuthenticationSpecification extends Specification { new InternalStreamConnection(SINGLE, new ServerId(new ClusterId(), new ServerAddress(getConnectionString().getHosts().get(0))), new TestConnectionGenerationSupplier(), async ? new NettyStreamFactory(SocketSettings.builder().build(), getSslSettings()) - : new SocketStreamFactory(SocketSettings.builder().build(), getSslSettings()), [], null, - new InternalStreamConnectionInitializer(SINGLE, createAuthenticator(credential), null, [], null), - null) + : new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()), + [], null, new InternalStreamConnectionInitializer(SINGLE, createAuthenticator(credential), null, [], null) + ) } private static Authenticator createAuthenticator(final MongoCredential credential) { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy index a0eb5ff12b9..02f6652ded0 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy @@ -47,9 +47,9 @@ class GSSAPIAuthenticatorSpecification extends Specification { def subjectProvider = Mock(SubjectProvider) def credential = ClusterFixture.getCredential().withMechanismProperty(JAVA_SUBJECT_PROVIDER_KEY, subjectProvider) def credentialWithCache = new MongoCredentialWithCache(credential) - def streamFactory = new SocketStreamFactory(SocketSettings.builder().build(), getSslSettings()) + def streamFactory = new SocketStreamFactory(settings.getInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()) def internalConnection = new InternalStreamConnectionFactory(SINGLE, streamFactory, credentialWithCache, null, - null, Collections. emptyList(), LoggerSettings.builder().build(), null, getServerApi(), null) + null, Collections. emptyList(), LoggerSettings.builder().build(), null, getServerApi()) .create(new ServerId(new ClusterId(), getPrimary())) when: diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy index a0e2571897f..e57627ce325 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy @@ -110,9 +110,9 @@ class PlainAuthenticationSpecification extends Specification { new ServerId(new ClusterId(), new ServerAddress(getConnectionString().getHosts().get(0))), new TestConnectionGenerationSupplier(), async ? new NettyStreamFactory(SocketSettings.builder().build(), getSslSettings()) - : new SocketStreamFactory(SocketSettings.builder().build(), getSslSettings()), [], null, - new InternalStreamConnectionInitializer(SINGLE, createAuthenticator(credential), null, [], null), - null) + : new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()), + [], null, new InternalStreamConnectionInitializer(SINGLE, createAuthenticator(credential), null, [], null) + ) } private static Authenticator createAuthenticator(final MongoCredential credential) { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java index cd47dfb5182..e2377c8efef 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java @@ -43,7 +43,7 @@ public class PlainAuthenticatorTest { private String userName; private String source; private String password; - private final StreamFactory streamFactory = new SocketStreamFactory(SocketSettings.builder().build(), getSslSettings()); + private final StreamFactory streamFactory = new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()); @Before public void setUp() { @@ -52,8 +52,8 @@ public void setUp() { source = System.getProperty("org.mongod.test.source"); password = System.getProperty("org.mongodb.test.password"); internalConnection = new InternalStreamConnectionFactory(ClusterConnectionMode.SINGLE, streamFactory, null, null, - null, Collections.emptyList(), LoggerSettings.builder().build(), null, getServerApi(), - null).create(new ServerId(new ClusterId(), + null, Collections.emptyList(), LoggerSettings.builder().build(), null, getServerApi() + ).create(new ServerId(new ClusterId(), new ServerAddress(host))); connectionDescription = new ConnectionDescription(new ServerId(new ClusterId(), new ServerAddress())); } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy index b8ea72dc246..e88de876273 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/ServerMonitorSpecification.groovy @@ -221,12 +221,11 @@ class ServerMonitorSpecification extends OperationFunctionalSpecification { } serverMonitor = new DefaultServerMonitor(new ServerId(new ClusterId(), address), ServerSettings.builder().build(), new ClusterClock(), - new InternalStreamConnectionFactory(SINGLE, new SocketStreamFactory(SocketSettings.builder() - .connectTimeout(500, TimeUnit.MILLISECONDS) - .build(), - getSslSettings()), getCredentialWithCache(), null, null, [], LoggerSettings.builder().build(), null, - getServerApi(), null), - getClusterConnectionMode(), getServerApi(), SameObjectProvider.initialized(sdam)) + new InternalStreamConnectionFactory(SINGLE, new SocketStreamFactory(new DefaultInetAddressResolver(), + SocketSettings.builder().connectTimeout(500, TimeUnit.MILLISECONDS).build(), getSslSettings()), + getCredentialWithCache(), null, null, [], LoggerSettings.builder().build(), null, + getServerApi()), + getClusterConnectionMode(), getServerApi(), SameObjectProvider.initialized(sdam)) serverMonitor.start() serverMonitor } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java index e25c433e3ec..55ba6875a16 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java @@ -50,13 +50,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -@SuppressWarnings("deprecation") public class SingleServerClusterTest { private SingleServerCluster cluster; private void setUpCluster(final ServerAddress serverAddress) { - SocketStreamFactory streamFactory = new SocketStreamFactory(SocketSettings.builder().build(), + SocketStreamFactory streamFactory = new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()); ClusterId clusterId = new ClusterId(); ClusterSettings clusterSettings = ClusterSettings.builder() @@ -70,7 +69,7 @@ private void setUpCluster(final ServerAddress serverAddress) { streamFactory, streamFactory, getCredential(), LoggerSettings.builder().build(), null, null, null, - Collections.emptyList(), getServerApi(), null)); + Collections.emptyList(), getServerApi())); } @After diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy index 5a2492da109..21e9d20b984 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy @@ -31,6 +31,7 @@ import javax.net.ssl.SSLSocketFactory import java.lang.reflect.Method import static com.mongodb.ClusterFixture.getPrimary +import static com.mongodb.internal.connection.ServerAddressHelper.getSocketAddresses import static java.util.concurrent.TimeUnit.MILLISECONDS import static java.util.concurrent.TimeUnit.SECONDS @@ -44,7 +45,8 @@ class SocketStreamHelperSpecification extends Specification { .build() when: - SocketStreamHelper.initialize(socket, getPrimary().getSocketAddress(), socketSettings, SslSettings.builder().build()) + SocketStreamHelper.initialize(socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + socketSettings, SslSettings.builder().build()) then: socket.getTcpNoDelay() @@ -68,7 +70,7 @@ class SocketStreamHelperSpecification extends Specification { Socket socket = SocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(socket, getPrimary().getSocketAddress(), + SocketStreamHelper.initialize(socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), SslSettings.builder().build()) then: @@ -84,7 +86,8 @@ class SocketStreamHelperSpecification extends Specification { SSLSocket socket = SSLSocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(socket, getPrimary().getSocketAddress(), SocketSettings.builder().build(), sslSettings) + SocketStreamHelper.initialize(socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), SocketSettings. + builder().build(), sslSettings) then: socket.getSSLParameters().endpointIdentificationAlgorithm == (sslSettings.invalidHostNameAllowed ? null : 'HTTPS') @@ -104,7 +107,8 @@ class SocketStreamHelperSpecification extends Specification { SSLSocket socket = SSLSocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(socket, getPrimary().getSocketAddress(), SocketSettings.builder().build(), sslSettings) + SocketStreamHelper.initialize(socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + SocketSettings.builder().build(), sslSettings) then: socket.getSSLParameters().getServerNames() == [new SNIHostName(getPrimary().getHost())] @@ -122,8 +126,8 @@ class SocketStreamHelperSpecification extends Specification { Socket socket = SocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(socket, getPrimary().getSocketAddress(), SocketSettings.builder().build(), - SslSettings.builder().enabled(true).build()) + SocketStreamHelper.initialize(socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + SocketSettings.builder().build(), SslSettings.builder().enabled(true).build()) then: thrown(MongoInternalException) diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy index 961b72ca0c8..7fcf694723c 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy @@ -1,5 +1,6 @@ package com.mongodb.internal.connection +import com.mongodb.spi.dns.InetAddressResolver import util.spock.annotations.Slow import com.mongodb.MongoSocketOpenException import com.mongodb.ServerAddress @@ -39,7 +40,7 @@ class StreamSocketAddressSpecification extends Specification { def socket2 = SocketFactory.default.createSocket() socketFactory.createSocket() >>> [socket0, socket1, socket2] - def socketStream = new SocketStream(serverAddress, socketSettings, sslSettings, socketFactory, bufferProvider) + def socketStream = new SocketStream(serverAddress, null, socketSettings, sslSettings, socketFactory, bufferProvider) when: socketStream.open() @@ -57,18 +58,11 @@ class StreamSocketAddressSpecification extends Specification { @IgnoreIf({ getSslSettings().isEnabled() }) def 'should throw exception when attempting to connect with incorrect ip address group'() { given: - def port = 27017 def socketSettings = SocketSettings.builder().connectTimeout(100, TimeUnit.MILLISECONDS).build() def sslSettings = SslSettings.builder().build() def bufferProvider = Stub(BufferProvider) - def inetAddresses = new InetSocketAddress[3] - - inetAddresses[0] = new InetSocketAddress(InetAddress.getByName('1.2.3.4'), port) - inetAddresses[1] = new InetSocketAddress(InetAddress.getByName('2.3.4.5'), port) - inetAddresses[2] = new InetSocketAddress(InetAddress.getByName('1.2.3.5'), port) - def serverAddress = Stub(ServerAddress) - serverAddress.getSocketAddresses() >> inetAddresses + def serverAddress = new ServerAddress() def socketFactory = Stub(SocketFactory) def socket0 = SocketFactory.default.createSocket() @@ -76,7 +70,16 @@ class StreamSocketAddressSpecification extends Specification { def socket2 = SocketFactory.default.createSocket() socketFactory.createSocket() >>> [socket0, socket1, socket2] - def socketStream = new SocketStream(serverAddress, socketSettings, sslSettings, socketFactory, bufferProvider) + def inetAddressResolver = new InetAddressResolver() { + @Override + List lookupByName(String host) { + [InetAddress.getByName('1.2.3.4'), + InetAddress.getByName('2.3.4.5'), + InetAddress.getByName('1.2.3.5')] + } + } + + def socketStream = new SocketStream(serverAddress, inetAddressResolver, socketSettings, sslSettings, socketFactory, bufferProvider) when: socketStream.open() diff --git a/driver-core/src/test/unit/com/mongodb/UnixServerAddressSpecification.groovy b/driver-core/src/test/unit/com/mongodb/UnixServerAddressSpecification.groovy index 24b473cc40d..b8e18198eb2 100644 --- a/driver-core/src/test/unit/com/mongodb/UnixServerAddressSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/UnixServerAddressSpecification.groovy @@ -31,17 +31,9 @@ class UnixServerAddressSpecification extends Specification { def 'should throw if the path does not end with .sock'() { when: - new UnixServerAddress('localhost').getSocketAddress() + new UnixServerAddress('localhost') then: thrown(IllegalArgumentException) } - - def 'should throw when trying to get a InetSocketAddress'() { - when: - new UnixServerAddress('/tmp/mongodb.sock').getSocketAddress() - - then: - thrown(UnsupportedOperationException) - } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java index 0e832457b82..81b92e5cf9a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java @@ -185,8 +185,8 @@ public void setUp() { Collections.emptyList(), LoggerSettings.builder().build(), new TestCommandListener(), - ClusterFixture.getServerApi(), - null), + ClusterFixture.getServerApi() + ), settings, internalSettings, sdamProvider)); sdamProvider.initialize(new DefaultSdamServerDescriptionManager(mockedCluster(), serverId, mock(ServerListener.class), mock(ServerMonitor.class), pool, connectionMode)); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy index 6c8e117b4cf..245c6c87a5a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactorySpecification.groovy @@ -27,7 +27,8 @@ class AsynchronousSocketChannelStreamFactoryFactorySpecification extends Specifi @Unroll def 'should create the expected #description AsynchronousSocketChannelStream'() { given: - def factory = new AsynchronousSocketChannelStreamFactoryFactory().create(socketSettings, sslSettings) + def factory = new AsynchronousSocketChannelStreamFactoryFactory(new DefaultInetAddressResolver()) + .create(socketSettings, sslSettings) when: AsynchronousSocketChannelStream stream = factory.create(serverAddress) as AsynchronousSocketChannelStream diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java index 60d443fbc7e..b8574081f5c 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolAsyncTest.java @@ -80,9 +80,9 @@ protected Callable createCallable(final BsonDocument operation) { @Override protected StreamFactory createStreamFactory(final SocketSettings socketSettings, final SslSettings sslSettings) { if (sslSettings.isEnabled()) { - return new TlsChannelStreamFactoryFactory().create(socketSettings, sslSettings); + return new TlsChannelStreamFactoryFactory(new DefaultInetAddressResolver()).create(socketSettings, sslSettings); } else { - return new AsynchronousSocketChannelStreamFactory(socketSettings, sslSettings); + return new AsynchronousSocketChannelStreamFactory(new DefaultInetAddressResolver(), socketSettings, sslSettings); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java index aecd88a50a9..b5b449c755d 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ConnectionPoolTest.java @@ -70,6 +70,6 @@ protected Callable createCallable(final BsonDocument operation) { @Override protected StreamFactory createStreamFactory(final SocketSettings socketSettings, final SslSettings sslSettings) { - return new SocketStreamFactory(socketSettings, sslSettings); + return new SocketStreamFactory(new DefaultInetAddressResolver(), socketSettings, sslSettings); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy index 6c9263e940e..52e316cc15b 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy @@ -108,7 +108,7 @@ class InternalStreamConnectionSpecification extends Specification { def getConnection() { new InternalStreamConnection(SINGLE, SERVER_ID, new TestConnectionGenerationSupplier(), streamFactory, [], commandListener, - initializer, null) + initializer) } def getOpenedConnection() { @@ -173,7 +173,7 @@ class InternalStreamConnectionSpecification extends Specification { startHandshake(_) >> { throw new MongoInternalException('Something went wrong') } } def connection = new InternalStreamConnection(SINGLE, SERVER_ID, new TestConnectionGenerationSupplier(), streamFactory, [], null, - failedInitializer, null) + failedInitializer) when: connection.open() @@ -190,7 +190,7 @@ class InternalStreamConnectionSpecification extends Specification { startHandshakeAsync(_, _) >> { it[1].onResult(null, new MongoInternalException('Something went wrong')) } } def connection = new InternalStreamConnection(SINGLE, SERVER_ID, new TestConnectionGenerationSupplier(), streamFactory, [], null, - failedInitializer, null) + failedInitializer) when: def futureResultCallback = new FutureResultCallback() diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java index 24cf24f2890..90989a8e133 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/StreamFactoryHelperTest.java @@ -19,6 +19,7 @@ import com.mongodb.connection.NettyTransportSettings; import com.mongodb.connection.TransportSettings; import com.mongodb.internal.connection.netty.NettyStreamFactoryFactory; +import com.mongodb.spi.dns.InetAddressResolver; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.nio.NioEventLoopGroup; import org.junit.jupiter.api.Test; @@ -30,12 +31,14 @@ class StreamFactoryHelperTest { @Test void streamFactoryFactoryIsDerivedFromTransportSettings() { + InetAddressResolver inetAddressResolver = new DefaultInetAddressResolver(); NettyTransportSettings nettyTransportSettings = TransportSettings.nettyBuilder() .eventLoopGroup(new NioEventLoopGroup()) .allocator(PooledByteBufAllocator.DEFAULT) .socketChannelClass(io.netty.channel.socket.oio.OioSocketChannel.class) .build(); - assertEquals(NettyStreamFactoryFactory.builder().applySettings(nettyTransportSettings).build(), - StreamFactoryHelper.getStreamFactoryFactoryFromSettings(nettyTransportSettings)); + assertEquals(NettyStreamFactoryFactory.builder().applySettings(nettyTransportSettings) + .inetAddressResolver(inetAddressResolver).build(), + StreamFactoryHelper.getStreamFactoryFactoryFromSettings(nettyTransportSettings, inetAddressResolver)); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy index 59dd78f40e2..a92e4f26ee6 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/netty/NettyStreamFactoryFactorySpecification.groovy @@ -20,6 +20,7 @@ import com.mongodb.ServerAddress import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings import com.mongodb.connection.TransportSettings +import com.mongodb.internal.connection.DefaultInetAddressResolver import io.netty.buffer.ByteBufAllocator import io.netty.buffer.UnpooledByteBufAllocator import io.netty.channel.nio.NioEventLoopGroup @@ -43,6 +44,7 @@ class NettyStreamFactoryFactorySpecification extends Specification { when: def factoryFactory = NettyStreamFactoryFactory.builder() + .inetAddressResolver(new DefaultInetAddressResolver()) .applySettings(nettySettings) .build() @@ -78,10 +80,13 @@ class NettyStreamFactoryFactorySpecification extends Specification { SocketSettings socketSettings = SocketSettings.builder().build() SslSettings sslSettings = SslSettings.builder().build() ServerAddress serverAddress = new ServerAddress() - static final DEFAULT_FACTORY = NettyStreamFactoryFactory.builder().build() + static final DEFAULT_FACTORY = NettyStreamFactoryFactory.builder() + .inetAddressResolver(new DefaultInetAddressResolver()) + .build() static final CUSTOM_FACTORY = NettyStreamFactoryFactory.builder() .allocator(UnpooledByteBufAllocator.DEFAULT) .socketChannelClass(OioSocketChannel) .eventLoopGroup(new OioEventLoopGroup()) + .inetAddressResolver(new DefaultInetAddressResolver()) .build() } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java index f22d3ab7c91..d4ad39bdec9 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java @@ -30,9 +30,11 @@ import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.internal.MongoClientImpl; +import com.mongodb.spi.dns.InetAddressResolver; import org.bson.codecs.configuration.CodecRegistry; import static com.mongodb.assertions.Assertions.notNull; +import static com.mongodb.internal.connection.ServerAddressHelper.getInetAddressResolver; import static com.mongodb.internal.connection.StreamFactoryHelper.getStreamFactoryFactoryFromSettings; import static com.mongodb.internal.event.EventListenerHelper.getCommandListener; @@ -113,14 +115,15 @@ public static MongoClient create(final MongoClientSettings settings, @Nullable f throw new MongoClientException("Proxy is not supported for reactive clients"); } + InetAddressResolver inetAddressResolver = getInetAddressResolver(settings); StreamFactoryFactory streamFactoryFactory; TransportSettings transportSettings = settings.getTransportSettings(); if (transportSettings != null) { - streamFactoryFactory = getStreamFactoryFactoryFromSettings(transportSettings); + streamFactoryFactory = getStreamFactoryFactoryFromSettings(transportSettings, inetAddressResolver); } else if (settings.getSslSettings().isEnabled()) { - streamFactoryFactory = new TlsChannelStreamFactoryFactory(); + streamFactoryFactory = new TlsChannelStreamFactoryFactory(inetAddressResolver); } else { - streamFactoryFactory = new AsynchronousSocketChannelStreamFactoryFactory(); + streamFactoryFactory = new AsynchronousSocketChannelStreamFactoryFactory(inetAddressResolver); } StreamFactory streamFactory = getStreamFactory(streamFactoryFactory, settings, false); StreamFactory heartbeatStreamFactory = getStreamFactory(streamFactoryFactory, settings, true); @@ -150,7 +153,7 @@ private static Cluster createCluster(final MongoClientSettings settings, InternalConnectionPoolSettings.builder().prestartAsyncWorkManager(true).build(), streamFactory, heartbeatStreamFactory, settings.getCredential(), settings.getLoggerSettings(), getCommandListener(settings.getCommandListeners()), settings.getApplicationName(), mongoDriverInformation, - settings.getCompressorList(), settings.getServerApi(), settings.getDnsClient(), settings.getInetAddressResolver()); + settings.getCompressorList(), settings.getServerApi(), settings.getDnsClient()); } private static MongoDriverInformation wrapMongoDriverInformation(@Nullable final MongoDriverInformation mongoDriverInformation) { diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java index c392b2a3f45..887129b24e1 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java @@ -21,11 +21,12 @@ import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; +import com.mongodb.crypt.capi.MongoKeyDecryptor; +import com.mongodb.internal.connection.AsynchronousChannelStream; +import com.mongodb.internal.connection.DefaultInetAddressResolver; import com.mongodb.internal.connection.Stream; import com.mongodb.internal.connection.StreamFactory; import com.mongodb.internal.connection.TlsChannelStreamFactoryFactory; -import com.mongodb.crypt.capi.MongoKeyDecryptor; -import com.mongodb.internal.connection.AsynchronousChannelStream; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.lang.Nullable; @@ -51,7 +52,7 @@ class KeyManagementService implements Closeable { KeyManagementService(final Map kmsProviderSslContextMap, final int timeoutMillis) { this.kmsProviderSslContextMap = kmsProviderSslContextMap; - this.tlsChannelStreamFactoryFactory = new TlsChannelStreamFactoryFactory(); + this.tlsChannelStreamFactoryFactory = new TlsChannelStreamFactoryFactory(new DefaultInetAddressResolver()); this.timeoutMillis = timeoutMillis; } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java index 70b767a7109..0a560442639 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java @@ -42,6 +42,7 @@ import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.internal.session.ServerSessionPool; import com.mongodb.lang.Nullable; +import com.mongodb.spi.dns.InetAddressResolver; import org.bson.BsonDocument; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; @@ -53,6 +54,7 @@ import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.client.internal.Crypts.createCrypt; import static com.mongodb.internal.connection.ClientMetadataHelper.createClientMetadataDocument; +import static com.mongodb.internal.connection.ServerAddressHelper.getInetAddressResolver; import static com.mongodb.internal.connection.StreamFactoryHelper.getStreamFactoryFactoryFromSettings; import static com.mongodb.internal.event.EventListenerHelper.getCommandListener; import static java.lang.String.format; @@ -222,16 +224,18 @@ private static Cluster createCluster(final MongoClientSettings settings, getStreamFactory(settings, false), getStreamFactory(settings, true), settings.getCredential(), settings.getLoggerSettings(), getCommandListener(settings.getCommandListeners()), settings.getApplicationName(), mongoDriverInformation, settings.getCompressorList(), settings.getServerApi(), - settings.getDnsClient(), settings.getInetAddressResolver()); + settings.getDnsClient()); } private static StreamFactory getStreamFactory(final MongoClientSettings settings, final boolean isHeartbeat) { SocketSettings socketSettings = isHeartbeat ? settings.getHeartbeatSocketSettings() : settings.getSocketSettings(); TransportSettings transportSettings = settings.getTransportSettings(); + InetAddressResolver inetAddressResolver = getInetAddressResolver(settings); if (transportSettings == null) { - return new SocketStreamFactory(socketSettings, settings.getSslSettings()); + return new SocketStreamFactory(inetAddressResolver, socketSettings, settings.getSslSettings()); } else { - return getStreamFactoryFactoryFromSettings(transportSettings).create(socketSettings, settings.getSslSettings()); + return getStreamFactoryFactoryFromSettings(transportSettings, inetAddressResolver) + .create(socketSettings, settings.getSslSettings()); } } From e975980ee26ebe762ee7763e6298a815723b82e7 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Tue, 24 Oct 2023 10:04:01 -0400 Subject: [PATCH 05/28] Migrate bson tests from JUnit 4 to 5 (#1229) JAVA-5215 --- .../unit/org/bson/BsonBinaryReaderTest.java | 9 +- .../unit/org/bson/BsonBinaryWriterTest.java | 22 +- .../test/unit/org/bson/BsonDocumentTest.java | 9 +- bson/src/test/unit/org/bson/DocumentTest.java | 11 +- .../test/unit/org/bson/GenericBsonTest.java | 114 +++++----- .../unit/org/bson/LazyBSONDecoderTest.java | 15 +- .../test/unit/org/bson/LazyBSONListTest.java | 21 +- .../bson/codecs/AtomicIntegerCodecTest.java | 19 +- .../org/bson/codecs/AtomicLongCodecTest.java | 21 +- .../unit/org/bson/codecs/ByteCodecTest.java | 19 +- .../unit/org/bson/codecs/CodecTestCase.java | 6 +- .../org/bson/codecs/DocumentCodecTest.java | 19 +- .../unit/org/bson/codecs/DoubleCodecTest.java | 20 +- .../unit/org/bson/codecs/FloatCodecTest.java | 16 +- .../org/bson/codecs/IntegerCodecTest.java | 20 +- .../codecs/JsonObjectCodecProviderTest.java | 2 +- .../unit/org/bson/codecs/LongCodecTest.java | 16 +- .../unit/org/bson/codecs/ShortCodecTest.java | 12 +- .../unit/org/bson/codecs/StringCodecTest.java | 33 +-- .../codecs/pojo/ClassModelBuilderTest.java | 53 ++--- .../org/bson/codecs/pojo/ClassModelTest.java | 22 +- .../org/bson/codecs/pojo/ConventionsTest.java | 104 +++++---- .../bson/codecs/pojo/IdGeneratorsTest.java | 4 +- .../pojo/PojoCodecCyclicalLookupTest.java | 2 +- .../codecs/pojo/PojoCodecProviderTest.java | 6 +- .../org/bson/codecs/pojo/PojoCustomTest.java | 204 +++++++++--------- .../bson/codecs/pojo/PojoRoundTripTest.java | 39 ++-- .../org/bson/codecs/pojo/PojoTestCase.java | 6 +- .../codecs/pojo/PropertyModelBuilderTest.java | 18 +- .../bson/codecs/pojo/PropertyModelTest.java | 8 +- .../org/bson/codecs/pojo/TypeDataTest.java | 6 +- .../codecs/pojo/TypeParameterMapTest.java | 12 +- .../unit/org/bson/internal/BsonUtilTest.java | 3 +- .../org/bson/io/BasicOutputBufferTest.java | 6 +- .../unit/org/bson/json/JsonObjectTest.java | 35 +-- .../unit/org/bson/json/JsonReaderTest.java | 30 +-- .../unit/org/bson/json/JsonScannerTest.java | 25 +-- .../org/bson/json/JsonStreamBufferTest.java | 9 +- .../org/bson/json/JsonStringBufferTest.java | 9 +- .../unit/org/bson/json/JsonWriterTest.java | 102 +++++---- .../org/bson/types/BSONBsonTimestampTest.java | 6 +- .../unit/org/bson/types/Decimal128Test.java | 32 +-- .../unit/org/bson/types/ObjectIdTest.java | 18 +- 43 files changed, 609 insertions(+), 554 deletions(-) diff --git a/bson/src/test/unit/org/bson/BsonBinaryReaderTest.java b/bson/src/test/unit/org/bson/BsonBinaryReaderTest.java index a2510c92b3c..bffda74ecaa 100644 --- a/bson/src/test/unit/org/bson/BsonBinaryReaderTest.java +++ b/bson/src/test/unit/org/bson/BsonBinaryReaderTest.java @@ -18,14 +18,14 @@ import org.bson.io.ByteBufferBsonInput; import org.bson.types.ObjectId; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class BsonBinaryReaderTest { @@ -53,8 +53,7 @@ public void testInvalidBsonType() { reader.readBsonType(); fail("Should have thrown BsonSerializationException"); } catch (BsonSerializationException e) { - assertEquals("Detected unknown BSON type \"\\x16\" for fieldname \"a\". Are you using the latest driver version?", - e.getMessage()); + assertEquals("Detected unknown BSON type \"\\x16\" for fieldname \"a\". Are you using the latest driver version?", e.getMessage()); } } diff --git a/bson/src/test/unit/org/bson/BsonBinaryWriterTest.java b/bson/src/test/unit/org/bson/BsonBinaryWriterTest.java index 93e3a7f121d..15e27065ba2 100644 --- a/bson/src/test/unit/org/bson/BsonBinaryWriterTest.java +++ b/bson/src/test/unit/org/bson/BsonBinaryWriterTest.java @@ -19,9 +19,9 @@ import org.bson.io.BasicOutputBuffer; import org.bson.io.ByteBufferBsonInput; import org.bson.types.ObjectId; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -31,25 +31,25 @@ import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class BsonBinaryWriterTest { private BsonBinaryWriter writer; private BasicOutputBuffer buffer; - @Before + @BeforeEach public void setup() { buffer = new BasicOutputBuffer(); writer = new BsonBinaryWriter(new BsonWriterSettings(100), new BsonBinaryWriterSettings(1024), buffer); } - @After + @AfterEach public void tearDown() { writer.close(); } diff --git a/bson/src/test/unit/org/bson/BsonDocumentTest.java b/bson/src/test/unit/org/bson/BsonDocumentTest.java index 0ec2c007296..32d56166f12 100644 --- a/bson/src/test/unit/org/bson/BsonDocumentTest.java +++ b/bson/src/test/unit/org/bson/BsonDocumentTest.java @@ -23,13 +23,13 @@ import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.StringWriter; import java.util.Arrays; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; // Don't convert to Spock, as Groovy intercepts equals/hashCode methods that we are trying to test public class BsonDocumentTest { @@ -78,8 +78,7 @@ public void shouldHaveSameHashCodeAsEquivalentBsonDocument() { @Test public void toJsonShouldReturnEquivalent() { - assertEquals(new BsonDocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()), - document); + assertEquals(new BsonDocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()), document); } @Test diff --git a/bson/src/test/unit/org/bson/DocumentTest.java b/bson/src/test/unit/org/bson/DocumentTest.java index 2e584282117..bd9551e9407 100644 --- a/bson/src/test/unit/org/bson/DocumentTest.java +++ b/bson/src/test/unit/org/bson/DocumentTest.java @@ -28,7 +28,7 @@ import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import org.bson.json.JsonReader; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -38,9 +38,9 @@ import static org.bson.codecs.configuration.CodecRegistries.fromCodecs; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.fail; // Don't convert to Spock, as Groovy intercepts equals/hashCode methods that we are trying to test public class DocumentTest { @@ -75,8 +75,7 @@ public void shouldHaveSameHashCodeAsEquivalentBsonDocument() { @Test public void toJsonShouldReturnEquivalent() { - assertEquals(new DocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()), - document); + assertEquals(new DocumentCodec().decode(new JsonReader(document.toJson()), DecoderContext.builder().build()), document); } // Test to ensure that toJson does not reorder _id field diff --git a/bson/src/test/unit/org/bson/GenericBsonTest.java b/bson/src/test/unit/org/bson/GenericBsonTest.java index 76a736237e7..2f50bcd7f61 100644 --- a/bson/src/test/unit/org/bson/GenericBsonTest.java +++ b/bson/src/test/unit/org/bson/GenericBsonTest.java @@ -24,10 +24,9 @@ import org.bson.json.JsonParseException; import org.bson.json.JsonWriterSettings; import org.bson.types.Decimal128; -import org.junit.Assume; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import util.Hex; import util.JsonPoweredTestHelper; @@ -40,17 +39,17 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import static java.lang.String.format; import static org.bson.BsonDocument.parse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; // BSON tests powered by language-agnostic JSON-based tests included in test resources -@RunWith(Parameterized.class) public class GenericBsonTest { private static final List IGNORED_PARSE_ERRORS = Arrays.asList( @@ -65,35 +64,26 @@ enum TestCaseType { PARSE_ERROR } - private final BsonDocument testDefinition; - private final BsonDocument testCase; - private final TestCaseType testCaseType; - - public GenericBsonTest(@SuppressWarnings("unused") final String description, + @ParameterizedTest(name = "{0}") + @MethodSource("data") + public void shouldPassAllOutcomes(@SuppressWarnings("unused") final String description, final BsonDocument testDefinition, final BsonDocument testCase, final TestCaseType testCaseType) { - this.testDefinition = testDefinition; - this.testCase = testCase; - this.testCaseType = testCaseType; - } - - @Test - public void shouldPassAllOutcomes() { switch (testCaseType) { case VALID: - runValid(); + runValid(testCase); break; case DECODE_ERROR: - runDecodeError(); + runDecodeError(testCase); break; case PARSE_ERROR: - runParseError(); + runParseError(testDefinition, testCase); break; default: throw new IllegalArgumentException(format("Unsupported test case type %s", testCaseType)); } } - private void runValid() { + private void runValid(final BsonDocument testCase) { String description = testCase.getString("description").getValue(); String canonicalBsonHex = testCase.getString("canonical_bson").getValue().toUpperCase(); String degenerateBsonHex = testCase.getString("degenerate_bson", new BsonString("")).getValue().toUpperCase(); @@ -105,50 +95,51 @@ private void runValid() { BsonDocument decodedDocument = decodeToDocument(canonicalBsonHex, description); // native_to_bson( bson_to_native(cB) ) = cB - assertEquals(format("Failed to create expected BSON for document with description '%s'", description), - canonicalBsonHex, encodeToHex(decodedDocument)); + assertEquals(canonicalBsonHex, encodeToHex(decodedDocument), + format("Failed to create expected BSON for document with description '%s'", description)); JsonWriterSettings canonicalJsonWriterSettings = JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build(); JsonWriterSettings relaxedJsonWriterSettings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build(); if (!canonicalJson.isEmpty()) { // native_to_canonical_extended_json( bson_to_native(cB) ) = cEJ - assertEquals(format("Failed to create expected canonical JSON for document with description '%s'", description), - stripWhiteSpace(canonicalJson), stripWhiteSpace(decodedDocument.toJson(canonicalJsonWriterSettings))); + assertEquals(stripWhiteSpace(canonicalJson), stripWhiteSpace(decodedDocument.toJson(canonicalJsonWriterSettings)), + format("Failed to create expected canonical JSON for document with description '%s'", description)); // native_to_canonical_extended_json( json_to_native(cEJ) ) = cEJ BsonDocument parsedCanonicalJsonDocument = parse(canonicalJson); - assertEquals("Failed to create expected canonical JSON from parsing canonical JSON", - stripWhiteSpace(canonicalJson), stripWhiteSpace(parsedCanonicalJsonDocument.toJson(canonicalJsonWriterSettings))); + assertEquals(stripWhiteSpace(canonicalJson), stripWhiteSpace(parsedCanonicalJsonDocument.toJson(canonicalJsonWriterSettings)), + "Failed to create expected canonical JSON from parsing canonical JSON"); if (!lossy) { // native_to_bson( json_to_native(cEJ) ) = cB - assertEquals("Failed to create expected canonical BSON from parsing canonical JSON", - canonicalBsonHex, encodeToHex(parsedCanonicalJsonDocument)); + assertEquals(canonicalBsonHex, encodeToHex(parsedCanonicalJsonDocument), + "Failed to create expected canonical BSON from parsing canonical JSON"); } } if (!relaxedJson.isEmpty()) { // native_to_relaxed_extended_json( bson_to_native(cB) ) = rEJ - assertEquals(format("Failed to create expected relaxed JSON for document with description '%s'", description), - stripWhiteSpace(relaxedJson), stripWhiteSpace(decodedDocument.toJson(relaxedJsonWriterSettings))); + assertEquals(stripWhiteSpace(relaxedJson), stripWhiteSpace(decodedDocument.toJson(relaxedJsonWriterSettings)), + format("Failed to create expected relaxed JSON for document with description '%s'", description)); // native_to_relaxed_extended_json( json_to_native(rEJ) ) = rEJ - assertEquals("Failed to create expected relaxed JSON from parsing relaxed JSON", stripWhiteSpace(relaxedJson), - stripWhiteSpace(parse(relaxedJson).toJson(relaxedJsonWriterSettings))); + assertEquals(stripWhiteSpace(relaxedJson), stripWhiteSpace(parse(relaxedJson).toJson(relaxedJsonWriterSettings)), + "Failed to create expected relaxed JSON from parsing relaxed JSON"); } if (!degenerateJson.isEmpty()) { // native_to_bson( json_to_native(dEJ) ) = cB - assertEquals("Failed to create expected canonical BSON from parsing canonical JSON", - canonicalBsonHex, encodeToHex(parse(degenerateJson))); + assertEquals(canonicalBsonHex, encodeToHex(parse(degenerateJson)), + "Failed to create expected canonical BSON from parsing canonical JSON"); } if (!degenerateBsonHex.isEmpty()) { BsonDocument decodedDegenerateDocument = decodeToDocument(degenerateBsonHex, description); // native_to_bson( bson_to_native(dB) ) = cB - assertEquals(format("Failed to create expected canonical BSON from degenerate BSON for document with description " - + "'%s'", description), canonicalBsonHex, encodeToHex(decodedDegenerateDocument)); + assertEquals(canonicalBsonHex, encodeToHex(decodedDegenerateDocument), + format("Failed to create expected canonical BSON from degenerate BSON for document with description '%s'", + description)); } } @@ -223,7 +214,7 @@ private BsonDocument decodeToDocument(final String subjectHex, final String desc if (byteBuffer.hasRemaining()) { throw new BsonSerializationException(format("Should have consumed all bytes, but " + byteBuffer.remaining() - + " still remain in the buffer for document with description ", + + " still remain in the buffer for document with description ", description)); } return actualDecodedDocument; @@ -235,20 +226,20 @@ private String encodeToHex(final BsonDocument decodedDocument) { return Hex.encode(outputBuffer.toByteArray()); } - private void runDecodeError() { + private void runDecodeError(final BsonDocument testCase) { try { String description = testCase.getString("description").getValue(); - throwIfValueIsStringContainingReplacementCharacter(description); + throwIfValueIsStringContainingReplacementCharacter(testCase, description); fail(format("Should have failed parsing for subject with description '%s'", description)); } catch (BsonSerializationException e) { // all good } } - private void runParseError() { + private void runParseError(final BsonDocument testDefinition, final BsonDocument testCase) { String description = testCase.getString("description").getValue(); - Assume.assumeFalse(IGNORED_PARSE_ERRORS.contains(description)); + assumeFalse(IGNORED_PARSE_ERRORS.contains(description)); String str = testCase.getString("string").getValue(); @@ -290,7 +281,7 @@ private boolean isTestOfNullByteInCString(final String description) { // Working around the fact that the Java driver doesn't report an error for invalid UTF-8, but rather replaces the invalid // sequence with the replacement character - private void throwIfValueIsStringContainingReplacementCharacter(final String description) { + private void throwIfValueIsStringContainingReplacementCharacter(final BsonDocument testCase, final String description) { BsonDocument decodedDocument = decodeToDocument(testCase.getString("bson").getValue(), description); BsonValue value = decodedDocument.get(decodedDocument.getFirstKey()); @@ -312,39 +303,40 @@ private void throwIfValueIsStringContainingReplacementCharacter(final String des if (decodedString.contains(StandardCharsets.UTF_8.newDecoder().replacement())) { throw new BsonSerializationException("String contains replacement character"); } - } + } - @Parameterized.Parameters(name = "{0}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); + private static Stream data() throws URISyntaxException, IOException { + List data = new ArrayList<>(); for (File file : JsonPoweredTestHelper.getTestFiles("/bson")) { BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); for (BsonValue curValue : testDocument.getArray("valid", new BsonArray())) { BsonDocument testCaseDocument = curValue.asDocument(); - data.add(new Object[]{createTestCaseDescription(testDocument, testCaseDocument, "valid"), testDocument, testCaseDocument, - TestCaseType.VALID}); + data.add(Arguments.of( + createTestCaseDescription(testDocument, testCaseDocument, "valid"), testDocument, testCaseDocument, + TestCaseType.VALID)); } for (BsonValue curValue : testDocument.getArray("decodeErrors", new BsonArray())) { BsonDocument testCaseDocument = curValue.asDocument(); - data.add(new Object[]{createTestCaseDescription(testDocument, testCaseDocument, "decodeError"), testDocument, - testCaseDocument, TestCaseType.DECODE_ERROR}); + data.add(Arguments.of( + createTestCaseDescription(testDocument, testCaseDocument, "decodeError"), testDocument, testCaseDocument, + TestCaseType.DECODE_ERROR)); } for (BsonValue curValue : testDocument.getArray("parseErrors", new BsonArray())) { BsonDocument testCaseDocument = curValue.asDocument(); - data.add(new Object[]{createTestCaseDescription(testDocument, testCaseDocument, "parseError"), testDocument, - testCaseDocument, TestCaseType.PARSE_ERROR}); + data.add(Arguments.of(createTestCaseDescription(testDocument, testCaseDocument, "parseError"), testDocument, + testCaseDocument, TestCaseType.PARSE_ERROR)); } } - return data; + return data.stream(); } private static String createTestCaseDescription(final BsonDocument testDocument, final BsonDocument testCaseDocument, - final String testCaseType) { + final String testCaseType) { return testDocument.getString("description").getValue() - + "[" + testCaseType + "]" - + ": " + testCaseDocument.getString("description").getValue(); + + "[" + testCaseType + "]" + + ": " + testCaseDocument.getString("description").getValue(); } private String stripWhiteSpace(final String json) { diff --git a/bson/src/test/unit/org/bson/LazyBSONDecoderTest.java b/bson/src/test/unit/org/bson/LazyBSONDecoderTest.java index 79dcfc7fbec..32b2f047f43 100644 --- a/bson/src/test/unit/org/bson/LazyBSONDecoderTest.java +++ b/bson/src/test/unit/org/bson/LazyBSONDecoderTest.java @@ -16,8 +16,8 @@ package org.bson; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -26,13 +26,14 @@ import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; public class LazyBSONDecoderTest { private BSONDecoder bsonDecoder; - @Before + @BeforeEach public void setUp() { bsonDecoder = new LazyBSONDecoder(); } @@ -59,10 +60,10 @@ public void testDecodingFromByteArray() throws IOException { assertEquals(1, document.get("a")); } - @Test(expected = BSONException.class) + @Test public void testDecodingFromInvalidInput() { byte[] bytes = {16, 0, 0, 0, 16, 97, 0, 1, 0, 0, 0, 0}; - bsonDecoder.readObject(bytes); + assertThrows(BSONException.class, () -> bsonDecoder.readObject(bytes)); } } diff --git a/bson/src/test/unit/org/bson/LazyBSONListTest.java b/bson/src/test/unit/org/bson/LazyBSONListTest.java index 5f93cc012a1..cd2672b6575 100644 --- a/bson/src/test/unit/org/bson/LazyBSONListTest.java +++ b/bson/src/test/unit/org/bson/LazyBSONListTest.java @@ -16,16 +16,17 @@ package org.bson; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings({"rawtypes"}) public class LazyBSONListTest { @@ -86,12 +87,14 @@ public void testIterator() { assertFalse(it.hasNext()); } - @Test(expected = NoSuchElementException.class) + @Test public void testIteratorNextWhileNothingLeft() { - LazyBSONList list = encodeAndExtractList(asList()); - Iterator it = list.iterator(); - assertFalse(it.hasNext()); - it.next(); + assertThrows(NoSuchElementException.class, () -> { + LazyBSONList list = encodeAndExtractList(asList()); + Iterator it = list.iterator(); + assertFalse(it.hasNext()); + it.next(); + }); } } diff --git a/bson/src/test/unit/org/bson/codecs/AtomicIntegerCodecTest.java b/bson/src/test/unit/org/bson/codecs/AtomicIntegerCodecTest.java index e8922aaaf26..e4fcfd001ed 100644 --- a/bson/src/test/unit/org/bson/codecs/AtomicIntegerCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/AtomicIntegerCodecTest.java @@ -18,11 +18,12 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public final class AtomicIntegerCodecTest extends CodecTestCase { @@ -44,20 +45,20 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", 9.9999999999999992), new AtomicIntegerComparator(expected)); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDoubleValues() { Document original = new Document("a", 9.9999999999999991); - roundTrip(original, new AtomicIntegerComparator(original)); + assertThrows(BsonInvalidOperationException.class, () ->roundTrip(original, new AtomicIntegerComparator(original))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMinRange() { - roundTrip(new Document("a", Long.MIN_VALUE)); + assertThrows(BsonInvalidOperationException.class, () ->roundTrip(new Document("a", Long.MIN_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMaxRange() { - roundTrip(new Document("a", Long.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () ->roundTrip(new Document("a", Long.MAX_VALUE))); } @Override @@ -74,7 +75,7 @@ private class AtomicIntegerComparator implements Comparator { @Override public void apply(final Document result) { - assertEquals("Codec Round Trip", + assertEquals( expected.get("a", AtomicInteger.class).get(), result.get("a", AtomicInteger.class).get()); } diff --git a/bson/src/test/unit/org/bson/codecs/AtomicLongCodecTest.java b/bson/src/test/unit/org/bson/codecs/AtomicLongCodecTest.java index 2321becc1ed..1efb30e6348 100644 --- a/bson/src/test/unit/org/bson/codecs/AtomicLongCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/AtomicLongCodecTest.java @@ -18,11 +18,12 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicLong; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public final class AtomicLongCodecTest extends CodecTestCase { @@ -44,20 +45,20 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", 9.9999999999999992), new AtomicLongComparator(expected)); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDoubleValues() { Document original = new Document("a", 9.9999999999999991); - roundTrip(original, new AtomicLongComparator(original)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(original, new AtomicLongComparator(original))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMinRange() { - roundTrip(new Document("a", -Double.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", -Double.MAX_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMaxRange() { - roundTrip(new Document("a", Double.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Double.MAX_VALUE))); } @Override @@ -74,9 +75,7 @@ private class AtomicLongComparator implements Comparator { @Override public void apply(final Document result) { - assertEquals("Codec Round Trip", - expected.get("a", AtomicLong.class).get(), - result.get("a", AtomicLong.class).get()); + assertEquals(expected.get("a", AtomicLong.class).get(), result.get("a", AtomicLong.class).get()); } } diff --git a/bson/src/test/unit/org/bson/codecs/ByteCodecTest.java b/bson/src/test/unit/org/bson/codecs/ByteCodecTest.java index 667c1308527..20629fb027d 100644 --- a/bson/src/test/unit/org/bson/codecs/ByteCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/ByteCodecTest.java @@ -18,7 +18,9 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public final class ByteCodecTest extends CodecTestCase { @@ -36,19 +38,22 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", 9.9999999999999992), expected); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMinRange() { - roundTrip(new Document("a", Integer.MIN_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> + roundTrip(new Document("a", Integer.MIN_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMaxRange() { - roundTrip(new Document("a", Integer.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> + roundTrip(new Document("a", Integer.MAX_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDoubleValues() { - roundTrip(new Document("a", 9.9999999999999991)); + assertThrows(BsonInvalidOperationException.class, () -> + roundTrip(new Document("a", 9.9999999999999991))); } @Override diff --git a/bson/src/test/unit/org/bson/codecs/CodecTestCase.java b/bson/src/test/unit/org/bson/codecs/CodecTestCase.java index d654c38d4c7..17768d0d133 100644 --- a/bson/src/test/unit/org/bson/codecs/CodecTestCase.java +++ b/bson/src/test/unit/org/bson/codecs/CodecTestCase.java @@ -36,7 +36,7 @@ import static java.util.Arrays.asList; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; abstract class CodecTestCase { @@ -82,7 +82,7 @@ void roundTripWithRegistry(final T value, final Comparator comparator, fi } public void roundTrip(final Document input, final Document expected) { - roundTrip(input, result -> assertEquals("Codec Round Trip", expected, result)); + roundTrip(input, result -> assertEquals(expected, result)); } OutputBuffer encode(final Codec codec, final T value) { @@ -119,7 +119,7 @@ class DefaultComparator implements Comparator { @Override public void apply(final T result) { - assertEquals("Codec Round Trip", original, result); + assertEquals(original, result); } } diff --git a/bson/src/test/unit/org/bson/codecs/DocumentCodecTest.java b/bson/src/test/unit/org/bson/codecs/DocumentCodecTest.java index 12911263b3e..79c65573556 100644 --- a/bson/src/test/unit/org/bson/codecs/DocumentCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/DocumentCodecTest.java @@ -33,9 +33,9 @@ import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -45,21 +45,21 @@ import java.util.List; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DocumentCodecTest { private BasicOutputBuffer buffer; private BsonBinaryWriter writer; - @Before + @BeforeEach public void setUp() throws Exception { buffer = new BasicOutputBuffer(); writer = new BsonBinaryWriter(buffer); } - @After + @AfterEach public void tearDown() { writer.close(); } @@ -103,8 +103,7 @@ public void testIterableEncoding() throws IOException { Document decodedDocument = documentCodec.decode(new BsonBinaryReader(bsonInput), DecoderContext.builder().build()); assertEquals(new Document() .append("list", asList(1, 2, 3, 4, 5)) - .append("set", asList(1, 2, 3, 4)), - decodedDocument); + .append("set", asList(1, 2, 3, 4)), decodedDocument); } @Test diff --git a/bson/src/test/unit/org/bson/codecs/DoubleCodecTest.java b/bson/src/test/unit/org/bson/codecs/DoubleCodecTest.java index cfceae50530..cbf6031fb88 100644 --- a/bson/src/test/unit/org/bson/codecs/DoubleCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/DoubleCodecTest.java @@ -19,7 +19,9 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; import org.bson.types.Decimal128; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public final class DoubleCodecTest extends CodecTestCase { @@ -37,24 +39,24 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", Decimal128.parse("10")), expected); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyLongValues() { - roundTrip(new Document("a", Long.MAX_VALUE - 1)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Long.MAX_VALUE - 1))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyLongValues2() { - roundTrip(new Document("a", Long.MIN_VALUE + 1)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Long.MIN_VALUE + 1))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDecimal128Values() { - roundTrip(new Document("a", Decimal128.parse("10.0"))); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Decimal128.parse("10.0")))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingNonExpressibleDecimal128Values() { - roundTrip(new Document("a", Decimal128.parse("NaN"))); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Decimal128.parse("NaN")))); } @Override diff --git a/bson/src/test/unit/org/bson/codecs/FloatCodecTest.java b/bson/src/test/unit/org/bson/codecs/FloatCodecTest.java index 2d59798fefc..90cf41a20de 100644 --- a/bson/src/test/unit/org/bson/codecs/FloatCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/FloatCodecTest.java @@ -19,7 +19,9 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; import org.bson.types.Decimal128; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public final class FloatCodecTest extends CodecTestCase { @@ -43,19 +45,19 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", Decimal128.parse("10")), expected); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMinRange() { - roundTrip(new Document("a", -Double.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", -Double.MAX_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMaxRange() { - roundTrip(new Document("a", Double.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Double.MAX_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDecimal128Values() { - roundTrip(new Document("a", Decimal128.parse("10.0"))); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Decimal128.parse("10.0")))); } @Override diff --git a/bson/src/test/unit/org/bson/codecs/IntegerCodecTest.java b/bson/src/test/unit/org/bson/codecs/IntegerCodecTest.java index d71e27122e0..11a8ac3647c 100644 --- a/bson/src/test/unit/org/bson/codecs/IntegerCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/IntegerCodecTest.java @@ -19,7 +19,9 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; import org.bson.types.Decimal128; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public final class IntegerCodecTest extends CodecTestCase { @@ -38,24 +40,24 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", Decimal128.parse("10")), expected); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMinRange() { - roundTrip(new Document("a", Long.MIN_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Long.MIN_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMaxRange() { - roundTrip(new Document("a", Long.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Long.MAX_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDoubleValues() { - roundTrip(new Document("a", 9.9999999999999991)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", 9.9999999999999991))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDecimal128Values() { - roundTrip(new Document("a", Decimal128.parse("10.0"))); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Decimal128.parse("10.0")))); } @Override diff --git a/bson/src/test/unit/org/bson/codecs/JsonObjectCodecProviderTest.java b/bson/src/test/unit/org/bson/codecs/JsonObjectCodecProviderTest.java index 7f12a6a5f93..f3af17ceefb 100644 --- a/bson/src/test/unit/org/bson/codecs/JsonObjectCodecProviderTest.java +++ b/bson/src/test/unit/org/bson/codecs/JsonObjectCodecProviderTest.java @@ -19,7 +19,7 @@ import org.bson.codecs.configuration.CodecProvider; import org.bson.codecs.configuration.CodecRegistry; import org.bson.json.JsonObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/bson/src/test/unit/org/bson/codecs/LongCodecTest.java b/bson/src/test/unit/org/bson/codecs/LongCodecTest.java index 07ac4cdede9..2005718a05d 100644 --- a/bson/src/test/unit/org/bson/codecs/LongCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/LongCodecTest.java @@ -19,7 +19,9 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; import org.bson.types.Decimal128; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public final class LongCodecTest extends CodecTestCase { @@ -38,19 +40,19 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", Decimal128.parse("10")), expected); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyValues() { - roundTrip(new Document("a", Double.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () ->roundTrip(new Document("a", Double.MAX_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDoubleValues() { - roundTrip(new Document("a", 9.9999999999999991)); + assertThrows(BsonInvalidOperationException.class, () ->roundTrip(new Document("a", 9.9999999999999991))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowWhenHandlingLossyDecimal128Values() { - roundTrip(new Document("a", Decimal128.parse("10.0"))); + assertThrows(BsonInvalidOperationException.class, () ->roundTrip(new Document("a", Decimal128.parse("10.0")))); } @Override diff --git a/bson/src/test/unit/org/bson/codecs/ShortCodecTest.java b/bson/src/test/unit/org/bson/codecs/ShortCodecTest.java index 3712f35176b..6bfb41fbb1a 100644 --- a/bson/src/test/unit/org/bson/codecs/ShortCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/ShortCodecTest.java @@ -18,7 +18,9 @@ import org.bson.BsonInvalidOperationException; import org.bson.Document; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public final class ShortCodecTest extends CodecTestCase { @@ -37,14 +39,14 @@ public void shouldHandleAlternativeNumberValues() { roundTrip(new Document("a", 9.9999999999999992), expected); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMinRange() { - roundTrip(new Document("a", Integer.MIN_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Integer.MIN_VALUE))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldErrorDecodingOutsideMaxRange() { - roundTrip(new Document("a", Integer.MAX_VALUE)); + assertThrows(BsonInvalidOperationException.class, () -> roundTrip(new Document("a", Integer.MAX_VALUE))); } @Override diff --git a/bson/src/test/unit/org/bson/codecs/StringCodecTest.java b/bson/src/test/unit/org/bson/codecs/StringCodecTest.java index e631d3a21ae..2c9ae408c11 100644 --- a/bson/src/test/unit/org/bson/codecs/StringCodecTest.java +++ b/bson/src/test/unit/org/bson/codecs/StringCodecTest.java @@ -23,17 +23,18 @@ import org.bson.codecs.configuration.CodecConfigurationException; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.StringWriter; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class StringCodecTest { private final DecoderContext decoderContext = DecoderContext.builder().build(); private final EncoderContext encoderContext = EncoderContext.builder().build(); - private final Codec parent = new StringCodec(); + private final Codec parent = new StringCodec(); @SuppressWarnings("unchecked") private final Codec child = ((RepresentationConfigurable) parent).withRepresentation(BsonType.OBJECT_ID); @@ -50,9 +51,9 @@ public void testStringRepresentation() { assertEquals(((RepresentationConfigurable) child).getRepresentation(), BsonType.STRING); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidRepresentation() { - ((RepresentationConfigurable) parent).withRepresentation(BsonType.INT32); + assertThrows(CodecConfigurationException.class, () -> ((RepresentationConfigurable) parent).withRepresentation(BsonType.INT32)); } @@ -66,20 +67,24 @@ public void testDecodeOnObjectIdWithObjectIdRep() { assertEquals(stringId, "5f5a6cc03237b5e06d6b887b"); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void testDecodeOnObjectIdWithStringRep() { - BsonReader reader = new JsonReader("{'_id': ObjectId('5f5a6cc03237b5e06d6b887b'), 'name': 'Brian'}"); - reader.readStartDocument(); - reader.readName(); - parent.decode(reader, decoderContext); + assertThrows(BsonInvalidOperationException.class, () -> { + BsonReader reader = new JsonReader("{'_id': ObjectId('5f5a6cc03237b5e06d6b887b'), 'name': 'Brian'}"); + reader.readStartDocument(); + reader.readName(); + parent.decode(reader, decoderContext); + }); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void testDecodeOnStringWithObjectIdRep() { - BsonReader reader = new JsonReader("{'name': 'Brian'"); - reader.readStartDocument(); - reader.readName(); - child.decode(reader, decoderContext); + assertThrows(BsonInvalidOperationException.class, () -> { + BsonReader reader = new JsonReader("{'name': 'Brian'"); + reader.readStartDocument(); + reader.readName(); + child.decode(reader, decoderContext); + }); } @Test diff --git a/bson/src/test/unit/org/bson/codecs/pojo/ClassModelBuilderTest.java b/bson/src/test/unit/org/bson/codecs/pojo/ClassModelBuilderTest.java index 769fbb773a6..83c9c432a07 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/ClassModelBuilderTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/ClassModelBuilderTest.java @@ -25,7 +25,7 @@ import org.bson.codecs.pojo.entities.SimpleIdModel; import org.bson.codecs.pojo.entities.UpperBoundsConcreteModel; import org.bson.codecs.pojo.entities.UpperBoundsModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.annotation.Annotation; import java.lang.reflect.Field; @@ -37,10 +37,11 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("rawtypes") public final class ClassModelBuilderTest { @@ -148,32 +149,36 @@ public void testCanRemoveField() { assertEquals(3, builder.getPropertyModelBuilders().size()); } - @Test(expected = CodecConfigurationException.class) + @Test() public void testValidationIdProperty() { - ClassModel.builder(SimpleGenericsModel.class).idPropertyName("ID").build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(SimpleGenericsModel.class).idPropertyName("ID").build()); } - @Test(expected = CodecConfigurationException.class) + @Test() public void testValidationDuplicateDocumentFieldName() { - ClassModelBuilder builder = ClassModel.builder(SimpleGenericsModel.class); - builder.getProperty("myIntegerField").writeName("myGenericField"); - builder.build(); + assertThrows(CodecConfigurationException.class, () -> { + ClassModelBuilder builder = ClassModel.builder(SimpleGenericsModel.class); + builder.getProperty("myIntegerField").writeName("myGenericField"); + builder.build(); + }); } - @Test(expected = CodecConfigurationException.class) + @Test() public void testDifferentTypeIdGenerator() { - ClassModel.builder(SimpleIdModel.class) - .idGenerator(new IdGenerator() { - @Override - public String generate() { - return "id"; - } - - @Override - public Class getType() { - return String.class; - } - }).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(SimpleIdModel.class) + .idGenerator(new IdGenerator() { + @Override + public String generate() { + return "id"; + } + + @Override + public Class getType() { + return String.class; + } + }).build()); } private static final List TEST_ANNOTATIONS = Collections.singletonList( diff --git a/bson/src/test/unit/org/bson/codecs/pojo/ClassModelTest.java b/bson/src/test/unit/org/bson/codecs/pojo/ClassModelTest.java index b553a1b2ae5..1bdf3059db0 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/ClassModelTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/ClassModelTest.java @@ -38,17 +38,17 @@ import org.bson.codecs.pojo.entities.SimpleWithStaticModel; import org.bson.codecs.pojo.entities.conventions.AnnotationInheritedModel; import org.bson.codecs.pojo.entities.conventions.AnnotationModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public final class ClassModelTest { @@ -200,8 +200,7 @@ public void testListListGenericExtendedModel() { ClassModel classModel = ClassModel.builder(ListListGenericExtendedModel.class).build(); assertEquals(1, classModel.getPropertyModels().size()); - assertEquals(createBuilder(List.class).addTypeParameter(createTypeData(List.class, Integer.class)).build(), - classModel.getPropertyModel("values").getTypeData()); + assertEquals(createBuilder(List.class).addTypeParameter(createTypeData(List.class, Integer.class)).build(), classModel.getPropertyModel("values").getTypeData()); } @Test @@ -218,8 +217,7 @@ public void testMapMapGenericExtendedModel() { assertEquals(1, classModel.getPropertyModels().size()); assertEquals(createBuilder(Map.class).addTypeParameter(createTypeData(String.class)) - .addTypeParameter(createTypeData(Map.class, String.class, Integer.class)).build(), - classModel.getPropertyModel("values").getTypeData()); + .addTypeParameter(createTypeData(Map.class, String.class, Integer.class)).build(), classModel.getPropertyModel("values").getTypeData()); } @Test @@ -227,8 +225,7 @@ public void testListMapGenericExtendedModel() { ClassModel classModel = ClassModel.builder(ListMapGenericExtendedModel.class).build(); assertEquals(1, classModel.getPropertyModels().size()); - assertEquals(createBuilder(List.class).addTypeParameter(createTypeData(Map.class, String.class, Integer.class)).build(), - classModel.getPropertyModel("values").getTypeData()); + assertEquals(createBuilder(List.class).addTypeParameter(createTypeData(Map.class, String.class, Integer.class)).build(), classModel.getPropertyModel("values").getTypeData()); } @@ -239,8 +236,7 @@ public void testMapListGenericExtendedModel() { assertEquals(1, classModel.getPropertyModels().size()); assertEquals(createBuilder(Map.class) .addTypeParameter(createTypeData(String.class)) - .addTypeParameter(createTypeData(List.class, Integer.class)).build(), - classModel.getPropertyModel("values").getTypeData()); + .addTypeParameter(createTypeData(List.class, Integer.class)).build(), classModel.getPropertyModel("values").getTypeData()); } diff --git a/bson/src/test/unit/org/bson/codecs/pojo/ConventionsTest.java b/bson/src/test/unit/org/bson/codecs/pojo/ConventionsTest.java index d750d25f34e..6554ab318ec 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/ConventionsTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/ConventionsTest.java @@ -38,18 +38,19 @@ import org.bson.codecs.pojo.entities.conventions.CreatorInvalidMultipleStaticCreatorsModel; import org.bson.codecs.pojo.entities.conventions.CreatorInvalidTypeConstructorModel; import org.bson.codecs.pojo.entities.conventions.CreatorInvalidTypeMethodModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.util.Collections.singletonList; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; import static org.bson.codecs.pojo.Conventions.ANNOTATION_CONVENTION; import static org.bson.codecs.pojo.Conventions.CLASS_AND_PROPERTY_CONVENTION; import static org.bson.codecs.pojo.Conventions.DEFAULT_CONVENTIONS; import static org.bson.codecs.pojo.Conventions.NO_CONVENTIONS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public final class ConventionsTest { @@ -122,7 +123,7 @@ public void testIdGeneratorChoice() { ClassModel stringIdObjectRep = ClassModel.builder(AnnotationBsonRepresentation.class).build(); assertEquals(stringIdObjectRep.getIdPropertyModelHolder().getIdGenerator(), IdGenerators.STRING_ID_GENERATOR); - ClassModel stringIdStringRep = ClassModel.builder(ConventionModel.class).build(); + ClassModel stringIdStringRep = ClassModel.builder(ConventionModel.class).build(); assertNull(stringIdStringRep.getIdPropertyModelHolder().getIdGenerator()); ClassModel bsonId = ClassModel.builder(BsonIdModel.class).build(); @@ -150,7 +151,7 @@ public void testClassAndFieldConventionDoesNotOverwrite() { .propertySerialization(new PropertyModelSerializationImpl<>()) .propertyAccessor(new PropertyAccessorTest<>()); - ClassModel classModel = builder.idPropertyName("stringField").build(); + ClassModel classModel = builder.idPropertyName("stringField").build(); assertTrue(classModel.useDiscriminator()); assertEquals("_cls", classModel.getDiscriminatorKey()); @@ -163,80 +164,93 @@ public void testClassAndFieldConventionDoesNotOverwrite() { assertNull(idPropertyModel.useDiscriminator()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testAnnotationCollision() { - ClassModel.builder(AnnotationCollision.class).conventions(DEFAULT_CONVENTIONS).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(AnnotationCollision.class).conventions(DEFAULT_CONVENTIONS).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testAnnotationWriteCollision() { - ClassModel.builder(AnnotationWriteCollision.class).conventions(DEFAULT_CONVENTIONS).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(AnnotationWriteCollision.class).conventions(DEFAULT_CONVENTIONS).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testAnnotationNameCollision() { - ClassModel.builder(AnnotationNameCollision.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(AnnotationNameCollision.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidConstructorModel() { - ClassModel.builder(CreatorInvalidConstructorModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidConstructorModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidMethodModel() { - ClassModel.builder(CreatorInvalidMethodModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidMethodModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidMultipleConstructorsModel() { - ClassModel.builder(CreatorInvalidMultipleConstructorsModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidMultipleConstructorsModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidMultipleCreatorsModel() { - ClassModel.builder(CreatorInvalidMultipleCreatorsModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidMultipleCreatorsModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidMultipleStaticCreatorsModel() { - ClassModel.builder(CreatorInvalidMultipleStaticCreatorsModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidMultipleStaticCreatorsModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidMethodReturnTypeModel() { - ClassModel.builder(CreatorInvalidMethodReturnTypeModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidMethodReturnTypeModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidTypeConstructorModel() { - ClassModel.builder(CreatorInvalidTypeConstructorModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidTypeConstructorModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorInvalidTypeMethodModel() { - ClassModel.builder(CreatorInvalidTypeMethodModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorInvalidTypeMethodModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorConstructorNoKnownIdModel() { - ClassModel.builder(CreatorConstructorNoKnownIdModel.class) - .conventions(singletonList(ANNOTATION_CONVENTION)).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(CreatorConstructorNoKnownIdModel.class) + .conventions(singletonList(ANNOTATION_CONVENTION)).build()); } - @Test(expected = CodecConfigurationException.class) + @Test public void testBsonIgnoreDuplicatePropertyMultipleTypesModel() { - ClassModel.builder(BsonIgnoreDuplicatePropertyMultipleTypes.class) - .conventions(NO_CONVENTIONS).build(); + assertThrows(CodecConfigurationException.class, () -> + ClassModel.builder(BsonIgnoreDuplicatePropertyMultipleTypes.class) + .conventions(NO_CONVENTIONS).build()); } private class PropertyAccessorTest implements PropertyAccessor { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/IdGeneratorsTest.java b/bson/src/test/unit/org/bson/codecs/pojo/IdGeneratorsTest.java index 2d0ea0600a3..fe812ba8fe9 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/IdGeneratorsTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/IdGeneratorsTest.java @@ -18,9 +18,9 @@ import org.bson.BsonObjectId; import org.bson.types.ObjectId; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class IdGeneratorsTest { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecCyclicalLookupTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecCyclicalLookupTest.java index 5911dc48167..161a54fd902 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecCyclicalLookupTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecCyclicalLookupTest.java @@ -36,7 +36,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class PojoCodecCyclicalLookupTest extends PojoTestCase { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecProviderTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecProviderTest.java index 22ce1ef19c4..1921e161854 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecProviderTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PojoCodecProviderTest.java @@ -21,11 +21,11 @@ import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.entities.SimpleModel; import org.bson.codecs.pojo.entities.conventions.CreatorInvalidMethodModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public final class PojoCodecProviderTest extends PojoTestCase { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java index 36ee65d90ea..5e9f195571b 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java @@ -79,7 +79,7 @@ import org.bson.codecs.pojo.entities.conventions.MapGetterNonEmptyModel; import org.bson.codecs.pojo.entities.conventions.MapGetterNullModel; import org.bson.types.ObjectId; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; @@ -99,9 +99,10 @@ import static org.bson.codecs.pojo.Conventions.NO_CONVENTIONS; import static org.bson.codecs.pojo.Conventions.SET_PRIVATE_FIELDS_CONVENTION; import static org.bson.codecs.pojo.Conventions.USE_GETTERS_FOR_SETTERS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("deprecation") public final class PojoCustomTest extends PojoTestCase { @@ -283,68 +284,68 @@ public void testWithWildcardListField() { + "'name': 'B'}]}"); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionInvalidTypeForCollection() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(CollectionsGetterMutableModel.class) .conventions(getDefaultAndUseGettersConvention()); - - decodingShouldFail(getCodec(builder, CollectionsGetterMutableModel.class), "{listField: ['1', '2']}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(builder, CollectionsGetterMutableModel.class), "{listField: ['1', '2']}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionInvalidTypeForMap() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(MapGetterMutableModel.class) .conventions(getDefaultAndUseGettersConvention()); - - decodingShouldFail(getCodec(builder, MapGetterMutableModel.class), "{mapField: {a: '1'}}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(builder, MapGetterMutableModel.class), "{mapField: {a: '1'}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionImmutableCollection() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(CollectionsGetterImmutableModel.class) .conventions(getDefaultAndUseGettersConvention()); - - roundTrip(builder, new CollectionsGetterImmutableModel(asList(1, 2)), "{listField: [1, 2]}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(builder, new CollectionsGetterImmutableModel(asList(1, 2)), "{listField: [1, 2]}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionImmutableMap() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(MapGetterImmutableModel.class) .conventions(getDefaultAndUseGettersConvention()); - - roundTrip(builder, new MapGetterImmutableModel(Collections.singletonMap("a", 3)), "{mapField: {a: 3}}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(builder, new MapGetterImmutableModel(Collections.singletonMap("a", 3)), "{mapField: {a: 3}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionNullCollection() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(CollectionsGetterNullModel.class) .conventions(getDefaultAndUseGettersConvention()); - - roundTrip(builder, new CollectionsGetterNullModel(asList(1, 2)), "{listField: [1, 2]}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(builder, new CollectionsGetterNullModel(asList(1, 2)), "{listField: [1, 2]}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionNullMap() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(MapGetterNullModel.class) .conventions(getDefaultAndUseGettersConvention()); - - roundTrip(builder, new MapGetterNullModel(Collections.singletonMap("a", 3)), "{mapField: {a: 3}}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(builder, new MapGetterNullModel(Collections.singletonMap("a", 3)), "{mapField: {a: 3}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionNotEmptyCollection() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(CollectionsGetterNonEmptyModel.class) .conventions(getDefaultAndUseGettersConvention()); - - roundTrip(builder, new CollectionsGetterNonEmptyModel(asList(1, 2)), "{listField: [1, 2]}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(builder, new CollectionsGetterNonEmptyModel(asList(1, 2)), "{listField: [1, 2]}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testUseGettersForSettersConventionNotEmptyMap() { PojoCodecProvider.Builder builder = getPojoCodecProviderBuilder(MapGetterNonEmptyModel.class) .conventions(getDefaultAndUseGettersConvention()); - - roundTrip(builder, new MapGetterNonEmptyModel(Collections.singletonMap("a", 3)), "{mapField: {a: 3}}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(builder, new MapGetterNonEmptyModel(Collections.singletonMap("a", 3)), "{mapField: {a: 3}}")); } @Test @@ -468,38 +469,34 @@ public void testMapStringObjectModel() { roundTrip(registry, model, "{ map: {a : 1, b: 'b', c: [1, 2, 3]}}"); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testMapStringObjectModelWithObjectCodec() { MapStringObjectModel model = new MapStringObjectModel(new HashMap<>(Document.parse("{a : 1, b: 'b', c: [1, 2, 3]}"))); CodecRegistry registry = fromRegistries(fromCodecs(new org.bson.codecs.MapCodec()), fromCodecs(new ObjectCodec()), fromProviders(getPojoCodecProviderBuilder(MapStringObjectModel.class).build())); - roundTrip(registry, model, "{ map: {a : 1, b: 'b', c: [1, 2, 3]}}"); + assertThrows(UnsupportedOperationException.class, () -> + roundTrip(registry, model, "{ map: {a : 1, b: 'b', c: [1, 2, 3]}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testEncodingInvalidMapModel() { - encodesTo(getPojoCodecProviderBuilder(InvalidMapModel.class), getInvalidMapModel(), "{'invalidMap': {'1': 1, '2': 2}}"); + assertThrows(CodecConfigurationException.class, () -> + encodesTo(getPojoCodecProviderBuilder(InvalidMapModel.class), getInvalidMapModel(), "{'invalidMap': {'1': 1, '2': 2}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testDecodingInvalidMapModel() { - try { - decodingShouldFail(getCodec(InvalidMapModel.class), "{'invalidMap': {'1': 1, '2': 2}}"); - } catch (CodecConfigurationException e) { - assertTrue(e.getMessage().startsWith("Failed to decode 'InvalidMapModel'. Decoding 'invalidMap' errored with:")); - throw e; - } + CodecConfigurationException e = assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(InvalidMapModel.class), "{'invalidMap': {'1': 1, '2': 2}}")); + assertTrue(e.getMessage().startsWith("Failed to decode 'InvalidMapModel'. Decoding 'invalidMap' errored with:")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testEncodingInvalidCollectionModel() { - try { - encodesTo(getPojoCodecProviderBuilder(InvalidCollectionModel.class), new InvalidCollectionModel(asList(1, 2, 3)), - "{collectionField: [1, 2, 3]}"); - } catch (CodecConfigurationException e) { - assertTrue(e.getMessage().startsWith("Failed to encode 'InvalidCollectionModel'. Encoding 'collectionField' errored with:")); - throw e; - } + CodecConfigurationException e = assertThrows(CodecConfigurationException.class, () -> + encodesTo(getPojoCodecProviderBuilder(InvalidCollectionModel.class), new InvalidCollectionModel(asList(1, 2, 3)), + "{collectionField: [1, 2, 3]}")); + assertTrue(e.getMessage().startsWith("Failed to encode 'InvalidCollectionModel'. Encoding 'collectionField' errored with:")); } @Test @@ -508,108 +505,122 @@ public void testInvalidMapModelWithCustomPropertyCodecProvider() { "{'invalidMap': {'1': 1, '2': 2}}"); } - @Test(expected = CodecConfigurationException.class) + @Test public void testConstructorNotPublicModel() { - decodingShouldFail(getCodec(ConstructorNotPublicModel.class), "{'integerField': 99}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(ConstructorNotPublicModel.class), "{'integerField': 99}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testDataUnknownClass() { ClassModel classModel = ClassModel.builder(SimpleModel.class).enableDiscriminator(true).build(); - try { - decodingShouldFail(getCodec(PojoCodecProvider.builder().register(classModel), SimpleModel.class), "{'_t': 'FakeModel'}"); - } catch (CodecConfigurationException e) { - assertTrue(e.getMessage().startsWith("Failed to decode 'SimpleModel'. Decoding errored with:")); - throw e; - } + CodecConfigurationException e = assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(PojoCodecProvider.builder().register(classModel), SimpleModel.class), "{'_t': 'FakeModel'}")); + assertTrue(e.getMessage().startsWith("Failed to decode 'SimpleModel'. Decoding errored with:")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidTypeForField() { - decodingShouldFail(getCodec(SimpleModel.class), "{'_t': 'SimpleModel', 'stringField': 123}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(SimpleModel.class), "{'_t': 'SimpleModel', 'stringField': 123}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidTypeForPrimitiveField() { - decodingShouldFail(getCodec(PrimitivesModel.class), "{ '_t': 'PrimitivesModel', 'myBoolean': null}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(PrimitivesModel.class), "{ '_t': 'PrimitivesModel', 'myBoolean': null}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidTypeForModelField() { - decodingShouldFail(getCodec(SimpleNestedPojoModel.class), "{ '_t': 'SimpleNestedPojoModel', 'simple': 123}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(SimpleNestedPojoModel.class), "{ '_t': 'SimpleNestedPojoModel', 'simple': 123}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidDiscriminatorInNestedModel() { - decodingShouldFail(getCodec(SimpleNestedPojoModel.class), "{ '_t': 'SimpleNestedPojoModel'," - + "'simple': {'_t': 'FakeModel', 'integerField': 42, 'stringField': 'myString'}}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(SimpleNestedPojoModel.class), "{ '_t': 'SimpleNestedPojoModel'," + + "'simple': {'_t': 'FakeModel', 'integerField': 42, 'stringField': 'myString'}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCannotEncodeUnspecializedClasses() { CodecRegistry registry = fromProviders(getPojoCodecProviderBuilder(GenericTreeModel.class).build()); - encode(registry.get(GenericTreeModel.class), getGenericTreeModel(), false); + assertThrows(CodecConfigurationException.class, () -> + encode(registry.get(GenericTreeModel.class), getGenericTreeModel(), false)); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCannotDecodeUnspecializedClasses() { - decodingShouldFail(getCodec(GenericTreeModel.class), - "{'field1': 'top', 'field2': 1, " - + "'left': {'field1': 'left', 'field2': 2, 'left': {'field1': 'left', 'field2': 3}}, " - + "'right': {'field1': 'right', 'field2': 4, 'left': {'field1': 'left', 'field2': 5}}}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(GenericTreeModel.class), + "{'field1': 'top', 'field2': 1, " + + "'left': {'field1': 'left', 'field2': 2, 'left': {'field1': 'left', 'field2': 3}}, " + + "'right': {'field1': 'right', 'field2': 4, 'left': {'field1': 'left', 'field2': 5}}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testBsonCreatorPrimitivesAndNullValues() { - decodingShouldFail(getCodec(CreatorConstructorPrimitivesModel.class), "{intField: 100, stringField: 'test'}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(CreatorConstructorPrimitivesModel.class), "{intField: 100, stringField: 'test'}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorMethodThrowsExceptionModel() { - decodingShouldFail(getCodec(CreatorMethodThrowsExceptionModel.class), - "{'integerField': 10, 'stringField': 'eleven', 'longField': {$numberLong: '12'}}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(CreatorMethodThrowsExceptionModel.class), + "{'integerField': 10, 'stringField': 'eleven', 'longField': {$numberLong: '12'}}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testCreatorConstructorThrowsExceptionModel() { - decodingShouldFail(getCodec(CreatorConstructorThrowsExceptionModel.class), "{}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(CreatorConstructorThrowsExceptionModel.class), "{}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidSetterModel() { - decodingShouldFail(getCodec(InvalidSetterArgsModel.class), "{'integerField': 42, 'stringField': 'myString'}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(InvalidSetterArgsModel.class), "{'integerField': 42, 'stringField': 'myString'}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidGetterAndSetterModelEncoding() { InvalidGetterAndSetterModel model = new InvalidGetterAndSetterModel(42, "myString"); - roundTrip(getPojoCodecProviderBuilder(InvalidGetterAndSetterModel.class), model, "{'integerField': 42, 'stringField': 'myString'}"); + assertThrows(CodecConfigurationException.class, () -> + roundTrip(getPojoCodecProviderBuilder(InvalidGetterAndSetterModel.class), model, "{'integerField': 42, 'stringField': 'myString'}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidGetterAndSetterModelDecoding() { - decodingShouldFail(getCodec(InvalidGetterAndSetterModel.class), "{'integerField': 42, 'stringField': 'myString'}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(InvalidGetterAndSetterModel.class), "{'integerField': 42, 'stringField': 'myString'}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidBsonRepresentationStringDecoding() { - decodingShouldFail(getCodec(BsonRepresentationUnsupportedString.class), "{'id': 'hello', s: 3}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(BsonRepresentationUnsupportedString.class), "{'id': 'hello', s: 3}")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidBsonRepresentationStringEncoding() { - encodesTo(getPojoCodecProviderBuilder(BsonRepresentationUnsupportedString.class), - new BsonRepresentationUnsupportedString("1"), ""); + assertThrows(CodecConfigurationException.class, () -> + encodesTo(getPojoCodecProviderBuilder(BsonRepresentationUnsupportedString.class), + new BsonRepresentationUnsupportedString("1"), "")); } - @Test(expected = CodecConfigurationException.class) + @Test public void testInvalidBsonRepresentationIntDecoding() { - decodingShouldFail(getCodec(BsonRepresentationUnsupportedInt.class), "{'id': 'hello', age: '3'}"); + assertThrows(CodecConfigurationException.class, () -> + decodingShouldFail(getCodec(BsonRepresentationUnsupportedInt.class), "{'id': 'hello', age: '3'}")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testStringIdIsNotObjectId() { - encodesTo(getCodec(BsonRepresentationModel.class), new BsonRepresentationModel("notanobjectid", 1), null); + assertThrows(IllegalArgumentException.class, () -> + encodesTo(getCodec(BsonRepresentationModel.class), new BsonRepresentationModel("notanobjectid", 1), null)); } @Test @@ -638,9 +649,10 @@ public void testMultiplePojoProviders() { roundTrip(actualRegistry, model, json); } - @Test(expected = CodecConfigurationException.class) + @Test public void testBsonExtraElementsInvalidModel() { - getPojoCodecProviderBuilder(BsonExtraElementsInvalidModel.class).build(); + assertThrows(CodecConfigurationException.class, () -> + getPojoCodecProviderBuilder(BsonExtraElementsInvalidModel.class).build()); } private List getDefaultAndUseGettersConvention() { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PojoRoundTripTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PojoRoundTripTest.java index 42ad410c884..cba65f487fa 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PojoRoundTripTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PojoRoundTripTest.java @@ -102,37 +102,25 @@ import org.bson.codecs.pojo.entities.conventions.Subclass2Model; import org.bson.codecs.pojo.entities.conventions.SuperClassModel; import org.bson.types.ObjectId; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import static java.lang.String.format; import static java.util.Arrays.asList; -@RunWith(Parameterized.class) public final class PojoRoundTripTest extends PojoTestCase { - private final String name; - private final Object model; - private final PojoCodecProvider.Builder builder; - private final String json; - - public PojoRoundTripTest(final String name, final Object model, final String json, final PojoCodecProvider.Builder builder) { - this.name = name; - this.model = model; - this.json = json; - this.builder = builder; - } - - @Test - public void test() { + @ParameterizedTest(name = "{0}") + @MethodSource("data") + public void test(final String name, final Object model, final String json, final PojoCodecProvider.Builder builder) { roundTrip(builder, model, json); threadedRoundTrip(builder, model, json); } @@ -540,16 +528,15 @@ private static List testCases() { return data; } - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - List data = new ArrayList<>(); + public static Stream data() { + List data = new ArrayList<>(); for (TestData testData : testCases()) { - data.add(new Object[]{format("%s", testData.getName()), testData.getModel(), testData.getJson(), testData.getBuilder()}); - data.add(new Object[]{format("%s [Auto]", testData.getName()), testData.getModel(), testData.getJson(), AUTOMATIC_BUILDER}); - data.add(new Object[]{format("%s [Package]", testData.getName()), testData.getModel(), testData.getJson(), PACKAGE_BUILDER}); + data.add(Arguments.of(format("%s", testData.getName()), testData.getModel(), testData.getJson(), testData.getBuilder())); + data.add(Arguments.of(format("%s [Auto]", testData.getName()), testData.getModel(), testData.getJson(), AUTOMATIC_BUILDER)); + data.add(Arguments.of(format("%s [Package]", testData.getName()), testData.getModel(), testData.getJson(), PACKAGE_BUILDER)); } - return data; + return data.stream(); } private static final PojoCodecProvider.Builder AUTOMATIC_BUILDER = PojoCodecProvider.builder().automatic(true); diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PojoTestCase.java b/bson/src/test/unit/org/bson/codecs/pojo/PojoTestCase.java index 9b3be471db1..b1feb09a5ec 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PojoTestCase.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PojoTestCase.java @@ -75,7 +75,7 @@ import static java.util.Collections.singletonList; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.pojo.Conventions.DEFAULT_CONVENTIONS; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static util.ThreadTestHelpers.executeAll; abstract class PojoTestCase { @@ -132,7 +132,7 @@ void encodesTo(final Codec codec, final T value, final String json, final OutputBuffer encoded = encode(codec, value, collectible); BsonDocument asBsonDocument = decode(DOCUMENT_CODEC, encoded); - assertEquals("Encoded value", BsonDocument.parse(json), asBsonDocument); + assertEquals(BsonDocument.parse(json), asBsonDocument); } void decodesTo(final PojoCodecProvider.Builder builder, final String json, final T expected) { @@ -148,7 +148,7 @@ void decodesTo(final CodecRegistry registry, final String json, final T expe void decodesTo(final Codec codec, final String json, final T expected) { OutputBuffer encoded = encode(DOCUMENT_CODEC, BsonDocument.parse(json), false); T result = decode(codec, encoded); - assertEquals("Decoded value", expected, result); + assertEquals(expected, result); } void decodingShouldFail(final Codec codec, final String json) { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelBuilderTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelBuilderTest.java index 0d9e10c5c35..9ec8ffb96f7 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelBuilderTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelBuilderTest.java @@ -18,17 +18,18 @@ import org.bson.codecs.IntegerCodec; import org.bson.codecs.pojo.annotations.BsonProperty; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.List; -import static junit.framework.TestCase.assertTrue; import static org.bson.codecs.pojo.PojoBuilderHelper.createPropertyModelBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public final class PropertyModelBuilderTest { @@ -67,12 +68,13 @@ public void testFieldOverrides() throws NoSuchFieldException { assertFalse(propertyModelBuilder.isDiscriminatorEnabled()); } - @Test(expected = IllegalStateException.class) + @Test public void testMustBeReadableOrWritable() { - createPropertyModelBuilder(PROPERTY_METADATA) + assertThrows(IllegalStateException.class, () -> + createPropertyModelBuilder(PROPERTY_METADATA) .readName(null) .writeName(null) - .build(); + .build()); } private static final List ANNOTATIONS = Collections.singletonList( diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelTest.java index 5af6d9f33b0..bd7f2160a4d 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PropertyModelTest.java @@ -18,16 +18,16 @@ import org.bson.codecs.IntegerCodec; import org.bson.codecs.pojo.annotations.BsonProperty; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.List; -import static junit.framework.TestCase.assertFalse; import static org.bson.codecs.pojo.PojoBuilderHelper.createPropertyModelBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; public final class PropertyModelTest { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/TypeDataTest.java b/bson/src/test/unit/org/bson/codecs/pojo/TypeDataTest.java index 03c45dc4b1a..ee52e7e7bcf 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/TypeDataTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/TypeDataTest.java @@ -17,15 +17,15 @@ package org.bson.codecs.pojo; import org.bson.codecs.pojo.entities.GenericHolderModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.Map; import static java.util.Collections.singletonList; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("rawtypes") public final class TypeDataTest { diff --git a/bson/src/test/unit/org/bson/codecs/pojo/TypeParameterMapTest.java b/bson/src/test/unit/org/bson/codecs/pojo/TypeParameterMapTest.java index 91789d015ea..6b743da53a2 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/TypeParameterMapTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/TypeParameterMapTest.java @@ -16,13 +16,14 @@ package org.bson.codecs.pojo; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public final class TypeParameterMapTest { @@ -49,8 +50,9 @@ public void testMapsClassAndFieldIndices() { assertEquals(expected, typeParameterMap.getPropertyToClassParamIndexMap()); } - @Test(expected = IllegalStateException.class) + @Test public void testFieldCannotBeGenericAndContainTypeParameters() { - TypeParameterMap.builder().addIndex(1).addIndex(2, 2).build(); + assertThrows(IllegalStateException.class, () -> + TypeParameterMap.builder().addIndex(1).addIndex(2, 2).build()); } } diff --git a/bson/src/test/unit/org/bson/internal/BsonUtilTest.java b/bson/src/test/unit/org/bson/internal/BsonUtilTest.java index 8c41c45b1b3..f0ed7c24b26 100644 --- a/bson/src/test/unit/org/bson/internal/BsonUtilTest.java +++ b/bson/src/test/unit/org/bson/internal/BsonUtilTest.java @@ -32,6 +32,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.singletonList; +import static org.bson.assertions.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; @@ -122,7 +123,7 @@ private static void assertEqualNotSameAndMutable(final Object expected, final Ob } else if (expected instanceof BsonJavaScriptWithScope) { assertEquals(BsonJavaScriptWithScope.class, actualClass); } else { - org.bson.assertions.Assertions.fail("Unexpected " + expected.getClass().toString()); + fail("Unexpected " + expected.getClass().toString()); } } diff --git a/bson/src/test/unit/org/bson/io/BasicOutputBufferTest.java b/bson/src/test/unit/org/bson/io/BasicOutputBufferTest.java index 456761e2264..795df289876 100644 --- a/bson/src/test/unit/org/bson/io/BasicOutputBufferTest.java +++ b/bson/src/test/unit/org/bson/io/BasicOutputBufferTest.java @@ -16,14 +16,14 @@ package org.bson.io; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; // for tests that are too slow to run in Groovy public class BasicOutputBufferTest { @@ -43,7 +43,7 @@ public void shouldEncodeAllCodePointsThatAreLettersOrDigits() throws IOException // then byte[] bytes = getBytes(bsonOutput); - assertArrayEquals("failed with code point " + codePoint, str.getBytes(StandardCharsets.UTF_8), Arrays.copyOfRange(bytes, 0, bytes.length - 1)); + assertArrayEquals(str.getBytes(StandardCharsets.UTF_8), Arrays.copyOfRange(bytes, 0, bytes.length - 1), "failed with code point " + codePoint); } } diff --git a/bson/src/test/unit/org/bson/json/JsonObjectTest.java b/bson/src/test/unit/org/bson/json/JsonObjectTest.java index bc4667fb4c9..80cfe07196c 100644 --- a/bson/src/test/unit/org/bson/json/JsonObjectTest.java +++ b/bson/src/test/unit/org/bson/json/JsonObjectTest.java @@ -20,47 +20,48 @@ import org.bson.BsonInt32; import org.bson.codecs.BsonCodecProvider; import org.bson.codecs.JsonObjectCodecProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class JsonObjectTest { - @Test(expected = IllegalArgumentException.class) + @Test public void testNull() { - new JsonObject(null); + assertThrows(IllegalArgumentException.class, () -> new JsonObject(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testArray() { - new JsonObject("['A', 'B', 'C']"); + assertThrows(IllegalArgumentException.class, () ->new JsonObject("['A', 'B', 'C']")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSpaceInvalidObject() { - new JsonObject(" ['A']"); + assertThrows(IllegalArgumentException.class, () ->new JsonObject(" ['A']")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testLineFeedInvalidObject() { - new JsonObject("\nvalue"); + assertThrows(IllegalArgumentException.class, () ->new JsonObject("\nvalue")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCarriageReturnInvalidObject() { - new JsonObject("\r123"); + assertThrows(IllegalArgumentException.class, () ->new JsonObject("\r123")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testHorizontalTabInvalidObject() { - new JsonObject("\t123"); + assertThrows(IllegalArgumentException.class, () ->new JsonObject("\t123")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testOnlyWhitespace() { - new JsonObject(" \t\n \r "); + assertThrows(IllegalArgumentException.class, () ->new JsonObject(" \t\n \r ")); } @Test diff --git a/bson/src/test/unit/org/bson/json/JsonReaderTest.java b/bson/src/test/unit/org/bson/json/JsonReaderTest.java index fe65822001b..27e1980a3e3 100644 --- a/bson/src/test/unit/org/bson/json/JsonReaderTest.java +++ b/bson/src/test/unit/org/bson/json/JsonReaderTest.java @@ -26,7 +26,7 @@ import org.bson.BsonType; import org.bson.types.Decimal128; import org.bson.types.ObjectId; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -41,11 +41,12 @@ import java.util.function.Function; import static java.util.Arrays.asList; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class JsonReaderTest { @@ -872,11 +873,11 @@ public void testUndefinedExtended() { }); } - @Test(expected = IllegalStateException.class) + @Test public void testClosedState() { AbstractBsonReader bsonReader = new JsonReader(""); bsonReader.close(); - bsonReader.readBinaryData(); + assertThrows(IllegalStateException.class, () -> bsonReader.readBinaryData()); } @Test @@ -1015,14 +1016,15 @@ public void testUuid() { } // testing that JsonReader uses internal UuidStringValidator, as UUID.fromString accepts this UUID - @Test(expected = JsonParseException.class) + @Test public void testInvalidUuid() { // first hyphen out of place String json = "{ \"$uuid\" : \"73ff-d26444b-34c6-990e8e-7d1dfc035d4\"}}"; - testStringAndStream(json, bsonReader -> { - bsonReader.readBinaryData(); - return null; - }); + assertThrows(JsonParseException.class, () -> + testStringAndStream(json, bsonReader -> { + bsonReader.readBinaryData(); + return null; + })); } @Test @@ -1305,7 +1307,7 @@ public void testTwoDocuments() { } private void testStringAndStream(final String json, final Function testFunc, - final Class exClass) { + final Class exClass) { try { testFunc.apply(new JsonReader(json)); } catch (Exception e) { diff --git a/bson/src/test/unit/org/bson/json/JsonScannerTest.java b/bson/src/test/unit/org/bson/json/JsonScannerTest.java index 290adab453e..cf0647b08de 100644 --- a/bson/src/test/unit/org/bson/json/JsonScannerTest.java +++ b/bson/src/test/unit/org/bson/json/JsonScannerTest.java @@ -17,9 +17,10 @@ package org.bson.json; import org.bson.BsonRegularExpression; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class JsonScannerTest { @@ -497,41 +498,41 @@ public void testRegularExpressionPatternAndEscapeSequence() { assertEquals(',', buffer.read()); } - @Test(expected = JsonParseException.class) + @Test public void testInvalidRegularExpression() { String json = "\t /pattern/nsk,"; JsonBuffer buffer = new JsonStringBuffer(json); JsonScanner scanner = new JsonScanner(buffer); - scanner.nextToken(); + assertThrows(JsonParseException.class, () -> scanner.nextToken()); } - @Test(expected = JsonParseException.class) + @Test public void testInvalidRegularExpressionNoEnd() { String json = "/b"; JsonBuffer buffer = new JsonStringBuffer(json); JsonScanner scanner = new JsonScanner(buffer); - scanner.nextToken(); + assertThrows(JsonParseException.class, () ->scanner.nextToken()); } - @Test(expected = JsonParseException.class) + @Test public void testInvalidInput() { String json = "\t &&"; JsonScanner scanner = new JsonScanner(json); - scanner.nextToken(); + assertThrows(JsonParseException.class, () -> scanner.nextToken()); } - @Test(expected = JsonParseException.class) + @Test public void testInvalidNumber() { String json = "\t 123a]"; JsonScanner scanner = new JsonScanner(json); - scanner.nextToken(); + assertThrows(JsonParseException.class, () -> scanner.nextToken()); } - @Test(expected = JsonParseException.class) + @Test public void testInvalidInfinity() { String json = "\t -Infinnity]"; JsonScanner scanner = new JsonScanner(json); - scanner.nextToken(); + assertThrows(JsonParseException.class, () -> scanner.nextToken()); } } diff --git a/bson/src/test/unit/org/bson/json/JsonStreamBufferTest.java b/bson/src/test/unit/org/bson/json/JsonStreamBufferTest.java index faa607755d3..c8bdfb42449 100644 --- a/bson/src/test/unit/org/bson/json/JsonStreamBufferTest.java +++ b/bson/src/test/unit/org/bson/json/JsonStreamBufferTest.java @@ -16,12 +16,13 @@ package org.bson.json; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class JsonStreamBufferTest { @@ -51,12 +52,12 @@ public void testPosition() { assertEquals(2, buffer.getPosition()); } - @Test(expected = JsonParseException.class) + @Test public void testEOFCheck() { JsonStreamBuffer buffer = new JsonStreamBuffer(new InputStreamReader(new ByteArrayInputStream("".getBytes()))); buffer.read(); - buffer.read(); + assertThrows(JsonParseException.class, () -> buffer.read()); } @Test diff --git a/bson/src/test/unit/org/bson/json/JsonStringBufferTest.java b/bson/src/test/unit/org/bson/json/JsonStringBufferTest.java index 8fdab60b12f..058a27cd4d0 100644 --- a/bson/src/test/unit/org/bson/json/JsonStringBufferTest.java +++ b/bson/src/test/unit/org/bson/json/JsonStringBufferTest.java @@ -16,9 +16,10 @@ package org.bson.json; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class JsonStringBufferTest { @@ -48,11 +49,11 @@ public void testPosition() { assertEquals(2, buffer.getPosition()); } - @Test(expected = JsonParseException.class) + @Test public void testEOFCheck() { JsonStringBuffer buffer = new JsonStringBuffer(""); buffer.read(); - buffer.read(); + assertThrows(JsonParseException.class, () -> buffer.read()); } } diff --git a/bson/src/test/unit/org/bson/json/JsonWriterTest.java b/bson/src/test/unit/org/bson/json/JsonWriterTest.java index 5d23f51aaa0..00777a3dfec 100644 --- a/bson/src/test/unit/org/bson/json/JsonWriterTest.java +++ b/bson/src/test/unit/org/bson/json/JsonWriterTest.java @@ -23,21 +23,22 @@ import org.bson.BsonTimestamp; import org.bson.types.Decimal128; import org.bson.types.ObjectId; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.StringWriter; import java.util.Date; import java.util.List; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class JsonWriterTest { private StringWriter stringWriter; private JsonWriter writer; - @Before + @BeforeEach public void before() { stringWriter = new StringWriter(); writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().build()); @@ -53,123 +54,140 @@ private static class TestData { } } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowExceptionForBooleanWhenWritingBeforeStartingDocument() { - writer.writeBoolean("b1", true); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeBoolean("b1", true)); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowExceptionForNameWhenWritingBeforeStartingDocument() { - writer.writeName("name"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeName("name")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowExceptionForStringWhenStateIsValue() { writer.writeStartDocument(); - writer.writeString("SomeString"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeString("SomeString")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowExceptionWhenEndingAnArrayWhenStateIsValue() { writer.writeStartDocument(); - writer.writeEndArray(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeEndArray()); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowExceptionWhenWritingASecondName() { writer.writeStartDocument(); writer.writeName("f1"); - writer.writeName("i2"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeName("i2")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowExceptionWhenEndingADocumentBeforeValueIsWritten() { writer.writeStartDocument(); writer.writeName("f1"); - writer.writeEndDocument(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeEndDocument()); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenTryingToWriteASecondValue() { + writer.writeStartDocument(); + writer.writeName("f1"); writer.writeDouble(100); - writer.writeString("i2"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeString("i2")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenTryingToWriteJavaScript() { + writer.writeStartDocument(); + writer.writeName("f1"); writer.writeDouble(100); - writer.writeJavaScript("var i"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeJavaScript("var i")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenWritingANameInAnArray() { writer.writeStartDocument(); writer.writeStartArray("f2"); - writer.writeName("i3"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeName("i3")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenEndingDocumentInTheMiddleOfWritingAnArray() { writer.writeStartDocument(); writer.writeStartArray("f2"); - writer.writeEndDocument(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeEndDocument()); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenEndingAnArrayInASubDocument() { writer.writeStartDocument(); writer.writeStartArray("f2"); writer.writeStartDocument(); - writer.writeEndArray(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeEndArray()); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenWritingANameInAnArrayEvenWhenSubDocumentExistsInArray() { writer.writeStartDocument(); writer.writeStartArray("f2"); writer.writeStartDocument(); writer.writeEndDocument(); - writer.writeName("i3"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeName("i3")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnExceptionWhenAttemptingToEndAnArrayThatWasNotStarted() { writer.writeStartDocument(); writer.writeStartArray("f2"); writer.writeEndArray(); - writer.writeEndArray(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeEndArray()); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnErrorIfTryingToWriteNameIntoAJavascriptScope() { writer.writeStartDocument(); writer.writeJavaScriptWithScope("js1", "var i = 1"); - - writer.writeName("b1"); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeName("b1")); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnErrorIfTryingToWriteValueIntoAJavascriptScope() { writer.writeStartDocument(); writer.writeJavaScriptWithScope("js1", "var i = 1"); - - writer.writeBinaryData(new BsonBinary(new byte[]{0, 0, 1, 0})); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeBinaryData(new BsonBinary(new byte[]{0, 0, 1, 0}))); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnErrorIfTryingToWriteArrayIntoAJavascriptScope() { writer.writeStartDocument(); writer.writeJavaScriptWithScope("js1", "var i = 1"); - - writer.writeStartArray(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeStartArray()); } - @Test(expected = BsonInvalidOperationException.class) + @Test public void shouldThrowAnErrorIfTryingToWriteEndDocumentIntoAJavascriptScope() { writer.writeStartDocument(); writer.writeJavaScriptWithScope("js1", "var i = 1"); - - writer.writeEndDocument(); + assertThrows(BsonInvalidOperationException.class, () -> + writer.writeEndDocument()); } @Test diff --git a/bson/src/test/unit/org/bson/types/BSONBsonTimestampTest.java b/bson/src/test/unit/org/bson/types/BSONBsonTimestampTest.java index 28d864c9465..f2a210d1d3e 100644 --- a/bson/src/test/unit/org/bson/types/BSONBsonTimestampTest.java +++ b/bson/src/test/unit/org/bson/types/BSONBsonTimestampTest.java @@ -16,10 +16,10 @@ package org.bson.types; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BSONBsonTimestampTest { diff --git a/bson/src/test/unit/org/bson/types/Decimal128Test.java b/bson/src/test/unit/org/bson/types/Decimal128Test.java index 49ab1f46bfc..4d662aefb37 100644 --- a/bson/src/test/unit/org/bson/types/Decimal128Test.java +++ b/bson/src/test/unit/org/bson/types/Decimal128Test.java @@ -16,7 +16,7 @@ package org.bson.types; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.math.BigDecimal; @@ -28,11 +28,12 @@ import static org.bson.types.Decimal128.POSITIVE_ZERO; import static org.bson.types.Decimal128.fromIEEE754BIDEncoding; import static org.bson.types.Decimal128.parse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class Decimal128Test { @@ -221,10 +222,11 @@ public void shouldConvertNaNFromString() { assertEquals(NEGATIVE_NaN, parse("-nAn")); } - @Test(expected = ArithmeticException.class) + @Test public void shouldNotConvertNaNToBigDecimal() { - // when - NaN.bigDecimalValue(); + assertThrows(ArithmeticException.class, () -> + // when + NaN.bigDecimalValue()); } @Test @@ -316,14 +318,14 @@ public void testHashCode() { assertEquals(809500703, fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000001L).hashCode()); } - @Test(expected = ArithmeticException.class) + @Test public void shouldNotConvertPositiveInfinityToBigDecimal() { - POSITIVE_INFINITY.bigDecimalValue(); + assertThrows(ArithmeticException.class, () -> POSITIVE_INFINITY.bigDecimalValue()); } - @Test(expected = ArithmeticException.class) + @Test public void shouldNotConvertNegativeInfinityToBigDecimal() { - NEGATIVE_INFINITY.bigDecimalValue(); + assertThrows(ArithmeticException.class, () ->NEGATIVE_INFINITY.bigDecimalValue()); } @Test @@ -506,9 +508,9 @@ public void shouldNotClampSmallExponentsIfNoExtraPrecisionCanBeDiscarded() { } } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldThrowIllegalArgumentExceptionIfBigDecimalIsTooLarge() { - new Decimal128(new BigDecimal("12345678901234567890123456789012345")); + assertThrows(IllegalArgumentException.class, () -> new Decimal128(new BigDecimal("12345678901234567890123456789012345"))); } @Test diff --git a/bson/src/test/unit/org/bson/types/ObjectIdTest.java b/bson/src/test/unit/org/bson/types/ObjectIdTest.java index 9e41e48b8c4..14c8241f55a 100644 --- a/bson/src/test/unit/org/bson/types/ObjectIdTest.java +++ b/bson/src/test/unit/org/bson/types/ObjectIdTest.java @@ -16,7 +16,7 @@ package org.bson.types; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -30,11 +30,11 @@ import java.util.Locale; import java.util.Random; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class ObjectIdTest { @Test @@ -167,8 +167,7 @@ public void testCompareTo() { @Test public void testToHexString() { assertEquals("000000000000000000000000", new ObjectId(new byte[12]).toHexString()); - assertEquals("7fffffff007fff7fff007fff", - new ObjectId(new byte[]{127, -1, -1, -1, 0, 127, -1, 127, -1, 0, 127, -1}).toHexString()); + assertEquals("7fffffff007fff7fff007fff", new ObjectId(new byte[]{127, -1, -1, -1, 0, 127, -1, 127, -1, 0, 127, -1}).toHexString()); } private Date getDate(final String s) throws ParseException { @@ -211,8 +210,7 @@ public void testObjectSerialization() throws IOException, ClassNotFoundException 46, 79, 98, 106, 101, 99, 116, 73, 100, 36, 83, 101, 114, 105, 97, 108, 105, 122, 97, 116, 105, 111, 110, 80, 114, 111, 120, 121, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 91, 0, 5, 98, 121, 116, 101, 115, 116, 0, 2, 91, 66, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120, 112, 0, 0, 0, 12, 95, -113, 79, -49, 39, 81, 111, - 5, -25, -22, -27, -66}, - baos.toByteArray()); + 5, -25, -22, -27, -66}, baos.toByteArray()); // when ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); From 86452b8ac21884f8e480c1a7107ee2fed61af244 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Wed, 25 Oct 2023 08:46:55 -0400 Subject: [PATCH 06/28] Remove deprecation of DBCursor#explain Since we ended up adding explain support to FindIterable, no reason to leave it deprecated in the legacy API. JAVA-5154 --- driver-legacy/src/main/com/mongodb/DBCursor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/driver-legacy/src/main/com/mongodb/DBCursor.java b/driver-legacy/src/main/com/mongodb/DBCursor.java index e9c210e0b1a..8012a1a8727 100644 --- a/driver-legacy/src/main/com/mongodb/DBCursor.java +++ b/driver-legacy/src/main/com/mongodb/DBCursor.java @@ -369,7 +369,6 @@ public DBCursor maxTime(final long maxTime, final TimeUnit timeUnit) { * @mongodb.driver.manual reference/command/explain Explain Output * @mongodb.server.release 3.0 */ - @Deprecated public DBObject explain() { return executor.execute(getQueryOperation(collection.getObjectCodec()) .asExplainableOperation(null, getDefaultCodecRegistry().get(DBObject.class)), From 775d40cfd8f23a7237adc95a4b7e9e1d6b2962a6 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Mon, 6 Nov 2023 10:09:37 -0500 Subject: [PATCH 07/28] Remove dead code in ReplyHeader (#1231) The dead code is a remnant of when the driver supported the full range of OP_REPLY wire protocol message usage. Since the driver now only runs against MongoDB releases that support OP_MSG, OP_REPLY is only used for the response to the `hello` command in the handshake, and therefore most of the OP_REPLY-handling code is no longer on any execution paths. JAVA-5204 --- .../connection/InternalStreamConnection.java | 2 +- .../internal/connection/ReplyHeader.java | 108 +++--------------- .../internal/connection/ReplyMessage.java | 53 ++------- .../internal/connection/ResponseBuffers.java | 2 +- .../ReplyHeaderSpecification.groovy | 22 +--- .../CommandMessageSpecification.groovy | 20 +--- .../internal/connection/MessageHelper.java | 15 +-- .../internal/connection/ReplyMessageTest.java | 52 ++------- .../connection/TestInternalConnection.java | 12 +- 9 files changed, 53 insertions(+), 233 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index d3cd2eab867..c1593851d2d 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -546,7 +546,7 @@ private void sendCommandMessageAsync(final int messageId, final Decoder d } private T getCommandResult(final Decoder decoder, final ResponseBuffers responseBuffers, final int messageId) { - T result = new ReplyMessage<>(responseBuffers, decoder, messageId).getDocuments().get(0); + T result = new ReplyMessage<>(responseBuffers, decoder, messageId).getDocument(); MongoException writeConcernBasedError = createSpecialWriteConcernException(responseBuffers, description.getServerAddress()); if (writeConcernBasedError != null) { throw new MongoWriteConcernWithResponseException(writeConcernBasedError, result); diff --git a/driver-core/src/main/com/mongodb/internal/connection/ReplyHeader.java b/driver-core/src/main/com/mongodb/internal/connection/ReplyHeader.java index 2588db6e312..f1b723778a7 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ReplyHeader.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ReplyHeader.java @@ -40,17 +40,10 @@ public final class ReplyHeader { */ public static final int TOTAL_REPLY_HEADER_LENGTH = REPLY_HEADER_LENGTH + MESSAGE_HEADER_LENGTH; - private static final int CURSOR_NOT_FOUND_RESPONSE_FLAG = 1; - private static final int QUERY_FAILURE_RESPONSE_FLAG = 2; - private final int messageLength; private final int requestId; private final int responseTo; - private final int responseFlags; - private final long cursorId; - private final int startingFrom; - private final int numberReturned; - private final int opMsgFlagBits; + private final boolean hasMoreToCome; ReplyHeader(final ByteBuf header, final MessageHeader messageHeader) { this(messageHeader.getMessageLength(), messageHeader.getOpCode(), messageHeader, header); @@ -66,27 +59,23 @@ private ReplyHeader(final int messageLength, final int opCode, final MessageHead this.requestId = messageHeader.getRequestId(); this.responseTo = messageHeader.getResponseTo(); if (opCode == OP_MSG.getValue()) { - responseFlags = 0; - cursorId = 0; - startingFrom = 0; - numberReturned = 1; - - opMsgFlagBits = header.getInt(); - header.get(); // ignore payload type + int flagBits = header.getInt(); + hasMoreToCome = (flagBits & (1 << 1)) != 0; + header.get(); // ignored payload type } else if (opCode == OP_REPLY.getValue()) { if (messageLength < TOTAL_REPLY_HEADER_LENGTH) { - throw new MongoInternalException(format("The reply message length %d is less than the mimimum message length %d", + throw new MongoInternalException(format("The reply message length %d is less than the minimum message length %d", messageLength, TOTAL_REPLY_HEADER_LENGTH)); } + hasMoreToCome = false; - responseFlags = header.getInt(); - cursorId = header.getLong(); - startingFrom = header.getInt(); - numberReturned = header.getInt(); - opMsgFlagBits = 0; + header.getInt(); // ignored responseFlags + header.getLong(); // ignored cursorId + header.getInt(); // ignored startingFrom + int numberReturned = header.getInt(); - if (numberReturned < 0) { - throw new MongoInternalException(format("The reply message number of returned documents, %d, is less than 0", + if (numberReturned != 1) { + throw new MongoInternalException(format("The reply message number of returned documents, %d, is expected to be 1", numberReturned)); } } else { @@ -123,78 +112,7 @@ public int getResponseTo() { return responseTo; } - /** - * Gets additional information about the response. - *
    - *
  • 0 - CursorNotFound: Set when getMore is called but the cursor id is not valid at the server. Returned with zero - * results.
  • - *
  • 1 - QueryFailure: Set when query failed. Results consist of one document containing an "$err" field describing the - * failure. - *
  • 2 - ShardConfigStale: Drivers should ignore this. Only mongos will ever see this set, in which case, - * it needs to update config from the server. - *
  • 3 - AwaitCapable: Set when the server supports the AwaitData Query option. If it doesn't, - * a client should sleep a little between getMore's of a Tailable cursor. Mongod version 1.6 supports AwaitData and thus always - * sets AwaitCapable. - *
  • 4-31 - Reserved: Ignore - *
- * - * @return bit vector - see details above - */ - public int getResponseFlags() { - return responseFlags; - } - - /** - * Gets the cursor ID that this response is a part of. If there are no more documents to fetch from the server, the cursor ID will be 0. - * This cursor ID must be used in any messages used to get more data, and also must be closed by the client when no longer needed. - * - * @return cursor ID to use if the client needs to fetch more from the server - */ - public long getCursorId() { - return cursorId; - } - - /** - * Returns the position in the cursor that is the start point of this reply. - * - * @return where in the cursor this reply is starting - */ - public int getStartingFrom() { - return startingFrom; - } - - /** - * Gets the number of documents to expect in the body of this reply. - * - * @return number of documents in the reply - */ - public int getNumberReturned() { - return numberReturned; - } - - /** - * Gets whether this query was performed with a cursor ID that was not valid on the server. - * - * @return true if this reply indicates the request to get more data was performed with a cursor ID that's not valid on the server - */ - public boolean isCursorNotFound() { - return (responseFlags & CURSOR_NOT_FOUND_RESPONSE_FLAG) == CURSOR_NOT_FOUND_RESPONSE_FLAG; - } - - /** - * Gets whether the query failed or not. - * - * @return true if this reply indicates the query failed. - */ - public boolean isQueryFailure() { - return (responseFlags & QUERY_FAILURE_RESPONSE_FLAG) == QUERY_FAILURE_RESPONSE_FLAG; - } - - public int getOpMsgFlagBits() { - return opMsgFlagBits; - } - public boolean hasMoreToCome() { - return (opMsgFlagBits & (1 << 1)) != 0; + return hasMoreToCome; } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/ReplyMessage.java b/driver-core/src/main/com/mongodb/internal/connection/ReplyMessage.java index 624b909a76a..68af818281e 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ReplyMessage.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ReplyMessage.java @@ -23,9 +23,6 @@ import org.bson.io.BsonInput; import org.bson.io.ByteBufferBsonInput; -import java.util.ArrayList; -import java.util.List; - import static java.lang.String.format; /** @@ -35,50 +32,24 @@ */ public class ReplyMessage { - private final ReplyHeader replyHeader; - private final List documents; + private final T document; public ReplyMessage(final ResponseBuffers responseBuffers, final Decoder decoder, final long requestId) { - this(responseBuffers.getReplyHeader(), requestId); - - if (replyHeader.getNumberReturned() > 0) { - try (BsonInput bsonInput = new ByteBufferBsonInput(responseBuffers.getBodyByteBuffer().duplicate())) { - while (documents.size() < replyHeader.getNumberReturned()) { - try (BsonBinaryReader reader = new BsonBinaryReader(bsonInput)) { - documents.add(decoder.decode(reader, DecoderContext.builder().build())); - } - } - } finally { - responseBuffers.reset(); - } - } - } - - ReplyMessage(final ReplyHeader replyHeader, final long requestId) { - if (requestId != replyHeader.getResponseTo()) { + if (requestId != responseBuffers.getReplyHeader().getResponseTo()) { throw new MongoInternalException(format("The responseTo (%d) in the response does not match the requestId (%d) in the " - + "request", replyHeader.getResponseTo(), requestId)); + + "request", responseBuffers.getReplyHeader().getResponseTo(), requestId)); } - this.replyHeader = replyHeader; - - documents = new ArrayList<>(replyHeader.getNumberReturned()); - } - /** - * Gets the reply header. - * - * @return the reply header - */ - public ReplyHeader getReplyHeader() { - return replyHeader; + try (BsonInput bsonInput = new ByteBufferBsonInput(responseBuffers.getBodyByteBuffer().duplicate())) { + try (BsonBinaryReader reader = new BsonBinaryReader(bsonInput)) { + document = decoder.decode(reader, DecoderContext.builder().build()); + } + } finally { + responseBuffers.reset(); + } } - /** - * Gets the documents. - * - * @return the documents - */ - public List getDocuments() { - return documents; + public T getDocument() { + return document; } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/ResponseBuffers.java b/driver-core/src/main/com/mongodb/internal/connection/ResponseBuffers.java index d10b594ef6f..e984862fe0f 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ResponseBuffers.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ResponseBuffers.java @@ -49,7 +49,7 @@ public ReplyHeader getReplyHeader() { T getResponseDocument(final int messageId, final Decoder decoder) { ReplyMessage replyMessage = new ReplyMessage<>(this, decoder, messageId); reset(); - return replyMessage.getDocuments().get(0); + return replyMessage.getDocument(); } /** diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/ReplyHeaderSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/ReplyHeaderSpecification.groovy index 9436559e910..0407baeca8a 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/ReplyHeaderSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/ReplyHeaderSpecification.groovy @@ -35,7 +35,7 @@ class ReplyHeaderSpecification extends Specification { writeInt(responseFlags) writeLong(9000) writeInt(4) - writeInt(30) + writeInt(1) } def byteBuf = outputBuffer.byteBuffers.get(0) @@ -46,12 +46,6 @@ class ReplyHeaderSpecification extends Specification { replyHeader.messageLength == 186 replyHeader.requestId == 45 replyHeader.responseTo == 23 - replyHeader.responseFlags == responseFlags - replyHeader.cursorId == 9000 - replyHeader.startingFrom == 4 - replyHeader.numberReturned == 30 - replyHeader.cursorNotFound == cursorNotFound - replyHeader.queryFailure == queryFailure where: responseFlags << [0, 1, 2, 3] @@ -72,7 +66,7 @@ class ReplyHeaderSpecification extends Specification { writeInt(responseFlags) writeLong(9000) writeInt(4) - writeInt(30) + writeInt(1) } def byteBuf = outputBuffer.byteBuffers.get(0) def compressedHeader = new CompressedHeader(byteBuf, new MessageHeader(byteBuf, getDefaultMaxMessageSize())) @@ -84,12 +78,6 @@ class ReplyHeaderSpecification extends Specification { replyHeader.messageLength == 274 replyHeader.requestId == 45 replyHeader.responseTo == 23 - replyHeader.responseFlags == responseFlags - replyHeader.cursorId == 9000 - replyHeader.startingFrom == 4 - replyHeader.numberReturned == 30 - replyHeader.cursorNotFound == cursorNotFound - replyHeader.queryFailure == queryFailure where: responseFlags << [0, 1, 2, 3] @@ -138,7 +126,7 @@ class ReplyHeaderSpecification extends Specification { then: def ex = thrown(MongoInternalException) - ex.getMessage() == 'The reply message length 35 is less than the mimimum message length 36' + ex.getMessage() == 'The reply message length 35 is less than the minimum message length 36' } def 'should throw MongoInternalException on message size > max message size'() { @@ -182,7 +170,7 @@ class ReplyHeaderSpecification extends Specification { then: def ex = thrown(MongoInternalException) - ex.getMessage() == 'The reply message number of returned documents, -1, is less than 0' + ex.getMessage() == 'The reply message number of returned documents, -1, is expected to be 1' } def 'should throw MongoInternalException on num documents < 0 with compressed header'() { @@ -208,6 +196,6 @@ class ReplyHeaderSpecification extends Specification { then: def ex = thrown(MongoInternalException) - ex.getMessage() == 'The reply message number of returned documents, -1, is less than 0' + ex.getMessage() == 'The reply message number of returned documents, -1, is expected to be 1' } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageSpecification.groovy index 6449d202f1b..12d22e31fd1 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageSpecification.groovy @@ -28,7 +28,6 @@ import com.mongodb.internal.session.SessionContext import com.mongodb.internal.validator.NoOpFieldNameValidator import org.bson.BsonArray import org.bson.BsonBinary -import org.bson.BsonBinaryReader import org.bson.BsonDocument import org.bson.BsonInt32 import org.bson.BsonMaximumSizeExceededException @@ -37,10 +36,7 @@ import org.bson.BsonTimestamp import org.bson.ByteBuf import org.bson.ByteBufNIO import org.bson.codecs.BsonDocumentCodec -import org.bson.codecs.DecoderContext import org.bson.io.BasicOutputBuffer -import org.bson.io.BsonInput -import org.bson.io.ByteBufferBsonInput import spock.lang.Specification import java.nio.ByteBuffer @@ -63,7 +59,7 @@ class CommandMessageSpecification extends Specification { .serverType(serverType as ServerType) .sessionSupported(true) .build(), - responseExpected, exhaustAllowed, null, null, clusterConnectionMode, null) + responseExpected, null, null, clusterConnectionMode, null) def output = new BasicOutputBuffer() when: @@ -76,8 +72,7 @@ class CommandMessageSpecification extends Specification { messageHeader.opCode == OpCode.OP_MSG.value replyHeader.requestId < RequestMessage.currentGlobalId replyHeader.responseTo == 0 - ((replyHeader.opMsgFlagBits & (1 << 16)) != 0) == exhaustAllowed - ((replyHeader.opMsgFlagBits & (1 << 1)) == 0) == responseExpected + replyHeader.hasMoreToCome() != responseExpected def expectedCommandDocument = command.clone() .append('$db', new BsonString(namespace.databaseName)) @@ -97,7 +92,7 @@ class CommandMessageSpecification extends Specification { getCommandDocument(byteBuf, replyHeader) == expectedCommandDocument where: - [readPreference, serverType, clusterConnectionMode, sessionContext, responseExpected, exhaustAllowed] << [ + [readPreference, serverType, clusterConnectionMode, sessionContext, responseExpected] << [ [ReadPreference.primary(), ReadPreference.secondary()], [ServerType.REPLICA_SET_PRIMARY, ServerType.SHARD_ROUTER], [ClusterConnectionMode.SINGLE, ClusterConnectionMode.MULTIPLE], @@ -126,7 +121,6 @@ class CommandMessageSpecification extends Specification { getReadConcern() >> ReadConcern.DEFAULT } ], - [true, false], [true, false] ].combinations() } @@ -372,12 +366,6 @@ class CommandMessageSpecification extends Specification { } private static BsonDocument getCommandDocument(ByteBufNIO byteBuf, ReplyHeader replyHeader) { - new ReplyMessage(new ResponseBuffers(replyHeader, byteBuf), new BsonDocumentCodec(), 0).documents.get(0) - } - - private static BsonDocument getCommandDocument(ByteBufNIO byteBuf) { - BsonInput bsonInput = new ByteBufferBsonInput(byteBuf) - BsonBinaryReader reader = new BsonBinaryReader(bsonInput) - new BsonDocumentCodec().decode(reader, DecoderContext.builder().build()) + new ReplyMessage(new ResponseBuffers(replyHeader, byteBuf), new BsonDocumentCodec(), 0).document } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/MessageHelper.java b/driver-core/src/test/unit/com/mongodb/internal/connection/MessageHelper.java index c98351bf793..2ef3c59cb95 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/MessageHelper.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/MessageHelper.java @@ -55,24 +55,15 @@ public static ResponseBuffers buildSuccessfulReply(final int responseTo, final S return buildReply(responseTo, json, 0); } - public static ResponseBuffers buildFailedReply(final String json) { - return buildFailedReply(0, json); - } - - public static ResponseBuffers buildFailedReply(final int responseTo, final String json) { - return buildReply(responseTo, json, 2); - } - public static ResponseBuffers buildReply(final int responseTo, final String json, final int responseFlags) { ByteBuf body = encodeJson(json); body.flip(); - ReplyHeader header = buildReplyHeader(responseTo, 1, body.remaining(), responseFlags); + ReplyHeader header = buildReplyHeader(responseTo, body.remaining(), responseFlags); return new ResponseBuffers(header, body); } - private static ReplyHeader buildReplyHeader(final int responseTo, final int numDocuments, final int documentsSize, - final int responseFlags) { + private static ReplyHeader buildReplyHeader(final int responseTo, final int documentsSize, final int responseFlags) { ByteBuffer headerByteBuffer = ByteBuffer.allocate(36); headerByteBuffer.order(ByteOrder.LITTLE_ENDIAN); headerByteBuffer.putInt(36 + documentsSize); // length @@ -82,7 +73,7 @@ private static ReplyHeader buildReplyHeader(final int responseTo, final int numD headerByteBuffer.putInt(responseFlags); // responseFlags headerByteBuffer.putLong(0); // cursorId headerByteBuffer.putInt(0); // startingFrom - headerByteBuffer.putInt(numDocuments); //numberReturned + headerByteBuffer.putInt(1); //numberReturned ((Buffer) headerByteBuffer).flip(); ByteBufNIO buffer = new ByteBufNIO(headerByteBuffer); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ReplyMessageTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ReplyMessageTest.java index 7432ad713e9..8f454a30168 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ReplyMessageTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ReplyMessageTest.java @@ -17,58 +17,22 @@ package com.mongodb.internal.connection; import com.mongodb.MongoInternalException; -import org.bson.ByteBufNIO; -import org.bson.Document; -import org.junit.Test; +import org.bson.codecs.BsonDocumentCodec; +import org.junit.jupiter.api.Test; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import static com.mongodb.connection.ConnectionDescription.getDefaultMaxMessageSize; +import static com.mongodb.internal.connection.MessageHelper.buildReply; +import static org.junit.jupiter.api.Assertions.assertThrows; public class ReplyMessageTest { - @Test(expected = MongoInternalException.class) + @Test public void shouldThrowExceptionIfRequestIdDoesNotMatchResponseTo() { int badResponseTo = 34565; int expectedResponseTo = 5; - ByteBuffer headerByteBuffer = ByteBuffer.allocate(36); - headerByteBuffer.order(ByteOrder.LITTLE_ENDIAN); - headerByteBuffer.putInt(36); - headerByteBuffer.putInt(2456); - headerByteBuffer.putInt(badResponseTo); - headerByteBuffer.putInt(1); - headerByteBuffer.putInt(0); - headerByteBuffer.putLong(0); - headerByteBuffer.putInt(0); - headerByteBuffer.putInt(0); - ((Buffer) headerByteBuffer).flip(); - - ByteBufNIO byteBuf = new ByteBufNIO(headerByteBuffer); - ReplyHeader replyHeader = new ReplyHeader(byteBuf, new MessageHeader(byteBuf, getDefaultMaxMessageSize())); - new ReplyMessage(replyHeader, expectedResponseTo); - } - - @Test(expected = MongoInternalException.class) - public void shouldThrowExceptionIfOpCodeIsIncorrect() { - int badOpCode = 2; - - ByteBuffer headerByteBuffer = ByteBuffer.allocate(36); - headerByteBuffer.order(ByteOrder.LITTLE_ENDIAN); - headerByteBuffer.putInt(36); - headerByteBuffer.putInt(2456); - headerByteBuffer.putInt(5); - headerByteBuffer.putInt(badOpCode); - headerByteBuffer.putInt(0); - headerByteBuffer.putLong(0); - headerByteBuffer.putInt(0); - headerByteBuffer.putInt(0); - ((Buffer) headerByteBuffer).flip(); + ResponseBuffers responseBuffers = buildReply(badResponseTo, "{ok: 1}", 0); - ByteBufNIO byteBuf = new ByteBufNIO(headerByteBuffer); - ReplyHeader replyHeader = new ReplyHeader(byteBuf, new MessageHeader(byteBuf, getDefaultMaxMessageSize())); - new ReplyMessage(replyHeader, 5); + assertThrows(MongoInternalException.class, () -> + new ReplyMessage<>(responseBuffers, new BsonDocumentCodec(), expectedResponseTo)); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java b/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java index ce8b109cd52..e8003f692a9 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java @@ -177,7 +177,7 @@ public T sendAndReceive(final CommandMessage message, final Decoder decod throw getCommandFailureException(getResponseDocument(responseBuffers, message, new BsonDocumentCodec()), description.getServerAddress()); } - return new ReplyMessage<>(responseBuffers, decoder, message.getId()).getDocuments().get(0); + return new ReplyMessage<>(responseBuffers, decoder, message.getId()).getDocument(); } } @@ -200,7 +200,7 @@ private T getResponseDocument(final ResponseBuffers res final CommandMessage commandMessage, final Decoder decoder) { ReplyMessage replyMessage = new ReplyMessage<>(responseBuffers, decoder, commandMessage.getId()); responseBuffers.reset(); - return replyMessage.getDocuments().get(0); + return replyMessage.getDocument(); } @Override @@ -222,10 +222,10 @@ private ReplyHeader replaceResponseTo(final ReplyHeader header, final int respon headerByteBuffer.putInt(header.getRequestId()); headerByteBuffer.putInt(responseTo); headerByteBuffer.putInt(1); - headerByteBuffer.putInt(header.getResponseFlags()); - headerByteBuffer.putLong(header.getCursorId()); - headerByteBuffer.putInt(header.getStartingFrom()); - headerByteBuffer.putInt(header.getNumberReturned()); + headerByteBuffer.putInt(0); + headerByteBuffer.putLong(0); + headerByteBuffer.putInt(0); + headerByteBuffer.putInt(1); ((Buffer) headerByteBuffer).flip(); ByteBufNIO buffer = new ByteBufNIO(headerByteBuffer); From f75aaf6ea203b172ebdbbc2d2a1db8a0c1f9440f Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Mon, 6 Nov 2023 11:05:48 -0500 Subject: [PATCH 08/28] Fix Groovy test --- .../internal/connection/GSSAPIAuthenticatorSpecification.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy index 02f6652ded0..9f2ca47b9ee 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy @@ -47,7 +47,7 @@ class GSSAPIAuthenticatorSpecification extends Specification { def subjectProvider = Mock(SubjectProvider) def credential = ClusterFixture.getCredential().withMechanismProperty(JAVA_SUBJECT_PROVIDER_KEY, subjectProvider) def credentialWithCache = new MongoCredentialWithCache(credential) - def streamFactory = new SocketStreamFactory(settings.getInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()) + def streamFactory = new SocketStreamFactory(new DefaultInetAddressResolver(), SocketSettings.builder().build(), getSslSettings()) def internalConnection = new InternalStreamConnectionFactory(SINGLE, streamFactory, credentialWithCache, null, null, Collections. emptyList(), LoggerSettings.builder().build(), null, getServerApi()) .create(new ServerId(new ClusterId(), getPrimary())) From b78348924d713245ff73031d0250c3960b024057 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Mon, 6 Nov 2023 11:32:12 -0500 Subject: [PATCH 09/28] Fix ClusterFixture creation of NettyStreamFactoryFactory --- driver-core/src/test/functional/com/mongodb/ClusterFixture.java | 1 + 1 file changed, 1 insertion(+) diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index fdf2edae906..09bc55a1215 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -429,6 +429,7 @@ public static StreamFactory getAsyncStreamFactory() { } else { StreamFactoryFactory overriddenStreamFactoryFactory = NettyStreamFactoryFactory.builder() .applySettings((NettyTransportSettings) transportSettings) + .inetAddressResolver(new DefaultInetAddressResolver()) .build(); return assertNotNull(overriddenStreamFactoryFactory).create(getSocketSettings(), getSslSettings()); } From 58c8171114bba8e6c27652012d3cbcdfa3671aea Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Mon, 6 Nov 2023 11:36:59 -0500 Subject: [PATCH 10/28] Remove Stream#shouldSupportAdditionalTimeout method (#1227) Now that Stream is not part of the API, this method can be removed. It only existed due to the possibility that an application creates its own Stream implementation. JAVA-5180 --- .../connection/AsynchronousChannelStream.java | 5 ---- .../connection/DefaultConnectionPool.java | 10 ++------ .../connection/DefaultServerMonitor.java | 2 +- .../connection/InternalConnection.java | 4 --- .../connection/InternalStreamConnection.java | 5 ---- .../internal/connection/SocketStream.java | 5 ---- .../mongodb/internal/connection/Stream.java | 25 +------------------ .../TlsChannelStreamFactoryFactory.java | 5 ---- .../UsageTrackingInternalConnection.java | 5 ---- .../connection/netty/NettyStream.java | 5 ---- .../DefaultServerMonitorSpecification.groovy | 4 --- 11 files changed, 4 insertions(+), 71 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java index dc652dab0d2..6f2b7e5c172 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousChannelStream.java @@ -143,11 +143,6 @@ public ByteBuf read(final int numBytes) throws IOException { return handler.getRead(); } - @Override - public boolean supportsAdditionalTimeout() { - return true; - } - @Override public ByteBuf read(final int numBytes, final int additionalTimeout) throws IOException { FutureAsyncCompletionHandler handler = new FutureAsyncCompletionHandler<>(); diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index 61ef1f09c27..f235410eb7e 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -43,8 +43,6 @@ import com.mongodb.event.ConnectionPoolListener; import com.mongodb.event.ConnectionPoolReadyEvent; import com.mongodb.event.ConnectionReadyEvent; -import com.mongodb.internal.time.TimePoint; -import com.mongodb.internal.time.Timeout; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.connection.SdamServerDescriptionManager.SdamIssue; @@ -56,6 +54,8 @@ import com.mongodb.internal.logging.StructuredLogger; import com.mongodb.internal.session.SessionContext; import com.mongodb.internal.thread.DaemonThreadFactory; +import com.mongodb.internal.time.TimePoint; +import com.mongodb.internal.time.Timeout; import com.mongodb.lang.NonNull; import com.mongodb.lang.Nullable; import org.bson.ByteBuf; @@ -777,12 +777,6 @@ public T receive(final Decoder decoder, final SessionContext sessionConte return wrapped.receive(decoder, sessionContext); } - @Override - public boolean supportsAdditionalTimeout() { - isTrue("open", !isClosed.get()); - return wrapped.supportsAdditionalTimeout(); - } - @Override public T receive(final Decoder decoder, final SessionContext sessionContext, final int additionalTimeout) { isTrue("open", !isClosed.get()); diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultServerMonitor.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultServerMonitor.java index 9ad1f49e613..52b01176b4c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultServerMonitor.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultServerMonitor.java @@ -254,7 +254,7 @@ private ServerDescription lookupServerDescription(final ServerDescription curren } private boolean shouldStreamResponses(final ServerDescription currentServerDescription) { - return currentServerDescription.getTopologyVersion() != null && connection.supportsAdditionalTimeout(); + return currentServerDescription.getTopologyVersion() != null; } private CommandMessage createCommandMessage(final BsonDocument command, final InternalConnection connection, diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java index c14a816b525..405ef31f5cf 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalConnection.java @@ -103,10 +103,6 @@ T sendAndReceive(CommandMessage message, Decoder decoder, SessionContext T receive(Decoder decoder, SessionContext sessionContext); - default boolean supportsAdditionalTimeout() { - return false; - } - default T receive(Decoder decoder, SessionContext sessionContext, int additionalTimeout) { throw new UnsupportedOperationException(); } diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index c1593851d2d..dec5a1d1977 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -375,11 +375,6 @@ public T receive(final Decoder decoder, final SessionContext sessionConte return receiveCommandMessageResponse(decoder, new NoOpCommandEventSender(), sessionContext, 0); } - @Override - public boolean supportsAdditionalTimeout() { - return stream.supportsAdditionalTimeout(); - } - @Override public T receive(final Decoder decoder, final SessionContext sessionContext, final int additionalTimeout) { isTrue("Response is expected", hasMoreToCome); diff --git a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java index a7f71314757..7ee08fd967c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java @@ -186,11 +186,6 @@ public ByteBuf read(final int numBytes) throws IOException { } } - @Override - public boolean supportsAdditionalTimeout() { - return true; - } - @Override public ByteBuf read(final int numBytes, final int additionalTimeout) throws IOException { int curTimeout = socket.getSoTimeout(); diff --git a/driver-core/src/main/com/mongodb/internal/connection/Stream.java b/driver-core/src/main/com/mongodb/internal/connection/Stream.java index bcce2bfabba..b26074d218f 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/Stream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/Stream.java @@ -60,39 +60,16 @@ public interface Stream extends BufferProvider { */ ByteBuf read(int numBytes) throws IOException; - /** - * Gets whether this implementation supports specifying an additional timeout for read operations - *

- * The default is to not support specifying an additional timeout - *

- * - * @return true if this implementation supports specifying an additional timeouts for reads operations - * @see #read(int, int) - */ - default boolean supportsAdditionalTimeout() { - return false; - } - /** * Read from the stream, blocking until the requested number of bytes have been read. If supported by the implementation, * adds the given additional timeout to the configured timeout for the stream. - *

- * This method should not be called unless {@link #supportsAdditionalTimeout()} returns true. - *

- *

- * The default behavior is to throw an {@link UnsupportedOperationException} - *

* * @param numBytes The number of bytes to read into the returned byte buffer * @param additionalTimeout additional timeout in milliseconds to add to the configured timeout * @return a byte buffer filled with number of bytes requested * @throws IOException if there are problems reading from the stream - * @throws UnsupportedOperationException if this implementation does not support additional timeouts - * @see #supportsAdditionalTimeout() */ - default ByteBuf read(int numBytes, int additionalTimeout) throws IOException { - throw new UnsupportedOperationException(); - } + ByteBuf read(int numBytes, int additionalTimeout) throws IOException; /** * Write each buffer in the list to the stream in order, asynchronously. This method should return immediately, and invoke the given diff --git a/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java index 4f6bacef191..bce3c353137 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java @@ -179,11 +179,6 @@ private static class TlsChannelStream extends AsynchronousChannelStream { this.selectorMonitor = selectorMonitor; } - @Override - public boolean supportsAdditionalTimeout() { - return true; - } - @Override public void openAsync(final AsyncCompletionHandler handler) { isTrue("unopened", getChannel() == null); diff --git a/driver-core/src/main/com/mongodb/internal/connection/UsageTrackingInternalConnection.java b/driver-core/src/main/com/mongodb/internal/connection/UsageTrackingInternalConnection.java index 794ec2772d5..f0ae4a9244e 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/UsageTrackingInternalConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/UsageTrackingInternalConnection.java @@ -129,11 +129,6 @@ public T receive(final Decoder decoder, final SessionContext sessionConte return result; } - @Override - public boolean supportsAdditionalTimeout() { - return wrapped.supportsAdditionalTimeout(); - } - @Override public T receive(final Decoder decoder, final SessionContext sessionContext, final int additionalTimeout) { T result = wrapped.receive(decoder, sessionContext, additionalTimeout); diff --git a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java index 8d9f9b65372..1f3c6ec9a1b 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStream.java @@ -240,11 +240,6 @@ public ByteBuf read(final int numBytes) throws IOException { return read(numBytes, 0); } - @Override - public boolean supportsAdditionalTimeout() { - return true; - } - @Override public ByteBuf read(final int numBytes, final int additionalTimeoutMillis) throws IOException { isTrueArgument("additionalTimeoutMillis must not be negative", additionalTimeoutMillis >= 0); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerMonitorSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerMonitorSpecification.groovy index d1790a8acb7..df0b6518dcc 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerMonitorSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerMonitorSpecification.groovy @@ -157,8 +157,6 @@ class DefaultServerMonitorSpecification extends Specification { initialServerDescription } - supportsAdditionalTimeout() >> true - send(_, _, _) >> { } receive(_, _) >> { @@ -238,8 +236,6 @@ class DefaultServerMonitorSpecification extends Specification { initialServerDescription } - supportsAdditionalTimeout() >> true - send(_, _, _) >> { } receive(_, _) >> { From f845b65219ee5277b2cccbe4d9977345b65e6044 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Wed, 25 Oct 2023 23:28:14 -0400 Subject: [PATCH 11/28] Remove deprecated methods in read preference classes JAVA-5145 --- .../src/main/com/mongodb/ReadPreference.java | 14 -------------- .../main/com/mongodb/TaggableReadPreference.java | 6 ------ 2 files changed, 20 deletions(-) diff --git a/driver-core/src/main/com/mongodb/ReadPreference.java b/driver-core/src/main/com/mongodb/ReadPreference.java index 5e7f86c033d..0d5267f3842 100644 --- a/driver-core/src/main/com/mongodb/ReadPreference.java +++ b/driver-core/src/main/com/mongodb/ReadPreference.java @@ -101,15 +101,6 @@ public abstract class ReadPreference { */ public abstract ReadPreference withHedgeOptions(ReadPreferenceHedgeOptions hedgeOptions); - /** - * True if this read preference allows reading from a secondary member of a replica set. - * - * @return if reading from a secondary is ok - * @deprecated Prefer {@link #isSecondaryOk()} - */ - @Deprecated - public abstract boolean isSlaveOk(); - /** * True if this read preference allows reading from a secondary member of a replica set. * @@ -696,11 +687,6 @@ public TaggableReadPreference withHedgeOptions(final ReadPreferenceHedgeOptions throw new UnsupportedOperationException("Primary read preference can not also specify hedge"); } - @Override - public boolean isSlaveOk() { - return false; - } - @Override public boolean isSecondaryOk() { return false; diff --git a/driver-core/src/main/com/mongodb/TaggableReadPreference.java b/driver-core/src/main/com/mongodb/TaggableReadPreference.java index 0418a429507..d92afa128fb 100644 --- a/driver-core/src/main/com/mongodb/TaggableReadPreference.java +++ b/driver-core/src/main/com/mongodb/TaggableReadPreference.java @@ -83,12 +83,6 @@ public abstract class TaggableReadPreference extends ReadPreference { @Override public abstract TaggableReadPreference withHedgeOptions(ReadPreferenceHedgeOptions hedgeOptions); - @Override - @Deprecated - public boolean isSlaveOk() { - return true; - } - @Override public boolean isSecondaryOk() { return true; From db1866a42d1c140000c6983dfd3d7963d15d2490 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Wed, 25 Oct 2023 23:31:29 -0400 Subject: [PATCH 12/28] Remove deprecated connection string option JAVA-4144 --- .../src/main/com/mongodb/ConnectionString.java | 11 ----------- .../com/mongodb/ConnectionStringSpecification.groovy | 5 ----- .../com/mongodb/MongoClientURISpecification.groovy | 2 +- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/driver-core/src/main/com/mongodb/ConnectionString.java b/driver-core/src/main/com/mongodb/ConnectionString.java index 9914c0d0aa7..5e6a5b7d81a 100644 --- a/driver-core/src/main/com/mongodb/ConnectionString.java +++ b/driver-core/src/main/com/mongodb/ConnectionString.java @@ -1018,17 +1018,6 @@ private Map> parseOptions(final String optionsPart) { LOGGER.warn("Uri option 'wtimeout' has been deprecated, use 'wtimeoutms' instead."); } } - String legacySecondaryOkOption = "slaveok"; - // handle legacy secondary ok settings - String legacySecondaryOk = getLastValue(optionsMap, legacySecondaryOkOption); - if (legacySecondaryOk != null && !optionsMap.containsKey("readpreference")) { - String readPreference = Boolean.TRUE.equals(parseBoolean(legacySecondaryOk, legacySecondaryOkOption)) - ? "secondaryPreferred" : "primary"; - optionsMap.put("readpreference", singletonList(readPreference)); - if (LOGGER.isWarnEnabled()) { - LOGGER.warn(format("Uri option '%s' has been deprecated, use 'readpreference' instead.", legacySecondaryOkOption)); - } - } // handle legacy j settings if (optionsMap.containsKey("j") && !optionsMap.containsKey("journal")) { optionsMap.put("journal", optionsMap.remove("j")); diff --git a/driver-core/src/test/unit/com/mongodb/ConnectionStringSpecification.groovy b/driver-core/src/test/unit/com/mongodb/ConnectionStringSpecification.groovy index 536a1e482e4..e0245e80092 100644 --- a/driver-core/src/test/unit/com/mongodb/ConnectionStringSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/ConnectionStringSpecification.groovy @@ -604,8 +604,6 @@ class ConnectionStringSpecification extends Specification { thrown(IllegalArgumentException) } - private static final LEGACY_SECONDARY_OK = 'slaveOk' - @Unroll def 'should correct parse read preference for #readPreference'() { expect: @@ -620,9 +618,6 @@ class ConnectionStringSpecification extends Specification { '?readPreference=secondary') | secondary() new ConnectionString('mongodb://localhost/' + '?readPreference=secondaryPreferred') | secondaryPreferred() - new ConnectionString("mongodb://localhost/?${LEGACY_SECONDARY_OK}=true") | secondaryPreferred() - new ConnectionString("mongodb://localhost/?${LEGACY_SECONDARY_OK}=false") | primary() - new ConnectionString("mongodb://localhost/?${LEGACY_SECONDARY_OK}=foo") | primary() new ConnectionString('mongodb://localhost/' + '?readPreference=secondaryPreferred' + '&readPreferenceTags=dc:ny,rack:1' + diff --git a/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy b/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy index 2992f2e0f96..3db0e1a45d8 100644 --- a/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy +++ b/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy @@ -422,7 +422,7 @@ class MongoClientURISpecification extends Specification { + 'minPoolSize=7;maxIdleTimeMS=1000;maxLifeTimeMS=2000;maxConnecting=1;' + 'replicaSet=test;' + 'connectTimeoutMS=2500;socketTimeoutMS=5500;autoConnectRetry=true;' - + 'slaveOk=true;safe=false;w=1;wtimeout=2600') + + 'readPreference=secondaryPreferred;safe=false;w=1;wtimeout=2600') MongoClientOptions.Builder builder = MongoClientOptions.builder() .connectionsPerHost(10) From a0ccaf722d952dfefafcfe1f3c4f2c7c30978a2c Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 26 Oct 2023 11:02:58 -0400 Subject: [PATCH 13/28] Remove deprecated DBCollection methods * getStats * isCapped JAVA-5116 --- .../src/main/com/mongodb/DBCollection.java | 32 ------------------- .../mongodb/DBCollectionSpecification.groovy | 21 ------------ .../test/functional/com/mongodb/DBTest.java | 20 +++--------- 3 files changed, 5 insertions(+), 68 deletions(-) diff --git a/driver-legacy/src/main/com/mongodb/DBCollection.java b/driver-legacy/src/main/com/mongodb/DBCollection.java index 0310cf96571..aadc99a2ea9 100644 --- a/driver-legacy/src/main/com/mongodb/DBCollection.java +++ b/driver-legacy/src/main/com/mongodb/DBCollection.java @@ -1917,38 +1917,6 @@ public void dropIndexes(final String indexName) { dropIndex(indexName); } - /** - * The collStats command returns a variety of storage statistics for a given collection - * - * @return a CommandResult containing the statistics about this collection - * @mongodb.driver.manual reference/command/collStats/ collStats Command - * @mongodb.driver.manual reference/operator/aggregation/collStats/ $collStats - * @deprecated If you are using server release 3.4 or newer, use the {@code $collStats} aggregation pipeline stage via - * {@link #aggregate(List, AggregationOptions)} instead. - * This method uses the {@code collStats} command, which is deprecated since server release 6.2. - */ - @Deprecated - public CommandResult getStats() { - return getDB().executeCommand(new BsonDocument("collStats", new BsonString(getName())), getReadPreference()); - } - - /** - * Checks whether this collection is capped - * - * @return true if this is a capped collection - * @mongodb.driver.manual core/capped-collections/#check-if-a-collection-is-capped Capped Collections - * @mongodb.driver.manual reference/operator/aggregation/collStats/ $collStats - * @deprecated If you are using server release 3.4 or newer, use the {@code $collStats} aggregation pipeline stage via - * {@link #aggregate(List, AggregationOptions)} instead, and inspect the {@code storageStats.capped} field. - * This method uses the {@code collStats} command, which is deprecated since server release 6.2. - */ - @Deprecated - public boolean isCapped() { - CommandResult commandResult = getStats(); - Object cappedField = commandResult.get("capped"); - return cappedField != null && (cappedField.equals(1) || cappedField.equals(true)); - } - /** * Gets the default class for objects in the collection * diff --git a/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy b/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy index c24368de965..0ee87ec37d1 100644 --- a/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy +++ b/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy @@ -35,7 +35,6 @@ import com.mongodb.internal.bulk.UpdateRequest import com.mongodb.internal.operation.AggregateOperation import com.mongodb.internal.operation.AggregateToCollectionOperation import com.mongodb.internal.operation.BatchCursor -import com.mongodb.internal.operation.CommandReadOperation import com.mongodb.internal.operation.CountOperation import com.mongodb.internal.operation.CreateIndexesOperation import com.mongodb.internal.operation.DistinctOperation @@ -53,18 +52,15 @@ import org.bson.BsonDocument import org.bson.BsonDocumentWrapper import org.bson.BsonInt32 import org.bson.BsonJavaScript -import org.bson.BsonString import org.bson.UuidRepresentation import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.BsonValueCodec import org.bson.codecs.UuidCodec -import spock.lang.IgnoreIf import spock.lang.Specification import java.util.concurrent.TimeUnit import static Fixture.getMongoClient -import static com.mongodb.ClusterFixture.serverVersionAtLeast import static com.mongodb.CustomMatchers.isTheSameAs import static com.mongodb.LegacyMixedBulkWriteOperation.createBulkWriteOperationForDelete import static com.mongodb.LegacyMixedBulkWriteOperation.createBulkWriteOperationForUpdate @@ -262,23 +258,6 @@ class DBCollectionSpecification extends Specification { thrown(IllegalArgumentException) } - @IgnoreIf({ serverVersionAtLeast(6, 2) }) - def 'getStats should execute the expected command with the collection default read preference'() { - given: - def executor = new TestOperationExecutor([new BsonDocument('ok', new BsonInt32(1))]) - def collection = new DB(getMongoClient(), 'myDatabase', executor).getCollection('test') - collection.setReadPreference(ReadPreference.secondary()) - - when: - collection.getStats() - - then: - expect executor.getReadOperation(), isTheSameAs(new CommandReadOperation('myDatabase', - new BsonDocument('collStats', new BsonString('test')), - new BsonDocumentCodec())) - executor.getReadPreference() == collection.getReadPreference() - } - def 'find should create the correct FindOperation'() { given: def cursor = Stub(BatchCursor) { diff --git a/driver-legacy/src/test/functional/com/mongodb/DBTest.java b/driver-legacy/src/test/functional/com/mongodb/DBTest.java index 0dc89b21f2c..8b2f8f59d90 100644 --- a/driver-legacy/src/test/functional/com/mongodb/DBTest.java +++ b/driver-legacy/src/test/functional/com/mongodb/DBTest.java @@ -37,7 +37,6 @@ import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.ClusterFixture.isSharded; import static com.mongodb.ClusterFixture.serverVersionAtLeast; -import static com.mongodb.ClusterFixture.serverVersionLessThan; import static com.mongodb.DBObjectMatchers.hasFields; import static com.mongodb.DBObjectMatchers.hasSubdocument; import static com.mongodb.Fixture.getDefaultDatabaseName; @@ -351,23 +350,14 @@ BsonDocument getCollectionInfo(final String collectionName) { } private boolean isCapped(final DBCollection collection) { - if (serverVersionLessThan(6, 2)) { - return collection.isCapped(); - } else { - Object capped = storageStats(collection).get("capped"); - return Boolean.TRUE.equals(capped) || Integer.valueOf(1).equals(capped); - } + return Boolean.TRUE.equals(storageStats(collection).get("capped")); } private DBObject storageStats(final DBCollection collection) { - if (serverVersionLessThan(6, 2)) { - return collection.getStats(); - } else { - try (Cursor cursor = collection.aggregate(singletonList( - new BasicDBObject("$collStats", new BasicDBObject("storageStats", new BasicDBObject()))), - AggregationOptions.builder().build())) { - return (DBObject) cursor.next().get("storageStats"); - } + try (Cursor cursor = collection.aggregate(singletonList( + new BasicDBObject("$collStats", new BasicDBObject("storageStats", new BasicDBObject()))), + AggregationOptions.builder().build())) { + return (DBObject) cursor.next().get("storageStats"); } } } From d83b259db4ec5bd73f636e5fb21618655dfd339f Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Mon, 6 Nov 2023 18:47:48 -0500 Subject: [PATCH 14/28] Remove deprecated index-related methods JAVA-5152 --- .../mongodb/client/model/IndexOptions.java | 29 ------------------- .../com/mongodb/client/model/Indexes.java | 21 -------------- .../mongodb/internal/bulk/IndexRequest.java | 13 --------- .../operation/CreateIndexesOperation.java | 3 -- .../internal/operation/Operations.java | 2 -- .../IndexesFunctionalSpecification.groovy | 12 -------- .../mongodb/client/test/CollectionHelper.java | 6 ---- ...CreateIndexesOperationSpecification.groovy | 18 ------------ .../mongodb/IndexRequestSpecification.groovy | 3 -- .../model/IndexOptionsSpecification.groovy | 3 -- .../client/model/IndexesSpecification.groovy | 6 ---- .../src/main/com/mongodb/DBCollection.java | 3 -- .../mongodb/DBCollectionSpecification.groovy | 3 +- .../org/mongodb/scala/model/Indexes.scala | 17 ----------- .../org/mongodb/scala/model/IndexesSpec.scala | 4 --- .../MongoCollectionSpecification.groovy | 2 -- 16 files changed, 1 insertion(+), 144 deletions(-) diff --git a/driver-core/src/main/com/mongodb/client/model/IndexOptions.java b/driver-core/src/main/com/mongodb/client/model/IndexOptions.java index 74c9dfdab64..f3cf45b5a3f 100644 --- a/driver-core/src/main/com/mongodb/client/model/IndexOptions.java +++ b/driver-core/src/main/com/mongodb/client/model/IndexOptions.java @@ -42,7 +42,6 @@ public class IndexOptions { private Integer bits; private Double min; private Double max; - private Double bucketSize; private Bson storageEngine; private Bson partialFilterExpression; private Collation collation; @@ -371,33 +370,6 @@ public IndexOptions max(@Nullable final Double max) { return this; } - /** - * Gets the specified the number of units within which to group the location values for geoHaystack Indexes - * - * @return the specified the number of units within which to group the location values for geoHaystack Indexes - * @mongodb.driver.manual core/geohaystack/ geoHaystack Indexes - * @deprecated geoHaystack is deprecated in MongoDB 4.4 - */ - @Nullable - @Deprecated - public Double getBucketSize() { - return bucketSize; - } - - /** - * Sets the specified the number of units within which to group the location values for geoHaystack Indexes - * - * @param bucketSize the specified the number of units within which to group the location values for geoHaystack Indexes - * @return this - * @mongodb.driver.manual core/geohaystack/ geoHaystack Indexes - * @deprecated geoHaystack is deprecated in MongoDB 4.4 - */ - @Deprecated - public IndexOptions bucketSize(@Nullable final Double bucketSize) { - this.bucketSize = bucketSize; - return this; - } - /** * Gets the storage engine options document for this index. * @@ -537,7 +509,6 @@ public String toString() { + ", bits=" + bits + ", min=" + min + ", max=" + max - + ", bucketSize=" + bucketSize + ", storageEngine=" + storageEngine + ", partialFilterExpression=" + partialFilterExpression + ", collation=" + collation diff --git a/driver-core/src/main/com/mongodb/client/model/Indexes.java b/driver-core/src/main/com/mongodb/client/model/Indexes.java index 553b206755c..e310e4bbcb7 100644 --- a/driver-core/src/main/com/mongodb/client/model/Indexes.java +++ b/driver-core/src/main/com/mongodb/client/model/Indexes.java @@ -127,27 +127,6 @@ public static Bson geo2d(final String fieldName) { return new BsonDocument(fieldName, new BsonString("2d")); } - /** - * Create an index key for a geohaystack index on the given field. - * - *

- * Note: For queries that use spherical geometry, a 2dsphere index is a better option than a haystack index. - * 2dsphere indexes allow field reordering; geoHaystack indexes require the first field to be the location field. Also, geoHaystack - * indexes are only usable via commands and so always return all results at once.. - *

- * - * @param fieldName the field to create a geoHaystack index on - * @param additional the additional field that forms the geoHaystack index key - * @return the index specification - * @mongodb.driver.manual core/geohaystack geoHaystack index - * @deprecated geoHaystack is deprecated in MongoDB 4.4, prefer {@link Indexes#geo2dsphere(String...)} - */ - @Deprecated - public static Bson geoHaystack(final String fieldName, final Bson additional) { - notNull("fieldName", fieldName); - return compoundIndex(new BsonDocument(fieldName, new BsonString("geoHaystack")), additional); - } - /** * Create an index key for a text index on the given field. * diff --git a/driver-core/src/main/com/mongodb/internal/bulk/IndexRequest.java b/driver-core/src/main/com/mongodb/internal/bulk/IndexRequest.java index 552b8ab2f44..ce515a1e598 100644 --- a/driver-core/src/main/com/mongodb/internal/bulk/IndexRequest.java +++ b/driver-core/src/main/com/mongodb/internal/bulk/IndexRequest.java @@ -50,7 +50,6 @@ public class IndexRequest { private Integer bits; private Double min; private Double max; - private Double bucketSize; private boolean dropDups; private BsonDocument storageEngine; private BsonDocument partialFilterExpression; @@ -216,18 +215,6 @@ public IndexRequest max(@Nullable final Double max) { return this; } - @Deprecated - @Nullable - public Double getBucketSize() { - return bucketSize; - } - - @Deprecated - public IndexRequest bucketSize(@Nullable final Double bucketSize) { - this.bucketSize = bucketSize; - return this; - } - public boolean getDropDups() { return dropDups; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java b/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java index b47b45a5eee..f3aae267b62 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java @@ -200,9 +200,6 @@ private BsonDocument getIndex(final IndexRequest request) { if (request.getMax() != null) { index.append("max", new BsonDouble(assertNotNull(request.getMax()))); } - if (request.getBucketSize() != null) { - index.append("bucketSize", new BsonDouble(assertNotNull(request.getBucketSize()))); - } if (request.getDropDups()) { index.append("dropDups", BsonBoolean.TRUE); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/Operations.java b/driver-core/src/main/com/mongodb/internal/operation/Operations.java index ed84e9b2e72..e65dc73d98e 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/Operations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/Operations.java @@ -609,7 +609,6 @@ CreateViewOperation createView(final String viewName, final String viewOn, final assertNotNull(toBsonDocumentList(pipeline)), writeConcern).collation(createViewOptions.getCollation()); } - @SuppressWarnings("deprecation") CreateIndexesOperation createIndexes(final List indexes, final CreateIndexOptions createIndexOptions) { notNull("indexes", indexes); notNull("createIndexOptions", createIndexOptions); @@ -633,7 +632,6 @@ CreateIndexesOperation createIndexes(final List indexes, final Creat .bits(model.getOptions().getBits()) .min(model.getOptions().getMin()) .max(model.getOptions().getMax()) - .bucketSize(model.getOptions().getBucketSize()) .storageEngine(toBsonDocument(model.getOptions().getStorageEngine())) .partialFilterExpression(toBsonDocument(model.getOptions().getPartialFilterExpression())) .collation(model.getOptions().getCollation()) diff --git a/driver-core/src/test/functional/com/mongodb/client/model/IndexesFunctionalSpecification.groovy b/driver-core/src/test/functional/com/mongodb/client/model/IndexesFunctionalSpecification.groovy index 92001f61470..2058d2cd197 100644 --- a/driver-core/src/test/functional/com/mongodb/client/model/IndexesFunctionalSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/client/model/IndexesFunctionalSpecification.groovy @@ -17,15 +17,12 @@ package com.mongodb.client.model import com.mongodb.OperationFunctionalSpecification -import spock.lang.IgnoreIf -import static com.mongodb.ClusterFixture.serverVersionAtLeast import static com.mongodb.client.model.Indexes.ascending import static com.mongodb.client.model.Indexes.compoundIndex import static com.mongodb.client.model.Indexes.descending import static com.mongodb.client.model.Indexes.geo2d import static com.mongodb.client.model.Indexes.geo2dsphere -import static com.mongodb.client.model.Indexes.geoHaystack import static com.mongodb.client.model.Indexes.hashed import static com.mongodb.client.model.Indexes.text import static org.bson.BsonDocument.parse @@ -100,15 +97,6 @@ class IndexesFunctionalSpecification extends OperationFunctionalSpecification { getCollectionHelper().listIndexes()*.get('key').contains(parse('{x : "2d"}')) } - @IgnoreIf({ serverVersionAtLeast(5, 0) }) - def 'geoHaystack'() { - when: - getCollectionHelper().createIndex(geoHaystack('x', descending('b')), 2.0) - - then: - getCollectionHelper().listIndexes()*.get('key').contains(parse('{x : "geoHaystack", b: -1}')) - } - def 'text helper'() { when: getCollectionHelper().createIndex(text('x')) diff --git a/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java b/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java index e2216629a7a..9bf435d013e 100644 --- a/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java +++ b/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java @@ -385,12 +385,6 @@ public void createIndex(final Bson key) { WriteConcern.ACKNOWLEDGED).execute(getBinding()); } - @SuppressWarnings("deprecation") - public void createIndex(final Bson key, final Double bucketSize) { - new CreateIndexesOperation(namespace, asList(new IndexRequest(key.toBsonDocument(Document.class, registry)) - .bucketSize(bucketSize)), WriteConcern.ACKNOWLEDGED).execute(getBinding()); - } - public List listIndexes(){ List indexes = new ArrayList<>(); BatchCursor cursor = new ListIndexesOperation<>(namespace, new BsonDocumentCodec()).execute(getBinding()); diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy index ee0725a9bde..3f0f1938bb6 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy @@ -334,24 +334,6 @@ class CreateIndexesOperationSpecification extends OperationFunctionalSpecificati async << [true, false] } - @IgnoreIf({ serverVersionAtLeast(5, 0) }) - def 'should be able to create a geoHaystack indexes'() { - given: - def operation = new CreateIndexesOperation(getNamespace(), - [new IndexRequest(new BsonDocument('field', new BsonString('geoHaystack')).append('field1', new BsonInt32(1))) - .bucketSize(10.0)]) - - when: - execute(operation, async) - - then: - getUserCreatedIndexes('key') == [[field: 'geoHaystack', field1: 1]] - getUserCreatedIndexes('bucketSize') == [10.0] - - where: - async << [true, false] - } - def 'should be able to create a 2dSphereIndex'() { given: def operation = new CreateIndexesOperation(getNamespace(), diff --git a/driver-core/src/test/unit/com/mongodb/IndexRequestSpecification.groovy b/driver-core/src/test/unit/com/mongodb/IndexRequestSpecification.groovy index 5673527b72f..d36a3ad771c 100644 --- a/driver-core/src/test/unit/com/mongodb/IndexRequestSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/IndexRequestSpecification.groovy @@ -50,7 +50,6 @@ class IndexRequestSpecification extends Specification { request.getBits() == null request.getMin() == null request.getMax() == null - request.getBucketSize() == null !request.getDropDups() request.getStorageEngine() == null request.getPartialFilterExpression() == null @@ -89,7 +88,6 @@ class IndexRequestSpecification extends Specification { .bits(1) .min(-180.0) .max(180.0) - .bucketSize(200.0) .dropDups(true) .storageEngine(storageEngine) .partialFilterExpression(partialFilterExpression) @@ -113,7 +111,6 @@ class IndexRequestSpecification extends Specification { request2.getBits() == 1 request2.getMin() == -180.0 request2.getMax() == 180.0 - request2.getBucketSize() == 200.0 request2.getDropDups() request2.getStorageEngine() == storageEngine request2.getPartialFilterExpression() == partialFilterExpression diff --git a/driver-core/src/test/unit/com/mongodb/client/model/IndexOptionsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/client/model/IndexOptionsSpecification.groovy index f336d656dc5..5342cfed885 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/IndexOptionsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/client/model/IndexOptionsSpecification.groovy @@ -42,7 +42,6 @@ class IndexOptionsSpecification extends Specification { options.getBits() == null options.getMin() == null options.getMax() == null - options.getBucketSize() == null options.getStorageEngine() == null options.getPartialFilterExpression() == null options.getCollation() == null @@ -69,7 +68,6 @@ class IndexOptionsSpecification extends Specification { .bits(1) .min(-180.0) .max(180.0) - .bucketSize(200.0) .storageEngine(storageEngine) .partialFilterExpression(partialFilterExpression) .collation(collation) @@ -91,7 +89,6 @@ class IndexOptionsSpecification extends Specification { options.getBits() == 1 options.getMin() == -180.0 options.getMax() == 180.0 - options.getBucketSize() == 200.0 options.getStorageEngine() == storageEngine options.getPartialFilterExpression() == partialFilterExpression options.getCollation() == collation diff --git a/driver-core/src/test/unit/com/mongodb/client/model/IndexesSpecification.groovy b/driver-core/src/test/unit/com/mongodb/client/model/IndexesSpecification.groovy index a887091d8d9..ac999f5b911 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/IndexesSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/client/model/IndexesSpecification.groovy @@ -25,7 +25,6 @@ import static com.mongodb.client.model.Indexes.compoundIndex import static com.mongodb.client.model.Indexes.descending import static com.mongodb.client.model.Indexes.geo2d import static com.mongodb.client.model.Indexes.geo2dsphere -import static com.mongodb.client.model.Indexes.geoHaystack import static com.mongodb.client.model.Indexes.hashed import static com.mongodb.client.model.Indexes.text import static org.bson.BsonDocument.parse @@ -58,11 +57,6 @@ class IndexesSpecification extends Specification { toBson(geo2d('x')) == parse('{x : "2d"}') } - def 'geoHaystack'() { - expect: - toBson(geoHaystack('x', descending('b'))) == parse('{x : "geoHaystack", b: -1}') - } - def 'text helper'() { expect: toBson(text('x')) == parse('{x : "text"}') diff --git a/driver-legacy/src/main/com/mongodb/DBCollection.java b/driver-legacy/src/main/com/mongodb/DBCollection.java index aadc99a2ea9..e71fd8c3aa4 100644 --- a/driver-legacy/src/main/com/mongodb/DBCollection.java +++ b/driver-legacy/src/main/com/mongodb/DBCollection.java @@ -2107,9 +2107,6 @@ private CreateIndexesOperation createIndexOperation(final DBObject key, final DB if (options.containsField("max")) { request.max(convertOptionsToType(options, "max", Double.class)); } - if (options.containsField("bucketSize")) { - request.bucketSize(convertOptionsToType(options, "bucketSize", Double.class)); - } if (options.containsField("dropDups")) { request.dropDups(convertOptionsToType(options, "dropDups", Boolean.class)); } diff --git a/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy b/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy index 0ee87ec37d1..6118ce4cdaa 100644 --- a/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy +++ b/driver-legacy/src/test/functional/com/mongodb/DBCollectionSpecification.groovy @@ -155,7 +155,7 @@ class DBCollectionSpecification extends Specification { 'expireAfterSeconds': 100, 'v': 1, 'weights': new BasicDBObject(['a': 1000]), 'default_language': 'es', 'language_override': 'language', 'textIndexVersion': 1, '2dsphereIndexVersion': 1, 'bits': 1, 'min': new Double(-180.0), - 'max' : new Double(180.0), 'bucketSize': new Double(200.0), 'dropDups': true, + 'max' : new Double(180.0), 'dropDups': true, 'storageEngine': BasicDBObject.parse(storageEngine), 'partialFilterExpression': BasicDBObject.parse(partialFilterExpression), 'collation': BasicDBObject.parse(collation.asDocument().toJson())])) @@ -178,7 +178,6 @@ class DBCollectionSpecification extends Specification { .bits(1) .min(-180.0) .max(180.0) - .bucketSize(200.0) .dropDups(true) .storageEngine(BsonDocument.parse(storageEngine)) .partialFilterExpression(BsonDocument.parse(partialFilterExpression)) diff --git a/driver-scala/src/main/scala/org/mongodb/scala/model/Indexes.scala b/driver-scala/src/main/scala/org/mongodb/scala/model/Indexes.scala index 252ceed6a5b..00680c6ec50 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/model/Indexes.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/model/Indexes.scala @@ -74,23 +74,6 @@ object Indexes { */ def geo2d(fieldName: String): Bson = JIndexes.geo2d(fieldName) - /** - * Create an index key for a geohaystack index on the given field. - * - *

- * Note: For queries that use spherical geometry, a 2dsphere index is a better option than a haystack index. - * 2dsphere indexes allow field reordering; geoHaystack indexes require the first field to be the location field. Also, geoHaystack - * indexes are only usable via commands and so always return all results at once.. - *

- * - * @param fieldName the field to create a geoHaystack index on - * @param additional the additional field that forms the geoHaystack index key - * @return the index specification - * @see [[https://www.mongodb.com/docs/manual/core/geohaystack geoHaystack index]] - */ - @deprecated("geoHaystack is deprecated in MongoDB 4.4", "4.2.1") - def geoHaystack(fieldName: String, additional: Bson): Bson = JIndexes.geoHaystack(fieldName, additional) - /** * Create an index key for a text index on the given field. * diff --git a/driver-scala/src/test/scala/org/mongodb/scala/model/IndexesSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/model/IndexesSpec.scala index afb313aa19b..10a9eb0a6b6 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/model/IndexesSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/model/IndexesSpec.scala @@ -59,10 +59,6 @@ class IndexesSpec extends BaseSpec { toBson(geo2d("x")) should equal(Document("""{x : "2d"}""")) } - it should "geoHaystack" in { - toBson(geoHaystack("x", descending("b"))) should equal(Document("""{x : "geoHaystack", b: -1}""")) - } - it should "text" in { toBson(text("x")) should equal(Document("""{x : "text"}""")) } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy index 1a45c682ae6..5951a5b6589 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy @@ -1196,7 +1196,6 @@ class MongoCollectionSpecification extends Specification { .bits(1) .min(-180.0) .max(180.0) - .bucketSize(200.0) .storageEngine(BsonDocument.parse('{wiredTiger: {configString: "block_compressor=zlib"}}')) .partialFilterExpression(BsonDocument.parse('{status: "active"}')) .collation(collation) @@ -1218,7 +1217,6 @@ class MongoCollectionSpecification extends Specification { .bits(1) .min(-180.0) .max(180.0) - .bucketSize(200.0) .storageEngine(BsonDocument.parse('{wiredTiger: {configString: "block_compressor=zlib"}}')) .partialFilterExpression(BsonDocument.parse('{status: "active"}')) .collation(collation) From faba36c50d1e11c5b7ee9ed3c02e94d164ece3a4 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Mon, 6 Nov 2023 18:59:21 -0500 Subject: [PATCH 15/28] Remove deprecated mapReduce options JAVA-5149 --- .../internal/operation/AsyncOperations.java | 3 +- .../MapReduceToCollectionOperation.java | 25 --------------- .../internal/operation/Operations.java | 3 -- .../internal/operation/SyncOperations.java | 4 +-- ...eToCollectionOperationSpecification.groovy | 2 -- .../syncadapter/SyncMapReduceIterable.kt | 4 --- .../kotlin/client/coroutine/MapReduceFlow.kt | 22 ------------- .../client/coroutine/MapReduceFlowTest.kt | 4 --- .../client/MapReducePublisher.java | 23 -------------- .../internal/MapReducePublisherImpl.java | 19 +----------- .../syncadapter/SyncMapReduceIterable.java | 12 ------- .../syncadapter/SyncMapReduceIterable.scala | 10 ------ .../mongodb/scala/MapReduceObservable.scala | 31 ------------------- .../scala/MapReduceObservableSpec.scala | 4 --- .../com/mongodb/client/MapReduceIterable.java | 24 -------------- .../internal/MapReduceIterableImpl.java | 16 +--------- .../MapReduceIterableSpecification.groovy | 4 --- 17 files changed, 4 insertions(+), 206 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/operation/AsyncOperations.java b/driver-core/src/main/com/mongodb/internal/operation/AsyncOperations.java index 81b5fb513f2..ef03d0538f2 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AsyncOperations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AsyncOperations.java @@ -164,10 +164,9 @@ public AsyncWriteOperation mapReduceToCollection(final Stri final long maxTimeMS, final boolean jsMode, final Bson scope, final Bson sort, final boolean verbose, final com.mongodb.client.model.MapReduceAction action, - final boolean nonAtomic, final boolean sharded, final Boolean bypassDocumentValidation, final Collation collation) { return operations.mapReduceToCollection(databaseName, collectionName, mapFunction, reduceFunction, finalizeFunction, filter, limit, - maxTimeMS, jsMode, scope, sort, verbose, action, nonAtomic, sharded, bypassDocumentValidation, collation); + maxTimeMS, jsMode, scope, sort, verbose, action, bypassDocumentValidation, collation); } public AsyncReadOperation> mapReduce(final String mapFunction, final String reduceFunction, diff --git a/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java index 482b4261d10..9483fa48273 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java @@ -46,7 +46,6 @@ import static com.mongodb.internal.operation.DocumentHelper.putIfNotZero; import static com.mongodb.internal.operation.DocumentHelper.putIfTrue; import static com.mongodb.internal.operation.OperationHelper.LOGGER; -import static com.mongodb.internal.operation.ServerVersionHelper.serverIsAtLeastVersionFourDotFour; import static com.mongodb.internal.operation.SyncOperationHelper.CommandWriteTransformer; import static com.mongodb.internal.operation.SyncOperationHelper.executeCommand; import static com.mongodb.internal.operation.SyncOperationHelper.withConnection; @@ -81,8 +80,6 @@ private long maxTimeMS; private String action = "replace"; private String databaseName; - private boolean sharded; - private boolean nonAtomic; private Boolean bypassDocumentValidation; private Collation collation; private static final List VALID_ACTIONS = asList("replace", "merge", "reduce"); @@ -217,24 +214,6 @@ public MapReduceToCollectionOperation databaseName(@Nullable final String databa return this; } - public boolean isSharded() { - return sharded; - } - - public MapReduceToCollectionOperation sharded(final boolean sharded) { - this.sharded = sharded; - return this; - } - - public boolean isNonAtomic() { - return nonAtomic; - } - - public MapReduceToCollectionOperation nonAtomic(final boolean nonAtomic) { - this.nonAtomic = nonAtomic; - return this; - } - public Boolean getBypassDocumentValidation() { return bypassDocumentValidation; } @@ -318,10 +297,6 @@ private CommandWriteTransformerAsync transfor private BsonDocument getCommand(@Nullable final ConnectionDescription description) { BsonDocument outputDocument = new BsonDocument(getAction(), new BsonString(getCollectionName())); - if (description != null && !serverIsAtLeastVersionFourDotFour(description)) { - putIfTrue(outputDocument, "sharded", isSharded()); - putIfTrue(outputDocument, "nonAtomic", isNonAtomic()); - } if (getDatabaseName() != null) { outputDocument.put("db", new BsonString(getDatabaseName())); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/Operations.java b/driver-core/src/main/com/mongodb/internal/operation/Operations.java index e65dc73d98e..5aeb47d113a 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/Operations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/Operations.java @@ -269,7 +269,6 @@ MapReduceToCollectionOperation mapReduceToCollection(final String databaseName, final int limit, final long maxTimeMS, final boolean jsMode, final Bson scope, final Bson sort, final boolean verbose, final com.mongodb.client.model.MapReduceAction action, - final boolean nonAtomic, final boolean sharded, final Boolean bypassDocumentValidation, final Collation collation) { MapReduceToCollectionOperation operation = new MapReduceToCollectionOperation(assertNotNull(namespace), new BsonJavaScript(mapFunction), new BsonJavaScript(reduceFunction), collectionName, writeConcern) @@ -281,8 +280,6 @@ MapReduceToCollectionOperation mapReduceToCollection(final String databaseName, .sort(toBsonDocument(sort)) .verbose(verbose) .action(action.getValue()) - .nonAtomic(nonAtomic) - .sharded(sharded) .databaseName(databaseName) .bypassDocumentValidation(bypassDocumentValidation) .collation(collation); diff --git a/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java b/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java index 064196d2568..05577f72be0 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java @@ -132,17 +132,15 @@ public ReadOperation aggregateToCollection(final List pipe comment, variables, aggregationLevel); } - @SuppressWarnings("deprecation") public WriteOperation mapReduceToCollection(final String databaseName, final String collectionName, final String mapFunction, final String reduceFunction, final String finalizeFunction, final Bson filter, final int limit, final long maxTimeMS, final boolean jsMode, final Bson scope, final Bson sort, final boolean verbose, final com.mongodb.client.model.MapReduceAction action, - final boolean nonAtomic, final boolean sharded, final Boolean bypassDocumentValidation, final Collation collation) { return operations.mapReduceToCollection(databaseName, collectionName, mapFunction, reduceFunction, finalizeFunction, filter, limit, - maxTimeMS, jsMode, scope, sort, verbose, action, nonAtomic, sharded, bypassDocumentValidation, collation); + maxTimeMS, jsMode, scope, sort, verbose, action, bypassDocumentValidation, collation); } public ReadOperation> mapReduce(final String mapFunction, final String reduceFunction, diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy index 62161de7a37..052a232e4d5 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy @@ -94,8 +94,6 @@ class MapReduceToCollectionOperationSpecification extends OperationFunctionalSpe operation.getCollation() == null !operation.isJsMode() !operation.isVerbose() - !operation.isSharded() - !operation.isNonAtomic() } def 'should set optional values correctly'(){ diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt b/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt index 39532a85660..9aab6ed51a6 100644 --- a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt +++ b/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt @@ -51,10 +51,6 @@ data class SyncMapReduceIterable(val wrapped: MapReduceFlow) : override fun databaseName(databaseName: String?): SyncMapReduceIterable = apply { wrapped.databaseName(databaseName) } - @Suppress("OVERRIDE_DEPRECATION") - override fun sharded(sharded: Boolean): SyncMapReduceIterable = apply { wrapped.sharded(sharded) } - @Suppress("OVERRIDE_DEPRECATION") - override fun nonAtomic(nonAtomic: Boolean): SyncMapReduceIterable = apply { wrapped.nonAtomic(nonAtomic) } override fun bypassDocumentValidation(bypassDocumentValidation: Boolean?): SyncMapReduceIterable = apply { wrapped.bypassDocumentValidation(bypassDocumentValidation) diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt index aef6ffedb31..1849f9ae92f 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt @@ -165,28 +165,6 @@ public class MapReduceFlow(private val wrapped: MapReducePublisher) */ public fun databaseName(databaseName: String?): MapReduceFlow = apply { wrapped.databaseName(databaseName) } - /** - * Sets if the output database is sharded - * - * @param sharded if the output database is sharded - * @return this - * @see - * [output with an action](https://www.mongodb.com/docs/manual/reference/command/mapReduce/#output-to-a-collection-with-an-action) - */ - public fun sharded(sharded: Boolean): MapReduceFlow = apply { wrapped.sharded(sharded) } - - /** - * Sets if the post-processing step will prevent MongoDB from locking the database. - * - * Valid only with the `MapReduceAction.MERGE` or `MapReduceAction.REDUCE` actions. - * - * @param nonAtomic if the post-processing step will prevent MongoDB from locking the database. - * @return this - * @see - * [output with an action](https://www.mongodb.com/docs/manual/reference/command/mapReduce/#output-to-a-collection-with-an-action) - */ - public fun nonAtomic(nonAtomic: Boolean): MapReduceFlow = apply { wrapped.nonAtomic(nonAtomic) } - /** * Sets the bypass document level validation flag. * diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt index 132d26cf764..440566fcae8 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt @@ -67,9 +67,7 @@ class MapReduceFlowTest { flow.limit(1) flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) - flow.nonAtomic(true) flow.scope(bson) - flow.sharded(true) flow.sort(bson) flow.verbose(true) flow.action(MapReduceAction.MERGE) @@ -85,9 +83,7 @@ class MapReduceFlowTest { verify(wrapped).limit(1) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).nonAtomic(true) verify(wrapped).scope(bson) - verify(wrapped).sharded(true) verify(wrapped).sort(bson) verify(wrapped).verbose(true) verify(wrapped).action(MapReduceAction.MERGE) diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java index e4cb194ddc9..e57a8fce007 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java @@ -134,29 +134,6 @@ public interface MapReducePublisher extends Publisher { * @mongodb.driver.manual reference/command/mapReduce/#output-to-a-collection-with-an-action output with an action */ MapReducePublisher databaseName(@Nullable String databaseName); - /** - * Sets if the output database is sharded - * - * @param sharded if the output database is sharded - * @return this - * @mongodb.driver.manual reference/command/mapReduce/#output-to-a-collection-with-an-action output with an action - * @deprecated this option will no longer be supported in MongoDB 4.4 - */ - @Deprecated - MapReducePublisher sharded(boolean sharded); - - /** - * Sets if the post-processing step will prevent MongoDB from locking the database. - *

- * Valid only with the {@code MapReduceAction.MERGE} or {@code MapReduceAction.REDUCE} actions. - * - * @param nonAtomic if the post-processing step will prevent MongoDB from locking the database. - * @return this - * @mongodb.driver.manual reference/command/mapReduce/#output-to-a-collection-with-an-action output with an action - * @deprecated this option will no longer be supported in MongoDB 4.4 as it will no longer hold a global or database level write lock. - */ - @Deprecated - MapReducePublisher nonAtomic(boolean nonAtomic); /** * Sets the bypass document level validation flag. diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java index 6dd37d6d1c4..37e30e04e07 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java @@ -57,8 +57,6 @@ final class MapReducePublisherImpl extends BatchCursorPublisher implements private long maxTimeMS; private com.mongodb.client.model.MapReduceAction action = com.mongodb.client.model.MapReduceAction.REPLACE; private String databaseName; - private boolean sharded; - private boolean nonAtomic; private Boolean bypassDocumentValidation; private Collation collation; @@ -140,20 +138,6 @@ public com.mongodb.reactivestreams.client.MapReducePublisher databaseName(@Nu return this; } - @Deprecated - @Override - public com.mongodb.reactivestreams.client.MapReducePublisher sharded(final boolean sharded) { - this.sharded = sharded; - return this; - } - - @Deprecated - @Override - public com.mongodb.reactivestreams.client.MapReducePublisher nonAtomic(final boolean nonAtomic) { - this.nonAtomic = nonAtomic; - return this; - } - @Override public com.mongodb.reactivestreams.client.MapReducePublisher batchSize(final int batchSize) { super.batchSize(batchSize); @@ -211,8 +195,7 @@ private WrappedMapReduceWriteOperation createMapReduceToCollectionOperation() { return new WrappedMapReduceWriteOperation(getOperations().mapReduceToCollection(databaseName, collectionName, mapFunction, reduceFunction, finalizeFunction, filter, limit, maxTimeMS, jsMode, scope, sort, verbose, action, - nonAtomic, sharded, - bypassDocumentValidation, collation)); + bypassDocumentValidation, collation)); } private AsyncReadOperation> createFindOperation(final int initialBatchSize) { diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java index 09042528f66..66a287cfa64 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java @@ -106,18 +106,6 @@ public com.mongodb.client.MapReduceIterable databaseName(@Nullable final Stri return this; } - @Override - public com.mongodb.client.MapReduceIterable sharded(final boolean sharded) { - wrapped.sharded(sharded); - return this; - } - - @Override - public com.mongodb.client.MapReduceIterable nonAtomic(final boolean nonAtomic) { - wrapped.nonAtomic(nonAtomic); - return this; - } - @Override public com.mongodb.client.MapReduceIterable batchSize(final int batchSize) { wrapped.batchSize(batchSize); diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala b/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala index 7224a4be0dc..6fce83ffa4b 100644 --- a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala +++ b/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala @@ -83,16 +83,6 @@ case class SyncMapReduceIterable[T](wrapped: MapReduceObservable[T]) this } - override def sharded(sharded: Boolean): MapReduceIterable[T] = { - wrapped.sharded(sharded) - this - } - - override def nonAtomic(nonAtomic: Boolean): MapReduceIterable[T] = { - wrapped.nonAtomic(nonAtomic) - this - } - override def batchSize(batchSize: Int): MapReduceIterable[T] = { wrapped.batchSize(batchSize) this diff --git a/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala index 29cf5885741..88ffe0fbd47 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala @@ -169,37 +169,6 @@ case class MapReduceObservable[TResult](wrapped: MapReducePublisher[TResult]) ex this } - /** - * Sets if the output database is sharded - * - * [[https://www.mongodb.com/docs/manual/reference/command/mapReduce#output-to-a-collection-with-an-action output with an action]] - * @param sharded if the output database is sharded - * @return this - */ - @deprecated("This option will no longer be supported in MongoDB 4.4.", "4.1.0") - def sharded(sharded: Boolean): MapReduceObservable[TResult] = { - wrapped.sharded(sharded) - this - } - - /** - * Sets if the post-processing step will prevent MongoDB from locking the database. - * - * Valid only with the `MapReduceAction.MERGE` or `MapReduceAction.REDUCE` actions. - * - * [[https://www.mongodb.com/docs/manual/reference/command/mapReduce/#output-to-a-collection-with-an-action Output with an action]] - * @param nonAtomic if the post-processing step will prevent MongoDB from locking the database. - * @return this - */ - @deprecated( - "This option will no longer be supported in MongoDB 4.4 as it will no longer hold a global or database level write lock", - "4.1.0" - ) - def nonAtomic(nonAtomic: Boolean): MapReduceObservable[TResult] = { - wrapped.nonAtomic(nonAtomic) - this - } - /** * Sets the bypass document level validation flag. * diff --git a/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala index dbb1d8551d0..1b8d164bd21 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala @@ -60,8 +60,6 @@ class MapReduceObservableSpec extends BaseSpec with MockitoSugar { observable.action(MapReduceAction.REPLACE) observable.jsMode(true) observable.verbose(true) - observable.sharded(true) - observable.nonAtomic(true) observable.bypassDocumentValidation(true) observable.collation(collation) observable.batchSize(batchSize) @@ -77,8 +75,6 @@ class MapReduceObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).action(MapReduceAction.REPLACE) verify(wrapper).jsMode(true) verify(wrapper).verbose(true) - verify(wrapper).sharded(true) - verify(wrapper).nonAtomic(true) verify(wrapper).bypassDocumentValidation(true) verify(wrapper).collation(collation) verify(wrapper).batchSize(batchSize) diff --git a/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java b/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java index f9001e1dd33..30706dd6373 100644 --- a/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java +++ b/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java @@ -146,30 +146,6 @@ public interface MapReduceIterable extends MongoIterable { */ MapReduceIterable databaseName(@Nullable String databaseName); - /** - * Sets if the output database is sharded - * - * @param sharded if the output database is sharded - * @return this - * @mongodb.driver.manual reference/command/mapReduce/#output-to-a-collection-with-an-action output with an action - * @deprecated this option will no longer be supported in MongoDB 4.4. - */ - @Deprecated - MapReduceIterable sharded(boolean sharded); - - /** - * Sets if the post-processing step will prevent MongoDB from locking the database. - *

- * Valid only with the {@code MapReduceAction.MERGE} or {@code MapReduceAction.REDUCE} actions. - * - * @param nonAtomic if the post-processing step will prevent MongoDB from locking the database. - * @return this - * @mongodb.driver.manual reference/command/mapReduce/#output-to-a-collection-with-an-action output with an action - * @deprecated this option will no longer be supported in MongoDB 4.4 as it will no longer hold a global or database level write lock. - */ - @Deprecated - MapReduceIterable nonAtomic(boolean nonAtomic); - /** * Sets the number of documents to return per batch. * diff --git a/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java index 60f47f71dec..9c531f45d58 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java @@ -61,8 +61,6 @@ class MapReduceIterableImpl extends MongoIterableImpl databaseName(@Nullable fina return this; } - @Override - public com.mongodb.client.MapReduceIterable sharded(final boolean sharded) { - this.sharded = sharded; - return this; - } - - @Override - public com.mongodb.client.MapReduceIterable nonAtomic(final boolean nonAtomic) { - this.nonAtomic = nonAtomic; - return this; - } - @Override public com.mongodb.client.MapReduceIterable batchSize(final int batchSize) { super.batchSize(batchSize); @@ -218,7 +204,7 @@ public ReadOperation> asReadOperation() { private WriteOperation createMapReduceToCollectionOperation() { return operations.mapReduceToCollection(databaseName, collectionName, mapFunction, reduceFunction, finalizeFunction, filter, - limit, maxTimeMS, jsMode, scope, sort, verbose, action, nonAtomic, sharded, bypassDocumentValidation, collation + limit, maxTimeMS, jsMode, scope, sort, verbose, action, bypassDocumentValidation, collation ); } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MapReduceIterableSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/MapReduceIterableSpecification.groovy index 8983c835701..c24f479b784 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MapReduceIterableSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MapReduceIterableSpecification.groovy @@ -121,9 +121,7 @@ class MapReduceIterableSpecification extends Specification { .sort(new Document('sort', 1)) .verbose(false) .batchSize(99) - .nonAtomic(true) .action(MapReduceAction.MERGE) - .sharded(true) .jsMode(true) .bypassDocumentValidation(true) .collation(collation) @@ -140,10 +138,8 @@ class MapReduceIterableSpecification extends Specification { .scope(new BsonDocument('scope', new BsonInt32(1))) .sort(new BsonDocument('sort', new BsonInt32(1))) .verbose(false) - .nonAtomic(true) .action(MapReduceAction.MERGE.getValue()) .jsMode(true) - .sharded(true) .bypassDocumentValidation(true) .collation(collation) From 78727c8020d58919af4cbfe5e33cb0571a6ae7c6 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Tue, 7 Nov 2023 07:44:31 -0500 Subject: [PATCH 16/28] Remove getCluster method (#1245) from the following internal interfaces: * ClusterAwareReadWriteBinding * AsyncClusterAwareReadWriteBinding The interfaces remain as they have picket up a second method. JAVA-5217 --- .../binding/AsyncClusterAwareReadWriteBinding.java | 2 -- .../mongodb/internal/binding/AsyncClusterBinding.java | 5 ----- .../internal/binding/ClusterAwareReadWriteBinding.java | 2 -- .../com/mongodb/internal/binding/ClusterBinding.java | 10 +--------- .../client/internal/crypt/CryptBinding.java | 6 ------ .../main/com/mongodb/client/internal/CryptBinding.java | 8 +------- 6 files changed, 2 insertions(+), 31 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterAwareReadWriteBinding.java b/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterAwareReadWriteBinding.java index 8a0ee5d8241..c66dc321513 100644 --- a/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterAwareReadWriteBinding.java +++ b/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterAwareReadWriteBinding.java @@ -18,13 +18,11 @@ import com.mongodb.ServerAddress; import com.mongodb.internal.async.SingleResultCallback; -import com.mongodb.internal.connection.Cluster; /** *

This class is not part of the public API and may be removed or changed at any time

*/ public interface AsyncClusterAwareReadWriteBinding extends AsyncReadWriteBinding { - Cluster getCluster(); /** * Returns a connection source to the specified server diff --git a/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterBinding.java b/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterBinding.java index fb813c25327..acf75a3b1e8 100644 --- a/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterBinding.java +++ b/driver-core/src/main/com/mongodb/internal/binding/AsyncClusterBinding.java @@ -80,11 +80,6 @@ public AsyncClusterAwareReadWriteBinding retain() { return this; } - @Override - public Cluster getCluster() { - return cluster; - } - @Override public ReadPreference getReadPreference() { return readPreference; diff --git a/driver-core/src/main/com/mongodb/internal/binding/ClusterAwareReadWriteBinding.java b/driver-core/src/main/com/mongodb/internal/binding/ClusterAwareReadWriteBinding.java index 12e9c4d591b..8f7552341a7 100644 --- a/driver-core/src/main/com/mongodb/internal/binding/ClusterAwareReadWriteBinding.java +++ b/driver-core/src/main/com/mongodb/internal/binding/ClusterAwareReadWriteBinding.java @@ -17,13 +17,11 @@ package com.mongodb.internal.binding; import com.mongodb.ServerAddress; -import com.mongodb.internal.connection.Cluster; /** * This interface is not part of the public API and may be removed or changed at any time. */ public interface ClusterAwareReadWriteBinding extends ReadWriteBinding { - Cluster getCluster(); /** * Returns a connection source to the specified server address. diff --git a/driver-core/src/main/com/mongodb/internal/binding/ClusterBinding.java b/driver-core/src/main/com/mongodb/internal/binding/ClusterBinding.java index 81321b631f2..a2223d02014 100644 --- a/driver-core/src/main/com/mongodb/internal/binding/ClusterBinding.java +++ b/driver-core/src/main/com/mongodb/internal/binding/ClusterBinding.java @@ -22,10 +22,10 @@ import com.mongodb.ServerAddress; import com.mongodb.ServerApi; import com.mongodb.connection.ClusterConnectionMode; -import com.mongodb.internal.connection.OperationContext; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.Connection; +import com.mongodb.internal.connection.OperationContext; import com.mongodb.internal.connection.ReadConcernAwareNoOpSessionContext; import com.mongodb.internal.connection.Server; import com.mongodb.internal.connection.ServerTuple; @@ -71,14 +71,6 @@ public ClusterBinding(final Cluster cluster, final ReadPreference readPreference operationContext = new OperationContext(); } - /** - * Return the cluster. - * @return the cluster - */ - public Cluster getCluster() { - return cluster; - } - @Override public ReadWriteBinding retain() { super.retain(); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptBinding.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptBinding.java index 11ecef6813e..ae100283ab8 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptBinding.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptBinding.java @@ -25,7 +25,6 @@ import com.mongodb.internal.binding.AsyncClusterAwareReadWriteBinding; import com.mongodb.internal.binding.AsyncConnectionSource; import com.mongodb.internal.connection.AsyncConnection; -import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.OperationContext; import com.mongodb.internal.session.SessionContext; import com.mongodb.lang.Nullable; @@ -132,11 +131,6 @@ public int release() { return wrapped.release(); } - @Override - public Cluster getCluster() { - return wrapped.getCluster(); - } - private class CryptConnectionSource implements AsyncConnectionSource { private final AsyncConnectionSource wrapped; diff --git a/driver-sync/src/main/com/mongodb/client/internal/CryptBinding.java b/driver-sync/src/main/com/mongodb/client/internal/CryptBinding.java index 1b826177267..ab195a46dd5 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/CryptBinding.java +++ b/driver-sync/src/main/com/mongodb/client/internal/CryptBinding.java @@ -20,13 +20,12 @@ import com.mongodb.RequestContext; import com.mongodb.ServerAddress; import com.mongodb.ServerApi; -import com.mongodb.internal.connection.OperationContext; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.binding.ClusterAwareReadWriteBinding; import com.mongodb.internal.binding.ConnectionSource; import com.mongodb.internal.binding.ReadWriteBinding; -import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.Connection; +import com.mongodb.internal.connection.OperationContext; import com.mongodb.internal.session.SessionContext; import com.mongodb.lang.Nullable; @@ -101,11 +100,6 @@ public int release() { return wrapped.release(); } - @Override - public Cluster getCluster() { - return wrapped.getCluster(); - } - private class CryptConnectionSource implements ConnectionSource { private final ConnectionSource wrapped; From 20bad8b45eccaca5db5a7cd3e71256edbdc52267 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Tue, 7 Nov 2023 10:50:44 -0500 Subject: [PATCH 17/28] Remove deprecated constructors and factory methods JAVA-5144 --- .../com/mongodb/MongoBulkWriteException.java | 18 ---- .../mongodb/MongoCursorNotFoundException.java | 13 --- .../main/com/mongodb/MongoQueryException.java | 54 ---------- .../com/mongodb/bulk/BulkWriteResult.java | 48 --------- .../changestream/ChangeStreamDocument.java | 99 ------------------- .../main/com/mongodb/event/CommandEvent.java | 42 -------- .../com/mongodb/event/CommandFailedEvent.java | 58 +---------- .../mongodb/event/CommandStartedEvent.java | 37 ------- .../mongodb/event/CommandSucceededEvent.java | 57 ----------- .../event/ConnectionCheckOutFailedEvent.java | 28 ------ .../event/ConnectionCheckOutStartedEvent.java | 11 --- .../event/ConnectionCheckedInEvent.java | 11 --- .../event/ConnectionCheckedOutEvent.java | 26 ----- .../mongodb/event/ConnectionReadyEvent.java | 12 --- .../event/ServerHeartbeatFailedEvent.java | 13 --- .../event/ServerHeartbeatSucceededEvent.java | 13 --- .../client/CommandMonitoringTestHelper.java | 8 +- ...ngeStreamDocumentCodecSpecification.groovy | 42 ++++---- .../ChangeStreamDocumentSpecification.groovy | 91 +++-------------- .../event/CommandEventSpecification.groovy | 8 +- ...ternalStreamConnectionSpecification.groovy | 28 +++--- 21 files changed, 56 insertions(+), 661 deletions(-) diff --git a/driver-core/src/main/com/mongodb/MongoBulkWriteException.java b/driver-core/src/main/com/mongodb/MongoBulkWriteException.java index 070dfed02d5..228daca503c 100644 --- a/driver-core/src/main/com/mongodb/MongoBulkWriteException.java +++ b/driver-core/src/main/com/mongodb/MongoBulkWriteException.java @@ -21,7 +21,6 @@ import com.mongodb.bulk.WriteConcernError; import com.mongodb.lang.Nullable; -import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; @@ -41,23 +40,6 @@ public class MongoBulkWriteException extends MongoServerException { private final ServerAddress serverAddress; private final WriteConcernError writeConcernError; - /** - * Constructs a new instance. - * - * @param writeResult the write result - * @param writeErrors the list of errors - * @param writeConcernError the write concern error - * @param serverAddress the server address. - * - * @deprecated Prefer {@link MongoBulkWriteException#MongoBulkWriteException(BulkWriteResult, List, WriteConcernError, - * ServerAddress, Set)} instead - */ - @Deprecated - public MongoBulkWriteException(final BulkWriteResult writeResult, final List writeErrors, - @Nullable final WriteConcernError writeConcernError, final ServerAddress serverAddress) { - this(writeResult, writeErrors, writeConcernError, serverAddress, Collections.emptySet()); - } - /** * Constructs a new instance. * diff --git a/driver-core/src/main/com/mongodb/MongoCursorNotFoundException.java b/driver-core/src/main/com/mongodb/MongoCursorNotFoundException.java index 3f0b2348ac3..77492b8a6e2 100644 --- a/driver-core/src/main/com/mongodb/MongoCursorNotFoundException.java +++ b/driver-core/src/main/com/mongodb/MongoCursorNotFoundException.java @@ -43,19 +43,6 @@ public MongoCursorNotFoundException(final long cursorId, final BsonDocument resp this.cursorId = cursorId; } - /** - * Construct a new instance. - * - * @param cursorId cursor identifier - * @param serverAddress server address - * @deprecated Prefer {@link #MongoCursorNotFoundException(long, BsonDocument, ServerAddress)} - */ - @Deprecated - public MongoCursorNotFoundException(final long cursorId, final ServerAddress serverAddress) { - super(serverAddress, -5, "Cursor " + cursorId + " not found on server " + serverAddress); - this.cursorId = cursorId; - } - /** * Get the cursor id that wasn't found. * diff --git a/driver-core/src/main/com/mongodb/MongoQueryException.java b/driver-core/src/main/com/mongodb/MongoQueryException.java index 0788b1f5095..eb9909a4806 100644 --- a/driver-core/src/main/com/mongodb/MongoQueryException.java +++ b/driver-core/src/main/com/mongodb/MongoQueryException.java @@ -16,10 +16,7 @@ package com.mongodb; -import com.mongodb.lang.Nullable; import org.bson.BsonDocument; -import org.bson.BsonInt32; -import org.bson.BsonString; /** * An exception indicating that a query operation failed on the server. @@ -40,55 +37,4 @@ public class MongoQueryException extends MongoCommandException { public MongoQueryException(final BsonDocument response, final ServerAddress serverAddress) { super(response, serverAddress); } - - /** - * Construct an instance. - * - * @param address the server address - * @param errorCode the error code - * @param errorMessage the error message - * @deprecated Prefer {@link #MongoQueryException(BsonDocument, ServerAddress)} - */ - @Deprecated - public MongoQueryException(final ServerAddress address, final int errorCode, final String errorMessage) { - this(manufactureResponse(errorCode, null, errorMessage), address); - } - - /** - * Construct an instance. - * - * @param address the server address - * @param errorCode the error code - * @param errorCodeName the error code name - * @param errorMessage the error message - * @since 4.6 - * @deprecated Prefer {@link #MongoQueryException(BsonDocument, ServerAddress)} - */ - @Deprecated - public MongoQueryException(final ServerAddress address, final int errorCode, @Nullable final String errorCodeName, - final String errorMessage) { - this(manufactureResponse(errorCode, errorCodeName, errorMessage), address); - } - - /** - * Construct an instance from a command exception. - * - * @param commandException the command exception - * @since 3.7 - * @deprecated Prefer {@link #MongoQueryException(BsonDocument, ServerAddress)} - */ - @Deprecated - public MongoQueryException(final MongoCommandException commandException) { - this(commandException.getResponse(), commandException.getServerAddress()); - } - - private static BsonDocument manufactureResponse(final int errorCode, @Nullable final String errorCodeName, final String errorMessage) { - BsonDocument response = new BsonDocument("ok", new BsonInt32(1)) - .append("code", new BsonInt32(errorCode)) - .append("errmsg", new BsonString(errorMessage)); - if (errorCodeName != null) { - response.append("codeName", new BsonString(errorCodeName)); - } - return response; - } } diff --git a/driver-core/src/main/com/mongodb/bulk/BulkWriteResult.java b/driver-core/src/main/com/mongodb/bulk/BulkWriteResult.java index 0b5de0cc298..d42c0252a8c 100644 --- a/driver-core/src/main/com/mongodb/bulk/BulkWriteResult.java +++ b/driver-core/src/main/com/mongodb/bulk/BulkWriteResult.java @@ -21,7 +21,6 @@ import java.util.List; import static com.mongodb.assertions.Assertions.assertNotNull; -import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; /** @@ -97,36 +96,6 @@ public abstract class BulkWriteResult { */ public abstract List getUpserts(); - /** - * Create an acknowledged BulkWriteResult - * - * @param type the type of the write - * @param count the number of documents matched - * @param upserts the list of upserts - * @return an acknowledged BulkWriteResult - * @deprecated Prefer {@link BulkWriteResult#acknowledged(int, int, int, Integer, List, List)} instead - */ - @Deprecated - public static BulkWriteResult acknowledged(final WriteRequest.Type type, final int count, final List upserts) { - return acknowledged(type, count, 0, upserts, emptyList()); - } - - /** - * Create an acknowledged BulkWriteResult - * - * @param type the type of the write - * @param count the number of documents matched - * @param modifiedCount the number of documents modified, which may be null if the server was not able to provide the count - * @param upserts the list of upserts - * @return an acknowledged BulkWriteResult - * @deprecated Prefer {@link BulkWriteResult#acknowledged(int, int, int, Integer, List, List)} instead - */ - @Deprecated - public static BulkWriteResult acknowledged(final WriteRequest.Type type, final int count, final Integer modifiedCount, - final List upserts) { - return acknowledged(type, count, modifiedCount, upserts, emptyList()); - } - /** * Create an acknowledged BulkWriteResult * @@ -146,23 +115,6 @@ public static BulkWriteResult acknowledged(final WriteRequest.Type type, final i modifiedCount, upserts, inserts); } - /** - * Create an acknowledged BulkWriteResult - * - * @param insertedCount the number of documents inserted by the write operation - * @param matchedCount the number of documents matched by the write operation - * @param removedCount the number of documents removed by the write operation - * @param modifiedCount the number of documents modified, which may not be null - * @param upserts the list of upserts - * @return an acknowledged BulkWriteResult - * @deprecated Prefer {@link BulkWriteResult#acknowledged(int, int, int, Integer, List, List)} instead - */ - @Deprecated - public static BulkWriteResult acknowledged(final int insertedCount, final int matchedCount, final int removedCount, - final Integer modifiedCount, final List upserts) { - return acknowledged(insertedCount, matchedCount, removedCount, modifiedCount, upserts, emptyList()); - } - /** * Create an acknowledged BulkWriteResult * diff --git a/driver-core/src/main/com/mongodb/client/model/changestream/ChangeStreamDocument.java b/driver-core/src/main/com/mongodb/client/model/changestream/ChangeStreamDocument.java index a5879e10f17..d9db11d6def 100644 --- a/driver-core/src/main/com/mongodb/client/model/changestream/ChangeStreamDocument.java +++ b/driver-core/src/main/com/mongodb/client/model/changestream/ChangeStreamDocument.java @@ -116,105 +116,6 @@ public ChangeStreamDocument( this.extraElements = extraElements; } - /** - * Creates a new instance - * - * @param operationTypeString the operation type - * @param resumeToken the resume token - * @param namespaceDocument the BsonDocument representing the namespace - * @param destinationNamespaceDocument the BsonDocument representing the destinatation namespace - * @param fullDocument the full document - * @param fullDocumentBeforeChange the full document before change - * @param documentKey a document containing the _id of the changed document - * @param clusterTime the cluster time at which the change occured - * @param updateDescription the update description - * @param txnNumber the transaction number - * @param lsid the identifier for the session associated with the transaction - * @param wallTime the wall time of the server at the moment the change occurred - * @param extraElements any extra elements that are part of the change stream document but not otherwise mapped to fields - * - * @since 4.7 - */ - @Deprecated - public ChangeStreamDocument(@BsonProperty("operationType") final String operationTypeString, - @BsonProperty("resumeToken") final BsonDocument resumeToken, - @Nullable @BsonProperty("ns") final BsonDocument namespaceDocument, - @Nullable @BsonProperty("to") final BsonDocument destinationNamespaceDocument, - @Nullable @BsonProperty("fullDocument") final TDocument fullDocument, - @Nullable @BsonProperty("fullDocumentBeforeChange") final TDocument fullDocumentBeforeChange, - @Nullable @BsonProperty("documentKey") final BsonDocument documentKey, - @Nullable @BsonProperty("clusterTime") final BsonTimestamp clusterTime, - @Nullable @BsonProperty("updateDescription") final UpdateDescription updateDescription, - @Nullable @BsonProperty("txnNumber") final BsonInt64 txnNumber, - @Nullable @BsonProperty("lsid") final BsonDocument lsid, - @Nullable @BsonProperty("wallTime") final BsonDateTime wallTime, - @Nullable @BsonProperty final BsonDocument extraElements) { - this(operationTypeString, resumeToken, namespaceDocument, destinationNamespaceDocument, fullDocument, fullDocumentBeforeChange, documentKey, - clusterTime, updateDescription, txnNumber, lsid, wallTime, null, extraElements); - } - - /** - * Creates a new instance - * - * @param operationTypeString the operation type - * @param resumeToken the resume token - * @param namespaceDocument the BsonDocument representing the namespace - * @param destinationNamespaceDocument the BsonDocument representing the destinatation namespace - * @param fullDocument the full document - * @param documentKey a document containing the _id of the changed document - * @param clusterTime the cluster time at which the change occured - * @param updateDescription the update description - * @param txnNumber the transaction number - * @param lsid the identifier for the session associated with the transaction - * - * @since 4.6 - */ - @Deprecated - public ChangeStreamDocument(@BsonProperty("operationType") final String operationTypeString, - @BsonProperty("resumeToken") final BsonDocument resumeToken, - @Nullable @BsonProperty("ns") final BsonDocument namespaceDocument, - @Nullable @BsonProperty("to") final BsonDocument destinationNamespaceDocument, - @Nullable @BsonProperty("fullDocument") final TDocument fullDocument, - @Nullable @BsonProperty("documentKey") final BsonDocument documentKey, - @Nullable @BsonProperty("clusterTime") final BsonTimestamp clusterTime, - @Nullable @BsonProperty("updateDescription") final UpdateDescription updateDescription, - @Nullable @BsonProperty("txnNumber") final BsonInt64 txnNumber, - @Nullable @BsonProperty("lsid") final BsonDocument lsid) { - this(operationTypeString, resumeToken, namespaceDocument, destinationNamespaceDocument, fullDocument, null, documentKey, - clusterTime, updateDescription, txnNumber, lsid, null, null, null); - } - - /** - * Creates a new instance - * - * @param operationType the operation type - * @param resumeToken the resume token - * @param namespaceDocument the BsonDocument representing the namespace - * @param destinationNamespaceDocument the BsonDocument representing the destinatation namespace - * @param fullDocument the full document - * @param documentKey a document containing the _id of the changed document - * @param clusterTime the cluster time at which the change occured - * @param updateDescription the update description - * @param txnNumber the transaction number - * @param lsid the identifier for the session associated with the transaction - * - * @since 3.11 - */ - @Deprecated - public ChangeStreamDocument(final OperationType operationType, - final BsonDocument resumeToken, - final BsonDocument namespaceDocument, - final BsonDocument destinationNamespaceDocument, - final TDocument fullDocument, - final BsonDocument documentKey, - final BsonTimestamp clusterTime, - final UpdateDescription updateDescription, - final BsonInt64 txnNumber, - final BsonDocument lsid) { - this(operationType.getValue(), resumeToken, namespaceDocument, destinationNamespaceDocument, fullDocument, null, documentKey, - clusterTime, updateDescription, txnNumber, lsid, null, null, null); - } - /** * Returns the resumeToken * diff --git a/driver-core/src/main/com/mongodb/event/CommandEvent.java b/driver-core/src/main/com/mongodb/event/CommandEvent.java index 40224b87e81..9a5bd87b54b 100644 --- a/driver-core/src/main/com/mongodb/event/CommandEvent.java +++ b/driver-core/src/main/com/mongodb/event/CommandEvent.java @@ -56,48 +56,6 @@ public CommandEvent(@Nullable final RequestContext requestContext, final long op this.operationId = operationId; } - /** - * Construct an instance. - * - * @param requestContext the request context - * @param operationId the operation id - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - * @since 4.10 - * @deprecated Prefer {@link CommandEvent#CommandEvent(RequestContext, long, int, ConnectionDescription, String, String)} - */ - @Deprecated - public CommandEvent(@Nullable final RequestContext requestContext, final long operationId, final int requestId, - final ConnectionDescription connectionDescription, final String commandName) { - this(requestContext, -1, requestId, connectionDescription, "", commandName); - } - - /** - * Construct an instance. - * @param requestContext the request context - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - * @since 4.4 - * @deprecated Prefer {@link CommandEvent#CommandEvent(RequestContext, long, int, ConnectionDescription, String, String)} - */ - @Deprecated - public CommandEvent(@Nullable final RequestContext requestContext, final int requestId, - final ConnectionDescription connectionDescription, final String commandName) { - this(requestContext, -1, requestId, connectionDescription, "", commandName); - } - - /** - * Construct an instance. - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - */ - public CommandEvent(final int requestId, final ConnectionDescription connectionDescription, final String commandName) { - this(null, requestId, connectionDescription, commandName); - } - /** * Gets the operation identifier * diff --git a/driver-core/src/main/com/mongodb/event/CommandFailedEvent.java b/driver-core/src/main/com/mongodb/event/CommandFailedEvent.java index 07bdc003655..43dfe666fe0 100644 --- a/driver-core/src/main/com/mongodb/event/CommandFailedEvent.java +++ b/driver-core/src/main/com/mongodb/event/CommandFailedEvent.java @@ -56,62 +56,6 @@ public CommandFailedEvent(@Nullable final RequestContext requestContext, final l this.throwable = throwable; } - /** - * Construct an instance. - * - * @param requestContext the request context - * @param operationId the operation id - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds for the operation to complete - * @param throwable the throwable cause of the failure - * @since 4.10 - * {@link CommandFailedEvent#CommandFailedEvent(RequestContext, long, int, ConnectionDescription, String, String, long, Throwable)} - */ - @Deprecated - public CommandFailedEvent(@Nullable final RequestContext requestContext, final long operationId, final int requestId, - final ConnectionDescription connectionDescription, final String commandName, final long elapsedTimeNanos, - final Throwable throwable) { - super(requestContext, operationId, requestId, connectionDescription, commandName); - isTrueArgument("elapsed time is not negative", elapsedTimeNanos >= 0); - this.elapsedTimeNanos = elapsedTimeNanos; - this.throwable = throwable; - } - - /** - * Construct an instance. - * @param requestContext the request context - * @param requestId the requestId - * @param connectionDescription the connection description - * @param commandName the command name - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds for the operation to complete - * @param throwable the throwable cause of the failure - * @since 4.4 - * @deprecated Prefer - * {@link CommandFailedEvent#CommandFailedEvent(RequestContext, long, int, ConnectionDescription, String, String, long, Throwable)} - */ - @Deprecated - public CommandFailedEvent(@Nullable final RequestContext requestContext, final int requestId, - final ConnectionDescription connectionDescription, final String commandName, final long elapsedTimeNanos, - final Throwable throwable) { - this(requestContext, -1, requestId, connectionDescription, commandName, elapsedTimeNanos, throwable); - } - - /** - * Construct an instance. - * @param requestId the requestId - * @param connectionDescription the connection description - * @param commandName the command name - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds for the operation to complete - * @param throwable the throwable cause of the failure - * {@link CommandFailedEvent#CommandFailedEvent(RequestContext, long, int, ConnectionDescription, String, long, Throwable)} - */ - @Deprecated - public CommandFailedEvent(final int requestId, final ConnectionDescription connectionDescription, - final String commandName, final long elapsedTimeNanos, final Throwable throwable) { - this(null, requestId, connectionDescription, commandName, elapsedTimeNanos, throwable); - } /** * Gets the elapsed time in the given unit of time. * @@ -125,7 +69,7 @@ public long getElapsedTime(final TimeUnit timeUnit) { /** * Gets the throwable cause of the failure * - * @return the throwable cause of the failuer + * @return the throwable cause of the failure */ public Throwable getThrowable() { return throwable; diff --git a/driver-core/src/main/com/mongodb/event/CommandStartedEvent.java b/driver-core/src/main/com/mongodb/event/CommandStartedEvent.java index 67442cf53df..bab0015e56a 100644 --- a/driver-core/src/main/com/mongodb/event/CommandStartedEvent.java +++ b/driver-core/src/main/com/mongodb/event/CommandStartedEvent.java @@ -48,43 +48,6 @@ public CommandStartedEvent(@Nullable final RequestContext requestContext, final this.command = command; } - /** - * Construct an instance. - * - * @param requestContext the request context - * @param requestId the request id - * @param connectionDescription the connection description - * @param databaseName the database name - * @param commandName the command name - * @param command the command as a BSON document - * @since 4.4 - * @deprecated Prefer {@link - * CommandStartedEvent#CommandStartedEvent(RequestContext, long, int, ConnectionDescription, String, String, BsonDocument)} - */ - @Deprecated - public CommandStartedEvent(@Nullable final RequestContext requestContext, final int requestId, - final ConnectionDescription connectionDescription, final String databaseName, final String commandName, - final BsonDocument command) { - this(requestContext, -1, requestId, connectionDescription, databaseName, commandName, command); - } - - /** - * Construct an instance. - * - * @param requestId the request id - * @param connectionDescription the connection description - * @param databaseName the database name - * @param commandName the command name - * @param command the command as a BSON document - * @deprecated Prefer {@link - * CommandStartedEvent#CommandStartedEvent(RequestContext, long, int, ConnectionDescription, String, String, BsonDocument)} - */ - @Deprecated - public CommandStartedEvent(final int requestId, final ConnectionDescription connectionDescription, - final String databaseName, final String commandName, final BsonDocument command) { - this(null, requestId, connectionDescription, databaseName, commandName, command); - } - /** * Gets the command document. The document is only usable within the method that delivered the event. If it's needed for longer, it * must be cloned via {@link Object#clone()}. diff --git a/driver-core/src/main/com/mongodb/event/CommandSucceededEvent.java b/driver-core/src/main/com/mongodb/event/CommandSucceededEvent.java index 5f7773c1e58..0daa83897a9 100644 --- a/driver-core/src/main/com/mongodb/event/CommandSucceededEvent.java +++ b/driver-core/src/main/com/mongodb/event/CommandSucceededEvent.java @@ -56,63 +56,6 @@ public CommandSucceededEvent(@Nullable final RequestContext requestContext, fina this.elapsedTimeNanos = elapsedTimeNanos; } - /** - * Construct an instance. - * - * @param requestContext the request context - * @param operationId the operation id - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - * @param response the command response - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds for the operation to complete - * @since 4.10 - * @deprecated Prefer - * {@link CommandSucceededEvent#CommandSucceededEvent(RequestContext, long, int, ConnectionDescription, String, String, BsonDocument, long)} - */ - @Deprecated - public CommandSucceededEvent(@Nullable final RequestContext requestContext, final long operationId, final int requestId, - final ConnectionDescription connectionDescription, final String commandName, final BsonDocument response, - final long elapsedTimeNanos) { - super(requestContext, operationId, requestId, connectionDescription, commandName); - this.response = response; - isTrueArgument("elapsed time is not negative", elapsedTimeNanos >= 0); - this.elapsedTimeNanos = elapsedTimeNanos; - } - - /** - * Construct an instance. - * @param requestContext the request context - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - * @param response the command response - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds for the operation to complete - * @since 4.4 - * @deprecated Prefer - * {@link CommandSucceededEvent#CommandSucceededEvent(RequestContext, long, int, ConnectionDescription, String, String, BsonDocument, long)} - */ - @Deprecated - public CommandSucceededEvent(@Nullable final RequestContext requestContext, final int requestId, - final ConnectionDescription connectionDescription, final String commandName, final BsonDocument response, - final long elapsedTimeNanos) { - this(requestContext, -1, requestId, connectionDescription, commandName, response, elapsedTimeNanos); - } - - /** - * Construct an instance. - * @param requestId the request id - * @param connectionDescription the connection description - * @param commandName the command name - * @param response the command response - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds for the operation to complete - * {@link CommandSucceededEvent#CommandSucceededEvent(RequestContext, long, int, ConnectionDescription, String, BsonDocument, long)} - */ - @Deprecated - public CommandSucceededEvent(final int requestId, final ConnectionDescription connectionDescription, final String commandName, - final BsonDocument response, final long elapsedTimeNanos) { - this(null, requestId, connectionDescription, commandName, response, elapsedTimeNanos); - } /** * Gets the elapsed time in the given unit of time. * diff --git a/driver-core/src/main/com/mongodb/event/ConnectionCheckOutFailedEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionCheckOutFailedEvent.java index 48ce1cb8c96..d951206e3ee 100644 --- a/driver-core/src/main/com/mongodb/event/ConnectionCheckOutFailedEvent.java +++ b/driver-core/src/main/com/mongodb/event/ConnectionCheckOutFailedEvent.java @@ -78,34 +78,6 @@ public ConnectionCheckOutFailedEvent(final ServerId serverId, final long operati this.elapsedTimeNanos = elapsedTimeNanos; } - /** - * Construct an instance - * - * @param serverId the server id - * @param operationId the operation id - * @param reason the reason the connection check out failed - * @since 4.10 - * @deprecated Prefer {@link ConnectionCheckOutFailedEvent#ConnectionCheckOutFailedEvent(ServerId, long, Reason, long)}. - * If this constructor is used, then {@link #getElapsedTime(TimeUnit)} is 0. - */ - @Deprecated - public ConnectionCheckOutFailedEvent(final ServerId serverId, final long operationId, final Reason reason) { - this(serverId, operationId, reason, 0); - } - - /** - * Construct an instance - * - * @param serverId the server id - * @param reason the reason the connection check out failed - * @deprecated Prefer {@link #ConnectionCheckOutFailedEvent(ServerId, long, Reason)} - * If this constructor is used, then {@link #getOperationId()} is -1. - */ - @Deprecated - public ConnectionCheckOutFailedEvent(final ServerId serverId, final Reason reason) { - this(serverId, -1, reason); - } - /** * Gets the server id * diff --git a/driver-core/src/main/com/mongodb/event/ConnectionCheckOutStartedEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionCheckOutStartedEvent.java index 3c8cef9e0ca..b01a0577550 100644 --- a/driver-core/src/main/com/mongodb/event/ConnectionCheckOutStartedEvent.java +++ b/driver-core/src/main/com/mongodb/event/ConnectionCheckOutStartedEvent.java @@ -41,17 +41,6 @@ public ConnectionCheckOutStartedEvent(final ServerId serverId, final long operat this.operationId = operationId; } - /** - * Construct an instance - * - * @param serverId the server id - * @deprecated Prefer {@link ConnectionCheckOutStartedEvent#ConnectionCheckOutStartedEvent(ServerId, long)} - */ - @Deprecated - public ConnectionCheckOutStartedEvent(final ServerId serverId) { - this(serverId, -1); - } - /** * Gets the server id * diff --git a/driver-core/src/main/com/mongodb/event/ConnectionCheckedInEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionCheckedInEvent.java index e18b7aabc0b..8f6b7ccff2d 100644 --- a/driver-core/src/main/com/mongodb/event/ConnectionCheckedInEvent.java +++ b/driver-core/src/main/com/mongodb/event/ConnectionCheckedInEvent.java @@ -44,17 +44,6 @@ public ConnectionCheckedInEvent(final ConnectionId connectionId, final long oper this.operationId = operationId; } - /** - * Construct an instance - * - * @param connectionId the connectionId - * @deprecated Prefer {@link #ConnectionCheckedInEvent(ConnectionId, long)} - */ - @Deprecated - public ConnectionCheckedInEvent(final ConnectionId connectionId) { - this(connectionId, -1); - } - /** * Gets the connection id * diff --git a/driver-core/src/main/com/mongodb/event/ConnectionCheckedOutEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionCheckedOutEvent.java index d289f797d21..91a1cfffe5c 100644 --- a/driver-core/src/main/com/mongodb/event/ConnectionCheckedOutEvent.java +++ b/driver-core/src/main/com/mongodb/event/ConnectionCheckedOutEvent.java @@ -50,32 +50,6 @@ public ConnectionCheckedOutEvent(final ConnectionId connectionId, final long ope this.elapsedTimeNanos = elapsedTimeNanos; } - /** - * Construct an instance - * - * @param connectionId the connectionId - * @param operationId the operation id - * @since 4.10 - * @deprecated Prefer {@link ConnectionCheckedOutEvent#ConnectionCheckedOutEvent(ConnectionId, long, long)}. - * If this constructor is used, then {@link #getElapsedTime(TimeUnit)} is 0. - */ - @Deprecated - public ConnectionCheckedOutEvent(final ConnectionId connectionId, final long operationId) { - this(connectionId, operationId, 0); - } - - /** - * Construct an instance - * - * @param connectionId the connectionId - * @deprecated Prefer {@link #ConnectionCheckedOutEvent(ConnectionId, long)}. - * If this constructor is used, then {@link #getOperationId()} is -1. - */ - @Deprecated - public ConnectionCheckedOutEvent(final ConnectionId connectionId) { - this(connectionId, -1); - } - /** * Gets the connection id * diff --git a/driver-core/src/main/com/mongodb/event/ConnectionReadyEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionReadyEvent.java index 0f5799148ff..1cc10672c8c 100644 --- a/driver-core/src/main/com/mongodb/event/ConnectionReadyEvent.java +++ b/driver-core/src/main/com/mongodb/event/ConnectionReadyEvent.java @@ -47,18 +47,6 @@ public ConnectionReadyEvent(final ConnectionId connectionId, final long elapsedT this.elapsedTimeNanos = elapsedTimeNanos; } - /** - * Construct an instance - * - * @param connectionId the connection id - * @deprecated Prefer {@link ConnectionReadyEvent#ConnectionReadyEvent(ConnectionId, long)}. - * If this constructor is used, then {@link #getElapsedTime(TimeUnit)} is 0. - */ - @Deprecated - public ConnectionReadyEvent(final ConnectionId connectionId) { - this(connectionId, 0); - } - /** * Gets the connection id * diff --git a/driver-core/src/main/com/mongodb/event/ServerHeartbeatFailedEvent.java b/driver-core/src/main/com/mongodb/event/ServerHeartbeatFailedEvent.java index d033e411a78..b324ddb84c9 100644 --- a/driver-core/src/main/com/mongodb/event/ServerHeartbeatFailedEvent.java +++ b/driver-core/src/main/com/mongodb/event/ServerHeartbeatFailedEvent.java @@ -34,19 +34,6 @@ public final class ServerHeartbeatFailedEvent { private final boolean awaited; private final Throwable throwable; - /** - * Construct an instance. - * - * @param connectionId the non-null connectionId - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds - * @param throwable the non-null exception that caused the failure - * @deprecated Prefer {@link #ServerHeartbeatFailedEvent(ConnectionId, long, boolean, Throwable)} - */ - @Deprecated - public ServerHeartbeatFailedEvent(final ConnectionId connectionId, final long elapsedTimeNanos, final Throwable throwable) { - this(connectionId, elapsedTimeNanos, false, throwable); - } - /** * Construct an instance. * diff --git a/driver-core/src/main/com/mongodb/event/ServerHeartbeatSucceededEvent.java b/driver-core/src/main/com/mongodb/event/ServerHeartbeatSucceededEvent.java index d396a089950..e6deb0bb7ad 100644 --- a/driver-core/src/main/com/mongodb/event/ServerHeartbeatSucceededEvent.java +++ b/driver-core/src/main/com/mongodb/event/ServerHeartbeatSucceededEvent.java @@ -35,19 +35,6 @@ public final class ServerHeartbeatSucceededEvent { private final long elapsedTimeNanos; private final boolean awaited; - /** - * Construct an instance. - * - * @param connectionId the non-null connectionId - * @param reply the non-null reply to an hello command - * @param elapsedTimeNanos the non-negative elapsed time in nanoseconds - * @deprecated Prefer {@link #ServerHeartbeatSucceededEvent(ConnectionId, BsonDocument, long, boolean)} - */ - @Deprecated - public ServerHeartbeatSucceededEvent(final ConnectionId connectionId, final BsonDocument reply, final long elapsedTimeNanos) { - this(connectionId, reply, elapsedTimeNanos, false); - } - /** * Construct an instance. * diff --git a/driver-core/src/test/functional/com/mongodb/client/CommandMonitoringTestHelper.java b/driver-core/src/test/functional/com/mongodb/client/CommandMonitoringTestHelper.java index 62e3582ccca..8ba3a5b3851 100644 --- a/driver-core/src/test/functional/com/mongodb/client/CommandMonitoringTestHelper.java +++ b/driver-core/src/test/functional/com/mongodb/client/CommandMonitoringTestHelper.java @@ -100,10 +100,9 @@ public static List getExpectedEvents(final BsonArray expectedEvent commandDocument); } else if (eventType.equals("command_succeeded_event")) { BsonDocument replyDocument = eventDescriptionDocument.get("reply").asDocument(); - commandEvent = new CommandSucceededEvent(null, 1, 1, null, commandName, replyDocument, 1); - + commandEvent = new CommandSucceededEvent(null, 1, 1, null, null, commandName, replyDocument, 1); } else if (eventType.equals("command_failed_event")) { - commandEvent = new CommandFailedEvent(null, 1, 1, null, commandName, 1, null); + commandEvent = new CommandFailedEvent(null, 1, 1, null, null, commandName, 1, null); } else { throw new UnsupportedOperationException("Unsupported command event type: " + eventType); } @@ -218,7 +217,8 @@ private static CommandSucceededEvent massageActualCommandSucceededEvent(final Co } } return new CommandSucceededEvent(actual.getRequestContext(), actual.getOperationId(), actual.getRequestId(), - actual.getConnectionDescription(), actual.getCommandName(), response, actual.getElapsedTime(TimeUnit.NANOSECONDS)); + actual.getConnectionDescription(), actual.getDatabaseName(), actual.getCommandName(), response, + actual.getElapsedTime(TimeUnit.NANOSECONDS)); } private static CommandStartedEvent massageActualCommandStartedEvent(final CommandStartedEvent event, diff --git a/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentCodecSpecification.groovy b/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentCodecSpecification.groovy index 3acd758fa73..585338a0749 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentCodecSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentCodecSpecification.groovy @@ -77,10 +77,9 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, null, BsonDocument.parse('{_id: 1}'), - new BsonTimestamp(1234, 2) - , + new BsonTimestamp(1234, 2), new UpdateDescription(['phoneNumber'], BsonDocument.parse('{email: "alice@10gen.com"}'), null), - null, null, null, null + null, null, null, null, null ), new ChangeStreamDocument(OperationType.UPDATE.value, BsonDocument.parse('{token: true}'), @@ -89,11 +88,10 @@ class ChangeStreamDocumentCodecSpecification extends Specification { Document.parse('{_id: 1, userName: "alice123", name: "Alice"}'), Document.parse('{_id: 1, userName: "alice1234", name: "Alice"}'), BsonDocument.parse('{_id: 1}'), - new BsonTimestamp(1234, 2) - , + new BsonTimestamp(1234, 2), new UpdateDescription(['phoneNumber'], BsonDocument.parse('{email: "alice@10gen.com"}'), singletonList(new TruncatedArray('education', 2))), - null, null, null, null + null, null, null, null, null ), new ChangeStreamDocument(OperationType.REPLACE.value, BsonDocument.parse('{token: true}'), @@ -102,9 +100,8 @@ class ChangeStreamDocumentCodecSpecification extends Specification { Document.parse('{_id: 1, userName: "alice123", name: "Alice"}'), Document.parse('{_id: 1, userName: "alice1234", name: "Alice"}'), BsonDocument.parse('{_id: 1}'), - new BsonTimestamp(1234, 2) - , - null, null, null, null, null + new BsonTimestamp(1234, 2), + null, null, null, null, null, null ), new ChangeStreamDocument(OperationType.DELETE.value, BsonDocument.parse('{token: true}'), @@ -113,9 +110,8 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, Document.parse('{_id: 1, userName: "alice123", name: "Alice"}'), BsonDocument.parse('{_id: 1}'), - new BsonTimestamp(1234, 2) - , - null, null, null, null, null + new BsonTimestamp(1234, 2), + null, null, null, null, null, null ), new ChangeStreamDocument(OperationType.DROP.value, BsonDocument.parse('{token: true}'), @@ -124,9 +120,8 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, null, null, - new BsonTimestamp(1234, 2) - , - null, null, null, null, null + new BsonTimestamp(1234, 2), + null, null, null, null, null, null ), new ChangeStreamDocument(OperationType.RENAME.value, BsonDocument.parse('{token: true}'), @@ -135,9 +130,8 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, null, null, - new BsonTimestamp(1234, 2) - , - null, null, null, null, null + new BsonTimestamp(1234, 2), + null, null, null, null, null, null ), new ChangeStreamDocument(OperationType.DROP_DATABASE.value, BsonDocument.parse('{token: true}'), @@ -146,9 +140,8 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, null, null, - new BsonTimestamp(1234, 2) - , - null, null, null, null, null + new BsonTimestamp(1234, 2), + null, null, null, null, null, null ), new ChangeStreamDocument(OperationType.INVALIDATE.value, BsonDocument.parse('{token: true}'), @@ -157,9 +150,8 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, null, null, - new BsonTimestamp(1234, 2) - , - null, null, null, null, null + new BsonTimestamp(1234, 2), + null, null, null, null, null, null ), new ChangeStreamDocument(OperationType.INSERT.value, BsonDocument.parse('{token: true}'), @@ -172,7 +164,7 @@ class ChangeStreamDocumentCodecSpecification extends Specification { null, new BsonInt64(1), BsonDocument.parse('{id: 1, uid: 2}'), - new BsonDateTime(42), + new BsonDateTime(42), null, new BsonDocument('extra', BsonBoolean.TRUE).append('value', new BsonInt32(1)) ), ] diff --git a/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentSpecification.groovy b/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentSpecification.groovy index b7651f7b341..9a1c8fc4aca 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/client/model/changestream/ChangeStreamDocumentSpecification.groovy @@ -46,7 +46,7 @@ class ChangeStreamDocumentSpecification extends Specification { def txnNumber = new BsonInt64(1) def lsid = BsonDocument.parse('{id: 1, uid: 1}') def wallTime = new BsonDateTime(42) - def splitEvent = new SplitEvent(1, 2); + def splitEvent = new SplitEvent(1, 2) def extraElements = new BsonDocument('extra', BsonBoolean.TRUE) when: @@ -73,87 +73,23 @@ class ChangeStreamDocumentSpecification extends Specification { changeStreamDocument.getWallTime() == wallTime changeStreamDocument.getSplitEvent() == splitEvent changeStreamDocument.getExtraElements() == extraElements - - when: - //noinspection GrDeprecatedAPIUsage - changeStreamDocument = new ChangeStreamDocument(operationType.value, resumeToken, namespaceDocument, - destinationNamespaceDocument, fullDocument, documentKey, clusterTime, updateDesc, txnNumber, lsid) - - then: - changeStreamDocument.getResumeToken() == resumeToken - changeStreamDocument.getFullDocument() == fullDocument - changeStreamDocument.getFullDocumentBeforeChange() == null - changeStreamDocument.getDocumentKey() == documentKey - changeStreamDocument.getClusterTime() == clusterTime - changeStreamDocument.getNamespace() == namespace - changeStreamDocument.getNamespaceDocument() == namespaceDocument - changeStreamDocument.getDestinationNamespace() == destinationNamespace - changeStreamDocument.getDestinationNamespaceDocument() == destinationNamespaceDocument - changeStreamDocument.getOperationTypeString() == operationType.value - changeStreamDocument.getOperationType() == operationType - changeStreamDocument.getUpdateDescription() == updateDesc - changeStreamDocument.getDatabaseName() == namespace.getDatabaseName() - changeStreamDocument.getTxnNumber() == txnNumber - changeStreamDocument.getLsid() == lsid - changeStreamDocument.getWallTime() == null - - when: - //noinspection GrDeprecatedAPIUsage - changeStreamDocument = new ChangeStreamDocument(operationType, resumeToken, namespaceDocument, - destinationNamespaceDocument, fullDocument, documentKey, clusterTime, updateDesc, txnNumber, lsid) - - then: - changeStreamDocument.getResumeToken() == resumeToken - changeStreamDocument.getFullDocument() == fullDocument - changeStreamDocument.getDocumentKey() == documentKey - changeStreamDocument.getClusterTime() == clusterTime - changeStreamDocument.getNamespace() == namespace - changeStreamDocument.getNamespaceDocument() == namespaceDocument - changeStreamDocument.getDestinationNamespace() == destinationNamespace - changeStreamDocument.getDestinationNamespaceDocument() == destinationNamespaceDocument - changeStreamDocument.getOperationTypeString() == operationType.value - changeStreamDocument.getOperationType() == operationType - changeStreamDocument.getUpdateDescription() == updateDesc - changeStreamDocument.getDatabaseName() == namespace.getDatabaseName() - changeStreamDocument.getTxnNumber() == txnNumber - changeStreamDocument.getLsid() == lsid - changeStreamDocument.getWallTime() == null - - when: - //noinspection GrDeprecatedAPIUsage - def changeStreamDocumentWithTxnInfo = new ChangeStreamDocument(operationType.value, resumeToken, - namespaceDocument, destinationNamespaceDocument, fullDocument, documentKey, clusterTime, updateDesc, - txnNumber, lsid) - - then: - changeStreamDocumentWithTxnInfo.getResumeToken() == resumeToken - changeStreamDocumentWithTxnInfo.getFullDocument() == fullDocument - changeStreamDocumentWithTxnInfo.getDocumentKey() == documentKey - changeStreamDocumentWithTxnInfo.getClusterTime() == clusterTime - changeStreamDocumentWithTxnInfo.getNamespace() == namespace - changeStreamDocumentWithTxnInfo.getNamespaceDocument() == namespaceDocument - changeStreamDocumentWithTxnInfo.getDestinationNamespace() == destinationNamespace - changeStreamDocumentWithTxnInfo.getDestinationNamespaceDocument() == destinationNamespaceDocument - changeStreamDocumentWithTxnInfo.getOperationTypeString() == operationType.value - changeStreamDocumentWithTxnInfo.getOperationType() == operationType - changeStreamDocumentWithTxnInfo.getUpdateDescription() == updateDesc - changeStreamDocumentWithTxnInfo.getDatabaseName() == namespace.getDatabaseName() - changeStreamDocumentWithTxnInfo.getTxnNumber() == txnNumber - changeStreamDocumentWithTxnInfo.getLsid() == lsid - changeStreamDocument.getWallTime() == null } def 'should handle null namespace correctly'() { given: def resumeToken = RawBsonDocument.parse('{token: true}') def fullDocument = BsonDocument.parse('{key: "value for fullDocument"}') + def fullDocumentBeforeChange = BsonDocument.parse('{key: "value for fullDocumentBeforeChange"}') def documentKey = BsonDocument.parse('{_id : 1}') def clusterTime = new BsonTimestamp(1234, 2) def operationType = OperationType.DROP_DATABASE def updateDesc = new UpdateDescription(['a', 'b'], BsonDocument.parse('{c: 1}'), emptyList()) - //noinspection GrDeprecatedAPIUsage + def wallTime = new BsonDateTime(42) + def splitEvent = new SplitEvent(1, 2) + def extraElements = new BsonDocument('extra', BsonBoolean.TRUE) def changeStreamDocumentNullNamespace = new ChangeStreamDocument(operationType.value, resumeToken, - (BsonDocument) null, (BsonDocument) null, fullDocument, documentKey, clusterTime, updateDesc, null, null) + (BsonDocument) null, (BsonDocument) null, fullDocument, fullDocumentBeforeChange, documentKey, clusterTime, updateDesc, + null, null, wallTime, splitEvent, extraElements) expect: changeStreamDocumentNullNamespace.getDatabaseName() == null @@ -169,17 +105,20 @@ class ChangeStreamDocumentSpecification extends Specification { def namespaceDocument = BsonDocument.parse('{db: "databaseName"}') def namespaceDocumentEmpty = new BsonDocument() def fullDocument = BsonDocument.parse('{key: "value for fullDocument"}') + def fullDocumentBeforeChange = BsonDocument.parse('{key: "value for fullDocumentBeforeChange"}') def documentKey = BsonDocument.parse('{_id : 1}') def clusterTime = new BsonTimestamp(1234, 2) def updateDesc = new UpdateDescription(['a', 'b'], BsonDocument.parse('{c: 1}'), singletonList(new TruncatedArray('d', 1))) + def wallTime = new BsonDateTime(42) + def splitEvent = new SplitEvent(1, 2) + def extraElements = new BsonDocument('extra', BsonBoolean.TRUE) - //noinspection GrDeprecatedAPIUsage def changeStreamDocument = new ChangeStreamDocument(null, resumeToken, namespaceDocument, - (BsonDocument) null, fullDocument, documentKey, clusterTime, updateDesc, null, null) - //noinspection GrDeprecatedAPIUsage + (BsonDocument) null, fullDocument, fullDocumentBeforeChange, documentKey, clusterTime, updateDesc, null, null, + wallTime, splitEvent, extraElements) def changeStreamDocumentEmptyNamespace = new ChangeStreamDocument(null, resumeToken, - namespaceDocumentEmpty, (BsonDocument) null, fullDocument, documentKey, clusterTime, updateDesc, - null, null) + namespaceDocumentEmpty, (BsonDocument) null, fullDocument, fullDocumentBeforeChange, documentKey, clusterTime, updateDesc, + null, null, wallTime, splitEvent, extraElements) expect: changeStreamDocument.getNamespace() == null diff --git a/driver-core/src/test/unit/com/mongodb/event/CommandEventSpecification.groovy b/driver-core/src/test/unit/com/mongodb/event/CommandEventSpecification.groovy index eb9dd19ce4b..015ac92aa3e 100644 --- a/driver-core/src/test/unit/com/mongodb/event/CommandEventSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/event/CommandEventSpecification.groovy @@ -20,6 +20,7 @@ import com.mongodb.ServerAddress import com.mongodb.connection.ClusterId import com.mongodb.connection.ConnectionDescription import com.mongodb.connection.ServerId +import com.mongodb.internal.IgnorableRequestContext import org.bson.BsonDocument import org.bson.BsonInt32 import spock.lang.Specification @@ -27,7 +28,8 @@ import spock.lang.Specification class CommandEventSpecification extends Specification { def 'should fail if elapsed time is negative'() { when: - new CommandSucceededEvent(1, new ConnectionDescription(new ServerId(new ClusterId(), new ServerAddress())), 'ping', + new CommandSucceededEvent(IgnorableRequestContext.INSTANCE, 1, 1, + new ConnectionDescription(new ServerId(new ClusterId(), new ServerAddress())), 'test', 'ping', new BsonDocument('ok', new BsonInt32(1)), -1) then: @@ -35,8 +37,8 @@ class CommandEventSpecification extends Specification { e.getMessage() == 'state should be: elapsed time is not negative' when: - new CommandFailedEvent(1, new ConnectionDescription(new ServerId(new ClusterId(), new ServerAddress())), 'ping', -1, - new Throwable()) + new CommandFailedEvent(IgnorableRequestContext.INSTANCE, 1, 1, + new ConnectionDescription(new ServerId(new ClusterId(), new ServerAddress())), 'test', 'ping', -1, new Throwable()) then: e = thrown(IllegalArgumentException) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy index 52e316cc15b..ba5625999d1 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy @@ -656,7 +656,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'ping', + new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', new BsonDocument('ok', new BsonInt32(1)), 1000)]) } @@ -680,7 +680,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'ping', + new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', new BsonDocument('ok', new BsonInt32(1)), 1000)]) } @@ -767,7 +767,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events for command failure with exception reading header'() { @@ -788,7 +788,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events for command failure with exception reading body'() { @@ -810,7 +810,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events for command failure with exception from failed command'() { @@ -833,7 +833,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events with elided command and response in successful security-sensitive commands'() { @@ -854,7 +854,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', securitySensitiveCommandName, new BsonDocument()), - new CommandSucceededEvent(null, 1, 1, connection.getDescription(), securitySensitiveCommandName, + new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'admin', securitySensitiveCommandName, new BsonDocument(), 1)]) where: @@ -939,7 +939,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'ping', + new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', new BsonDocument('ok', new BsonInt32(1)), 1000)]) } @@ -973,7 +973,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'ping', + new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', new BsonDocument('ok', new BsonInt32(1)), 1000)]) } @@ -1001,7 +1001,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events for asynchronous command failure with exception reading header'() { @@ -1030,7 +1030,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events for asynchronous command failure with exception reading body'() { @@ -1062,7 +1062,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events for asynchronous command failure with exception from failed command'() { @@ -1095,7 +1095,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', pingCommandDocument.append('$db', new BsonString('admin'))), - new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'ping', 0, e)]) + new CommandFailedEvent(null, 1, 1, connection.getDescription(), 'admin', 'ping', 0, e)]) } def 'should send events with elided command and response in successful security-sensitive asynchronous commands'() { @@ -1126,7 +1126,7 @@ class InternalStreamConnectionSpecification extends Specification { commandListener.eventsWereDelivered([ new CommandStartedEvent(null, 1, 1, connection.getDescription(), 'admin', securitySensitiveCommandName, new BsonDocument()), - new CommandSucceededEvent(null, 1, 1, connection.getDescription(), securitySensitiveCommandName, + new CommandSucceededEvent(null, 1, 1, connection.getDescription(), 'admin', securitySensitiveCommandName, new BsonDocument(), 1)]) where: From c5dd111117878b16f75d0394150596590cedbf73 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 9 Nov 2023 09:06:09 -0500 Subject: [PATCH 18/28] Remove deprecated oplogReplay-related methods (#1252) JAVA-5150 --- config/detekt/baseline.xml | 4 +-- .../internal/client/model/FindOptions.java | 26 ++----------------- .../internal/operation/FindOperation.java | 13 ---------- .../internal/operation/Operations.java | 1 - .../FindOperationSpecification.groovy | 4 --- .../model/FindOptionsSpecification.groovy | 9 ------- .../FindOperationUnitSpecification.groovy | 3 --- .../coroutine/syncadapter/SyncFindIterable.kt | 4 --- .../kotlin/client/coroutine/FindFlow.kt | 11 -------- .../kotlin/client/coroutine/FindFlowTest.kt | 10 +------ .../client/syncadapter/SyncFindIterable.kt | 4 --- .../com/mongodb/kotlin/client/FindIterable.kt | 11 -------- .../mongodb/kotlin/client/FindIterableTest.kt | 10 +------ .../src/main/com/mongodb/DBCursor.java | 16 ------------ .../client/model/DBCollectionFindOptions.java | 26 ------------------- .../com/mongodb/DBCursorSpecification.groovy | 4 --- ...BCollectionFindOptionsSpecification.groovy | 5 ---- .../reactivestreams/client/FindPublisher.java | 10 ------- .../client/internal/FindPublisherImpl.java | 7 ----- .../client/syncadapter/SyncFindIterable.java | 7 ----- .../internal/FindPublisherImplTest.java | 2 -- .../scala/syncadapter/SyncFindIterable.scala | 5 ---- .../org/mongodb/scala/FindObservable.scala | 15 ++--------- .../mongodb/scala/FindObservableSpec.scala | 6 ++--- .../main/com/mongodb/client/FindIterable.java | 10 ------- .../client/internal/FindIterableImpl.java | 7 ----- .../internal/FindIterableSpecification.groovy | 3 --- 27 files changed, 10 insertions(+), 223 deletions(-) diff --git a/config/detekt/baseline.xml b/config/detekt/baseline.xml index c899728c7be..5d6b5a9fec1 100644 --- a/config/detekt/baseline.xml +++ b/config/detekt/baseline.xml @@ -4,8 +4,8 @@ IteratorNotThrowingNoSuchElementException:MongoCursor.kt$MongoCursor<T : Any> : IteratorCloseable LargeClass:MongoCollectionTest.kt$MongoCollectionTest - LongMethod:FindFlowTest.kt$FindFlowTest$@Suppress("DEPRECATION") @Test fun shouldCallTheUnderlyingMethods() - LongMethod:FindIterableTest.kt$FindIterableTest$@Suppress("DEPRECATION") @Test fun shouldCallTheUnderlyingMethods() + LongMethod:FindFlowTest.kt$FindFlowTest$@Test fun shouldCallTheUnderlyingMethods() + LongMethod:FindIterableTest.kt$FindIterableTest$@Test fun shouldCallTheUnderlyingMethods() LongMethod:KotlinSerializerCodecTest.kt$KotlinSerializerCodecTest$@Test fun testDataClassOptionalBsonValues() MaxLineLength:MapReduceFlow.kt$MapReduceFlow$* MaxLineLength:MapReduceIterable.kt$MapReduceIterable$* diff --git a/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java b/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java index f92885ae9fc..3a87434e9ed 100644 --- a/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java +++ b/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java @@ -43,7 +43,6 @@ public final class FindOptions { private Bson sort; private CursorType cursorType = CursorType.NonTailable; private boolean noCursorTimeout; - private boolean oplogReplay; private boolean partial; private Collation collation; private BsonValue comment; @@ -65,7 +64,7 @@ public FindOptions() { //CHECKSTYLE:OFF FindOptions( final int batchSize, final int limit, final Bson projection, final long maxTimeMS, final long maxAwaitTimeMS, final int skip, - final Bson sort, final CursorType cursorType, final boolean noCursorTimeout, final boolean oplogReplay, final boolean partial, + final Bson sort, final CursorType cursorType, final boolean noCursorTimeout, final boolean partial, final Collation collation, final BsonValue comment, final Bson hint, final String hintString, final Bson variables, final Bson max, final Bson min, final boolean returnKey, final boolean showRecordId, final Boolean allowDiskUse) { this.batchSize = batchSize; @@ -77,7 +76,6 @@ public FindOptions() { this.sort = sort; this.cursorType = cursorType; this.noCursorTimeout = noCursorTimeout; - this.oplogReplay = oplogReplay; this.partial = partial; this.collation = collation; this.comment = comment; @@ -94,7 +92,7 @@ public FindOptions() { public FindOptions withBatchSize(final int batchSize) { return new FindOptions(batchSize, limit, projection, maxTimeMS, maxAwaitTimeMS, skip, sort, cursorType, noCursorTimeout, - oplogReplay, partial, collation, comment, hint, hintString, variables, max, min, returnKey, showRecordId, allowDiskUse); + partial, collation, comment, hint, hintString, variables, max, min, returnKey, showRecordId, allowDiskUse); } /** @@ -295,26 +293,6 @@ public FindOptions noCursorTimeout(final boolean noCursorTimeout) { return this; } - /** - * Users should not set this under normal circumstances. - * - * @return if oplog replay is enabled - */ - public boolean isOplogReplay() { - return oplogReplay; - } - - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - */ - public FindOptions oplogReplay(final boolean oplogReplay) { - this.oplogReplay = oplogReplay; - return this; - } - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java b/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java index 72d20835aa1..fa5aa9af1be 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java @@ -83,7 +83,6 @@ public class FindOperation implements AsyncExplainableReadOperation cursorType(final CursorType cursorType) { return this; } - public boolean isOplogReplay() { - return oplogReplay; - } - - public FindOperation oplogReplay(final boolean oplogReplay) { - this.oplogReplay = oplogReplay; - return this; - } - public boolean isNoCursorTimeout() { return noCursorTimeout; } @@ -418,9 +408,6 @@ private BsonDocument getCommand(final SessionContext sessionContext, final int m if (isAwaitData()) { commandDocument.put("awaitData", BsonBoolean.TRUE); } - if (oplogReplay) { - commandDocument.put("oplogReplay", BsonBoolean.TRUE); - } if (noCursorTimeout) { commandDocument.put("noCursorTimeout", BsonBoolean.TRUE); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/Operations.java b/driver-core/src/main/com/mongodb/internal/operation/Operations.java index 5aeb47d113a..bb09230e3bc 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/Operations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/Operations.java @@ -197,7 +197,6 @@ private FindOperation createFindOperation(final MongoNamespac .sort(toBsonDocument(options.getSort())) .cursorType(options.getCursorType()) .noCursorTimeout(options.isNoCursorTimeout()) - .oplogReplay(options.isOplogReplay()) .partial(options.isPartial()) .collation(options.getCollation()) .comment(options.getComment()) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy index 602b18e6a95..3bd84accd6f 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy @@ -95,7 +95,6 @@ class FindOperationSpecification extends OperationFunctionalSpecification { operation.getProjection() == null operation.getCollation() == null !operation.isNoCursorTimeout() - !operation.isOplogReplay() !operation.isPartial() operation.isAllowDiskUse() == null } @@ -119,7 +118,6 @@ class FindOperationSpecification extends OperationFunctionalSpecification { .cursorType(Tailable) .collation(defaultCollation) .partial(true) - .oplogReplay(true) .noCursorTimeout(true) .allowDiskUse(true) @@ -134,7 +132,6 @@ class FindOperationSpecification extends OperationFunctionalSpecification { operation.getProjection() == projection operation.getCollation() == defaultCollation operation.isNoCursorTimeout() - operation.isOplogReplay() operation.isPartial() operation.isAllowDiskUse() } @@ -709,7 +706,6 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def operation = new FindOperation(namespace, new BsonDocumentCodec()) .noCursorTimeout(true) .partial(true) - .oplogReplay(true) when: execute(operation, async) diff --git a/driver-core/src/test/unit/com/mongodb/client/model/FindOptionsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/client/model/FindOptionsSpecification.groovy index 3ca239ef53a..380d305cb28 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/FindOptionsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/client/model/FindOptionsSpecification.groovy @@ -44,7 +44,6 @@ class FindOptionsSpecification extends Specification { options.getBatchSize() == 0 options.getCursorType() == CursorType.NonTailable !options.isNoCursorTimeout() - !options.isOplogReplay() !options.isPartial() !options.isAllowDiskUse() } @@ -113,14 +112,6 @@ class FindOptionsSpecification extends Specification { partial << [true, false] } - def 'should set oplogReplay'() { - expect: - new FindOptions().oplogReplay(oplogReplay).isOplogReplay() == oplogReplay - - where: - oplogReplay << [true, false] - } - def 'should set noCursorTimeout'() { expect: new FindOptions().noCursorTimeout(noCursorTimeout).isNoCursorTimeout() == noCursorTimeout diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/FindOperationUnitSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/FindOperationUnitSpecification.groovy index 0128b4158ee..b2bd9019ef5 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/FindOperationUnitSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/FindOperationUnitSpecification.groovy @@ -47,10 +47,8 @@ class FindOperationUnitSpecification extends OperationUnitSpecification { .limit(limit) .batchSize(batchSize) .cursorType(TailableAwait) - .oplogReplay(true) .noCursorTimeout(true) .partial(true) - .oplogReplay(true) .maxTime(10, MILLISECONDS) .comment(new BsonString('my comment')) .hint(BsonDocument.parse('{ hint : 1}')) @@ -70,7 +68,6 @@ class FindOperationUnitSpecification extends OperationUnitSpecification { .append('awaitData', BsonBoolean.TRUE) .append('allowPartialResults', BsonBoolean.TRUE) .append('noCursorTimeout', BsonBoolean.TRUE) - .append('oplogReplay', BsonBoolean.TRUE) .append('maxTimeMS', new BsonInt64(operation.getMaxTime(MILLISECONDS))) .append('comment', operation.getComment()) .append('hint', operation.getHint()) diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt b/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt index 49ba1d49f58..b9e3a6665d6 100644 --- a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt +++ b/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt @@ -26,7 +26,6 @@ import org.bson.BsonValue import org.bson.Document import org.bson.conversions.Bson -@Suppress("DEPRECATION") data class SyncFindIterable(val wrapped: FindFlow) : JFindIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncFindIterable = apply { wrapped.batchSize(batchSize) } override fun filter(filter: Bson?): SyncFindIterable = apply { wrapped.filter(filter) } @@ -55,9 +54,6 @@ data class SyncFindIterable(val wrapped: FindFlow) : JFindIterable = apply { wrapped.oplogReplay(oplogReplay) } - override fun partial(partial: Boolean): SyncFindIterable = apply { wrapped.partial(partial) } override fun cursorType(cursorType: CursorType): SyncFindIterable = apply { wrapped.cursorType(cursorType) } diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt index ed0992b1bf7..49a391c236f 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt @@ -131,17 +131,6 @@ public class FindFlow(private val wrapped: FindPublisher) : Flow wrapped.noCursorTimeout(noCursorTimeout) } - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Suppress("DEPRECATION") - @Deprecated("oplogReplay has been deprecated in MongoDB 4.4", replaceWith = ReplaceWith("")) - public fun oplogReplay(oplogReplay: Boolean): FindFlow = apply { wrapped.oplogReplay(oplogReplay) } - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt index d86b0daef99..2216c044883 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt @@ -27,12 +27,7 @@ import org.bson.BsonDocument import org.bson.BsonString import org.bson.Document import org.junit.jupiter.api.Test -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.mock -import org.mockito.kotlin.times -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoMoreInteractions -import org.mockito.kotlin.whenever +import org.mockito.kotlin.* import reactor.core.publisher.Mono class FindFlowTest { @@ -44,7 +39,6 @@ class FindFlowTest { assertEquals(jFindPublisherFunctions, kFindFlowFunctions) } - @Suppress("DEPRECATION") @Test fun shouldCallTheUnderlyingMethods() { val wrapped: FindPublisher = mock() @@ -77,7 +71,6 @@ class FindFlowTest { flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) flow.min(bson) - flow.oplogReplay(true) flow.noCursorTimeout(true) flow.partial(true) flow.projection(bson) @@ -103,7 +96,6 @@ class FindFlowTest { verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).min(bson) - verify(wrapped).oplogReplay(true) verify(wrapped).noCursorTimeout(true) verify(wrapped).partial(true) verify(wrapped).projection(bson) diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt b/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt index c52866f1243..f179f4ff6bc 100644 --- a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt +++ b/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt @@ -25,7 +25,6 @@ import org.bson.BsonValue import org.bson.Document import org.bson.conversions.Bson -@Suppress("DEPRECATION") internal class SyncFindIterable(val wrapped: FindIterable) : JFindIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncFindIterable = apply { wrapped.batchSize(batchSize) } @@ -55,9 +54,6 @@ internal class SyncFindIterable(val wrapped: FindIterable) : wrapped.noCursorTimeout(noCursorTimeout) } - @Suppress("OVERRIDE_DEPRECATION") - override fun oplogReplay(oplogReplay: Boolean): SyncFindIterable = apply { wrapped.oplogReplay(oplogReplay) } - override fun partial(partial: Boolean): SyncFindIterable = apply { wrapped.partial(partial) } override fun cursorType(cursorType: CursorType): SyncFindIterable = apply { wrapped.cursorType(cursorType) } diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt index 45b51a1e9c9..2a33cb6f268 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt @@ -126,17 +126,6 @@ public class FindIterable(private val wrapped: JFindIterable) : Mong wrapped.noCursorTimeout(noCursorTimeout) } - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Suppress("DEPRECATION") - @Deprecated("oplogReplay has been deprecated in MongoDB 4.4", replaceWith = ReplaceWith("")) - public fun oplogReplay(oplogReplay: Boolean): FindIterable = apply { wrapped.oplogReplay(oplogReplay) } - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt index c84176a0cbf..9d8d28104d1 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt @@ -26,12 +26,7 @@ import org.bson.BsonDocument import org.bson.BsonString import org.bson.Document import org.junit.jupiter.api.Test -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.mock -import org.mockito.kotlin.times -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoMoreInteractions -import org.mockito.kotlin.whenever +import org.mockito.kotlin.* class FindIterableTest { @Test @@ -42,7 +37,6 @@ class FindIterableTest { assertEquals(jFindIterableFunctions, kFindIterableFunctions) } - @Suppress("DEPRECATION") @Test fun shouldCallTheUnderlyingMethods() { val wrapped: JFindIterable = mock() @@ -85,7 +79,6 @@ class FindIterableTest { iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) iterable.min(bson) - iterable.oplogReplay(true) iterable.noCursorTimeout(true) iterable.partial(true) iterable.projection(bson) @@ -114,7 +107,6 @@ class FindIterableTest { verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).min(bson) - verify(wrapped).oplogReplay(true) verify(wrapped).noCursorTimeout(true) verify(wrapped).partial(true) verify(wrapped).projection(bson) diff --git a/driver-legacy/src/main/com/mongodb/DBCursor.java b/driver-legacy/src/main/com/mongodb/DBCursor.java index 8012a1a8727..739901b7c57 100644 --- a/driver-legacy/src/main/com/mongodb/DBCursor.java +++ b/driver-legacy/src/main/com/mongodb/DBCursor.java @@ -387,20 +387,6 @@ public DBCursor cursorType(final CursorType cursorType) { return this; } - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - * @since 3.9 - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Deprecated - public DBCursor oplogReplay(final boolean oplogReplay) { - findOptions.oplogReplay(oplogReplay); - return this; - } - /** * The server normally times out idle cursors after an inactivity period (10 minutes) * to prevent excess memory use. Set this option to prevent that. @@ -426,7 +412,6 @@ public DBCursor partial(final boolean partial) { return this; } - @SuppressWarnings("deprecation") private FindOperation getQueryOperation(final Decoder decoder) { return new FindOperation<>(collection.getNamespace(), decoder) @@ -449,7 +434,6 @@ private FindOperation getQueryOperation(final Decoder decode .max(collection.wrapAllowNull(findOptions.getMax())) .cursorType(findOptions.getCursorType()) .noCursorTimeout(findOptions.isNoCursorTimeout()) - .oplogReplay(findOptions.isOplogReplay()) .partial(findOptions.isPartial()) .returnKey(findOptions.isReturnKey()) .showRecordId(findOptions.isShowRecordId()) diff --git a/driver-legacy/src/main/com/mongodb/client/model/DBCollectionFindOptions.java b/driver-legacy/src/main/com/mongodb/client/model/DBCollectionFindOptions.java index 930843cc3ce..256419315f7 100644 --- a/driver-legacy/src/main/com/mongodb/client/model/DBCollectionFindOptions.java +++ b/driver-legacy/src/main/com/mongodb/client/model/DBCollectionFindOptions.java @@ -44,7 +44,6 @@ public final class DBCollectionFindOptions { private DBObject sort; private CursorType cursorType = CursorType.NonTailable; private boolean noCursorTimeout; - private boolean oplogReplay; private boolean partial; private ReadPreference readPreference; private ReadConcern readConcern; @@ -79,7 +78,6 @@ public DBCollectionFindOptions copy() { copiedOptions.sort(sort); copiedOptions.cursorType(cursorType); copiedOptions.noCursorTimeout(noCursorTimeout); - copiedOptions.oplogReplay(oplogReplay); copiedOptions.partial(partial); copiedOptions.readPreference(readPreference); copiedOptions.readConcern(readConcern); @@ -294,30 +292,6 @@ public DBCollectionFindOptions noCursorTimeout(final boolean noCursorTimeout) { return this; } - /** - * Users should not set this under normal circumstances. - * - * @return if oplog replay is enabled - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Deprecated - public boolean isOplogReplay() { - return oplogReplay; - } - - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Deprecated - public DBCollectionFindOptions oplogReplay(final boolean oplogReplay) { - this.oplogReplay = oplogReplay; - return this; - } - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-legacy/src/test/unit/com/mongodb/DBCursorSpecification.groovy b/driver-legacy/src/test/unit/com/mongodb/DBCursorSpecification.groovy index 768dd52d7ed..84a755b5353 100644 --- a/driver-legacy/src/test/unit/com/mongodb/DBCursorSpecification.groovy +++ b/driver-legacy/src/test/unit/com/mongodb/DBCursorSpecification.groovy @@ -169,7 +169,6 @@ class DBCursorSpecification extends Specification { .limit(1) .maxTime(1, TimeUnit.MILLISECONDS) .noCursorTimeout(true) - .oplogReplay(true) .partial(true) .skip(1) .sort(sort) @@ -186,7 +185,6 @@ class DBCursorSpecification extends Specification { .limit(1) .maxTime(1, TimeUnit.MILLISECONDS) .noCursorTimeout(true) - .oplogReplay(true) .partial(true) .skip(1) .sort(bsonSort) @@ -226,7 +224,6 @@ class DBCursorSpecification extends Specification { .maxAwaitTime(1, TimeUnit.MILLISECONDS) .maxTime(1, TimeUnit.MILLISECONDS) .noCursorTimeout(true) - .oplogReplay(true) .partial(true) .projection(projection) .readConcern(readConcern) @@ -255,7 +252,6 @@ class DBCursorSpecification extends Specification { .maxAwaitTime(1, TimeUnit.MILLISECONDS) .maxTime(1, TimeUnit.MILLISECONDS) .noCursorTimeout(true) - .oplogReplay(true) .partial(true) .projection(bsonProjection) .skip(1) diff --git a/driver-legacy/src/test/unit/com/mongodb/client/model/DBCollectionFindOptionsSpecification.groovy b/driver-legacy/src/test/unit/com/mongodb/client/model/DBCollectionFindOptionsSpecification.groovy index 33e8e5af851..71127c6e9e3 100644 --- a/driver-legacy/src/test/unit/com/mongodb/client/model/DBCollectionFindOptionsSpecification.groovy +++ b/driver-legacy/src/test/unit/com/mongodb/client/model/DBCollectionFindOptionsSpecification.groovy @@ -32,7 +32,6 @@ class DBCollectionFindOptionsSpecification extends Specification { then: !options.isNoCursorTimeout() - !options.isOplogReplay() !options.isPartial() options.getBatchSize() == 0 options.getCollation() == null @@ -77,7 +76,6 @@ class DBCollectionFindOptionsSpecification extends Specification { .maxAwaitTime(1, TimeUnit.MILLISECONDS) .maxTime(1, TimeUnit.MILLISECONDS) .noCursorTimeout(true) - .oplogReplay(true) .partial(true) .projection(projection) .readConcern(readConcern) @@ -105,7 +103,6 @@ class DBCollectionFindOptionsSpecification extends Specification { options.getSkip() == 1 options.getSort() == sort options.isNoCursorTimeout() - options.isOplogReplay() options.isPartial() options.getComment() == comment options.getHint() == hint @@ -139,7 +136,6 @@ class DBCollectionFindOptionsSpecification extends Specification { .maxAwaitTime(1, TimeUnit.MILLISECONDS) .maxTime(1, TimeUnit.MILLISECONDS) .noCursorTimeout(true) - .oplogReplay(true) .partial(true) .projection(projection) .readConcern(readConcern) @@ -171,7 +167,6 @@ class DBCollectionFindOptionsSpecification extends Specification { options.getSkip() == 1 options.getSort() == sort options.isNoCursorTimeout() - options.isOplogReplay() options.isPartial() options.getComment() == comment options.getHint() == hint diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java index d7ec41a1bfb..8a485facaf5 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java @@ -126,16 +126,6 @@ public interface FindPublisher extends Publisher { */ FindPublisher noCursorTimeout(boolean noCursorTimeout); - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Deprecated - FindPublisher oplogReplay(boolean oplogReplay); - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java index f1b0f116f63..401c02dc583 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java @@ -110,13 +110,6 @@ public FindPublisher noCursorTimeout(final boolean noCursorTimeout) { return this; } - @Override - @Deprecated - public FindPublisher oplogReplay(final boolean oplogReplay) { - findOptions.oplogReplay(oplogReplay); - return this; - } - @Override public FindPublisher partial(final boolean partial) { findOptions.partial(partial); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java index ca218e50ada..0cc68b0042e 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java @@ -89,13 +89,6 @@ public FindIterable noCursorTimeout(final boolean noCursorTimeout) { return this; } - @Override - @Deprecated - public FindIterable oplogReplay(final boolean oplogReplay) { - wrapped.oplogReplay(oplogReplay); - return this; - } - @Override public FindIterable partial(final boolean partial) { wrapped.partial(partial); diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/FindPublisherImplTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/FindPublisherImplTest.java index 0b297c13a87..62a7596a681 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/FindPublisherImplTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/FindPublisherImplTest.java @@ -37,7 +37,6 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings("deprecation") public class FindPublisherImplTest extends TestHelper { private static final MongoNamespace NAMESPACE = new MongoNamespace("db", "coll"); @@ -73,7 +72,6 @@ void shouldBuildTheExpectedOperation() { .limit(100) .skip(10) .cursorType(CursorType.NonTailable) - .oplogReplay(false) .noCursorTimeout(false) .partial(false) .collation(COLLATION) diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala b/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala index b9114a91ab2..e66f70913b6 100644 --- a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala +++ b/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala @@ -69,11 +69,6 @@ case class SyncFindIterable[T](wrapped: FindObservable[T]) extends SyncMongoIter this } - override def oplogReplay(oplogReplay: Boolean): FindIterable[T] = { - wrapped.oplogReplay(oplogReplay) - this - } - override def partial(partial: Boolean): FindIterable[T] = { wrapped.partial(partial) this diff --git a/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala index 2d147a42211..575ca66e8c8 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala @@ -16,14 +16,14 @@ package org.mongodb.scala -import java.util.concurrent.TimeUnit -import com.mongodb.{ CursorType, ExplainVerbosity } import com.mongodb.reactivestreams.client.FindPublisher +import com.mongodb.{ CursorType, ExplainVerbosity } import org.mongodb.scala.bson.BsonValue import org.mongodb.scala.bson.DefaultHelper.DefaultsTo import org.mongodb.scala.bson.conversions.Bson import org.mongodb.scala.model.Collation +import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration import scala.reflect.ClassTag @@ -152,17 +152,6 @@ case class FindObservable[TResult](private val wrapped: FindPublisher[TResult]) this } - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - */ - def oplogReplay(oplogReplay: Boolean): FindObservable[TResult] = { - wrapped.oplogReplay(oplogReplay) - this - } - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala index d06053b96a2..1af77eeb6e7 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala @@ -16,14 +16,14 @@ package org.mongodb.scala -import java.util.concurrent.TimeUnit -import com.mongodb.{ CursorType, ExplainVerbosity } import com.mongodb.reactivestreams.client.FindPublisher +import com.mongodb.{ CursorType, ExplainVerbosity } import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.mongodb.scala.model.Collation import org.reactivestreams.Publisher import org.scalatestplus.mockito.MockitoSugar +import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration class FindObservableSpec extends BaseSpec with MockitoSugar { @@ -67,7 +67,6 @@ class FindObservableSpec extends BaseSpec with MockitoSugar { observable.maxAwaitTime(maxDuration) observable.maxTime(duration) observable.noCursorTimeout(true) - observable.oplogReplay(true) observable.partial(true) observable.projection(projection) observable.skip(1) @@ -86,7 +85,6 @@ class FindObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).maxAwaitTime(maxDuration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).noCursorTimeout(true) - verify(wrapper).oplogReplay(true) verify(wrapper).partial(true) verify(wrapper).projection(projection) verify(wrapper).skip(1) diff --git a/driver-sync/src/main/com/mongodb/client/FindIterable.java b/driver-sync/src/main/com/mongodb/client/FindIterable.java index 3ea23c178c1..4cd3c7b7f43 100644 --- a/driver-sync/src/main/com/mongodb/client/FindIterable.java +++ b/driver-sync/src/main/com/mongodb/client/FindIterable.java @@ -119,16 +119,6 @@ public interface FindIterable extends MongoIterable { */ FindIterable noCursorTimeout(boolean noCursorTimeout); - /** - * Users should not set this under normal circumstances. - * - * @param oplogReplay if oplog replay is enabled - * @return this - * @deprecated oplogReplay has been deprecated in MongoDB 4.4. - */ - @Deprecated - FindIterable oplogReplay(boolean oplogReplay); - /** * Get partial results from a sharded cluster if one or more shards are unreachable (instead of throwing an error). * diff --git a/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java index b7b405d5a5a..de0fdc94f3e 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java @@ -128,13 +128,6 @@ public FindIterable noCursorTimeout(final boolean noCursorTimeout) { return this; } - @Override - @Deprecated - public FindIterable oplogReplay(final boolean oplogReplay) { - findOptions.oplogReplay(oplogReplay); - return this; - } - @Override public FindIterable partial(final boolean partial) { findOptions.partial(partial); diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/FindIterableSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/FindIterableSpecification.groovy index ebfe762cf90..98848a84dfa 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/FindIterableSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/FindIterableSpecification.groovy @@ -68,7 +68,6 @@ class FindIterableSpecification extends Specification { .limit(100) .skip(10) .cursorType(CursorType.NonTailable) - .oplogReplay(false) .noCursorTimeout(false) .partial(false) .collation(null) @@ -118,7 +117,6 @@ class FindIterableSpecification extends Specification { .limit(99) .skip(9) .cursorType(CursorType.Tailable) - .oplogReplay(true) .noCursorTimeout(true) .partial(true) .collation(collation) @@ -144,7 +142,6 @@ class FindIterableSpecification extends Specification { .limit(99) .skip(9) .cursorType(CursorType.Tailable) - .oplogReplay(true) .noCursorTimeout(true) .partial(true) .collation(collation) From 0b26c04eeddadc3c27987fccdf6c4240cda03c62 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 9 Nov 2023 15:44:42 -0500 Subject: [PATCH 19/28] Suppress deprecation warning --- .../src/main/com/mongodb/internal/operation/SyncOperations.java | 1 + 1 file changed, 1 insertion(+) diff --git a/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java b/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java index 05577f72be0..6eabd3f5fe3 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/SyncOperations.java @@ -132,6 +132,7 @@ public ReadOperation aggregateToCollection(final List pipe comment, variables, aggregationLevel); } + @SuppressWarnings("deprecation") public WriteOperation mapReduceToCollection(final String databaseName, final String collectionName, final String mapFunction, final String reduceFunction, final String finalizeFunction, final Bson filter, final int limit, From eed78158aed73afa00d26f26add8715f2b43a39f Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 9 Nov 2023 15:46:56 -0500 Subject: [PATCH 20/28] Re-enable deprecation warnings JAVA-5142 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index c92919238b4..8d7fa8e3b36 100644 --- a/build.gradle +++ b/build.gradle @@ -186,7 +186,7 @@ configure(javaMainProjects) { options.encoding = 'ISO-8859-1' options.fork = true options.debug = true - options.compilerArgs = ['-Xlint:all', '-Xlint:-deprecation'] + options.compilerArgs = ['-Xlint:all'] } } From ac603f3939470e3c6f1fd5b317211097d550975e Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Tue, 14 Nov 2023 14:27:18 -0500 Subject: [PATCH 21/28] Make NettyStreamFactoryFactory implement AutoCloseable (#1244) Since StreamFactoryFactory is now internal, just made that interface extend AutoCloseable in order to simplify MongoClients code JAVA-5158 --- .../mongodb/connection/NettyTransportSettings.java | 3 +-- ...AsynchronousSocketChannelStreamFactoryFactory.java | 4 ++++ .../internal/connection/StreamFactoryFactory.java | 5 ++++- .../connection/TlsChannelStreamFactoryFactory.java | 2 +- .../connection/netty/NettyStreamFactoryFactory.java | 11 +++++++++++ .../mongodb/reactivestreams/client/MongoClients.java | 3 +-- 6 files changed, 22 insertions(+), 6 deletions(-) diff --git a/driver-core/src/main/com/mongodb/connection/NettyTransportSettings.java b/driver-core/src/main/com/mongodb/connection/NettyTransportSettings.java index d1e5beb940d..ef9d68b32b4 100644 --- a/driver-core/src/main/com/mongodb/connection/NettyTransportSettings.java +++ b/driver-core/src/main/com/mongodb/connection/NettyTransportSettings.java @@ -87,8 +87,7 @@ public Builder socketChannelClass(final Class socketCha /** * Sets the event loop group. * - *

It is highly recommended to supply your own event loop group and manage its shutdown. Otherwise, the event - * loop group created by default will not be shutdown properly.

+ *

The application is responsible for shutting down the provided {@code eventLoopGroup}

* * @param eventLoopGroup the event loop group that all channels created by this factory will be a part of * @return this diff --git a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java index 8810272b90d..db9166eda64 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AsynchronousSocketChannelStreamFactoryFactory.java @@ -36,4 +36,8 @@ public AsynchronousSocketChannelStreamFactoryFactory(final InetAddressResolver i public StreamFactory create(final SocketSettings socketSettings, final SslSettings sslSettings) { return new AsynchronousSocketChannelStreamFactory(inetAddressResolver, socketSettings, sslSettings); } + + @Override + public void close() { + } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java index 96df4c29348..6cbe620fd43 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/StreamFactoryFactory.java @@ -22,7 +22,7 @@ /** * A factory of {@code StreamFactory} instances. */ -public interface StreamFactoryFactory { +public interface StreamFactoryFactory extends AutoCloseable { /** * Create a {@code StreamFactory} with the given settings. @@ -32,4 +32,7 @@ public interface StreamFactoryFactory { * @return a stream factory that will apply the given settins */ StreamFactory create(SocketSettings socketSettings, SslSettings sslSettings); + + @Override + void close(); } diff --git a/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java index bce3c353137..8a822d03f6a 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/TlsChannelStreamFactoryFactory.java @@ -59,7 +59,7 @@ /** * A {@code StreamFactoryFactory} that supports TLS/SSL. The implementation supports asynchronous usage. */ -public class TlsChannelStreamFactoryFactory implements StreamFactoryFactory, Closeable { +public class TlsChannelStreamFactoryFactory implements StreamFactoryFactory { private static final Logger LOGGER = Loggers.getLogger("connection.tls"); diff --git a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java index d1f6e52f356..7fe54defaa2 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/netty/NettyStreamFactoryFactory.java @@ -47,6 +47,7 @@ public final class NettyStreamFactoryFactory implements StreamFactoryFactory { private final EventLoopGroup eventLoopGroup; + private final boolean ownsEventLoopGroup; private final Class socketChannelClass; private final ByteBufAllocator allocator; @Nullable @@ -202,6 +203,15 @@ public StreamFactory create(final SocketSettings socketSettings, final SslSettin sslContext); } + @Override + public void close() { + if (ownsEventLoopGroup) { + // ignore the returned Future. This is in line with MongoClient behavior to not block waiting for connections to be returned + // to the pool + eventLoopGroup.shutdownGracefully(); + } + } + @Override public boolean equals(final Object o) { if (this == o) { @@ -225,6 +235,7 @@ private NettyStreamFactoryFactory(final Builder builder) { allocator = builder.allocator == null ? ByteBufAllocator.DEFAULT : builder.allocator; socketChannelClass = builder.socketChannelClass == null ? NioSocketChannel.class : builder.socketChannelClass; eventLoopGroup = builder.eventLoopGroup == null ? new NioEventLoopGroup() : builder.eventLoopGroup; + ownsEventLoopGroup = builder.eventLoopGroup == null; sslContext = builder.sslContext; inetAddressResolver = builder.inetAddressResolver; } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java index d4ad39bdec9..28bcc068805 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoClients.java @@ -127,10 +127,9 @@ public static MongoClient create(final MongoClientSettings settings, @Nullable f } StreamFactory streamFactory = getStreamFactory(streamFactoryFactory, settings, false); StreamFactory heartbeatStreamFactory = getStreamFactory(streamFactoryFactory, settings, true); - AutoCloseable externalResourceCloser = streamFactoryFactory instanceof AutoCloseable ? (AutoCloseable) streamFactoryFactory : null; MongoDriverInformation wrappedMongoDriverInformation = wrapMongoDriverInformation(mongoDriverInformation); Cluster cluster = createCluster(settings, wrappedMongoDriverInformation, streamFactory, heartbeatStreamFactory); - return new MongoClientImpl(settings, wrappedMongoDriverInformation, cluster, externalResourceCloser); + return new MongoClientImpl(settings, wrappedMongoDriverInformation, cluster, streamFactoryFactory); } /** From bea8ecfedd9039ac689c3ae7c8c9b42a7a1045f8 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Tue, 14 Nov 2023 15:42:13 -0500 Subject: [PATCH 22/28] Remove deprecated record annotations (#1249) JAVA-5141 --- .../org/bson/codecs/record/RecordCodec.java | 44 +++++++++---------- .../codecs/record/annotations/BsonId.java | 36 --------------- .../record/annotations/BsonProperty.java | 42 ------------------ .../annotations/BsonRepresentation.java | 44 ------------------- .../record/annotations/package-info.java | 20 --------- .../bson/codecs/record/RecordCodecTest.java | 37 ++-------------- .../TestRecordWithDeprecatedAnnotations.java | 36 --------------- 7 files changed, 24 insertions(+), 235 deletions(-) delete mode 100644 bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonId.java delete mode 100644 bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonProperty.java delete mode 100644 bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonRepresentation.java delete mode 100644 bson-record-codec/src/main/org/bson/codecs/record/annotations/package-info.java delete mode 100644 bson-record-codec/src/test/unit/org/bson/codecs/record/samples/TestRecordWithDeprecatedAnnotations.java diff --git a/bson-record-codec/src/main/org/bson/codecs/record/RecordCodec.java b/bson-record-codec/src/main/org/bson/codecs/record/RecordCodec.java index 5bce0560233..01b59f35265 100644 --- a/bson-record-codec/src/main/org/bson/codecs/record/RecordCodec.java +++ b/bson-record-codec/src/main/org/bson/codecs/record/RecordCodec.java @@ -26,9 +26,13 @@ import org.bson.codecs.RepresentationConfigurable; import org.bson.codecs.configuration.CodecConfigurationException; import org.bson.codecs.configuration.CodecRegistry; -import org.bson.codecs.record.annotations.BsonId; -import org.bson.codecs.record.annotations.BsonProperty; -import org.bson.codecs.record.annotations.BsonRepresentation; +import org.bson.codecs.pojo.annotations.BsonCreator; +import org.bson.codecs.pojo.annotations.BsonDiscriminator; +import org.bson.codecs.pojo.annotations.BsonExtraElements; +import org.bson.codecs.pojo.annotations.BsonId; +import org.bson.codecs.pojo.annotations.BsonIgnore; +import org.bson.codecs.pojo.annotations.BsonProperty; +import org.bson.codecs.pojo.annotations.BsonRepresentation; import org.bson.diagnostics.Logger; import org.bson.diagnostics.Loggers; @@ -87,7 +91,6 @@ Object getValue(final Record record) throws InvocationTargetException, IllegalAc return component.getAccessor().invoke(record); } - @SuppressWarnings("deprecation") private static Codec computeCodec(final List typeParameters, final RecordComponent component, final CodecRegistry codecRegistry) { var rawType = toWrapper(resolveComponentType(typeParameters, component)); @@ -97,11 +100,9 @@ private static Codec computeCodec(final List typeParameters, final Reco : codecRegistry.get(rawType); BsonType bsonRepresentationType = null; - if (component.isAnnotationPresent(BsonRepresentation.class)) { - bsonRepresentationType = component.getAnnotation(BsonRepresentation.class).value(); - } else if (isAnnotationPresentOnField(component, org.bson.codecs.pojo.annotations.BsonRepresentation.class)) { + if (isAnnotationPresentOnField(component, BsonRepresentation.class)) { bsonRepresentationType = getAnnotationOnField(component, - org.bson.codecs.pojo.annotations.BsonRepresentation.class).value(); + BsonRepresentation.class).value(); } if (bsonRepresentationType != null) { if (codec instanceof RepresentationConfigurable representationConfigurable) { @@ -145,16 +146,11 @@ private static int getIndexOfTypeParameter(final String typeParameterName, final recordClass.getName(), typeParameterName)); } - @SuppressWarnings("deprecation") private static String computeFieldName(final RecordComponent component) { - if (component.isAnnotationPresent(BsonId.class)) { + if (isAnnotationPresentOnField(component, BsonId.class)) { return "_id"; - } else if (isAnnotationPresentOnField(component, org.bson.codecs.pojo.annotations.BsonId.class)) { - return "_id"; - } else if (component.isAnnotationPresent(BsonProperty.class)) { - return component.getAnnotation(BsonProperty.class).value(); - } else if (isAnnotationPresentOnField(component, org.bson.codecs.pojo.annotations.BsonProperty.class)) { - return getAnnotationOnField(component, org.bson.codecs.pojo.annotations.BsonProperty.class).value(); + } else if (isAnnotationPresentOnField(component, BsonProperty.class)) { + return getAnnotationOnField(component, BsonProperty.class).value(); } return component.getName(); } @@ -182,14 +178,14 @@ private static T getAnnotationOnField(final RecordCompone } private static void validateAnnotations(final RecordComponent component, final int index) { - validateAnnotationNotPresentOnType(component.getDeclaringRecord(), org.bson.codecs.pojo.annotations.BsonDiscriminator.class); - validateAnnotationNotPresentOnConstructor(component.getDeclaringRecord(), org.bson.codecs.pojo.annotations.BsonCreator.class); - validateAnnotationNotPresentOnMethod(component.getDeclaringRecord(), org.bson.codecs.pojo.annotations.BsonCreator.class); - validateAnnotationNotPresentOnFieldOrAccessor(component, org.bson.codecs.pojo.annotations.BsonIgnore.class); - validateAnnotationNotPresentOnFieldOrAccessor(component, org.bson.codecs.pojo.annotations.BsonExtraElements.class); - validateAnnotationOnlyOnField(component, index, org.bson.codecs.pojo.annotations.BsonId.class); - validateAnnotationOnlyOnField(component, index, org.bson.codecs.pojo.annotations.BsonProperty.class); - validateAnnotationOnlyOnField(component, index, org.bson.codecs.pojo.annotations.BsonRepresentation.class); + validateAnnotationNotPresentOnType(component.getDeclaringRecord(), BsonDiscriminator.class); + validateAnnotationNotPresentOnConstructor(component.getDeclaringRecord(), BsonCreator.class); + validateAnnotationNotPresentOnMethod(component.getDeclaringRecord(), BsonCreator.class); + validateAnnotationNotPresentOnFieldOrAccessor(component, BsonIgnore.class); + validateAnnotationNotPresentOnFieldOrAccessor(component, BsonExtraElements.class); + validateAnnotationOnlyOnField(component, index, BsonId.class); + validateAnnotationOnlyOnField(component, index, BsonProperty.class); + validateAnnotationOnlyOnField(component, index, BsonRepresentation.class); } private static void validateAnnotationNotPresentOnType(final Class clazz, diff --git a/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonId.java b/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonId.java deleted file mode 100644 index 24a409dc3a5..00000000000 --- a/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonId.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs.record.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation that configures the record component as the _id field of the document - * - * @since 4.6 - * @deprecated Prefer {@link org.bson.codecs.pojo.annotations.BsonId} - */ -@Deprecated -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.RECORD_COMPONENT}) -public @interface BsonId { -} diff --git a/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonProperty.java b/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonProperty.java deleted file mode 100644 index 428584d6539..00000000000 --- a/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonProperty.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs.record.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation that configures a record component. - * - * @since 4.6 - * @deprecated Prefer {@link org.bson.codecs.pojo.annotations.BsonProperty} - */ -@Deprecated -@Documented -@Target({ElementType.RECORD_COMPONENT}) -@Retention(RetentionPolicy.RUNTIME) -public @interface BsonProperty { - /** - * The field name of the record component. - * - * @return the field name to use for the record component - */ - String value() default ""; -} diff --git a/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonRepresentation.java b/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonRepresentation.java deleted file mode 100644 index 5838734fba5..00000000000 --- a/bson-record-codec/src/main/org/bson/codecs/record/annotations/BsonRepresentation.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs.record.annotations; - -import org.bson.BsonType; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation that specifies what type the record component is stored as in the database. - * - * @since 4.6 - * @deprecated Prefer {@link org.bson.codecs.pojo.annotations.BsonRepresentation} - */ -@Deprecated -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.RECORD_COMPONENT}) -public @interface BsonRepresentation { - /** - * The type that the property is stored as in the database. - * - * @return the type that the property should be stored as. - */ - BsonType value(); -} diff --git a/bson-record-codec/src/main/org/bson/codecs/record/annotations/package-info.java b/bson-record-codec/src/main/org/bson/codecs/record/annotations/package-info.java deleted file mode 100644 index 60bab08a860..00000000000 --- a/bson-record-codec/src/main/org/bson/codecs/record/annotations/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * This package contains annotations for encoding and decoding Java records. - */ -package org.bson.codecs.record.annotations; diff --git a/bson-record-codec/src/test/unit/org/bson/codecs/record/RecordCodecTest.java b/bson-record-codec/src/test/unit/org/bson/codecs/record/RecordCodecTest.java index 636554443fd..c7adef45bc8 100644 --- a/bson-record-codec/src/test/unit/org/bson/codecs/record/RecordCodecTest.java +++ b/bson-record-codec/src/test/unit/org/bson/codecs/record/RecordCodecTest.java @@ -32,7 +32,6 @@ import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.record.samples.TestRecordEmbedded; import org.bson.codecs.record.samples.TestRecordParameterized; -import org.bson.codecs.record.samples.TestRecordWithDeprecatedAnnotations; import org.bson.codecs.record.samples.TestRecordWithIllegalBsonCreatorOnConstructor; import org.bson.codecs.record.samples.TestRecordWithIllegalBsonCreatorOnMethod; import org.bson.codecs.record.samples.TestRecordWithIllegalBsonDiscriminatorOnRecord; @@ -69,34 +68,6 @@ public class RecordCodecTest { - @Test - public void testRecordWithDeprecatedAnnotations() { - var codec = createRecordCodec(TestRecordWithDeprecatedAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY); - var identifier = new ObjectId(); - var testRecord = new TestRecordWithDeprecatedAnnotations("Lucas", 14, List.of("soccer", "basketball"), identifier.toHexString()); - - var document = new BsonDocument(); - var writer = new BsonDocumentWriter(document); - - // when - codec.encode(writer, testRecord, EncoderContext.builder().build()); - - // then - assertEquals( - new BsonDocument("_id", new BsonObjectId(identifier)) - .append("name", new BsonString("Lucas")) - .append("hobbies", new BsonArray(List.of(new BsonString("soccer"), new BsonString("basketball")))) - .append("a", new BsonInt32(14)), - document); - assertEquals("_id", document.getFirstKey()); - - // when - var decoded = codec.decode(new BsonDocumentReader(document), DecoderContext.builder().build()); - - // then - assertEquals(testRecord, decoded); - } - @Test public void testRecordWithPojoAnnotations() { var codec = createRecordCodec(TestRecordWithPojoAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY); @@ -305,9 +276,9 @@ public void testRecordWithNestedParameterizedRecordWithDifferentlyOrderedTypePar @Test public void testRecordWithNulls() { - var codec = createRecordCodec(TestRecordWithDeprecatedAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY); + var codec = createRecordCodec(TestRecordWithPojoAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY); var identifier = new ObjectId(); - var testRecord = new TestRecordWithDeprecatedAnnotations(null, 14, null, identifier.toHexString()); + var testRecord = new TestRecordWithPojoAnnotations(null, 14, null, identifier.toHexString()); var document = new BsonDocument(); var writer = new BsonDocumentWriter(document); @@ -359,9 +330,9 @@ public void testExceptionsWithStoredNullsOnPrimitiveField() { @Test public void testRecordWithExtraData() { - var codec = createRecordCodec(TestRecordWithDeprecatedAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY); + var codec = createRecordCodec(TestRecordWithPojoAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY); var identifier = new ObjectId(); - var testRecord = new TestRecordWithDeprecatedAnnotations("Felix", 13, List.of("rugby", "badminton"), identifier.toHexString()); + var testRecord = new TestRecordWithPojoAnnotations("Felix", 13, List.of("rugby", "badminton"), identifier.toHexString()); var document = new BsonDocument("_id", new BsonObjectId(identifier)) .append("nationality", new BsonString("British")) diff --git a/bson-record-codec/src/test/unit/org/bson/codecs/record/samples/TestRecordWithDeprecatedAnnotations.java b/bson-record-codec/src/test/unit/org/bson/codecs/record/samples/TestRecordWithDeprecatedAnnotations.java deleted file mode 100644 index 851ef55efc5..00000000000 --- a/bson-record-codec/src/test/unit/org/bson/codecs/record/samples/TestRecordWithDeprecatedAnnotations.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs.record.samples; - -import org.bson.BsonType; -import org.bson.codecs.record.annotations.BsonId; -import org.bson.codecs.record.annotations.BsonProperty; -import org.bson.codecs.record.annotations.BsonRepresentation; - -import java.util.List; - -@SuppressWarnings("deprecation") -public record TestRecordWithDeprecatedAnnotations(String name, - @BsonProperty("a") int age, - List hobbies, - @BsonRepresentation(BsonType.OBJECT_ID) @BsonId String identifier) { - - // To test that the canonical constructor is always used for decoding - public TestRecordWithDeprecatedAnnotations(final String identifier) { - this("Adrian", 17, List.of("soccer", "music"), identifier); - } -} From 8c82359535c93ddf6074066d826349fd66d2780d Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Wed, 15 Nov 2023 09:16:03 -0500 Subject: [PATCH 23/28] Remove deprecated Parameterizable interface (#1248) JAVA-5143 --- .../main/org/bson/codecs/Parameterizable.java | 49 ---------- .../codecs/configuration/CodecRegistry.java | 1 - ...idableUuidRepresentationCodecProvider.java | 3 +- .../bson/internal/ProvidersCodecRegistry.java | 19 +--- ...ProvidersCodecRegistrySpecification.groovy | 93 ------------------- .../mongodb/Jep395RecordCodecProvider.java | 3 +- .../main/com/mongodb/KotlinCodecProvider.java | 6 +- 7 files changed, 6 insertions(+), 168 deletions(-) delete mode 100644 bson/src/main/org/bson/codecs/Parameterizable.java diff --git a/bson/src/main/org/bson/codecs/Parameterizable.java b/bson/src/main/org/bson/codecs/Parameterizable.java deleted file mode 100644 index 479ab205524..00000000000 --- a/bson/src/main/org/bson/codecs/Parameterizable.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs; - -import org.bson.codecs.configuration.CodecProvider; -import org.bson.codecs.configuration.CodecRegistry; - -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.List; - -/** - * An interface indicating that a Codec is for a type that can be parameterized by generic types. - * - * @since 4.8 - * @deprecated Since 4.10. Instead of implementing {@link Parameterizable} for a custom {@link Codec}, - * users should implement {@link CodecProvider#get(Class, List, CodecRegistry)} for a custom {@link CodecProvider}. - */ -@Deprecated -// After releasing this interface, we realized that our implementations of `Parameterizable.parameterize` were doing what -// `CodecProvider.get` is supposed to be doing. As a result, we introduced a new default method to `CodecProvider`, -// and deprecated `Parameterizable`. -public interface Parameterizable { - /** - * Recursively parameterize the codec with the given registry and generic type arguments. - * - * @param codecRegistry the code registry to use to resolve codecs for the generic type arguments - * @param types the types that are parameterizing the containing type. The size of the list should be equal to the number of type - * parameters of the class whose codec is being parameterized, e.g. for a {@link Collection} the size of the list - * would be one since {@code Collection} has a single type parameter. Additionally, the size will never be 0 - * since there is no purpose in parameterizing a codec for a type that has no type parameters. - * @return the Codec parameterized with the given types - */ - Codec parameterize(CodecRegistry codecRegistry, List types); -} diff --git a/bson/src/main/org/bson/codecs/configuration/CodecRegistry.java b/bson/src/main/org/bson/codecs/configuration/CodecRegistry.java index 31479d31820..f77ad80068c 100644 --- a/bson/src/main/org/bson/codecs/configuration/CodecRegistry.java +++ b/bson/src/main/org/bson/codecs/configuration/CodecRegistry.java @@ -64,7 +64,6 @@ public interface CodecRegistry extends CodecProvider { * @throws CodecConfigurationException if no codec can be found for the given class and type arguments. * @throws AssertionError by default, if the implementation does not override this method, or if no codec can be found * for the given class and type arguments. - * @see org.bson.codecs.Parameterizable * @since 4.8 */ default Codec get(Class clazz, List typeArguments) { diff --git a/bson/src/main/org/bson/codecs/configuration/OverridableUuidRepresentationCodecProvider.java b/bson/src/main/org/bson/codecs/configuration/OverridableUuidRepresentationCodecProvider.java index e1c6223cfb3..f46964fedd3 100644 --- a/bson/src/main/org/bson/codecs/configuration/OverridableUuidRepresentationCodecProvider.java +++ b/bson/src/main/org/bson/codecs/configuration/OverridableUuidRepresentationCodecProvider.java @@ -25,7 +25,6 @@ import java.util.List; import static org.bson.assertions.Assertions.notNull; -import static org.bson.internal.ProvidersCodecRegistry.getFromCodecProvider; final class OverridableUuidRepresentationCodecProvider implements CodecProvider { @@ -44,7 +43,7 @@ public Codec get(final Class clazz, final CodecRegistry registry) { @Override public Codec get(final Class clazz, final List typeArguments, final CodecRegistry registry) { - Codec codec = getFromCodecProvider(wrapped, clazz, typeArguments, registry); + Codec codec = wrapped.get(clazz, typeArguments, registry); if (codec instanceof OverridableUuidRepresentationCodec) { @SuppressWarnings("unchecked") Codec codecWithUuidRepresentation = ((OverridableUuidRepresentationCodec) codec).withUuidRepresentation(uuidRepresentation); diff --git a/bson/src/main/org/bson/internal/ProvidersCodecRegistry.java b/bson/src/main/org/bson/internal/ProvidersCodecRegistry.java index 3decf4b1d1d..ddb3c44355d 100644 --- a/bson/src/main/org/bson/internal/ProvidersCodecRegistry.java +++ b/bson/src/main/org/bson/internal/ProvidersCodecRegistry.java @@ -22,7 +22,6 @@ import org.bson.codecs.configuration.CodecRegistry; import org.bson.internal.CodecCache.CodecCacheKey; -import javax.annotation.Nullable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; @@ -67,7 +66,7 @@ public Codec get(final Class clazz, final CodecRegistry registry) { @Override public Codec get(final Class clazz, final List typeArguments, final CodecRegistry registry) { for (CodecProvider provider : codecProviders) { - Codec codec = getFromCodecProvider(provider, clazz, typeArguments, registry); + Codec codec = provider.get(clazz, typeArguments, registry); if (codec != null) { return codec; } @@ -79,7 +78,7 @@ public Codec get(final ChildCodecRegistry context) { CodecCacheKey codecCacheKey = new CodecCacheKey(context.getCodecClass(), context.getTypes().orElse(null)); return codecCache.get(codecCacheKey).orElseGet(() -> { for (CodecProvider provider : codecProviders) { - Codec codec = getFromCodecProvider(provider, context.getCodecClass(), context.getTypes().orElse(emptyList()), context); + Codec codec = provider.get(context.getCodecClass(), context.getTypes().orElse(emptyList()), context); if (codec != null) { return codecCache.putIfAbsent(codecCacheKey, codec); } @@ -88,20 +87,6 @@ public Codec get(final ChildCodecRegistry context) { }); } - @Nullable - @SuppressWarnings("deprecation") - public static Codec getFromCodecProvider(final CodecProvider provider, - final Class clazz, final List typeArguments, final CodecRegistry registry) { - Codec codec = provider.get(clazz, typeArguments, registry); - // `Parameterizable` is deprecated, but we still have to support it until it is removed - if (codec instanceof org.bson.codecs.Parameterizable && !typeArguments.isEmpty()) { - @SuppressWarnings("unchecked") - Codec parameterizedCodec = (Codec) ((org.bson.codecs.Parameterizable) codec).parameterize(registry, typeArguments); - codec = parameterizedCodec; - } - return codec; - } - @Override public boolean equals(final Object o) { if (this == o) { diff --git a/bson/src/test/unit/org/bson/internal/ProvidersCodecRegistrySpecification.groovy b/bson/src/test/unit/org/bson/internal/ProvidersCodecRegistrySpecification.groovy index c007a23718b..40897b3a5aa 100644 --- a/bson/src/test/unit/org/bson/internal/ProvidersCodecRegistrySpecification.groovy +++ b/bson/src/test/unit/org/bson/internal/ProvidersCodecRegistrySpecification.groovy @@ -25,10 +25,7 @@ import org.bson.ByteBufNIO import org.bson.codecs.Codec import org.bson.codecs.DecoderContext import org.bson.codecs.EncoderContext -import org.bson.codecs.IntegerCodec import org.bson.codecs.MinKeyCodec -import org.bson.codecs.Parameterizable -import org.bson.codecs.ValueCodecProvider import org.bson.codecs.configuration.CodecConfigurationException import org.bson.codecs.configuration.CodecProvider import org.bson.codecs.configuration.CodecRegistry @@ -38,12 +35,9 @@ import org.bson.types.MaxKey import org.bson.types.MinKey import spock.lang.Specification -import java.lang.reflect.Type import java.nio.ByteBuffer import static java.util.Arrays.asList -import static org.bson.codecs.ContainerCodecHelper.getCodec -import static org.bson.codecs.configuration.CodecRegistries.fromCodecs class ProvidersCodecRegistrySpecification extends Specification { @@ -169,93 +163,6 @@ class ProvidersCodecRegistrySpecification extends Specification { expect: ((SimpleCodec) provider.get(Simple, registry)).registry.is(registry) } - - def 'should parameterize codec'() { - given: - def registry = new ProvidersCodecRegistry([fromCodecs(new CollectionCodec()), new ValueCodecProvider()]) - - when: - def codec = registry.get(Collection, [Integer]) - - then: - codec instanceof ParameterizedCollectionCodec - (codec as ParameterizedCollectionCodec).getCodec() instanceof IntegerCodec - - when: - def secondCodec = registry.get(Collection, [Integer]) - - then: - codec == secondCodec - } - - def 'should parameterize codec with cycles'() { - given: - def registry = new ProvidersCodecRegistry([fromCodecs(new CollectionCodec()), new ValueCodecProvider()]) - - when: - def codec = registry.get(Collection, [Holder.getField('c').getGenericType()]) - - then: - codec instanceof ParameterizedCollectionCodec - (codec as ParameterizedCollectionCodec).getCodec() instanceof LazyCodec - - when: - def secondCodec = registry.get(Collection, [Holder.getField('c').getGenericType()]) - - then: - codec == secondCodec - } -} - -class CollectionCodec implements Codec>, Parameterizable { - - @Override - Collection decode(BsonReader reader, DecoderContext decoderContext) { - throw new UnsupportedOperationException() - } - - @Override - void encode(BsonWriter writer, Collection value, EncoderContext encoderContext) { - throw new UnsupportedOperationException() - } - - @Override - Class> getEncoderClass() { - Collection - } - - @Override - Codec parameterize(CodecRegistry codecRegistry, List types) { - new ParameterizedCollectionCodec(getCodec(codecRegistry, types.get(0))) - } -} - -class ParameterizedCollectionCodec implements Codec> { - - private final Codec codec - - ParameterizedCollectionCodec(Codec codec) { - this.codec = codec - } - - Codec getCodec() { - codec - } - - @Override - Collection decode(BsonReader reader, DecoderContext decoderContext) { - throw new UnsupportedOperationException() - } - - @Override - void encode(BsonWriter writer, Collection value, EncoderContext encoderContext) { - throw new UnsupportedOperationException() - } - - @Override - Class> getEncoderClass() { - Collection - } } class SingleCodecProvider implements CodecProvider { diff --git a/driver-core/src/main/com/mongodb/Jep395RecordCodecProvider.java b/driver-core/src/main/com/mongodb/Jep395RecordCodecProvider.java index 69d0ab12233..b53d8595b6f 100644 --- a/driver-core/src/main/com/mongodb/Jep395RecordCodecProvider.java +++ b/driver-core/src/main/com/mongodb/Jep395RecordCodecProvider.java @@ -27,7 +27,6 @@ import java.util.List; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; -import static org.bson.internal.ProvidersCodecRegistry.getFromCodecProvider; /** @@ -66,7 +65,7 @@ public Codec get(final Class clazz, final CodecRegistry registry) { @Override @Nullable public Codec get(final Class clazz, final List typeArguments, final CodecRegistry registry) { - return RECORD_CODEC_PROVIDER != null ? getFromCodecProvider(RECORD_CODEC_PROVIDER, clazz, typeArguments, registry) : null; + return RECORD_CODEC_PROVIDER != null ? RECORD_CODEC_PROVIDER.get(clazz, typeArguments, registry) : null; } /** diff --git a/driver-core/src/main/com/mongodb/KotlinCodecProvider.java b/driver-core/src/main/com/mongodb/KotlinCodecProvider.java index 74f88ed0956..5a1a2f84645 100644 --- a/driver-core/src/main/com/mongodb/KotlinCodecProvider.java +++ b/driver-core/src/main/com/mongodb/KotlinCodecProvider.java @@ -26,8 +26,6 @@ import java.util.Collections; import java.util.List; -import static org.bson.internal.ProvidersCodecRegistry.getFromCodecProvider; - /** * A CodecProvider for Kotlin data classes. * Delegates to {@code org.bson.codecs.kotlinx.KotlinSerializerCodecProvider} @@ -76,11 +74,11 @@ public Codec get(final Class clazz, final CodecRegistry registry) { public Codec get(final Class clazz, final List typeArguments, final CodecRegistry registry) { Codec codec = null; if (KOTLIN_SERIALIZABLE_CODEC_PROVIDER != null) { - codec = getFromCodecProvider(KOTLIN_SERIALIZABLE_CODEC_PROVIDER, clazz, typeArguments, registry); + codec = KOTLIN_SERIALIZABLE_CODEC_PROVIDER.get(clazz, typeArguments, registry); } if (codec == null && DATA_CLASS_CODEC_PROVIDER != null) { - codec = getFromCodecProvider(DATA_CLASS_CODEC_PROVIDER, clazz, typeArguments, registry); + codec = DATA_CLASS_CODEC_PROVIDER.get(clazz, typeArguments, registry); } return codec; } From 3298efd0b64d06f819d256d2fc29c1c5d5edf3a9 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 26 Oct 2023 12:06:46 -0400 Subject: [PATCH 24/28] Remove deprecated connection pool-event related classes/methods * ConnectionPoolOpenedEvent * ConnectionAddedEvent * ConnectionRemovedEvent * ConnectionPoolListener#connectionPoolOpened * ConnectionPoolListener#connectionAdded * ConnectionPoolListener#connectionRemoved JAVA-5151 --- .../mongodb/event/ConnectionAddedEvent.java | 57 --------- .../mongodb/event/ConnectionPoolListener.java | 36 ------ .../event/ConnectionPoolOpenedEvent.java | 71 ----------- .../mongodb/event/ConnectionRemovedEvent.java | 111 ------------------ .../connection/DefaultConnectionPool.java | 26 +--- .../ConnectionPoolListenerMulticaster.java | 40 ------- .../AbstractConnectionPoolTest.java | 3 - .../DefaultConnectionPoolSpecification.groovy | 7 +- .../TestConnectionPoolListener.java | 22 ---- ...ctionsSurvivePrimaryStepDownProseTest.java | 21 ++-- ...ctionsSurvivePrimaryStepDownProseTest.java | 22 ++-- 11 files changed, 24 insertions(+), 392 deletions(-) delete mode 100644 driver-core/src/main/com/mongodb/event/ConnectionAddedEvent.java delete mode 100644 driver-core/src/main/com/mongodb/event/ConnectionPoolOpenedEvent.java delete mode 100644 driver-core/src/main/com/mongodb/event/ConnectionRemovedEvent.java diff --git a/driver-core/src/main/com/mongodb/event/ConnectionAddedEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionAddedEvent.java deleted file mode 100644 index 2c21f4050b7..00000000000 --- a/driver-core/src/main/com/mongodb/event/ConnectionAddedEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -import com.mongodb.connection.ConnectionId; - -import static com.mongodb.assertions.Assertions.notNull; - -/** - * An event for adding a new connection to the pool. - * - * @deprecated Prefer {@link ConnectionCreatedEvent} - * @since 3.5 - */ -@Deprecated -public final class ConnectionAddedEvent { - private final ConnectionId connectionId; - - /** - * Construct an instance - * - * @param connectionId the connectionId - */ - public ConnectionAddedEvent(final ConnectionId connectionId) { - this.connectionId = notNull("connectionId", connectionId); - } - - /** - * Gets the connection id - * - * @return the connection id - */ - public ConnectionId getConnectionId() { - return connectionId; - } - - @Override - public String toString() { - return "ConnectionAddedEvent{" - + "connectionId=" + connectionId - + '}'; - } -} diff --git a/driver-core/src/main/com/mongodb/event/ConnectionPoolListener.java b/driver-core/src/main/com/mongodb/event/ConnectionPoolListener.java index 5269df278c8..5cc2db467e7 100644 --- a/driver-core/src/main/com/mongodb/event/ConnectionPoolListener.java +++ b/driver-core/src/main/com/mongodb/event/ConnectionPoolListener.java @@ -24,18 +24,6 @@ * @since 3.5 */ public interface ConnectionPoolListener extends EventListener { - /** - * Invoked when a connection pool is opened. The default implementation does nothing. - * - * @param event the event - * @deprecated Prefer {@link #connectionPoolCreated} Implementations should NOT implement this method at all, instead relying on - * the default no-op implementation. If an application implements both this method and connectionPoolCreated, the application risks - * double-counting events. - */ - @Deprecated - default void connectionPoolOpened(ConnectionPoolOpenedEvent event) { - } - /** * Invoked when a connection pool is created. The default implementation does nothing. * @@ -105,18 +93,6 @@ default void connectionCheckOutFailed(ConnectionCheckOutFailedEvent event) { default void connectionCheckedIn(ConnectionCheckedInEvent event) { } - /** - * Invoked when a connection is added to a pool. The default implementation does nothing. - * - * @param event the event - * @deprecated Prefer {@link #connectionCreated} Implementations should NOT implement this method at all, instead relying on - * the default no-op implementation. If an application implements both this method and connectionCreated, the application risks - * double-counting events. - */ - @Deprecated - default void connectionAdded(ConnectionAddedEvent event) { - } - /** * Invoked when a connection is created. The default implementation does nothing. * @@ -135,18 +111,6 @@ default void connectionCreated(ConnectionCreatedEvent event) { default void connectionReady(ConnectionReadyEvent event) { } - /** - * Invoked when a connection is removed from a pool. The default implementation does nothing. - * - * @param event the event - * @deprecated Prefer {@link #connectionClosed} Implementations should NOT implement this method at all, instead relying on - * the default no-op implementation. If an application implements both this method and connectionClosed, the application risks - * double-counting events. - */ - @Deprecated - default void connectionRemoved(ConnectionRemovedEvent event) { - } - /** * Invoked when a connection is removed from a pool. The default implementation does nothing. * diff --git a/driver-core/src/main/com/mongodb/event/ConnectionPoolOpenedEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionPoolOpenedEvent.java deleted file mode 100644 index f03832caeb7..00000000000 --- a/driver-core/src/main/com/mongodb/event/ConnectionPoolOpenedEvent.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -import com.mongodb.connection.ConnectionPoolSettings; -import com.mongodb.connection.ServerId; - -import static com.mongodb.assertions.Assertions.notNull; - -/** - * An event signifying the opening of a connection pool. - * - * @since 3.5 - * @deprecated Prefer {@link ConnectionPoolCreatedEvent} - */ -@Deprecated -public final class ConnectionPoolOpenedEvent { - private final ServerId serverId; - private final ConnectionPoolSettings settings; - - /** - * Constructs a new instance of the event. - * - * @param serverId the server id - * @param settings the connection pool settings - */ - public ConnectionPoolOpenedEvent(final ServerId serverId, final ConnectionPoolSettings settings) { - this.serverId = notNull("serverId", serverId); - this.settings = notNull("settings", settings); - } - - /** - * Gets the server id - * - * @return the server id - */ - public ServerId getServerId() { - return serverId; - } - - /** - * Gets the connection pool settings. - * - * @return the connection pool settings. - */ - public ConnectionPoolSettings getSettings() { - return settings; - } - - @Override - public String toString() { - return "ConnectionPoolOpenedEvent{" - + "serverId=" + serverId - + " settings=" + settings - + '}'; - } -} diff --git a/driver-core/src/main/com/mongodb/event/ConnectionRemovedEvent.java b/driver-core/src/main/com/mongodb/event/ConnectionRemovedEvent.java deleted file mode 100644 index 6bd2fc290e2..00000000000 --- a/driver-core/src/main/com/mongodb/event/ConnectionRemovedEvent.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -import com.mongodb.connection.ConnectionId; -import org.bson.assertions.Assertions; - -/** - * An event for removing a connection from the pool. - * - * @since 3.5 - * @deprecated Prefer {@link ConnectionClosedEvent} - */ -@Deprecated -public final class ConnectionRemovedEvent { - - /** - * An enumeration of the reasons a connection could be closed - * @since 3.11 - */ - public enum Reason { - /** - * Reason unknown - */ - UNKNOWN, - - /** - * The pool became stale because the pool has been cleared - */ - STALE, - - /** - * The connection became stale by being idle for too long - */ - MAX_IDLE_TIME_EXCEEDED, - - /** - * The connection became stale by being open for too long - */ - MAX_LIFE_TIME_EXCEEDED, - - /** - * The connection experienced an error, making it no longer valid - */ - ERROR, - - /** - * The pool was closed, making the connection no longer valid - */ - POOL_CLOSED, - } - - private final ConnectionId connectionId; - private final Reason reason; - - /** - * Constructs an instance. - * - * @param connectionId the connection id - * @param reason the reason the connection was closed - * @since 3.11 - */ - public ConnectionRemovedEvent(final ConnectionId connectionId, final Reason reason) { - this.connectionId = Assertions.notNull("connectionId", connectionId); - this.reason = Assertions.notNull("reason", reason); - } - - - /** - * Gets the connection id - * - * @return the connection id - */ - public ConnectionId getConnectionId() { - return connectionId; - } - - /** - * Get the reason the connection was removed. - * - * @return the reason - * @since 3.11 - */ - public Reason getReason() { - return reason; - } - - @Override - public String toString() { - return "ConnectionRemovedEvent{" - + "connectionId=" + connectionId - + ", server=" + connectionId.getServerId().getAddress() - + ", clusterId=" + connectionId.getServerId().getClusterId() - + ", reason=" + reason - + '}'; - } -} diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index f235410eb7e..5127481f8fb 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -498,14 +498,13 @@ private void connectionPoolCreated(final ConnectionPoolListener connectionPoolLi logMessage("Connection pool created", clusterId, message, entries); } connectionPoolListener.connectionPoolCreated(new ConnectionPoolCreatedEvent(serverId, settings)); - connectionPoolListener.connectionPoolOpened(new com.mongodb.event.ConnectionPoolOpenedEvent(serverId, settings)); } /** * Send both current and deprecated events in order to preserve backwards compatibility. * Must not throw {@link Exception}s. * - * @return A {@link TimePoint} after executing {@link ConnectionPoolListener#connectionAdded(com.mongodb.event.ConnectionAddedEvent)}, + * @return A {@link TimePoint} after executing {@link ConnectionPoolListener#connectionCreated(ConnectionCreatedEvent)}, * {@link ConnectionPoolListener#connectionCreated(ConnectionCreatedEvent)}. * This order is required by * CMAP @@ -516,7 +515,6 @@ private TimePoint connectionCreated(final ConnectionPoolListener connectionPoolL "Connection created: address={}:{}, driver-generated ID={}", connectionId.getLocalValue()); - connectionPoolListener.connectionAdded(new com.mongodb.event.ConnectionAddedEvent(connectionId)); connectionPoolListener.connectionCreated(new ConnectionCreatedEvent(connectionId)); return TimePoint.now(); } @@ -541,7 +539,6 @@ private void connectionClosed(final ConnectionPoolListener connectionPoolListene "Connection closed: address={}:{}, driver-generated ID={}. Reason: {}.[ Error: {}]", entries); } - connectionPoolListener.connectionRemoved(new com.mongodb.event.ConnectionRemovedEvent(connectionId, getReasonForRemoved(reason))); connectionPoolListener.connectionClosed(new ConnectionClosedEvent(connectionId, reason)); } @@ -577,27 +574,6 @@ private TimePoint connectionCheckoutStarted(final OperationContext operationCont return TimePoint.now(); } - private com.mongodb.event.ConnectionRemovedEvent.Reason getReasonForRemoved(final ConnectionClosedEvent.Reason reason) { - com.mongodb.event.ConnectionRemovedEvent.Reason removedReason = com.mongodb.event.ConnectionRemovedEvent.Reason.UNKNOWN; - switch (reason) { - case STALE: - removedReason = com.mongodb.event.ConnectionRemovedEvent.Reason.STALE; - break; - case IDLE: - removedReason = com.mongodb.event.ConnectionRemovedEvent.Reason.MAX_IDLE_TIME_EXCEEDED; - break; - case ERROR: - removedReason = com.mongodb.event.ConnectionRemovedEvent.Reason.ERROR; - break; - case POOL_CLOSED: - removedReason = com.mongodb.event.ConnectionRemovedEvent.Reason.POOL_CLOSED; - break; - default: - break; - } - return removedReason; - } - /** * Must not throw {@link Exception}s. */ diff --git a/driver-core/src/main/com/mongodb/internal/event/ConnectionPoolListenerMulticaster.java b/driver-core/src/main/com/mongodb/internal/event/ConnectionPoolListenerMulticaster.java index 180261f2d8b..5aa5d9fa305 100644 --- a/driver-core/src/main/com/mongodb/internal/event/ConnectionPoolListenerMulticaster.java +++ b/driver-core/src/main/com/mongodb/internal/event/ConnectionPoolListenerMulticaster.java @@ -37,7 +37,6 @@ import static com.mongodb.assertions.Assertions.isTrue; import static java.lang.String.format; -@SuppressWarnings("deprecation") final class ConnectionPoolListenerMulticaster implements ConnectionPoolListener { private static final Logger LOGGER = Loggers.getLogger("protocol.event"); @@ -48,19 +47,6 @@ final class ConnectionPoolListenerMulticaster implements ConnectionPoolListener this.connectionPoolListeners = new ArrayList<>(connectionPoolListeners); } - @Override - public void connectionPoolOpened(final com.mongodb.event.ConnectionPoolOpenedEvent event) { - for (ConnectionPoolListener cur : connectionPoolListeners) { - try { - cur.connectionPoolOpened(event); - } catch (Exception e) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn(format("Exception thrown raising connection pool opened event to listener %s", cur), e); - } - } - } - } - @Override public void connectionPoolCreated(final ConnectionPoolCreatedEvent event) { for (ConnectionPoolListener cur : connectionPoolListeners) { @@ -165,32 +151,6 @@ public void connectionCheckedIn(final ConnectionCheckedInEvent event) { } } - @Override - public void connectionRemoved(final com.mongodb.event.ConnectionRemovedEvent event) { - for (ConnectionPoolListener cur : connectionPoolListeners) { - try { - cur.connectionRemoved(event); - } catch (Exception e) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn(format("Exception thrown raising connection pool connection removed event to listener %s", cur), e); - } - } - } - } - - @Override - public void connectionAdded(final com.mongodb.event.ConnectionAddedEvent event) { - for (ConnectionPoolListener cur : connectionPoolListeners) { - try { - cur.connectionAdded(event); - } catch (Exception e) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn(format("Exception thrown raising connection pool connection added event to listener %s", cur), e); - } - } - } - } - @Override public void connectionCreated(final ConnectionCreatedEvent event) { for (ConnectionPoolListener cur : connectionPoolListeners) { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java index 81b92e5cf9a..3f72278b0a8 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java @@ -421,9 +421,6 @@ private List getNonIgnoredActualEvents() { private Set> getIgnoredEventClasses() { Set> ignoredEventClasses = new HashSet<>(); - ignoredEventClasses.add(com.mongodb.event.ConnectionPoolOpenedEvent.class); - ignoredEventClasses.add(com.mongodb.event.ConnectionAddedEvent.class); - ignoredEventClasses.add(com.mongodb.event.ConnectionRemovedEvent.class); for (BsonValue cur : definition.getArray("ignore", new BsonArray())) { String type = cur.asString().getValue(); Class eventClass = getEventClass(type); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy index 68b3242b317..ecbdb2c55ab 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy @@ -20,7 +20,6 @@ import com.mongodb.MongoConnectionPoolClearedException import com.mongodb.MongoServerUnavailableException import com.mongodb.MongoTimeoutException import com.mongodb.ServerAddress -import com.mongodb.logging.TestLoggingInterceptor import com.mongodb.connection.ClusterId import com.mongodb.connection.ConnectionDescription import com.mongodb.connection.ConnectionId @@ -31,6 +30,7 @@ import com.mongodb.internal.async.SingleResultCallback import com.mongodb.internal.inject.EmptyProvider import com.mongodb.internal.inject.SameObjectProvider import com.mongodb.internal.logging.LogMessage +import com.mongodb.logging.TestLoggingInterceptor import org.bson.types.ObjectId import spock.lang.Specification import spock.lang.Subject @@ -191,7 +191,6 @@ class DefaultConnectionPoolSpecification extends Specification { then: 1 * listener.connectionPoolCreated { it.serverId == SERVER_ID && it.settings == settings } - 1 * listener.connectionPoolOpened { it.serverId == SERVER_ID && it.settings == settings } } def 'should invoke connection pool closed event'() { @@ -218,7 +217,6 @@ class DefaultConnectionPoolSpecification extends Specification { then: 1 * listener.connectionCreated { it.connectionId.serverId == SERVER_ID } - 1 * listener.connectionAdded { it.connectionId.serverId == SERVER_ID } 1 * listener.connectionReady { it.connectionId.serverId == SERVER_ID } } @@ -418,7 +416,6 @@ class DefaultConnectionPoolSpecification extends Specification { then: 1 * listener.connectionCreated { it.connectionId.serverId == SERVER_ID } - 1 * listener.connectionAdded { it.connectionId.serverId == SERVER_ID } 1 * listener.connectionReady { it.connectionId.serverId == SERVER_ID } } @@ -436,7 +433,6 @@ class DefaultConnectionPoolSpecification extends Specification { then: 1 * listener.connectionClosed { it.connectionId.serverId == SERVER_ID } - 1 * listener.connectionRemoved { it.connectionId.serverId == SERVER_ID } } def 'should fire asynchronous connection removed from pool event'() { @@ -453,7 +449,6 @@ class DefaultConnectionPoolSpecification extends Specification { then: 1 * listener.connectionClosed { it.connectionId.serverId == SERVER_ID } - 1 * listener.connectionRemoved { it.connectionId.serverId == SERVER_ID } } def 'should fire connection pool events on check out and check in'() { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/TestConnectionPoolListener.java b/driver-core/src/test/unit/com/mongodb/internal/connection/TestConnectionPoolListener.java index e0a2fb355a6..9d8eda976d6 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/TestConnectionPoolListener.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/TestConnectionPoolListener.java @@ -41,7 +41,6 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -@SuppressWarnings("deprecation") public class TestConnectionPoolListener implements ConnectionPoolListener { private final Set eventTypes; @@ -133,13 +132,6 @@ public void connectionPoolCreated(final ConnectionPoolCreatedEvent event) { } } - @Override - public void connectionPoolOpened(final com.mongodb.event.ConnectionPoolOpenedEvent event) { - if (eventTypes.contains("poolOpenedEvent")) { - addEvent(event); - } - } - @Override public void connectionPoolCleared(final ConnectionPoolClearedEvent event) { if (eventTypes.contains("poolClearedEvent")) { @@ -198,20 +190,6 @@ public void connectionCreated(final ConnectionCreatedEvent event) { } } - @Override - public void connectionAdded(final com.mongodb.event.ConnectionAddedEvent event) { - if (eventTypes.contains("connectionAddedEvent")) { - addEvent(event); - } - } - - @Override - public void connectionRemoved(final com.mongodb.event.ConnectionRemovedEvent event) { - if (eventTypes.contains("connectionRemovedEvent")) { - addEvent(event); - } - } - @Override public void connectionReady(final ConnectionReadyEvent event) { if (eventTypes.contains("connectionReadyEvent")) { diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/ConnectionsSurvivePrimaryStepDownProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/ConnectionsSurvivePrimaryStepDownProseTest.java index 300774799b5..7e55971ea1d 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/ConnectionsSurvivePrimaryStepDownProseTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/ConnectionsSurvivePrimaryStepDownProseTest.java @@ -22,6 +22,7 @@ import com.mongodb.MongoNotPrimaryException; import com.mongodb.WriteConcern; import com.mongodb.client.test.CollectionHelper; +import com.mongodb.event.ConnectionCreatedEvent; import com.mongodb.event.ConnectionPoolClearedEvent; import com.mongodb.internal.connection.TestConnectionPoolListener; import com.mongodb.reactivestreams.client.MongoClient; @@ -99,7 +100,7 @@ public void testGetMoreIteration() { Document.parse("{_id: 4}"), Document.parse("{_id: 5}")); Mono.from(collection.withWriteConcern(WriteConcern.MAJORITY).insertMany(documents)).block(TIMEOUT_DURATION); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); BatchCursor cursor = ((FindPublisherImpl) collection.find().batchSize(2)).batchCursor(2) .block(TIMEOUT_DURATION); @@ -110,7 +111,7 @@ public void testGetMoreIteration() { assertEquals(asList(documents.get(2), documents.get(3)), Mono.from(cursor.next()).block(TIMEOUT_DURATION)); assertEquals(singletonList(documents.get(4)), Mono.from(cursor.next()).block(TIMEOUT_DURATION)); - assertEquals(connectionCount, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test @@ -119,7 +120,7 @@ public void testNotPrimaryKeepConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, " + "data: {failCommands: ['insert'], errorCode: 10107}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); @@ -129,7 +130,7 @@ public void testNotPrimaryKeepConnectionPool() { } Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); - assertEquals(connectionCount, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test @@ -138,7 +139,7 @@ public void testNotPrimaryClearConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, " + "data: {failCommands: ['insert'], errorCode: 10107}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); @@ -149,14 +150,14 @@ public void testNotPrimaryClearConnectionPool() { assertEquals(1, connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class)); Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); - assertEquals(connectionCount + 1, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount + 1, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test public void testInterruptedAtShutdownResetsConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, " + "data: {failCommands: ['insert'], errorCode: 11600}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); @@ -165,14 +166,14 @@ public void testInterruptedAtShutdownResetsConnectionPool() { } assertEquals(1, connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class)); Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); - assertEquals(connectionCount + 1, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount + 1, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test public void testShutdownInProgressResetsConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, " + "data: {failCommands: ['insert'], errorCode: 91}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); @@ -182,7 +183,7 @@ public void testShutdownInProgressResetsConnectionPool() { assertEquals(1, connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class)); Mono.from(collection.insertOne(new Document())).block(TIMEOUT_DURATION); - assertEquals(connectionCount + 1, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount + 1, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/ConnectionsSurvivePrimaryStepDownProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/ConnectionsSurvivePrimaryStepDownProseTest.java index 03d57aefce3..06aef2168b0 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ConnectionsSurvivePrimaryStepDownProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ConnectionsSurvivePrimaryStepDownProseTest.java @@ -22,6 +22,7 @@ import com.mongodb.MongoNotPrimaryException; import com.mongodb.WriteConcern; import com.mongodb.client.test.CollectionHelper; +import com.mongodb.event.ConnectionCreatedEvent; import com.mongodb.event.ConnectionPoolClearedEvent; import com.mongodb.internal.connection.TestConnectionPoolListener; import org.bson.Document; @@ -43,7 +44,6 @@ import static org.junit.Assume.assumeTrue; // See https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests -@SuppressWarnings("deprecation") public class ConnectionsSurvivePrimaryStepDownProseTest { private static final String COLLECTION_NAME = "step-down"; @@ -92,14 +92,14 @@ public void testGetMoreIteration() { Document.parse("{_id: 4}"), Document.parse("{_id: 5}")); collection.withWriteConcern(WriteConcern.MAJORITY).insertMany(documents); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); MongoCursor cursor = collection.find().batchSize(2).iterator(); assertEquals(asList(documents.get(0), documents.get(1)), asList(cursor.next(), cursor.next())); collectionHelper.runAdminCommand("{replSetStepDown: 5, force: true}"); assertEquals(asList(documents.get(2), documents.get(3), documents.get(4)), asList(cursor.next(), cursor.next(), cursor.next())); - assertEquals(connectionCount, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test @@ -108,7 +108,7 @@ public void testNotPrimaryKeepConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, data: {failCommands: ['insert'], " + "errorCode: 10107}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { collection.insertOne(new Document()); @@ -118,7 +118,7 @@ public void testNotPrimaryKeepConnectionPool() { } collection.insertOne(new Document()); - assertEquals(connectionCount, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test @@ -127,7 +127,7 @@ public void testNotPrimaryClearConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, data: {failCommands: ['insert'], " + "errorCode: 10107}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { collection.insertOne(new Document()); @@ -137,14 +137,14 @@ public void testNotPrimaryClearConnectionPool() { } assertEquals(1, connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class)); collection.insertOne(new Document("test", 1)); - assertEquals(connectionCount + 1, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount + 1, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test public void testInterruptedAtShutdownResetsConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, data: {failCommands: ['insert'], " + "errorCode: 11600}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { collection.insertOne(new Document()); @@ -154,14 +154,14 @@ public void testInterruptedAtShutdownResetsConnectionPool() { } assertEquals(1, connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class)); collection.insertOne(new Document("test", 1)); - assertEquals(connectionCount + 1, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount + 1, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } @Test public void testShutdownInProgressResetsConnectionPool() { collectionHelper.runAdminCommand("{configureFailPoint: 'failCommand', mode: {times: 1}, data: {failCommands: ['insert'], " + "errorCode: 91}}"); - int connectionCount = connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class); + int connectionCount = connectionPoolListener.countEvents(ConnectionCreatedEvent.class); try { collection.insertOne(new Document()); @@ -171,7 +171,7 @@ public void testShutdownInProgressResetsConnectionPool() { } assertEquals(1, connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class)); collection.insertOne(new Document("test", 1)); - assertEquals(connectionCount + 1, connectionPoolListener.countEvents(com.mongodb.event.ConnectionAddedEvent.class)); + assertEquals(connectionCount + 1, connectionPoolListener.countEvents(ConnectionCreatedEvent.class)); } } From f03a71327c8842a4ec05564939ba14025ee60776 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 26 Oct 2023 12:11:53 -0400 Subject: [PATCH 25/28] Remove deprecated event adapters * ClusterListenerAdapter * ConnectionPoolListenerAdapter * ServerListenerAdapter * ServerMonitorListenerAdapter JAVA-5151 --- .../mongodb/event/ClusterListenerAdapter.java | 27 ---------------- .../event/ConnectionPoolListenerAdapter.java | 27 ---------------- .../mongodb/event/ServerListenerAdapter.java | 27 ---------------- .../event/ServerMonitorListenerAdapter.java | 27 ---------------- .../ServerSettingsSpecification.groovy | 32 +++++++++---------- 5 files changed, 16 insertions(+), 124 deletions(-) delete mode 100644 driver-core/src/main/com/mongodb/event/ClusterListenerAdapter.java delete mode 100644 driver-core/src/main/com/mongodb/event/ConnectionPoolListenerAdapter.java delete mode 100644 driver-core/src/main/com/mongodb/event/ServerListenerAdapter.java delete mode 100644 driver-core/src/main/com/mongodb/event/ServerMonitorListenerAdapter.java diff --git a/driver-core/src/main/com/mongodb/event/ClusterListenerAdapter.java b/driver-core/src/main/com/mongodb/event/ClusterListenerAdapter.java deleted file mode 100644 index 44ef3339930..00000000000 --- a/driver-core/src/main/com/mongodb/event/ClusterListenerAdapter.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -/** - * An adapter for cluster listener implementations, for clients that want to listen for a subset of cluster events. Extend this class to - * listen for cluster events and override the methods of interest. - * - * @since 3.3 - */ -@Deprecated -public class ClusterListenerAdapter implements ClusterListener { -} diff --git a/driver-core/src/main/com/mongodb/event/ConnectionPoolListenerAdapter.java b/driver-core/src/main/com/mongodb/event/ConnectionPoolListenerAdapter.java deleted file mode 100644 index d5a2014bbe3..00000000000 --- a/driver-core/src/main/com/mongodb/event/ConnectionPoolListenerAdapter.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -/** - * An adapter for connection pool listener implementations, for clients that want to listen for a subset of connection pool events. Extend - * this class to listen for connection pool events and override the methods of interest. - * - * @since 3.5 - */ -@Deprecated -public class ConnectionPoolListenerAdapter implements ConnectionPoolListener { -} diff --git a/driver-core/src/main/com/mongodb/event/ServerListenerAdapter.java b/driver-core/src/main/com/mongodb/event/ServerListenerAdapter.java deleted file mode 100644 index d8c0e6242b3..00000000000 --- a/driver-core/src/main/com/mongodb/event/ServerListenerAdapter.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -/** - * An adapter for server listener implementations, for clients that want to listen for a subset of server events. Extend - * this class to listen for server events and override the methods of interest. - * - * @since 3.5 - */ -@Deprecated -public class ServerListenerAdapter implements ServerListener { -} diff --git a/driver-core/src/main/com/mongodb/event/ServerMonitorListenerAdapter.java b/driver-core/src/main/com/mongodb/event/ServerMonitorListenerAdapter.java deleted file mode 100644 index cffc4a2a432..00000000000 --- a/driver-core/src/main/com/mongodb/event/ServerMonitorListenerAdapter.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.event; - -/** - * An adapter for server monitor listener implementations, for clients that want to listen for a subset of server monitor-related events. - * Extend this class to listen for server monitor-related events and override the methods of interest. - * - * @since 3.5 - */ -@Deprecated -public class ServerMonitorListenerAdapter implements ServerMonitorListener { -} diff --git a/driver-core/src/test/unit/com/mongodb/connection/ServerSettingsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/connection/ServerSettingsSpecification.groovy index 407fb540b4e..b92d8630f14 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSettingsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSettingsSpecification.groovy @@ -17,8 +17,8 @@ package com.mongodb.connection import com.mongodb.ConnectionString -import com.mongodb.event.ServerListenerAdapter -import com.mongodb.event.ServerMonitorListenerAdapter +import com.mongodb.event.ServerListener +import com.mongodb.event.ServerMonitorListener import spock.lang.Specification import static java.util.concurrent.TimeUnit.MILLISECONDS @@ -38,12 +38,12 @@ class ServerSettingsSpecification extends Specification { def 'should apply builder settings'() { given: - def serverListenerOne = new ServerListenerAdapter() { } - def serverListenerTwo = new ServerListenerAdapter() { } - def serverListenerThree = new ServerListenerAdapter() { } - def serverMonitorListenerOne = new ServerMonitorListenerAdapter() { } - def serverMonitorListenerTwo = new ServerMonitorListenerAdapter() { } - def serverMonitorListenerThree = new ServerMonitorListenerAdapter() { } + def serverListenerOne = new ServerListener() { } + def serverListenerTwo = new ServerListener() { } + def serverListenerThree = new ServerListener() { } + def serverMonitorListenerOne = new ServerMonitorListener() { } + def serverMonitorListenerTwo = new ServerMonitorListener() { } + def serverMonitorListenerThree = new ServerMonitorListener() { } when: def settings = ServerSettings.builder() @@ -84,8 +84,8 @@ class ServerSettingsSpecification extends Specification { def 'should apply settings'() { given: - def serverListenerOne = new ServerListenerAdapter() { } - def serverMonitorListenerOne = new ServerMonitorListenerAdapter() { } + def serverListenerOne = new ServerListener() { } + def serverMonitorListenerOne = new ServerMonitorListener() { } def defaultSettings = ServerSettings.builder().build() def customSettings = ServerSettings.builder() .heartbeatFrequency(4, SECONDS) @@ -104,13 +104,13 @@ class ServerSettingsSpecification extends Specification { def settings = ServerSettings.builder().build() when: - settings.serverListeners.add(new ServerListenerAdapter() { }) + settings.serverListeners.add(new ServerListener() { }) then: thrown(UnsupportedOperationException) when: - settings.serverMonitorListeners.add(new ServerMonitorListenerAdapter() { }) + settings.serverMonitorListeners.add(new ServerMonitorListener() { }) then: thrown(UnsupportedOperationException) @@ -132,8 +132,8 @@ class ServerSettingsSpecification extends Specification { def 'identical settings should be equal'() { given: - def serverListenerOne = new ServerListenerAdapter() { } - def serverMonitorListenerOne = new ServerMonitorListenerAdapter() { } + def serverListenerOne = new ServerListener() { } + def serverMonitorListenerOne = new ServerMonitorListener() { } expect: ServerSettings.builder().build() == ServerSettings.builder().build() @@ -158,8 +158,8 @@ class ServerSettingsSpecification extends Specification { def 'identical settings should have same hash code'() { given: - def serverListenerOne = new ServerListenerAdapter() { } - def serverMonitorListenerOne = new ServerMonitorListenerAdapter() { } + def serverListenerOne = new ServerListener() { } + def serverMonitorListenerOne = new ServerMonitorListener() { } expect: ServerSettings.builder().build().hashCode() == ServerSettings.builder().build().hashCode() From 4726012956b970db692a8e1ce647dade900eed20 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 26 Oct 2023 11:29:16 -0400 Subject: [PATCH 26/28] Removed deprecated MapCodec JAVA-5142 --- bson/src/main/org/bson/codecs/MapCodec.java | 150 ------------ bson/src/main/org/bson/codecs/MapCodecV2.java | 2 - .../bson/codecs/MapCodecSpecification.groovy | 227 ------------------ .../org/bson/codecs/pojo/PojoCustomTest.java | 9 +- 4 files changed, 5 insertions(+), 383 deletions(-) delete mode 100644 bson/src/main/org/bson/codecs/MapCodec.java delete mode 100644 bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy diff --git a/bson/src/main/org/bson/codecs/MapCodec.java b/bson/src/main/org/bson/codecs/MapCodec.java deleted file mode 100644 index a92c19a69d6..00000000000 --- a/bson/src/main/org/bson/codecs/MapCodec.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs; - -import org.bson.BsonReader; -import org.bson.BsonType; -import org.bson.BsonWriter; -import org.bson.Transformer; -import org.bson.UuidRepresentation; -import org.bson.codecs.configuration.CodecRegistry; - -import java.util.HashMap; -import java.util.Map; - -import static java.util.Arrays.asList; -import static org.bson.assertions.Assertions.notNull; -import static org.bson.codecs.ContainerCodecHelper.readValue; -import static org.bson.codecs.configuration.CodecRegistries.fromProviders; - -/** - * A Codec for Map instances. - * - *

This class has been deprecated because it's not possible to extend it to support {@code Map}s that are not type-compatible with - * {@code HashMap}. - *

- * - * @since 3.5 - * @deprecated Prefer {@link MapCodecProvider} - */ -@Deprecated -public class MapCodec implements Codec>, OverridableUuidRepresentationCodec> { - - private static final CodecRegistry DEFAULT_REGISTRY = fromProviders(asList(new ValueCodecProvider(), new BsonValueCodecProvider(), - new DocumentCodecProvider(), new IterableCodecProvider(), new MapCodecProvider())); - private static final BsonTypeClassMap DEFAULT_BSON_TYPE_CLASS_MAP = new BsonTypeClassMap(); - private final BsonTypeCodecMap bsonTypeCodecMap; - private final CodecRegistry registry; - private final Transformer valueTransformer; - private final UuidRepresentation uuidRepresentation; - - /** - * Construct a new instance with a default {@code CodecRegistry} - */ - public MapCodec() { - this(DEFAULT_REGISTRY); - } - - /** - Construct a new instance with the given registry - * - * @param registry the registry - */ - public MapCodec(final CodecRegistry registry) { - this(registry, DEFAULT_BSON_TYPE_CLASS_MAP); - } - - /** - * Construct a new instance with the given registry and BSON type class map. - * - * @param registry the registry - * @param bsonTypeClassMap the BSON type class map - */ - public MapCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap) { - this(registry, bsonTypeClassMap, null); - } - - /** - * Construct a new instance with the given registry and BSON type class map. The transformer is applied as a last step when decoding - * values, which allows users of this codec to control the decoding process. For example, a user of this class could substitute a - * value decoded as a Document with an instance of a special purpose class (e.g., one representing a DBRef in MongoDB). - * - * @param registry the registry - * @param bsonTypeClassMap the BSON type class map - * @param valueTransformer the value transformer to use as a final step when decoding the value of any field in the map - */ - public MapCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap, final Transformer valueTransformer) { - this(registry, new BsonTypeCodecMap(notNull("bsonTypeClassMap", bsonTypeClassMap), registry), valueTransformer, - UuidRepresentation.UNSPECIFIED); - } - - private MapCodec(final CodecRegistry registry, final BsonTypeCodecMap bsonTypeCodecMap, final Transformer valueTransformer, - final UuidRepresentation uuidRepresentation) { - this.registry = notNull("registry", registry); - this.bsonTypeCodecMap = bsonTypeCodecMap; - this.valueTransformer = valueTransformer != null ? valueTransformer : value -> value; - this.uuidRepresentation = uuidRepresentation; - } - - @Override - public Codec> withUuidRepresentation(final UuidRepresentation uuidRepresentation) { - if (this.uuidRepresentation.equals(uuidRepresentation)) { - return this; - } - return new MapCodec(registry, bsonTypeCodecMap, valueTransformer, uuidRepresentation); - } - - @Override - public void encode(final BsonWriter writer, final Map map, final EncoderContext encoderContext) { - writer.writeStartDocument(); - for (final Map.Entry entry : map.entrySet()) { - writer.writeName(entry.getKey()); - writeValue(writer, encoderContext, entry.getValue()); - } - writer.writeEndDocument(); - } - - @Override - public Map decode(final BsonReader reader, final DecoderContext decoderContext) { - Map map = new HashMap<>(); - - reader.readStartDocument(); - while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { - String fieldName = reader.readName(); - map.put(fieldName, readValue(reader, decoderContext, bsonTypeCodecMap, uuidRepresentation, registry, valueTransformer)); - } - - reader.readEndDocument(); - return map; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public Class> getEncoderClass() { - return (Class>) ((Class) Map.class); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private void writeValue(final BsonWriter writer, final EncoderContext encoderContext, final Object value) { - if (value == null) { - writer.writeNull(); - } else { - Codec codec = registry.get(value.getClass()); - encoderContext.encodeWithChildContext(codec, writer, value); - } - } -} diff --git a/bson/src/main/org/bson/codecs/MapCodecV2.java b/bson/src/main/org/bson/codecs/MapCodecV2.java index d7f2351f7f5..d5e74f922e6 100644 --- a/bson/src/main/org/bson/codecs/MapCodecV2.java +++ b/bson/src/main/org/bson/codecs/MapCodecV2.java @@ -34,8 +34,6 @@ * {@code HashMap} instances when decoding. If the type argument is {@code NavigableMap}, it constructs * {@code TreeMap} instances when decoding.

* - *

Replaces the now deprecated {@link MapCodec}.

- * * @param the actual type of the Map, e.g. {@code NavigableMap} */ @SuppressWarnings("rawtypes") diff --git a/bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy b/bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy deleted file mode 100644 index 5f5d3c54303..00000000000 --- a/bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.bson.codecs - -import org.bson.BsonBinaryReader -import org.bson.BsonBinaryWriter -import org.bson.BsonDbPointer -import org.bson.BsonDocument -import org.bson.BsonDocumentReader -import org.bson.BsonDocumentWriter -import org.bson.BsonInt32 -import org.bson.BsonReader -import org.bson.BsonRegularExpression -import org.bson.BsonTimestamp -import org.bson.BsonUndefined -import org.bson.BsonWriter -import org.bson.ByteBufNIO -import org.bson.Document -import org.bson.io.BasicOutputBuffer -import org.bson.io.ByteBufferBsonInput -import org.bson.json.JsonReader -import org.bson.types.Binary -import org.bson.types.Code -import org.bson.types.CodeWithScope -import org.bson.types.MaxKey -import org.bson.types.MinKey -import org.bson.types.ObjectId -import org.bson.types.Symbol -import spock.lang.Shared -import spock.lang.Specification -import spock.lang.Unroll - -import java.nio.ByteBuffer -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicInteger -import java.util.concurrent.atomic.AtomicLong - -import static java.util.Arrays.asList -import static org.bson.UuidRepresentation.C_SHARP_LEGACY -import static org.bson.UuidRepresentation.JAVA_LEGACY -import static org.bson.UuidRepresentation.PYTHON_LEGACY -import static org.bson.UuidRepresentation.STANDARD -import static org.bson.UuidRepresentation.UNSPECIFIED -import static org.bson.codecs.configuration.CodecRegistries.fromCodecs -import static org.bson.codecs.configuration.CodecRegistries.fromProviders -import static org.bson.codecs.configuration.CodecRegistries.fromRegistries - -@SuppressWarnings('deprecation') -class MapCodecSpecification extends Specification { - - static final REGISTRY = fromRegistries(fromCodecs(new UuidCodec(JAVA_LEGACY)), - fromProviders(asList(new ValueCodecProvider(), new BsonValueCodecProvider(), - new DocumentCodecProvider(), new IterableCodecProvider(), new MapCodecProvider()))) - - @Shared - BsonDocument bsonDoc = new BsonDocument() - @Shared - StringWriter stringWriter = new StringWriter() - - def 'should encode and decode all default types with all readers and writers'(BsonWriter writer) { - given: - def originalDocument = [:] - originalDocument.with { - put('null', null) - put('int32', 42) - put('int64', 52L) - put('booleanTrue', true) - put('booleanFalse', false) - put('date', new Date()) - put('dbPointer', new BsonDbPointer('foo.bar', new ObjectId())) - put('double', 62.0 as double) - put('minKey', new MinKey()) - put('maxKey', new MaxKey()) - put('code', new Code('int i = 0;')) - put('codeWithScope', new CodeWithScope('int x = y', new Document('y', 1))) - put('objectId', new ObjectId()) - put('regex', new BsonRegularExpression('^test.*regex.*xyz$', 'i')) - put('string', 'the fox ...') - put('symbol', new Symbol('ruby stuff')) - put('timestamp', new BsonTimestamp(0x12345678, 5)) - put('undefined', new BsonUndefined()) - put('binary', new Binary((byte) 0x80, [5, 4, 3, 2, 1] as byte[])) - put('array', asList(1, 1L, true, [1, 2, 3], new Document('a', 1), null)) - put('document', new Document('a', 2)) - put('map', [a:1, b:2]) - put('atomicLong', new AtomicLong(1)) - put('atomicInteger', new AtomicInteger(1)) - put('atomicBoolean', new AtomicBoolean(true)) - } - - when: - new MapCodec(REGISTRY).encode(writer, originalDocument, EncoderContext.builder().build()) - BsonReader reader - if (writer instanceof BsonDocumentWriter) { - reader = new BsonDocumentReader(bsonDoc) - } else if (writer instanceof BsonBinaryWriter) { - BasicOutputBuffer buffer = (BasicOutputBuffer)writer.getBsonOutput() - reader = new BsonBinaryReader(new ByteBufferBsonInput(new ByteBufNIO( - ByteBuffer.wrap(buffer.toByteArray())))) - } else { - reader = new JsonReader(stringWriter.toString()) - } - def decodedDoc = new MapCodec(REGISTRY).decode(reader, DecoderContext.builder().build()) - - then: - decodedDoc.get('null') == originalDocument.get('null') - decodedDoc.get('int32') == originalDocument.get('int32') - decodedDoc.get('int64') == originalDocument.get('int64') - decodedDoc.get('booleanTrue') == originalDocument.get('booleanTrue') - decodedDoc.get('booleanFalse') == originalDocument.get('booleanFalse') - decodedDoc.get('date') == originalDocument.get('date') - decodedDoc.get('dbPointer') == originalDocument.get('dbPointer') - decodedDoc.get('double') == originalDocument.get('double') - decodedDoc.get('minKey') == originalDocument.get('minKey') - decodedDoc.get('maxKey') == originalDocument.get('maxKey') - decodedDoc.get('code') == originalDocument.get('code') - decodedDoc.get('codeWithScope') == originalDocument.get('codeWithScope') - decodedDoc.get('objectId') == originalDocument.get('objectId') - decodedDoc.get('regex') == originalDocument.get('regex') - decodedDoc.get('string') == originalDocument.get('string') - decodedDoc.get('symbol') == originalDocument.get('symbol') - decodedDoc.get('timestamp') == originalDocument.get('timestamp') - decodedDoc.get('undefined') == originalDocument.get('undefined') - decodedDoc.get('binary') == originalDocument.get('binary') - decodedDoc.get('array') == originalDocument.get('array') - decodedDoc.get('document') == originalDocument.get('document') - decodedDoc.get('map') == originalDocument.get('map') - decodedDoc.get('atomicLong') == ((AtomicLong) originalDocument.get('atomicLong')).get() - decodedDoc.get('atomicInteger') == ((AtomicInteger) originalDocument.get('atomicInteger')).get() - decodedDoc.get('atomicBoolean') == ((AtomicBoolean) originalDocument.get('atomicBoolean')).get() - - where: - writer << [ - new BsonDocumentWriter(bsonDoc), - new BsonBinaryWriter(new BasicOutputBuffer()) - ] - } - - def 'should decode binary subtypes for UUID that are not 16 bytes into Binary'() { - given: - def reader = new BsonBinaryReader(ByteBuffer.wrap(bytes as byte[])) - - when: - def document = new DocumentCodec().decode(reader, DecoderContext.builder().build()) - - then: - value == document.get('f') - - where: - value | bytes - new Binary((byte) 0x03, (byte[]) [115, 116, 11]) | [16, 0, 0, 0, 5, 102, 0, 3, 0, 0, 0, 3, 115, 116, 11, 0] - new Binary((byte) 0x04, (byte[]) [115, 116, 11]) | [16, 0, 0, 0, 5, 102, 0, 3, 0, 0, 0, 4, 115, 116, 11, 0] - } - - @SuppressWarnings(['LineLength']) - @Unroll - def 'should decode binary subtype 3 for UUID'() { - given: - def reader = new BsonBinaryReader(ByteBuffer.wrap(bytes as byte[])) - - when: - def map = new MapCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec())) - .withUuidRepresentation(representation) - .decode(reader, DecoderContext.builder().build()) - - then: - value == map.get('f') - - where: - representation | value | bytes - JAVA_LEGACY | UUID.fromString('08070605-0403-0201-100f-0e0d0c0b0a09') | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - C_SHARP_LEGACY | UUID.fromString('04030201-0605-0807-090a-0b0c0d0e0f10') | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - PYTHON_LEGACY | UUID.fromString('01020304-0506-0708-090a-0b0c0d0e0f10') | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - STANDARD | new Binary((byte) 3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as byte[]) | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - UNSPECIFIED | new Binary((byte) 3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as byte[]) | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - } - - @SuppressWarnings(['LineLength']) - @Unroll - def 'should decode binary subtype 4 for UUID'() { - given: - def reader = new BsonBinaryReader(ByteBuffer.wrap(bytes as byte[])) - - when: - def map = new MapCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec())) - .withUuidRepresentation(representation) - .decode(reader, DecoderContext.builder().build()) - - then: - value == map.get('f') - - where: - representation | value | bytes - STANDARD | UUID.fromString('01020304-0506-0708-090a-0b0c0d0e0f10') | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - JAVA_LEGACY | new Binary((byte) 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as byte[]) | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - C_SHARP_LEGACY | new Binary((byte) 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as byte[]) | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - PYTHON_LEGACY | new Binary((byte) 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as byte[]) | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - UNSPECIFIED | new Binary((byte) 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as byte[]) | [29, 0, 0, 0, 5, 102, 0, 16, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0] - } - - - def 'should apply transformer to decoded values'() { - given: - def codec = new MapCodec(fromProviders([new ValueCodecProvider(), new DocumentCodecProvider(), new BsonValueCodecProvider()]), - new BsonTypeClassMap(), - { Object value -> 5 }) - when: - def doc = codec.decode(new BsonDocumentReader(new BsonDocument('_id', new BsonInt32(1))), DecoderContext.builder().build()) - - then: - doc['_id'] == 5 - } -} diff --git a/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java b/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java index 5e9f195571b..acb63b04f06 100644 --- a/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java +++ b/bson/src/test/unit/org/bson/codecs/pojo/PojoCustomTest.java @@ -23,7 +23,9 @@ import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; +import org.bson.codecs.IterableCodecProvider; import org.bson.codecs.LongCodec; +import org.bson.codecs.MapCodecProvider; import org.bson.codecs.SimpleEnum; import org.bson.codecs.ValueCodecProvider; import org.bson.codecs.configuration.CodecConfigurationException; @@ -104,7 +106,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -@SuppressWarnings("deprecation") public final class PojoCustomTest extends PojoTestCase { @Test @@ -464,15 +465,15 @@ public void testCustomRegisteredPropertyCodecOmittedValue() { @Test public void testMapStringObjectModel() { MapStringObjectModel model = new MapStringObjectModel(new HashMap<>(Document.parse("{a : 1, b: 'b', c: [1, 2, 3]}"))); - CodecRegistry registry = fromRegistries(fromCodecs(new org.bson.codecs.MapCodec()), - fromProviders(getPojoCodecProviderBuilder(MapStringObjectModel.class).build())); + CodecRegistry registry = fromRegistries(fromProviders(new MapCodecProvider(), new IterableCodecProvider(), new ValueCodecProvider(), + getPojoCodecProviderBuilder(MapStringObjectModel.class).build())); roundTrip(registry, model, "{ map: {a : 1, b: 'b', c: [1, 2, 3]}}"); } @Test public void testMapStringObjectModelWithObjectCodec() { MapStringObjectModel model = new MapStringObjectModel(new HashMap<>(Document.parse("{a : 1, b: 'b', c: [1, 2, 3]}"))); - CodecRegistry registry = fromRegistries(fromCodecs(new org.bson.codecs.MapCodec()), fromCodecs(new ObjectCodec()), + CodecRegistry registry = fromRegistries(fromProviders(new MapCodecProvider()), fromCodecs(new ObjectCodec()), fromProviders(getPojoCodecProviderBuilder(MapStringObjectModel.class).build())); assertThrows(UnsupportedOperationException.class, () -> roundTrip(registry, model, "{ map: {a : 1, b: 'b', c: [1, 2, 3]}}")); From 1a84aaaec2eea3e3ad5542c00c988e52bbd5c5c1 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 26 Oct 2023 11:30:04 -0400 Subject: [PATCH 27/28] Rename MapCodecV2 to MapCodec JAVA-5142 --- .../bson/codecs/{MapCodecV2.java => MapCodec.java} | 8 ++++---- .../src/main/org/bson/codecs/MapCodecProvider.java | 2 +- .../unit/org/bson/codecs/MapCodecProviderTest.java | 8 ++++---- ...ication.groovy => MapCodecSpecification.groovy} | 14 +++++++------- 4 files changed, 16 insertions(+), 16 deletions(-) rename bson/src/main/org/bson/codecs/{MapCodecV2.java => MapCodec.java} (89%) rename bson/src/test/unit/org/bson/codecs/{MapCodecV2Specification.groovy => MapCodecSpecification.groovy} (93%) diff --git a/bson/src/main/org/bson/codecs/MapCodecV2.java b/bson/src/main/org/bson/codecs/MapCodec.java similarity index 89% rename from bson/src/main/org/bson/codecs/MapCodecV2.java rename to bson/src/main/org/bson/codecs/MapCodec.java index d5e74f922e6..e98a2bde399 100644 --- a/bson/src/main/org/bson/codecs/MapCodecV2.java +++ b/bson/src/main/org/bson/codecs/MapCodec.java @@ -37,7 +37,7 @@ * @param the actual type of the Map, e.g. {@code NavigableMap} */ @SuppressWarnings("rawtypes") -final class MapCodecV2> extends AbstractMapCodec +final class MapCodec> extends AbstractMapCodec implements OverridableUuidRepresentationCodec { private final BsonTypeCodecMap bsonTypeCodecMap; @@ -56,13 +56,13 @@ final class MapCodecV2> extends AbstractMapCodec clazz) { this(registry, new BsonTypeCodecMap(notNull("bsonTypeClassMap", bsonTypeClassMap), registry), valueTransformer, UuidRepresentation.UNSPECIFIED, clazz); } - private MapCodecV2(final CodecRegistry registry, final BsonTypeCodecMap bsonTypeCodecMap, final Transformer valueTransformer, + private MapCodec(final CodecRegistry registry, final BsonTypeCodecMap bsonTypeCodecMap, final Transformer valueTransformer, final UuidRepresentation uuidRepresentation, final Class clazz) { super(clazz); this.registry = notNull("registry", registry); @@ -76,7 +76,7 @@ public Codec withUuidRepresentation(final UuidRepresentation uuidRepresentati if (this.uuidRepresentation.equals(uuidRepresentation)) { return this; } - return new MapCodecV2<>(registry, bsonTypeCodecMap, valueTransformer, uuidRepresentation, getEncoderClass()); + return new MapCodec<>(registry, bsonTypeCodecMap, valueTransformer, uuidRepresentation, getEncoderClass()); } @Override diff --git a/bson/src/main/org/bson/codecs/MapCodecProvider.java b/bson/src/main/org/bson/codecs/MapCodecProvider.java index 0db9ee975f9..d87de577211 100644 --- a/bson/src/main/org/bson/codecs/MapCodecProvider.java +++ b/bson/src/main/org/bson/codecs/MapCodecProvider.java @@ -90,7 +90,7 @@ public Codec get(final Class clazz, final List typeArguments, fi switch (typeArgumentsSize) { case 0: { @SuppressWarnings({"unchecked", "rawtypes"}) - Codec result = new MapCodecV2(registry, bsonTypeClassMap, valueTransformer, clazz); + Codec result = new MapCodec(registry, bsonTypeClassMap, valueTransformer, clazz); return result; } case 2: { diff --git a/bson/src/test/unit/org/bson/codecs/MapCodecProviderTest.java b/bson/src/test/unit/org/bson/codecs/MapCodecProviderTest.java index 5e850a8f64d..6437334675a 100644 --- a/bson/src/test/unit/org/bson/codecs/MapCodecProviderTest.java +++ b/bson/src/test/unit/org/bson/codecs/MapCodecProviderTest.java @@ -37,8 +37,8 @@ void shouldReturnMapCodecForMap() { MapCodecProvider provider = new MapCodecProvider(); @SuppressWarnings({"rawtypes", "unchecked"}) Codec> codec = (Codec>) (Codec) provider.get(Map.class, Bson.DEFAULT_CODEC_REGISTRY); - assertTrue(codec instanceof MapCodecV2); - MapCodecV2> recordCodec = (MapCodecV2>) codec; + assertTrue(codec instanceof MapCodec); + MapCodec> recordCodec = (MapCodec>) codec; assertEquals(Map.class, recordCodec.getEncoderClass()); } @@ -46,8 +46,8 @@ void shouldReturnMapCodecForMap() { public void shouldReturnMapCodecForMapUsingDefaultRegistry() { @SuppressWarnings({"rawtypes", "unchecked"}) Codec> codec = (Codec>) (Codec) Bson.DEFAULT_CODEC_REGISTRY.get(Map.class); - assertTrue(codec instanceof MapCodecV2); - MapCodecV2> recordCodec = (MapCodecV2>) codec; + assertTrue(codec instanceof MapCodec); + MapCodec> recordCodec = (MapCodec>) codec; assertEquals(Map.class, recordCodec.getEncoderClass()); } } diff --git a/bson/src/test/unit/org/bson/codecs/MapCodecV2Specification.groovy b/bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy similarity index 93% rename from bson/src/test/unit/org/bson/codecs/MapCodecV2Specification.groovy rename to bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy index 911053a900a..ffe66e32d10 100644 --- a/bson/src/test/unit/org/bson/codecs/MapCodecV2Specification.groovy +++ b/bson/src/test/unit/org/bson/codecs/MapCodecSpecification.groovy @@ -64,7 +64,7 @@ import static org.bson.codecs.configuration.CodecRegistries.fromCodecs import static org.bson.codecs.configuration.CodecRegistries.fromProviders import static org.bson.codecs.configuration.CodecRegistries.fromRegistries -class MapCodecV2Specification extends Specification { +class MapCodecSpecification extends Specification { static final REGISTRY = fromRegistries(fromCodecs(new UuidCodec(JAVA_LEGACY)), fromProviders(asList(new ValueCodecProvider(), new BsonValueCodecProvider(), @@ -107,7 +107,7 @@ class MapCodecV2Specification extends Specification { } when: - new MapCodecV2(REGISTRY, new BsonTypeClassMap(), null, Map).encode(writer, originalDocument, EncoderContext.builder().build()) + new MapCodec(REGISTRY, new BsonTypeClassMap(), null, Map).encode(writer, originalDocument, EncoderContext.builder().build()) BsonReader reader if (writer instanceof BsonDocumentWriter) { reader = new BsonDocumentReader(bsonDoc) @@ -118,7 +118,7 @@ class MapCodecV2Specification extends Specification { } else { reader = new JsonReader(stringWriter.toString()) } - def decodedDoc = new MapCodecV2(REGISTRY, new BsonTypeClassMap(), null, Map).decode(reader, DecoderContext.builder().build()) + def decodedDoc = new MapCodec(REGISTRY, new BsonTypeClassMap(), null, Map).decode(reader, DecoderContext.builder().build()) then: decodedDoc.get('null') == originalDocument.get('null') @@ -177,7 +177,7 @@ class MapCodecV2Specification extends Specification { def reader = new BsonBinaryReader(ByteBuffer.wrap(bytes as byte[])) when: - def map = new MapCodecV2(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap(), null, Map) + def map = new MapCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap(), null, Map) .withUuidRepresentation(representation) .decode(reader, DecoderContext.builder().build()) @@ -200,7 +200,7 @@ class MapCodecV2Specification extends Specification { def reader = new BsonBinaryReader(ByteBuffer.wrap(bytes as byte[])) when: - def map = new MapCodecV2(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap(), null, Map) + def map = new MapCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap(), null, Map) .withUuidRepresentation(representation) .decode(reader, DecoderContext.builder().build()) @@ -219,7 +219,7 @@ class MapCodecV2Specification extends Specification { def 'should apply transformer to decoded values'() { given: - def codec = new MapCodecV2(fromProviders([new ValueCodecProvider(), new DocumentCodecProvider(), new BsonValueCodecProvider()]), + def codec = new MapCodec(fromProviders([new ValueCodecProvider(), new DocumentCodecProvider(), new BsonValueCodecProvider()]), new BsonTypeClassMap(), { Object value -> 5 }, Map) when: @@ -234,7 +234,7 @@ class MapCodecV2Specification extends Specification { def doc = new BsonDocument('_id', new BsonInt32(1)) when: - def codec = new MapCodecV2(fromProviders([new ValueCodecProvider()]), new BsonTypeClassMap(), null, mapType) + def codec = new MapCodec(fromProviders([new ValueCodecProvider()]), new BsonTypeClassMap(), null, mapType) def map = codec.decode(new BsonDocumentReader(doc), DecoderContext.builder().build()) then: From 7b3312a2dcf0728cc946f5ae22155cd5d04b57a1 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 26 Oct 2023 11:43:28 -0400 Subject: [PATCH 28/28] Make deprecated IterableCodec package-private It's still used by IterableCodecProvider, so it can't be removed entirely. (Though IterableCodecProvider is almost entirely supplanted by CollectionCodecProvider, it was not itself deprecated because it provides a codec for any Iterable, while CollectionCodecProvider only provides one for any Collection, which is not quite the same thing). JAVA-5142 --- .../main/org/bson/codecs/IterableCodec.java | 25 ++----------------- .../codecs/IterableCodecSpecification.groovy | 12 ++++----- 2 files changed, 8 insertions(+), 29 deletions(-) diff --git a/bson/src/main/org/bson/codecs/IterableCodec.java b/bson/src/main/org/bson/codecs/IterableCodec.java index 4903f9a8493..028c571aaef 100644 --- a/bson/src/main/org/bson/codecs/IterableCodec.java +++ b/bson/src/main/org/bson/codecs/IterableCodec.java @@ -31,37 +31,16 @@ /** * Encodes and decodes {@code Iterable} objects. - * - * @since 3.3 - * @deprecated Prefer {@link CollectionCodecProvider} */ -@Deprecated @SuppressWarnings("rawtypes") -public class IterableCodec implements Codec, OverridableUuidRepresentationCodec { +class IterableCodec implements Codec, OverridableUuidRepresentationCodec { private final CodecRegistry registry; private final BsonTypeCodecMap bsonTypeCodecMap; private final Transformer valueTransformer; private final UuidRepresentation uuidRepresentation; - /** - * Construct a new instance with the given {@code CodecRegistry} and {@code BsonTypeClassMap}. - * - * @param registry the non-null codec registry - * @param bsonTypeClassMap the non-null BsonTypeClassMap - */ - public IterableCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap) { - this(registry, bsonTypeClassMap, null); - } - - /** - * Construct a new instance with the given {@code CodecRegistry} and {@code BsonTypeClassMap}. - * - * @param registry the non-null codec registry - * @param bsonTypeClassMap the non-null BsonTypeClassMap - * @param valueTransformer the value Transformer - */ - public IterableCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap, final Transformer valueTransformer) { + IterableCodec(final CodecRegistry registry, final BsonTypeClassMap bsonTypeClassMap, final Transformer valueTransformer) { this(registry, new BsonTypeCodecMap(notNull("bsonTypeClassMap", bsonTypeClassMap), registry), valueTransformer, UuidRepresentation.UNSPECIFIED); } diff --git a/bson/src/test/unit/org/bson/codecs/IterableCodecSpecification.groovy b/bson/src/test/unit/org/bson/codecs/IterableCodecSpecification.groovy index 02a09e23134..6af13dfc2ac 100644 --- a/bson/src/test/unit/org/bson/codecs/IterableCodecSpecification.groovy +++ b/bson/src/test/unit/org/bson/codecs/IterableCodecSpecification.groovy @@ -43,7 +43,7 @@ class IterableCodecSpecification extends Specification { def 'should have Iterable encoding class'() { given: - def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap()) + def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap(), null) expect: codec.getEncoderClass() == Iterable @@ -51,7 +51,7 @@ class IterableCodecSpecification extends Specification { def 'should encode an Iterable to a BSON array'() { given: - def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap()) + def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap(), null) def writer = new BsonDocumentWriter(new BsonDocument()) when: @@ -66,7 +66,7 @@ class IterableCodecSpecification extends Specification { def 'should decode a BSON array to an Iterable'() { given: - def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap()) + def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap(), null) def reader = new BsonDocumentReader(parse('{array : [1, 2, 3, null]}')) when: @@ -81,7 +81,7 @@ class IterableCodecSpecification extends Specification { def 'should decode a BSON array of arrays to an Iterable of Iterables'() { given: - def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap()) + def codec = new IterableCodec(REGISTRY, new BsonTypeClassMap(), null) def reader = new BsonDocumentReader(parse('{array : [[1, 2], [3, 4, 5]]}')) when: @@ -116,7 +116,7 @@ class IterableCodecSpecification extends Specification { def 'should decode binary subtype 3 for UUID'() { given: def reader = new BsonDocumentReader(parse(document)) - def codec = new IterableCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap()) + def codec = new IterableCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap(), null) .withUuidRepresentation(representation) when: @@ -142,7 +142,7 @@ class IterableCodecSpecification extends Specification { def 'should decode binary subtype 4 for UUID'() { given: def reader = new BsonDocumentReader(parse(document)) - def codec = new IterableCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap()) + def codec = new IterableCodec(fromCodecs(new UuidCodec(representation), new BinaryCodec()), new BsonTypeClassMap(), null) .withUuidRepresentation(representation) when: