Search in sources :

Example 11 with Nullable

use of com.mongodb.lang.Nullable 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 12 with Nullable

use of com.mongodb.lang.Nullable 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 13 with Nullable

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

the class GridFSPublisherCreator method createDeletePublisher.

public static Publisher<Void> createDeletePublisher(final MongoCollection<GridFSFile> filesCollection, final MongoCollection<Document> chunksCollection, @Nullable final ClientSession clientSession, final BsonValue id) {
    notNull("filesCollection", filesCollection);
    notNull("chunksCollection", chunksCollection);
    notNull("id", id);
    BsonDocument filter = new BsonDocument("_id", id);
    Publisher<DeleteResult> fileDeletePublisher;
    if (clientSession == null) {
        fileDeletePublisher = filesCollection.deleteOne(filter);
    } else {
        fileDeletePublisher = filesCollection.deleteOne(clientSession, filter);
    }
    return Mono.from(fileDeletePublisher).flatMap(deleteResult -> {
        if (deleteResult.wasAcknowledged() && deleteResult.getDeletedCount() == 0) {
            throw new MongoGridFSException(format("No file found with the ObjectId: %s", id));
        }
        if (clientSession == null) {
            return Mono.from(chunksCollection.deleteMany(new BsonDocument("files_id", id)));
        } else {
            return Mono.from(chunksCollection.deleteMany(clientSession, new BsonDocument("files_id", id)));
        }
    }).flatMap(i -> Mono.empty());
}
Also used : Document(org.bson.Document) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) Publisher(org.reactivestreams.Publisher) MongoGridFSException(com.mongodb.MongoGridFSException) Mono(reactor.core.publisher.Mono) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) ClientSession(com.mongodb.reactivestreams.client.ClientSession) BsonString(org.bson.BsonString) ByteBuffer(java.nio.ByteBuffer) String.format(java.lang.String.format) BsonDocument(org.bson.BsonDocument) BsonValue(org.bson.BsonValue) Bson(org.bson.conversions.Bson) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) UpdateResult(com.mongodb.client.result.UpdateResult) GridFSDownloadOptions(com.mongodb.client.gridfs.model.GridFSDownloadOptions) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) DeleteResult(com.mongodb.client.result.DeleteResult) GridFSFindPublisher(com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher) Nullable(com.mongodb.lang.Nullable) BsonDocument(org.bson.BsonDocument) MongoGridFSException(com.mongodb.MongoGridFSException) DeleteResult(com.mongodb.client.result.DeleteResult)

Example 14 with Nullable

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

the class GeometryDecoderHelper method decodeCoordinateReferenceSystem.

@Nullable
static CoordinateReferenceSystem decodeCoordinateReferenceSystem(final BsonReader reader) {
    String crsName = null;
    validateIsDocument(reader);
    reader.readStartDocument();
    while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
        String name = reader.readName();
        if (name.equals("type")) {
            String type = reader.readString();
            if (!type.equals("name")) {
                throw new CodecConfigurationException(format("Unsupported CoordinateReferenceSystem '%s'.", type));
            }
        } else if (name.equals("properties")) {
            crsName = decodeCoordinateReferenceSystemProperties(reader);
        } else {
            throw new CodecConfigurationException(format("Found invalid key '%s' in the CoordinateReferenceSystem.", name));
        }
    }
    reader.readEndDocument();
    return crsName != null ? new NamedCoordinateReferenceSystem(crsName) : null;
}
Also used : NamedCoordinateReferenceSystem(com.mongodb.client.model.geojson.NamedCoordinateReferenceSystem) CodecConfigurationException(org.bson.codecs.configuration.CodecConfigurationException) LineString(com.mongodb.client.model.geojson.LineString) MultiLineString(com.mongodb.client.model.geojson.MultiLineString) Nullable(com.mongodb.lang.Nullable)

Example 15 with Nullable

use of com.mongodb.lang.Nullable in project morphia by mongodb.

the class Modify method execute.

/**
 * Performs the operation
 *
 * @param options the options to apply
 * @return the operation result
 */
@Nullable
public T execute(ModifyOptions options) {
    ClientSession session = getDatastore().findSession(options);
    Document update = toDocument();
    return session == null ? options.prepare(getCollection()).findOneAndUpdate(getQuery().toDocument(), update, options) : options.prepare(getCollection()).findOneAndUpdate(session, getQuery().toDocument(), update, options);
}
Also used : ClientSession(com.mongodb.client.ClientSession) Document(org.bson.Document) Nullable(com.mongodb.lang.Nullable)

Aggregations

Nullable (com.mongodb.lang.Nullable)19 EntityModel (dev.morphia.mapping.codec.pojo.EntityModel)4 BsonDocument (org.bson.BsonDocument)4 Mono (reactor.core.publisher.Mono)4 MongoClientException (com.mongodb.MongoClientException)3 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)3 PropertyModel (dev.morphia.mapping.codec.pojo.PropertyModel)3 BsonString (org.bson.BsonString)3 RawBsonDocument (org.bson.RawBsonDocument)3 MongoException (com.mongodb.MongoException)2 MongoInternalException (com.mongodb.MongoInternalException)2 MongoNamespace (com.mongodb.MongoNamespace)2 ReadPreference (com.mongodb.ReadPreference)2 RequestContext (com.mongodb.RequestContext)2 ClientSession (com.mongodb.reactivestreams.client.ClientSession)2 MongoOperationPublisher.sinkToCallback (com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback)2 String.format (java.lang.String.format)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2