Search in sources :

Example 1 with DuplicateKeyException

use of com.mongodb.DuplicateKeyException in project sling by apache.

the class MongoDBNoSqlAdapter method createIndexDefinitions.

@Override
public void createIndexDefinitions() {
    // create index on parent path field (if it does not exist yet)
    try {
        Document parenPathtIndex = new Document(PN_PARENT_PATH, 1);
        this.collection.createIndex(parenPathtIndex);
    } catch (DuplicateKeyException ex) {
    // index already exists, ignore
    } catch (Throwable ex) {
        log.error("Unable to create index on " + PN_PARENT_PATH + ": " + ex.getMessage(), ex);
    }
    // create unique index on path field (if it does not exist yet)
    try {
        Document pathIndex = new Document(PN_PATH, 1);
        IndexOptions idxOptions = new IndexOptions();
        idxOptions.unique(true);
        this.collection.createIndex(pathIndex, idxOptions);
    } catch (DuplicateKeyException ex) {
    // index already exists, ignore
    } catch (Throwable ex) {
        log.error("Unable to create unique index on " + PN_PATH + ": " + ex.getMessage(), ex);
    }
}
Also used : IndexOptions(com.mongodb.client.model.IndexOptions) Document(org.bson.Document) DuplicateKeyException(com.mongodb.DuplicateKeyException)

Example 2 with DuplicateKeyException

use of com.mongodb.DuplicateKeyException in project jackrabbit-oak by apache.

the class MongoBlobStore method storeBlock.

@Override
protected void storeBlock(byte[] digest, int level, byte[] data) throws IOException {
    String id = StringUtils.convertBytesToHex(digest);
    cache.put(id, data);
    // Check if it already exists?
    MongoBlob mongoBlob = new MongoBlob();
    mongoBlob.setId(id);
    mongoBlob.setData(data);
    mongoBlob.setLevel(level);
    mongoBlob.setLastMod(System.currentTimeMillis());
    // TODO verify insert is fast if the entry already exists
    try {
        getBlobCollection().insertOne(mongoBlob);
    } catch (DuplicateKeyException e) {
    // the same block was already stored before: ignore
    } catch (MongoException e) {
        if (e.getCode() == DUPLICATE_KEY_ERROR_CODE) {
        // the same block was already stored before: ignore
        } else {
            throw new IOException(e.getMessage(), e);
        }
    }
}
Also used : MongoException(com.mongodb.MongoException) IOException(java.io.IOException) DuplicateKeyException(com.mongodb.DuplicateKeyException)

Example 3 with DuplicateKeyException

use of com.mongodb.DuplicateKeyException in project graylog2-server by Graylog2.

the class V20190705071400_AddEventIndexSetsMigration method setupEventsIndexSet.

private IndexSet setupEventsIndexSet(String indexSetTitle, String indexSetDescription, String indexPrefix) {
    final Optional<IndexSetConfig> optionalIndexSetConfig = getEventsIndexSetConfig(indexPrefix);
    if (optionalIndexSetConfig.isPresent()) {
        return mongoIndexSetFactory.create(optionalIndexSetConfig.get());
    }
    final IndexSetConfig indexSetConfig = IndexSetConfig.builder().title(indexSetTitle).description(indexSetDescription).indexTemplateType(EVENT_TEMPLATE_TYPE).isWritable(true).isRegular(false).indexPrefix(indexPrefix).shards(elasticsearchConfiguration.getShards()).replicas(elasticsearchConfiguration.getReplicas()).rotationStrategyClass(TimeBasedRotationStrategy.class.getCanonicalName()).rotationStrategy(TimeBasedRotationStrategyConfig.create(Period.months(1), null)).retentionStrategyClass(DeletionRetentionStrategy.class.getCanonicalName()).retentionStrategy(DeletionRetentionStrategyConfig.create(12)).creationDate(ZonedDateTime.now(ZoneOffset.UTC)).indexAnalyzer(elasticsearchConfiguration.getAnalyzer()).indexTemplateName(indexPrefix + "-template").indexOptimizationMaxNumSegments(elasticsearchConfiguration.getIndexOptimizationMaxNumSegments()).indexOptimizationDisabled(elasticsearchConfiguration.isDisableIndexOptimization()).fieldTypeRefreshInterval(Duration.standardMinutes(1)).build();
    try {
        final Optional<IndexSetValidator.Violation> violation = indexSetValidator.validate(indexSetConfig);
        if (violation.isPresent()) {
            throw new RuntimeException(violation.get().message());
        }
        final IndexSetConfig savedIndexSet = indexSetService.save(indexSetConfig);
        LOG.info("Successfully created events index-set <{}/{}>", savedIndexSet.id(), savedIndexSet.title());
        return mongoIndexSetFactory.create(savedIndexSet);
    } catch (DuplicateKeyException e) {
        LOG.error("Couldn't create index-set <{}/{}>", indexSetTitle, indexPrefix);
        throw new RuntimeException(e.getMessage());
    }
}
Also used : DeletionRetentionStrategy(org.graylog2.indexer.retention.strategies.DeletionRetentionStrategy) IndexSetConfig(org.graylog2.indexer.indexset.IndexSetConfig) TimeBasedRotationStrategy(org.graylog2.indexer.rotation.strategies.TimeBasedRotationStrategy) DuplicateKeyException(com.mongodb.DuplicateKeyException)

Example 4 with DuplicateKeyException

use of com.mongodb.DuplicateKeyException in project graylog2-server by Graylog2.

the class LookupTableResource method createAdapter.

@POST
@Path("adapters")
@AuditEvent(type = AuditEventTypes.LOOKUP_ADAPTER_CREATE)
@ApiOperation(value = "Create a new data adapter")
@RequiresPermissions(RestPermissions.LOOKUP_TABLES_CREATE)
public DataAdapterApi createAdapter(@Valid @ApiParam DataAdapterApi newAdapter) {
    try {
        DataAdapterDto dto = newAdapter.toDto();
        DataAdapterDto saved = dbDataAdapterService.save(dto);
        return DataAdapterApi.fromDto(saved);
    } catch (DuplicateKeyException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : DataAdapterDto(org.graylog2.lookup.dto.DataAdapterDto) BadRequestException(javax.ws.rs.BadRequestException) DuplicateKeyException(com.mongodb.DuplicateKeyException) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) AuditEvent(org.graylog2.audit.jersey.AuditEvent)

Example 5 with DuplicateKeyException

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

the class ProtocolHelper method throwWriteException.

@SuppressWarnings("deprecation")
private static void throwWriteException(final BsonDocument result, final ServerAddress serverAddress) {
    MongoException specialException = createSpecialException(result, serverAddress, "err");
    if (specialException != null) {
        throw specialException;
    }
    int code = WriteConcernException.extractErrorCode(result);
    if (ErrorCategory.fromErrorCode(code) == ErrorCategory.DUPLICATE_KEY) {
        throw new DuplicateKeyException(result, serverAddress, createWriteResult(result));
    } else {
        throw new WriteConcernException(result, serverAddress, createWriteResult(result));
    }
}
Also used : MongoException(com.mongodb.MongoException) WriteConcernException(com.mongodb.WriteConcernException) DuplicateKeyException(com.mongodb.DuplicateKeyException)

Aggregations

DuplicateKeyException (com.mongodb.DuplicateKeyException)9 MongoException (com.mongodb.MongoException)4 BasicDBObject (com.mongodb.BasicDBObject)2 DBObject (com.mongodb.DBObject)2 ApiOperation (io.swagger.annotations.ApiOperation)2 IOException (java.io.IOException)2 BadRequestException (javax.ws.rs.BadRequestException)2 POST (javax.ws.rs.POST)2 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)2 AuditEvent (org.graylog2.audit.jersey.AuditEvent)2 IndexSetConfig (org.graylog2.indexer.indexset.IndexSetConfig)2 Timed (com.codahale.metrics.annotation.Timed)1 DBCollection (com.mongodb.DBCollection)1 MongoSocketException (com.mongodb.MongoSocketException)1 ServerAddress (com.mongodb.ServerAddress)1 WriteConcernException (com.mongodb.WriteConcernException)1 IndexOptions (com.mongodb.client.model.IndexOptions)1 FailedDBOperationException (edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException)1 RecordExistsException (edu.umass.cs.gnscommon.exceptions.server.RecordExistsException)1 RecordNotFoundException (edu.umass.cs.gnscommon.exceptions.server.RecordNotFoundException)1