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:org.ohmage.query.impl.UserQueries.java

@Override
public void updateUser(final String username, final String emailAddress, final Boolean admin,
        final Boolean enabled, final Boolean newAccount, final Boolean campaignCreationPrivilege,
        final Boolean classCreationPrivilege, final Boolean userSetupPrivilege, final String firstName,
        final String lastName, final String organization, final String personalId,
        final boolean deletePersonalInfo) throws DataAccessException {

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Updating a user's privileges and information.");

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

        if (emailAddress != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_EMAIL_ADDRESS, emailAddress, username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing the following SQL '" + SQL_UPDATE_EMAIL_ADDRESS
                        + "' with parameters: " + emailAddress + ", " + username, e);
            }
        }

        // Update the admin value if it's not null.
        if (admin != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_ADMIN, admin, username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing the following SQL '" + SQL_UPDATE_ADMIN
                        + "' with parameters: " + admin + ", " + username, e);
            }
        }

        // Update the enabled value if it's not null.
        if (enabled != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_ENABLED, enabled, username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing the following SQL '" + SQL_UPDATE_ENABLED
                        + "' with parameters: " + enabled + ", " + username, e);
            }
        }

        // Update the new account value if it's not null.
        if (newAccount != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_NEW_ACCOUNT, newAccount, username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing the following SQL '" + SQL_UPDATE_NEW_ACCOUNT
                        + "' with parameters: " + newAccount + ", " + username, e);
            }
        }

        // Update the campaign creation privilege value if it's not null.
        if (campaignCreationPrivilege != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_CAMPAIGN_CREATION_PRIVILEGE, campaignCreationPrivilege,
                        username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException(
                        "Error executing the following SQL '" + SQL_UPDATE_CAMPAIGN_CREATION_PRIVILEGE
                                + "' with parameters: " + campaignCreationPrivilege + ", " + username,
                        e);
            }
        }

        // Update the class creation privilege value if it's not null.
        if (classCreationPrivilege != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_CLASS_CREATION_PRIVILEGE, classCreationPrivilege, username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException(
                        "Error executing the following SQL '" + SQL_UPDATE_CLASS_CREATION_PRIVILEGE
                                + "' with parameters: " + classCreationPrivilege + ", " + username,
                        e);
            }
        }

        // Update the user setup privilege value if it's not null.
        if (userSetupPrivilege != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_USER_SETUP_PRIVILEGE, userSetupPrivilege, username);
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException(
                        "Error executing the following SQL '" + SQL_UPDATE_USER_SETUP_PRIVILEGE
                                + "' with parameters: " + userSetupPrivilege + ", " + username,
                        e);
            }
        }

        // If we are deleting the user's personal information, then we 
        // won't add new or update existing personal information.
        if (deletePersonalInfo) {
            try {
                getJdbcTemplate().update(SQL_DELETE_USER_PERSONAL, new Object[] { username });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException(
                        "Error executing SQL '" + SQL_DELETE_USER_PERSONAL + "' with parameter: " + username,
                        e);
            }
        } else {
            if (userHasPersonalInfo(username)) {
                if (firstName != null) {
                    try {
                        getJdbcTemplate().update(SQL_UPDATE_FIRST_NAME, firstName, username);
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_FIRST_NAME
                                + "' with parameters: " + firstName + ", " + username, e);
                    }
                }

                if (lastName != null) {
                    try {
                        getJdbcTemplate().update(SQL_UPDATE_LAST_NAME, lastName, username);
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_LAST_NAME
                                + "' with parameters: " + lastName + ", " + username, e);
                    }
                }

                if (organization != null) {
                    try {
                        getJdbcTemplate().update(SQL_UPDATE_ORGANIZATION, organization, username);
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_ORGANIZATION
                                + "' with parameters: " + organization + ", " + username, e);
                    }
                }

                if (personalId != null) {
                    try {
                        getJdbcTemplate().update(SQL_UPDATE_PERSONAL_ID, personalId, username);
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_PERSONAL_ID
                                + "' with parameters: " + personalId + ", " + username, e);
                    }
                }
            } else if ((firstName != null) && (lastName != null) && (organization != null)
                    && (personalId != null)) {

                try {
                    getJdbcTemplate().update(SQL_INSERT_USER_PERSONAL, username, firstName, lastName,
                            organization, personalId);
                } catch (org.springframework.dao.DataAccessException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_PERSONAL
                            + "' with parameters: " + username + ", " + firstName + ", " + lastName + ", "
                            + organization + ", " + personalId, 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.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * {@inheritDoc}//from   w  w w.  j a  v a2s .co  m
 */
@Override
@RequestMapping(value = "/rateEssay", method = RequestMethod.POST)
public ResponseEntity<Response> rateEssay(@RequestBody final EssayUploadData essayUploadData) {
    String entityName = null;
    boolean status = false;
    SimpleResponse response = null;
    TransactionStatus statusDao = null;
    try {
        if (!AuthenticationFilter.isAuthed(context)) {
            response = new SimpleResponse(SibConstants.FAILURE, "Authentication required.");
            return new ResponseEntity<Response>(response, HttpStatus.FORBIDDEN);
        }

        String uploadEssayId = essayUploadData.getUploadEssayId();
        String uid = essayUploadData.getUid();
        String rate = essayUploadData.getRating();

        // Return if vid or uid
        if (StringUtil.isNull(uploadEssayId) || StringUtil.isNull(uid) || StringUtil.isNull(rate)) {
            response = new SimpleResponse(SibConstants.FAILURE, "essay", "rateEssay",
                    "Parameter cannot null or Emppty.");
            return new ResponseEntity<Response>(response, HttpStatus.OK);
        }
        TransactionDefinition def = new DefaultTransactionDefinition();
        statusDao = transactionManager.getTransaction(def);
        // Check user rated yet
        Object[] queryParams = new Object[] { uid, uploadEssayId };
        List<Object> videoRated = dao.readObjects(SibConstants.SqlMapper.SQL_SIB_GET_USER_RATE_ESSAY,
                queryParams);

        boolean isRated = videoRated.size() > 0 ? true : false;

        if (!isRated) {
            // New rating
            entityName = SibConstants.SqlMapper.SQL_SIB_RATE_ESSAY;
            queryParams = new Object[] { uploadEssayId, uid, rate };
            status = dao.insertUpdateObject(entityName, queryParams);

            Object[] queryUpdateRate = { rate, uploadEssayId };
            dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_AVG_RATE_ESSAY, queryUpdateRate);
            // Activity Log
            activiLogService.insertActivityLog(new ActivityLogData(SibConstants.TYPE_ESSAY, "C",
                    "You rated a artical", uid, String.valueOf(uploadEssayId)));
        } else {
            Map<String, Integer> object = (Map<String, Integer>) videoRated.get(0);
            int rateOld = object.get(Parameters.RATING);
            int rateNew = Integer.parseInt(rate);
            if (rateOld != rateNew) {
                // Update rating
                queryParams = new Object[] { rate, uploadEssayId, uid };
                entityName = SibConstants.SqlMapper.SQL_SIB_RATE_UPDATE_ESSAY;
                status = dao.insertUpdateObject(entityName, queryParams);

                Object[] queryUpdateRate = { rateNew - rateOld, uploadEssayId };
                status = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_AVG_RATE_ESSAY_AGAIN,
                        queryUpdateRate);
                // Activity Log
                activiLogService.insertActivityLog(new ActivityLogData(SibConstants.TYPE_ESSAY, "U",
                        "You updated the rating a artical", uid, String.valueOf(uploadEssayId)));
            }
        }

        transactionManager.commit(statusDao);
        logger.info("Rate essay successful " + new Date());

        response = new SimpleResponse("" + status, "essay", "rateEssay", uploadEssayId);
    } catch (Exception e) {
        if (statusDao != null) {
            transactionManager.rollback(statusDao);
        }
        e.printStackTrace();
        response = new SimpleResponse(SibConstants.FAILURE, "essay", "rateEssay", e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

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

public void deleteCampaign(String campaignId) throws DataAccessException {
    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Deleting a campaign.");

    try {/*from   w  w w.ja  v a2  s  .  c  o  m*/
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            getJdbcTemplate().update(SQL_DELETE_CAMPAIGN, campaignId);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException(
                    "Error executing SQL '" + SQL_DELETE_CAMPAIGN + "' with parameter: " + campaignId, 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.krawler.spring.crm.leadModule.crmLeadCommonController.java

public ModelAndView saveEditWTLForm(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 va 2  s. co m*/
        String formfields = request.getParameter("formfields");
        String formname = request.getParameter("formname");
        String formdomain = request.getParameter("formdomain");
        String redirecturl = request.getParameter("redirectURL");
        String leadowner = request.getParameter("leadowner");
        String companyid = sessionHandlerImpl.getCompanyid(request);
        String formid = request.getParameter("formid");

        jobj = webtoLeadFormHandlerObj.saveEditWTLForm(formname, formdomain, redirecturl, formfields, companyid,
                formid, leadowner);

        txnManager.commit(status);
    } catch (Exception e) {
        txnManager.rollback(status);
        logger.warn(e.getMessage(), e);
    }
    return new ModelAndView(successView, "model", jobj.toString());
}

From source file:com.krawler.spring.crm.leadModule.crmLeadCommonController.java

public ModelAndView deleteWTLForm(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  ww.  j  a v a2s  .c  o m*/
        String formid = request.getParameter("formid");
        jobj = webtoLeadFormHandlerObj.deleteWTLForm(formid);

        txnManager.commit(status);
    } catch (Exception e) {
        txnManager.rollback(status);
        logger.warn(e.getMessage(), e);
    }
    return new ModelAndView(successView, "model", jobj.toString());
}

From source file:com.krawler.spring.crm.leadModule.crmLeadCommonController.java

public ModelAndView getWebtoleadFormlist(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobjresult = 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);
    KwlReturnObject kmsg = null;/*  w  w  w  .  j  a v  a  2s . co m*/
    try {
        String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
        String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
        String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);

        String companyid = sessionHandlerImpl.getCompanyid(request);
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("companyid", companyid);
        if (request.getParameter("ss") != null && !StringUtil.isNullOrEmpty(request.getParameter("ss"))) {
            requestParams.put("ss", request.getParameter("ss"));
        }
        requestParams.put("start", StringUtil.checkForNull(request.getParameter("start")));
        requestParams.put("limit", StringUtil.checkForNull(request.getParameter("limit")));
        kmsg = webtoLeadFormHandlerObj.getWebtoleadFormlist(requestParams);
        Iterator itr = kmsg.getEntityList().iterator();
        while (itr.hasNext()) {
            JSONObject jobj = new JSONObject();
            webtoleadform wtlformObj = (webtoleadform) itr.next();
            jobj.accumulate("formname", wtlformObj.getFormname());
            jobj.accumulate("formdomain", wtlformObj.getFormdomain());
            jobj.accumulate("redirecturl", wtlformObj.getRedirecturl());
            jobj.accumulate("formid", wtlformObj.getFormid());
            jobj.accumulate("lastupdatedon",
                    kwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId, timeZoneDiff)
                            .format(wtlformObj.getLastupdatedon()));
            jobj.accumulate("formfields", wtlformObj.getFormfield());
            jobj.accumulate("leadowner", ((User) wtlformObj.getLeadowner()).getUserID());
            jobjresult.append("data", jobj);
        }
        if (!jobjresult.has("data")) {
            jobjresult.put("data", "");
        }
        jobjresult.accumulate("totalCount", kmsg.getRecordTotalCount());
        jobjresult.accumulate("success", true);
        txnManager.commit(status);
    } catch (Exception e) {
        txnManager.rollback(status);
        logger.warn(e.getMessage(), e);
    }
    return new ModelAndView(successView, "model", jobjresult.toString());
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

/**
 * @param requestParams/*from   w w w  .  ja  v a2 s  .  co m*/
 * @param txnManager
 * @param KwlCommonTablesDAOObj
 * @param importDao
 * @param fieldManagerDAOobj
 * @return
 */
public static JSONObject importFileData(HashMap<String, Object> requestParams,
        HibernateTransactionManager txnManager, kwlCommonTablesDAO KwlCommonTablesDAOObj, ImportDAO importDao,
        fieldManagerDAO fieldManagerDAOobj) {

    JSONObject jobj = new JSONObject();
    String msg = "";
    boolean issuccess = true;

    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("import_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txnManager.getTransaction(def);
    boolean commitedEx = false;

    int total = 0, failed = 0;
    String fileName = "", tableName = "", extn = "";
    Modules module = null;

    try {
        String moduleID = "";
        String mode = (String) requestParams.get("modName");
        fileName = (String) requestParams.get("filename");
        String companyid = (String) requestParams.get("companyid");
        extn = fileName.substring(fileName.lastIndexOf(".") + 1);
        StringBuilder failedRecords = new StringBuilder();

        String dateFormat = null, dateFormatId = (String) requestParams.get("dateFormat");
        if (extn.equalsIgnoreCase("csv") && !StringUtil.isNullOrEmpty(dateFormatId)) {
            KWLDateFormat kdf = (KWLDateFormat) KwlCommonTablesDAOObj
                    .getClassObject(KWLDateFormat.class.getName(), dateFormatId);
            dateFormat = kdf != null ? kdf.getJavaForm() : null;
        }

        Object extraObj = requestParams.get("extraObj");
        JSONObject extraParams = (JSONObject) requestParams.get("extraParams");

        String jsondata = (String) requestParams.get("resjson");
        JSONObject rootcsvjobj = new JSONObject(jsondata);
        JSONArray mapping = rootcsvjobj.getJSONArray("root");

        String classPath = "", primaryKey = "", uniqueKeyMethodName = "", uniqueKeyHbmName = "";
        try {
            List list = importDao.getModuleObject(mode);
            module = (Modules) list.get(0); //Will throw null pointer if no module entry found
        } catch (Exception ex) {
            throw new DataInvalidateException("Column config not available for module " + mode);
        }

        try {
            classPath = module.getPojoClassPathFull().toString();
            primaryKey = module.getPrimaryKey_MethodName().toString();
            moduleID = module.getId();
        } catch (Exception ex) {
            throw new DataInvalidateException("Please set proper properties for module " + mode);
        }
        uniqueKeyMethodName = module.getUniqueKey_MethodName();
        uniqueKeyHbmName = module.getUniqueKey_HbmName();

        JSONArray columnConfig = getModuleColumnConfig1(module.getId(), companyid, fieldManagerDAOobj,
                module.getModuleName(), true);
        tableName = importDao.getTableName(fileName);
        HashMap<String, Object> filterParams = new HashMap<String, Object>();
        //            filterParams.put("isvalid", 1); //To fetch valid records
        KwlReturnObject kresult = importDao.getFileData(tableName, filterParams); //Fetch all valid records
        List fileDataList = kresult.getEntityList();
        Iterator itr = fileDataList.iterator();
        if (itr.hasNext()) {
            Object[] fileData = (Object[]) itr.next(); //Skip header row
            failedRecords.append(createCSVrecord(fileData) + "\"Error Message\"");//failedRecords.append("\"Row No.\","+createCSVrecord(fileData)+"\"Error Message\"");
        }
        int recIndex = 0;
        importDao.markRecordValidation(tableName, -1, 1, "", ""); //reset all invalidation
        int batchCounter = 0;
        Session session = txnManager.getSessionFactory().getCurrentSession();

        /*-Auto no custom column changes*/
        String customdataclasspath = "";
        int intModuleId = 0;
        if (moduleID.equals(Constants.MODULEID_LEAD)) {
            intModuleId = Constants.Crm_lead_moduleid;
            customdataclasspath = Constants.Crm_lead_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_ACCOUNT)) {
            intModuleId = Constants.Crm_account_moduleid;
            customdataclasspath = Constants.Crm_account_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_CONTACT)) {
            intModuleId = Constants.Crm_contact_moduleid;
            customdataclasspath = Constants.Crm_contact_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_OPPORTUNITY)) {
            intModuleId = Constants.Crm_opportunity_moduleid;
            customdataclasspath = Constants.Crm_opportunity_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_CASE)) {
            intModuleId = Constants.Crm_case_moduleid;
            customdataclasspath = Constants.Crm_case_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_PRODUCT)) {
            intModuleId = Constants.Crm_product_moduleid;
            customdataclasspath = Constants.Crm_product_custom_data_classpath;
        }
        List autoNoFieldName = new ArrayList();
        HashMap<String, String> autoNoMap = new HashMap<String, String>();
        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, intModuleId, Constants.CUSTOM_FIELD_AUTONUMBER));
        KwlReturnObject AutoNoFieldMap = fieldManagerDAOobj.getFieldParams(fieldrequestParams);
        if (AutoNoFieldMap.getEntityList().size() != 0) {
            List<FieldParams> autNoList = AutoNoFieldMap.getEntityList();
            for (FieldParams obj : autNoList) {
                String maxNo = fieldManagerDAOobj.getMaxAutoNumber(
                        Constants.Custom_column_Prefix + obj.getColnum(), customdataclasspath, companyid,
                        obj.getPrefix(), obj.getSuffix());
                Integer maxNumber = Integer.parseInt(maxNo) + 1;
                autoNoMap.put(obj.getFieldname(), maxNumber.toString());
                autoNoFieldName.add(obj.getFieldname());
                autoNoMap.put(obj.getFieldname() + "_" + Constants.CUSTOM_FIELD_PREFIX, obj.getPrefix());
                autoNoMap.put(obj.getFieldname() + "_" + Constants.CUSTOM_FIELD_SUFFIX, obj.getSuffix());
            }
        }
        // End
        while (itr.hasNext()) {
            total++;
            Object[] fileData = (Object[]) itr.next();
            recIndex = (Integer) fileData[0];
            HashMap<String, Object> dataMap = new HashMap<String, Object>();
            HashMap<String, Object> columnHeaderMap = new HashMap<String, Object>();
            HashMap<String, Object> columnCSVindexMap = new HashMap<String, Object>();
            JSONArray customfield = new JSONArray();
            for (int k = 0; k < mapping.length(); k++) {
                JSONObject mappingJson = mapping.getJSONObject(k);
                String datakey = mappingJson.getString("columnname");
                Object dataValue = cleanHTML(fileData[mappingJson.getInt("csvindex") + 1] == null ? null
                        : String.valueOf(fileData[mappingJson.getInt("csvindex") + 1])); //+1 for id column at index-0
                dataMap.put(datakey, dataValue);
                columnHeaderMap.put(datakey, mappingJson.getString("csvheader"));
                columnCSVindexMap.put(datakey, mappingJson.getInt("csvindex") + 1);
            }

            for (int j = 0; j < extraParams.length(); j++) {
                String datakey = (String) extraParams.names().get(j);
                Object dataValue = extraParams.get(datakey);
                dataMap.put(datakey, dataValue);
            }

            Object object = null;
            try {
                //                    CheckUniqueRecord(requestParams, dataMap, classPath, uniqueKeyMethodName, uniqueKeyHbmName);
                validateDataMAP2(requestParams, dataMap, columnConfig, customfield, columnHeaderMap,
                        columnCSVindexMap, dateFormat, importDao, autoNoMap);
                object = importDao.saveRecord(requestParams, dataMap, null, mode, classPath, primaryKey,
                        extraObj, customfield);
                if (batchCounter % 100 == 0) {
                    session.flush();
                    session.clear();
                }
                batchCounter++;
            } catch (Exception ex) {
                failed++;
                String errorMsg = ex.getMessage(), invalidColumns = "";
                try {
                    JSONObject errorLog = new JSONObject(errorMsg);
                    errorMsg = errorLog.getString("errorMsg");
                    invalidColumns = errorLog.getString("invalidColumns");
                } catch (JSONException jex) {
                }
                failedRecords.append("\n" + createCSVrecord(fileData) + "\"" + errorMsg + "\"");//failedRecords.append("\n"+(total)+","+createCSVrecord(fileData)+"\""+ex.getMessage()+"\"");
                importDao.markRecordValidation(tableName, recIndex, 0, errorMsg, invalidColumns);
            }
        }

        if (failed > 0) {
            createFailureFiles(fileName, failedRecords, ".csv");
        }

        int success = total - failed;
        if (total == 0) {
            msg = "Empty file.";
        } else if (success == 0) {
            msg = "Failed to import all the records.";
        } else if (success == total) {
            msg = "All records are imported successfully.";
        } else {
            msg = "Imported " + success + " record" + (success > 1 ? "s" : "") + " successfully";
            msg += (failed == 0 ? "."
                    : " and failed to import " + failed + " record" + (failed > 1 ? "s" : "") + ".");
        }

        try {
            txnManager.commit(status);
            importDao.linkCustomData(mode);
        } catch (Exception ex) {
            commitedEx = true;
            throw ex;
        }
    } catch (Exception e) {
        if (!commitedEx) { //if exception occurs during commit then dont call rollback
            txnManager.rollback(status);
        }
        issuccess = false;
        msg = "" + e.getMessage();
        Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        DefaultTransactionDefinition ldef = new DefaultTransactionDefinition();
        ldef.setName("import_Tx");
        ldef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus lstatus = txnManager.getTransaction(ldef);
        boolean exCommit = false;
        try {
            //Insert Integration log

            requestParams.put("modulename", module.getModuleName());
            requestParams.put("validflag", 2);
            if (!module.getModuleName().equals("Target") && !module.getModuleName().equals("Calibration"))
                fieldManagerDAOobj.validateimportrecords(requestParams);

            HashMap<String, Object> logDataMap = new HashMap<String, Object>();
            String logId = (String) requestParams.get("logId");
            if (!StringUtil.isNullOrEmpty(logId)) {
                logDataMap.put("Id", logId);
            }
            failed = issuccess ? failed : total;
            logDataMap.put("FileName", ImportLog.getActualFileName(fileName));
            logDataMap.put("StorageName", fileName);
            logDataMap.put("Log", msg);
            logDataMap.put("Type", fileName.substring(fileName.lastIndexOf(".") + 1));
            logDataMap.put("TotalRecs", total);
            logDataMap.put("Rejected", failed);
            logDataMap.put("Module", module.getId());
            logDataMap.put("ImportDate", new Date());
            logDataMap.put("User", (String) requestParams.get("userid"));
            logDataMap.put("Company", (String) requestParams.get("companyid"));
            importDao.saveImportLog(logDataMap);
            importDao.removeFileTable(tableName);//Remove table after importing all records
            try {
                txnManager.commit(lstatus);
            } catch (Exception ex) {
                exCommit = true;
                throw ex;
            }
        } catch (Exception ex) {
            if (!exCommit) { //if exception occurs during commit then dont call rollback
                txnManager.rollback(lstatus);
            }
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            jobj.put("success", issuccess);
            jobj.put("msg", msg);
            jobj.put("totalrecords", total);
            jobj.put("successrecords", total - failed);
            jobj.put("failedrecords", failed);
            jobj.put("filename", ImportLog.getActualFileName(fileName));
        } catch (JSONException ex) {
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return jobj;
}

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

/**
 * Updates a user's password.//from  ww  w.  j av  a 2s.  co  m
 * 
 * @param username The username of the user to be updated.
 * 
 * @param hashedPassword The new, hashed password for the user.
 */
public void updateUserPassword(String username, String hashedPassword, boolean setNewAccount)
        throws DataAccessException {
    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Updating a user's password.");

    try {
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Update the password.
        try {
            getJdbcTemplate().update(SQL_UPDATE_PASSWORD, hashedPassword, username);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing the following SQL '" + SQL_UPDATE_PASSWORD
                    + "' with parameters: " + hashedPassword + ", " + username, e);
        }

        // Ensure that this user is no longer a new user.
        try {
            getJdbcTemplate().update(SQL_UPDATE_NEW_ACCOUNT, setNewAccount, username);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing the following SQL '" + SQL_UPDATE_NEW_ACCOUNT
                    + "' with parameters: " + setNewAccount + ", " + username, 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.krawler.spring.crm.leadModule.crmLeadCommonController.java

public ModelAndView storeLead(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String result = "Problem while submitting your form.";
    HashMap model = new HashMap();
    Map paramMap1 = (java.util.Map) request.getParameterMap();
    HashMap paramMap = new HashMap();
    User user = null;/*from w w  w  .  j  a  v a2  s. c  o  m*/
    User sender = 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 {
        model.put("successFlag", "1");
        model.put("redirectFlag", "0");
        String successMsg = "Thank you for submitting your information.";
        String val = "";
        int mtyfieldCntr = 0;
        Set arrayKeys = paramMap1.keySet();
        HashMap fieldMap = new HashMap();
        JSONObject fieldJSON = null;
        if (!StringUtil.isNullOrEmpty(request.getParameter("fieldJSON"))) {
            try {
                fieldJSON = new JSONObject(request.getParameter("fieldJSON"));
            } catch (JSONException je) {
                logger.warn("crmLeadCommonController.storeLead :- " + je.getMessage());
            } finally {
                fieldJSON = null;
            }
        }

        HashMap<String, Object> mailFieldsMap = new HashMap<String, Object>();
        HashMap<String, Object> mailValueMap = new HashMap<String, Object>();
        for (Object key : arrayKeys) {
            if (((String) key).startsWith("wl_")) {
                fieldMap.put(key, paramMap1.get((String) key) != null
                        ? new String[] {
                                StringUtil.serverHTMLStripper(((String[]) paramMap1.get((String) key))[0]) }
                        : null);
                if (paramMap1.get((String) key) != null) {
                    val = StringUtil.serverHTMLStripper(((String[]) paramMap1.get((String) key))[0]);
                    if (val.trim().equals("")) {
                        mtyfieldCntr++;
                    }
                }
            }
        }
        if (mtyfieldCntr != fieldMap.size()) {
            paramMap.putAll(paramMap1);
            paramMap.putAll(fieldMap);
            String subdomain = URLUtil.getDomainName(request);
            String companyid = companyDetailsDAOObj.getCompanyid(subdomain);
            Company company = (Company) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.Company",
                    companyid);
            sender = company.getCreator();
            String acceptURL = URLUtil.getRequestPageURL(request, Links.UnprotectedLoginPageFull)
                    + "crm/common/acceptweblead.do";
            int leadRoutingUser = 0;
            CompanyPreferences cmpPref = (CompanyPreferences) kwlCommonTablesDAOObj
                    .getClassObject("com.krawler.crm.database.tables.CompanyPreferences", companyid);
            JSONObject companyPrefObj = crmManagerCommon.getCompanyPreferencesJSON(cmpPref, new JSONObject());
            user = (User) kwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User",
                    ((String[]) paramMap.get("leadOwner"))[0]);
            if (companyPrefObj.getInt(
                    com.krawler.common.util.Constants.SESSION_LEADROUTING) == LeadRoutingUsers.ROUNDROBIN) {
                user = crmManagerDAOObj.getNextLeadRoutingUsers(companyid).get(0);
                leadRoutingUser = LeadRoutingUsers.ROUNDROBIN;
            }
            if (companyPrefObj
                    .getInt(com.krawler.common.util.Constants.SESSION_LEADROUTING) == LeadRoutingUsers.FCFS) {
                leadRoutingUser = LeadRoutingUsers.FCFS;
            }

            JSONObject resultObj = webtoLeadFormHandlerObj.storeLead(paramMap, companyid, user.getUserID(),
                    acceptURL, leadRoutingUser);

            result = resultObj.optString("msg", result);
            if (!result.equals("Success")) {
                successMsg = result;
                model.put("successFlag", "0");
                txnManager.rollback(status);
            } else {
                CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, resultObj.getString("leadid"));
                if (fieldJSON != null) {
                    Iterator itr = fieldJSON.keys();
                    String keyStr = "";
                    String tmp = "";
                    String str = "";
                    String tmpAr = "";
                    int xtype = 999;
                    String[] valuesArr = null;
                    DefaultMasterItem defItem = null;
                    FieldComboData fieldCombodata = null;
                    Object invoker = null;
                    Class cl = null;
                    CrmLeadCustomData lcdata = null;
                    Method setter = null;
                    List<String> tmpProductlist = new ArrayList<String>();
                    while (itr.hasNext()) {
                        keyStr = (String) itr.next();
                        mailFieldsMap.put(keyStr, fieldJSON.get(keyStr));
                    }

                    for (String tmpStr : mailFieldsMap.keySet()) {
                        if (tmpStr.endsWith("_DROPDOWN#")) {
                            str = tmpStr;
                            str = str.replace("_DROPDOWN#", "");
                            if (tmpStr.startsWith("custom_field")) {
                                str = str.replace("custom_field", "");
                                if (paramMap.get("wl_custom_field" + str) != null) {
                                    fieldCombodata = (FieldComboData) kwlCommonTablesDAOObj.getClassObject(
                                            "com.krawler.common.admin.FieldComboData",
                                            ((String[]) paramMap.get("wl_custom_field" + str))[0]);
                                    if (fieldCombodata == null) { //Custom reference combo check- Since some   custom column may have reference of default combos.
                                        defItem = (DefaultMasterItem) kwlCommonTablesDAOObj.getClassObject(
                                                "com.krawler.crm.database.tables.DefaultMasterItem",
                                                ((String[]) paramMap.get("wl_custom_field" + str))[0]);
                                        if (defItem != null) {
                                            mailValueMap.put(tmpStr, defItem.getValue());
                                        }
                                    } else {
                                        FieldParams fieldParamObj = fieldCombodata.getField();
                                        xtype = fieldParamObj.getFieldtype();
                                        if (xtype == 7) { // for Multi select dropdown
                                            if (request.getParameterValues("wl_custom_field" + str) != null) {
                                                valuesArr = request.getParameterValues("wl_custom_field" + str);
                                                tmp = "";
                                                tmpAr = "";
                                                for (int i = 0; i < valuesArr.length; i++) {
                                                    fieldCombodata = (FieldComboData) kwlCommonTablesDAOObj
                                                            .getClassObject(
                                                                    "com.krawler.common.admin.FieldComboData",
                                                                    valuesArr[i]);
                                                    if (i == valuesArr.length - 1) {
                                                        tmp += fieldCombodata.getValue();
                                                        tmpAr += valuesArr[i];
                                                    } else {
                                                        tmp += fieldCombodata.getValue() + ",";
                                                        tmpAr += valuesArr[i] + ",";
                                                    }
                                                }
                                                mailValueMap.put(tmpStr, tmp);
                                                //Since multiselect combo list has not been saved becoz parammap contains only single value as there are multiple values selected
                                                if (((String[]) paramMap.get(
                                                        "wl_custom_field" + str)).length < valuesArr.length) {
                                                    try {
                                                        lcdata = l.getCrmLeadCustomDataobj();
                                                        cl = Class.forName(
                                                                "com.krawler.crm.database.tables.CrmCustomData");
                                                        invoker = (Object) lcdata;
                                                        setter = cl.getMethod(
                                                                "setCol" + fieldParamObj.getColnum(),
                                                                String.class);
                                                        setter.invoke(invoker, tmpAr);
                                                        l.setCrmLeadCustomDataobj((CrmLeadCustomData) invoker);
                                                    } catch (Exception e) {
                                                        logger.warn(e.getMessage());
                                                    }
                                                }
                                            } else
                                                mailValueMap.put(tmpStr, "");
                                        } else {
                                            fieldCombodata = (FieldComboData) kwlCommonTablesDAOObj
                                                    .getClassObject("com.krawler.common.admin.FieldComboData",
                                                            ((String[]) paramMap
                                                                    .get("wl_custom_field" + str))[0]);
                                            mailValueMap.put(tmpStr, fieldCombodata.getValue());
                                        }
                                    }
                                } else {
                                    mailValueMap.put(tmpStr, "");
                                }
                            } else if (tmpStr.startsWith("productid")) {
                                if (request.getParameterValues("wl_" + str) != null) {
                                    valuesArr = request.getParameterValues("wl_" + str);
                                    tmp = "";
                                    for (int n = 0; n < valuesArr.length; n++) {
                                        if (!tmpProductlist.isEmpty()) {
                                            tmpProductlist.remove(0);
                                        }
                                        tmpProductlist.add(valuesArr[n]);
                                        tmp += ((crmProductDAOObj.getProducts(tmpProductlist)).get(0))
                                                .getProductname() + ",";
                                    }
                                    tmp = tmp.substring(0, tmp.lastIndexOf(','));
                                    mailValueMap.put(tmpStr, tmp);
                                    if (((String[]) paramMap.get("wl_productid")).length < valuesArr.length) {
                                        //Since products list has not been saved becoz parammap contains only single value as there are multiple values selected
                                        try {
                                            crmLeadDAOObj.saveLeadProducts(new String[] { l.getLeadid() },
                                                    valuesArr);
                                        } catch (Exception ex) {
                                            logger.warn(ex.getMessage());
                                        }
                                    }
                                } else
                                    mailValueMap.put(tmpStr, "");
                            } else if (tmpStr.startsWith("type")) {
                                tmp = ((String[]) paramMap.get("wl_" + str))[0];
                                if (tmp == "1")
                                    mailValueMap.put(tmpStr, "Company");
                                else
                                    mailValueMap.put(tmpStr, "Individual");

                            } else {
                                defItem = (DefaultMasterItem) kwlCommonTablesDAOObj.getClassObject(
                                        "com.krawler.crm.database.tables.DefaultMasterItem",
                                        ((String[]) paramMap.get("wl_" + str))[0]);
                                if (defItem != null)
                                    mailValueMap.put(tmpStr, defItem.getValue());
                                else
                                    mailValueMap.put(tmpStr, "");
                            }
                        } else
                            mailValueMap.put(tmpStr,
                                    ((String[]) paramMap.get("wl_" + tmpStr))[0] != null
                                            ? ((String[]) paramMap.get("wl_" + tmpStr))[0]
                                            : "");
                    }
                }
                String id = java.util.UUID.randomUUID().toString();
                String ipaddr = null;
                if (StringUtil.isNullOrEmpty(request.getHeader("x-real-ip"))) {
                    ipaddr = request.getRemoteAddr();
                } else {
                    ipaddr = request.getHeader("x-real-ip");
                }
                auditTrailDAOObj
                        .insertAuditLog(AuditAction.LEAD_CREATE,
                                ((l.getLastname() == null) ? "" : l.getLastname())
                                        + " - Lead created through Web to Lead Form ",
                                ipaddr, user.getUserID(), id);

                crmCommonDAOObj.validaterecorsingledHB(Constants.MODULE_LEAD, l.getLeadid(), companyid);

                txnManager.commit(status);
                if (resultObj.has("leadid")) {
                    String leadid = resultObj.getString("leadid");
                    if (leadRoutingUser == LeadRoutingUsers.ROUNDROBIN) {
                        crmManagerDAOObj.setLastUsedFlagForLeadRouting(user.getUserID(), companyid);
                        if (fieldJSON != null)
                            sendMailToLeadOwner(user, leadid, mailFieldsMap, mailValueMap);
                        else
                            sendMailToLeadOwner(user, leadid, null, null);
                    } else if (leadRoutingUser == LeadRoutingUsers.FCFS) {
                        List<String> recepients = new ArrayList();
                        KwlReturnObject kmsg = crmManagerDAOObj.getAssignedLeadRoutingUsers(companyid,
                                new HashMap<String, Object>());
                        List<User> userlist = kmsg.getEntityList();
                        for (User userObj : userlist) {
                            recepients.add(userObj.getUserID());
                        }
                        Map refTypeMap = new HashMap();
                        Map refIdMap = new HashMap();
                        refIdMap.put("refid1", leadid);
                        refTypeMap.put("reftype1", Constants.Crm_lead_classpath);
                        HashMap<String, Object> extraParams = new HashMap<String, Object>();
                        extraParams.put(NotificationConstants.LOGINURL, acceptURL);
                        if (recepients.size() > 0) {
                            String platformUrl = ConfigReader.getinstance().get("platformURL");
                            if (platformUrl != null) {
                                getPartnerURL(platformUrl, company, CHANNEL.EMAIL, NOTIFICATIONSTATUS.REQUEST,
                                        company.getCreator().getUserID(), recepients, refIdMap, refTypeMap,
                                        extraParams);
                            } else {
                                extraParams.put(NotificationConstants.PARTNERNAME, company.getCompanyName());
                                sendMailToAssignedLeadRoutingUsers(CHANNEL.EMAIL, NOTIFICATIONSTATUS.REQUEST,
                                        company.getCreator().getUserID(), recepients, refIdMap, refTypeMap,
                                        extraParams);
                            }
                        }
                    } else {
                        if (fieldJSON != null)
                            sendMailToLeadOwner(user, leadid, mailFieldsMap, mailValueMap);
                        else
                            sendMailToLeadOwner(user, leadid, null, null);
                    }
                }
            }
            model.put("successMsg", successMsg);
            String returnurl = request.getParameter("returnurl");
            if (!StringUtil.isNullOrEmpty(returnurl)) {
                model.put("redirectFlag", "1");
                model.put("returnurl", returnurl);
            }
        } else {
            model.put("successMsg", "Form should not be empty");
            model.put("successFlag", "0");
            txnManager.rollback(status);
        }

    } catch (Exception e) {
        txnManager.rollback(status);
        logger.warn(e.getMessage(), e);
        if (user != null) {
            sender = user;
        }
        if (sender != null) {
            sendMailToLeadOwner(sender, paramMap1);
        }
    }
    return new ModelAndView("captureLead", "model", model);
}

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

public ModelAndView scheduleEmailMarketing(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 {//from  ww w. jav a 2 s. co  m
        jobj.put("success", false);
        HashMap<String, Object> requestParams = new HashMap<String, Object>();

        requestParams.put("emailmarketingid", request.getParameter("emailmarketingid"));
        requestParams.put("userid", sessionHandlerImpl.getUserid(request));
        Long scheduledate = Long.parseLong(request.getParameter("scheduledate"));
        String scheduletime = request.getParameter("scheduletime");
        requestParams.put("scheduledate", scheduledate);
        requestParams.put("scheduletime", scheduletime);

        KwlReturnObject kmsg = crmEmailMarketingDAOObj.scheduleEmailMarketing(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());
}