当前位置: 首页>>代码示例>>Java>>正文


Java DuplicateKeyException类代码示例

本文整理汇总了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);
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:30,代码来源:SimpleReplacerTest.java

示例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;
}
 
开发者ID:WenZuHuai,项目名称:light-task-scheduler,代码行数:17,代码来源:MongoJobFeedbackQueue.java

示例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;
}
 
开发者ID:WenZuHuai,项目名称:light-task-scheduler,代码行数:17,代码来源:MongoExecutableJobQueue.java

示例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());
}
 
开发者ID:xeraa,项目名称:morphia-demo,代码行数:20,代码来源:PersistenceTest.java

示例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;
}
 
开发者ID:lightblue-platform,项目名称:lightblue-mongo,代码行数:25,代码来源:MongoLocking.java

示例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);
	}
}
 
开发者ID:kbase,项目名称:workspace_deluxe,代码行数:24,代码来源:GridFSBlobStore.java

示例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;
}
 
开发者ID:kbase,项目名称:workspace_deluxe,代码行数:22,代码来源:MongoWorkspaceDB.java

示例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;
    }
}
 
开发者ID:AlfrescoBenchmark,项目名称:alfresco-benchmark,代码行数:29,代码来源:UserDataServiceImpl.java

示例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;
    }
}
 
开发者ID:AlfrescoBenchmark,项目名称:alfresco-benchmark,代码行数:27,代码来源:FileFolderService.java

示例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
    }
}
 
开发者ID:AlfrescoBenchmark,项目名称:alfresco-benchmark,代码行数:19,代码来源:UserDataServiceTest.java

示例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
    }
}
 
开发者ID:AlfrescoBenchmark,项目名称:alfresco-benchmark,代码行数:19,代码来源:UserDataServiceTest.java

示例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;
    }
}
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:10,代码来源:UserRepositoryImpl.java

示例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;
    }
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:39,代码来源:ClientService.java

示例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;
}
 
开发者ID:researchgate,项目名称:restler,代码行数:11,代码来源:MongoServiceDao.java

示例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);
    }
}
 
开发者ID:researchgate,项目名称:restler,代码行数:10,代码来源:MongoServiceDao.java


注:本文中的com.mongodb.DuplicateKeyException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。