package com.gpc.tams.eod.autoeod; import com.gpc.common.ApplicationContext; import com.gpc.common.Profile; import com.gpc.common.TsoConstant; import com.gpc.common.constants.refvalues.RefEODApiStatus; import com.gpc.common.constants.refvalues.RefEODTriggeredSource; import com.gpc.common.util.LockableBoolean; import com.gpc.server.storeprofile.dataaccess.StoreProfile; import com.gpc.server.util.ServerUtil; import com.gpc.tams.eod.autoeod.dataaccess.InvoiceCheck; import com.gpc.tams.eod.server.EODServer; import com.gpc.tams.eod.shared.EODApiResponse; import com.gpc.tams.eod.shared.EndOfDay; import com.gpc.valueobjects.profile.EndOfDayProfileVO; import com.gpc.valueobjects.profile.StoreProfileVO; import com.gpc.valueobjects.report.FwoPrintSettings; import com.sssw.rt.util.AgiInvokeBusinessObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.gpc.valueobjects.endofday.RefEODTaskVO; import com.gpc.server.eod.dataaccess.EODTask; import com.gpc.valueobjects.endofday.EndOfDayMonitorVO; import java.sql.SQLException; import java.text.ParseException; import java.util.Timer; import java.util.TimerTask; import java.text.SimpleDateFormat; import java.util.Date; import com.gpc.tams.eod.client.EODController; import java.util.*; public class EODAutoTriggerBackOffice{ /** * Initialize InvoiceCheck */ InvoiceCheck invoiceCheck= null; /** * Initialize AgiInvokeBusinessObject */ private AgiInvokeBusinessObject m_invoker; /** * Initialize EODController */ private EODController eODController; /** * Initialize StoreProfile */ StoreProfile storeProfileDAO = null; /** * The location of the store. */ private Integer loc = null; /** * The store locale used. */ private Locale storeLocale = null; private String autoStartTimeFormat= "HH:mm:ss"; private String centralTimeZone="CST"; private String dateTimeFormat="MM/dd/yyyy HH:mm:ss"; private String dateFormat="MM/dd/yyyy"; private String endOfDayStarted="End of Day started"; private String ipAddress = null; private HashMap eodParams = new HashMap(); private boolean isRebootTriggered = false; public EODAutoTriggerBackOffice(AgiInvokeBusinessObject invoker) { this.m_invoker = invoker; invoiceCheck = new InvoiceCheck(); storeProfileDAO = new StoreProfile(); if (loc == null) { try { loc = storeProfileDAO.getStoreLocation(); } catch (SQLException sqlException) { logger.error(" Exception while getting store location" + sqlException.getMessage()); } } eODController = EODController.getController(loc); } public EODAutoTriggerBackOffice() { invoiceCheck = new InvoiceCheck(); storeProfileDAO = new StoreProfile(); if (loc == null) { try { loc = storeProfileDAO.getStoreLocation(); } catch (SQLException sqlException) { logger.error(" Exception while getting store location" + sqlException.getMessage()); } } this.m_invoker= ServerUtil.getDatabase(); eODController = EODController.getController(loc); } private static final Logger logger = Logger.getLogger(EODAutoTriggerBackOffice.class); /** * The startSchedler method is to trigger within the time interval. */ public void startScheduler() { new Timer().scheduleAtFixedRate(new AutoTriggerBackOffice(), 0, 2 * 60000); } /** * AutoTriggerBackOffice Inner class is to trigger the runner method. */ class AutoTriggerBackOffice extends TimerTask { public void run() { boolean invoiceReviewFlag= true; boolean timeReached=false; boolean checkAutoTriggerStatus = false; EODServer.getInstance(loc).invalidateCacheEndOfDayProfileVO(); String sourceName = EODServer.getInstance(loc).getProfileVO().getEodTriggeredSource(); if(sourceName != null && sourceName.equalsIgnoreCase(RefEODTriggeredSource.AUTO)){ checkAutoTriggerStatus = true; } Integer employeeID= ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getEndOfDayProfile().getAutostartEmployeeID(); StoreProfileVO storeProfileVO = ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getStoreProfile(); storeLocale = new Locale (storeProfileVO.getRefLanguageCd(), storeProfileVO.getRefCountryCd()); String IpAddress= ApplicationContext.getInstance().getClientIPAddress(); LockableBoolean autoStartEodEnabled= ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getEndOfDayProfile().getUseAutostartEOD(); invoiceReviewFlag = invoiceCheck.checkInvoiceNeedToReviewed(loc,storeLocale.getLanguage()); boolean allCountersClosed=invoiceCheck.activityProgramSource(); EODServer.getInstance(loc).setLogFile(true); String EOD_MONITOR_LOG= EODServer.getInstance(loc).cacheLogFileString(); boolean eodExecutedForTheDay=checkEODTriggeredForDay(EOD_MONITOR_LOG); FwoPrintSettings autoEODPrinterSetup = autoEODPrinterSetup(); boolean timeToStartEOD= isTimeToStartEOD(); Boolean rebootBeforeAutoEOD=ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getEndOfDayProfile().getRebootBeforeAutoEOD(); if( timeToStartEOD == true && ! eodExecutedForTheDay && ! EODServer.isEODInProgress(loc) && autoStartEodEnabled.booleanValue() && checkAutoTriggerStatus){ if(rebootBeforeAutoEOD && !isRebootTriggered) { isRebootTriggered = EODServer.getInstance(loc).rebootServer(sourceName); } if(!isRebootTriggered){ logger.warn("EOD started"); eODController.startEndOfDay(false,false,employeeID, autoEODPrinterSetup,new FwoPrintSettings(),m_invoker ,storeLocale,IpAddress); isRebootTriggered=false; } } } } /** * startEODServletTrigger method is to trigger the EOD Manually. * @return response */ public String startEODServletTrigger(){ boolean checkAutoTriggerStatus = false; EODServer.getInstance(loc).invalidateCacheEndOfDayProfileVO(); String sourceName = EODServer.getInstance(loc).getProfileVO().getEodTriggeredSource(); if(sourceName != null && sourceName.equalsIgnoreCase(RefEODTriggeredSource.AUTO)){ checkAutoTriggerStatus = true; } boolean invoiceReviewFlag= true; EndOfDayMonitorVO endOfDayMonitorVO =invoiceCheck.getEndofDayMonitor(); if(endOfDayMonitorVO.getStartedByEmployeeID()==null){ endOfDayMonitorVO.setStartedByEmployeeID(invoiceCheck.getFirstEmployeeId()); } if( endOfDayMonitorVO.getReportPrinterID()==null){ endOfDayMonitorVO.setReportPrinterID(invoiceCheck.getFirstPrinterId()); } Integer employeeID= endOfDayMonitorVO.getStartedByEmployeeID(); if(employeeID!=null && endOfDayMonitorVO.getReportPrinterID() !=null) { String responseString=""; StoreProfileVO storeProfileVO = ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getStoreProfile(); storeLocale = new Locale (storeProfileVO.getRefLanguageCd(), storeProfileVO.getRefCountryCd()); String IpAddress= ApplicationContext.getInstance().getClientIPAddress(); invoiceReviewFlag = invoiceCheck.checkInvoiceNeedToReviewed(loc,storeLocale.getLanguage()); boolean allCountersClosed=invoiceCheck.activityProgramSource(); EODServer.getInstance(loc).setLogFile(true); String EOD_MONITOR_LOG= EODServer.getInstance(loc).cacheLogFileString(); boolean eodExecutedForTheDay=checkEODTriggeredForDay(EOD_MONITOR_LOG); FwoPrintSettings autoEODPrinterSetup = triggerEODPrinterSetup(endOfDayMonitorVO); if(checkAutoTriggerStatus && !invoiceReviewFlag && ! EODServer.isEODInProgress(loc) && !eodExecutedForTheDay && allCountersClosed){ eODController.startEndOfDay(false,false,employeeID, autoEODPrinterSetup,new FwoPrintSettings(),m_invoker ,storeLocale,IpAddress); responseString= "EOD triggered successfully"; }else{ if(!checkAutoTriggerStatus) responseString = "EOD Trigger Source Not Set to AUTO"; if(invoiceReviewFlag ) responseString= "Need Invoice Review,Can't trigger EOD\n"; if(EODServer.isEODInProgress(loc)) { responseString = responseString + "EOD is already inProgress\n"; }else if(eodExecutedForTheDay) { responseString = responseString + "EOD is already triggered for the day\n"; } if(!allCountersClosed) responseString=responseString+"Counter's open, can't trigger EOD\n"; } return responseString; }else{ return "Employee-Id or Printer Id is null"; } } /** * triggerEODPrinterSetup is to setup the PrinterDetails into the AutoEODProcess. * @return FwoPrintSettings */ private FwoPrintSettings triggerEODPrinterSetup(EndOfDayMonitorVO endOfDayMonitorVo) { FwoPrintSettings autoEODPrinterSetting= new FwoPrintSettings(); autoEODPrinterSetting.setEmployeeId(endOfDayMonitorVo.getStartedByEmployeeID()); autoEODPrinterSetting.setPrinterID(endOfDayMonitorVo.getReportPrinterID()); if(endOfDayMonitorVo.getReportPrinterUseDuplex()!=null){ autoEODPrinterSetting.setDuplex(endOfDayMonitorVo.getReportPrinterUseDuplex()); }else{ autoEODPrinterSetting.setDuplex(false); } if(endOfDayMonitorVo.getReportPrintOrientation()!=null){ autoEODPrinterSetting.setOrientation(endOfDayMonitorVo.getReportPrintOrientation()); }else{ autoEODPrinterSetting.setOrientation("P"); } autoEODPrinterSetting.setCopies(1); autoEODPrinterSetting.setRefPaperSizeID(1); autoEODPrinterSetting.setIncludePrinterControlCodes(true); return autoEODPrinterSetting; } /** * isTimeToStartEOD method is to check the time limit is reached and * start the trigger of the EOD Function. * @return boolean */ private boolean isTimeToStartEOD() { Date startTime= null; String currentTime = ""; SimpleDateFormat format = new SimpleDateFormat(autoStartTimeFormat); try { startTime = ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getEndOfDayProfile().getAutostartTime(); currentTime=format.format(new Date()); } catch (Exception e) { logger.error("Time Conversion Exception",e); } if(!currentTime.isEmpty() && !Objects.isNull(startTime)){ try { Date currentDateAndTime= format.parse(currentTime); if(currentDateAndTime.after(startTime)){ return true; } } catch (Exception e) { logger.error("currentDate parsing Exception",e); } } return false; } /** * autoEODPrinterSetup is to setup the PrinterDetails into the AutoEODProcess. * @return FwoPrintSettings */ private FwoPrintSettings autoEODPrinterSetup() { FwoPrintSettings autoEODPrinterSetting= new FwoPrintSettings(); EndOfDayProfileVO endOfDayProfileVo= ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getEndOfDayProfile(); autoEODPrinterSetting.setEmployeeId(endOfDayProfileVo.getAutostartEmployeeID()); autoEODPrinterSetting.setPrinterID(endOfDayProfileVo.getAutostartReportPrinterID()); autoEODPrinterSetting.setDuplex(endOfDayProfileVo.getAutostartReportPrinterUseDuplex()); autoEODPrinterSetting.setOrientation(endOfDayProfileVo.getAutostartReportPrintOrientation()); autoEODPrinterSetting.setCopies(1); autoEODPrinterSetting.setRefPaperSizeID(1); autoEODPrinterSetting.setIncludePrinterControlCodes(true); return autoEODPrinterSetting; } /** * checkEODTriggeredForDay is to check EOD is already triggered for the Day. * @param EOD_MONITOR_LOG * @return boolean */ private boolean checkEODTriggeredForDay(String EOD_MONITOR_LOG) { if(StringUtils.isNotEmpty(EOD_MONITOR_LOG)) { int indexOfStartEOD= StringUtils.lastIndexOf(EOD_MONITOR_LOG, endOfDayStarted); if(indexOfStartEOD!=-1) { EOD_MONITOR_LOG =EOD_MONITOR_LOG.substring(indexOfStartEOD, EOD_MONITOR_LOG.length()); String[] lines = EOD_MONITOR_LOG.split("[\r\n]+"); List myList=Arrays.asList(lines); if(myList!=null && !myList.isEmpty()) { String startLine=(String) myList.get(0); SimpleDateFormat df = new SimpleDateFormat(dateFormat); String currentTime=""; df.setTimeZone(TimeZone.getTimeZone(centralTimeZone)); currentTime=df.format(new Date()); return currentTime.equals(startLine.substring(57, 67)); } } } return false; } /** * Here in this method we were checking for the taskName passed via URL and perform required validations and * according to that it will send respond to the API in json format and the json format and required message & codes * available in the EODApiResponse.java class. * For each API request following validations are checked:- * Before retrieving the taskName from the URL: - * i) Retrieving the EOD_TRIGGERED_SOURCE from END_OF_DAY_PROFILE and check the value equals to the API. * ii) All Counters are closed or not. * iii) Auto EOD flag is turn on or off will check from the END_OF_DAY_PROFILE table column name is USE_AUTOSTART_EOD. * After passing this validation it will retrieve the list for Active tasks from the REF_EOD_TASK and EOD_TASK_DETAILS table * having ACTIVE value as Y. * Retrieving the taskName from the URL and will check this Task is available in the disabled task List if yes it will return the * response as 'Task Disable for this server'. * Else it will iterate through the Active task list and will check the following validations: - * i) Passed taskName is related to Form Task or not if it is form eod will not trigger for this task. * ii) It will check for the current task is running or not. * iii) The task is already executed for the day or not. * For the first task after the FROM_TASKS we will print the START END OF DAY MESSAGE in EODLOG.PF report * For the next task after these task will check for the following validations as per the previous task status: - * i) STATUS_NOT_FOUND * ii) DATE_MISMATCH - EOD not triggered for today * iii) STARTED or SERVER_RESTARTED - Previous task is still running. * iv) CRITICAL_TASK_FAILED - Previous critical task is failed * v) NOT_TRIGGERED_TODAY - Previous task not yet triggered * iv) After passing all these validations at last it will return the response as SUCCESSFUL * In case if the passed taskName is not available in the Active and Disable task list then it will check for the eod task name * array if it is available in that list it will return the response as TASK_NOT_AVAILABLE otherwise it will return the response * as TASK_NOT_FOUND. */ public HashMap triggerEODTaskViaAPI(String taskName){ boolean allCountersClosed = invoiceCheck.activityProgramSource(); LockableBoolean autoStartEodEnabled= ApplicationContext.getInstance().getProfile(Profile.SERVER, loc).getEndOfDayProfile().getUseAutostartEOD(); eodParams(); String responseString; HashMap paramMap = new HashMap(); EODServer.getInstance(loc).invalidateCacheEndOfDayProfileVO(); String sourceName = EODServer.getInstance(loc).getProfileVO().getEodTriggeredSource(); if(sourceName == null || !sourceName.equalsIgnoreCase(RefEODTriggeredSource.API)){ paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.EOD_TRIGGER_SOURCE, EODApiResponse.EOD_TRIGGER_SOURCE)); return paramMap; } if(!allCountersClosed){ paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.COUNTERS_NOT_CLOSED, EODApiResponse.COUNTERS_NOT_CLOSED)); return paramMap; } if(autoStartEodEnabled.booleanValue()){ paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.AUTO_EOD_FLAG, EODApiResponse.AUTO_EOD_FLAG)); return paramMap; } ArrayList allTasksList = EODTask.getRefEODTaskVOs(loc); ArrayList allNonActiveTaskList = EODTask.getEODInactiveTaskVOList(loc); String param= taskName.replace("/",""); String params = param.replaceAll("\\W", ""); String lowerTaskName = params.toLowerCase(); boolean inactiveTaskFlag = checkIfTaskIsDisabledOrNot(lowerTaskName,allNonActiveTaskList); if (!inactiveTaskFlag) { for (int i = 0; i <= allTasksList.size() - 1; i++) { RefEODTaskVO refEodTaskVo = (RefEODTaskVO) allTasksList.get(i); String logText = refEodTaskVo.getLogText(); String dbTaskDetails = logText.replace(" ", "").toLowerCase(); String dbTask = dbTaskDetails.replaceAll("\\W", ""); if (dbTask.equals(lowerTaskName)) { if (Boolean.TRUE.equals(refEodTaskVo.isFormTask())) { responseString = String.format(EODApiResponse.FORM_TASK, refEodTaskVo.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.FORM_TASK, responseString)); return paramMap; } if (EODServer.isCurrentTaskRunning(refEodTaskVo.getId())) { responseString = String.format(EODApiResponse.CURRENT_TASK_EOD_IS_RUNNING, refEodTaskVo.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.CURRENT_TASK_EOD_IS_RUNNING, responseString)); return paramMap; } if (EODServer.isTaskAlreadyExecutedForTheDay(refEodTaskVo)) { responseString = String.format(EODApiResponse.ALREADY_EXECUTED, refEodTaskVo.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.ALREADY_EXECUTED, responseString)); return paramMap; } if (i == 2) { if(EODServer.isFirstTaskAlreadyExecutedForTheDay(refEodTaskVo)){ responseString = String.format(EODApiResponse.ALREADY_EXECUTED, refEodTaskVo.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.ALREADY_EXECUTED, responseString)); return paramMap; } callInitEodMethodFromEODServer(); } if (i > 2) { RefEODTaskVO refEodTaskVo1 = (RefEODTaskVO) allTasksList.get(i - 1); String previousTaskStatus = EODServer.checkPreviousTaskStatus(refEodTaskVo1.getId()); if (previousTaskStatus == null) { responseString = String.format(EODApiResponse.STATUS_NOT_FOUND, refEodTaskVo1.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.STATUS_NOT_FOUND, responseString)); return paramMap; } if (previousTaskStatus.equalsIgnoreCase(RefEODApiStatus.DATE_MISMATCH)) { responseString = String.format(EODApiResponse.DATE_MISMATCH, refEodTaskVo1.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.DATE_MISMATCH, responseString)); return paramMap; } if (previousTaskStatus.equalsIgnoreCase(RefEODApiStatus.STARTED) || previousTaskStatus.equalsIgnoreCase(RefEODApiStatus.SERVER_RESTARTED)) { responseString = String.format(EODApiResponse.PREVIOUS_TASK_EOD_IS_RUNNING, refEodTaskVo1.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.PREVIOUS_TASK_EOD_IS_RUNNING, responseString)); return paramMap; } if (previousTaskStatus.equalsIgnoreCase(RefEODApiStatus.CRITICAL_TASK_FAILED)) { responseString = String.format(EODApiResponse.CRITICAL_TASK_FAILED, refEodTaskVo1.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.CRITICAL_TASK_FAILED, responseString)); return paramMap; } if (previousTaskStatus.equalsIgnoreCase(RefEODApiStatus.NOT_TRIGGERED_TODAY)) { responseString = String.format(EODApiResponse.PREVIOUS_TASK_NOT_TRIGGERED, refEodTaskVo1.getLogText()); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.PREVIOUS_TASK_NOT_TRIGGERED, responseString)); return paramMap; } } HashMap map = new HashMap(); if (i == allTasksList.size() - 1) { map.put(EndOfDay.KEY_IS_LAST_EOD_TASK, "TRUE"); } map.put(EndOfDay.KEY_REF_EOD_TASK_VO, refEodTaskVo); map.putAll(eodParams); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.SUCCESSFUL, EODApiResponse.SUCCESSFUL)); paramMap.put(EndOfDay.KEY_MAP_PARAMS, map); return paramMap; } } boolean isTaskNotAvailable = checkIfTaskIsNotAvailable(lowerTaskName); if(!isTaskNotAvailable){ responseString = String.format(EODApiResponse.TASK_NOT_FOUND, param); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.TASK_NOT_FOUND, responseString)); } else { responseString = String.format(EODApiResponse.TASK_NOT_AVAILABLE, param); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.TASK_NOT_AVAILABLE, responseString)); } } else { responseString = String.format(EODApiResponse.INACTIVE_TASK, param); paramMap.put(EndOfDay.KEY_OUTCOME, EODApiResponse.jsonObject(EODApiResponse.INACTIVE_TASK, responseString)); } return paramMap; } /** * Here in this method we will check for the passed taskName is available in disabled task list * or not and as per the availability it will return the boolean value. */ private static boolean checkIfTaskIsDisabledOrNot(String taskName, ArrayList taskList){ boolean flag = false; for(int i=0;i