Search in sources :

Example 11 with MongoClientException

use of com.mongodb.MongoClientException in project mongo-java-driver by mongodb.

the class DefaultDnsResolver method createDnsDirContext.

/*
      It's unfortunate that we take a runtime dependency on com.sun.jndi.dns.DnsContextFactory.
      This is not guaranteed to work on all JVMs but in practice is expected to work on most.
    */
private static InitialDirContext createDnsDirContext() {
    Hashtable<String, String> envProps = new Hashtable<String, String>();
    envProps.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    try {
        return new InitialDirContext(envProps);
    } catch (NamingException e) {
        // Just in case the provider url default has been changed to a non-dns pseudo url, fallback to the JDK default
        envProps.put(Context.PROVIDER_URL, "dns:");
        try {
            return new InitialDirContext(envProps);
        } catch (NamingException ex) {
            throw new MongoClientException("Unable to support mongodb+srv// style connections as the 'com.sun.jndi.dns.DnsContextFactory' " + "class is not available in this JRE. A JNDI context is required for resolving SRV records.", e);
        }
    }
}
Also used : MongoClientException(com.mongodb.MongoClientException) Hashtable(java.util.Hashtable) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 12 with MongoClientException

use of com.mongodb.MongoClientException in project mongo-java-driver by mongodb.

the class CryptConnection method commandAsync.

@Override
public <T> void commandAsync(final String database, final BsonDocument command, final FieldNameValidator commandFieldNameValidator, final ReadPreference readPreference, final Decoder<T> commandResultDecoder, final SessionContext sessionContext, final ServerApi serverApi, final RequestContext requestContext, final boolean responseExpected, @Nullable final SplittablePayload payload, @Nullable final FieldNameValidator payloadFieldNameValidator, final SingleResultCallback<T> callback) {
    if (serverIsLessThanVersionFourDotTwo(wrapped.getDescription())) {
        callback.onResult(null, new MongoClientException("Auto-encryption requires a minimum MongoDB version of 4.2"));
        return;
    }
    try {
        BasicOutputBuffer bsonOutput = new BasicOutputBuffer();
        BsonBinaryWriter bsonBinaryWriter = new BsonBinaryWriter(new BsonWriterSettings(), new BsonBinaryWriterSettings(getDescription().getMaxDocumentSize()), bsonOutput, getFieldNameValidator(payload, commandFieldNameValidator, payloadFieldNameValidator));
        BsonWriter writer = payload == null ? bsonBinaryWriter : new SplittablePayloadBsonWriter(bsonBinaryWriter, bsonOutput, createSplittablePayloadMessageSettings(), payload, MAX_SPLITTABLE_DOCUMENT_SIZE);
        getEncoder(command).encode(writer, command, EncoderContext.builder().build());
        crypt.encrypt(database, new RawBsonDocument(bsonOutput.getInternalBuffer(), 0, bsonOutput.getSize())).flatMap((Function<RawBsonDocument, Mono<RawBsonDocument>>) encryptedCommand -> Mono.create(sink -> wrapped.commandAsync(database, encryptedCommand, commandFieldNameValidator, readPreference, new RawBsonDocumentCodec(), sessionContext, serverApi, requestContext, responseExpected, null, null, sinkToCallback(sink)))).flatMap(crypt::decrypt).map(decryptedResponse -> commandResultDecoder.decode(new BsonBinaryReader(decryptedResponse.getByteBuffer().asNIO()), DecoderContext.builder().build())).subscribe(decryptedResult -> callback.onResult(decryptedResult, null), e -> callback.onResult(null, e));
    } catch (Throwable t) {
        callback.onResult(null, t);
    }
}
Also used : ReadPreference(com.mongodb.ReadPreference) InsertRequest(com.mongodb.internal.bulk.InsertRequest) MongoClientException(com.mongodb.MongoClientException) ServerApi(com.mongodb.ServerApi) HashMap(java.util.HashMap) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) SplittablePayloadBsonWriter(com.mongodb.internal.connection.SplittablePayloadBsonWriter) BsonBinaryWriter(org.bson.BsonBinaryWriter) Function(java.util.function.Function) BsonDocument(org.bson.BsonDocument) ConnectionDescription(com.mongodb.connection.ConnectionDescription) Connection(com.mongodb.internal.connection.Connection) Map(java.util.Map) WriteConcernResult(com.mongodb.WriteConcernResult) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) SessionContext(com.mongodb.internal.session.SessionContext) MappedFieldNameValidator(com.mongodb.internal.validator.MappedFieldNameValidator) FieldNameValidator(org.bson.FieldNameValidator) BsonBinaryWriterSettings(org.bson.BsonBinaryWriterSettings) DecoderContext(org.bson.codecs.DecoderContext) RawBsonDocumentCodec(org.bson.codecs.RawBsonDocumentCodec) EncoderContext(org.bson.codecs.EncoderContext) QueryResult(com.mongodb.internal.connection.QueryResult) MongoNamespace(com.mongodb.MongoNamespace) MessageSettings(com.mongodb.internal.connection.MessageSettings) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) RawBsonDocument(org.bson.RawBsonDocument) CodecRegistries.fromProviders(org.bson.codecs.configuration.CodecRegistries.fromProviders) BasicOutputBuffer(org.bson.io.BasicOutputBuffer) Mono(reactor.core.publisher.Mono) RequestContext(com.mongodb.RequestContext) BsonValueCodecProvider(org.bson.codecs.BsonValueCodecProvider) ServerVersionHelper.serverIsLessThanVersionFourDotTwo(com.mongodb.internal.operation.ServerVersionHelper.serverIsLessThanVersionFourDotTwo) SplittablePayload(com.mongodb.internal.connection.SplittablePayload) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) Decoder(org.bson.codecs.Decoder) List(java.util.List) BsonBinaryReader(org.bson.BsonBinaryReader) Codec(org.bson.codecs.Codec) BsonWriter(org.bson.BsonWriter) MongoOperationPublisher.sinkToCallback(com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback) Nullable(com.mongodb.lang.Nullable) AsyncConnection(com.mongodb.internal.connection.AsyncConnection) BsonWriterSettings(org.bson.BsonWriterSettings) MongoClientException(com.mongodb.MongoClientException) RawBsonDocumentCodec(org.bson.codecs.RawBsonDocumentCodec) BsonBinaryReader(org.bson.BsonBinaryReader) SplittablePayloadBsonWriter(com.mongodb.internal.connection.SplittablePayloadBsonWriter) BsonWriter(org.bson.BsonWriter) RawBsonDocument(org.bson.RawBsonDocument) Function(java.util.function.Function) SplittablePayloadBsonWriter(com.mongodb.internal.connection.SplittablePayloadBsonWriter) BsonBinaryWriter(org.bson.BsonBinaryWriter) BsonBinaryWriterSettings(org.bson.BsonBinaryWriterSettings) BsonWriterSettings(org.bson.BsonWriterSettings) BasicOutputBuffer(org.bson.io.BasicOutputBuffer)

Example 13 with MongoClientException

use of com.mongodb.MongoClientException in project mongo-java-driver by mongodb.

the class OperationExecutorImpl method execute.

@Override
public <T> Mono<T> execute(final AsyncReadOperation<T> operation, final ReadPreference readPreference, final ReadConcern readConcern, @Nullable final ClientSession session) {
    notNull("operation", operation);
    notNull("readPreference", readPreference);
    notNull("readConcern", readConcern);
    if (session != null) {
        session.notifyOperationInitiated(operation);
    }
    return Mono.from(subscriber -> clientSessionHelper.withClientSession(session, OperationExecutorImpl.this).map(clientSession -> getReadWriteBinding(getContext(subscriber), readPreference, readConcern, clientSession, session == null && clientSession != null)).switchIfEmpty(Mono.fromCallable(() -> getReadWriteBinding(getContext(subscriber), readPreference, readConcern, session, false))).flatMap(binding -> {
        if (session != null && session.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) {
            binding.release();
            return Mono.error(new MongoClientException("Read preference in a transaction must be primary"));
        } else {
            return Mono.<T>create(sink -> operation.executeAsync(binding, (result, t) -> {
                try {
                    binding.release();
                } finally {
                    sinkToCallback(sink).onResult(result, t);
                }
            })).doOnError((t) -> {
                labelException(session, t);
                unpinServerAddressOnTransientTransactionError(session, t);
            });
        }
    }).subscribe(subscriber));
}
Also used : MongoInternalException(com.mongodb.MongoInternalException) ReadPreference(com.mongodb.ReadPreference) AsyncReadWriteBinding(com.mongodb.internal.binding.AsyncReadWriteBinding) MongoClientException(com.mongodb.MongoClientException) MongoSocketException(com.mongodb.MongoSocketException) MongoQueryException(com.mongodb.MongoQueryException) CryptBinding(com.mongodb.reactivestreams.client.internal.crypt.CryptBinding) TRANSIENT_TRANSACTION_ERROR_LABEL(com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL) IgnorableRequestContext(com.mongodb.internal.IgnorableRequestContext) ReadConcern(com.mongodb.ReadConcern) Subscriber(org.reactivestreams.Subscriber) MongoException(com.mongodb.MongoException) AsyncWriteOperation(com.mongodb.internal.operation.AsyncWriteOperation) Mono(reactor.core.publisher.Mono) RequestContext(com.mongodb.RequestContext) ClientSessionBinding(com.mongodb.internal.async.client.ClientSessionBinding) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ReactiveContextProvider(com.mongodb.reactivestreams.client.ReactiveContextProvider) MongoTimeoutException(com.mongodb.MongoTimeoutException) Crypt(com.mongodb.reactivestreams.client.internal.crypt.Crypt) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) ContextProvider(com.mongodb.ContextProvider) AsyncReadOperation(com.mongodb.internal.operation.AsyncReadOperation) AsyncClusterBinding(com.mongodb.internal.binding.AsyncClusterBinding) UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL(com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) ReadPreference.primary(com.mongodb.ReadPreference.primary) MongoOperationPublisher.sinkToCallback(com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback) Nullable(com.mongodb.lang.Nullable) AsyncClusterAwareReadWriteBinding(com.mongodb.internal.binding.AsyncClusterAwareReadWriteBinding) MongoClientException(com.mongodb.MongoClientException)

Example 14 with MongoClientException

use of com.mongodb.MongoClientException in project mongo-java-driver by mongodb.

the class ClientSessionPublisherImpl method startTransaction.

@Override
public void startTransaction(final TransactionOptions transactionOptions) {
    notNull("transactionOptions", transactionOptions);
    Boolean snapshot = getOptions().isSnapshot();
    if (snapshot != null && snapshot) {
        throw new IllegalArgumentException("Transactions are not supported in snapshot sessions");
    }
    if (transactionState == TransactionState.IN) {
        throw new IllegalStateException("Transaction already in progress");
    }
    if (transactionState == TransactionState.COMMITTED) {
        cleanupTransaction(TransactionState.IN);
    } else {
        transactionState = TransactionState.IN;
    }
    getServerSession().advanceTransactionNumber();
    this.transactionOptions = TransactionOptions.merge(transactionOptions, getOptions().getDefaultTransactionOptions());
    WriteConcern writeConcern = this.transactionOptions.getWriteConcern();
    if (writeConcern == null) {
        throw new MongoInternalException("Invariant violated. Transaction options write concern can not be null");
    }
    if (!writeConcern.isAcknowledged()) {
        throw new MongoClientException("Transactions do not support unacknowledged write concern");
    }
    clearTransactionContext();
}
Also used : MongoClientException(com.mongodb.MongoClientException) WriteConcern(com.mongodb.WriteConcern) MongoInternalException(com.mongodb.MongoInternalException)

Example 15 with MongoClientException

use of com.mongodb.MongoClientException in project mongo-java-driver by mongodb.

the class NettyStream method addSslHandler.

private void addSslHandler(final SocketChannel channel) {
    SSLEngine engine;
    if (sslContext == null) {
        SSLContext sslContext;
        try {
            sslContext = (sslSettings.getContext() == null) ? SSLContext.getDefault() : sslSettings.getContext();
        } catch (NoSuchAlgorithmException e) {
            throw new MongoClientException("Unable to create standard SSLContext", e);
        }
        engine = sslContext.createSSLEngine(address.getHost(), address.getPort());
    } else {
        engine = sslContext.newEngine(channel.alloc(), address.getHost(), address.getPort());
    }
    engine.setUseClientMode(true);
    SSLParameters sslParameters = engine.getSSLParameters();
    enableSni(address.getHost(), sslParameters);
    if (!sslSettings.isInvalidHostNameAllowed()) {
        enableHostNameVerification(sslParameters);
    }
    engine.setSSLParameters(sslParameters);
    channel.pipeline().addFirst("ssl", new SslHandler(engine, false));
}
Also used : MongoClientException(com.mongodb.MongoClientException) SSLParameters(javax.net.ssl.SSLParameters) SSLEngine(javax.net.ssl.SSLEngine) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SslHandler(io.netty.handler.ssl.SslHandler)

Aggregations

MongoClientException (com.mongodb.MongoClientException)19 MongoException (com.mongodb.MongoException)4 BsonDocument (org.bson.BsonDocument)4 MongoInternalException (com.mongodb.MongoInternalException)3 ClusterSettings (com.mongodb.connection.ClusterSettings)3 MongoQueryException (com.mongodb.MongoQueryException)2 MongoSocketException (com.mongodb.MongoSocketException)2 ReadPreference (com.mongodb.ReadPreference)2 RequestContext (com.mongodb.RequestContext)2 ServerAddress (com.mongodb.ServerAddress)2 WriteConcern (com.mongodb.WriteConcern)2 ClusterId (com.mongodb.connection.ClusterId)2 ConnectionDescription (com.mongodb.connection.ConnectionDescription)2 Nullable (com.mongodb.lang.Nullable)2 MongoOperationPublisher.sinkToCallback (com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 BsonString (org.bson.BsonString)2 BsonValue (org.bson.BsonValue)2 Test (org.junit.jupiter.api.Test)2