@Override public void create(final Entity entity) throws EntityStorageException { requireNonNull(entity); try { final boolean hasDuplicate = detectDuplicates(entity); if (!hasDuplicate) { mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .insertOne( ENTITY_CONVERTER.toDocument(entity) ); } else { throw new EntityNearDuplicateException("Duplicate data found and will not be inserted for Entity with Subject: " + entity); } } catch(final MongoException e) { final ErrorCategory category = ErrorCategory.fromErrorCode( e.getCode() ); if(category == ErrorCategory.DUPLICATE_KEY) { throw new EntityAlreadyExistsException("Failed to create Entity with Subject '" + entity.getSubject().getData() + "'.", e); } throw new EntityStorageException("Failed to create Entity with Subject '" + entity.getSubject().getData() + "'.", e); } }
@Override public void create(final Event event) throws EventStorageException { requireNonNull(event); try { mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .insertOne(EVENT_CONVERTER.toDocument(event)); } catch(final MongoException e) { final ErrorCategory category = ErrorCategory.fromErrorCode( e.getCode() ); if(category == ErrorCategory.DUPLICATE_KEY) { throw new EventAlreadyExistsException("Failed to create Event with Subject '" + event.getSubject().getData() + "'.", e); } throw new EventStorageException("Failed to create Event with Subject '" + event.getSubject().getData() + "'.", e); } }
public boolean acquireLock(MongoDatabase db) { Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD"); // acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held) // there will be an exception try { db.getCollection(lockCollectionName).insertOne(insertObj); } catch (MongoWriteException ex) { if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired."); } return false; } return true; }
@ManagedOperation(description = "Adds the key to the store") @Override public boolean add(E key) { Document document = new Document("_id", key); try { collection.insertOne(document); } catch (com.mongodb.MongoWriteException ex) { if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { return false; } throw ex; } return true; }