List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED
int PROPAGATION_REQUIRED
To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED.
Click Source Link
From source file:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param requestParams//from www . j a va2 s .c o 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:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param filename//from ww w.ja v a 2s . c o m * @param delimiterType * @param startindex * @param importDao * @return * @throws ServiceException */ public static void dumpCSVFileData(String filename, String delimiterType, int startindex, ImportDAO importDao, HibernateTransactionManager txnManager) throws ServiceException { boolean commitedEx = false; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("import_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txnManager.getTransaction(def); try { CsvReader csvReader = null; FileInputStream fstream = null; String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "importplans"; File csv = new File(destinationDirectory + "/" + filename); fstream = new FileInputStream(csv); csvReader = new CsvReader(new InputStreamReader(fstream), delimiterType); // csvReader.readHeaders(); String tableName = importDao.getTableName(filename); Session session = txnManager.getSessionFactory().getCurrentSession(); int flushCounter = 0; while (csvReader.readRecord()) { ArrayList<String> dataArray = new ArrayList<String>(); for (int i = 0; i < csvReader.getColumnCount(); i++) { dataArray.add(cleanHTML(csvReader.get(i))); } importDao.dumpFileRow(tableName, dataArray.toArray()); if (flushCounter % 30 == 0) { session.flush(); session.clear(); } flushCounter++; } try { txnManager.commit(status); } catch (Exception ex) { commitedEx = true; throw ex; } } catch (IOException ex) { throw ServiceException.FAILURE("dumpCSVFileData: " + ex.getMessage(), ex); } catch (Exception ex) { if (!commitedEx) { //if exception occurs during commit then dont call rollback txnManager.rollback(status); } throw ServiceException.FAILURE("dumpCSVFileData: " + ex.getMessage(), ex); } }
From source file:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param filename// www . jav a 2s. c o m * @param sheetNo * @param startindex * @param importDao * @return * @throws ServiceException */ public static void dumpXLSFileData(String filename, int sheetNo, int startindex, ImportDAO importDao, HibernateTransactionManager txnManager) throws ServiceException { boolean commitedEx = false; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("import_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txnManager.getTransaction(def); Session session = txnManager.getSessionFactory().getCurrentSession(); try { String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "xlsfiles"; POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(destinationDirectory + "/" + filename)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(sheetNo); //DateFormat sdf = new SimpleDateFormat(df_full); int maxRow = sheet.getLastRowNum(); int maxCol = 0; String tableName = importDao.getTableName(filename); int flushCounter = 0; for (int i = startindex; i <= maxRow; i++) { HSSFRow row = sheet.getRow(i); if (row == null) { continue; } if (i == startindex) { maxCol = row.getLastCellNum(); //Column Count } ArrayList<String> dataArray = new ArrayList<String>(); JSONObject dataObj = new JSONObject(); for (int j = 0; j < maxCol; j++) { HSSFCell cell = row.getCell(j); String val = null; if (cell == null) { dataArray.add(val); continue; } String colHeader = new CellReference(i, j).getCellRefParts()[2]; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { val = Long.toString(cell.getDateCellValue().getTime()); } else { val = dfmt.format(cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_STRING: val = ImportUtil.cleanHTML(cell.getRichStringCellValue().getString()); break; } dataObj.put(colHeader, val); dataArray.add(val); //Collect row data } //Insert Query if (dataObj.length() > 0) { // Empty row check (if lenght==0 then all columns are empty) importDao.dumpFileRow(tableName, dataArray.toArray()); if (flushCounter % 30 == 0) { session.flush(); session.clear(); } flushCounter++; } } try { txnManager.commit(status); } catch (Exception ex) { commitedEx = true; throw ex; } } catch (IOException ex) { throw ServiceException.FAILURE("dumpXLSFileData: " + ex.getMessage(), ex); } catch (Exception ex) { if (!commitedEx) { //if exception occurs during commit then dont call rollback txnManager.rollback(status); } throw ServiceException.FAILURE("dumpXLSFileData: " + ex.getMessage(), ex); } }
From source file:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param filename//from w w w . j a va 2 s . c o m * @param sheetNo * @param startindex * @param importDao * @return * @throws ServiceException */ public static void dumpXLSXFileData(String filename, int sheetNo, int startindex, ImportDAO importDao, HibernateTransactionManager txnManager) throws ServiceException { boolean commitedEx = false; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("import_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txnManager.getTransaction(def); Session session = txnManager.getSessionFactory().getCurrentSession(); try { String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "xlsfiles"; FileInputStream fs = new FileInputStream(destinationDirectory + "/" + filename); XSSFWorkbook wb = new XSSFWorkbook(fs); XSSFSheet sheet = wb.getSheetAt(sheetNo); //DateFormat sdf = new SimpleDateFormat(df_full); int maxRow = sheet.getLastRowNum(); int maxCol = 0; String tableName = importDao.getTableName(filename); int flushCounter = 0; for (int i = startindex; i <= maxRow; i++) { XSSFRow row = sheet.getRow(i); if (row == null) { continue; } if (i == startindex) { maxCol = row.getLastCellNum(); //Column Count } ArrayList<String> dataArray = new ArrayList<String>(); JSONObject dataObj = new JSONObject(); for (int j = 0; j < maxCol; j++) { XSSFCell cell = row.getCell(j); String val = null; if (cell == null) { dataArray.add(val); continue; } String colHeader = new CellReference(i, j).getCellRefParts()[2]; switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { val = Long.toString(cell.getDateCellValue().getTime()); } else { val = dfmt.format(cell.getNumericCellValue()); } break; case XSSFCell.CELL_TYPE_STRING: val = ImportUtil.cleanHTML(cell.getRichStringCellValue().getString()); break; } dataObj.put(colHeader, val); dataArray.add(val); //Collect row data } //Insert Query if (dataObj.length() > 0) { // Empty row check (if lenght==0 then all columns are empty) importDao.dumpFileRow(tableName, dataArray.toArray()); if (flushCounter % 30 == 0) { session.flush(); session.clear(); } flushCounter++; } } try { txnManager.commit(status); } catch (Exception ex) { commitedEx = true; throw ex; } } catch (IOException ex) { throw ServiceException.FAILURE("dumpXLSXFileData: " + ex.getMessage(), ex); } catch (Exception ex) { if (!commitedEx) { //if exception occurs during commit then dont call rollback txnManager.rollback(status); } throw ServiceException.FAILURE("dumpXLSXFileData: " + ex.getMessage(), ex); } }
From source file:com.krawler.spring.organizationChart.organizationChartController.java
public ModelAndView insertNode(HttpServletRequest request, HttpServletResponse response) { JSONObject jobj = new JSONObject(); JSONObject jobj1 = new JSONObject(); String retMsg = ""; //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 w ww.j a v a 2 s. c om*/ String parentid = StringUtil.checkForNull(request.getParameter("fromId")); String childid = StringUtil.checkForNull(request.getParameter("userid")); HashMap<String, Object> hm = organizationService.insertNode(parentid, childid); boolean success = Boolean.parseBoolean(hm.get("success").toString()); User parent = (User) hm.get("parent"); User child = (User) hm.get("child"); if (parent != null && child != null) { auditTrailDAOObj.insertAuditLog(AuditAction.ORGANIZATION_CHART_NODE_ASSIGNED, child.getFirstName() + " " + child.getLastName() + " re-assigned to " + parent.getFirstName() + " " + parent.getLastName(), request, "0"); } if (success) { retMsg = "{success:true}"; } else { retMsg = "{success:false,msg:\"" + messageSource.getMessage("hrms.common.not.assign.parent.node.employee.role", null, "Could not assign because, parent node has Employee role.", RequestContextUtils.getLocale(request)) + "\"}"; } jobj.put("data", retMsg); jobj1.put("valid", true); jobj1.put("data", jobj); jobj1.put("success", true); txnManager.commit(status); } catch (Exception e) { logger.warn("General exception in insertNode()", e); txnManager.rollback(status); } return new ModelAndView("jsonView", "model", jobj1.toString()); }
From source file:com.krawler.spring.organizationChart.organizationChartController.java
public ModelAndView updateNode(HttpServletRequest request, HttpServletResponse response) { JSONObject jobj = new JSONObject(); JSONObject jobj1 = new JSONObject(); String retMsg = ""; //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 a 2 s .c om String childid = request.getParameter("nodeid"); String parentid = request.getParameter("fromId"); HashMap<String, Object> hm = organizationService.updateNode(parentid, childid); boolean success = Boolean.parseBoolean(hm.get("success").toString()); User parent = (User) hm.get("parent"); User child = (User) hm.get("child"); if (parent != null && child != null) { auditTrailDAOObj.insertAuditLog(AuditAction.ORGANIZATION_CHART_NODE_ASSIGNED, child.getFirstName() + " " + child.getLastName() + " re-assigned to " + parent.getFirstName() + " " + parent.getLastName(), request, "0"); } if (success) { retMsg = "{success:true}"; } else { retMsg = "{success:false,msg:\"" + messageSource.getMessage("hrms.common.not.assign.parent.node.employee.role", null, "Could not assign because, parent node has Employee role.", RequestContextUtils.getLocale(request)) + "\"}"; } jobj.put("data", retMsg); jobj1.put("valid", true); jobj1.put("data", jobj); jobj1.put("success", true); txnManager.commit(status); } catch (Exception e) { logger.warn("General exception in updateNode()", e); txnManager.rollback(status); } return new ModelAndView("jsonView", "model", jobj1.toString()); }
From source file:com.krawler.spring.organizationChart.organizationChartController.java
public ModelAndView deleteNode(HttpServletRequest request, HttpServletResponse response) { 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 {//from w ww . j av a2s . c o m boolean success = false; String nodeid = request.getParameter("nodeId"); if (!StringUtil.isNullOrEmpty(nodeid)) { HashMap<String, Object> deleteJobj = organizationService.deleteNode(nodeid); success = Boolean.parseBoolean(deleteJobj.get("success").toString()); List<Empprofile> ll = (List<Empprofile>) deleteJobj.get("childList"); Empprofile emp = null; if (deleteJobj.get("deletedEmployee") != null) { emp = (Empprofile) deleteJobj.get("deletedEmployee"); } User parentEmp = null; if (deleteJobj.get("parentEmployee") != null) { parentEmp = (User) deleteJobj.get("parentEmployee"); } if (parentEmp != null && emp != null) { if (emp != null) { String details = emp.getUserLogin().getUserName() + " [ " + emp.getUserLogin().getUser().getFirstName() + " " + emp.getUserLogin().getUser().getLastName() + " ] Un-assigned from " + parentEmp.getFirstName() + " " + parentEmp.getLastName() + " , and removed from Organization."; auditTrailDAOObj.insertAuditLog(AuditAction.ORGANIZATION_CHART_NODE_DELETED, details, request, "0"); } for (Empprofile e : ll) { String details = e.getUserLogin().getUser().getFirstName() + " " + e.getUserLogin().getUser().getLastName() + " re-assigned to " + parentEmp.getFirstName() + " " + parentEmp.getLastName() + " "; auditTrailDAOObj.insertAuditLog(AuditAction.ORGANIZATION_CHART_NODE_ASSIGNED, details, request, "0"); } } } jobj.put("data", "{success:" + success + "}"); jobj1.put("valid", true); jobj1.put("data", jobj); jobj1.put("success", true); txnManager.commit(status); } catch (Exception e) { logger.warn("General exception in deleteNode()", e); txnManager.rollback(status); } return new ModelAndView("jsonView", "model", jobj1.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 w ww . j a v a 2s.c o 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.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 {//from w w w .j a va2 s . c om 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.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 w w w . java 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()); }