Java 类org.springframework.transaction.interceptor.TransactionAspectSupport 实例源码

项目:sql-streams-spring    文件:SqlStreamTransactionAwareProxy.java   
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
    Sql sql = this.sql;

    if (method.getDeclaringClass() == SqlStreamHolder.class) {
        return sql;
    }

    TransactionStatus transactionStatus = null;
    try {
        transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    } catch (NoTransactionException e) {
        if (FAIL_WITHOUT_TRANSACTION) {
            throw e;
        }
    }
    if (transactionStatus instanceof SqlStreamTransactionStatus) {
        sql = ((SqlStreamTransactionStatus) transactionStatus).transaction;
    }

    return method.invoke(sql, objects);
}
项目:classchecks    文件:ClockinAsTeacherServiceImpl.java   
/**
 * (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;
    }
}
项目:ZeroSSH    文件:AdminServiceImpl.java   
@Override
public AdminLoginResult login(String sessionId, String username, String orginealPassword) {
    try {
        Admin admin = adminDao.get(username);
        if (admin == null) {
            return AdminLoginResult.PASSWORD_WRONG;
        }
        String salt = admin.getPasswordSalt();
        String password = securityService.uglifyPassoword(orginealPassword, salt);
        if (admin.getPassword().equals(password) == false) {
            return AdminLoginResult.PASSWORD_WRONG;
        } else if (admin.isSuspended()) {
            return AdminLoginResult.SUSPENDED_STATUS;
        }
        adminOnlineDao.clear(SESSION_LIFE_MINUTE);
        if (adminOnlineDao.isExist(sessionId)) {
            return AdminLoginResult.ADMIN_LOGINED;
        }
        adminOnlineDao.saveAdminOnline(sessionId, admin);
        return AdminLoginResult.SUCCESS;
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return AdminLoginResult.DATABASE_EXCEPTION;
    }
}
项目:ZeroSSH    文件:UserServiceImp.java   
@Override
public UserLoginResult login(String sessionId, String userAuth, String orginealPassword) {
    try {
        String userAuthId = makeUserAuthId(userAuth);
        User user = checkUser(userAuthId, orginealPassword + "");
        if (user == null) {
            return UserLoginResult.PASSWORD_WRONG;
        }
        userOnlineDao.clear(SESSION_LIFE_MINUTE);
        if (userOnlineDao.isExist(sessionId)) {
            return UserLoginResult.USER_LOGINED;
        }
        userOnlineDao.saveUserOnline(sessionId, user);
        return UserLoginResult.SUCCESS;
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return UserLoginResult.DATABASE_EXCEPTION;
    }
}
项目:ZeroSSH    文件:LinkServiceImpl.java   
@Override
public AddLinkGroupResult addLinkGroup(String namespace, String pageName, String name, String comment, int picWidth, int picHeight) {
    AddLinkGroupResult result = validateAddLinkGroup(namespace, pageName, name, comment, picWidth, picHeight);
    if (result != null) {
        return result;
    }
    try {
        if (linkGroupDao.isExist(namespace, pageName, name)) {
            return AddLinkGroupResult.DUPLICATE_GROUP;
        }
        linkGroupDao.addLinkGroup(namespace, pageName, name, comment, picWidth, picHeight);
    } catch (RuntimeException re) {
        System.out.println("Error when addLinkGroup: " + re.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return AddLinkGroupResult.DATABASE_FAIL;
    }
    return AddLinkGroupResult.SUCCESS;
}
项目:ZeroSSH    文件:LinkServiceImpl.java   
@Override
public UpdateLinkGroupResult updateLinkGroupByJSON(JSONObject json) {
    try {
        String namespace = json.getString("namespace");
        String pageName = json.getString("pageName");
        String name = json.getString("name");
        JSONArray linkArray = json.getJSONArray("linkArray");

        LinkGroup linkGroup = linkGroupDao.getLinkGroup(namespace, pageName, name);
        removeAllLinks(linkGroup);
        saveLinks(linkGroup.getId(), linkArray);
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        re.printStackTrace();
        return UpdateLinkGroupResult.DATABASE_FAIL;
    }
    return UpdateLinkGroupResult.SUCCESS;
}
项目:ZeroSSH    文件:PageServiceImpl.java   
@Override
public boolean addCategory(String name, String description) {
    try {
        if (pageCategoryDao.get(name) != null) {
            throw new RuntimeException("this category is existing.");
        }
        PageCategory category = new PageCategory();
        category.setName(name);
        category.setDescription(description);
        pageCategoryDao.save(category);
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:ZeroSSH    文件:PageServiceImpl.java   
@Override
public boolean removePage(int id) {
    try {
        Page page = pageDao.get(id);
        for (PageImage image : page.getPageImageList()) {
            String uuid = image.getImgId();
            storageService.delete(uuid);
            pageImageDao.delete(image);
        }
        pageDao.delete(page);
    } catch (RuntimeException re) {
        System.out.println("Error when removePage:" + re.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:openregistry    文件:DefaultEmailService.java   
@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;
}
项目:openregistry    文件:DefaultEmailService.java   
@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;
}
项目:openregistry    文件:DefaultEmailService.java   
@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;
}
项目:openregistry    文件:DefaultPersonService.java   
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);
}
项目:alfresco-core    文件:SpringAwareUserTransactionTest.java   
private void checkNoStatusOnThread()
{
    try
    {
        TransactionAspectSupport.currentTransactionStatus();
        fail("Spring transaction info is present outside of transaction boundaries");
    }
    catch (NoTransactionException e)
    {
        // expected
    }
}
项目:spring-boot-start-current    文件:TransactionUtils.java   
/**
 * 手动进行回滚事务.
 * 接口中如果 try catch 异常无法回滚时,这手动调用回滚处理
 */
public static void rollback () {
    TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    if ( null != transactionStatus ) {
        transactionStatus.setRollbackOnly();
    }
}
项目:classchecks    文件:TeacherRegisterServiceImpl.java   
@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;
    }
项目:classchecks    文件:RegisterServiceImpl.java   
@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]);
    }
项目:ZeroSSH    文件:AdminServiceImpl.java   
@Override
public boolean logout(String sessionId) {
    try {
        AdminOnline adminOnline = adminOnlineDao.get(sessionId);
        if (adminOnline != null) {
            adminOnlineDao.delete(adminOnline);
        }
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:ZeroSSH    文件:UserServiceImp.java   
@Override
public boolean logout(String sessionId) {
    try {
        UserOnline userOnline = userOnlineDao.get(sessionId);
        if (userOnline != null) {
            userOnlineDao.delete(userOnline);
        }
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:ZeroSSH    文件:PageServiceImpl.java   
@Override
public boolean removeCategory(String name) {
    try {
        PageCategory category = pageCategoryDao.get(name);
        pageCategoryDao.delete(category);
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:ZeroSSH    文件:PageServiceImpl.java   
@Override
public AddPageResult addPage(String category, String title, String description, String content) {
    AddPageResult result = AddPageResult.FAIL;
    try {
        PageCategory pageCategory = pageCategoryDao.get(category);
        if (pageCategory == null) {
            result = AddPageResult.NO_CATEGORY;
            throw new RuntimeException("no category");
        } else if (title == null || title.length() == 0) {
            result = AddPageResult.NO_TITLE;
            throw new RuntimeException("no title");
        } else if (content == null || content.length() == 0) {
            result = AddPageResult.NO_CONTENT;
            throw new RuntimeException("no content");
        }
        Date now = new Date();
        Page page = new Page();
        page.setCategory(pageCategory);
        page.setTitle(title);
        page.setDescription(description);
        page.setContent(content);
        page.setCreateTime(now);
        page.setLastModifyTime(now);
        pageDao.save(page);

        Set<String> imgIdSet = imagePathService.pickImageIdSet(content);
        saveImage(page, imgIdSet);
        result = AddPageResult.SUCCESS;
    } catch (RuntimeException re) {
        System.out.println("Error when addPage:" + re.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
    return result;
}
项目:ZeroSSH    文件:PageServiceImpl.java   
@Override
public UpdatePageResult updatePage(int id, String title, String description, String content) {
    UpdatePageResult result = UpdatePageResult.FAIL;
    try {
        if (title == null || title.length() == 0) {
            result = UpdatePageResult.NO_TITLE;
            throw new RuntimeException("no title");
        } else if (content == null || content.length() == 0) {
            result = UpdatePageResult.NO_CONTENT;
            throw new RuntimeException("no content");
        }
        Page page = pageDao.get(id);
        page.setContent(content);
        page.setDescription(description);
        page.setLastModifyTime(new Date());
        page.setTitle(title);

        Set<String> imgIdSet = imagePathService.pickImageIdSet(content);
        removeImageWhenUpdatePage(page, imgIdSet);
        saveImage(page, imgIdSet);
        result = UpdatePageResult.SUCCESS;
    } catch (RuntimeException re) {
        System.out.println("Error when updatePage:" + re.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
    return result;
}
项目:ZeroSSH    文件:ValueConfigServiceImpl.java   
@Override
public boolean insertValueConfig(String namespace, String pageName, String name, String val) {
    try {
        valueConfigDao.insertValueConfig(namespace, pageName, name, val);
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:ZeroSSH    文件:ValueConfigServiceImpl.java   
@Override
public boolean updateValueConfig(String namespace, String pageName, Map<String, List<String>> valueConfigMap) {
    try {
        valueConfigDao.updateValueConfig(namespace, pageName, valueConfigMap);
    } catch (RuntimeException re) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }
    return false;
}
项目:gemfirexd-oss    文件:SpringTxnManager.java   
public void rollback() {
    //Programmatic way to roll back current transaction
    TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();

    //Declarative way to roll back current transaction
    //throw new RollbackIndicatorException();
}
项目:soeasy    文件:BizInterceptor.java   
@Override
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object target = methodInvocation.getThis();
    if (target instanceof AbstractBiz) {
        Class bizClass = target.getClass();
        logger.debug(bizClass.getName());
        Annotation annotation = bizClass.getDeclaredAnnotation(Api.class);
        if (annotation != null) {
            if (annotation instanceof Api) {
                Api api = (Api) annotation;
                logger.debug("\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=\\/=");
                logger.debug("{}开始调用:{}【{}】", PERFIX, api.name(), bizClass.getName());
                long start = System.currentTimeMillis();
                Object result;
                try {
                    Object[] objects = methodInvocation.getArguments();
                    if (objects.length > 0 && objects[0] instanceof BaseRequestDto) {
                        logger.debug("{} {}请求参数:{}", PERFIX, api.name(), objects[0].toString());
                    }
                    result = methodInvocation.proceed();
                    logger.debug("{} {}响应参数:{}", PERFIX, api.name(), result.toString());
                } catch (Exception e) {
                    logger.error(PERFIX + api.name() + "调用异常:{}", e);
                    result = Result.getFailureResult(FailureCodeEnum.SERVICE_EXCEPTION.getCode(),
                            FailureCodeEnum.SERVICE_EXCEPTION.getMsg() + ";异常信息:" + e);
                    //事物回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                } finally {
                    long end = System.currentTimeMillis();
                    logger.debug("{}调用完成:{}【{}】,耗时{}ms", PERFIX, api.name(), bizClass.getName(), end - start);
                    logger.debug("/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=/\\=");
                }
                return result;
            }
        }
    }
    return methodInvocation.proceed();
}
项目:communote-server    文件:TransactionManagementImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public <T> T execute(RunInTransactionWithResult<T> runInTransaction) {
    try {
        return runInTransaction.execute();
    } catch (TransactionException e) {
        LOGGER.warn("Rolling back transaction: {0}", e.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        // pass the actual cause
        throw new TransactionManagementException("Transactional operation failed", e.getCause());
    }
}
项目:communote-server    文件:TransactionManagementImpl.java   
/**
 * This uses propagation REQUIRES_NEW
 *
 * @param runInTransaction
 *            {@link com.communote.server.core.general.RunInTransaction}
 */
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void executeInNew(RunInTransaction runInTransaction) {
    try {
        runInTransaction.execute();
    } catch (TransactionException e) {
        LOGGER.warn("Rolling back transaction: {0}", e.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}
项目:communote-server    文件:TransactionManagementImpl.java   
/**
 * This uses propagation REQUIRES_NEW
 *
 * @param <T>
 *            Type of the result.
 * @param runInTransaction
 *            The run in transaction
 * @return The result.
 */
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public <T> T executeInNew(RunInTransactionWithResult<T> runInTransaction) {
    try {
        return runInTransaction.execute();
    } catch (TransactionException e) {
        LOGGER.warn("Rolling back transaction: {0}", e.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        // pass the actual cause
        throw new TransactionManagementException("Transactional operation failed", e.getCause());
    }
}
项目:communote-server    文件:TransactionManagementImpl.java   
/**
 * {@inheritDoc}
 */
@Override
protected void handleExecute(RunInTransaction runInTransaction) {
    try {
        runInTransaction.execute();
    } catch (TransactionException e) {
        LOGGER.warn("Rolling back transaction: {0}", e.getMessage());
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}
项目:ccshop    文件:BaseAction.java   
/**
    * 事务回滚
    */
   public static boolean setTransactionRollback() {
    try {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    } catch (Exception e) {
        return false;
    }
}
项目:gemfirexd-oss    文件:SpringTxnManager.java   
public void rollback() {
    //Programmatic way to roll back current transaction
    TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();

    //Declarative way to roll back current transaction
    //throw new RollbackIndicatorException();
}
项目:dbapp    文件:CatalogService.java   
public Boolean drop(int lectureId) {
    try {
        lectureMapper.deleteLectureTime(lectureId);
        return lectureMapper.deleteLecture(lectureId) > 0;
    } catch (Exception e) {
        TransactionAspectSupport.currentTransactionStatus()
                .setRollbackOnly();
        return false;
    }
}
项目:dbapp    文件:CatalogService.java   
public Boolean create(int majorId, int year, int schoolYear,
        String lectureNumber, String subjectId, String instructorName) {
    try {
        final Integer roomId = null;
        final int limit = 40;

        String instructorId = userMapper.getInstructorByName(instructorName);
        return lectureMapper.createLecture(lectureNumber, subjectId,
                majorId, schoolYear, instructorId, limit, roomId, year) > 0;
    } catch (Exception e) {
        TransactionAspectSupport.currentTransactionStatus()
                .setRollbackOnly();
        return false;
    }
}
项目:openregistry    文件:DefaultPersonService.java   
@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);
}
项目:openregistry    文件:DefaultPersonService.java   
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);
}
项目:openregistry    文件:DefaultPersonService.java   
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);
}
项目:alfresco-core    文件:SpringAwareUserTransaction.java   
/**
 * 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;
}
项目:spring4-understanding    文件:TransactionAspectTests.java   
public void setTransactionAspect(TransactionAspectSupport transactionAspect) {
    this.txManager = (CallCountingTransactionManager) transactionAspect.getTransactionManager();
}
项目:nimble-orm    文件:P0_JdbcTemplateOp.java   
@Override
public void rollback() {
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
项目:class-guard    文件:TransactionAspectTests.java   
public void setTransactionAspect(TransactionAspectSupport transactionAspect) {
    this.transactionAspect = transactionAspect;
    this.txManager = (CallCountingTransactionManager) transactionAspect.getTransactionManager();
}