org.springframework.transaction.interceptor.TransactionAspectSupport Java Examples

The following examples show how to use org.springframework.transaction.interceptor.TransactionAspectSupport. 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: UserServiceImpl.java    From springBoot-study with Apache License 2.0 7 votes vote down vote up
@Override
@Transactional
public boolean test3(User user) {

	/*
	 * 子方法出现异常进行回滚
	 */
	try {
		System.out.println("查询的数据1:" + udao.findById(user.getId()));
		deal1(user);
		deal2(user);
		deal3(user);
	} catch (Exception e) {
		System.out.println("发生异常,进行手动回滚!");
		// 手动回滚事物
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		e.printStackTrace();
	} 
	return false;

}
 
Example #2
Source File: UserServiceImpl.java    From springBoot-study with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public boolean test2(User user) {

	/*
	 * 简单的事物回滚 自己捕获该异常进行手动回滚
	 */
	long id = user.getId();
	try {
		System.out.println("查询的数据1:" + udao.findById(id));
		// 新增两次,会出现主键ID冲突,看是否可以回滚该条数据
		udao.insert(user);
		System.out.println("查询的数据2:" + udao.findById(id));
		udao.insert(user);
	} catch (Exception e) {
		System.out.println("发生异常,进行手动回滚!");
		// 手动回滚事物
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		// 注意手动回滚事物要在异常抛出之前!
		e.printStackTrace();
	}

	return false;
}
 
Example #3
Source File: DefaultPersonService.java    From openregistry with Apache License 2.0 6 votes vote down vote up
public ServiceExecutionResult<ReconciliationResult> reconcile(final ReconciliationCriteria reconciliationCriteria) throws IllegalArgumentException {
    Assert.notNull(reconciliationCriteria, "reconciliationCriteria cannot be null");
    logger.info("reconcile start");
    final Set validationErrors = this.validator.validate(reconciliationCriteria);

    if (!validationErrors.isEmpty()) {
        Iterator iter = validationErrors.iterator();
        while (iter.hasNext()) {
            logger.info("validation errors: " + iter.next());
        }
        logger.info("reconcile start");
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384
        if( TransactionAspectSupport.currentTransactionStatus()!=null){
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         }


        return new GeneralServiceExecutionResult<ReconciliationResult>(validationErrors);
    }

    final ReconciliationResult result = this.reconciler.reconcile(reconciliationCriteria);
    //(reconciliationCriteria, result);
    return new GeneralServiceExecutionResult<ReconciliationResult>(result);
}
 
Example #4
Source File: DefaultEmailService.java    From openregistry with Apache License 2.0 6 votes vote down vote up
@Override
//OR-386
public List<ServiceExecutionResult<SorPerson>> saveOrCreateEmailForAllSorPersons(List<SorPerson> sorPersons,String emailAddress,Type emailType) {
    List <ServiceExecutionResult<SorPerson>> listOfServiceExecutionResults = new ArrayList<ServiceExecutionResult<SorPerson>>();
    for(SorPerson sorPerson:sorPersons){
        ServiceExecutionResult<SorPerson> result = null;
        result = saveOrCreateEmailForSorPersonForAllRoles(sorPerson,
                emailAddress,
                emailType);

        listOfServiceExecutionResults.add(result);
        if(!result.succeeded()){
            //transaction rollback
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //there is no need to execute the loop as the trasnaction is rolling back
            break;
        }

    }
    return listOfServiceExecutionResults;
}
 
Example #5
Source File: DefaultEmailService.java    From openregistry with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceExecutionResult<SorPerson> saveOrCreateEmailForSorPersonForAllRoles(SorPerson sorPerson, String emailAddress,
                                                                                               Type emailType) {

    //get all the roles for an SorPerson
    List<SorRole> openRoles = sorPerson.getRoles();
    if (openRoles.isEmpty()) {
        return new GeneralServiceExecutionResult<SorPerson>((SorPerson) null);
    }
    for (SorRole r : openRoles) {
        r.addOrUpdateEmail(emailAddress, emailType);
    }

    ServiceExecutionResult<SorPerson> ser = this.personService.updateSorPerson(sorPerson);
    //OR-384
    if(!ser.succeeded()){
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
    return ser;
}
 
Example #6
Source File: DefaultEmailService.java    From openregistry with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceExecutionResult<SorPerson> saveOrCreateEmailForSorPersonWithRoleIdentifiedByAffiliation(SorPerson sorPerson,
                                                                                                      String emailAddress,
                                                                                                      Type emailType,
                                                                                                      Type affiliationType) {
    List<SorRole> openRoles = sorPerson.findOpenRolesByAffiliation(affiliationType);
    if (openRoles.isEmpty()) {
        return new GeneralServiceExecutionResult<SorPerson>((SorPerson) null);
    }
    for (SorRole r : openRoles) {
        r.addOrUpdateEmail(emailAddress, emailType);
    }

    ServiceExecutionResult<SorPerson> ser = this.personService.updateSorPerson(sorPerson);
    //OR-384
    if(!ser.succeeded()){
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
    return ser;
}
 
Example #7
Source File: ClockinAsTeacherServiceImpl.java    From classchecks with Apache License 2.0 6 votes vote down vote up
/**
 * (non-Javadoc)
 * 
 * @see com.classchecks.client.teacher.api.clockin.service.ClockinAsTeacherService#saveClockInRecord(java.lang.String,
 *      java.util.List)
 */
@Override
@Transactional(readOnly=false, rollbackFor=RuntimeException.class)
public boolean saveClockInRecord(String jwAccount, Double lng, Double lat, List<TeachingRosterVo> studentList) {

	try {
		// 获得现在的学校时钟
		// 获得现在指定教师的课程时间ID
		SchoolCourseClockModel schoolCourseClockModel = basicService.getSchoolCourseClockModelNow();
		Integer idCourseTime = clockinAsTeacherMapper.getCourseTimeByTeacherNoNow(jwAccount, schoolCourseClockModel);
		if (idCourseTime == null) {
			LOG.debug("获取教师课程时间ID时失败,未找到");
			return false;
		}
		// 添加教师考勤记录
		clockinAsTeacherMapper.insertClockInRecord(jwAccount, idCourseTime, lng, lat, schoolCourseClockModel);
		// 添加学生考勤记录
		clockinAsTeacherMapper.insertStudentClockInRecord(idCourseTime, schoolCourseClockModel.getWeek(), studentList);
		return true;
	} catch(RuntimeException ex) {
		LOG.info("数据库异常.....", ex);
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		return false;
	}
}
 
Example #8
Source File: DefaultPersonService.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public ServiceExecutionResult<SorRole> updateSorRole(final SorPerson sorPerson, final SorRole sorRole) {
    Assert.notNull(sorPerson, "sorPerson cannot be null.");
    Assert.notNull(sorRole, "sorRole cannot be null.");

    final Set validationErrors = this.validator.validate(sorRole);

    if (!validationErrors.isEmpty()) {
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384
        if( TransactionAspectSupport.currentTransactionStatus()!=null){
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         }


        return new GeneralServiceExecutionResult<SorRole>(validationErrors);
    }

    final SorRole savedSorRole = this.personRepository.saveSorRole(sorRole);

    final Person person = this.personRepository.findByInternalId(sorPerson.getPersonId());
    final Role role = person.findRoleBySoRRoleId(savedSorRole.getId());
    if(role!=null){
       //update calculated role only if that role was previously converted to calculated one by sorRoleElector
      role.recalculate(savedSorRole);
      this.personRepository.savePerson(person);
    }
    //else //do nothing i.e. don't update the calculated role if SorRoleElector Previously decided not to convert this sor role to calculated role

    return new GeneralServiceExecutionResult<SorRole>(savedSorRole);
}
 
Example #9
Source File: PasswordForgetServiceImpl.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public PasswordForgetDTO resetPassword(String token, String password) {
    // 使用token,查出存在redis里的email,然后再根据email查出用户信息
    String email = getEmailByToken(token);
    UserE user = userService.queryByEmail(email);
    PasswordForgetDTO passwordForgetDTO = new PasswordForgetDTO();
    try {
        BaseUserDTO baseUser = new BaseUserDTO();
        BeanUtils.copyProperties(user, baseUser);
        baseUser.setPassword(password);
        BasePasswordPolicyDTO basePasswordPolicyDO = new BasePasswordPolicyDTO();
        basePasswordPolicyDO.setOrganizationId(user.getOrganizationId());
        basePasswordPolicyDO = basePasswordPolicyMapper.selectOne(basePasswordPolicyDO);
        passwordPolicyManager.passwordValidate(password, baseUser, basePasswordPolicyDO);
        userPasswordValidator.validate(password, user.getOrganizationId(), true);
    } catch (CommonException e) {
        LOGGER.error(e.getMessage());
        passwordForgetDTO.setSuccess(false);
        passwordForgetDTO.setMsg(e.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return passwordForgetDTO;
    }
    user.setPassword(ENCODER.encode(password));
    UserE userE = userService.updateSelective(user);
    if (userE != null) {
        passwordRecord.updatePassword(user.getId(), ENCODER.encode(password));
        passwordForgetDTO.setSuccess(true);
        redisTokenUtil.expireByKey(token);
        passwordForgetDTO.setUser(new UserDTO(userE.getId(), userE.getLoginName(), user.getEmail()));

        this.sendSiteMsg(user.getId(), user.getRealName());
        return passwordForgetDTO;
    }

    return new PasswordForgetDTO(false);
}
 
Example #10
Source File: DefaultPersonService.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public ServiceExecutionResult<Person> addPerson(final ReconciliationCriteria reconciliationCriteria) throws ReconciliationException, IllegalArgumentException, SorPersonAlreadyExistsException {
        Assert.notNull(reconciliationCriteria, "reconciliationCriteria cannot be null");
        logger.info("addPerson start");
    if (reconciliationCriteria.getSorPerson().getSorId() != null && this.findBySorIdentifierAndSource(reconciliationCriteria.getSorPerson().getSourceSor(), reconciliationCriteria.getSorPerson().getSorId()) != null) {
        //throw new IllegalStateException("CANNOT ADD SAME SOR RECORD.");
        throw new SorPersonAlreadyExistsException(this.findBySorIdentifierAndSource(reconciliationCriteria.getSorPerson().getSourceSor(), reconciliationCriteria.getSorPerson().getSorId()));
    }

    final Set validationErrors = this.validator.validate(reconciliationCriteria);

    if (!validationErrors.isEmpty()) {
        Iterator iter = validationErrors.iterator();
        while (iter.hasNext()) {
            logger.info("validation errors: " + iter.next());
        }
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384
        if( TransactionAspectSupport.currentTransactionStatus()!=null){
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         }


        return new GeneralServiceExecutionResult<Person>(validationErrors);
    }

    final ReconciliationResult result = this.reconciler.reconcile(reconciliationCriteria);

    switch (result.getReconciliationType()) {
        case NONE:
            return new GeneralServiceExecutionResult<Person>(saveSorPersonAndConvertToCalculatedPerson(reconciliationCriteria));

        case EXACT:
            return new GeneralServiceExecutionResult<Person>(addNewSorPersonAndLinkWithMatchedCalculatedPerson(reconciliationCriteria, result));
    }

    this.criteriaCache.put(reconciliationCriteria, result);
    logger.info("addPerson start");
    throw new ReconciliationException(result);
}
 
Example #11
Source File: DefaultPersonService.java    From openregistry with Apache License 2.0 5 votes vote down vote up
@PreAuthorize("hasPermission(#sorRole, 'admin')")
public ServiceExecutionResult<SorRole> validateAndSaveRoleForSorPerson(final SorPerson sorPerson, final SorRole sorRole) {
	logger.info(" validateAndSaveRoleForSorPerson start");
	 Assert.notNull(sorPerson, "SorPerson cannot be null.");
    Assert.notNull(sorRole, "SorRole cannot be null.");

    // check if the SoR Role has an ID assigned to it already and assign source sor
    setRoleIdAndSource(sorRole, sorPerson.getSourceSor());

    final Set validationErrors = this.validator.validate(sorRole);

    if (!validationErrors.isEmpty()) {
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384
       if( TransactionAspectSupport.currentTransactionStatus()!=null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return new GeneralServiceExecutionResult<SorRole>(validationErrors);
    }

    final SorPerson newSorPerson = this.personRepository.saveSorPerson(sorPerson);
    Person person = this.personRepository.findByInternalId(newSorPerson.getPersonId());
    final SorRole newSorRole = newSorPerson.findSorRoleBySorRoleId(sorRole.getSorId());
    //let sor role elector decide if this new role can be converted to calculated one
    sorRoleElector.addSorRole(newSorRole,person);
    person = recalculatePersonBiodemInfo(person, newSorPerson, RecalculationType.UPDATE, false);
    this.personRepository.savePerson(person);
    logger.info("validateAndSaveRoleForSorPerson end");
    return new GeneralServiceExecutionResult<SorRole>(newSorRole);
}
 
Example #12
Source File: SpringTxnManager.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void rollback() {
	//Programmatic way to roll back current transaction
	TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
	
	//Declarative way to roll back current transaction
	//throw new RollbackIndicatorException();
}
 
Example #13
Source File: SpringTxnManager.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void rollback() {
	//Programmatic way to roll back current transaction
	TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
	
	//Declarative way to roll back current transaction
	//throw new RollbackIndicatorException();
}
 
Example #14
Source File: RegisterServiceImpl.java    From classchecks with Apache License 2.0 5 votes vote down vote up
@Override
	@Transactional(readOnly = false, rollbackFor = RuntimeException.class)
	public BasicVo register(String phone, String smscode, String regID, CommonsMultipartFile[] files) {
		// 检测数据库是否已有记录,这里检查是防止用户获取验证码成功后,更换一个已有的手机号输入
		boolean hasPhone = smsCodeMapper.hasPhoneRegistered(phone).length > 0 ? true : false;
		if(hasPhone) {
			return new BasicVo(RegisterBusinessCode.BUSSINESS_PHONE_EXIST[0], RegisterBusinessCode.BUSSINESS_PHONE_EXIST[1]);
		}
		
		// 调用短信接口验证输入的短信验证码是否可用
		boolean isVerify = SMSUtil.verifySmsCode(phone, smscode);
		
		if(isVerify) {
			BasicVo basicVo = null;
			try {
				SecurityAccountVo secAcc = new SecurityAccountVo();
				secAcc.setSecurityAccount(phone);
				secAcc.setSecuritSmsCode(smscode);
				secAcc.setRegID(regID);
				secAcc.setSecuritType(Student_User_Type);
//				// 插入数据
				registerMapper.saveRegisterInfo(secAcc);
				secAcc = registerMapper.findAccountByPhone(phone);
				LOG.info("secAcc="+secAcc);
				fileSave(files, phone); // 保存上传的图片到临时位置
				// 图片预处理
				rawFaceProc(ImgStoragePath.RAW_FACE_IMG_SAVE_PATH+File.separator+phone,
						ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, secAcc.getFaceLabel());
				// 生成CSV标签
				generateCSV(ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, ImgStoragePath.CSV_FILE_SAVE_PATH);
				basicVo = new BasicVo(RegisterBusinessCode.BUSINESS_SUCCESS[0], RegisterBusinessCode.BUSINESS_SUCCESS[1]);
			} catch(Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				basicVo = new BasicVo(RegisterBusinessCode.BUSSINESS_FAILED[0], RegisterBusinessCode.BUSSINESS_FAILED[1]);
				LOG.error("学生注册错误", e);
			}
			return basicVo;
		}
		return new BasicVo(RegisterBusinessCode.BUSSINESS_SMS_ERROR[0], RegisterBusinessCode.BUSSINESS_SMS_ERROR[1]);
	}
 
Example #15
Source File: TeacherRegisterServiceImpl.java    From classchecks with Apache License 2.0 5 votes vote down vote up
@Override
	@Transactional(readOnly=false, rollbackFor = RuntimeException.class)
	public BasicVo teacherRegister(String phone, String smscode, String regID) {
		// 检测数据库是否已有记录,这里检查是防止用户获取验证码成功后,更换一个已有的手机号输入
		boolean hasPhone = smsCodeMapper.hasPhoneRegistered(phone).length > 0 ? true : false;
		if(hasPhone) {
			return new BasicVo(RegisterBusinessCode.BUSSINESS_PHONE_EXIST[0], RegisterBusinessCode.BUSSINESS_PHONE_EXIST[1]);
		}
		
		// 调用短信接口验证输入的短信验证码是否可用
		boolean isVerify = SMSUtil.verifySmsCode(phone, smscode);
		
		if(!isVerify) { // 当短信验证失败后直接返回‘验证码错误’消息
			return new BasicVo(RegisterBusinessCode.BUSSINESS_SMS_ERROR[0], RegisterBusinessCode.BUSSINESS_SMS_ERROR[1]);
		}
		
		BasicVo basicVo = null;
		try {
			SecurityAccountVo secAcc = new SecurityAccountVo();
			secAcc.setSecurityAccount(phone);
			secAcc.setSecuritSmsCode(smscode);
			secAcc.setRegID(regID);
			secAcc.setSecuritType(Teacher_User_Type);
//			// 插入数据
			teacherRegisterMapper.saveRegisterInfo(secAcc);
			basicVo = new BasicVo(RegisterBusinessCode.BUSINESS_SUCCESS[0], RegisterBusinessCode.BUSINESS_SUCCESS[1]);
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			basicVo = new BasicVo(RegisterBusinessCode.BUSSINESS_FAILED[0], RegisterBusinessCode.BUSSINESS_FAILED[1]);
			LOG.error("教师注册错误", e);
		}
		return basicVo;
	}
 
Example #16
Source File: TransactionUtils.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
/**
 * 手动进行回滚事务.
 * 接口中如果 try catch 异常无法回滚时,这手动调用回滚处理
 */
public static void rollback () {
    TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    if ( null != transactionStatus ) {
        transactionStatus.setRollbackOnly();
    }
}
 
Example #17
Source File: PlatformTransactionManagerAdapter.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public TransactionHolder getOrCreateTransaction(boolean start) {
    TransactionStatus status = null;
    try {
        //Spring managed transaction
        status = TransactionAspectSupport.currentTransactionStatus();
    } catch (NoTransactionException e) {
        //Teiid programatically managed transaction
        if (start) {
            status = platformTransactionManager.getTransaction(NEW_TRANSACTION_DEFINITION);
            TransactionHolder holder = new TransactionHolder(status, new PlatformTransactionAdapter(status));
            TRANSACTION_HOLDERS.set(holder);
            return holder;
        } else {
            try {
                status = platformTransactionManager.getTransaction(EXISTING_TRANSACTION_DEFINITION);
                //success means that there is one defined/associated, so we are safe to use
                //the thread local
                return TRANSACTION_HOLDERS.get();
            } catch (TransactionException e1) {
                TRANSACTION_HOLDERS.remove();
            }
        }
    }
    if (status == null) {
        return null;
    }
    synchronized (transactions) {
        PlatformTransactionAdapter adapter = transactions.get(status);
        if (adapter == null) {
            adapter = new PlatformTransactionAdapter(status);
            transactions.put(status, adapter);
        }
        return new TransactionHolder(status, adapter);
    }
}
 
Example #18
Source File: SpringAwareUserTransactionTest.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkNoStatusOnThread()
{
    try
    {
        TransactionAspectSupport.currentTransactionStatus();
        fail("Spring transaction info is present outside of transaction boundaries");
    }
    catch (NoTransactionException e)
    {
        // expected
    }
}
 
Example #19
Source File: TransactionAspectTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public void setTransactionAspect(TransactionAspectSupport transactionAspect) {
	this.txManager = (CallCountingTransactionManager) transactionAspect.getTransactionManager();
}
 
Example #20
Source File: AbstractExportService.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public BulkExportResult doExport(final JobContext context) {

    final JobStatusListener statusListener = context.getListener();

    final ED exportDescriptor = context.getAttribute(JobContextKeys.EXPORT_DESCRIPTOR);
    final String exportDescriptorName = context.getAttribute(JobContextKeys.EXPORT_DESCRIPTOR_NAME);
    final String exportRoot = context.getAttribute(JobContextKeys.EXPORT_DIRECTORY_ROOT);
    final String exportOverrideFile = context.getAttribute(JobContextKeys.EXPORT_FILE);

    try {

        String fileToExport = exportDescriptor.getExportFileDescriptor().getFileName();
        if (StringUtils.isNotBlank(exportOverrideFile)) {
            fileToExport = exportOverrideFile;
        } else {
            if (fileToExport.contains(ROOT_PLACEHOLDER)) {
                fileToExport = fileToExport.replace(ROOT_PLACEHOLDER, exportRoot);
            }
            if (fileToExport.contains(TIMESTAMP_PLACEHOLDER)) {
                fileToExport = fileToExport.replace(TIMESTAMP_PLACEHOLDER, DateUtils.exportFileTimestamp());
                if (new File(fileToExport).exists()) {
                    // Only do this for timestamped files, otherwise we assume that files are re-writable
                    statusListener.notifyError("export file already exists: {}", fileToExport);
                    return BulkExportResult.ERROR;
                }
            }
        }

        statusListener.notifyMessage("Export descriptor {} specifies file {} to export", exportDescriptorName, fileToExport);
        if (exportDescriptor.getSelectCmd() == null) {
            final String msgErr = "export can not be started, because 'select' is empty";
            statusListener.notifyError(msgErr);
            return BulkExportResult.ERROR;
        }
        doExport(statusListener, exportDescriptorName, exportDescriptor, fileToExport);

    } catch (Exception e) {

        /*
         * Programmatically rollback for any error during import - ALL or NOTHING.
         * But we do not throw exception since this is in a separate thread so not point
         * Need to finish gracefully with error status
         */
        if (!TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        statusListener.notifyError("unexpected error {}", e, e.getMessage());
        return BulkExportResult.ERROR;
    }
    return BulkExportResult.OK;
}
 
Example #21
Source File: P0_JdbcTemplateOp.java    From nimble-orm with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void rollback() {
	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
 
Example #22
Source File: SpringAwareUserTransaction.java    From alfresco-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the current transaction info, or null if none exists.
 * <p>
 * A check is done to ensure that the transaction info on the stack is exactly
 * the same instance used when this transaction was started.
 * The internal status is also checked against the transaction info.
 * These checks ensure that the transaction demarcation is done correctly and that
 * thread safety is adhered to.
 * 
 * @return Returns the current transaction
 */
private TransactionInfo getTransactionInfo()
{
    // a few quick self-checks
    if (threadId < 0 && internalStatus != Status.STATUS_NO_TRANSACTION)
    {
        throw new RuntimeException("Transaction has been started but there is no thread ID");
    }
    else if (threadId >= 0 && internalStatus == Status.STATUS_NO_TRANSACTION)
    {
        throw new RuntimeException("Transaction has not been started but a thread ID has been recorded");
    }
    
    TransactionInfo txnInfo = null;
    try
    {
        txnInfo = TransactionAspectSupport.currentTransactionInfo();
        // we are in a transaction
    }
    catch (NoTransactionException e)
    {
        // No transaction.  It is possible that the transaction threw an exception during commit.
    }
    // perform checks for active transactions
    if (internalStatus == Status.STATUS_ACTIVE)
    {
        if (Thread.currentThread().getId() != threadId)
        {
            // the internally stored transaction info (retrieved in begin()) should match the info
            // on the thread
            throw new RuntimeException("UserTransaction may not be accessed by multiple threads");
        }
        else if (txnInfo == null)
        {
            // internally we recorded a transaction starting, but there is nothing on the thread
            throw new RuntimeException("Transaction boundaries have been made to overlap in the stack");
        }
        else if (txnInfo != internalTxnInfo)
        {
            // the transaction info on the stack isn't the one we started with
            throw new RuntimeException("UserTransaction begin/commit mismatch");
        }
    }
    return txnInfo;
}
 
Example #23
Source File: DefaultPersonService.java    From openregistry with Apache License 2.0 4 votes vote down vote up
public ServiceExecutionResult<Person> validateAndSavePersonAndRole(final ReconciliationCriteria reconciliationCriteria)   {
	logger.info(" validateAndSavePersonAndRole start");
    SorPerson sorPerson = reconciliationCriteria.getSorPerson();
    if (sorPerson == null || sorPerson.getRoles() == null)
        throw new IllegalArgumentException("Sor Person not found in provided criteria.");
    SorRole sorRole =  reconciliationCriteria.getSorPerson().getRoles().get(0);
    if  (sorRole == null)
         throw new IllegalArgumentException("Sor Role not found for provided criteria.");

    setRoleIdAndSource(sorRole, sorPerson.getSourceSor());

    final Set validationErrors = this.validator.validate(sorRole);
    
    if (!validationErrors.isEmpty()) {
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384
        if( TransactionAspectSupport.currentTransactionStatus()!=null){
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         }

        return new GeneralServiceExecutionResult<Person>(validationErrors);
    }

    Long personId = sorPerson.getPersonId();
    if (personId == null) {
    	logger.info("calling saveSorPersonAndConvertToCalculatedPerson");
    	   // add new Sor Person and roles, create calculated person
            return new GeneralServiceExecutionResult<Person>(saveSorPersonAndConvertToCalculatedPerson(reconciliationCriteria));
    } else { // Add new Sor Person and role and link to the existing person
                Person thisPerson = this.personRepository.findByInternalId(personId);
                try {
                	logger.info("calling addSorPersonAndLink");
                	  Person savedPerson = this.addSorPersonAndLink(reconciliationCriteria, thisPerson);
                     return new GeneralServiceExecutionResult<Person>(savedPerson);
                } catch (SorPersonAlreadyExistsException sorE) {
                     throw new IllegalArgumentException("If a sor Person of the same source already exists, should call the other method to add the role only");
                }
    }
    
   
}
 
Example #24
Source File: TransactionalBean.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
public String doSomething() {
    // should not throw
    final TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    Assert.assertNotNull(transactionStatus);
    return "foo";
}
 
Example #25
Source File: DefaultPersonService.java    From openregistry with Apache License 2.0 4 votes vote down vote up
/**
 * Persists an SorPerson on update.
 *
 * @param sorPerson the person to update.
 * @return serviceExecutionResult.
 */
public ServiceExecutionResult<SorPerson> updateSorPerson(final SorPerson sorPerson) {
    final Set validationErrors = this.validator.validate(sorPerson);

    if (!validationErrors.isEmpty()) {
        Iterator iter = validationErrors.iterator();
        while (iter.hasNext()) {
            logger.info("validation errors: " + iter.next());
        }
        //since because of existing design we cannot raise exception, we can only rollback the transaction through code
        //OR-384
        if( TransactionAspectSupport.currentTransactionStatus()!=null){
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         }


        return new GeneralServiceExecutionResult<SorPerson>(validationErrors);
    }

    //do reconciliationCheck to make sure that modifications do not cause person to reconcile to a different person
    if (!this.reconciler.reconcilesToSamePerson(sorPerson)) {
        throw new IllegalStateException();
    }

    // Iterate over any sorRoles setting sorid and source id if not specified by SoR.
    for (final SorRole sorRole : sorPerson.getRoles()){
        setRoleIdAndSource(sorRole, sorPerson.getSourceSor());
    }
    
    // Save Sor Person
    final SorPerson savedSorPerson = this.personRepository.saveSorPerson(sorPerson);

    Person person = this.findPersonById(savedSorPerson.getPersonId());

    Assert.notNull(person, "person cannot be null.");

    logger.info("Verifying Number of calculated Roles before the calculate: "+ person.getRoles().size());
   
    // Iterate over sorRoles. SorRoles may be new or updated.
    for (final SorRole savedSorRole:savedSorPerson.getRoles()){
        logger.info("DefaultPersonService: savedSorPersonRole Found, savedSorRoleID: "+ savedSorRole.getId());
        logger.info("DefaultPersonService: savedSorPersonRole Found, Role Must be newly added.");
        //let sor role elector decide if this new role can be converted to calculated one
        sorRoleElector.addSorRole(savedSorRole,person);
        logger.info("Verifying Number of calculated Roles after calculate: "+ person.getRoles().size());
    }
    
    for (final IdentifierAssigner ia : this.identifierAssigners) {
        ia.addIdentifierTo(sorPerson, person);
    }

    person = recalculatePersonBiodemInfo(person, savedSorPerson, RecalculationType.UPDATE, false);
    person =this.personRepository.savePerson(person);

    return new GeneralServiceExecutionResult<SorPerson>(savedSorPerson);
}
 
Example #26
Source File: MetaTransactionalBean.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
public String doSomething() {
    // should not throw
    final TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    Assert.assertNotNull(transactionStatus);
    return "foo";
}
 
Example #27
Source File: TransactionManual.java    From rebuild with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Shadow for TransactionAspectSupport#currentTransactionStatus
 *
 * @return
 */
public static TransactionStatus currentTransactionStatus() {
    return TransactionAspectSupport.currentTransactionStatus();
}