Example usage for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition

List of usage examples for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition

Introduction

In this page you can find the example usage for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition.

Prototype

public DefaultTransactionDefinition() 

Source Link

Document

Create a new DefaultTransactionDefinition, with default settings.

Usage

From source file:com.saysth.commons.quartz.SchedulerAccessor.java

/**
 * Register jobs and triggers (within a transaction, if possible).
 *//*from ww w.j  a v  a2s .c o m*/
protected void registerJobsAndTriggers() throws SchedulerException {
    TransactionStatus transactionStatus = null;
    if (this.transactionManager != null) {
        transactionStatus = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    }
    try {

        if (this.jobSchedulingDataLocations != null) {
            ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader);
            clh.initialize();
            // JobSchedulingDataProcessor dataProcessor = new
            // JobSchedulingDataProcessor(clh, true, true);
            XMLSchedulingDataProcessor dataProcessor = new XMLSchedulingDataProcessor(clh);
            for (String location : this.jobSchedulingDataLocations) {
                // dataProcessor.processFileAndScheduleJobs(location,
                // getScheduler(), this.overwriteExistingJobs);
                dataProcessor.processFileAndScheduleJobs(location, this.getScheduler());
            }
        }

        // Register JobDetails.
        if (this.jobDetails != null) {
            for (JobDetail jobDetail : this.jobDetails) {
                addJobToScheduler(jobDetail);
            }
        } else {
            // Create empty list for easier checks when registering
            // triggers.
            this.jobDetails = new LinkedList<JobDetail>();
        }

        // Register Calendars.
        if (this.calendars != null) {
            for (String calendarName : this.calendars.keySet()) {
                Calendar calendar = this.calendars.get(calendarName);
                getScheduler().addCalendar(calendarName, calendar, true, true);
            }
        }

        // Register Triggers.
        if (this.triggers != null) {
            for (Trigger trigger : this.triggers) {
                addTriggerToScheduler(trigger);
            }
        }
    }

    catch (Throwable ex) {
        if (transactionStatus != null) {
            try {
                this.transactionManager.rollback(transactionStatus);
            } catch (TransactionException tex) {
                logger.error("Job registration exception overridden by rollback exception", ex);
                throw tex;
            }
        }
        if (ex instanceof SchedulerException) {
            throw (SchedulerException) ex;
        }
        if (ex instanceof Exception) {
            throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage(), ex);
        }
        throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage());
    }

    if (transactionStatus != null) {
        this.transactionManager.commit(transactionStatus);
    }
}

From source file:org.mybatis.spring.MyBatisSpringTest.java

@Test(expected = TransientDataAccessResourceException.class)
public void testChangeExecutorTypeInTx() throws Exception {
    TransactionStatus status = null;/*from w  w  w .  jav  a  2  s  . c om*/

    try {
        status = txManager.getTransaction(new DefaultTransactionDefinition());

        session = SqlSessionUtils.getSqlSession(sqlSessionFactory);

        session = SqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH, exceptionTranslator);

        fail("should not be able to change the Executor type during an existing transaction");
    } finally {
        SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

        // rollback required to close connection
        txManager.rollback(status);
    }
}

From source file:org.businessmanager.dao.GenericDaoImpl.java

@Override
public TransactionStatus getTransaction() {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("CustomTransaction");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    return txManager.getTransaction(def);
}

From source file:com.bleum.canton.jms.dao.impl.JMSTaskDao.java

@Override
public void updateTaskFatal(long taskId, String errorMsg) {
    DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition();
    TransactionStatus tstatus = platformTransactionManager.getTransaction(paramTransactionDefinition);
    try {/*from  w  w w .  j av  a 2  s.co m*/
        this.jdbcTemplate.update(UPDATE_TASK_FATAL, errorMsg, new Date(), taskId);
        platformTransactionManager.commit(tstatus);
    } catch (Exception e) {
        platformTransactionManager.rollback(tstatus);
    }

}

From source file:alfio.manager.AdminReservationManager.java

public Result<Pair<TicketReservation, List<Ticket>>> createReservation(AdminReservationModification input,
        String eventName, String username) {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    TransactionTemplate template = new TransactionTemplate(transactionManager, definition);
    return template.execute(status -> {
        try {//from  w w w .ja v a  2 s.c o  m
            Result<Pair<TicketReservation, List<Ticket>>> result = eventRepository
                    .findOptionalByShortNameForUpdate(eventName).map(e -> validateTickets(input, e))
                    .map(r -> r
                            .flatMap(p -> transactionalCreateReservation(p.getRight(), p.getLeft(), username)))
                    .orElse(Result.error(ErrorCode.EventError.NOT_FOUND));
            if (!result.isSuccess()) {
                log.debug("Error during update of reservation eventName: {}, username: {}, reservation: {}",
                        eventName, username, AdminReservationModification.summary(input));
                status.setRollbackOnly();
            }
            return result;
        } catch (Exception e) {
            log.error("Error during update of reservation eventName: {}, username: {}, reservation: {}",
                    eventName, username, AdminReservationModification.summary(input));
            status.setRollbackOnly();
            return Result.error(singletonList(ErrorCode.custom(
                    e instanceof DuplicateReferenceException ? "duplicate-reference" : "", e.getMessage())));
        }
    });
}

From source file:org.bitsofinfo.util.address.usps.ais.store.jpa.JPAStore.java

private void processNonCopyrightRecords(List<USPSRecord> records, Copyright copyright) throws StoreException {

    DefaultTransactionDefinition td = new DefaultTransactionDefinition();
    td.setName("Process copyright");
    td.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    TransactionStatus txs = this.transactionManager.getTransaction(td);
    try {/*from ww  w . j ava 2 s  . c  om*/

        //copyright = this.entityMgr.merge(copyright);

        for (USPSRecord r : records) {

            // skip copyrights if it is the same one passed in above
            if (r instanceof Copyright) {
                if (r.getIdentifier().equals(copyright.getIdentifier())) {
                    // chuck it as it has already been processed
                    continue;
                }
            }

            // ensure the copyright is linked
            r.setCopyright(copyright);

            // if we use the action code, use that to
            // determine to save or delete.
            if (r.getActionCode() == ActionCode.D) {
                this.deleteRecord(r);
            } else {
                this.saveRecord(r);
            }
        }

        this.transactionManager.commit(txs);

    } catch (Exception e) {
        this.transactionManager.rollback(txs);
    }

}

From source file:org.mybatis.spring.MyBatisSpringTest.java

@Test
public void testChangeExecutorTypeInTxRequiresNew() throws Exception {

    try {//from w  w w . ja va  2s.c om
        txManager.setDataSource(dataSource);
        TransactionStatus status = txManager.getTransaction(new DefaultTransactionDefinition());

        session = SqlSessionUtils.getSqlSession(sqlSessionFactory);

        // start a new tx while the other is in progress
        DefaultTransactionDefinition txRequiresNew = new DefaultTransactionDefinition();
        txRequiresNew.setPropagationBehaviorName("PROPAGATION_REQUIRES_NEW");
        TransactionStatus status2 = txManager.getTransaction(txRequiresNew);

        SqlSession session2 = SqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH,
                exceptionTranslator);

        SqlSessionUtils.closeSqlSession(session2, sqlSessionFactory);
        txManager.rollback(status2);

        SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);
        txManager.rollback(status);

    } finally {
        // reset the txManager; keep other tests from potentially failing
        txManager.setDataSource(dataSource);

        // null the connection since it was not used
        // this avoids failing in validateConnectionClosed()
        connection = null;
    }
}

From source file:com.poscoict.license.service.MorgueService.java

public int replyBoard(HttpSession session, String boardId, String title, String content, String contentNo,
        MultipartFile[] boardAttach) throws UserException {
    logger.info("replyCustomBoard: boardId= " + boardId + " contentNo= " + contentNo);
    TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());

    CustomUserDetails userDetails = (CustomUserDetails) session.getAttribute("userDetails");
    String userNo = userDetails.getUserNo();

    // ? GRP, SEQ 
    HashMap<String, Object> map = (HashMap<String, Object>) morgueDao.replyCheck(boardId,
            Integer.parseInt(contentNo));
    //  //from w  w  w . j  ava 2  s.c  om
    int no = morgueDao.getBoardTotalCount(boardId) + 1;

    ArrayList<Map<String, Object>> attachList = new ArrayList<Map<String, Object>>();
    if (boardAttach.length > 0) {
        for (int i = 0; i < boardAttach.length; i++) {

            Map<String, Object> attach = new HashMap<String, Object>();
            String attachPath = Consts.BOARD_ATTACH_FILE_HOME;
            attachPath += boardId + File.separator + attachDateFormat() + File.separator
                    + attachFileDateFormat();
            attach.put("fileName", boardAttach[i].getOriginalFilename());

            int attachSize = (int) boardAttach[i].getSize();
            if (attachSize == 0)
                continue;

            if (attachSize > 100 * 1024 * 1000)
                throw new UserException("? ? 100MB  .");

            attachPath += "(" + (i + 1) + ")_"
                    + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);

            if (boardAttach[i].getOriginalFilename().lastIndexOf(".") != -1) {
                attachPath += boardAttach[i].getOriginalFilename()
                        .substring(boardAttach[i].getOriginalFilename().lastIndexOf("."));
            }
            String objectId = "at_" + attachFileDateFormat() + i;
            objectId += UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);

            attach.put("filePath", attachPath);
            attach.put("fileSize", attachSize);
            attach.put("objectId", objectId);
            attachList.add(attach);

            System.out.println(
                    "up: fileName: " + boardAttach[i].getOriginalFilename() + " attachPath: " + attachPath);
            try {
                File ufile = new File(attachPath);
                if (!ufile.exists()) {
                    ufile.mkdirs();
                }
                boardAttach[i].transferTo(ufile);
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    throw new IOException("? ? ");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    try {
        if (attachList.size() > 0) {
            for (int i = 0; i < attachList.size(); i++) {
                morgueDao.setAttachFileInfo(no, boardId, attachList.get(i).get("objectId").toString(),
                        attachList.get(i).get("fileName").toString(),
                        attachList.get(i).get("filePath").toString(),
                        Integer.parseInt(attachList.get(i).get("fileSize").toString()), userNo);
            }
        }
        morgueDao.insertBoard(no, boardId, title, content.replaceAll("'", "&apos;"), userNo,
                (Integer) map.get("CONTENT_GRP"), (Integer) map.get("CONTENT_SEQ") + 1);

        this.transactionManager.commit(status);
    } catch (Exception e) {
        this.transactionManager.rollback(status);
        logger.error("userDao.insertBoard: ", e);
        throw new UserException(" ? ");
    }

    logger.info("replyBoard: success ");
    return no;
}

From source file:com.siblinks.ws.service.impl.PostServiceImpl.java

/**
 * {@inheritDoc}/*www . j av a 2s  .  com*/
 */
@Override
@RequestMapping(value = "/createAnswer", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<Response> createAnswer(@RequestParam("pid") final String pid,
        @RequestParam("content") final String content, @RequestParam("studentId") final String studentId,
        @RequestParam("mentorId") final String mentorId, @RequestParam("file") final MultipartFile[] files,
        @RequestParam("subjectId") final String subjectId) {

    SimpleResponse simpleResponse = null;
    TransactionStatus statusBD = null;
    try {
        if (!AuthenticationFilter.isAuthed(context)) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "Authentication required.");
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.FORBIDDEN);
        }

        boolean status = false;
        long id = 0l;
        String error = validateFileImage(files);
        if (StringUtil.isNull(content)) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "post", "createAnswer",
                    "Content is not empty.");
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
        } else if (content.length() > 4000) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "post", "createAnswer",
                    "Content must be less than 4000 characters.");
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
        }
        if (!StringUtil.isNull(error)) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "post", "createAnswer", error);
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
        }
        TransactionDefinition def = new DefaultTransactionDefinition();
        statusBD = transactionManager.getTransaction(def);
        MultipartFile file = null;
        String filePath = "";
        String pathget = environment.getProperty("directoryGetImageAnswer");
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                file = files[i];
                filePath += pathget + uploadFile(file, "directoryImageAnswer") + ".png";
                if (i < files.length - 1) {
                    filePath += ";";
                }
            }
        }
        String strContent = CommonUtil.filterWord(content, cachedDao.getAllWordFilter());

        Object[] queryParamsAnswer = { pid, mentorId, strContent, filePath };
        String strContentNofi = strContent;
        if (!StringUtil.isNull(strContent) && strContent.length() > Parameters.MAX_LENGTH_TO_NOFICATION) {
            strContentNofi = strContent.substring(0, Parameters.MAX_LENGTH_TO_NOFICATION);
        }
        id = dao.insertObject(SibConstants.SqlMapper.SQL_CREATE_ANSWER, queryParamsAnswer);
        Object[] queryParams = { mentorId, studentId, SibConstants.NOTIFICATION_TYPE_ANSWER_QUESTION,
                SibConstants.NOTIFICATION_TITLE_ANSWER_QUESTION, strContentNofi, subjectId, pid };
        dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_NUMREPLIES_QUESTION, new Object[] { pid });

        status = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_CREATE_NOTIFICATION, queryParams);
        // Push message notification
        String toTokenId = userservice.getTokenUser(studentId);
        if (!StringUtil.isNull(toTokenId)) {

            fireBaseNotification.sendMessage(toTokenId, SibConstants.NOTIFICATION_TITLE_ANSWER_QUESTION,
                    SibConstants.TYPE_QUENSION_ANSWER, pid, strContent, SibConstants.NOTIFICATION_ICON,
                    SibConstants.NOTIFICATION_PRIPORITY_HIGH);
        }
        if (id > 0 && status == true) {
            status = true;
        }
        activityLogSerservice.insertActivityLog(new ActivityLogData(SibConstants.TYPE_QUENSION_ANSWER, "C",
                "You answered a question", mentorId, pid));
        transactionManager.commit(statusBD);
        logger.info("Insert Menu success " + new Date());
        simpleResponse = new SimpleResponse("" + status, "POST", "createAnswer", status);
    } catch (Exception e) {
        e.printStackTrace();
        if (statusBD != null) {
            transactionManager.rollback(statusBD);
        }
        logger.info("Create answer Error:" + e.getMessage(), e.getCause());
        simpleResponse = new SimpleResponse(e.getMessage(), "POST", "createAnswer", e.getMessage());
    }

    return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * //from w  ww  .  j a  v a 2  s. c  om
 * Check that not existing control are created.
 */
@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void creationControls() {
    try {
        DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
        // Set user for testing
        tx.setTxEndUserId("userForCreation");
        List<DbeExpendControl> controls = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        Assert.assertTrue(controls.size() == 0);
        // Update limits.
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        limitService.proccesLimit(tx);
        transactionManager.commit(status);
        controls = controlService.getExpendDataForUserAppProvCurrencyObCountry(tx.getTxEndUserId(),
                tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(), tx.getBmObMop().getBmObCountry());
        Assert.assertNotNull(controls);
        Assert.assertTrue(controls.size() == 3);
        // All the new control have to be set to 0
        for (DbeExpendControl control : controls) {
            Assert.assertTrue(control.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0);
        }
        ProcessingLimitServiceTest.logger.debug("Controls:" + controls.size());
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());

    }
}