本文整理汇总了Java中com.mongodb.DuplicateKeyException类的典型用法代码示例。如果您正苦于以下问题:Java DuplicateKeyException类的具体用法?Java DuplicateKeyException怎么用?Java DuplicateKeyException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DuplicateKeyException类属于com.mongodb包,在下文中一共展示了DuplicateKeyException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: duplicateKeyUpsertSameKeyDifferentVersions
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
/**
* When upsert is requested on different versions but same ID there should be duplicate
* key exception thrown by Mongo since there will be an attempt to insert new document (same id
* different version)
* Based on criteria it is a new document, based on primary key ({@code _id}) it exists already.
*/
@Test
public void duplicateKeyUpsertSameKeyDifferentVersions() throws Exception {
ImmutableEntity entity = ImmutableEntity.builder().id("e1").version(0).value("v0").build();
repository.upsert(entity).getUnchecked();
// first upsert successful (document should be with new version)
repository.find(repository.criteria().id(entity.id()).version(0))
.andReplaceFirst(entity.withVersion(1))
.upsert()
.getUnchecked();
try {
// this should fail because here upsert == insert (document e1 with version 0 doesn't exist)
repository.find(repository.criteria().id(entity.id()).version(0))
.andReplaceFirst(entity.withVersion(1))
.upsert()
.getUnchecked();
fail("Should fail with " + DuplicateKeyException.class.getName());
} catch (Exception e) {
MongoAsserts.assertDuplicateKeyException(e);
}
}
示例2: add
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Override
public boolean add(List<JobFeedbackPo> jobFeedbackPos) {
if (CollectionUtils.isEmpty(jobFeedbackPos)) {
return true;
}
for (JobFeedbackPo jobFeedbackPo : jobFeedbackPos) {
String tableName = JobQueueUtils.getFeedbackQueueName(
jobFeedbackPo.getTaskTrackerJobResult().getJobWrapper().getJob().getSubmitNodeGroup());
try {
template.save(tableName, jobFeedbackPo);
} catch (DuplicateKeyException e) {
LOGGER.warn("duplicate key for job feedback po: " + JSON.toJSONString(jobFeedbackPo));
}
}
return true;
}
示例3: add
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Override
public boolean add(JobPo jobPo) {
try {
String tableName = JobQueueUtils.getExecutableQueueName(jobPo.getTaskTrackerNodeGroup());
if (!EXIST_TABLE.contains(tableName)) {
createQueue(jobPo.getTaskTrackerNodeGroup());
}
jobPo.setGmtCreated(SystemClock.now());
jobPo.setGmtModified(jobPo.getGmtCreated());
template.save(tableName, jobPo);
} catch (DuplicateKeyException e) {
// 已经存在
throw new DupEntryException(e);
}
return true;
}
示例4: uniqueness
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
/**
* Check the uniqueness constraint.
*/
@Test
public void uniqueness() {
WorkerEntity worker1 = new WorkerEntity().setFirstname("Philipp").setSurname("Krenn")
.setEmail("[email protected]");
persistence.persistWorkerEntity(worker1);
try {
WorkerEntity worker2 = new WorkerEntity().setFirstname("Paul").setSurname("Kaufmann")
.setEmail("[email protected]");
persistence.persistWorkerEntity(worker2);
fail("A duplicate key exception should be thrown");
} catch (DuplicateKeyException e) {
}
assertEquals(
"When adding a second user with the same email address, the first one should be preserved",
"Philipp", persistence.getAllEmployees().get(0).getFirstname());
}
示例5: acquire
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
/**
* Attempts to insert a lock record to the db
*
* @returns true if successful, false if lock already exists. Any other case
* would be an exception.
*/
private boolean acquire(String callerId, String resourceId, Long ttl, Date now, Date expiration) {
BasicDBObject update = new BasicDBObject().
append(CALLERID, callerId).
append(RESOURCEID, resourceId).
append(TIMESTAMP, now).
append(TTL, ttl).
append(EXPIRATION, expiration).
append(COUNT, 1).
append(VERSION, 1);
try {
LOGGER.debug("insert: {}", update);
coll.insert(update, WriteConcern.ACKNOWLEDGED);
} catch (DuplicateKeyException dke) {
return false;
}
return true;
}
示例6: saveBlob
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Override
public void saveBlob(final MD5 md5, final InputStream data,
final boolean sorted)
throws BlobStoreCommunicationException {
if(data == null || md5 == null) {
throw new NullPointerException("Arguments cannot be null");
}
if (getFile(md5) != null) {
return; //already exists
}
final GridFSInputFile gif = gfs.createFile(data, true);
gif.setId(md5.getMD5());
gif.setFilename(md5.getMD5());
gif.put(Fields.GFS_SORTED, sorted);
try {
gif.save();
} catch (DuplicateKeyException dk) {
// already here, done
} catch (MongoException me) {
throw new BlobStoreCommunicationException(
"Could not write to the mongo database", me);
}
}
示例7: renameWorkspace
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Override
public Instant renameWorkspace(final ResolvedWorkspaceID rwsi, final String newname)
throws WorkspaceCommunicationException, CorruptWorkspaceDBException {
if (newname.equals(rwsi.getName())) {
throw new IllegalArgumentException("Workspace is already named " +
newname);
}
final Instant now = Instant.now();
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_WS_ID_QRY, rwsi.getID())
.with(M_RENAME_WS_WTH, newname, Date.from(now));
} catch (DuplicateKeyException medk) {
throw new IllegalArgumentException(
"There is already a workspace named " + newname);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return now;
}
示例8: createNewUser
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public void createNewUser(UserData data)
{
BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start()
.add(FIELD_RANDOMIZER, data.getRandomizer())
.add(FIELD_USERNAME, data.getUsername())
.add(FIELD_PASSWORD, data.getPassword())
.add(FIELD_CREATION_STATE, data.getCreationState().toString())
.add(FIELD_FIRST_NAME, data.getFirstName())
.add(FIELD_LAST_NAME, data.getLastName())
.add(FIELD_EMAIL, data.getEmail())
.add(FIELD_DOMAIN, data.getDomain())
.add(FIELD_GROUPS, data.getGroups());
DBObject insertObj = insertObjBuilder.get();
try
{
collection.insert(insertObj);
}
catch (DuplicateKeyException e)
{
// We just rethrow as per the API
throw e;
}
}
示例9: createNewFolder
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
/**
* Create a new folder entry with the given data
*/
public void createNewFolder(FolderData data)
{
BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start()
.add(FIELD_ID, data.getId())
.add(FIELD_CONTEXT, data.getContext())
.add(FIELD_PATH, data.getPath())
.add(FIELD_LEVEL, data.getLevel())
.add(FIELD_PARENT_PATH, data.getParentPath())
.add(FIELD_NAME, data.getName())
.add(FIELD_FOLDER_COUNT, data.getFolderCount())
.add(FIELD_FILE_COUNT, data.getFileCount());
DBObject insertObj = insertObjBuilder.get();
try
{
collection.insert(insertObj);
}
catch (DuplicateKeyException e)
{
// We just rethrow as per the API
throw e;
}
}
示例10: testDuplicateUsername
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Test
public void testDuplicateUsername()
{
UserData user = createUserData("testDuplicateUsername" + System.nanoTime());
userDataService.createNewUser(user);
UserData userDup = createUserData("testDuplicateUsername" + System.nanoTime());
userDup.setUsername(user.getUsername());
// This should fail
try
{
userDataService.createNewUser(userDup);
Assert.fail("Should fail due to duplicate username.");
}
catch (DuplicateKeyException e)
{
// Expected
}
}
示例11: testDuplicateEmail
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Test
public void testDuplicateEmail()
{
UserData user = createUserData("testDuplicateEmail" + System.nanoTime());
userDataService.createNewUser(user);
UserData userDup = createUserData("testDuplicateEmail" + System.nanoTime());
userDup.setEmail(user.getEmail());
// This should fail
try
{
userDataService.createNewUser(userDup);
Assert.fail("Should fail due to duplicate email.");
}
catch (DuplicateKeyException e)
{
// Expected
}
}
示例12: create
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Override
public SmartiUser create(SmartiUser user) {
try {
mongoTemplate.insert(user);
return mongoTemplate.findById(user.getLogin(), SmartiUser.class);
} catch (DuplicateKeyException e) {
return null;
}
}
示例13: save
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
public Client save(Client client) {
if(client.getId() != null) {
Client client_old = clientRepository.findOne(client.getId());
if(client_old == null) {
throw new ConflictException(Client.class, "id", "New clients may not have an id set");
}
if(!client_old.getName().equals(client.getName())) {
validateClientName(client);
}
} else {
if(!isProperClientName(client.getName())) {
throw new IllegalArgumentException("Client name must match pattern: " + NAME_PATTERN);
}
}
if(client.isDefaultClient()) {
clientRepository.save(clientRepository.findByDefaultClientTrue().stream().map(
c -> {
c.setDefaultClient(false);
return c;
}
).collect(Collectors.toList()));
}
//save the client
client.setLastUpdate(new Date());
try {
client = clientRepository.save(client);
} catch (DuplicateKeyException | org.springframework.dao.DuplicateKeyException e) {
throw new ConflictException(Client.class, "name", "A Client with the name '" + client.getName() + "' already exists!");
}
//init the client configuration
initClientConfiguration(client);
return client;
}
示例14: save
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
@Override
public V save(V entity) {
prePersist(entity);
try {
morphiaDao.save(entity);
} catch (DuplicateKeyException e) {
throw new RestDslException("Duplicate mongo key: " + e.getMessage(), RestDslException.Type.DUPLICATE_KEY);
}
return entity;
}
示例15: findAndModify
import com.mongodb.DuplicateKeyException; //导入依赖的package包/类
protected V findAndModify(ServiceQuery<K> q, UpdateOperations<V> updateOperations, boolean oldVersion, boolean createIfMissing) throws RestDslException {
preUpdate(q, updateOperations);
Query<V> morphiaQuery = convertToMorphiaQuery(q, false);
try {
return morphiaDao.getDatastore().findAndModify(morphiaQuery, updateOperations, oldVersion, createIfMissing);
} catch (DuplicateKeyException e) {
throw new RestDslException("Duplicate mongo key: " + e.getMessage(), RestDslException.Type.DUPLICATE_KEY);
}
}