Search in sources :

Example 41 with WriteConcern

use of com.mongodb.WriteConcern in project morphia by mongodb.

the class Mapper method getWriteConcern.

/**
 * Gets the write concern for entity or returns the default write concern for this datastore
 *
 * @param clazz the class to use when looking up the WriteConcern
 * @return the write concern for the type
 * @morphia.internal
 */
@Nullable
public WriteConcern getWriteConcern(Class clazz) {
    WriteConcern wc = null;
    EntityModel entityModel = getEntityModel(clazz);
    if (entityModel != null) {
        final Entity entityAnn = entityModel.getEntityAnnotation();
        if (entityAnn != null && !entityAnn.concern().isEmpty()) {
            wc = WriteConcern.valueOf(entityAnn.concern());
        }
    }
    return wc;
}
Also used : ExternalEntity(dev.morphia.annotations.experimental.ExternalEntity) Entity(dev.morphia.annotations.Entity) WriteConcern(com.mongodb.WriteConcern) EntityModel(dev.morphia.mapping.codec.pojo.EntityModel) Nullable(com.mongodb.lang.Nullable)

Example 42 with WriteConcern

use of com.mongodb.WriteConcern in project jmeter by apache.

the class MongoSourceElement method testStarted.

@Override
public void testStarted() {
    if (log.isDebugEnabled()) {
        log.debug(getTitle() + " testStarted");
    }
    MongoClientOptions.Builder builder = MongoClientOptions.builder().autoConnectRetry(getAutoConnectRetry()).connectTimeout(getConnectTimeout()).connectionsPerHost(getConnectionsPerHost()).maxAutoConnectRetryTime(getMaxAutoConnectRetryTime()).maxWaitTime(getMaxWaitTime()).socketKeepAlive(getSocketKeepAlive()).socketTimeout(getSocketTimeout()).threadsAllowedToBlockForConnectionMultiplier(getThreadsAllowedToBlockForConnectionMultiplier());
    if (getSafe()) {
        builder.writeConcern(WriteConcern.SAFE);
    } else {
        builder.writeConcern(new WriteConcern(getWriteOperationNumberOfServers(), getWriteOperationTimeout(), getFsync(), getWaitForJournaling(), getContinueOnInsertError()));
    }
    MongoClientOptions mongoOptions = builder.build();
    if (log.isDebugEnabled()) {
        log.debug("options : " + mongoOptions.toString());
    }
    if (getThreadContext().getVariables().getObject(getSource()) != null) {
        if (log.isWarnEnabled()) {
            log.warn(getSource() + " has already been defined.");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug(getSource() + "  is being defined.");
        }
        try {
            getThreadContext().getVariables().putObject(getSource(), new MongoDB(MongoUtils.toServerAddresses(getConnection()), mongoOptions));
        } catch (UnknownHostException e) {
            throw new IllegalStateException(e);
        }
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) MongoClientOptions(com.mongodb.MongoClientOptions) WriteConcern(com.mongodb.WriteConcern) MongoDB(org.apache.jmeter.protocol.mongodb.mongo.MongoDB)

Example 43 with WriteConcern

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

the class ClientSessionImpl method startTransaction.

@Override
public void startTransaction(final TransactionOptions transactionOptions) {
    Boolean snapshot = getOptions().isSnapshot();
    if (snapshot != null && snapshot) {
        throw new IllegalArgumentException("Transactions are not supported in snapshot sessions");
    }
    notNull("transactionOptions", transactionOptions);
    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 44 with WriteConcern

use of com.mongodb.WriteConcern 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 45 with WriteConcern

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

the class MixedBulkWriteOperation method execute.

/**
 * Executes a bulk write operation.
 *
 * @param binding the WriteBinding        for the operation
 * @return the bulk write result.
 * @throws MongoBulkWriteException if a failure to complete the bulk write is detected based on the server response
 */
@Override
public BulkWriteResult execute(final WriteBinding binding) {
    /* We cannot use the tracking of attempts built in the `RetryState` class because conceptually we have to maintain multiple attempt
         * counters while executing a single bulk write operation:
         * - a counter that limits attempts to select server and checkout a connection before we created a batch;
         * - a counter per each batch that limits attempts to execute the specific batch.
         * Fortunately, these counters do not exist concurrently with each other. While maintaining the counters manually,
         * we must adhere to the contract of `RetryingSyncSupplier`. When the retry timeout is implemented, there will be no counters,
         * and the code related to the attempt tracking in `BulkWriteTracker` will be removed. */
    RetryState retryState = new RetryState();
    BulkWriteTracker.attachNew(retryState, retryWrites);
    Supplier<BulkWriteResult> retryingBulkWrite = decorateWriteWithRetries(retryState, () -> {
        logRetryExecute(retryState);
        return withSourceAndConnection(binding::getWriteConnectionSource, true, (source, connection) -> {
            ConnectionDescription connectionDescription = connection.getDescription();
            int maxWireVersion = connectionDescription.getMaxWireVersion();
            // attach `maxWireVersion` ASAP because it is used to check whether we can retry
            retryState.attach(AttachmentKeys.maxWireVersion(), maxWireVersion, true);
            BulkWriteTracker bulkWriteTracker = retryState.attachment(AttachmentKeys.bulkWriteTracker()).orElseThrow(Assertions::fail);
            SessionContext sessionContext = binding.getSessionContext();
            WriteConcern writeConcern = getAppliedWriteConcern(sessionContext);
            if (!retryState.isFirstAttempt() && !isRetryableWrite(retryWrites, writeConcern, source.getServerDescription(), connectionDescription, sessionContext)) {
                RuntimeException prospectiveFailedResult = (RuntimeException) retryState.exception().orElse(null);
                retryState.breakAndThrowIfRetryAnd(() -> !(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException));
                bulkWriteTracker.batch().ifPresent(bulkWriteBatch -> {
                    assertTrue(prospectiveFailedResult instanceof MongoWriteConcernWithResponseException);
                    bulkWriteBatch.addResult((BsonDocument) ((MongoWriteConcernWithResponseException) prospectiveFailedResult).getResponse());
                    BulkWriteTracker.attachNext(retryState, bulkWriteBatch);
                });
            }
            validateWriteRequests(connectionDescription, bypassDocumentValidation, writeRequests, writeConcern);
            if (writeConcern.isAcknowledged() || serverIsAtLeastVersionThreeDotSix(connectionDescription)) {
                if (!bulkWriteTracker.batch().isPresent()) {
                    BulkWriteTracker.attachNew(retryState, BulkWriteBatch.createBulkWriteBatch(namespace, source.getServerDescription(), connectionDescription, ordered, writeConcern, bypassDocumentValidation, retryWrites, writeRequests, sessionContext));
                }
                logRetryExecute(retryState);
                return executeBulkWriteBatch(retryState, binding, connection, maxWireVersion);
            } else {
                retryState.markAsLastAttempt();
                return executeLegacyBatches(binding, connection);
            }
        });
    });
    try {
        return retryingBulkWrite.get();
    } catch (MongoException e) {
        throw transformWriteException(e);
    }
}
Also used : MongoException(com.mongodb.MongoException) Assertions(com.mongodb.assertions.Assertions) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) ConnectionDescription(com.mongodb.connection.ConnectionDescription) MongoWriteConcernWithResponseException(com.mongodb.internal.connection.MongoWriteConcernWithResponseException) WriteConcern(com.mongodb.WriteConcern) SessionContext(com.mongodb.internal.session.SessionContext) RetryState(com.mongodb.internal.async.function.RetryState)

Aggregations

WriteConcern (com.mongodb.WriteConcern)53 Document (org.bson.Document)14 MongoException (com.mongodb.MongoException)11 List (java.util.List)11 ArrayList (java.util.ArrayList)9 ReadPreference (com.mongodb.ReadPreference)8 Map (java.util.Map)8 Collectors (java.util.stream.Collectors)8 TimeUnit (java.util.concurrent.TimeUnit)7 BsonDocument (org.bson.BsonDocument)7 DeleteResult (com.mongodb.client.result.DeleteResult)6 HashMap (java.util.HashMap)6 ClientSessionOptions (com.mongodb.ClientSessionOptions)5 ReadConcern (com.mongodb.ReadConcern)5 Arrays (java.util.Arrays)5 BsonValue (org.bson.BsonValue)5 FullDocument (com.mongodb.client.model.changestream.FullDocument)4 InsertOneResult (com.mongodb.client.result.InsertOneResult)4 MongoClient (com.mongodb.reactivestreams.client.MongoClient)4 MongoCollection (com.mongodb.reactivestreams.client.MongoCollection)4