Java 类org.springframework.dao.DuplicateKeyException 实例源码

项目:SpaceInvasion-09-2017    文件:UserController.java   
@PostMapping(path = "signup")
public ResponseEntity<?> signUp(@RequestBody @Valid User user, HttpSession httpSession) {
    if (!checkUser(user)) {
        return TypicalResponses.BAD_REQUEST;
    }

    final Integer userId = (Integer) httpSession.getAttribute("user");
    if (userId != null) {
        User curUser = userService.getUser(userId);
        return ResponseEntity.badRequest().body(curUser); // Already authorized by curUser
    }
    try {
        user = userService.create(user);
    } catch (DuplicateKeyException e) {
        return TypicalResponses.USERNAME_ALREADY_USED_RESPONSE;
    }
    httpSession.setAttribute("user", user.getId());

    return ResponseEntity.ok(user);
}
项目:TITAN    文件:LinkController.java   
/**
 * @desc 新增链路
 *
 * @author liuliang
 *
 * @param linkBO 链路BO
 * @return Result
 */
@RequestMapping(value = "/add")
@ResponseBody
public Result add(@Validated(Groups.Add.class) LinkBO linkBO,BindingResult br){
    Result result = new Result();
    //参数校验
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //新增
    try {
        int addResult = linkService.addLink(linkBO);
        if(0 < addResult) {
            return ResultUtil.success(result);
        }
    } catch(DuplicateKeyException de){
        logger.error("新增数据异常,链路名重复,params:{}",linkBO.toString(),de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"链路名已存在",result);
    } catch (Exception e) {
        logger.error("新增数据异常,params:{}",linkBO.toString(),e);
    }
    //返回失败结果
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
项目:xproject    文件:AdminResourceServiceImpl.java   
@Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
public void updateResource(AdminResource resource) {
    ValidationAssert.notNull(resource, "参数不能为空!");
    ValidationAssert.notNull(resource.getResourceId(), "资源id不能为空!");
    resource.setPermissionExpression(StringUtils.defaultIfEmpty(resource.getPermissionExpression(), null));
    resource.setResourceUrl(StringUtils.defaultIfEmpty(resource.getResourceUrl(), null));
    AdminResource presource = adminResourceMapper.selectThinResourceById(resource.getResourceId(), true);
    ValidationAssert.notNull(presource, "该资源已经不存在了!");
    try {
        adminResourceMapper.updateResource(resource);
    } catch(DuplicateKeyException e) {
        BusinessAssert.isTrue(!e.getCause().getMessage().toUpperCase().contains("RESOURCE_NAME"), "修改资源失败,该资源名称已经存在!");
        BusinessAssert.isTrue(!e.getCause().getMessage().toUpperCase().contains("PERMISSION_EXPRESSION"), "修改资源失败,该权限表达式已经存在!");
        throw e;
    }
}
项目:happy-news    文件:NewsCrawler.java   
/**
 * Insert sources into database after server startup.
 */
@PostConstruct
public void insertSources() {
    List<Source> sources = new ArrayList<>();
    sources.add(new Source("the-next-web", "The Next Web", "latest"));
    sources.add(new Source("associated-press", "Associated Press", "latest"));
    sources.add(new Source("bbc-news", "BBC News", "top"));
    sources.add(new Source("bloomberg", "Bloomberg", "top"));
    sources.add(new Source("business-insider", "Business Insider", "latest"));
    sources.add(new Source("buzzfeed", "BuzzFeed", "latest"));
    sources.add(new Source("cnbc", "CNBC", "top"));
    sources.add(new Source("cnn", "CNN", "top"));
    sources.add(new Source("entertainment-weekly", "Entertainment Weekly", "top"));
    sources.add(new Source("financial-times", "Financial Times", "latest"));
    for (Source s : sources) {
        try {
            sourceRepository.save(s);
            logger.info(s.getName() + " added as source.");
        } catch (DuplicateKeyException ex) {
            logger.warn(s.getName() + " already in database, not inserted");
        }
    }

}
项目:alfresco-repository    文件:EntityLookupCacheTest.java   
/**
 * Simulate creation of a new database entry
 */
public Pair<Long, Object> createValue(Object value)
{
    assertTrue(value == null || value instanceof TestValue);
    String dbValue = (value == null) ? null : ((TestValue)value).val;

    // Kick out any duplicate values
    if (database.containsValue(dbValue))
    {
        throw new DuplicateKeyException("Value is duplicated: " + value);
    }

    // Get the last key
    Long lastKey = database.isEmpty() ? null : database.lastKey();
    Long newKey = null;
    if (lastKey == null)
    {
        newKey = new Long(1);
    }
    else
    {
        newKey = new Long(lastKey.longValue() + 1);
    }
    database.put(newKey, dbValue);
    return new Pair<Long, Object>(newKey, value);
}
项目:zkAdmin    文件:CoreServiceImpl.java   
@Override
public void saveConnection(ConnectionInfo connectionInfo) throws DataExistException {
    try{
        if(connectionInfo.getId()!=null){
            connectionInfo.setUpdatedDate(new Date());
            connectionInfoMapper.updateByPrimaryKeySelective(connectionInfo);
        }else{
            connectionInfo.setCreatedDate(new Date());
            connectionInfo.setUpdatedDate(new Date());
            connectionInfoMapper.insert(connectionInfo);
        }
    }catch (DuplicateKeyException dke){
        throw new DataExistException("已经存在:["+connectionInfo.getConnectUrl()+"]的连接信息");
    }

}
项目:core-data    文件:ValueDescriptorControllerImpl.java   
/**
 * Add a new ValueDescriptor whose name must be unique. ServcieException (HTTP 503) for unknown or
 * unanticipated issues. DataValidationException (HTTP 409) if the a formatting string of the
 * value descriptor is not a valid printf format or if the name is determined to not be unique
 * with regard to other value descriptors.
 * 
 * @param valueDescriptor object
 * @return id of the new ValueDescriptor
 * @throws ServcieException (HTTP 503) for unknown or unanticipated issues
 * @throws DataValidationException (HTTP 409) if the format string is not valid or name not unique
 */
@RequestMapping(method = RequestMethod.POST)
@Override
public String add(@RequestBody ValueDescriptor valueDescriptor) {
  if (!validateFormatString(valueDescriptor))
    throw new DataValidationException(
        "Value descriptor's format string doesn't fit the required pattern: " + formatSpecifier);
  try {
    valDescRepos.save(valueDescriptor);
    return valueDescriptor.getId();
  } catch (DuplicateKeyException dE) {
    throw new DataValidationException(
        "Value descriptor's name is not unique: " + valueDescriptor.getName());
  } catch (Exception e) {
    logger.error("Error adding value descriptor:  " + e.getMessage());
    throw new ServiceException(e);
  }
}
项目:oneops    文件:CmRestController.java   
@RequestMapping(method=RequestMethod.POST, value="/cm/simple/relations")
@ResponseBody
public CmsCIRelationSimple createCIRelation(
        @RequestParam(value="value", required = false)  String valueType, 
        @RequestBody CmsCIRelationSimple relSimple,
        @RequestHeader(value="X-Cms-Scope", required = false)  String scope,
        @RequestHeader(value="X-Cms-User", required = false)  String userId) throws CIValidationException {

    scopeVerifier.verifyScope(scope, relSimple);

    CmsCIRelation rel = cmsUtil.custCIRelationSimple2CIRelation(relSimple, valueType);
    rel.setCreatedBy(userId);
    try {
        CmsCIRelation newRel = cmManager.createRelation(rel);
        return cmsUtil.custCIRelation2CIRelationSimple(newRel, valueType,false);
    } catch (DataIntegrityViolationException dive) {
        if (dive instanceof DuplicateKeyException) {
            throw new CIValidationException(CmsError.CMS_DUPCI_NAME_ERROR, dive.getMessage());
        } else {
            throw new CmsException(CmsError.CMS_EXCEPTION, dive.getMessage());
        }
    }
}
项目:batch-scheduler    文件:GroupTaskDaoImpl.java   
@Override
public int addTaskDependency(List<TaskDependencyEntity> list, String groupId) {
    // 删除任务组内所有的连线信息
    jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_218"), groupId);

    for (TaskDependencyEntity m : list) {
        try {
            if (1 != jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_151"),
                    DigestUtils.sha1Hex(JoinCode.join(m.getJobKey(), m.getUpJobKey())),
                    m.getJobKey(),
                    m.getUpJobKey(),
                    m.getDomainId())) {
                logger.warn("新增任务失败");
                return -1;
            }
        } catch (DuplicateKeyException e) {
            logger.warn("任务已经存在,刷新成功,{}", m.getJobKey());
        }
    }
    return 1;
}
项目:chat-rooms    文件:ChannelService.java   
/**
 * Create channel with unique name.
 *
 * @param name channel name.
 * @return created channel.
 */
public Channel createChannel(String name) {
    if (StringUtils.isBlank(name)) {
        throw new ChatException("Channel name must not be null", HttpStatus.BAD_REQUEST);
    }

    name = name.trim();
    try {
        LOGGER.debug("Creating new channel with name: {}", name);
        return channelRepository.save(new Channel(name));

    } catch (DuplicateKeyException e) {
        LOGGER.error("Could not channel: {}",
                e.getMostSpecificCause().getMessage());

        throw new ChatException("Channel with such name already exists", HttpStatus.BAD_REQUEST);
    }
}
项目:RotaryLive    文件:EventServiceImpl.java   
public Event createBooking(Event event, User user, String comment) throws Exception {
    Booking booking = new Booking();
    booking.setComment(comment);
    booking.setUser(user);
    boolean find = false;
    List<Booking> books = event.getBooking();

    for (Booking book : books) {
        if(book.getUser().getUsername().equals(user.getUsername())){
            find = true;
            break;
        }
    }

    if(find)throw new DuplicateKeyException("this account already exists");

    books.add(booking);
    event.setBooking(books);
    return eventRepository.save(event);
}
项目:ryf_mms2    文件:SysManageService.java   
/**
* @title: addGateRoute
* @description: 渠道新增
* @author li.zhenxing
* @date 2014-11-10
* @param gid
* @param name
* @param merNo
* @param requestUrl
* @param remark
*/ 
public String addGateRoute(Integer gid,String name,String merNo,String requestUrl,String remark){
    String msg = "添加失败";
    try {
        if(null != gid && StringUtils.isNotBlank(name) && StringUtils.isNotBlank(merNo) && StringUtils.isNotBlank(requestUrl) && StringUtils.isNotBlank(remark)){
            int count  = dao.addGateRoute(gid, name, merNo, requestUrl, remark);
            dao.saveOperLog("支付渠道维护", "gid:"+gid+",name:"+name+",merNo:"+merNo+",requestUrl:"+requestUrl+",remark:"+remark);
            if(count == 1){
                msg = AppParam.SUCCESS_FLAG;
            }
        }
    } catch (DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        msg+=",支付渠道ID ["+gid+"] 已存在!";
    } catch (Exception ee) {
        logger.info(ee.getMessage(), ee);
    }
    return msg;
}
项目:cloudstreetmarket.com    文件:SocialUserConnectionRepositoryImpl.java   
public void addConnection(Connection<?> connection) {
    try {
        ConnectionData data = connection.createData();
        int rank = socialUserRepository.getRank(userId, data.getProviderId()) ;

        socialUserRepository.create(
            userId, 
            data.getProviderId(), 
            data.getProviderUserId(), 
            rank, 
            data.getDisplayName(), 
            data.getProfileUrl(), 
            data.getImageUrl(), 
            encrypt(data.getAccessToken()), 
            encrypt(data.getSecret()),
            encrypt(data.getRefreshToken()), 
            data.getExpireTime()
        );
    } catch (DuplicateKeyException e) {
        throw new DuplicateConnectionException(connection.getKey());
    }
}
项目:spectingular.spock    文件:TaskServiceTest.java   
@Test
public void shouldNotRegisterTaskForBuildWhenTheTaskAlreadyExists() throws Exception {
    buildOptional = of(build);
    phaseOptional = of(phase);
    taskOptional = of(task);
    when(buildRepository.findByNumber(eq(1))).thenReturn(buildOptional);
    when(phaseRepository.findByBuildAndName(eq(build), eq("phase"))).thenReturn(phaseOptional);
    doThrow(DuplicateKeyException.class).when(taskRepository).save(eq(task));
    try {
        service.register(1, "phase", task);
        fail();
    } catch (DuplicateKeyException e) {
    }
    verify(task).setState(isA(State.class));
    verify(task).setPhase(eq(phase));
    verify(buildRepository).findByNumber(eq(1));
    verify(phaseRepository).findByBuildAndName(eq(build), eq("phase"));
    verify(taskRepository).save(task);
}
项目:spectingular.spock    文件:TaskServiceTest.java   
@Test
public void shouldNotRegisterTaskForModuleWhenTheTaskAlreadyExists() throws Exception {
    buildOptional = of(build);
    moduleOptional = of(module);
    phaseOptional = of(phase);
    taskOptional = of(task);
    when(buildRepository.findByNumber(eq(1))).thenReturn(buildOptional);
    when(moduleRepository.findByBuildAndName(eq(build), eq("module"))).thenReturn(moduleOptional);
    when(phaseRepository.findByModuleAndName(eq(module), eq("phase"))).thenReturn(phaseOptional);
    doThrow(DuplicateKeyException.class).when(taskRepository).save(eq(task));
    try {
        service.register(1, "module", "phase", task);
        fail();
    } catch (DuplicateKeyException e) {
    }
    verify(task).setState(isA(State.class));
    verify(task).setPhase(eq(phase));
    verify(buildRepository).findByNumber(eq(1));
    verify(moduleRepository).findByBuildAndName(eq(build), eq("module"));
    verify(phaseRepository).findByModuleAndName(eq(module), eq("phase"));
    verify(taskRepository).save(task);
}
项目:spectingular.spock    文件:PhaseServiceTest.java   
@Test
public void shouldNotRegisterPhaseForModuleWhenThePhaseAlreadyExists() throws Exception {
    buildOptional = of(build);
    moduleOptional = of(module);
    phaseOptional = of(phase);
    when(buildRepository.findByNumber(eq(1))).thenReturn(buildOptional);
    when(moduleRepository.findByBuildAndName(eq(build), eq("module"))).thenReturn(moduleOptional);
    doThrow(DuplicateKeyException.class).when(phaseRepository).save(eq(phase));
    try {
        service.register(1, "module", phase);
        fail();
    } catch (DuplicateKeyException e) {
    }
    verify(buildRepository).findByNumber(eq(1));
    verify(moduleRepository).findByBuildAndName(eq(build), eq("module"));
    verify(phaseRepository).save(eq(phase));
}
项目:queue-server    文件:JdbcQueueApi.java   
protected boolean initQueueMetadata(String queueName) {
    if (!isValidQueueName(queueName)) {
        return false;
    }

    String normalizedQueueName = normalizeQueueName(queueName);
    try {
        Connection conn = connection();
        try {
            conn.setAutoCommit(true);
            JdbcTemplate jdbcTemplate = jdbcTemplate(conn);

            final String SQL = "INSERT INTO {0} (queue_name, queue_timestamp_create) VALUES (?, ?)";
            jdbcTemplate.update(MessageFormat.format(SQL, getTableMetadata()),
                    normalizedQueueName, new Date());
            return true;
        } catch (DuplicateKeyException dke) {
            // EMPTY
        } finally {
            conn.close();
        }
    } catch (SQLException e) {
        Logger.error(e.getMessage(), e);
    }
    return false;
}
项目:ameba-lib    文件:IntegrationLayerAspect.java   
/**
 * Called after an exception is thrown by classes of the integration layer. <p> Set log level to ERROR to log the root cause. </p>
 *
 * @param ex The root exception that is thrown
 * @return Returns the exception to be thrown
 */
public Exception translateException(Exception ex) {
    if (EXC_LOGGER.isErrorEnabled()) {
        EXC_LOGGER.error(ex.getLocalizedMessage(), ex);
    }

    if (ex instanceof BusinessRuntimeException) {
        return ex;
    }

    Optional<Exception> handledException = doTranslateException(ex);
    if (handledException.isPresent()) {
        return handledException.get();
    }
    if (ex instanceof DuplicateKeyException) {
        return new ResourceExistsException();
    }
    if (ex instanceof IntegrationLayerException) {
        return ex;
    }
    return withRootCause ? new IntegrationLayerException(ex.getMessage(), ex) : new IntegrationLayerException(ex.getMessage());
}
项目:ws_hcm    文件:_OithController.java   
public void errorHandler(BindingResult bindingResult, Exception e) {

        if (e instanceof DuplicateKeyException) {
            DuplicateKeyException uuu = (DuplicateKeyException) e;

            String hhh = uuu.getCause().getMessage();

            System.out.println("err dup key: " + hhh);

            int kk = hhh.lastIndexOf(": \"");
            if (kk != -1) {
                hhh = hhh.substring(kk + 3, hhh.length() - 4);
            }

            ObjectError yyyy = new ObjectError(bindingResult.getObjectName(), "Duplicate record notification for value '" + hhh + "'");
            //FieldError yyyy=   new FieldError(bindingResult.getObjectName(), "code", e.getMessage()+" real val: "+ uuu.getRootCause()+" hhhh"+ val);

            bindingResult.addError(yyyy);
        }
    }
项目:summerb    文件:UserServiceImpl.java   
@Override
@Transactional(rollbackFor = Throwable.class)
public void updateUser(User user) throws FieldValidationException, UserNotFoundException {
    Preconditions.checkArgument(user != null, "User reference required");
    Preconditions.checkArgument(StringUtils.hasText(user.getUuid()), "User uuid must be provided");

    validateUser(user);

    boolean isUpdatedSuccessfully;
    try {
        isUpdatedSuccessfully = userDao.updateUser(user);
        eventBus.post(EntityChangedEvent.updated(user));
    } catch (DuplicateKeyException dke) {
        throw new FieldValidationException(new DuplicateUserValidationError(User.FN_EMAIL));
    } catch (Throwable t) {
        String msg = String.format("Failed to update user '%s'", user.getUuid());
        throw new UserServiceUnexpectedException(msg, t);
    }

    if (!isUpdatedSuccessfully) {
        throw new UserNotFoundException(user.getUuid());
    }
}
项目:summerb    文件:PermissionServiceImpl.java   
@Override
@Transactional(rollbackFor = Throwable.class)
public void grantPermission(String optionalDomainName, String userUuid, String optionalSubjectId,
        String permissionKey) {
    Preconditions.checkArgument(StringUtils.hasText(permissionKey));
    Preconditions.checkArgument(StringUtils.hasText(userUuid));
    String domainName = getOptionalParamValue(optionalDomainName);
    String subjectId = getOptionalParamValue(optionalSubjectId);

    try {
        permissionDao.grantPermission(domainName, userUuid, subjectId, permissionKey);
    } catch (DuplicateKeyException dke) {
        // it's ok
        log.debug("Duplicate key exception sealed. Looks like same permission is already granted.", dke);
    } catch (Throwable t) {
        String msg = String.format("Failed to grant permission '%s' to user '%s' on subject '%s' in domain '%s'",
                permissionKey, userUuid, subjectId, domainName);
        throw new UserServiceUnexpectedException(msg, t);
    }
}
项目:summerb    文件:StringIdAliasServiceSimpleImpl.java   
@Override
@Transactional(rollbackFor = Throwable.class)
public long getAliasFor(String str) {
    Long ret = null;
    try {
        ret = stringIdAliasDao.findAliasFor(str);
        if (ret != null) {
            return ret;
        }

        try {
            return stringIdAliasDao.createAliasFor(str);
        } catch (DuplicateKeyException dke) {
            log.debug("Looks like alias already exist in database, will load it");
            ret = stringIdAliasDao.findAliasFor(str);
            if (ret == null) {
                throw new PropertyServiceUnexpectedException(
                        "Failed to create alias because of duplicate, but later was unable to find that duplicate.");
            }
            return ret;
        }
    } catch (Throwable t) {
        throw new PropertyServiceUnexpectedException("Failed to store alias", t);
    }
}
项目:summerb    文件:EasyCrudDaoMySqlImpl.java   
private void processDuplicateEntryException(Throwable t) throws FieldValidationException {
    DuplicateKeyException dke = ExceptionUtils.findExceptionOfType(t, DuplicateKeyException.class);
    if (dke == null) {
        return;
    }

    String constraint = DaoExceptionUtils.findViolatedConstraintName(dke);
    // Handle case when uuid is duplicated
    if (DaoExceptionUtils.MYSQL_CONSTRAINT_PRIMARY.equals(constraint)) {
        throw new IllegalArgumentException("Row with same primary key already exists", dke);
    }

    if (!constraint.contains(DaoExceptionUtils.MYSQL_CONSTRAINT_UNIQUE)) {
        throw new IllegalArgumentException("Constraint violation " + constraint, dke);
    }

    String fieldName = constraint.substring(0, constraint.indexOf(DaoExceptionUtils.MYSQL_CONSTRAINT_UNIQUE));
    if (fieldName.contains("_")) {
        fieldName = JdbcUtils.convertUnderscoreNameToPropertyName(fieldName);
    }

    throw new FieldValidationException(new DuplicateRecordValidationError(fieldName));
}
项目:summerb    文件:DaoExceptionUtils.java   
/**
 * Parse exception and find constraint name.
 * 
 * Current impl will parse text string which format is expected to be like:
 * "Duplicate entry 'sameUuid' for key 'PRIMARY'"
 * 
 * @param duplicateKeyException
 *            exception received from DAO
 * @return null if failed to parse, constraint name otherwise
 */
public static String findViolatedConstraintName(DuplicateKeyException duplicateKeyException) {
    if (duplicateKeyException == null) {
        return null;
    }

    String message = duplicateKeyException.getMessage();
    int pos = message.indexOf("for key");
    if (pos < 0) {
        return null;
    }

    message = message.substring(pos);
    if (message.indexOf("'") < 0) {
        return null;
    }

    String[] parts = message.split("'");
    if (parts.length < 2) {
        return null;
    }

    return parts[1];
}
项目:onboard    文件:SubscriberServiceImpl.java   
@Override
public void addSubscribers(Subscribable subscribable) {
    if (subscribable.getSubscribers() == null || subscribable.getSubscribers().size() == 0) {
        return;
    }
    for (User user : subscribable.getSubscribers()) {
        try {
            Subscriber subscriber = new Subscriber();
            subscriber.setSubscribeId(subscribable.getSubscribableId());
            subscriber.setSubscribeType(subscribable.getSubscribableType());
            subscriber.setUserId(user.getId());
            subscriberMapper.insert(subscriber);
        } catch (DuplicateKeyException e) {
            // do nothing
        }
    }

}
项目:ddth-queue    文件:AbstractLessLockingUniversalJdbcQueue.java   
/**
 * {@inheritDoc}
 */
protected boolean _requeueSilentWithRetries(Connection conn, IQueueMessage<Long, byte[]> msg,
        int numRetries, int maxRetries) {
    try {
        int numRows = getJdbcHelper().execute(conn, SQL_REQUEUE_SILENT, msg.qId());
        return numRows > 0;
    } catch (DuplicatedValueException dve) {
        LOGGER.warn(dve.getMessage(), dve);
        return true;
    } catch (DaoException de) {
        if (de.getCause() instanceof DuplicateKeyException) {
            LOGGER.warn(de.getMessage(), de);
            return true;
        }
        if (de.getCause() instanceof ConcurrencyFailureException) {
            if (numRetries > maxRetries) {
                throw new QueueException(de);
            } else {
                return _requeueSilentWithRetries(conn, msg, numRetries + 1, maxRetries);
            }
        }
        throw de;
    } catch (Exception e) {
        throw e instanceof QueueException ? (QueueException) e : new QueueException(e);
    }
}
项目:ddth-queue    文件:AbstractLessLockingUniversalJdbcQueue.java   
/**
 * {@inheritDoc}
 */
protected boolean _requeueSilentWithRetries(Connection conn, IQueueMessage<String, byte[]> msg,
        int numRetries, int maxRetries) {
    try {
        int numRows = getJdbcHelper().execute(conn, SQL_REQUEUE_SILENT, msg.qId());
        return numRows > 0;
    } catch (DuplicatedValueException dve) {
        LOGGER.warn(dve.getMessage(), dve);
        return true;
    } catch (DaoException de) {
        if (de.getCause() instanceof DuplicateKeyException) {
            LOGGER.warn(de.getMessage(), de);
            return true;
        }
        if (de.getCause() instanceof ConcurrencyFailureException) {
            if (numRetries > maxRetries) {
                throw new QueueException(de);
            } else {
                return _requeueSilentWithRetries(conn, msg, numRetries + 1, maxRetries);
            }
        }
        throw de;
    } catch (Exception e) {
        throw e instanceof QueueException ? (QueueException) e : new QueueException(e);
    }
}
项目:kaif    文件:V1VoteResourceTest.java   
@Test
public void ignoreDuplicateKeyException() throws Exception {
  ArticleVoter articleVoter = articleVoter(VoteState.UP, "foo1");
  when(voteService.listArticleVoters(isA(ClientAppUserAccessToken.class),
      eq(asList(FlakeId.fromString("foo1"))))).thenReturn(asList(articleVoter));

  Mockito.doThrow(new DuplicateKeyException("fake"))
      .when(voteService)
      .voteArticle(eq(VoteState.EMPTY),
          eq(FlakeId.fromString("foo1")),
          isA(ClientAppUserAccessToken.class),
          eq(VoteState.UP),
          eq(0L));

  oauthPerform(user,
      post("/v1/vote/article").content(q("{'voteState':'EMPTY','articleId':'foo1'}"))).andExpect(
      status().isOk());
}
项目:kaif    文件:VoteResourceTest.java   
@Test
public void ignoreDuplicateVote() throws Exception {
  Account account = accountCitizen("foo");
  String token = prepareAccessToken(account);

  VoteResource.VoteArticle voteArticle = new VoteResource.VoteArticle();
  voteArticle.articleId = FlakeId.fromString("a");
  voteArticle.newState = VoteState.DOWN;
  voteArticle.previousCount = 100L;
  voteArticle.previousState = VoteState.EMPTY;

  Mockito.doThrow(new DuplicateKeyException("vote dup"))
      .when(voteService)
      .voteArticle(eq(VoteState.DOWN),
          eq(FlakeId.fromString("a")),
          isA(Authorization.class),
          eq(VoteState.EMPTY),
          eq(100L));

  mockMvc.perform(post("/api/vote/article").header(AccountAccessToken.HEADER_KEY, token)
      .contentType(MediaType.APPLICATION_JSON)
      .content(new ObjectMapper().writeValueAsBytes(voteArticle))).andExpect(status().isOk());
}
项目:community-edition-old    文件:EntityLookupCacheTest.java   
/**
 * Simulate creation of a new database entry
 */
public Pair<Long, Object> createValue(Object value)
{
    assertTrue(value == null || value instanceof TestValue);
    String dbValue = (value == null) ? null : ((TestValue)value).val;

    // Kick out any duplicate values
    if (database.containsValue(dbValue))
    {
        throw new DuplicateKeyException("Value is duplicated: " + value);
    }

    // Get the last key
    Long lastKey = database.isEmpty() ? null : database.lastKey();
    Long newKey = null;
    if (lastKey == null)
    {
        newKey = new Long(1);
    }
    else
    {
        newKey = new Long(lastKey.longValue() + 1);
    }
    database.put(newKey, dbValue);
    return new Pair<Long, Object>(newKey, value);
}
项目:ontrack    文件:AccountJdbcRepository.java   
@Override
public Account newAccount(Account account) {
    try {
        int id = dbCreate(
                "INSERT INTO ACCOUNTS (NAME, FULLNAME, EMAIL, MODE, PASSWORD, ROLE) " +
                        "VALUES (:name, :fullName, :email, :mode, :password, :role)",
                params("name", account.getName())
                        .addValue("fullName", account.getFullName())
                        .addValue("email", account.getEmail())
                        .addValue("mode", account.getAuthenticationSource().getId())
                        .addValue("password", "")
                        .addValue("role", account.getRole().name())
        );
        return account.withId(ID.of(id));
    } catch (DuplicateKeyException ex) {
        throw new AccountNameAlreadyDefinedException(account.getName());
    }
}
项目:ontrack    文件:StructureJdbcRepository.java   
@Override
public Project newProject(Project project) {
    // Creation
    try {
        int id = dbCreate(
                "INSERT INTO PROJECTS(NAME, DESCRIPTION, DISABLED, CREATION, CREATOR) VALUES (:name, :description, :disabled, :creation, :creator)",
                params("name", project.getName())
                        .addValue("description", project.getDescription())
                        .addValue("disabled", project.isDisabled())
                        .addValue("creation", dateTimeForDB(project.getSignature().getTime()))
                        .addValue("creator", project.getSignature().getUser().getName())
        );
        // Returns with ID
        return project.withId(id(id));
    } catch (DuplicateKeyException ex) {
        throw new ProjectNameAlreadyDefinedException(project.getName());
    }
}
项目:ontrack    文件:StructureJdbcRepository.java   
@Override
public Branch newBranch(Branch branch) {
    // Creation
    try {
        int id = dbCreate(
                "INSERT INTO BRANCHES(PROJECTID, NAME, DESCRIPTION, DISABLED, CREATION, CREATOR) VALUES (:projectId, :name, :description, :disabled, :creation, :creator)",
                params("name", branch.getName())
                        .addValue("description", branch.getDescription())
                        .addValue("disabled", branch.isDisabled())
                        .addValue("projectId", branch.getProject().id())
                        .addValue("creation", dateTimeForDB(branch.getSignature().getTime()))
                        .addValue("creator", branch.getSignature().getUser().getName())
        );
        // Returns with ID
        return branch.withId(id(id));
    } catch (DuplicateKeyException ex) {
        throw new BranchNameAlreadyDefinedException(branch.getName());
    }
}
项目:ontrack    文件:StructureJdbcRepository.java   
@Override
public Build newBuild(Build build) {
    // Creation
    try {
        int id = dbCreate(
                "INSERT INTO BUILDS(BRANCHID, NAME, DESCRIPTION, CREATION, CREATOR) VALUES (:branchId, :name, :description, :creation, :creator)",
                params("name", build.getName())
                        .addValue("description", build.getDescription())
                        .addValue("branchId", build.getBranch().id())
                        .addValue("creation", dateTimeForDB(build.getSignature().getTime()))
                        .addValue("creator", build.getSignature().getUser().getName())
        );
        return build.withId(id(id));
    } catch (DuplicateKeyException ex) {
        throw new BuildNameAlreadyDefinedException(build.getName());
    }
}
项目:ontrack    文件:StructureJdbcRepository.java   
@Override
public Build saveBuild(Build build) {
    // Update
    try {
        getNamedParameterJdbcTemplate().update(
                "UPDATE BUILDS SET NAME = :name, DESCRIPTION = :description, CREATION = :creation, CREATOR = :creator WHERE ID = :id",
                params("name", build.getName())
                        .addValue("description", build.getDescription())
                        .addValue("creation", dateTimeForDB(build.getSignature().getTime()))
                        .addValue("creator", build.getSignature().getUser().getName())
                        .addValue("id", build.id())
        );
        return build;
    } catch (DuplicateKeyException ex) {
        throw new BuildNameAlreadyDefinedException(build.getName());
    }
}
项目:ontrack    文件:AccountGroupMappingJdbcRepository.java   
@Override
public AccountGroupMapping newMapping(String mapping, AccountGroupMappingInput input) {
    try {
        return getMapping(
                ID.of(dbCreate(
                        "INSERT INTO ACCOUNT_GROUP_MAPPING(MAPPING, SOURCE, GROUPID) " +
                                "VALUES(:mapping, :source, :groupId)",
                        params("mapping", mapping)
                                .addValue("source", input.getName())
                                .addValue("groupId", input.getGroup().get())
                        )
                )
        );
    } catch (DuplicateKeyException ex) {
        throw new AccountGroupMappingNameAlreadyDefinedException(input.getName());
    }
}
项目:ontrack    文件:PredefinedPromotionLevelJdbcRepository.java   
@Override
public ID newPredefinedPromotionLevel(PredefinedPromotionLevel stamp) {
    try {
        // Order nb = max + 1
        Integer orderNbValue = getFirstItem(
                "SELECT MAX(ORDERNB) FROM PREDEFINED_PROMOTION_LEVELS",
                noParams(),
                Integer.class
        );
        int orderNb = orderNbValue != null ? orderNbValue + 1 : 0;
        return ID.of(
                dbCreate(
                        "INSERT INTO PREDEFINED_PROMOTION_LEVELS(NAME, ORDERNB, DESCRIPTION) VALUES (:name, :orderNb, :description)",
                        params("name", stamp.getName())
                                .addValue("description", stamp.getDescription())
                                .addValue("orderNb", orderNb)
                )
        );
    } catch (DuplicateKeyException ex) {
        throw new PredefinedPromotionLevelNameAlreadyDefinedException(stamp.getName());
    }
}
项目:ontrack    文件:AccountGroupJdbcRepository.java   
@Override
public AccountGroup newAccountGroup(AccountGroup group) {
    try {
        return group.withId(
                ID.of(
                        dbCreate(
                                "INSERT INTO ACCOUNT_GROUPS (NAME, DESCRIPTION) " +
                                        "VALUES (:name, :description)",
                                params("name", group.getName())
                                        .addValue("description", group.getDescription())
                        )
                )
        );
    } catch (DuplicateKeyException ex) {
        throw new AccountGroupNameAlreadyDefinedException(group.getName());
    }
}
项目:spring-data-keyvalue    文件:KeyValueTemplate.java   
@Override
public void insert(Object id, Object objectToInsert) {

    Assert.notNull(id, "Id for object to be inserted must not be null!");
    Assert.notNull(objectToInsert, "Object to be inserted must not be null!");

    String keyspace = resolveKeySpace(objectToInsert.getClass());

    potentiallyPublishEvent(KeyValueEvent.beforeInsert(id, keyspace, objectToInsert.getClass(), objectToInsert));

    execute((KeyValueCallback<Void>) adapter -> {

        if (adapter.contains(id, keyspace)) {
            throw new DuplicateKeyException(
                    String.format("Cannot insert existing object with id %s!. Please use update.", id));
        }

        adapter.put(id, objectToInsert, keyspace);
        return null;
    });

    potentiallyPublishEvent(KeyValueEvent.afterInsert(id, keyspace, objectToInsert.getClass(), objectToInsert));
}
项目:porra-joc-eda    文件:AccountService.java   
/**
 * Assume name and email are already set
 * @param account
 */
public void createAccount(final Account account) throws SignupException {
    this.logger.info("AccountService.createAccount");
    // Starting status 'pending no password' - User must activate account and provide own password (ie. by following emailed link)
    final String activationToken = AccountUtils.generateActivationToken();
    account.setStatus(AccountStatus.STATUS_PENDING_NOPASSWORD.name());
    account.setRoles(new ArrayList<String>());
    account.addRole(AccountRole.ROLE_USER.name());
    account.setActivationToken(activationToken);
    account.setKudos(AccountUtils.INITIAL_KUDOS);
    account.setActiveBets(0);
    account.setBets(new ArrayList<Bet>());
    account.setCreatedOn(new Date());
    try {
        this.accountRepo.insert(account);
    } catch (final DuplicateKeyException exception) {
        this.handleDuplicatekeyException(exception);
    }
}