Java 类com.mongodb.MongoCommandException 实例源码

项目:alfresco-benchmark    文件:MongoResultService.java   
/**
 * Construct a test result provider against a Mongo database and given collection name
 */
public MongoResultService(DB db, String collection)
{
    try
    {
        this.collection = db.createCollection(collection, new BasicDBObject());
        checkIndexes = true;
    }
    catch (MongoCommandException e)
    {
        if (!db.collectionExists(collection))
        {
            // The collection is really not there
            throw e;
        }
        // Someone else created it
        this.collection = db.getCollection(collection);
        this.checkIndexes = false;
    }
}
项目:ShedLock    文件:MongoLockProvider.java   
@Override
public boolean insertRecord(LockConfiguration lockConfiguration) {
    Bson update = combine(
        setOnInsert(LOCK_UNTIL, Date.from(lockConfiguration.getLockAtMostUntil())),
        setOnInsert(LOCKED_AT, now()),
        setOnInsert(LOCKED_BY, hostname)
    );
    try {
        Document result = getCollection().findOneAndUpdate(
            eq(ID, lockConfiguration.getName()),
            update,
            new FindOneAndUpdateOptions().upsert(true)
        );
        return result == null;
    } catch (MongoCommandException e) {
        if (e.getErrorCode() == 11000) { // duplicate key
            // this should not normally happen, but it happened once in tests
            return false;
        } else {
            throw e;
        }

    }
}
项目:alfresco-benchmark    文件:DataReportServiceImpl.java   
/**
 * Constructor
 * 
 * @param db
 *            (DB, required) the database to use
 */
public DataReportServiceImpl(DB db)
{
    if (null == db)
    {
        throw new IllegalArgumentException("'db' is mandatory!");
    }
    try
    {
        // create collection with no options
        this.collectionExtraData = db.createCollection(COLLECTION_EXTRA_DATA, null);
        this.collectionDescription = db.createCollection(COLLECTION_EXTRA_DATA_DESCRIPTION, null);
    }
    catch (MongoCommandException e)
    {
        // try to get collection anyway - if not there, re-throw
        if (!db.collectionExists(COLLECTION_EXTRA_DATA) || !db.collectionExists(COLLECTION_EXTRA_DATA_DESCRIPTION))
        {
            throw e;
        }

        this.collectionExtraData = db.getCollection(COLLECTION_EXTRA_DATA);
        this.collectionDescription = db.getCollection(COLLECTION_EXTRA_DATA_DESCRIPTION);
    }
}
项目:morphia    文件:TestDocumentValidation.java   
@Test
public void findAndModify() {
    getMorphia().map(DocumentValidation.class);
    getDs().enableDocumentValidation();

    getDs().save(new DocumentValidation("Harold", 100, new Date()));

    Query<DocumentValidation> query = getDs().find(DocumentValidation.class);
    UpdateOperations<DocumentValidation> updates = getDs().createUpdateOperations(DocumentValidation.class)
                                                          .set("number", 5);
    FindAndModifyOptions options = new FindAndModifyOptions()
        .bypassDocumentValidation(false);
    try {
        getDs().findAndModify(query, updates, options);
        fail("Document validation should have complained");
    } catch (MongoCommandException e) {
        // expected
    }

    options.bypassDocumentValidation(true);
    getDs().findAndModify(query, updates, options);

    Assert.assertNotNull(query.field("number").equal(5).get());
}
项目:boteco    文件:MongoRequestRepository.java   
public MongoRequestRepository(MongoDatabase database, Long minutesToExpire) {
  this.requests = database.getCollection("requests");
  try {
    this.requests.dropIndex("createdAt_1");
    logger.info("Dropped index 'createdAt', creating a new one.");
  } catch (MongoCommandException e) {
    logger.info("Index for 'createdAt' doesn't exist, creating index.");
  }
  this.requests.createIndex(new Document("createdAt", 1),
      new IndexOptions().expireAfter(minutesToExpire, TimeUnit.MINUTES));
  this.gson = new Gson();
}
项目:mongo-java-driver-rx    文件:Fixture.java   
public static MongoCollection<Document> initializeCollection(final MongoNamespace namespace) throws Throwable {
    MongoDatabase database = getMongoClient().getDatabase(namespace.getDatabaseName());
    try {
        database.runCommand(new Document("drop", namespace.getCollectionName())).timeout(10, SECONDS).toBlocking().first();
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().startsWith("ns not found")) {
            throw e;
        }
    }
    return database.getCollection(namespace.getCollectionName());
}
项目:mongo-java-driver-rx    文件:Fixture.java   
public static void dropDatabase(final String name) throws Throwable {
    if (name == null) {
        return;
    }
    try {
        getMongoClient().getDatabase(name).runCommand(new Document("dropDatabase", 1)).timeout(10, SECONDS).toBlocking().first();
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().startsWith("ns not found")) {
            throw e;
        }
    }
}
项目:mongo-java-driver-rx    文件:Fixture.java   
public static void drop(final MongoNamespace namespace) throws Throwable {
    try {
        getMongoClient().getDatabase(namespace.getDatabaseName())
                .runCommand(new Document("drop", namespace.getCollectionName())).timeout(10, SECONDS).toBlocking().first();
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().contains("ns not found")) {
            throw e;
        }
    }
}
项目:mongo-java-driver-reactivestreams    文件:Fixture.java   
public static MongoCollection<Document> initializeCollection(final MongoNamespace namespace) throws Throwable {
    MongoDatabase database = getMongoClient().getDatabase(namespace.getDatabaseName());
    try {
        RxReactiveStreams.toObservable(database.runCommand(new Document("drop", namespace.getCollectionName())))
                .timeout(10, SECONDS).toBlocking().toIterable();
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().startsWith("ns not found")) {
            throw e;
        }
    }
    return database.getCollection(namespace.getCollectionName());
}
项目:mongo-java-driver-reactivestreams    文件:Fixture.java   
public static void dropDatabase(final String name) throws Throwable {
    if (name == null) {
        return;
    }
    try {
        RxReactiveStreams.toObservable(getMongoClient().getDatabase(name).runCommand(new Document("dropDatabase", 1)))
                .timeout(10, SECONDS).toBlocking().toIterable();
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().startsWith("ns not found")) {
            throw e;
        }
    }
}
项目:mongo-java-driver-reactivestreams    文件:Fixture.java   
public static void drop(final MongoNamespace namespace) throws Throwable {
    try {
        RxReactiveStreams.toObservable(getMongoClient().getDatabase(namespace.getDatabaseName())
                .runCommand(new Document("drop", namespace.getCollectionName()))).timeout(10, SECONDS).toBlocking().toIterable();
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().contains("ns not found")) {
            throw e;
        }
    }
}
项目:mongo-java-driver-reactivestreams    文件:Fixture.java   
public static MongoCollection<Document> initializeCollection(final MongoNamespace namespace) throws Throwable {
    MongoDatabase database = getMongoClient().getDatabase(namespace.getDatabaseName());
    try {
        ObservableSubscriber<Document> subscriber = new ObservableSubscriber<Document>();
        database.runCommand(new Document("drop", namespace.getCollectionName())).subscribe(subscriber);
        subscriber.await(10, SECONDS);
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().startsWith("ns not found")) {
            throw e;
        }
    }
    return database.getCollection(namespace.getCollectionName());
}
项目:mongo-java-driver-reactivestreams    文件:Fixture.java   
public static void dropDatabase(final String name) throws Throwable {
    if (name == null) {
        return;
    }
    try {
        ObservableSubscriber<Document> subscriber = new ObservableSubscriber<Document>();
        getMongoClient().getDatabase(name).runCommand(new Document("dropDatabase", 1)).subscribe(subscriber);
        subscriber.await(10, SECONDS);
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().startsWith("ns not found")) {
            throw e;
        }
    }
}
项目:mongo-java-driver-reactivestreams    文件:Fixture.java   
public static void drop(final MongoNamespace namespace) throws Throwable {
    try {
        ObservableSubscriber<Document> subscriber = new ObservableSubscriber<Document>();
        getMongoClient().getDatabase(namespace.getDatabaseName())
                .runCommand(new Document("drop", namespace.getCollectionName()))
                .subscribe(subscriber);
        subscriber.await(20, SECONDS);
    } catch (MongoCommandException e) {
        if (!e.getErrorMessage().contains("ns not found")) {
            throw e;
        }
    }
}
项目:immutables    文件:MongoAsserts.java   
/**
 * Ensures current exception has been generated due to a duplicate (primary) key.
 * Differentiates between Fongo and Mongo exceptions since the behaviour under these databases
 * is different.
 */
public static void assertDuplicateKeyException(Throwable exception) {
  Preconditions.checkNotNull(exception, "exception");

  // unwrap, if necessary
  exception = exception instanceof MongoException ? exception : exception.getCause();

  // fongo throws directly DuplicateKeyException
  if (exception instanceof DuplicateKeyException) return;

  // MongoDB throws custom exception
  if (exception instanceof MongoCommandException) {
    String codeName = ((MongoCommandException) exception).getResponse().get("codeName").asString().getValue();
    int errorCode = ((MongoCommandException) exception).getErrorCode();

    check(codeName).is("DuplicateKey");
    check(errorCode).is(11000);

    // all good here (can return)
    return;
  }

  // for bulk writes as well
  if (exception instanceof MongoBulkWriteException) {
    List<BulkWriteError> errors = ((MongoBulkWriteException) exception).getWriteErrors();
    check(errors).hasSize(1);
    check(errors.get(0).getCode()).is(11000);
    check(errors.get(0).getMessage()).contains("duplicate key");
    return;
  }

  // if we got here means there is a problem (no duplicate key exception)
  fail("Should get duplicate key exception after " + exception);
}
项目:morphia    文件:TestTextIndexing.java   
@Test(expected = MongoCommandException.class)
public void shouldNotAllowMultipleTextIndexes() {
    Class<MultipleTextIndexes> clazz = MultipleTextIndexes.class;
    getMorphia().map(clazz);
    getDs().getCollection(clazz).drop();
    getDs().ensureIndexes();
}
项目:morphia    文件:AggregationTest.java   
@Test
public void testBypassDocumentValidation() {
    checkMinServerVersion(3.2);
    getDs().save(asList(new User("john doe", new Date()), new User("John Doe", new Date())));

    MongoDatabase database = getMongoClient().getDatabase(TEST_DB_NAME);
    database.getCollection("out_users").drop();
    database.createCollection("out_users", new CreateCollectionOptions()
        .validationOptions(new ValidationOptions()
                               .validator(Document.parse("{ age : { gte : 13 } }"))));

    try {
        getDs()
            .createAggregation(User.class)
            .match(getDs().find(User.class).field("name").equal("john doe"))
            .out("out_users", User.class);
        fail("Document validation should have complained.");
    } catch (MongoCommandException e) {
        // expected
    }

    getDs()
        .createAggregation(User.class)
        .match(getDs().find(User.class).field("name").equal("john doe"))
        .out("out_users", User.class, builder()
            .bypassDocumentValidation(true)
            .build());

    Assert.assertEquals(1, getAds().find("out_users", User.class).count());
}
项目:morphia    文件:TestMapreduce.java   
@Test
public void testBypassDocumentValidation() {
    checkMinServerVersion(3.4);
    getDs().save(asList(new Book("The Banquet", "Dante", 2),
                        new Book("Divine Comedy", "Dante", 1),
                        new Book("Eclogues", "Dante", 2),
                        new Book("The Odyssey", "Homer", 10),
                        new Book("Iliad", "Homer", 10)));

    Document validator = Document.parse("{ count : { $gt : '10' } }");
    ValidationOptions validationOptions = new ValidationOptions()
        .validator(validator)
        .validationLevel(ValidationLevel.STRICT)
        .validationAction(ValidationAction.ERROR);
    MongoDatabase database = getMongoClient().getDatabase(TEST_DB_NAME);
    database.getCollection("counts").drop();
    database.createCollection("counts", new CreateCollectionOptions().validationOptions(validationOptions));


    final String map = "function () { emit(this.author, 1); return; }";
    final String reduce = "function (key, values) { return values.length }";

    MapReduceOptions<CountResult> options = new MapReduceOptions<CountResult>()
        .query(getDs().find(Book.class))
        .resultType(CountResult.class)
        .outputType(OutputType.REPLACE)
        .map(map)
        .reduce(reduce);
    try {
        getDs().mapReduce(options);
        fail("Document validation should have complained.");
    } catch (MongoCommandException e) {
        // expected
    }

    getDs().mapReduce(options.bypassDocumentValidation(true));
    Assert.assertEquals(2, count(getDs().find(CountResult.class).iterator()));
}
项目:GitHub    文件:MongoAsserts.java   
/**
 * Ensures current exception has been generated due to a duplicate (primary) key.
 * Differentiates between Fongo and Mongo exceptions since the behaviour under these databases
 * is different.
 */
public static void assertDuplicateKeyException(Throwable exception) {
  Preconditions.checkNotNull(exception, "exception");

  // unwrap, if necessary
  exception = exception instanceof MongoException ? exception : exception.getCause();

  // fongo throws directly DuplicateKeyException
  if (exception instanceof DuplicateKeyException) return;

  // MongoDB throws custom exception
  if (exception instanceof MongoCommandException) {
    String codeName = ((MongoCommandException) exception).getResponse().get("codeName").asString().getValue();
    int errorCode = ((MongoCommandException) exception).getErrorCode();

    check(codeName).is("DuplicateKey");
    check(errorCode).is(11000);

    // all good here (can return)
    return;
  }

  // for bulk writes as well
  if (exception instanceof MongoBulkWriteException) {
    List<BulkWriteError> errors = ((MongoBulkWriteException) exception).getWriteErrors();
    check(errors).hasSize(1);
    check(errors.get(0).getCode()).is(11000);
    check(errors.get(0).getMessage()).contains("duplicate key");
    return;
  }

  // if we got here means there is a problem (no duplicate key exception)
  fail("Should get duplicate key exception after " + exception);
}