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.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * {@inheritDoc}/* ww w .j  a va 2  s. com*/
 */
@Override
@RequestMapping(value = "/insertUpdateCommentEssay", method = RequestMethod.POST)
public ResponseEntity<Response> insertUpdateCommentEssay(
        @RequestParam(required = false) final MultipartFile file, @RequestParam final long essayId,
        @RequestParam final long mentorId, @RequestParam(required = false) final Long studentId,
        @RequestParam final String comment, @RequestParam(required = false) final Long commentId,
        @RequestParam(required = false) final String fileOld, @RequestParam final boolean isUpdate) {
    SimpleResponse reponse = null;
    TransactionStatus status = null;
    try {
        if (comment != null && comment.length() > 1000) {
            reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                    "Content can not longer than 1000 characters");
        } else {
            boolean flag = false;
            Object[] params = null;
            TransactionDefinition def = new DefaultTransactionDefinition();
            status = transactionManager.getTransaction(def);
            String statusMsg = validateEssay(file);
            if (statusMsg.equals("Error Format")) {
                reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                        "Your file is not valid.");
            } else if (statusMsg.equals("File over 10M")) {
                reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                        "Your file is lager than 10MB.");
            } else if (statusMsg.equals("File name is not valid")) {
                reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                        "File name is not valid.");
            } else {
                // Word filter content
                List<Map<String, String>> allWordFilter = cachedDao.getAllWordFilter();
                String strContent = CommonUtil.filterWord(comment, allWordFilter);
                String strFileName = CommonUtil.filterWord((file != null) ? file.getOriginalFilename() : null,
                        allWordFilter);

                if (!isUpdate) {
                    params = new Object[] { "", mentorId, strContent };
                    long cid = dao.insertObject(SibConstants.SqlMapper.SQL_SIB_ADD_COMMENT, params);
                    params = new Object[] { essayId, cid };
                    flag = dao.insertUpdateObject(SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_FK,
                            params);
                    if (StringUtil.isNull(statusMsg)) {
                        params = new Object[] { mentorId, file.getInputStream(), file.getSize(), strFileName,
                                essayId };
                        flag = dao.insertUpdateObject(
                                SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITH_FILE, params);
                    } else {
                        params = new Object[] { mentorId, essayId };
                        flag = dao.insertUpdateObject(
                                SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITHOUT_FILE, params);
                    }
                    if (flag) {
                        String contentNofi = strContent;
                        if (!StringUtil.isNull(strContent)
                                && strContent.length() > Parameters.MAX_LENGTH_TO_NOFICATION) {
                            contentNofi = strContent.substring(0, Parameters.MAX_LENGTH_TO_NOFICATION);
                        }
                        Object[] queryParamsIns3 = { mentorId, studentId,
                                SibConstants.NOTIFICATION_TYPE_REPLY_ESSAY,
                                SibConstants.NOTIFICATION_TITLE_REPLY_ESSAY, contentNofi, null, essayId };
                        dao.insertUpdateObject(SibConstants.SqlMapper.SQL_CREATE_NOTIFICATION, queryParamsIns3);

                        // send message fire base
                        String toTokenId = userservice.getTokenUser(String.valueOf(studentId));
                        if (!StringUtil.isNull(toTokenId)) {

                            fireBaseNotification.sendMessage(toTokenId,
                                    SibConstants.NOTIFICATION_TITLE_REPLY_ESSAY, SibConstants.TYPE_VIDEO,
                                    String.valueOf(essayId), contentNofi, SibConstants.NOTIFICATION_ICON,
                                    SibConstants.NOTIFICATION_PRIPORITY_HIGH);
                        }
                        activiLogService.insertActivityLog(new ActivityLogData(SibConstants.TYPE_ESSAY, "C",
                                "You replied an essay", String.valueOf(mentorId), String.valueOf(essayId)));
                    } else {
                        transactionManager.rollback(status);
                        reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertComstrContentay",
                                "Failed");
                    }
                } else {
                    params = new Object[] { strContent, commentId };
                    dao.insertUpdateObject(SibConstants.SqlMapper.SQL_SIB_EDIT_COMMENT, params);

                    if (StringUtil.isNull(statusMsg)) {
                        params = new Object[] { mentorId, file.getInputStream(), file.getSize(), strFileName,
                                essayId };
                        dao.insertUpdateObject(SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITH_FILE,
                                params);
                    } else {
                        if (fileOld == null || fileOld.equals("null")) {
                            params = new Object[] { mentorId, essayId };
                            flag = dao.insertUpdateObject(
                                    SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITHOUT_FILE,
                                    params);
                        }
                    }
                }
                transactionManager.commit(status);
                reponse = new SimpleResponse(SibConstants.SUCCESS, "essay", "insertCommentEssay", "Success");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (status != null) {
            transactionManager.rollback(status);
        }
        reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay", e.getMessage());
    }
    return new ResponseEntity<Response>(reponse, HttpStatus.OK);
}

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

public String modifyCustomUser(String adminUser, String customUserNo, String mode, UserInfo userInfo,
        UserPermission userPermission) throws UserException {
    String userNo = "";
    if (mode.equals("info")) {
        userNo = userInfo.getUSER_NO().trim();

        // 16.11.08 17:37 
        logger.info("@@ userInfo : " + userInfo);
        logger.info("@@ adminUser : " + adminUser);
        logger.info("@@ customUserNo : " + customUserNo);

        managementDao.updateCustomUserInfo(userInfo, adminUser, customUserNo);
        logger.info("@@ passed");

    } else if (mode.equals("permission")) {
        userNo = customUserNo;//from   w  w  w. j a v  a2 s.c o  m
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            managementDao.deleteCustomUserPermission(customUserNo);

            Map<String, Object> map = setPermissionCode(userPermission);
            String codes = (String) map.get("codes");
            String codeTypes = (String) map.get("codeTypes");
            int size = (Integer) map.get("size");
            managementDao.insert_user_permission(codes, codeTypes, customUserNo, size);

            this.transactionManager.commit(status);
        } catch (Exception e) {
            this.transactionManager.rollback(status);
            logger.error("CustomUser Modify Permission FAIL: " + customUserNo, e);
            throw new UserException("   ");
        }
    }

    return userNo;
}

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

protected void initMemoryDatabaseOnBeforeEveryTestCase() {
    Method method = ThreadContextCache.get(Method.class, BuiltInCacheKey.Method);
    if (!isNeedPrepare(method)) {
        return;//from   w w w.  jav a 2  s. c  om
    }
    // ?handle
    DbEncodingUtil.clearInfo();

    final PrepareAnnotationTool prepareAnnotation = new PrepareAnnotationTool(method);
    // xml_tree???MemoryDatabase
    if (DataReaderType.TreeXml == prepareAnnotation.type()) {
        return;
    }

    // ?
    DbEncodingUtil.applyInfo(new CnStringDbEncodingInfo(prepareAnnotation.cnStringEncoding()));
    DbEncodingUtil.applyInfo(new UTF8StringDbEncodingInfo(prepareAnnotation.utf8StringEncoding()));

    // ?Sheet
    final String[] importTables = StringUtil.splitAndTrimByComma(prepareAnnotation.importTables());

    PrepareEventUtil.clearRegister();
    if (prepareAnnotation.autoClearExistsData() || prepareAnnotation.autoClearImportDataOnFinish()) {
        log.info("Import data clear exists ones on.");
        PrepareEventUtil.register(new ClearSpecialDataPrepareEvent(prepareAnnotation.primaryKey()));
    }

    final MemoryDatabase prepare = getMemoryDB(prepareAnnotation.type(), BuiltInCacheKey.Prepare.getValue(),
            true);
    getMemoryDB(prepareAnnotation.type(), BuiltInCacheKey.Result.getValue(), false);

    // common prepare (for test case class)
    MemoryDatabase commonPrepare = null;
    if (prepareAnnotation.autoImportCommonData()) {
        commonPrepare = getMemoryDB(prepareAnnotation.type(), ":prepare", false);
    }
    final MemoryDatabase finalCommonPrepare = commonPrepare;

    if (prepareAnnotation.autoImport()) {

        boolean isDefaultRollback = isDefaultRollback();
        if (prepareAnnotation.autoClear()) {
            if ((!isDefaultRollback) || (prepareAnnotation.newThreadTransactionImport())) {
                if (!prepareAnnotation.forceClear()) {
                    throw new RuntimeException("Cannot import data when default rollback was"
                            + " turned off and no force clear flag.");
                }
            }
        }
        log.info("Auto import data on flag autoImport:" + prepareAnnotation.autoImport() + ", autoClear:"
                + prepareAnnotation.autoClear() + ", defaultRollback:" + isDefaultRollback + ", forceClear:"
                + prepareAnnotation.forceClear() + ", newThreadTransactionImport:"
                + prepareAnnotation.newThreadTransactionImport());
        if (prepareAnnotation.newThreadTransactionImport()) {
            runInBlockedThread(new Runnable() {

                public void run() {
                    log.warn("Import data in new thread (transaction).");
                    TransactionStatus localTransactionStatus = transactionManager
                            .getTransaction(new DefaultTransactionDefinition());
                    try {
                        if (prepareAnnotation.autoImportCommonData() && (finalCommonPrepare != null)) {
                            PrepareUtil.prepareDataBase(jdbcTemplate, finalCommonPrepare,
                                    prepareAnnotation.autoClear());
                        }

                        if (importTables != null) {
                            PrepareUtil.prepareDataBase(jdbcTemplate, prepare, prepareAnnotation.autoClear(),
                                    importTables);
                        } else {
                            PrepareUtil.prepareDataBase(jdbcTemplate, prepare, prepareAnnotation.autoClear());
                        }

                        log.info("Import data transaction has be commited.");
                        transactionManager.commit(localTransactionStatus);
                    } catch (Throwable t) {
                        log.error("Import data transaction has be rolled back.", t);
                        transactionManager.rollback(localTransactionStatus);
                        throw new RuntimeException(t);
                    }
                }
            });
        } else {
            if (prepareAnnotation.autoImportCommonData() && (finalCommonPrepare != null)) {
                PrepareUtil.prepareDataBase(jdbcTemplate, finalCommonPrepare, prepareAnnotation.autoClear());
            }
            if (importTables != null) {
                PrepareUtil.prepareDataBase(jdbcTemplate, prepare, prepareAnnotation.autoClear(), importTables);
            } else {
                PrepareUtil.prepareDataBase(jdbcTemplate, prepare, prepareAnnotation.autoClear());
            }
        }
    }
}

From source file:com.krawler.spring.crm.common.documentController.java

public ModelAndView saveDocOwners(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;//from  w w  w.  jav  a  2 s .co m
    //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 {
        String docid = request.getParameter("leadid");
        String owners = request.getParameter("owners");
        String mainowner = request.getParameter("mainOwner");
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("docid", docid);
        requestParams.put("owners", owners);
        requestParams.put("mainOwner", mainowner);
        kmsg = crmDocumentDAOObj.saveDocOwners(requestParams);

        myjobj.put("success", kmsg.isSuccessFlag());
        txnManager.commit(status);
    } catch (SessionExpiredException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (JSONException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (ServiceException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

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

public ModelAndView sendEmailMarketMail(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    //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);
    String msg = "";
    try {/*from w ww .ja v a2s.  c o m*/
        jobj.put("success", false);
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("userid", sessionHandlerImpl.getUserid(request));
        requestParams.put("companyid", sessionHandlerImpl.getCompanyid(request));
        requestParams.put("campaignid", request.getParameter("campid"));
        requestParams.put("emailmarkid", request.getParameter("emailmarkid"));
        requestParams.put("resume", Boolean.parseBoolean(request.getParameter("resume")));
        requestParams.put("baseurl", URLUtil.getRequestPageURL(request, Links.UnprotectedLoginPageFull));
        KwlReturnObject kmsg = crmEmailMarketingDAOObj.sendEmailMarketMail(requestParams);
        jobj.put("success", kmsg.isSuccessFlag());
        msg = kmsg.getEntityList().get(0).toString();
        jobj.put("msgs", msg);
        txnManager.commit(status);
    } catch (SessionExpiredException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (ServiceException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (JSONException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

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

public void updateCampaign(String campaignId, String xml, String description,
        Campaign.RunningState runningState, Campaign.PrivacyState privacyState, Collection<String> classesToAdd,
        Collection<String> classesToRemove, Map<String, Set<Campaign.Role>> usersAndRolesToAdd,
        Map<String, Set<Campaign.Role>> usersAndRolesToRemove) throws DataAccessException {

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

    try {/*  w  w w . j  a va2  s  .  c  o m*/
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Update the XML if it is present.
        if (xml != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_XML, new Object[] { xml, campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_XML + "' with parameters: "
                        + xml + ", " + campaignId, e);
            }
        }

        // Update the description if it is present.
        if (description != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_DESCRIPTION, new Object[] { description, campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_DESCRIPTION
                        + "' with parameters: " + description + ", " + campaignId, e);
            }
        }

        // Update the running state if it is present.
        if (runningState != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_RUNNING_STATE,
                        new Object[] { runningState.toString(), campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_RUNNING_STATE
                        + "' with parameters: " + runningState + ", " + campaignId, e);
            }
        }

        // Update the privacy state if it is present.
        if (privacyState != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_PRIVACY_STATE,
                        new Object[] { privacyState.toString(), campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_PRIVACY_STATE
                        + "' with parameters: " + privacyState + ", " + campaignId, e);
            }
        }

        // Add the specific users with specific roles.
        if (usersAndRolesToAdd != null) {
            for (String username : usersAndRolesToAdd.keySet()) {
                for (Campaign.Role role : usersAndRolesToAdd.get(username)) {
                    try {
                        getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN,
                                new Object[] { username, campaignId, role.toString() });
                    } catch (org.springframework.dao.DuplicateKeyException e) {
                        // This means that the user already had the role in
                        // the campaign. We can ignore this.
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN
                                + "' with parameters: " + username + ", " + campaignId + ", " + role, e);
                    }
                }
            }
        }

        // Remove the specific users and their roles.
        if (usersAndRolesToRemove != null) {
            for (String username : usersAndRolesToRemove.keySet()) {
                for (Campaign.Role role : usersAndRolesToRemove.get(username)) {
                    try {
                        getJdbcTemplate().update(SQL_DELETE_USER_ROLE_CAMPAIGN,
                                new Object[] { username, campaignId, role.toString() });
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_DELETE_USER_ROLE_CAMPAIGN
                                + "' with parameters: " + username + ", " + campaignId + ", " + role, e);
                    }
                }
            }
        }

        if (classesToRemove != null) {
            // For all of the classes that are associated with the campaign
            // but are not in the classIds list,
            for (String classId : classesToRemove) {
                // For each of the users in the class, if they are only 
                // associated with the campaign through this class then 
                // remove them.
                List<String> usernames;
                try {
                    usernames = userClassQueries.getUsersInClass(classId);
                } catch (DataAccessException e) {
                    transactionManager.rollback(status);
                    throw e;
                }

                for (String username : usernames) {
                    // If the user is not associated with the campaign 
                    // through any other class, they are removed from the
                    // campaign.
                    int numClasses;
                    try {
                        numClasses = userCampaignClassQueries
                                .getNumberOfClassesThroughWhichUserIsAssociatedWithCampaign(username,
                                        campaignId);
                    } catch (DataAccessException e) {
                        transactionManager.rollback(status);
                        throw e;
                    }
                    if (numClasses == 1) {
                        // Retrieve the default roles that the user was 
                        // given when they joined the class.
                        List<Campaign.Role> roles;
                        try {
                            roles = getJdbcTemplate().query(SQL_GET_USER_DEFAULT_ROLES,
                                    new Object[] { username, campaignId, classId },
                                    new RowMapper<Campaign.Role>() {
                                        @Override
                                        public Campaign.Role mapRow(ResultSet rs, int rowNum)
                                                throws SQLException {
                                            return Campaign.Role.getValue(rs.getString("role"));
                                        }
                                    });
                        } catch (org.springframework.dao.DataAccessException e) {
                            transactionManager.rollback(status);
                            throw new DataAccessException("Error executing SQL '" + SQL_GET_USER_DEFAULT_ROLES
                                    + "' with parameters: " + username + ", " + campaignId + ", " + classId, e);
                        }

                        for (Campaign.Role role : roles) {
                            try {
                                getJdbcTemplate().update(SQL_DELETE_USER_ROLE_CAMPAIGN,
                                        new Object[] { username, campaignId, role.toString() });
                            } catch (org.springframework.dao.DataAccessException e) {
                                transactionManager.rollback(status);
                                throw new DataAccessException("Error executing SQL '"
                                        + SQL_DELETE_USER_ROLE_CAMPAIGN + "' with parameters: " + username
                                        + ", " + campaignId + ", " + role, e);
                            }
                        }
                    }
                }

                // Remove the campaign, class association.
                try {
                    getJdbcTemplate().update(SQL_DELETE_CAMPAIGN_CLASS, new Object[] { campaignId, classId });
                } catch (org.springframework.dao.DataAccessException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_DELETE_CAMPAIGN_CLASS
                            + "' with parameters: " + campaignId + ", " + classId, e);
                }
            }
        }

        if (classesToAdd != null) {
            // For all of the classes that are in the classIds list but not
            // associated with the campaign,
            for (String classId : classesToAdd) {
                associateCampaignAndClass(transactionManager, status, campaignId, classId);
            }
        }

        // 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.krawler.spring.crm.common.documentController.java

public ModelAndView deleteDocumentFromModule(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    KwlReturnObject kmsg = null;//  w w  w.jav  a2 s . c  o m
    //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);
    String docid = "";
    String details = "";
    String auditAction = "";
    if (request.getParameter("docid") != null)
        docid = request.getParameter("docid");
    String map = request.getParameter("mapid");
    String refId = request.getParameter("recid");
    String docName = request.getParameter("docName");
    try {
        crmDocumentDAOObj.deleteDocumentFromModule(docid);
        if (map.equals("0")) {
            CrmCampaign c = (CrmCampaign) hibernateTemplate.get(CrmCampaign.class, refId);
            details = " Campaign - ";
            details += StringUtil.isNullOrEmpty(c.getCampaignname()) ? "" : c.getCampaignname();
            auditAction = AuditAction.CAMPAIGN_DOC_DELETED;
        } else if (map.equals("1")) {
            CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, refId);
            details = " Lead - ";
            details += StringUtil.isNullOrEmpty(l.getFirstname()) ? "" : l.getFirstname() + " ";
            details += StringUtil.isNullOrEmpty(l.getLastname()) ? "" : l.getLastname();
            auditAction = AuditAction.LEAD_DOC_DELETED;
        } else if (map.equals("2")) {
            CrmContact c = (CrmContact) hibernateTemplate.get(CrmContact.class, refId);
            details = " Contact - ";
            details += StringUtil.isNullOrEmpty(c.getFirstname()) ? "" : c.getFirstname() + " ";
            details += StringUtil.isNullOrEmpty(c.getLastname()) ? "" : c.getLastname();
            auditAction = AuditAction.CONTACT_DOC_DELETED;
        } else if (map.equals("3")) {
            CrmProduct p = (CrmProduct) hibernateTemplate.get(CrmProduct.class, refId);
            details = " Product - ";
            details += StringUtil.isNullOrEmpty(p.getProductname()) ? "" : p.getProductname();
            auditAction = AuditAction.PRODUCT_DOC_DELETED;
        } else if (map.equals("4")) {
            CrmAccount a = (CrmAccount) hibernateTemplate.get(CrmAccount.class, refId);
            details = " Account - ";
            details += StringUtil.isNullOrEmpty(a.getAccountname()) ? "" : a.getAccountname();
            auditAction = AuditAction.ACCOUNT_DOC_DELETED;
        } else if (map.equals("5")) {
            CrmOpportunity o = (CrmOpportunity) hibernateTemplate.get(CrmOpportunity.class, refId);
            details = " Opportunity - ";
            details += StringUtil.isNullOrEmpty(o.getOppname()) ? "" : o.getOppname();
            auditAction = AuditAction.OPPORTUNITY_DOC_DELETED;
        } else if (map.equals("6")) {
            CrmCase c = (CrmCase) hibernateTemplate.get(CrmCase.class, refId);
            details = " Case - ";
            details += StringUtil.isNullOrEmpty(c.getSubject()) ? "" : c.getSubject();
            auditAction = AuditAction.CASE_DOC_DELETED;
        } else if (map.equals("7")) {
            CrmActivityMaster am = (CrmActivityMaster) hibernateTemplate.get(CrmActivityMaster.class, refId);
            details = " Activity - ";
            details += StringUtil.isNullOrEmpty(am.getFlag()) ? "" : am.getFlag() + " ";
            details += StringUtil.isNullOrEmpty(am.getCrmCombodataByStatusid().getValue()) ? ""
                    : am.getCrmCombodataByStatusid().getValue();
            auditAction = AuditAction.ACTIVITY_DOC_DELETED;
        } else if (map.equals("-1")) {
            details = " My - Document ";
            auditAction = AuditAction.MY_DOC_DELETED;
        }
        auditTrailDAOObj.insertAuditLog(auditAction, " Docment: '" + docName + "' , deleted for " + details,
                request, refId, docid);

        //    auditTrailDAOObj.insertAuditLog(AuditAction.DOC_TAG_ADDED,
        //            " Document - '" + newTag + "' tag added for "+d.getDocname(),
        //            request, d.getDocid());
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

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

public ModelAndView sendTestEmailMarketMail(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    //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 {/*  w w w  . ja v  a  2  s. c  o  m*/
        jobj.put("success", false);
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("userid", sessionHandlerImpl.getUserid(request));
        requestParams.put("companyid", sessionHandlerImpl.getCompanyid(request));
        requestParams.put("emailmarkid", request.getParameter("emailmarkid"));
        requestParams.put("reciepientMailId", request.getParameter("reciepientMailId"));
        requestParams.put("baseurl", URLUtil.getRequestPageURL(request, Links.UnprotectedLoginPageFull));
        KwlReturnObject kmsg = crmEmailMarketingDAOObj.sendTestEmailMarketMail(requestParams);
        jobj.put("success", kmsg.isSuccessFlag());
        txnManager.commit(status);
    } catch (SessionExpiredException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (ServiceException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } catch (JSONException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

From source file:com.krawler.spring.hrms.common.hrmsCommonController.java

public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response) {
    JSONObject jobj = new JSONObject();
    Integer codeid2 = null;// ww  w.  ja v  a  2  s  . c  om
    KwlReturnObject result = null;
    String msg = "";
    int roleflag = 0;
    String employeeIdFormat = "";
    boolean isStadardEmpFormatWithIdAvilable = false;

    //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 {

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        ArrayList filter_names = new ArrayList(), filter_values = new ArrayList();

        HashMap newhm = new FileUploadHandler().getItems(request);
        HashMap<String, String> hm = new HashMap<String, String>();
        for (Object key : newhm.keySet()) {
            hm.put(key.toString(),
                    new String(newhm.get(key.toString()).toString().getBytes("iso-8859-1"), "UTF-8"));
        }
        String id = (String) hm.get("userid");
        //String lastname = (String) hm.get("lastname");
        //lastname = new String (lastname.getBytes ("iso-8859-1"), "UTF-8");

        if (!StringUtil.isNullOrEmpty((String) hm.get("employeeid"))) {
            String[] codeid = ((String) hm.get("employeeid")).split("-");

            for (int x = 0; x < codeid.length; x++) {
                if (codeid[x].matches("[0-9]*") == true) {
                    codeid2 = Integer.parseInt(codeid[x]);
                } else {
                    employeeIdFormat += (codeid[x] + "-");
                }
            }
            if (employeeIdFormat.length() > 0) {
                employeeIdFormat = employeeIdFormat.substring(0, employeeIdFormat.length() - 1);
            }
        }
        if (StringUtil.isNullOrEmpty(employeeIdFormat))
            employeeIdFormat = null;
        String companyid = sessionHandlerImplObj.getCompanyid(request);
        String pwd = null;

        if (!StringUtil.isNullOrEmpty(id)) {
            requestParams.clear();

            //                filter_names.add("employeeid");
            //                filter_values.add(codeid2);
            //
            //                filter_names.add("userID");
            //                filter_values.add(id);
            //
            //                filter_names.add("company.companyID");
            //                filter_values.add(companyid);
            //
            //                requestParams.put("filter_names", filter_names);
            //                requestParams.put("filter_values", filter_values);
            //
            //                result = hrmsCommonDAOObj.getUsers(requestParams);
            //                if (result.getEntityList().isEmpty()) {
            requestParams.put("employeeIdFormat", employeeIdFormat);
            requestParams.put("userID", id);
            requestParams.put("employeeid", codeid2);
            requestParams.put("request", request);
            isStadardEmpFormatWithIdAvilable = isStadardEmpFormatWithIdAvilable(requestParams);
            String standardEmpId = getStadardEmpFormat(requestParams);
            if (standardEmpId != null && employeeIdFormat != null && standardEmpId.equals(employeeIdFormat)) {
                employeeIdFormat = null;
            }
            requestParams.clear();
            filter_names.clear();
            filter_values.clear();

            filter_names.add("employeeid");
            filter_values.add(codeid2);

            if (employeeIdFormat == null) {
                filter_names.add("IS employeeIdFormat");
            } else {
                filter_names.add("employeeIdFormat");
                filter_values.add(employeeIdFormat);
            }
            filter_names.add("!userID");
            filter_values.add(id);

            filter_names.add("user.company.companyID");
            filter_values.add(companyid);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getUseraccount(requestParams);

            if (!result.getEntityList().isEmpty() || isStadardEmpFormatWithIdAvilable) {
                throw new Exception("Employee ID already present.");
            }
            //                }
            requestParams.clear();
            requestParams.put("id", id);
            if (((String) hm.get("formname")).equals("user")) {
                if (!StringUtil.isNullOrEmpty((String) hm.get("templateid"))) {
                    requestParams.put("templateid", (String) hm.get("templateid"));
                } else {
                    requestParams.put("templateid", " ");
                }
            }
        } else {
            requestParams.clear();
            filter_names.clear();
            filter_values.clear();

            filter_names.add("userLogin.userName");
            filter_values.add(hm.get("username"));

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getUsers(requestParams);
            if (!result.getEntityList().isEmpty()) {
                throw new Exception("User name not available.");
            }
            requestParams.clear();
            filter_names.clear();
            filter_values.clear();

            filter_names.add("employeeid");
            filter_values.add(codeid2);

            filter_names.add("company.companyID");
            filter_values.add(companyid);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getUsers(requestParams);

            if (!result.getEntityList().isEmpty()) {
                throw new Exception("Employee ID already present.");
            }

            requestParams.clear();
            requestParams.put("username", hm.get("username"));
            pwd = AuthHandler.generateNewPassword();
            requestParams.put("pwd", AuthHandler.getSHA1(pwd));
            requestParams.put("companyid", companyid);
        }

        requestParams.put("fname", hm.get("firstname"));
        requestParams.put("lname", hm.get("lastname"));
        requestParams.put("emailid", hm.get("emailid"));
        requestParams.put("address", hm.get("address"));
        requestParams.put("contactno", hm.get("contactnumber"));
        requestParams.put("empid", codeid2);
        requestParams.put("employeeIdFormat", employeeIdFormat);
        requestParams.put("companyid", companyid);

        int histsave = 0;
        String histdept = "";
        String histdesig = "";
        String histsal = "";
        Date saveDate = new Date();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");
        saveDate = new Date(fmt.format(saveDate));
        String updatedby = sessionHandlerImplObj.getUserid(request);
        Useraccount ua = (Useraccount) kwlCommonTablesDAOObj.getObject("com.krawler.common.admin.Useraccount",
                id);

        if (!StringUtil.isNullOrEmpty((String) hm.get("roleid"))
                && !hm.get("roleid").equals(ua.getRole().getID())) {
            if (ua.getRole().getID().equals("1") && hrmsCommonDAOObj.isCompanySuperAdmin(id, companyid)) {//Can't Edit role for super admin
                roleflag = 1;
            } else {

                String newRoleId = hm.get("roleid").toString();
                if (StringUtil.equal(newRoleId, Role.COMPANY_USER)) { // Check whether new Role is Company User/ Company Employee

                    List<Empprofile> childList = organizationChartDAOObj.getChildNode(id); // Check for child list before changing its role to Employee.

                    if (childList.size() > 0) {
                        roleflag = 2;
                    } else {
                        requestParams.put("roleid", newRoleId);
                    }
                } else {

                    requestParams.put("roleid", newRoleId);
                }

            }
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("designationid"))) {
            if ((MasterData) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.master.MasterData",
                    (String) hm.get("designationid")) != ua.getDesignationid()) {
                histdesig = (ua.getDesignationid() == null) ? "" : ua.getDesignationid().getId();
                histsave = 1;
            }
            requestParams.put("designationid", hm.get("designationid"));
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("department"))) {
            if ((MasterData) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.master.MasterData",
                    (String) hm.get("department")) != ua.getDepartment()) {
                histdept = (ua.getDepartment() == null) ? "" : ua.getDepartment().getId();
                if (histsave == 0) {
                    histdesig = (ua.getDesignationid() == null) ? "" : ua.getDesignationid().getId();
                }
                histsave = 2;
            }
            requestParams.put("department", hm.get("department"));
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("salary"))) {
            String tempsal = "0";
            if (((String) hm.get("salary")).length() > 0) {
                tempsal = hm.get("salary").toString();
            }
            if (!tempsal.equals(ua.getSalary())) {
                if (ua.getSalary() != null) {
                    histsal = ua.getSalary();
                }
            }
            requestParams.put("salary", tempsal);
        }

        if (!StringUtil.isNullOrEmpty((String) hm.get("accno"))) {
            if (((String) hm.get("accno")).length() > 0) {
                requestParams.put("accno", hm.get("accno"));
            } else {
                requestParams.put("accno", "0");
            }
        }

        if (!StringUtil.isNullOrEmpty((String) hm.get("formatid"))) {
            requestParams.put("formatid", hm.get("formatid"));
        }
        String diff = null;
        if (!StringUtil.isNullOrEmpty((String) hm.get("tzid"))) {
            KWLTimeZone timeZone = (KWLTimeZone) kwlCommonTablesDAOObj
                    .getObject("com.krawler.common.admin.KWLTimeZone", (String) hm.get("tzid"));
            diff = timeZone.getDifference();
            requestParams.put("tzid", hm.get("tzid"));
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("aboutuser"))) {
            requestParams.put("aboutuser", hm.get("aboutuser"));
        }
        String imageName = "";
        if (newhm.get("userimage") != null) {
            imageName = ((FileItem) (newhm.get("userimage"))).getName();
            if (!StringUtil.isNullOrEmpty(imageName)) {
                requestParams.put("userimage", hm.get("userimage"));
            }
        }

        result = hrmsCommonDAOObj.saveUser(requestParams, RequestContextUtils.getLocale(request));
        if (!StringUtil.isNullOrEmpty(imageName)) {
            User user = (User) result.getEntityList().get(0);
            String fileName = user.getImage().substring(user.getImage().lastIndexOf("/") + 1,
                    user.getImage().length());
            new FileUploadHandler().uploadImage((FileItem) (newhm.get("userimage")), fileName,
                    StorageHandler.GetProfileImgStorePath(), 100, 100, false, false);
        }
        msg = result.getMsg();
        requestParams.clear();
        if (histsave == 1) {
            histdept = ua.getDepartment().getId();
        }
        if (histsave == 1 || histsave == 2) {
            String latestUpdate = "";
            HashMap<String, Object> requestParams2 = new HashMap<String, Object>();
            requestParams2.put("id", id);
            requestParams2.put("cat", Emphistory.Emp_Desg_change);
            result = hrmsCommonDAOObj.getLastUpdatedHistory(requestParams2);
            latestUpdate = result.getEntityList().get(0).toString();
            if (!latestUpdate.equals("")) {
                latestUpdate = latestUpdate.replace("-", "/");
                requestParams.put("Joindate", fmt.parse(latestUpdate));
            }
            requestParams.put("Department", histdept);
            requestParams.put("Designation", histdesig);
            requestParams.put("Userid", id);
            requestParams.put("Empid", ua.getEmployeeid());
            requestParams.put("Updatedon", saveDate);
            requestParams.put("Updatedby", updatedby);
            requestParams.put("Category", Emphistory.Emp_Desg_change);
            result = hrmsCommonDAOObj.addEmphistory(requestParams);
        }
        if (!histsal.equals("")) {
            requestParams.clear();
            requestParams.put("Userid", id);
            requestParams.put("Salary", histsal);
            requestParams.put("Updatedon", saveDate);
            requestParams.put("Updatedby", updatedby);
            requestParams.put("Category", Emphistory.Emp_Salary);
            result = hrmsCommonDAOObj.addEmphistory(requestParams);
        }

        sessionHandlerImplObj.updatePreferences(request, null,
                (StringUtil.isNullOrEmpty((String) hm.get("formatid")) ? null : (String) hm.get("formatid")),
                (StringUtil.isNullOrEmpty((String) hm.get("tzid")) ? null : (String) hm.get("tzid")), diff);
        if (roleflag == 1) {
            msg = msg + " "
                    + messageSource.getMessage("hrms.common.Rolecannotbechangedforsuperadministrator", null,
                            "Role cannot be changed for Super Administrator.",
                            RequestContextUtils.getLocale(request));
            jobj.put("roleflag", roleflag);
        }
        if (roleflag == 2) {
            msg = msg + " <br><br><br>" + messageSource.getMessage(
                    "hrms.common.rolecannotbechangedtocompanyemployee", null,
                    "Note : Role cannot be changed to Company Employee. Please re-assign or remove its child node in Organization Chart before changing its role to Company Employee.",
                    RequestContextUtils.getLocale(request));
            jobj.put("roleflag", roleflag);
        }
        jobj.put("msg", msg);
        jobj.put("success", true);
        txnManager.commit(status);
    } catch (Exception e) {
        try {
            if (e.getMessage().equals("Employee ID already present.")) {
                jobj.put("msg", e.getMessage());
            }
        } catch (Exception ex) {
            e.printStackTrace();
        }
        e.printStackTrace();
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

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

public ModelAndView saveCampaignTarget(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;//from w ww. jav a  2 s  .  c o  m
    //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 type = Integer.parseInt(request.getParameter("type"));
        JSONObject jobj = new JSONObject();

        if (type == 1) {
            String targID = request.getParameter("targID");
            String campID = request.getParameter("campID");
            String userid = sessionHandlerImpl.getUserid(request);
            String camptargetid = java.util.UUID.randomUUID().toString();

            jobj.put("userid", userid);
            jobj.put("campid", campID);
            jobj.put("targetid", targID);
            jobj.put("camptargetid", camptargetid);
            jobj.put("userid", userid);
            jobj.put("createdon", new Date().getTime());
            kmsg = crmEmailMarketingDAOObj.addCampaignTarget(jobj);
        } else if (type == 2) {
            String camptargetid = request.getParameter("ctID");
            jobj.put("camptargetid", camptargetid);
            jobj.put("deleted", 1);
            kmsg = crmEmailMarketingDAOObj.editCampaignTarget(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());
}