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

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

Introduction

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

Prototype

public DefaultTransactionDefinition() 

Source Link

Document

Create a new DefaultTransactionDefinition, with default settings.

Usage

From source file:com.krawler.spring.crm.activityModule.crmActivityController.java

public ModelAndView deleteActivity(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = null;/*from w ww. j  av  a2  s. com*/
    KwlReturnObject kmsg = null;
    CrmActivityMaster activity = 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 {
        String userid = sessionHandlerImpl.getUserid(request);
        ArrayList activityids = new ArrayList();
        String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
        myjobj = new JSONObject();
        myjobj.put("success", false);
        if (StringUtil.bNull(request.getParameter("jsondata"))) {
            String jsondata = request.getParameter("jsondata");
            JSONArray jarr = new JSONArray("[" + jsondata + "]");

            for (int i = 0; i < jarr.length(); i++) {
                JSONObject jobject = jarr.getJSONObject(i);
                activityids.add(jobject.getString("activityid").toString());
            }

            String[] arrayid = (String[]) activityids.toArray(new String[] {});
            JSONObject jobj = new JSONObject();
            jobj.put("deleteflag", 1);
            jobj.put("activityid", arrayid);
            jobj.put("userid", userid);
            jobj.put("updatedon", new Date());
            jobj.put("tzdiff", timeZoneDiff);

            kmsg = crmActivityDAOObj.updateMassActivity(jobj);

            List<CrmActivityMaster> ll = crmActivityDAOObj.getActivities(activityids);

            if (ll != null) {
                for (int i = 0; i < ll.size(); i++) {
                    CrmActivityMaster activityaudit = (CrmActivityMaster) ll.get(i);
                    if (activityaudit.getValidflag() == 1) {
                        auditTrailDAOObj.insertAuditLog(AuditAction.ACTIVITY_DELETE,
                                activityaudit.getFlag() + " - Activity deleted ", request,
                                activityaudit.getActivityid());
                    }
                }
            }

            JSONObject cometObj = new JSONObject();
            cometObj.put("ids", jarr);
            publishActivityModuleInformation(request, cometObj, CrmPublisherHandler.DELETERECORDCODE,
                    sessionHandlerImpl.getCompanyid(request), userid);
        }
        myjobj.put("success", true);
        myjobj.put("ID", activityids.toArray());
        txnManager.commit(status);
    } catch (JSONException 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.profileHandler.profileHandlerController.java

public ModelAndView saveDateFormat(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.j  a v  a 2  s .co  m*/
        String dateid = request.getParameter("newformat");
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("userid", sessionHandlerImpl.getUserid(request));
        requestParams.put("dateformat", StringUtil.checkForNull(dateid));
        requestParams.put("addUser", false);

        profileHandlerDAOObj.saveUser(requestParams);
        request.getSession().setAttribute("dateformatid", dateid);
        jobj.put("success", true);
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn("General exception in saveDateFormat()", e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

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

/**
 * {@inheritDoc}//from w w w  .  j  av  a2s . c o m
 */
@Override
@RequestMapping(value = "/remove", method = RequestMethod.POST)
public ResponseEntity<Response> remove(@RequestBody final RequestData request) {

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

    Object[] queryParams = { request.getRequest_data().getCid() };

    TransactionDefinition def = new DefaultTransactionDefinition();
    TransactionStatus status = transactionManager.getTransaction(def);
    SimpleResponse reponse = null;
    try {
        dao.insertUpdateObject(SibConstants.SqlMapperBROT163.SQL_DELETE_COMMENT_VIDEO, queryParams);
        dao.insertUpdateObject(SibConstants.SqlMapper.SQL_SIB_REMOVE_COMMENT, queryParams);
        transactionManager.commit(status);
        reponse = new SimpleResponse(SibConstants.SUCCESS, request.getRequest_data_type(),
                request.getRequest_data_method(), "Success");
    } catch (Exception e) {
        e.printStackTrace();
        transactionManager.rollback(status);
        reponse = new SimpleResponse(SibConstants.FAILURE, request.getRequest_data_type(),
                request.getRequest_data_method(), "Failed");
    }
    ResponseEntity<Response> entity = new ResponseEntity<Response>(reponse, HttpStatus.OK);
    return entity;
}

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

public ModelAndView deleteDocuments(HttpServletRequest request, HttpServletResponse response) {
    KwlReturnObject result;//from w  w w  .j a va2 s. co  m
    JSONObject jobj = new JSONObject();
    JSONObject jobj1 = 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 {
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("ids", request.getParameterValues("ids"));
        String applicant = request.getParameter("applicant");
        applicant = StringUtil.checkForNull(applicant);
        if (applicant.equalsIgnoreCase("applicant")) {
            result = hrmsExtApplDocsDAOObj.deleteDocuments(requestParams);
        } else {
            result = documentDAOObj.deleteDocuments(requestParams);
        }
        if (result.isSuccessFlag()) {
            jobj.put("success", true);
        } else {
            jobj.put("success", false);
        }
        jobj1.put("data", jobj.toString());
        jobj1.put("valid", true);
        txnManager.commit(status);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        txnManager.rollback(status);
    } finally {
        return new ModelAndView("jsonView", "model", jobj1.toString());
    }
}

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

public void createUserRegistration(final String username, final String hashedPassword,
        final String emailAddress, final String registrationId) throws DataAccessException {

    // Get the public class.
    String publicClassId;/*from   ww w.j a va2 s. com*/
    try {
        publicClassId = PreferenceCache.instance().lookup(PreferenceCache.KEY_PUBLIC_CLASS_ID);
    } catch (CacheMissException e) {
        throw new DataAccessException("The public class is not configured");
    }

    Boolean defaultCampaignCreationPrivilege;
    try {
        String privilegeString = PreferenceCache.instance()
                .lookup(PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE);

        if (privilegeString == null) {
            throw new DataAccessException("The default campaign creation privilege is missing.");
        }

        defaultCampaignCreationPrivilege = StringUtils.decodeBoolean(privilegeString);

        if (defaultCampaignCreationPrivilege == null) {
            throw new DataAccessException("The default campaign creation privilege is not a valid boolean.");
        }
    } catch (CacheMissException e) {
        throw new DataAccessException(
                "Cache doesn't know about 'known' value: " + PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE,
                e);
    }

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

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

        // Insert the new user.
        try {
            getJdbcTemplate().update(SQL_INSERT_USER, new Object[] { username, hashedPassword, emailAddress,
                    false, false, false, defaultCampaignCreationPrivilege });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER
                    + "' with parameters: " + username + ", " + emailAddress + ", " + hashedPassword + ", "
                    + false + ", " + false + ", " + false + ", " + "null", e);
        }

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

        // Get the list of campaigns for this class.
        String sqlGetCampaignIds = "SELECT ca.urn " + "FROM campaign ca, class cl, campaign_class cc "
                + "WHERE cl.urn = ? " + "AND cl.id = cc.class_id " + "AND ca.id = cc.campaign_id";
        List<String> campaignIds;
        try {
            campaignIds = getJdbcTemplate().query(sqlGetCampaignIds, new Object[] { publicClassId },
                    new SingleColumnRowMapper<String>());
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException(
                    "Error executing SQL '" + sqlGetCampaignIds + "' with parameter: " + publicClassId, e);
        }

        // Construct the parameter map for the batch update.
        List<Object[]> batchParameters = new ArrayList<Object[]>(campaignIds.size());
        for (String campaignId : campaignIds) {
            String[] parameters = new String[3];
            parameters[0] = username;
            parameters[1] = campaignId;
            parameters[2] = Campaign.Role.PARTICIPANT.toString();
            batchParameters.add(parameters);
        }

        // Perform the batch update.
        String sqlInsertUserCampaign = "INSERT INTO user_role_campaign"
                + "(user_id, campaign_id, user_role_id) " + "VALUES ("
                + "(SELECT id FROM user WHERE username = ?), " + "(SELECT id FROM campaign WHERE urn = ?), "
                + "(SELECT id FROM user_role WHERE role = ?)" + ")";
        try {
            getJdbcTemplate().batchUpdate(sqlInsertUserCampaign, batchParameters);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + sqlInsertUserCampaign + "'.", e);
        }

        // Insert the user's registration information into the 
        try {
            getJdbcTemplate().update(SQL_INSERT_REGISTRATION,
                    new Object[] { username, registrationId, (new Date()).getTime() });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_REGISTRATION
                    + "' with parameters: " + username + ", " + registrationId + ", " + (new Date()).getTime(),
                    e);
        }

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

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

@Test
public void testSuspendAndResume() throws Exception {

    try {//from   w  ww .ja  v a2  s  . co m
        txManager.setDataSource(dataSource);
        TransactionStatus status = txManager.getTransaction(new DefaultTransactionDefinition());

        session = SqlSessionUtils.getSqlSession(sqlSessionFactory);

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

        SqlSession session2 = SqlSessionUtils.getSqlSession(sqlSessionFactory);

        assertNotSame("getSqlSession() should not return suspended SqlSession", session, session2);

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

        // first tx should be resumed now and this should succeed
        session.getMapper(TestMapper.class).findTest();
        SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);
        txManager.commit(status);

        // two transactions should have completed, each using their own Connection
        assertEquals("should call DataSource.getConnection() twice", 2, dataSource.getConnectionCount());

        // both connections and should be committed
        assertEquals("should call commit on Connection 1", 1, connection.getNumberCommits());
        assertEquals("should not call rollback on Connection 1", 0, connection.getNumberRollbacks());

        assertEquals("should call commit on Connection 2", 1, connectionTwo.getNumberCommits());
        assertEquals("should not call rollback on Connection 2", 0, connectionTwo.getNumberRollbacks());

        // the SqlSession should have also committed twice
        assertEquals("should call commit on SqlSession", 2, executorInterceptor.getCommitCount());
        assertEquals("should call rollback on SqlSession", 0, executorInterceptor.getRollbackCount());

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

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

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

public ModelAndView saveEmailType(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;//from   w ww. j av  a  2 s  .c om
    //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);
        JSONObject jobj = new JSONObject();
        String companyid = sessionHandlerImpl.getCompanyid(request);
        String templatename = request.getParameter("tname");
        templatename = templatename.replaceAll("\\s+", " ").trim();
        jobj.put("userid", sessionHandlerImpl.getUserid(request));
        jobj.put("tbody", request.getParameter("tbody"));
        jobj.put("description", request.getParameter("tdesc"));
        jobj.put("subject", request.getParameter("tsub"));
        jobj.put("name", templatename);
        jobj.put("plaintext", request.getParameter("plaintext"));
        jobj.put("companyid", companyid);

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

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_params", filter_params);
        KwlReturnObject kmsg1 = crmEmailMarketingDAOObj.getEmailTypeContent(requestParams);
        if (kmsg1.getRecordTotalCount() > 0) {
            List<EnumEmailType> enumEmailList = kmsg1.getEntityList();
            for (EnumEmailType eet : enumEmailList) {
                jobj.put("modifiedon", new Date().getTime());
                jobj.put("tid", eet.getTypeid());
            }
            kmsg = crmEmailMarketingDAOObj.editEmailType(jobj);
        } else {
            jobj.put("modifiedon", new Date().getTime());
            jobj.put("createdon", new Date().getTime());
            kmsg = crmEmailMarketingDAOObj.addEmailType(jobj);
        }

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

From source file:com.krawler.spring.profileHandler.profileHandlerController.java

public ModelAndView deleteUser(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 .j  a  v  a2s.  co m
        String[] ids = request.getParameterValues("userids");
        for (int i = 0; i < ids.length; i++) {
            profileHandlerDAOObj.deleteUser(ids[i]);
        }
        jobj.put("msg", messageSource.getMessage("crm.userprofile.deleteusersuccessmsg", null,
                RequestContextUtils.getLocale(request)));//"User deleted successfully");
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn("General exception in deleteUser()", e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

From source file:com.krawler.esp.handlers.zohoRequestHandler.java

public String saveUpdateZohoAccounts(String username, String password, String authToken, String userid,
        String companyid) {//from   ww w  . j a v a 2  s  . co  m

    //        Session s = zohoRequestDAO.getCurrentSession();
    String result = "{success:false,recCount:0,totalRecords:0}";
    int recCount = 0;
    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 Hql = "from CrmAccount c where  c.accountid= ?";
        JSONObject jobj = getRecordJson("Accounts", username, password, authToken); //Potential , Leads, Accounts
        if (jobj.get("success").equals(true)) {
            JSONArray dataArray = jobj.getJSONArray("data");
            for (int cnt = 0; cnt < dataArray.length(); cnt++) {
                //                    Transaction tx = (Transaction) s.beginTransaction();
                JSONObject recObj = dataArray.getJSONObject(cnt);
                List existingContact = zohoRequestDAO.executeQuery(Hql,
                        new Object[] { recObj.get("ACCOUNTID") });

                JSONObject accJObj = new JSONObject();
                accJObj.put("accountid", recObj.get("ACCOUNTID"));
                accJObj.put("companyid", companyid);
                accJObj.put("userid", userid);
                accJObj.put("updatedon", new Date());
                accJObj.put("accountname", recObj.getString("Account Name").equals("null") ? ""
                        : recObj.getString("Account Name"));
                accJObj.put("description", "");
                accJObj.put("email",
                        recObj.getString("Website").equals("null") ? "" : recObj.getString("Website"));
                accJObj.put("phone", recObj.getString("Phone").equals("null") ? "" : recObj.getString("Phone"));
                accJObj.put("revenue", recObj.getString("Annual Revenue").equals("null") ? ""
                        : recObj.getString("Annual Revenue"));
                accJObj.put("validflag", 1);
                accJObj.put("accountownerid", userid);
                accJObj.put("isarchive", false);
                accJObj.put("deleteflag", 0);

                if (existingContact.size() > 0) {
                    KwlReturnObject kmsg = crmAccountDAOObj.editAccounts(accJObj);
                } else {
                    //                        accJObj.put("createdon", new Date());
                    KwlReturnObject kmsg = crmAccountDAOObj.addAccounts(accJObj);
                }
                recCount++;
            }
            txnManager.commit(status);
            result = "{success:true,recCount:" + recCount + ",totalRecords:" + jobj.get("recordCount") + "}";
        }
    } catch (ServiceException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    } finally {
        //            s.close();
        return result;
    }

}

From source file:com.krawler.spring.profileHandler.profileHandlerController.java

public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response) {
    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);
    KWLTimeZone timeZone = null;//from   ww  w  .  ja va  2  s  . c  o  m
    try {
        KwlReturnObject kmsg = null;
        HashMap hm = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            hm = new FileUploadHandler().getItems(request);
        }
        if (hm == null)
            throw new Exception("Form does not support file upload");

        String id = (String) hm.get("userid");

        String auditDetails = "";
        User user = null;
        String pwd = null;

        if (id != null && id.length() > 0) {
            user = (User) KwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User", id);
        }
        String companyid = sessionHandlerImpl.getCompanyid(request);
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("userid", id);
        requestParams.put("companyid", companyid);

        ArrayList filter_names = new ArrayList();
        ArrayList filter_params = new ArrayList();
        filter_names.add("u.userLogin.userName");
        filter_names.add("u.company.companyID");
        filter_names.add("!u.userID");
        filter_params.add(hm.get("username"));
        filter_params.add(sessionHandlerImpl.getCompanyid(request));
        filter_params.add(id);

        kmsg = profileHandlerDAOObj.getUserDetails(requestParams, filter_names, filter_params);
        if (kmsg.getRecordTotalCount() > 0) {
            throw new Exception("User Name already exists");
        }

        String name = (String) hm.get("username");
        String oldname = user.getUserLogin().getUserName();
        if (!name.equals(oldname))
            auditDetails += "User Name '" + oldname + "' updated to '" + name + "',";

        name = (String) hm.get("fname");
        oldname = user.getFirstName();
        if (!name.equals(oldname))
            if (!StringUtil.isNullOrEmpty(oldname))
                auditDetails += " First Name '" + oldname + "' updated to '" + name + "',";
            else
                auditDetails += " First Name '" + name + "' added,";
        name = (String) hm.get("lname");
        oldname = user.getLastName();
        if (!name.equals(oldname))
            if (!StringUtil.isNullOrEmpty(oldname))
                auditDetails += " Last Name '" + oldname + "' updated to '" + name + "',";
            else
                auditDetails += " Last Name '" + name + "' added,";
        name = (String) hm.get("emailid");
        oldname = user.getEmailID();
        if (!name.equals(oldname))
            if (!StringUtil.isNullOrEmpty(oldname))
                auditDetails += " E-mail '" + oldname + "' updated to '" + name + "',";
            else
                auditDetails += " E-mail '" + name + "' added,";
        name = StringUtil.serverHTMLStripper((String) hm.get("address"));
        oldname = user.getAddress();
        if (!name.equals(oldname))
            if (!StringUtil.isNullOrEmpty(oldname))
                auditDetails += " Address '" + oldname + "' updated to '" + name + "',";
            else
                auditDetails += " Address '" + name + "' added,";

        if (hm.get("callwithid") != null) {
            int callid = Integer.parseInt(hm.get("callwithid").toString());
            if (callid != user.getCallwith())
                auditDetails += " Call With updated,";
        }
        if (hm.get("timeformat") != null) {
            int timeformat = Integer.parseInt(hm.get("timeformat").toString());
            if (timeformat != user.getTimeformat())
                auditDetails += " Time format updated,";
        }
        name = (String) hm.get("contactno");
        oldname = user.getContactNumber();
        if (!name.equals(oldname))
            if (!StringUtil.isNullOrEmpty(oldname))
                auditDetails += " Contact Number '" + oldname + "' updated to '" + name + "',";
            else
                auditDetails += " Contact Number '" + name + "' added,";

        if (StringUtil.isNullOrEmpty((String) hm.get("formatid")) == false) {
            KWLDateFormat kdf = (KWLDateFormat) KwlCommonTablesDAOObj
                    .getClassObject("com.krawler.common.admin.KWLDateFormat", (String) hm.get("formatid"));
            if (!kdf.equals(user.getDateFormat()))
                auditDetails += " Date format updated to '" + kdf.getJavaForm() + "',";
        }
        String diff = null, tzid = null;
        if (StringUtil.isNullOrEmpty((String) hm.get("tzid")) == false) {
            timeZone = (KWLTimeZone) KwlCommonTablesDAOObj
                    .getClassObject("com.krawler.common.admin.KWLTimeZone", (String) hm.get("tzid"));
            diff = timeZone.getDifference();
            tzid = timeZone.getTzID();
            if (!timeZone.equals(user.getTimeZone()))
                auditDetails += " Timezone updated to " + timeZone.getName() + ",";
        }
        if (StringUtil.isNullOrEmpty((String) hm.get("aboutuser")) == false) {
            name = (String) hm.get("aboutuser");
            oldname = user.getAboutUser();
            if (!name.equals(oldname))
                if (!StringUtil.isNullOrEmpty(oldname))
                    auditDetails += " About User '" + oldname + "' updated to '" + name + "',";
                else
                    auditDetails += " About User '" + name + "' added,";
        }

        requestParams.put("username", hm.get("username"));
        requestParams.put("firstName", hm.get("fname"));
        requestParams.put("lastName", hm.get("lname"));
        requestParams.put("emailID", hm.get("emailid"));
        requestParams.put("address", (String) hm.get("address"));
        requestParams.put("callwith", hm.get("callwithid"));
        requestParams.put("timeformat", hm.get("timeformat"));
        requestParams.put("contactNumber", hm.get("contactno"));
        requestParams.put("dateFormat", hm.get("formatid"));
        requestParams.put("timeZone", hm.get("tzid"));
        requestParams.put("aboutUser", hm.get("aboutuser"));
        requestParams.put("image", hm.get("userimage"));

        int notificationtype = 0;
        if (hm.containsKey("notificationtype") && hm.get("notificationtype").equals("on"))
            notificationtype = 1;
        requestParams.put("notificationtype", notificationtype);
        sessionHandlerImpl.updateNotifyOnFlag(request, notificationtype == 1 ? true : false);

        requestParams.put("addUser", false);

        sessionHandlerImpl.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,
                tzid, true);
        sessionHandlerImpl.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,
                (StringUtil.isNullOrEmpty((String) hm.get("timeformat")) ? null
                        : (String) hm.get("timeformat")));

        if (id == null || id.length() <= 0) {
            //permissionHandlerDAOObj.setDefaultPermissions(1,newuser.getUserID());
            HashMap<String, Object> userRoleParams = new HashMap<String, Object>();
            userRoleParams.put("userid", sessionHandlerImpl.getUserid(request));
            userRoleParams.put("roleid", 4);
            permissionHandlerDAOObj.saveRoleList(userRoleParams);
            User creater = (User) KwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User",
                    sessionHandlerImpl.getUserid(request));
            //String fullnameCreator = (creater.getFirstName() + " " + creater.getLastName()).trim();
            String fullnameCreator = creater.getFirstName();
            if (fullnameCreator != null && creater.getLastName() != null)
                fullnameCreator += " " + creater.getLastName();

            if (StringUtil.isNullOrEmpty(creater.getFirstName())
                    && StringUtil.isNullOrEmpty(creater.getLastName())) {
                fullnameCreator = creater.getUserLogin().getUserName();
            }
            String uri = URLUtil.getPageURL(request, Links.loginpageFull);
            String pmsg = String.format(KWLErrorMsgs.msgMailInvite, user.getFirstName(), fullnameCreator,
                    user.getUserLogin().getUserName(), pwd, uri, fullnameCreator);
            String htmlmsg = String.format(KWLErrorMsgs.msgMailInviteUsernamePassword, user.getFirstName(),
                    fullnameCreator, sessionHandlerImplObj.getCompanyName(request),
                    user.getUserLogin().getUserName(), pwd, uri, uri, fullnameCreator);
            try {
                SendMailHandler.postMail(new String[] { user.getEmailID() }, "[Deskera] Welcome to Deskera CRM",
                        htmlmsg, pmsg, creater.getEmailID());
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }

        kmsg = profileHandlerDAOObj.saveUser(requestParams);
        if (kmsg.isSuccessFlag()) {
            jobj.put("msg", messageSource.getMessage("crm.userprofile.updateusersuccessmsg", null,
                    RequestContextUtils.getLocale(request)));//"Profile has been updated successfully.");
            if (!StringUtil.isNullObject(timeZone)) {
                jobj.put("tzdiff", timeZone.getDifference());
            }
            // create user entry for emails in krawlercrm database
            if (StringUtil.isNullOrEmpty(id)) {
                mailIntDAOObj.addUserEntryForEmails(sessionHandlerImpl.getUserid(request), user,
                        user.getUserLogin(), pwd, true);
            }
        } else {
            jobj.put("msg", messageSource.getMessage("crm.userprofile.updateuserfailuremsg", null,
                    RequestContextUtils.getLocale(request)));//"Sorry! User information could not be saved successfully. Please try again.");
        }

        if (auditDetails.length() > 0) {
            auditDetails = auditDetails.substring(0, auditDetails.length() - 1);
            if (!sessionHandlerImpl.getUserid(request).equals(id)) {
                auditDetails += " for user " + user.getFirstName() + " " + user.getLastName() + " ";
            }
            auditTrailDAOObj.insertAuditLog(AuditAction.User_Profile_update, auditDetails, request, id);
        }

        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn("General exception in saveUser()", e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}