Search in sources :

Example 16 with MongoClientException

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

the class BulkWriteBatch method createBulkWriteBatch.

static BulkWriteBatch createBulkWriteBatch(final MongoNamespace namespace, final ServerDescription serverDescription, final ConnectionDescription connectionDescription, final boolean ordered, final WriteConcern writeConcern, final Boolean bypassDocumentValidation, final boolean retryWrites, final List<? extends WriteRequest> writeRequests, final SessionContext sessionContext) {
    if (sessionContext.hasSession() && !sessionContext.isImplicitSession() && !sessionContext.hasActiveTransaction() && !writeConcern.isAcknowledged()) {
        throw new MongoClientException("Unacknowledged writes are not supported when using an explicit session");
    }
    boolean canRetryWrites = isRetryableWrite(retryWrites, writeConcern, serverDescription, connectionDescription, sessionContext);
    List<WriteRequestWithIndex> writeRequestsWithIndex = new ArrayList<WriteRequestWithIndex>();
    boolean writeRequestsAreRetryable = true;
    for (int i = 0; i < writeRequests.size(); i++) {
        WriteRequest writeRequest = writeRequests.get(i);
        writeRequestsAreRetryable = writeRequestsAreRetryable && isRetryable(writeRequest);
        writeRequestsWithIndex.add(new WriteRequestWithIndex(writeRequest, i));
    }
    if (canRetryWrites && !writeRequestsAreRetryable) {
        canRetryWrites = false;
        LOGGER.debug("retryWrites set but one or more writeRequests do not support retryable writes");
    }
    return new BulkWriteBatch(namespace, connectionDescription, ordered, writeConcern, bypassDocumentValidation, canRetryWrites, new BulkWriteBatchCombiner(connectionDescription.getServerAddress(), ordered, writeConcern), writeRequestsWithIndex, sessionContext);
}
Also used : MongoClientException(com.mongodb.MongoClientException) WriteRequestWithIndex(com.mongodb.internal.bulk.WriteRequestWithIndex) WriteRequest(com.mongodb.internal.bulk.WriteRequest) ArrayList(java.util.ArrayList) BulkWriteBatchCombiner(com.mongodb.internal.connection.BulkWriteBatchCombiner)

Example 17 with MongoClientException

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

the class CreateIndexesOperation method getCommand.

private BsonDocument getCommand(final ConnectionDescription description) {
    BsonDocument command = new BsonDocument("createIndexes", new BsonString(namespace.getCollectionName()));
    List<BsonDocument> values = new ArrayList<BsonDocument>();
    for (IndexRequest request : requests) {
        values.add(getIndex(request));
    }
    command.put("indexes", new BsonArray(values));
    putIfNotZero(command, "maxTimeMS", maxTimeMS);
    appendWriteConcernToCommand(writeConcern, command, description);
    if (commitQuorum != null) {
        if (serverIsAtLeastVersionFourDotFour(description)) {
            command.put("commitQuorum", commitQuorum.toBsonValue());
        } else {
            throw new MongoClientException("Specifying a value for the create index commit quorum option " + "requires a minimum MongoDB version of 4.4");
        }
    }
    return command;
}
Also used : BsonDocument(org.bson.BsonDocument) MongoClientException(com.mongodb.MongoClientException) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) ArrayList(java.util.ArrayList) IndexRequest(com.mongodb.internal.bulk.IndexRequest)

Example 18 with MongoClientException

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

the class InitialDnsSeedlistDiscoveryTest method shouldResolveTxtRecord.

@Test
public void shouldResolveTxtRecord() throws InterruptedException {
    if (isError) {
        MongoClient client = null;
        try {
            final AtomicReference<MongoException> exceptionReference = new AtomicReference<MongoException>();
            final CountDownLatch latch = new CountDownLatch(1);
            ConnectionString connectionString;
            MongoClientSettings settings;
            try {
                connectionString = new ConnectionString(uri);
                final SslSettings sslSettings = getSslSettings(connectionString);
                assumeTrue("SSL settings don't match", getSslSettings().isEnabled() == sslSettings.isEnabled());
                settings = MongoClientSettings.builder().applyConnectionString(connectionString).applyToSslSettings(new Block<SslSettings.Builder>() {

                    @Override
                    public void apply(final SslSettings.Builder builder) {
                        builder.applySettings(sslSettings);
                        builder.invalidHostNameAllowed(true);
                    }
                }).applyToClusterSettings(new Block<ClusterSettings.Builder>() {

                    @Override
                    public void apply(final ClusterSettings.Builder builder) {
                        builder.serverSelectionTimeout(5, TimeUnit.SECONDS);
                        builder.addClusterListener(new ClusterListener() {

                            @Override
                            public void clusterDescriptionChanged(final ClusterDescriptionChangedEvent event) {
                                if (event.getNewDescription().getSrvResolutionException() != null) {
                                    exceptionReference.set(event.getNewDescription().getSrvResolutionException());
                                    latch.countDown();
                                }
                            }
                        });
                    }
                }).build();
            } catch (MongoClientException | IllegalArgumentException e) {
                // all good
                return;
            }
            client = createMongoClient(settings);
            // Instead we just try to execute an operation and assert that it throws
            if (settings.getClusterSettings().getMode() == ClusterConnectionMode.LOAD_BALANCED) {
                try {
                    client.getDatabase("admin").runCommand(new Document("ping", 1));
                } catch (MongoClientException e) {
                // all good
                }
            } else {
                if (!latch.await(5, TimeUnit.SECONDS)) {
                    fail("Failed to capture SRV resolution exception");
                }
                try {
                    throw exceptionReference.get();
                } catch (MongoClientException e) {
                // all good
                }
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
    } else {
        ConnectionString connectionString = new ConnectionString(this.uri);
        for (Map.Entry<String, BsonValue> entry : options.entrySet()) {
            if (entry.getKey().equals("replicaSet")) {
                assertEquals(entry.getValue().asString().getValue(), connectionString.getRequiredReplicaSetName());
            } else if (entry.getKey().equals("ssl")) {
                assertEquals(entry.getValue().asBoolean().getValue(), connectionString.getSslEnabled());
            } else if (entry.getKey().equals("authSource")) {
                // ignoring authSource for now, because without at least a userName also in the connection string,
                // the authSource is ignored.  If the test gets this far, at least we know that a TXT record
                // containing in authSource doesn't blow up.  We just don't test that it's actually used.
                assertTrue(true);
            } else if (entry.getKey().equals("directConnection")) {
                assertEquals(entry.getValue().asBoolean().getValue(), connectionString.isDirectConnection());
            } else if (entry.getKey().equals("loadBalanced")) {
                assertEquals(entry.getValue().asBoolean().getValue(), connectionString.isLoadBalanced());
            } else if (entry.getKey().equals("srvMaxHosts")) {
                assertEquals(Integer.valueOf(entry.getValue().asInt32().getValue()), connectionString.getSrvMaxHosts());
            } else if (entry.getKey().equals("srvServiceName")) {
                assertEquals(entry.getValue().asString().getValue(), connectionString.getSrvServiceName());
            } else {
                throw new UnsupportedOperationException("No support configured yet for " + entry.getKey());
            }
        }
    }
}
Also used : ClusterSettings(com.mongodb.connection.ClusterSettings) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) MongoException(com.mongodb.MongoException) MongoClientException(com.mongodb.MongoClientException) AtomicReference(java.util.concurrent.atomic.AtomicReference) MongoClientSettings(com.mongodb.MongoClientSettings) CountDownLatch(java.util.concurrent.CountDownLatch) ClusterFixture.getSslSettings(com.mongodb.ClusterFixture.getSslSettings) SslSettings(com.mongodb.connection.SslSettings) ClusterDescriptionChangedEvent(com.mongodb.event.ClusterDescriptionChangedEvent) ClusterListener(com.mongodb.event.ClusterListener) Block(com.mongodb.Block) ConnectionString(com.mongodb.ConnectionString) Map(java.util.Map) BsonValue(org.bson.BsonValue) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 19 with MongoClientException

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

the class ErrorMatcher method assertErrorsMatch.

void assertErrorsMatch(final BsonDocument expectedError, final Exception e) {
    context.push(ContextElement.ofError(expectedError, e));
    assertTrue(context.getMessage("Unexpected field in expectError.  One of " + expectedError.keySet()), EXPECTED_ERROR_FIELDS.containsAll(expectedError.keySet()));
    if (expectedError.containsKey("isError")) {
        assertTrue(context.getMessage("isError must be true"), expectedError.getBoolean("isError").getValue());
    }
    if (expectedError.containsKey("isClientError")) {
        assertEquals(context.getMessage("Exception must be of type MongoClientException or IllegalArgumentException" + " or IllegalStateException or MongoSocketException"), expectedError.getBoolean("isClientError").getValue(), e instanceof MongoClientException || e instanceof IllegalArgumentException || e instanceof IllegalStateException || e instanceof MongoSocketException);
    }
    if (expectedError.containsKey("errorContains")) {
        String errorContains = expectedError.getString("errorContains").getValue();
        assertTrue(context.getMessage("Error message does not contain expected string: " + errorContains), e.getMessage().contains(errorContains));
    }
    if (expectedError.containsKey("errorCode")) {
        assertTrue(context.getMessage("Exception must be of type MongoCommandException or MongoQueryException when checking" + " for error codes"), e instanceof MongoCommandException || e instanceof MongoQueryException);
        int errorCode = (e instanceof MongoCommandException) ? ((MongoCommandException) e).getErrorCode() : ((MongoQueryException) e).getErrorCode();
        assertEquals(context.getMessage("Error codes must match"), expectedError.getNumber("errorCode").intValue(), errorCode);
    }
    if (expectedError.containsKey("errorCodeName")) {
        assertTrue(context.getMessage("Exception must be of type MongoCommandException when checking for error codes"), e instanceof MongoCommandException);
        MongoCommandException mongoCommandException = (MongoCommandException) e;
        assertEquals(context.getMessage("Error code names must match"), expectedError.getString("errorCodeName").getValue(), mongoCommandException.getErrorCodeName());
    }
    if (expectedError.containsKey("errorLabelsOmit")) {
        assertTrue(context.getMessage("Exception must be of type MongoException when checking for error labels"), e instanceof MongoException);
        MongoException mongoException = (MongoException) e;
        for (BsonValue cur : expectedError.getArray("errorLabelsOmit")) {
            assertFalse(context.getMessage("Expected error label to be omitted but it is not: " + cur.asString().getValue()), mongoException.hasErrorLabel(cur.asString().getValue()));
        }
    }
    if (expectedError.containsKey("errorLabelsContain")) {
        assertTrue(context.getMessage("Exception must be of type MongoException when checking for error labels"), e instanceof MongoException);
        MongoException mongoException = (MongoException) e;
        for (BsonValue cur : expectedError.getArray("errorLabelsContain")) {
            assertTrue(context.getMessage("Expected error label: " + cur.asString().getValue()), mongoException.hasErrorLabel(cur.asString().getValue()));
        }
    }
    if (expectedError.containsKey("expectResult")) {
        // MongoBulkWriteException does not include information about the successful writes, so this is the only check
        // that can currently be done
        assertTrue(context.getMessage("Exception must be of type MongoBulkWriteException when checking for results"), e instanceof MongoBulkWriteException);
    }
    context.pop();
}
Also used : MongoException(com.mongodb.MongoException) MongoClientException(com.mongodb.MongoClientException) MongoCommandException(com.mongodb.MongoCommandException) MongoSocketException(com.mongodb.MongoSocketException) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) MongoQueryException(com.mongodb.MongoQueryException) BsonValue(org.bson.BsonValue)

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