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.krawler.spring.crm.accountModule.crmAccountController.java

public ModelAndView saveAccounts(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;//from w  w  w  .  j av a2s.c  o  m
    CrmAccount acc = null;
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        boolean ownerChanged = false;
        JSONObject jobj = new JSONObject(request.getParameter("jsondata"));
        String userid = sessionHandlerImpl.getUserid(request);
        String accountIds = jobj.getString("accountid");
        String arrayId[] = accountIds.split(",");
        Integer operationCode = CrmPublisherHandler.ADDRECORDCODE;
        String companyid = sessionHandlerImpl.getCompanyid(request);
        for (int i = 0; i < arrayId.length; i++) {
            String id = arrayId[i];
            jobj.put("userid", userid);
            jobj.put("companyid", companyid);
            jobj.put("updatedon", System.currentTimeMillis());
            jobj.put("accountid", id);
            JSONArray jcustomarray = null;
            if (jobj.has("customfield")) {
                jcustomarray = jobj.getJSONArray("customfield");
            }

            if (id.equals("0")) {
                if (jobj.has("accountownerid") && !jobj.getString("accountownerid").equals(userid)) {
                    ownerChanged = true;
                }

                id = java.util.UUID.randomUUID().toString();
                jobj.put("accountid", id);
                //                   if (jobj.has("customfield")) {
                //                       fieldManager.storeCustomFields(jcustomarray, "account", true, id);
                //                   }
                //                   jobj = StringUtil.setcreatedonDate(jobj, request);
                kmsg = crmAccountDAOObj.addAccounts(jobj);
                HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                customrequestParams.put("customarray", jcustomarray);
                customrequestParams.put("modulename", Constants.Crm_Account_modulename);
                customrequestParams.put("moduleprimarykey", Constants.Crm_Accountid);
                customrequestParams.put("modulerecid", id);
                customrequestParams.put("companyid", companyid);
                customrequestParams.put("customdataclasspath", Constants.Crm_account_custom_data_classpath);
                acc = (CrmAccount) kmsg.getEntityList().get(0);
                if (jobj.has("customfield")) {
                    KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                    if (customDataresult != null && customDataresult.getEntityList().size() > 0) {
                        jobj.put("CrmAccountCustomDataobj", id);
                        kmsg = crmAccountDAOObj.editAccounts(jobj);
                    }

                    //                    fieldManager.storeCustomFields(jcustomarray,"account",true,id);
                }
                // fetch auto-number columns only
                HashMap<String, Object> fieldrequestParams = new HashMap<String, Object>();
                fieldrequestParams.put("isexport", true);
                fieldrequestParams.put("filter_names", Arrays.asList("companyid", "moduleid", "fieldtype"));
                fieldrequestParams.put("filter_values", Arrays.asList(companyid, Constants.Crm_account_moduleid,
                        Constants.CUSTOM_FIELD_AUTONUMBER));
                KwlReturnObject AutoNoFieldMap = fieldManagerDAOobj.getFieldParams(fieldrequestParams);

                // increment auto number if exist
                if (AutoNoFieldMap.getEntityList().size() > 0) {
                    JSONArray autoNoData = fieldDataManagercntrl.setAutoNumberCustomData(customrequestParams,
                            AutoNoFieldMap.getEntityList());
                    jobj.put(Constants.AUTOCUSTOMFIELD, autoNoData);
                } // END logic - auto no
                if (acc.getValidflag() == 1) {
                    auditTrailDAOObj.insertAuditLog(AuditAction.ACCOUNT_CREATE,
                            ((acc.getAccountname() == null) ? "" : acc.getAccountname())
                                    + " - Account created ",
                            request, id);
                }

            } else {
                // check if account owner changed
                String mainownerId = crmAccountHandler.getMainAccOwner(crmAccountDAOObj, id);
                if (!StringUtil.isNullOrEmpty(mainownerId)) {
                    if (!mainownerId.equals(jobj.optString("accountownerid", mainownerId))) {
                        ownerChanged = true;
                    }
                }

                operationCode = CrmPublisherHandler.UPDATERECORDCODE;
                if (jobj.has("customfield")) {
                    HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                    customrequestParams.put("customarray", jcustomarray);
                    customrequestParams.put("modulename", Constants.Crm_Account_modulename);
                    customrequestParams.put("moduleprimarykey", Constants.Crm_Accountid);
                    customrequestParams.put("modulerecid", id);
                    customrequestParams.put("companyid", companyid);
                    customrequestParams.put("customdataclasspath", Constants.Crm_account_custom_data_classpath);
                    KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                    if (customDataresult != null && customDataresult.getEntityList().size() > 0) {
                        jobj.put("CrmAccountCustomDataobj", id);
                    }
                }
                if (jobj.has("createdon")) {
                    jobj.put("createdon", jobj.getLong("createdon"));
                }
                kmsg = crmAccountDAOObj.editAccounts(jobj);
                acc = (CrmAccount) kmsg.getEntityList().get(0);
                if (acc.getValidflag() == 1) {
                    auditTrailDAOObj.insertAuditLog(AuditAction.ACCOUNT_UPDATE,
                            jobj.getString("auditstr") + " Account - "
                                    + ((acc.getAccountname() == null) ? "" : acc.getAccountname()) + " ",
                            request, id);
                }
            }
        }
        txnManager.commit(status);
        JSONObject cometObj = jobj;
        if (request.getParameter("massEdit") != null
                && Boolean.parseBoolean(request.getParameter("massEdit"))) {
            if (arrayId[0].equals("0"))
                crmCommonService.validateMassupdate(new String[] { acc.getAccountid() }, "Account", companyid);
            else
                crmCommonService.validateMassupdate(arrayId, "Account", companyid);
            cometObj.put("accountid", accountIds);
            cometObj.put("ismassedit", true);
        }

        myjobj.put("success", true);
        myjobj.put("ID", acc.getAccountid());
        myjobj.put("createdon", jobj.has("createdon") ? jobj.getLong("createdon") : "");
        cometObj.put("createdon", acc.getCreatedon());
        myjobj.put("updatedon", jobj.has("updatedon") ? jobj.getLong("updatedon") : "");
        myjobj.put(Constants.AUTOCUSTOMFIELD,
                jobj.has(Constants.AUTOCUSTOMFIELD) ? jobj.getJSONArray(Constants.AUTOCUSTOMFIELD) : "");
        cometObj.put("updatedon", acc.getUpdatedon());
        cometObj.put(Constants.AUTOCUSTOMFIELD,
                jobj.has(Constants.AUTOCUSTOMFIELD) ? jobj.getJSONArray(Constants.AUTOCUSTOMFIELD) : "");
        publishAccountModuleInformation(request, cometObj, operationCode, companyid, userid);

        if (sessionHandlerImpl.getCompanyNotifyOnFlag(request)) {// send Notification if set flag at company level
            if (ownerChanged) {// Send Notification if owner changed
                List<String> recepients = new ArrayList();
                recepients.add(jobj.getString("accountownerid"));
                Map refTypeMap = new HashMap();
                Map refIdMap = new HashMap();
                refIdMap.put("refid1", acc.getAccountid());
                refTypeMap.put("reftype1", Constants.Crm_account_classpath);
                refIdMap.put("refid2", userid);
                refTypeMap.put("reftype2", Constants.USERS_CLASSPATH);
                String loginURL = URLUtil.getRequestPageURL(request, Links.loginpageFull);
                HashMap<String, Object> extraParams = new HashMap<String, Object>();
                extraParams.put(NotificationConstants.LOGINURL, loginURL);
                extraParams.put(NotificationConstants.PARTNERNAME, sessionHandlerImpl.getPartnerName(request));
                if (recepients.size() > 0) {
                    NotificationManagementServiceDAO.sendNotificationRequest(CHANNEL.EMAIL, ACCOUNT_ASSIGNED,
                            NOTIFICATIONSTATUS.REQUEST, userid, recepients, refIdMap, refTypeMap, extraParams);
                }
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage());
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:ca.nrc.cadc.uws.server.JobDAO.java

public JobDAO(DataSource dataSource, JobSchema jobSchema, IdentityManager identManager,
        StringIDGenerator idGenerator) {
    this.jobSchema = jobSchema;
    this.identManager = identManager;
    this.idGenerator = idGenerator;

    this.defaultTransactionDef = new DefaultTransactionDefinition();
    defaultTransactionDef.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_REPEATABLE_READ);
    this.transactionManager = new DataSourceTransactionManager(dataSource);

    this.jdbc = new JdbcTemplate(dataSource);
}

From source file:org.ohmage.query.impl.UserClassQueries.java

public void addUserToClassWithRole(final String username, final String classId, final Clazz.Role classRole)
        throws DataAccessException {

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Adding a user to a class.");

    try {//from w  w w  .j  a v  a 2 s. co  m
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Insert the new user.
        try {
            getJdbcTemplate().update(SQL_INSERT_USER_CLASS,
                    new Object[] { username, classId, classRole.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER_CLASS
                    + "' with parameters: " + username + ", " + classId + ", " + classRole.toString(), e);
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }
    } catch (TransactionException e) {
        throw new DataAccessException("Error while attempting to rollback the transaction.", e);
    }
}

From source file:org.ohmage.query.impl.CampaignQueries.java

public void createCampaign(final Campaign campaign, final Collection<String> classIds,
        final String creatorUsername) throws DataAccessException {

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Creating a new campaign.");

    try {//  w ww. j  a va2s  .  c om
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        String iconUrlString = null;
        URL iconUrl = campaign.getIconUrl();
        if (iconUrl != null) {
            iconUrlString = iconUrl.toString();
        }

        String xml;
        try {
            xml = campaign.getXml();
        } catch (DomainException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("The XML could not be saved.");
        }

        // Create the campaign.
        try {
            getJdbcTemplate().update(SQL_INSERT_CAMPAIGN,
                    new Object[] { campaign.getId(), campaign.getName(), xml, campaign.getDescription(),
                            iconUrlString, campaign.getAuthoredBy(), campaign.getRunningState().toString(),
                            campaign.getPrivacyState().toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_CAMPAIGN + "' with parameters: "
                    + campaign.getId() + ", " + campaign.getName() + ", " + xml + ", "
                    + campaign.getDescription() + ", " + iconUrlString + ", " + campaign.getAuthoredBy() + ", "
                    + campaign.getRunningState().toString() + ", " + campaign.getPrivacyState().toString(), e);
        }

        // Create the set of survey and prompt IDs for this campaign.
        final Set<String> surveyIds = new HashSet<String>();
        final Set<String> promptIds = new HashSet<String>();

        // Loop through all of the surveys and add the survey and prompt
        // IDs.
        for (Survey survey : campaign.getSurveys().values()) {
            // Get this survey's ID.
            surveyIds.add(survey.getId());

            Queue<SurveyItem> surveyItems = new LinkedList<SurveyItem>();
            surveyItems.addAll(survey.getSurveyItems().values());
            while (surveyItems.size() > 0) {
                SurveyItem surveyItem = surveyItems.poll();

                if (surveyItem instanceof RepeatableSet) {
                    RepeatableSet repeatableSet = (RepeatableSet) surveyItem;

                    for (SurveyItem rsSurveyItem : repeatableSet.getSurveyItems().values()) {
                        surveyItems.add(rsSurveyItem);
                    }
                } else if (surveyItem instanceof Prompt) {
                    promptIds.add(((Prompt) surveyItem).getId());
                }
            }
        }

        // Get the campaign's ID.
        final String campaignId = campaign.getId();

        // Compile the list of parameters for the survey ID lookup table.
        List<Object[]> surveyParameters = new ArrayList<Object[]>(surveyIds.size());
        for (String surveyId : surveyIds) {
            Object[] params = new Object[2];
            params[0] = surveyId;
            params[1] = campaignId;
            surveyParameters.add(params);
        }

        // The SQL to write the data.
        final String surveyIdLookupBatchSql = "INSERT INTO " + "campaign_survey_lookup(survey_id, campaign_id) "
                + "VALUES (?, (SELECT id FROM campaign WHERE urn = ?))";

        // Add the survey IDs to the lookup table.
        try {
            getJdbcTemplate().batchUpdate(surveyIdLookupBatchSql, surveyParameters);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + surveyIdLookupBatchSql + "'.", e);
        }

        // Compile the list of parameters for the prompt ID lookup table.
        List<Object[]> promptParameters = new ArrayList<Object[]>(surveyIds.size());
        for (String promptId : promptIds) {
            Object[] params = new Object[2];
            params[0] = promptId;
            params[1] = campaignId;
            promptParameters.add(params);
        }

        // The SQL to write the data.
        final String promptIdLookupBatchSql = "INSERT INTO " + "campaign_prompt_lookup(prompt_id, campaign_id) "
                + "VALUES (?, (SELECT id FROM campaign WHERE urn = ?))";

        // Add the prompt IDs to the lookup table.
        try {
            getJdbcTemplate().batchUpdate(promptIdLookupBatchSql, promptParameters);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + promptIdLookupBatchSql + "'.", e);
        }

        // Add each of the classes to the campaign.
        for (String classId : classIds) {
            associateCampaignAndClass(transactionManager, status, campaign.getId(), classId);
        }

        // Add the requesting user as the author. This may have already 
        // happened above.
        try {
            getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, creatorUsername, campaign.getId(),
                    Campaign.Role.AUTHOR.toString());
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            // The user was already an author of this campaign implying 
            // that it's one of the default campaign roles based on a class
            // role that the 'creatorUsername' has.
            e.printStackTrace();
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN
                    + "' with parameters: " + creatorUsername + ", " + campaign.getId() + ", "
                    + Campaign.Role.AUTHOR.toString(), e);
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }
    } catch (TransactionException e) {
        throw new DataAccessException("Error while attempting to rollback the transaction.", e);
    }
}

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

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

    ArrayList<Map<String, Object>> attachList = new ArrayList<Map<String, Object>>();

    try {//from w  w  w  .  j av  a  2 s .  c  o m
        morgueDao.modifyBoard(title, content.replaceAll("'", "&apos;"), dateFormat(),
                (String) session.getAttribute("USER_NO"), boardId, contentNo);

        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 += File.separator + "custom" + File.separator + 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) + ")";
                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);

                try {
                    File ufile = new File(attachPath);
                    if (!ufile.exists()) {
                        ufile.mkdirs();
                    }
                    boardAttach[i].transferTo(ufile);
                    morgueDao.setAttachFileInfo(Integer.parseInt(contentNo), 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()),
                            (String) session.getAttribute("USER_NO"));
                } catch (IOException e) {
                    e.printStackTrace();
                    try {
                        throw new IOException("? ? ");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }

        // ? 
        if (deleteFile != null) {
            for (int i = 0; i < deleteFile.length; i++) {
                String deleteAttachFilePath = morgueDao.getAttachFilePath(deleteFile[i]);
                logger.info("deleteAttachFilePath: " + deleteAttachFilePath);
                File file = new File(deleteAttachFilePath);
                if (file.exists() == true)
                    file.delete();
                morgueDao.deleteAttachFile(deleteFile[i]);
            }
        }

        transactionManager.commit(status);
    } catch (Exception e) {
        logger.error("userDao.modifyBoard: ", e);
        transactionManager.rollback(status);
        throw new UserException("  ");
    }
    logger.info("modifyBoard-success");
}

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

public void insertBoard(String title, String openFlag, String folder, String subCategory, String mainContent,
        String menubar, MultipartFile[] boardAttach, String guestID, String guestPW, HttpSession session)
        throws Exception {
    logger.info("boardList: folder= " + folder);
    TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());

    CustomUserDetails userDetails = (CustomUserDetails) session.getAttribute("userDetails");
    String userNo = userDetails.getUserNo();
    String userName = userDetails.getUsername();
    boolean extraAccount = userDetails.getAuthorities().toString()
            .contains(Consts.rolePrefix + Consts.USERLV_GUEST);

    if (extraAccount) {
        guestID = guestID.trim();/* w  w w  . j a v  a2s  .  co  m*/
        guestPW = guestPW.trim();
        if (guestID.isEmpty() || guestPW.isEmpty())
            throw new UserException("guest  ID ? PW  .");
        if (guestID.length() > 50 || guestPW.length() > 50)
            throw new UserException("ID ? PW  ? 50? .");
    }

    Board board = new Board();

    int no = userDao.getBoardCount(folder) + 1;
    board.setCONTENT_NO(no);
    board.setFOLDER_ID(folder);
    board.setORI_FOLDER_ID(folder);
    board.setSUBCATEGORY(subCategory);
    board.setTITLE(title);
    board.setOPEN_FLAG(openFlag);
    board.setMAIN_CONTENT(mainContent.replaceAll("'", "&apos;"));
    board.setUSER_NO(userNo);
    board.setR_CREATION_USER(userNo);
    board.setR_CREATION_DATE(dateFormat());

    logger.info("@@@@ dateFormat() : " + dateFormat());

    board.setCONTENT_GRP(no);
    board.setCONTENT_SEQ(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 += folder + 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++) {
                userDao.setAttachFileInfo(no, folder, 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);
            }
        }
        userDao.insertBoard(board);

        if (extraAccount)
            userDao.insertExtraAccounts(guestID, guestPW, no, folder);

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

    //      Insert this new board data into push message table 
    //      DATE : 16.11.22
    try {
        int pushObjectId = pushDao.getMessageCount() + 1;
        String postType = new String("board");
        insertPush(pushObjectId, no, false, postType, folder, subCategory, title,
                mainContent.replaceAll("'", "&apos;"), userName, dateFormat());
    } catch (Exception e) {
        // TODO: handle exception
        this.transactionManager.rollback(status);
        logger.error("pushDao.insertPushMessage : ", e);
        throw new UserException("Push  ? ");
    }

    try {
        pushService.sendPushMessage();
    } catch (Exception e) {
        // TODO: handle exception
        logger.error("sendPush error in insertBoard: ", e);
    }

}

From source file:com.ms.commons.test.BaseTestCase.java

@After
@SuppressWarnings("unchecked")
public void after() throws Exception {
    log.debug("=========================> BaseTestCase.after()");
    if (ThreadContextCache.get(BuiltInCacheKey.Finally) != null) {

        for (Runnable runnable : (List<Runnable>) ThreadContextCache.get(List.class, BuiltInCacheKey.Finally)) {
            try {
                runnable.run();/*  www  .j  av a2 s .c o m*/
            } catch (Exception e) {
                log.error("Error occured in clear data.", e);
            }
        }
    }

    final List<Task> taskList = (List<Task>) TestCaseRuntimeInfo.current().getContext()
            .get(ClearSpecialDataPrepareEvent.__finish__task__list__);
    if (taskList != null) {
        if (TestCaseRuntimeInfo.current().getPrepare().newThreadTransactionImport()) {
            runInBlockedThread(new Runnable() {

                public void run() {
                    log.warn("Clear data in new thread (transaction).");
                    TransactionStatus localTransactionStatus = transactionManager
                            .getTransaction(new DefaultTransactionDefinition());
                    try {
                        TaskUtil.runTasks(taskList);
                        transactionManager.commit(localTransactionStatus);
                    } catch (Throwable t) {
                        log.error("Clear data transaction has be rolled back.", t);
                        transactionManager.rollback(localTransactionStatus);
                        throw new RuntimeException(t);
                    }
                }
            });
        } else {
            TaskUtil.runTasks(taskList);
        }
    }

    super.tearDown();

    if (isMockOn()) {
        AliMock.clearMock();
    }
    objectMethodMap.clear();
    ThreadContextCache.clear();
}

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

@Test
public void testWithTxRequired() {
    DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
    txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED");

    TransactionStatus status = txManager.getTransaction(txDef);

    session = SqlSessionUtils.getSqlSession(sqlSessionFactory);
    session.getMapper(TestMapper.class).findTest();
    SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

    txManager.commit(status);/* w w  w. j  a v a  2s  .  co m*/

    assertCommit();
    assertCommitSession();
    assertSingleConnection();
}

From source file:com.krawler.spring.crm.emailMarketing.crmEmailMarketingController.java

public ModelAndView saveEmailTemplate(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;/*from ww  w. j  a  va2  s. com*/
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        myjobj.put("success", false);
        int mode = Integer.parseInt(request.getParameter("mode"));
        String templateClass = request.getParameter("templateclass");
        JSONObject jobj = new JSONObject();
        String companyid = sessionHandlerImpl.getCompanyid(request);
        String templatename = request.getParameter("tname");
        templatename = templatename.replaceAll("\\s+", " ").trim();
        jobj.put("userid", sessionHandlerImpl.getUserid(request));
        jobj.put("tbody", request.getParameter("tbody"));
        jobj.put("description", request.getParameter("tdesc"));
        jobj.put("subject", request.getParameter("tsub"));
        jobj.put("name", templatename);

        ArrayList filter_names = new ArrayList();
        ArrayList filter_params = new ArrayList();
        filter_names.add("c.name");
        filter_params.add(templatename);
        filter_names.add("c.creator.company.companyID");
        filter_params.add(companyid);
        filter_names.add("c.deleted");
        filter_params.add(0);

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_params", filter_params);

        KwlReturnObject kmsg1 = crmEmailMarketingDAOObj.getTemplateContent(requestParams);
        if (kmsg1.getRecordTotalCount() > 0 && (mode == 0 || templateClass.equals("DefaultTemplates"))) {
            myjobj.put("msg", "Email template with ' " + templatename
                    + " ' name already exists. Please change the name and save it again.");
        } else {
            if (mode == 0) {
                jobj.put("modifiedon", new Date().getTime());
                jobj.put("createdon", new Date().getTime());
                kmsg = crmEmailMarketingDAOObj.addEmailTemplate(jobj);
            } else {
                jobj.put("modifiedon", new Date().getTime());
                jobj.put("deleted", "0");
                if (templateClass.equals("DefaultTemplates")) {
                    HashMap<String, Object> params = new HashMap<String, Object>();
                    params.put("userid", sessionHandlerImpl.getUserid(request));
                    params.put("templateid", request.getParameter("tid"));
                    KwlReturnObject copyMsg = crmEmailMarketingDAOObj.copyDefaultTemplates(params);
                    List templateid = copyMsg.getEntityList();
                    jobj.put("tid", templateid.get(0));
                } else {
                    jobj.put("tid", request.getParameter("tid"));
                }
                kmsg = crmEmailMarketingDAOObj.editEmailTemplate(jobj);
            }
        }
        myjobj.put("success", true);
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

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

/**
 * Update periods and check amounts./*w w w.  j a  v a2s  . c  om*/
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);

        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }

        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }

    // check that
    try {
        tx.setFtChargedAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();

        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);

        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        boolean found = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                found = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(found);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}