org.springframework.dao.DuplicateKeyException Java Examples

The following examples show how to use org.springframework.dao.DuplicateKeyException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpInterfaceHeaderDaoImpl.java    From AnyMock with Apache License 2.0 6 votes vote down vote up
@Override
public void batchCreate(List<HttpInterfaceHeaderBO> httpInterfaceHeaderBOListList, Long httpInterfaceId, HttpHeaderType type) {
    httpInterfaceHeaderBOListList.forEach(httpInterfaceHeaderBO -> {
        HttpInterfaceHeaderDO httpInterfaceHeaderDO = convertToDO(httpInterfaceHeaderBO, httpInterfaceId, type);

        int resultSize;
        try {
            resultSize = httpInterfaceHeaderDOMapper.insert(httpInterfaceHeaderDO);
        } catch (DuplicateKeyException e) {
            throw new BizException(ResultCode.DUPLICATE_KEY_HTTP_INTERFACE_HEADER);
        }

        if (resultSize != 1) {
            throw new IncorrectResultSizeException(resultSize);
        }
    });
}
 
Example #2
Source File: JpaConnectionRepository.java    From cola with MIT License 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void addConnection(Connection<?> connection) {
	try {
		ConnectionData data = connection.createData();
		UserConnection userConnection = new UserConnection();
		userConnection.setProviderUserName(data.getDisplayName());
		userConnection.setImageUrl(data.getImageUrl());
		userConnection.setAccessToken(encrypt(data.getAccessToken()));
		userConnection.setSecret(encrypt(data.getSecret()));
		userConnection.setRefreshToken(encrypt(data.getRefreshToken()));
		userConnection.setProviderId(data.getProviderId());
		userConnection.setProviderUserId(data.getProviderUserId());
		userConnection.setExpireTime(data.getExpireTime());
		userConnection.setUserId(userId);
		this.userConnectionRepository.save(userConnection);
	} catch (DuplicateKeyException e) {
		throw new DuplicateConnectionException(connection.getKey());
	}
}
 
Example #3
Source File: ThrowableSupplier.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Response error(final Throwable throwable) {
    logger.error("throwable exception",throwable);
    if (throwable instanceof IllegalArgumentException) {
        return Responses.error(ErrorCode.BadRequest.getCode(), ErrorCode.BadRequest.getStatus(), throwable.getMessage());
    } else if (throwable instanceof DuplicateKeyException) {
        return Responses.error(ErrorCode.DuplicateError.getCode(), ErrorCode.DuplicateError.getStatus(), "记录已经存在,请刷新重试");
    } else if (throwable instanceof DataIntegrityViolationException) {
        return Responses.error(ErrorCode.RuntimeError.getCode(), ErrorCode.RuntimeError.getStatus(), "输入记录不符合要求");
    } else if (throwable instanceof InvocationTargetException) {
        Throwable targetException = ((InvocationTargetException) throwable).getTargetException();
        if (targetException instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) targetException;
            return Responses.error(ErrorCode.ServiceError.getCode(), serviceException.getStatus(), serviceException.getMessage());
        }
        return Responses.error(ErrorCode.RuntimeError.getCode(), ErrorCode.RuntimeError.getStatus(), targetException.getMessage());
    } else if(throwable instanceof NullPointerException) {
        return Responses.error(ErrorCode.RuntimeError.getCode(), ErrorCode.RuntimeError.getStatus(), ((NullPointerException) throwable).toString());
    }

    return Responses.error(ErrorCode.RuntimeError.getCode(), ErrorCode.RuntimeError.getStatus(),
            (StringUtils.isNotBlank(throwable.toString()) ? throwable.toString(): ErrorCode.RuntimeError.getMessage()));
}
 
Example #4
Source File: ExecutorContainerServiceImpl.java    From liteflow with Apache License 2.0 6 votes vote down vote up
@Override
public void add(ExecutorContainer container) throws ExecutorRuntimeException{
    Preconditions.checkArgument(container != null, "model不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(container.getName()), "name不能为空");

    ExecutorContainer existContainer = executorContainerMapper.getByName(container.getName());
    if (existContainer != null) {
        throw new ExecutorRuntimeException("该容器名称已经存在");
    }

    container.setStatus(StatusType.ON.getValue());
    try {
        executorContainerMapper.insert(container);
    } catch (DuplicateKeyException e) {
        LOG.error("add executor container duplicate, name:{}", container.getName());
        throw new ExecutorRuntimeException("已经存在同名的执行容器");
    }
}
 
Example #5
Source File: ExecutorPluginServiceImpl.java    From liteflow with Apache License 2.0 6 votes vote down vote up
@Override
public void add(ExecutorPlugin executorPlugin) {
    Preconditions.checkArgument(executorPlugin != null, "executorPlugin不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(executorPlugin.getName()), "name不能为空");
    Preconditions.checkArgument(executorPlugin.getContainerId() != null, "containerId不能为空");


    ExecutorPlugin existModel = executorPluginMapper.getByName(executorPlugin.getName());
    if (existModel != null) {
        throw new ExecutorRuntimeException("该名称已经存在");
    }

    if (executorContainerService.getById(executorPlugin.getContainerId()) == null) {
        throw new ExecutorRuntimeException("该容器不存在");
    }

    executorPlugin.setStatus(StatusType.ON.getValue());
    try {
        executorPluginMapper.insert(executorPlugin);
    } catch (DuplicateKeyException e) {
        LOG.error("add executor container duplicate, name:{}", executorPlugin.getName());
        throw new ExecutorRuntimeException("该插件名称已经存在");
    }
}
 
Example #6
Source File: DbDicService.java    From qmq with Apache License 2.0 6 votes vote down vote up
private String getOrCreateId(String name) {
    int id;
    try {
        id = dicStore.getId(name);
    } catch (EmptyResultDataAccessException e) {
        try {
            id = dicStore.insertName(name);
        } catch (DuplicateKeyException e2) {
            id = dicStore.getId(name);
        } catch (Exception e3) {
            LOG.error("insert name error: {}", name, e3);
            throw new RuntimeException("insert name error: " + name, e3);
        }
    }
    return String.format(pattern, id);
}
 
Example #7
Source File: UiTopicService.java    From pmq with Apache License 2.0 6 votes vote down vote up
private void createSuccessTopic(TopicEntity topicEntity) {
	TopicEntity entity= topicService.getTopicByName(topicEntity.getName());
	if(entity!=null){
		throw new CheckFailException("topic:"+topicEntity.getName()+"重复,检查是否有重名topic已经存在。");
	}
	try {
		topicService.insert(topicEntity);
	} catch (DuplicateKeyException e) {
		throw new CheckFailException("topic:" + topicEntity.getName() + "重复,检查是否有重名topic已经存在。");
	}
	uiAuditLogService.recordAudit(TopicEntity.TABLE_NAME, topicEntity.getId(),
			"新建topic," + JsonUtil.toJson(topicEntity));
	// 计算分配的队列数
	int expectDayCount = topicEntity.getExpectDayCount() * 10000;
	int successQueueNum = expectDayCount / Constants.MSG_NUMS_OF_ONE_QUEUE;
	// 分配队列
	topicService.distributeQueueWithLock(topicEntity, successQueueNum,
			NodeTypeEnum.SUCCESS_NODE_TYPE.getTypeCode());
}
 
Example #8
Source File: CollectionService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
@Transactional
@CacheEvict(value = "collections", key = "#collectionId")
public Boolean addIllustrationToCollection(Integer userId, Integer collectionId, Illustration illustration) {
    //校验collectionId是否属于用户
    checkCollectionAuth(collectionId, userId);
    Collection collection = queryCollectionByIdFromDb(collectionId);
    //插入
    try {
        collectionMapper.incrCollectionIllustCount(collectionId);
        collectionMapper.addIllustrationToCollection(collectionId, illustration.getId());
        if (collection.getIllustCount() == 0) {
            collectionMapper.updateCollectionCover(collectionId, illustrationBizService.queryIllustrationById(illustration.getId()));
        }
    } catch (DuplicateKeyException e) {
        throw new BusinessException(HttpStatus.BAD_REQUEST, "画作在该画集中已经存在");
    }
    return true;
}
 
Example #9
Source File: UserController.java    From angular-spring-api with MIT License 6 votes vote down vote up
@PostMapping()
@PreAuthorize("hasAnyRole('ADMIN')")
public ResponseEntity<Response<User>> create(HttpServletRequest request, @RequestBody User user,
		BindingResult result) {
	Response<User> response = new Response<User>();
	try {
		validateCreateUser(user, result);
		if (result.hasErrors()) {
			result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage()));
			return ResponseEntity.badRequest().body(response);
		}
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		User userPersisted = (User) userService.createOrUpdate(user);
		response.setData(userPersisted);
	} catch (DuplicateKeyException dE) {
		response.getErrors().add("E-mail already registered !");
		return ResponseEntity.badRequest().body(response);
	} catch (Exception e) {
		response.getErrors().add(e.getMessage());
		return ResponseEntity.badRequest().body(response);
	}
	return ResponseEntity.ok(response);
}
 
Example #10
Source File: ConfigServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
private void createOrUpdateConfig(final CandidateSnapshot snapshot) throws ModifiedException {
    final ConfigMeta configMeta = new ConfigMeta(snapshot.getGroup(), snapshot.getDataId(), snapshot.getProfile());
    final ConfigInfoWithoutPublicStatus currentConfig = configDao.findCurrentConfigInfo(configMeta);
    final long version = currentConfig == null ? 0 : currentConfig.getVersion();

    if (version != snapshot.getBasedVersion()) {
        throw new ModifiedException();
    } else if (version == 0) {
        try {
            configDao.create(VersionData.of(snapshot.getEditVersion(), configMeta));
        } catch (DuplicateKeyException e) {
            throw new ModifiedException();
        }
    } else {
        int update = configDao.update(VersionData.of(snapshot.getEditVersion(), configMeta),
                snapshot.getBasedVersion(),
                PublicStatus.INUSE);
        if (update == 0) {
            throw new ModifiedException();
        }
    }
}
 
Example #11
Source File: TestPlanService.java    From server with MIT License 6 votes vote down vote up
@Transactional
public Response update(TestPlan testPlan) {
    if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE && StringUtils.isEmpty(testPlan.getCronExpression())) {
        // 开启定时任务,表达式不能为空
        return Response.fail("cron表达式不能为空");
    }

    int updateRow;
    try {
        updateRow = testPlanMapper.updateByPrimaryKeyWithBLOBs(testPlan);
    } catch (DuplicateKeyException e) {
        return Response.fail("命名冲突");
    }

    if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE) {
        addOrUpdateScheduleTask(testPlan);
    } else {
        cancelScheduleTask(testPlan.getId());
    }

    return updateRow == 1 ? Response.success("更新TestPlan成功") : Response.fail("更新TestPlan失败,请稍后重试");
}
 
Example #12
Source File: ServiceConditionImpl.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
@Override
public com.iflytek.ccr.polaris.cynosure.domain.Service add(AddServiceRequestBody body) {
    String name = body.getName();
    String desc = body.getDesc();
    String userId = this.getUserId();
    String clusterId = body.getClusterId();

    //新增
    Date now = new Date();
    com.iflytek.ccr.polaris.cynosure.domain.Service service = new com.iflytek.ccr.polaris.cynosure.domain.Service();
    service.setId(SnowflakeIdWorker.getId());
    service.setName(name);
    service.setDescription(desc);
    service.setUserId(userId);
    service.setGroupId(clusterId);
    service.setCreateTime(now);
    try {
        this.serviceMapper.insert(service);
        return service;
    } catch (DuplicateKeyException ex) {
        logger.warn("service duplicate key " + ex.getMessage());
        return this.find(name, clusterId);
    }
}
 
Example #13
Source File: SpaceDaoImpl.java    From AnyMock with Apache License 2.0 6 votes vote down vote up
@Override
public void create(SpaceBO spaceBO) {
    SpaceDO spaceDO = convertToDO(spaceBO);
    Date now = new Date();
    spaceDO.setId(null);
    spaceDO.setGmtCreate(now);
    spaceDO.setGmtModified(now);

    int resultSize;
    try {
        resultSize = spaceDOMapper.insert(spaceDO);
    } catch (DuplicateKeyException e) {
        throw new BizException(ResultCode.DUPLICATE_KEY_SPACE);
    }

    if (resultSize != 1) {
        throw new IncorrectResultSizeException(resultSize);
    }
}
 
Example #14
Source File: ServiceApiVersionConditionImpl.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceApiVersion add(AddServiceApiVersionRequestBody body) {
    String apiVersion = body.getApiVersion();
    String serviceId = body.getServiceId();
    String desc = body.getDesc();
    String userId = this.getUserId();

    //新增
    Date now = new Date();
    ServiceApiVersion serviceApiVersion = new ServiceApiVersion();
    serviceApiVersion.setId(SnowflakeIdWorker.getId());
    serviceApiVersion.setApiVersion(apiVersion);
    serviceApiVersion.setServiceId(serviceId);
    serviceApiVersion.setUserId(userId);
    serviceApiVersion.setDescription(desc);
    serviceApiVersion.setCreateTime(now);
    serviceApiVersion.setUpdateTime(now);
    try {
        this.serviceApiVersionMapper.insert(serviceApiVersion);
        return serviceApiVersion;
    } catch (DuplicateKeyException ex) {
        logger.warn("service version duplicate key " + ex.getMessage());
        return this.find(apiVersion, serviceId);
    }
}
 
Example #15
Source File: SpaceDaoImpl.java    From AnyMock with Apache License 2.0 6 votes vote down vote up
@Override
public void update(SpaceBO spaceBO) {
    SpaceDO spaceDO = convertToDO(spaceBO);
    spaceDO.setGmtCreate(null);
    spaceDO.setGmtModified(new Date());

    int resultSize;
    try {
        resultSize = spaceDOMapper.updateByPrimaryKeySelective(spaceDO);
    } catch (DuplicateKeyException e) {
        throw new BizException(ResultCode.DUPLICATE_KEY_SPACE);
    }

    if (resultSize == 0) {
        throw new BizException(ResultCode.NOT_FOUND_SPACE);
    } else if (resultSize != 1) {
        throw new IncorrectResultSizeException(resultSize);
    }
}
 
Example #16
Source File: ProjectMemberConditionImpl.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
@Override
public ProjectMember add(String userId, String projectId) {
    ProjectMember projectMember = new ProjectMember();
    projectMember.setId(SnowflakeIdWorker.getId());
    projectMember.setUserId(userId);
    projectMember.setCreator((byte) DBEnumInt.CREATOR_N.getIndex());
    projectMember.setProjectId(projectId);
    projectMember.setCreateTime(new Date());
    try {
        this.projectMemberMapper.insert(projectMember);
        return projectMember;
    } catch (DuplicateKeyException ex) {
        logger.warn("project member duplicate key " + ex.getMessage());
        return this.find(userId, projectId);
    }
}
 
Example #17
Source File: ProjectMemberConditionImpl.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
@Override
public ProjectMember addCreator(String projectId) {
    String userId = this.getUserId();
    ProjectMember projectMember = new ProjectMember();
    projectMember.setId(SnowflakeIdWorker.getId());
    projectMember.setUserId(userId);
    projectMember.setCreator((byte) DBEnumInt.CREATOR_Y.getIndex());
    projectMember.setProjectId(projectId);
    projectMember.setCreateTime(new Date());
    try {
        this.projectMemberMapper.insert(projectMember);
        return projectMember;
    } catch (DuplicateKeyException ex) {
        logger.warn("project member duplicate key " + ex.getMessage());
        return this.find(userId, projectId);
    }
}
 
Example #18
Source File: TestSuiteService.java    From server with MIT License 5 votes vote down vote up
public Response add(TestSuite testSuite) {
    testSuite.setCreateTime(new Date());
    testSuite.setCreatorUid(SecurityUtil.getCurrentUserId());

    int insertRow;
    try {
        insertRow = testSuiteMapper.insertSelective(testSuite);
    } catch (DuplicateKeyException e) {
        return Response.fail("命名冲突");
    }
    return insertRow == 1 ? Response.success("添加TestSuite成功") : Response.fail("添加TestSuite失败");
}
 
Example #19
Source File: RecommendationServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Recommendation createRecommendation(Recommendation body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    RecommendationEntity entity = mapper.apiToEntity(body);
    Mono<Recommendation> newEntity = repository.save(entity)
        .log()
        .onErrorMap(
            DuplicateKeyException.class,
            ex -> new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Recommendation Id:" + body.getRecommendationId()))
        .map(e -> mapper.entityToApi(e));

    return newEntity.block();
}
 
Example #20
Source File: ProjectService.java    From server with MIT License 5 votes vote down vote up
public Response add(Project project) {
    project.setCreateTime(new Date());
    project.setCreatorUid(SecurityUtil.getCurrentUserId());

    int insertRow;
    try {
        insertRow = projectMapper.insertSelective(project);
    } catch (DuplicateKeyException e) {
        return Response.fail("命名冲突");
    }
    return insertRow == 1 ? Response.success("添加Project成功") : Response.fail("添加Project失败,请稍后重试");
}
 
Example #21
Source File: EnvironmentService.java    From server with MIT License 5 votes vote down vote up
public Response add(Environment environment) {
    environment.setCreateTime(new Date());
    environment.setCreatorUid(SecurityUtil.getCurrentUserId());

    int insertRow;
    try {
        insertRow = environmentMapper.insertSelective(environment);
    } catch (DuplicateKeyException e) {
        return Response.fail("命名冲突");
    }
    return insertRow == 1 ? Response.success("添加成功") : Response.fail("添加失败,请稍后重试");
}
 
Example #22
Source File: SyncServiceImpl.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
/**
 * 添加应用用户
 *
 * @param info
 * @param application
 * @return
 */
protected int addAppUser(final UserInfo info, final Application application) {
    if (info == null) {
        return 0;
    }
    try {
        ApplicationUser applicationUser = new ApplicationUser(application.identity(), info.identity());
        applicationUser.setCreateBy(info.getUser());
        applicationUser.setUpdateBy(info.getUser());
        return userService.addAppUser(applicationUser);
    } catch (DuplicateKeyException e) {
        //忽略唯一索引冲突
        return 0;
    }
}
 
Example #23
Source File: RecommendationServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Recommendation createRecommendation(Recommendation body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    RecommendationEntity entity = mapper.apiToEntity(body);
    Mono<Recommendation> newEntity = repository.save(entity)
        .log()
        .onErrorMap(
            DuplicateKeyException.class,
            ex -> new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Recommendation Id:" + body.getRecommendationId()))
        .map(e -> mapper.entityToApi(e));

    return newEntity.block();
}
 
Example #24
Source File: SheetsReadModel.java    From library with MIT License 5 votes vote down vote up
@Override
@EventListener
public void handle(BookCheckedOut event) {
    try {
        createNewCheckout(event);
    } catch (DuplicateKeyException ex) {
        //idempotent operation
    }
}
 
Example #25
Source File: SheetsReadModel.java    From library with MIT License 5 votes vote down vote up
@Override
@Transactional
@EventListener
public void handle(BookPlacedOnHold event) {
    try {
        createNewHold(event);
    } catch (DuplicateKeyException ex) {
        //idempotent operation
    }
}
 
Example #26
Source File: ProductServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Product createProduct(Product body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    ProductEntity entity = mapper.apiToEntity(body);
    Mono<Product> newEntity = repository.save(entity)
        .log()
        .onErrorMap(
            DuplicateKeyException.class,
            ex -> new InvalidInputException("Duplicate key, Product Id: " + body.getProductId()))
        .map(e -> mapper.entityToApi(e));

    return newEntity.block();
}
 
Example #27
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example #28
Source File: RecommendationServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Recommendation createRecommendation(Recommendation body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    RecommendationEntity entity = mapper.apiToEntity(body);
    Mono<Recommendation> newEntity = repository.save(entity)
        .log()
        .onErrorMap(
            DuplicateKeyException.class,
            ex -> new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Recommendation Id:" + body.getRecommendationId()))
        .map(e -> mapper.entityToApi(e));

    return newEntity.block();
}
 
Example #29
Source File: AgentServiceImpl.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public Agent update(String token, String name, Set<String> tags) {
    Agent agent = getByToken(token);
    agent.setName(name);
    agent.setTags(tags);

    try {
        return agentDao.save(agent);
    } catch (DuplicateKeyException e) {
        throw new DuplicateException("Agent name {0} is already defined", name);
    }
}
 
Example #30
Source File: UserOrderReportSubscriber.java    From libevent with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
@Override
public void onEvent(Event e) {
    Order order = Order.fromJson(e.getContext());
    while (true) {
        UserOrderReport report = orderRepos.selectUserOrderReportByKey(order.getUserId());

        if (null == report) {
            report = new UserOrderReport();
            report.setUserId(order.getUserId());
            report.setOrderNum(0L);
            report.setOrderTotal(0L);

            try {
                orderRepos.createUserOrderReport(report);
            } catch (DuplicateKeyException ex) {
                log.warn("Duplicated message " + eventSerde.toJson(e));
            }
        } else {
            report.setOrderNum(1L);
            report.setOrderTotal(Long.valueOf(order.getOrderAmount()));

            orderRepos.updateUserOrderReport(report);
            break;
        }
    }
}