package com.gpc.tams.eod.server; // this is here for diff reasons. // Java imports import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.HashMap; import com.gpc.common.pattern.DateStyle; import com.gpc.common.pattern.FwoDatePattern; import com.gpc.common.pattern.FwoPattern; import com.gpc.common.util.RefStoreConfigurationUtil; import net.sf.json.JSONArray; import com.gpc.common.util.DateUtil; import com.gpc.valueobjects.applicationmessage.ShutdownMessageVO; import com.gpc.valueobjects.misc.ProcessControlStatusVO; import com.gpc.backofficecommon.constants.schema.*; import org.apache.log4j.Logger; import com.gpc.backofficecommon.FwoQueryBuffer; import com.gpc.backofficecommon.JNDILocator; import com.gpc.backofficecommon.JNDILocatorConstants; import com.gpc.backofficecommon.report.FwoReportPrintLogDupKeyException; import com.gpc.backofficecommon.report.FwoReportPrintLogException; import com.gpc.backofficecommon.report.FwoReportPrintLogUpdateException; import com.gpc.backofficecommon.report.TsoPrintFormat; import com.gpc.backofficecommon.util.SilverStreamExceptionHelper; import com.gpc.backofficecommon.util.TamsMisc; import com.gpc.common.ApplicationContext; import com.gpc.common.Profile; import com.gpc.common.ResourceBundleReader; import com.gpc.common.TsoConstant; import com.gpc.common.exception.ApplicationException; import com.gpc.common.util.EJBRemoteExceptionHelper; import com.gpc.common.constants.refvalues.RefEODApiStatus; import com.gpc.ejb.rpt.SBReport; import com.gpc.ejb.system.SBSystem; import com.gpc.ejb.system.SBSystemHome; import com.gpc.server.eod.dataaccess.EODTask; import com.gpc.server.rms.dataaccess.PrintLog; import com.gpc.server.util.BinLabelGeneratorUtil; import com.gpc.server.util.JDBCUtil; import com.gpc.server.util.ServerUtil; import com.gpc.server.wipmanager.FileStateManager; import com.gpc.tams.eod.shared.EndOfDay; import com.gpc.tams.io.TsoFileWriter; import com.gpc.tams.transmit.TsoTransmit; import com.gpc.valueobjects.endofday.EndOfDayMonitorVO; import com.gpc.valueobjects.endofday.EndOfDayProfileVO; import com.gpc.valueobjects.endofday.RefEODTaskVO; import com.gpc.valueobjects.profile.StoreProfileVO; import com.gpc.valueobjects.report.FwoPrintSettings; import com.gpc.valueobjects.report.printlog.FwoReportPrintLog; import com.gpc.valueobjects.system.BackupMonitorVO; import com.sssw.rt.util.AgiInvokeBusinessObject; import net.sf.json.JSONObject; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; /** * Initiates requested server-side end-of-day task * Updates table and log upon completion of server-side tasks, or upon client request * Caches log in memory and returns this short file upon request * @author Copyright © 1999-2003, Genuine Parts Company, All Rights Reserved * @version 1.0 **/ public class EODServer implements EndOfDay { private StringBuffer m_log; private EndOfDayMonitorVO m_monitorVO; private EndOfDayProfileVO m_profileVO; private Integer m_reportPrintLogID; private AgiInvokeBusinessObject m_invoker; private Collection m_eodTasks; private File m_logFile; private Integer m_loc; private Integer m_manualEmpID; private Locale m_locale; private Locale currentLocale; private String m_ipAddress; private boolean m_eodRunning; private boolean m_eodStopped; private StoreProfileVO m_storeProfileVO; private boolean m_isEOM; private boolean m_isEOQ; private boolean m_isECY; private boolean m_isEFY; private boolean isoriginalFileRenamedToCopyFile = false; private boolean isRestarted; private boolean isManuallyTriggered; private Boolean skipBackup = Boolean.FALSE; private static SBSystem sbSystem; private static final Logger logger = Logger.getLogger(EODServer.class); public static final SimpleDateFormat DT_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); public static final int LOG_TEXT_MAX_WIDTH = 52; public static final String LOG_DIVIDER = " "; public static final String PROPERTY_EOD_START_MESSAGE = "eod.PROPERTY_EOD_START_MESSAGE"; public static final String PROPERTY_EOD_RESTART_MESSAGE = "eod.PROPERTY_EOD_RESTART_MESSAGE"; public static final String PROPERTY_EOD_COMPLETE_MESSAGE = "eod.PROPERTY_EOD_COMPLETE_MESSAGE"; public static final String PROPERTY_EOD_STOP_MESSAGE = "eod.PROPERTY_EOD_STOP_MESSAGE"; public static final String PROPERTY_EOD_FAIL_MESSAGE = "eod.PROPERTY_EOD_FAIL_MESSAGE"; public static final String PROPERTY_EOD_BACKUP_FAILED_MESSAGE = "eod.PROPERTY_EOD_BACKUP_FAILED_MESSAGE"; public static final String PROPERTY_EOD_OFFLINE_TASK_FAILED_MESSAGE = "eod.PROPERTY_EOD_OFFLINE_TASK_FAILED_MESSAGE"; public static final String PROPERTY_EOD_BACKUP_COMPLETED_SUCCESSFULLY = "eod.PROPERTY_EOD_BACKUP_COMPLETED_SUCCESSFULLY"; public static final String PROPERTY_EOD_BACKUP_COMPLETED_TAPE_FAILED = "eod.PROPERTY_EOD_BACKUP_COMPLETED_TAPE_FAILED"; public static final String PROPERTY_EOD_DAILY_WAREHOUSE_TASK_NAME = "eod.PROPERTY_EOD_DAILY_WAREHOUSE_TASK_NAME"; public static final String PROPERTY_EOD_CUSTOM_PRICING_TASK_NAME = "eod.PROPERTY_EOD_CUSTOM_PRICING_TASK_NAME"; public static final String PROPERTY_EOD_MONTHLY_WAREHOUSE_TASK_NAME = "eod.PROPERTY_EOD_MONTHLY_WAREHOUSE_TASK_NAME"; public static final String PROPERTY_EOD_WAREHOUSE_STORE_WITH_GPCOWNED = "eod.PROPERTY_EOD_WAREHOUSE_STORE_WITH_GPCOWNED"; public static final String PROPERTY_EOD_WAREHOUSE_FILE_WITH_SIZE = "eod.PROPERTY_EOD_WAREHOUSE_FILE_WITH_SIZE"; public static final String PROPERTY_EOD_WAREHOUSE_NO_FILE_CREATED = "eod.PROPERTY_EOD_WAREHOUSE_NO_FILE_CREATED"; public static final String PROPERTY_EOD_CURRENT_TASK_ID = "eod.PROPERTY_EOD_CURRENT_TASK_ID"; public static final String PROPERTY_EOD_LAST_TASK_ID = "eod.PROPERTY_EOD_LAST_TASK_ID"; public static final String PROPERTY_EOD_RESTARTED_BY = "eod.PROPERTY_EOD_RESTARTED_BY"; public static final Integer EOD_LOG_REF_REPORT_ID = new Integer(91); private static final ArrayList eodServers = new ArrayList(); private SBReport sbReport; private static final Integer PROCESS_TRANSIN_TASK = new Integer(49); private static final long ONE_HOUR = 60 * 60000; private static final int ONE_DAY = 1000*60*60*24; private EODServer(Integer loc) { logger.debug("new EODServer(" + loc + ")"); this.m_loc = loc; } private static EODServer findInstance(Integer loc) { for(int i = 0; i < eodServers.size(); i++) { if(((EODServer)eodServers.get(i)).getLoc().equals(loc)) { return (EODServer)eodServers.get(i); } } return null; } public static EODServer getInstance(Integer loc) { if(loc == null) { logger.error("LOC can not be null"); throw new RuntimeException("LOC can not be null"); } EODServer aServer = findInstance(loc); if(aServer == null) { aServer = new EODServer(loc); eodServers.add(aServer); } return aServer; } public Integer getLoc() { return m_loc; } public void setLogFile(boolean createIfNotExists) { logger.debug("setLogFile()"); try { if(m_logFile == null) { String fileDir = TsoFileWriter.ARCHIVE_DIRECTORY + File.separator; java.text.SimpleDateFormat yrMthFormat = new java.text.SimpleDateFormat("yyyyMM"); String acctDate = yrMthFormat.format(getMonitorVO().getSalesYearMonth()) + getMonitorVO().getAcctDay(); if(acctDate.length() == 7) { String rightDate = acctDate.substring(0, 6) + "0" + acctDate.substring(6); acctDate = rightDate; } fileDir += acctDate; m_logFile = new File(fileDir, "EODLOG.PF"); // logger.debug("New logfile: " + m_logFile.getAbsolutePath()); } // logger.debug("m_logFile is currently set to " + m_logFile.getAbsolutePath()); // create the log file if it doesn't exist if(!m_logFile.exists() && createIfNotExists) { TsoFileWriter.createFile(m_logFile.getParent(), m_logFile.getName(), null); // logger.debug("created logFile: " + m_logFile.getAbsolutePath()); } } catch(IOException ioe) { logger.error(ioe.getMessage(), ioe); } // logger.debug("Logfile now is: " + m_logFile.getAbsolutePath()); } /** * Initializes the EOD process. * * @param invoker the invoker * @param isRestarted true, if restarted * @param isManuallyTriggered true, if manually triggered * @param manualEmpID the manual employee id * @param printOptions the printer selection settings for reports * @param binLabelPrintOptions the printer selection settings for labels * @param ipAddress the IP address * @param locale the locale * @return the Hashtable containing the parameters that are required for EOD */ public Hashtable initEOD(AgiInvokeBusinessObject invoker, boolean isRestarted, boolean isManuallyTriggered, Integer manualEmpID, FwoPrintSettings printOptions, final FwoPrintSettings binLabelPrintOptions, String ipAddress, Locale locale) { // Open file handles and database connections, and refresh singleton logger.debug("initEOD"); java.util.Date currentSysDate = new java.util.Date(); Connection conn = ServerUtil.getConnection(); this.m_eodRunning = true; this.m_invoker = invoker; this.m_manualEmpID = manualEmpID; this.isRestarted = isRestarted; this.isManuallyTriggered = isManuallyTriggered; this.m_ipAddress = ipAddress; this.m_eodStopped = false; if (locale == null) { this.currentLocale = getLocale(); } else { this.currentLocale = locale; } if( !isRestarted ) { // Clear static variables and value objects; this.m_storeProfileVO = null; this.m_log = null; this.m_monitorVO = null; this.m_profileVO = null; this.m_reportPrintLogID = null; this.m_eodTasks = null; this.m_logFile = null; this.m_isEOM = false; this.m_isEOQ = false; this.m_isECY = false; this.m_isEFY = false; // get store profile values Integer currAcctDay = getStoreProfileVO().getCurrAcctDay(); java.sql.Date currSalesYearMonth = new java.sql.Date(getStoreProfileVO().getCurrentSalesYearMonth().getTime()); Integer currQuarter = getStoreProfileVO().getCurrentQtr(); Integer lastMonthFiscalYear = getStoreProfileVO().getLastMthFiscalYr(); Integer numOfBusinessDays = getStoreProfileVO().getNumBusinessDays(); // 3. create calendar for sales year month to get current month and year values Calendar cal = Calendar.getInstance(); cal.setTime(currSalesYearMonth); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); // 3. get eod month profile values java.util.Date salesMonthEndDate = null; Statement stmt = null; ResultSet rs = null; try { FwoQueryBuffer qBuffer = new FwoQueryBuffer(); qBuffer.append("SELECT ").append(Sch_EndOfMonthProfile.SALES_MONTH_END_DATE).append(" FROM "); qBuffer.append(Sch_Tables.END_OF_MONTH_PROFILE).append(" WHERE "); qBuffer.append(Sch_EndOfMonthProfile.LOC).append(" = ").append(m_loc).append(" AND "); qBuffer.append(Sch_EndOfMonthProfile.REF_MONTH_OF_YEAR_ID).append(" = ").append(new Integer(month + 1)); logger.info("SQL: " + qBuffer.getSQL()); stmt = conn.createStatement(); rs = stmt.executeQuery(qBuffer.getSQL()); if(rs.next()) { salesMonthEndDate = (java.util.Date)rs.getObject(Sch_EndOfMonthProfile.SALES_MONTH_END_DATE); } } catch(SQLException e) { logger.error("Error getting EOD Profile settings: ", e); } finally { JDBCUtil.closeResultSet(rs); JDBCUtil.closeStatement(stmt); } FwoQueryBuffer monitorBuffer = new FwoQueryBuffer(); // 1. update the monitor, store_profile, ? tables try { FwoQueryBuffer storeProfileBuffer = new FwoQueryBuffer(); FwoQueryBuffer eodMonthProfileBuffer = new FwoQueryBuffer(); // Primary #1 monitorBuffer.append("UPDATE ").append(Sch_Tables.END_OF_DAY_MONITOR).append(" SET "); monitorBuffer.append(Sch_EndOfDayMonitor.EOD_BACKUP_FAILED).append(" = 'N'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.STARTED_BY_IP_ADDRESS).append(" = '").append(ipAddress).append("'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.CURRENT_REF_EOD_TASK_ID).append(" = NULL"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.LAST_COMPLETED_REF_EOD_TASK_ID).append(" = NULL"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.ACCT_DAY).append(" = ").append(currAcctDay); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.SALES_YEAR_MONTH).append(" = '").append(currSalesYearMonth); monitorBuffer.append("', ").append(Sch_EndOfDayMonitor.SALES_QUARTER).append(" = ").append(currQuarter); monitorBuffer.append(", ").append("PREVIOUS_EOD_STARTED_DATE = EOD_STARTED_DATE"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.EOD_STARTED_DATE).append(" = '").append(new java.sql.Timestamp(currentSysDate.getTime())).append("'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.NEW_DAY_STARTED_DATE).append(" = NULL"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.LAST_TASK_COMPLETED_DATE).append(" = NULL"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.CURRENT_TASK_START_DATE).append(" = NULL"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.LAST_PRINTED_REF_REPORT_ID).append(" = NULL"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.COMM_RECEIVED).append(" = 'N'"); // 2. update the backup monitor, set to not in use. try { BackupMonitorVO backupMonitorVO = getSBSystem().getBackupMonitorVO(); if(backupMonitorVO.getBackupInProgress() != null && backupMonitorVO.getBackupInProgress().booleanValue()) { backupMonitorVO.setBackupInProgress(Boolean.FALSE); getSBSystem().updateBackupMonitor(backupMonitorVO); } } catch(RemoteException rer) { EJBRemoteExceptionHelper.HandleMarshalException(rer); } // Primary #4 if(isManuallyTriggered) { if(manualEmpID != null) { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.STARTED_BY_EMPLOYEE_ID).append(" = ").append(manualEmpID); } if(printOptions != null) { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_ID).append(" = ").append(printOptions.getPrinterID()); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINT_ORIENTATION).append(" = '").append(printOptions.getOrientation()).append("'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_USE_DUPLEX).append(" = ").append(printOptions.getDuplex()!=null && printOptions.getDuplex().booleanValue() ? "'Y'" : "'N'"); } // update the bin label printer information. if(binLabelPrintOptions == null) { monitorBuffer.append(", ") .append(Sch_EndOfDayMonitor.BIN_LABEL_PRINTER_ID).append(" = NULL "); } else { final Integer printerId = binLabelPrintOptions.getPrinterID(); // Update BIN_LABEL_PRINTER_ID with the printer id. If no printer id is // available then set to null. if (printerId == null) { monitorBuffer.append(", ") .append(Sch_EndOfDayMonitor.BIN_LABEL_PRINTER_ID) .append(" = NULL "); } else { monitorBuffer.append(", ") .append(Sch_EndOfDayMonitor.BIN_LABEL_PRINTER_ID) .append(" = ").append(printerId).append(" "); } } // Primary #4 } else if(getProfileVO() != null) { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.STARTED_BY_EMPLOYEE_ID).append(" = ").append(getProfileVO().getAUTOSTART_EMPLOYEE_ID()); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_ID).append(" = ").append(getProfileVO().getAUTOSTART_REPORT_PRINTER_ID()); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINT_ORIENTATION).append(" = '").append(getProfileVO().getAUTOSTART_REPORT_PRINT_ORIENTATION()); monitorBuffer.append("', ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_USE_DUPLEX).append(" = '").append(getProfileVO().getAUTOSTART_REPORT_PRINTER_USE_DUPLEX()).append("'"); } storeProfileBuffer.append("UPDATE ").append(Sch_Tables.STORE_PROFILE).append(" SET\n"); // Primary #6 and data mapping #6 - is end of month? Calendar calEndOfWeek = Calendar.getInstance(); calEndOfWeek.setTime(currentSysDate); int currentDayOfWeek = calEndOfWeek.get(Calendar.DAY_OF_WEEK); if(currentDayOfWeek == Calendar.FRIDAY) { calEndOfWeek.add(Calendar.DATE,2); } else if(currentDayOfWeek == Calendar.SATURDAY) { calEndOfWeek.add(Calendar.DATE,1); } // round-up to the last second of the day calEndOfWeek.set(Calendar.HOUR_OF_DAY, 23); calEndOfWeek.set(Calendar.MINUTE, 59); calEndOfWeek.set(Calendar.SECOND, 59); boolean isSMEDBeforeSysDate = (salesMonthEndDate != null && (salesMonthEndDate.before(currentSysDate) || salesMonthEndDate.equals(currentSysDate))); boolean doesCurrentDayEqualBusinessDays = (numOfBusinessDays != null && ( (currentDayOfWeek == Calendar.FRIDAY && numOfBusinessDays.intValue() == 5) || (currentDayOfWeek == Calendar.SATURDAY && numOfBusinessDays.intValue() == 6))); boolean isSMEDDuringEndOfWeek = (salesMonthEndDate != null && (salesMonthEndDate.after(currentSysDate) && (salesMonthEndDate.before(calEndOfWeek.getTime()) || salesMonthEndDate.compareTo(calEndOfWeek.getTime())==0))); /* Three scenarios 1. Last bussiness date is the end of month date * 2. Last bussiness date is Friday and end of month is Saturday or Sunday for numOfBusinessDays=5 * 3. Last bussiness date is Saturday and end of month is Sunday for numOfBusinessDays=6 */ if(isSMEDBeforeSysDate || (doesCurrentDayEqualBusinessDays && isSMEDDuringEndOfWeek)) { // Primary #6ab if(month == Calendar.DECEMBER) { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.CALENDAR_YEAR_END).append(" = 'Y'"); cal.add(Calendar.YEAR, 1); cal.set(Calendar.MONTH, 0); storeProfileBuffer.append(Sch_StoreProfile.CURRENT_SALES_YEAR_MONTH).append(" = '"); storeProfileBuffer.append(new java.sql.Date(cal.getTime().getTime())).append("'"); // DM#5 m_isECY = true; } else { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.CALENDAR_YEAR_END).append(" = 'N'"); cal.add(Calendar.MONTH, 1); storeProfileBuffer.append(Sch_StoreProfile.CURRENT_SALES_YEAR_MONTH).append(" = '"); storeProfileBuffer.append(new java.sql.Date(cal.getTime().getTime())).append("'"); // DM#5 m_isECY = false; } // Primary #6c monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.END_OF_MONTH).append(" = 'Y'"); // DM#5 m_isEOM = true; // Primary #6d cal.setTime(salesMonthEndDate); cal.add(Calendar.YEAR, 1); eodMonthProfileBuffer.append("UPDATE ").append(Sch_Tables.END_OF_MONTH_PROFILE).append(" SET\n"); eodMonthProfileBuffer.append(Sch_EndOfMonthProfile.SALES_MONTH_END_DATE).append(" = '"); eodMonthProfileBuffer.append(new java.sql.Date(cal.getTime().getTime())).append("',"); eodMonthProfileBuffer.append(Sch_EndOfMonthProfile.LAST_MODIFIED_DATE).append(" = '"); eodMonthProfileBuffer.append(getUpdateTimestamp()).append("',"); eodMonthProfileBuffer.append(Sch_EndOfMonthProfile.MODIFIED_BY_EMPLOYEE_ID).append(" = "); eodMonthProfileBuffer.append(manualEmpID); // Primary #6e storeProfileBuffer.append(", ").append(Sch_StoreProfile.CURR_ACCT_DAY).append(" = 1"); // Primary #6fg if(month == Calendar.MARCH || month == Calendar.JUNE || month == Calendar.SEPTEMBER || month == Calendar.DECEMBER) { // quarters monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.END_OF_QUARTER).append(" = 'Y'"); storeProfileBuffer.append(", ").append(Sch_StoreProfile.CURRENT_QTR).append(" = "); switch (month) { case Calendar.MARCH: storeProfileBuffer.append("2"); break; case Calendar.JUNE: storeProfileBuffer.append("3"); break; case Calendar.SEPTEMBER: storeProfileBuffer.append("4"); break; case Calendar.DECEMBER: storeProfileBuffer.append("1"); break; default: storeProfileBuffer.append("1"); } // DM#5 m_isEOQ = true; } else { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.END_OF_QUARTER).append(" = 'N'"); // DM#5 m_isEOQ = false; } // check if it's end of fiscal year if(month + 1 == lastMonthFiscalYear.intValue()) { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.FISCAL_YEAR_END).append(" = 'Y'"); // DM#5 m_isEFY = true; } else { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.FISCAL_YEAR_END).append(" = 'N'"); // DM#5 m_isEFY = false; } } else { // Primary #7a-d monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.END_OF_MONTH).append(" = 'N'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.END_OF_QUARTER).append(" = 'N'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.CALENDAR_YEAR_END).append(" = 'N'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.FISCAL_YEAR_END).append(" = 'N'"); // DM#5 m_isEOM = false; m_isEOQ = false; m_isECY = false; m_isEFY = false; // Primary #5 storeProfileBuffer.append(Sch_StoreProfile.CURR_ACCT_DAY).append(" = ").append("" + (currAcctDay.intValue() + 1)); } // append where clauses for all update statements monitorBuffer.append("\nWHERE ").append(Sch_EndOfDayMonitor.LOC).append(" = ").append(m_loc); storeProfileBuffer.append("\nWHERE ").append(Sch_StoreProfile.LOC).append(" = ").append(m_loc); if(eodMonthProfileBuffer.toString().trim().length() > 0) { eodMonthProfileBuffer.append("\nWHERE ").append(Sch_EndOfMonthProfile.LOC).append(" = ").append(m_loc); eodMonthProfileBuffer.append("\nAND ").append(Sch_EndOfMonthProfile.REF_MONTH_OF_YEAR_ID).append("=").append(new Integer(month + 1)); logger.info("update end of month profile sql = " + eodMonthProfileBuffer.getSQL()); } // Primary #8 - execute all statements logger.info("update end of day monitor sql = " + monitorBuffer.getSQL()); logger.info("update store profile sql = " + storeProfileBuffer.getSQL()); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(monitorBuffer.getSQL()); stmt.executeUpdate(storeProfileBuffer.getSQL()); if(eodMonthProfileBuffer.toString().trim().length() > 0) { // Statement stmt1 = getSharedConnection().createStatement(); Statement stmt1 = conn.createStatement(); stmt1.executeUpdate(eodMonthProfileBuffer.getSQL()); } // set FILE_ACTIVITY_REGISTER range String updateFAR = "UPDATE FILE_ACTIVITY_REGISTER SET " + "ACCOUNTING_DAY_STARTING_FILE_ACTIVITY_ID = " + "ISNULL((ACCOUNTING_DAY_ENDING_FILE_ACTIVITY_ID)+1, 0)," + "ACCOUNTING_DAY_ENDING_FILE_ACTIVITY_ID = " + "(SELECT ISNULL(MAX(ID), 0) FROM FILE_ACTIVITY WHERE " + "FILE_ACTIVITY.LOC = " + m_loc +") WHERE LOC = " + m_loc; logger.debug("updateFAR = " + updateFAR); stmt.execute(updateFAR); conn.commit(); JDBCUtil.closeStatement(stmt); } catch(SQLException e) { logger.error("Error updating END_OF_DAY_MONITOR sql: \n" + monitorBuffer.getSQL() + "- a rollback will take place: ", e); // rollback the transaction try { conn.rollback(); } catch(SQLException e2) { logger.error("Error on rollback: ", e2); } } finally { try { conn.setAutoCommit(true); } catch(SQLException e) { logger.error("Error reseting the auto commit flag: ", e); } } } else { // THIS IS A RESTART. // update the monitor, store_profile, ? tables Statement stmt = null; try { FwoQueryBuffer monitorBuffer = new FwoQueryBuffer(); monitorBuffer.append("UPDATE ").append(Sch_Tables.END_OF_DAY_MONITOR).append(" SET\n"); // Secondary #7 if(isManuallyTriggered) { if(manualEmpID != null) { monitorBuffer.append(Sch_EndOfDayMonitor.STARTED_BY_EMPLOYEE_ID).append(" = ").append(manualEmpID); } if(printOptions != null) { monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_ID).append(" = ").append(printOptions.getPrinterID()); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINT_ORIENTATION).append(" = '").append(printOptions.getOrientation()).append("'"); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_USE_DUPLEX).append(" = ").append(printOptions.getDuplex()!=null && printOptions.getDuplex().booleanValue() ? "'Y'" : "'N'"); } // Update the bin label printer information. if(binLabelPrintOptions == null) { monitorBuffer.append(", ") .append(Sch_EndOfDayMonitor.BIN_LABEL_PRINTER_ID).append(" = NULL "); } else { // Update BIN_LABEL_PRINTER_ID with the printer id. If no printer id is // available then set to null. final Integer printerId = binLabelPrintOptions.getPrinterID(); if (printerId == null) { monitorBuffer.append(", ") .append(Sch_EndOfDayMonitor.BIN_LABEL_PRINTER_ID) .append(" = NULL "); } else { monitorBuffer.append(", ") .append(Sch_EndOfDayMonitor.BIN_LABEL_PRINTER_ID).append(" = ") .append(printerId).append(" "); } } } else if(getProfileVO() != null) { monitorBuffer.append(Sch_EndOfDayMonitor.STARTED_BY_EMPLOYEE_ID).append(" = ").append(getProfileVO().getAUTOSTART_EMPLOYEE_ID()); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_ID).append(" = ").append(getProfileVO().getAUTOSTART_REPORT_PRINTER_ID()); monitorBuffer.append(", ").append(Sch_EndOfDayMonitor.REPORT_PRINT_ORIENTATION).append(" = '").append(getProfileVO().getAUTOSTART_REPORT_PRINT_ORIENTATION()); monitorBuffer.append("', ").append(Sch_EndOfDayMonitor.REPORT_PRINTER_USE_DUPLEX).append(" = '").append(getProfileVO().getAUTOSTART_REPORT_PRINTER_USE_DUPLEX()).append("'"); } monitorBuffer.append("WHERE ").append(Sch_EndOfDayMonitor.LOC).append(" = ").append(m_loc); logger.info("update end of day monitor restart sql = " + monitorBuffer.getSQL()); stmt = conn.createStatement(); stmt.executeUpdate(monitorBuffer.getSQL()); } catch(SQLException e) { logger.error("Error updating END_OF_DAY_MONITOR on restart: ", e); } finally { JDBCUtil.closeStatement(stmt); } } if(conn != null) { ServerUtil.releaseConnection(conn); } // freshstart / restart differences now worked out... // read the monitor table after initialization m_monitorVO = getEndOfDayMonitorVO(); // Primary #9 setLogFile(true); cacheLogFile(); if(!isRestarted) { // create initial log entry // "End of Day started " String eodStartMsg = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_START_MESSAGE, getLocale()); logger.warn("EOD START MESSAGE: " + eodStartMsg); updateLog(TsoPrintFormat.format(eodStartMsg + " " + m_ipAddress, LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currentSysDate)); // create report print log record with an initial status of "INCOMPLETE_STATUS" FwoReportPrintLog printLogEntry = new FwoReportPrintLog(); printLogEntry.setLOC(m_loc); printLogEntry.setRefReportId(EOD_LOG_REF_REPORT_ID); // EODLOG printLogEntry.setEmployeeId(getMonitorVO().getStartedByEmployeeID()); //.getSTARTED_BY_EMPLOYEE_ID()); printLogEntry.setNumOfCopies(new Integer(1)); printLogEntry.setSalesYearAndMonth(new java.sql.Date(getMonitorVO().getSalesYearMonth().getTime())); printLogEntry.setAccountingDay((getMonitorVO().getAcctDay() != null ? new Integer(getMonitorVO().getAcctDay().byteValue()) : null)); printLogEntry.setRunStartDate(new java.sql.Timestamp(currentSysDate.getTime())); printLogEntry.setPrintStatus(FwoReportPrintLog.PRINT_STATUS_INCOMPLETE); try { printLogEntry = PrintLog.createPrintLog(printLogEntry); m_reportPrintLogID = printLogEntry != null ? printLogEntry.getId() : null; } catch(FwoReportPrintLogDupKeyException e) { logger.error("Error creating REPORT_PRINT_LOG record: ", e); } catch(FwoReportPrintLogUpdateException e) { logger.error("Error creating REPORT_PRINT_LOG record: ", e); } catch(FwoReportPrintLogException e) { logger.error("Error creating REPORT_PRINT_LOG record: ", e); } // prepare TOADP file if(!insertTOADPHeader()) { logger.error("Failed to insert TOADP TRANSMIT_0 header"); } } else { // restart log entry // "End of Day Manually Restarted " String eodRestartMsg = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_RESTART_MESSAGE, getLocale()); logger.warn("EOD RESTART MESSAGE: " + eodRestartMsg); updateLog(TsoPrintFormat.format(eodRestartMsg, LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currentSysDate)); // for Stel-1441 if(m_monitorVO!=null) { if(m_monitorVO.getCurrentRefEODTaskID()!=null) { String currentTaskMessage = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_CURRENT_TASK_ID, getLocale()) + m_monitorVO.getCurrentRefEODTaskID(); updateLog(currentTaskMessage); } if(m_monitorVO.getLastCompletedRefEODTaskID()!=null) { String lastTaskMessage = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_LAST_TASK_ID, getLocale()) + m_monitorVO.getLastCompletedRefEODTaskID(); updateLog(lastTaskMessage); } if(m_monitorVO.getStartedByEmployeeID()!=null) { String startedByEmployeeMsg = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_RESTARTED_BY, getLocale()) + m_monitorVO.getStartedByEmployeeID(); updateLog(startedByEmployeeMsg); } } Statement stmt = null; ResultSet rs = null; try { FwoQueryBuffer qBuffer = new FwoQueryBuffer(); qBuffer.append("SELECT ID FROM REPORT_PRINT_LOG WHERE"); qBuffer.append(" ACCOUNTING_DAY = ").append(getMonitorVO().getAcctDay().toString()); // getACCT_DAY()); qBuffer.append(" AND SALES_YEAR_MONTH = '"); qBuffer.append(new java.sql.Date(getMonitorVO().getSalesYearMonth().getTime()).toString()); qBuffer.append("'"); qBuffer.append(" AND REF_REPORT_ID = " + EOD_LOG_REF_REPORT_ID); qBuffer.append(" AND LOC = ").append(m_loc); logger.info("REPORT PRINT LOG QUERY = " + qBuffer.getSQL()); conn = ServerUtil.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(qBuffer.getSQL()); if(rs.next()) { m_reportPrintLogID = (Integer)rs.getObject("ID"); } } catch(SQLException e) { logger.error("Error retreiving REPORT_PRINT_LOG record: ", e); } finally { JDBCUtil.closeResultSet(rs); JDBCUtil.closeStatement(stmt); if(conn != null) { ServerUtil.releaseConnection(conn); } } } // read and cache the task table readTaskTable(); // why is this here? /* if(getMonitorVO().getEODBackupFailed().booleanValue()) { // if("Y".equals(getMonitorVO().getEOD_BACKUP_FAILED())) { return EODServer.createError(EODServer.ERROR_EOD_BACKUP_FAILED); } else { */ // Pass necessary the task list and the EOD string back to the controller Hashtable returnValues = new Hashtable(); returnValues.put(KEY_OUTCOME, OUTCOME_SUCCESS); returnValues.put(KEY_TASK_LIST, getEODTasks()); returnValues.put(KEY_EOD_TYPE, getEODType()); return (Hashtable) returnValues; /* } */ } private boolean insertTOADPHeader() { logger.debug("Attempting to insertTOADPHeader before EOD tasks are processed"); Date now = new Date(); String MMdd = new SimpleDateFormat("MMdd").format(now); StringBuffer buffer = new StringBuffer(); // record ID, len 1 buffer.append("0"); // store num, len 9 buffer.append(getStoreProfileVO().getStoreNum()); // MMdd, len 4 buffer.append( MMdd); logger.warn("TOADP header " + buffer.toString()); TsoTransmit transmitUtil = new TsoTransmit(); transmitUtil.setStringBuffer(buffer); transmitUtil.appendLineBreak(); return transmitUtil.writeTransmitFile(); } public String cacheLogFileString(){ cacheLogFile(); return m_log.toString(); } private void cacheLogFile() { logger.debug("cacheLogFile()"); if(m_logFile == null || !m_logFile.exists()) { //create error ??? logger.error("log file not initialized or file not found."); return; } // Connect to log .pf file and Read log file into cache try { FileInputStream fis = new FileInputStream(m_logFile); byte[] logContent = new byte[(int)m_logFile.length()]; fis.read(logContent); fis.close(); fis = null; m_log = new StringBuffer(new String(logContent)); logger.debug("cached log file: " + m_log.toString()); } catch(IOException e) { logger.error("Error caching EODLOG file: ", e); } } private static SBSystem getSBSystem() { if(sbSystem == null) { JNDILocator jndiLocator = JNDILocator.getInstance(); SBSystemHome sbSystemHome = (SBSystemHome)jndiLocator.getEJBHome(SBSystemHome.class, JNDILocatorConstants.SBSYSTEM_RMISTR); try { sbSystem = sbSystemHome.create(); } catch(RemoteException e) { EJBRemoteExceptionHelper.HandleMarshalException(e); } catch(javax.ejb.CreateException ce) { logger.error(ce.toString(), ce); } } return sbSystem; } private EndOfDayMonitorVO getEndOfDayMonitorVO() { // logger.debug("getEndOfDayMonitorVO(" + m_loc + ")"); EndOfDayMonitorVO endOfDayMonitorVO = null; try { SBSystem sbSystem = getSBSystem(); if(sbSystem != null) { endOfDayMonitorVO = sbSystem.getEndOfDayMonitor(m_loc); } } catch(RemoteException re) { EJBRemoteExceptionHelper.HandleMarshalException(re); } return endOfDayMonitorVO; } private void readProfileTable() { // logger.debug("readProfileTable"); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { FwoQueryBuffer qBuffer = new FwoQueryBuffer(); qBuffer.append("SELECT *"); qBuffer.append(" FROM ").append(Sch_Tables.END_OF_DAY_PROFILE).append(" WHERE "); qBuffer.append(Sch_EndOfDayProfile.LOC).append(" = ").append(m_loc); logger.info("query = " + qBuffer.getSQL()); conn = ServerUtil.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(qBuffer.getSQL()); if(rs.next()) { m_profileVO = new EndOfDayProfileVO(); m_profileVO.setLOC((Integer) rs.getObject(Sch_EndOfDayProfile.LOC)); m_profileVO.setSEND_LOCAL_DETAIL((Integer) rs.getObject(Sch_EndOfDayProfile.SEND_LOCAL_DETAIL)); m_profileVO.setNON_STOCK_PURGE((Integer) rs.getObject(Sch_EndOfDayProfile.NON_STOCK_PURGE)); m_profileVO.setHISTORY_PURGE_PROCESS_DAY((Integer) rs.getObject(Sch_EndOfDayProfile.HISTORY_PURGE_PROCESS_DAY)); m_profileVO.setSEND_EOM_REPORTABLE_SALES((Integer) rs.getObject(Sch_EndOfDayProfile.SEND_EOM_REPORTABLE_SALES)); m_profileVO.setREPORTED_SALES_SUMMARY_COUNTER((Integer) rs.getObject(Sch_EndOfDayProfile.REPORTED_SALES_SUMMARY_COUNTER)); m_profileVO.setPHONE_SWITCH_REMINDER((Integer) rs.getObject(Sch_EndOfDayProfile.PHONE_SWITCH_REMINDER)); m_profileVO.setCLEAR_AVG_COST_AT_ECY((Integer) rs.getObject(Sch_EndOfDayProfile.CLEAR_AVG_COST_AT_ECY)); m_profileVO.setEXPORT_TO_DATA_WAREHOUSE((Integer) rs.getObject(Sch_EndOfDayProfile.EXPORT_TO_DATA_WAREHOUSE)); m_profileVO.setUSE_AUTOSTART_EOD((Integer) rs.getObject(Sch_EndOfDayProfile.USE_AUTOSTART_EOD)); m_profileVO.setAUTOSTART_EMPLOYEE_ID((Integer) rs.getObject(Sch_EndOfDayProfile.AUTOSTART_EMPLOYEE_ID)); m_profileVO.setAUTOSTART_REPORT_PRINTER_ID((Integer) rs.getObject(Sch_EndOfDayProfile.AUTOSTART_REPORT_PRINTER_ID)); m_profileVO.setAUTOSTART_REPORT_PRINT_ORIENTATION((String) rs.getObject(Sch_EndOfDayProfile.AUTOSTART_REPORT_PRINT_ORIENTATION)); m_profileVO.setAUTOSTART_REPORT_PRINTER_USE_DUPLEX((String) rs.getObject(Sch_EndOfDayProfile.AUTOSTART_REPORT_PRINTER_USE_DUPLEX)); m_profileVO.setBACKUP_FAILURE_MSG_TO_EMAIL((String) rs.getObject(Sch_EndOfDayProfile.BACKUP_FAILURE_MSG_TO_EMAIL)); m_profileVO.setBACKUP_FAILURE_MSG_TO_EMPLOYEE_ID((Integer) rs.getObject(Sch_EndOfDayProfile.BACKUP_FAILURE_MSG_TO_EMPLOYEE_ID)); m_profileVO.setLAST_MODIFIED_DATE((Timestamp) rs.getObject(Sch_EndOfDayProfile.LAST_MODIFIED_DATE)); m_profileVO.setMODIFIED_BY_EMPLOYEE_ID((Integer) rs.getObject(Sch_EndOfDayProfile.MODIFIED_BY_EMPLOYEE_ID)); m_profileVO.setLAST_REBATE_CLAIM_NUMBER((Integer) rs.getObject(Sch_EndOfDayProfile.LAST_REBATE_CLAIM_NUMBER)); m_profileVO.setUSE_LABEL_QTY_FOR_GENERATION((Integer) rs.getObject(Sch_EndOfDayProfile.USE_LABEL_QTY_FOR_GENERATION)); m_profileVO.setUSE_NEW_EDW_COLUMN_DELIMITER((Integer)rs.getObject(Sch_EndOfDayProfile.USE_NEW_EDW_COLUMN_DELIMITER)); m_profileVO.setAUTO_CATALOG_UPDATE_DAY_OF_WEEK((Integer) rs.getObject(Sch_EndOfDayProfile.AUTO_CATALOG_UPDATE_DAY_OF_WEEK)); m_profileVO.setREBOOT_BEFORE_TRANSIN_PROCESSING((String) rs.getObject(Sch_EndOfDayProfile.REBOOT_BEFORE_TRANSIN_PROCESSING)); m_profileVO.setEOD_TRIGGERED_SOURCE((String) rs.getObject(Sch_EndOfDayProfile.EOD_TRIGGERED_SOURCE)); m_profileVO.setRegulationRunFrequency( (Integer) rs.getObject( Sch_EndOfDayProfile.REGULATION_RUN_FREQUENCY ) ); m_profileVO.setCLOSE_OF_DAY_TRIGGERED( (String) rs.getObject(Sch_EndOfDayProfile.CLOSE_OF_DAY_TRIGGERED) ); m_profileVO.setBMC_EOD_READY( (String) rs.getObject(Sch_EndOfDayProfile.BMC_EOD_READY) ); m_profileVO.setUSE_CLOUD_BACKUP_ALERT( (String) rs.getObject(Sch_EndOfDayProfile.USE_CLOUD_BACKUP_ALERT) ); m_profileVO.setPOSTPONE_EOD_FLAG( (String) rs.getObject(Sch_EndOfDayProfile.POSTPONE_EOD_FLAG) ); Object regulationLastRunDate = rs.getObject( Sch_EndOfDayProfile.REGULATION_LAST_RUN_DATE ); m_profileVO.setRegulationLastRunDate( ( regulationLastRunDate != null ) ? DateUtil.getDateFromTimestamp( (Timestamp) regulationLastRunDate ) : null ); Object o = rs.getObject(Sch_EndOfDayProfile.LAST_BIN_LABEL_GENERATED_DATE); if(o != null) { m_profileVO.setLAST_BIN_LABEL_GENERATED_DATE(new java.sql.Date(((java.util.Date)o).getTime())); } java.sql.Timestamp autoTS = (java.sql.Timestamp)rs.getObject(Sch_EndOfDayProfile.AUTOSTART_TIME); if(autoTS != null) { m_profileVO.setAUTOSTART_TIME(new java.sql.Time(autoTS.getTime())); } m_profileVO.setAUTO_INVOICE_COSTING_GP_PERCENT((java.math.BigDecimal)rs.getObject(Sch_EndOfDayProfile.AUTO_INVOICE_COSTING_GP_PERCENT)); } } catch(SQLException e) { logger.error("Error reading END_OF_DAY_PROFILE table: " + e.toString(), e); } finally { JDBCUtil.closeResultSet(rs); JDBCUtil.closeStatement(stmt); if(conn != null) { ServerUtil.releaseConnection(conn); } } } private void readTaskTable() { ArrayList alltasks = EODTask.getRefEODTaskVOs(m_loc); logger.debug("got back " + alltasks.size() + " tasks"); // remove tasks that are already done if(isRestarted) { //only if tasks were completed remove them from the list if(getMonitorVO().getLastCompletedRefEODTaskID() != null && !getMonitorVO().getLastCompletedRefEODTaskID().equals(new Integer("0"))){ while(alltasks.size() > 0) { RefEODTaskVO task = (RefEODTaskVO)alltasks.remove(0); logger.debug("removed task " + task.getId() + ", " + task.getLogText()); if(task.getId().equals(getMonitorVO().getLastCompletedRefEODTaskID())) { break; } } } } this.m_eodTasks = alltasks; } private Collection getEODTasks() { if(m_eodTasks == null) { readTaskTable(); } return m_eodTasks; } private String getEODType() { String eodInProgress = "EOD"; if(m_isEFY && m_isECY && m_isEOQ) { eodInProgress += "EFYEOQECY"; } else if(m_isECY && m_isEOQ) { eodInProgress += "EFYEOQ"; } else if(m_isEFY) { eodInProgress += "EFY"; } else if(m_isECY) { eodInProgress += "ECY"; } else if(m_isEOQ) { eodInProgress += "EOQ"; } return eodInProgress; } /** * find out if legacy eod stuff is running **/ public static boolean isEODBackgroundInProgress(Integer loc) { EODServer aServer = null; if((aServer = findInstance(loc)) == null) { return false; } else { return aServer.isEODBackgroundInProgress(); } } /** * find out if legacy eod stuff is running **/ public boolean isEODBackgroundInProgress() { logger.warn("This is a filler method that will check the system for any " + "running EOD processes that may have \"Hung\" up, and did not keep the server " + "from setting the in-progress flag to false.\nFor the time being, it returns false."); return false; } /** * find out if TAMSII EOD is running **/ public static boolean isEODInProgress(Integer loc) { EODServer aServer = findInstance(loc); if(aServer == null) { return false; } else { return aServer.isEODInProgress(); } } /** * find out if TAMSII EOD is running **/ public boolean isEODInProgress() { // logger.debug("isEODInProgress()"); return m_eodRunning; // || isEODBackgroundInProgress(); } /** * Close file handles and database connections, and destroy singleton **/ public void stopEOD() { m_eodStopped = true; } /** * Close file handles and database connections, and destroy singleton **/ public Hashtable finishEOD() { logger.debug("finishEOD()"); java.util.Date currSysDate = new java.util.Date(); skipBackup = Boolean.FALSE; if(m_eodStopped) { // add stopped log entry String eodStopMsg = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_STOP_MESSAGE, getLocale()); updateLog(TsoPrintFormat.format(eodStopMsg, LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currSysDate)); } else { // todo - this may no longer be necessary; talk to Lynn and Martha // thread checks every 5 minutes until EOD Monitor.COMM_IN_PROGRESS != "Y" while(getMonitorVO().getCommInProgress().booleanValue()) { try { logger.debug("Waiting on communications..."); Thread.currentThread().sleep(30000); // wait 5 minutes } catch(InterruptedException e) { logger.error("Error waiting on communications to complete: ", e); } // refresh the monitor object m_monitorVO = getEndOfDayMonitorVO(); } // update log with completion entry //"End of Day completed successfully " String eodCompleteMsg = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_COMPLETE_MESSAGE, getLocale()); logger.debug("EOD COMPLETE MESSAGE: " + eodCompleteMsg); updateLog(TsoPrintFormat.format(eodCompleteMsg, LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currSysDate)); // Clear all END_OF_DAY_MONITOR fields except LOC and NEW_DAY_STARTED_DAY clearMonitorTable(); // Write to REPORT_PRINT_LOG; set RUN_END_DATE = curr sys dt/tm if(m_reportPrintLogID != null) { FwoReportPrintLog printLogEntry = new FwoReportPrintLog(); printLogEntry.setId(m_reportPrintLogID); printLogEntry.setLOC(m_loc); printLogEntry.setRunEndDate(new java.sql.Timestamp(currSysDate.getTime())); printLogEntry.setPrintStatus(FwoReportPrintLog.PRINT_STATUS_COMPLETE); try { PrintLog.updatePrintLog(printLogEntry); } catch(FwoReportPrintLogUpdateException e) { logger.error("Error creating REPORT_PRINT_LOG record: ", e); } catch(FwoReportPrintLogException e) { logger.error("Error creating REPORT_PRINT_LOG record: ", e); } } } // Added code to check for 'Bin Label in Progress' value. If 'Bin Label in Progress' value // is 'Y' after completion of EOD tasks, set the value to 'N' try { if (BinLabelGeneratorUtil.isBinLabelInProgress(m_loc)) { logger.debug("Bin Label in progress"); BinLabelGeneratorUtil.updateBinLabelProgress(m_loc, TsoConstant.GENERIC_N); logger.debug("Updated Bin Label in progress to false ..."); } } catch(ApplicationException applicationException) { logger.error("Exception occured while resetting for bin label progress value: ", applicationException); } // reset restarted flag; why??? isRestarted = false; m_eodRunning = false; // return success Hashtable result = new Hashtable(); result.put(KEY_OUTCOME, OUTCOME_SUCCESS); return result; } /** * Return the cached monitor information from memory - new one if none cached **/ public EndOfDayMonitorVO getMonitorVO() { // logger.debug("getMonitorVO()"); if(m_monitorVO == null) { m_monitorVO = getEndOfDayMonitorVO(); } return m_monitorVO; } /** * Return the cached profile information from memory - new one if none cached **/ public EndOfDayProfileVO getProfileVO() { // logger.debug("getProfileVO()"); if(m_profileVO == null) { readProfileTable(); } return m_profileVO; } public void invalidateCacheEndOfDayProfileVO(){ m_profileVO = null; } public void invalidateCacheEndOfDayMonitorVO(){ m_monitorVO = null; } /** * return cached Locale from memory - new one if none cached **/ public Locale getLocale() { // logger.debug("getLocale()"); if(m_locale == null) { m_locale = new Locale(getStoreProfileVO().getRefLanguageCd().toLowerCase(), getStoreProfileVO().getRefCountryCd()); } return m_locale; } /** * Return a reference to the invoker **/ public AgiInvokeBusinessObject getInvoker() { return m_invoker; } /** * return the cached store profile from memory - new one if none cached **/ public StoreProfileVO getStoreProfileVO() { // logger.debug("getStoreProfileVO()"); if(m_storeProfileVO == null) { m_storeProfileVO = ApplicationContext.getInstance().getProfile(Profile.SERVER, m_loc.intValue()).getStoreProfile(); } return m_storeProfileVO; } public boolean isEODStopped() { return m_eodStopped; } /** * Update the task status **/ public Hashtable updateTaskStatus(Integer newTaskID, boolean updateLog, boolean currentTaskComplete) { logger.debug("updateTaskStatus(" + newTaskID + ", " + updateLog + ", " + currentTaskComplete + ")"); if(newTaskID != null) { convertWipFile(getEODTaskVO(newTaskID).getExecutionOrder().intValue()); } updateMonitorTable(newTaskID, updateLog, currentTaskComplete); return (Hashtable) null; } // Update the monitor table with the passed in task id private void updateMonitorTable(Integer newTaskID, boolean updateLog, boolean currentTaskComplete) { logger.debug("updateMonitorTable newTaskID = " + newTaskID + "; updateLog = " + updateLog); java.sql.Timestamp currSysDate = new java.sql.Timestamp((new java.util.Date()).getTime()); Integer currTaskID = getMonitorVO().getCurrentRefEODTaskID(); // EndOfDayTaskVO currTaskVO = getEODTaskVO(currTaskID); RefEODTaskVO currTaskVO = getEODTaskVO(currTaskID); java.sql.Timestamp currTaskStartDate = (Timestamp)getMonitorVO().getCurrentTaskStartDate(); // .getCURRENT_TASK_START_DATE(); //write to EODLOG.pf with log text + start dt/tm and end dt/tm if(updateLog && currTaskID != null && currTaskVO != null && !currTaskID.equals(newTaskID)) { logger.debug("update the log file for task " + currTaskID); if(currentTaskComplete) { // show that task completed logger.debug(currTaskVO.getId() + " completed."); updateLog(TsoPrintFormat.format(currTaskVO.getLogText(), LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currTaskStartDate) + " - " + DT_FORMAT.format(currSysDate)); } else { // show that task failed logger.error("Failure message: " + TsoPrintFormat.format(currTaskVO.getLogText(), LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currTaskStartDate) + " - " + ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_FAIL_MESSAGE, getLocale())); updateLog(TsoPrintFormat.format(currTaskVO.getLogText(), LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currTaskStartDate) + " - " + ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_FAIL_MESSAGE, getLocale())); } } // Connect to monitor table and update record with new task logger.debug("update the monitor table with the new task id: " + newTaskID); Connection conn = null; Statement stmt = null; try { FwoQueryBuffer qBuffer = new FwoQueryBuffer(); qBuffer.append("UPDATE ").append(Sch_Tables.END_OF_DAY_MONITOR).append(" SET "); // update the current task start if a new task is given if(newTaskID != null) { qBuffer.append(Sch_EndOfDayMonitor.CURRENT_REF_EOD_TASK_ID).append(" = ").append(newTaskID).append(", "); qBuffer.append(Sch_EndOfDayMonitor.CURRENT_TASK_START_DATE).append(" = '"); qBuffer.append(currSysDate).append("'"); } else { qBuffer.append(Sch_EndOfDayMonitor.CURRENT_REF_EOD_TASK_ID).append(" = NULL, "); qBuffer.append(Sch_EndOfDayMonitor.CURRENT_TASK_START_DATE).append(" = NULL"); } // only update the last completed task if current task successfully completed logger.debug("update the current task if: currTaskID != null && !currTaskID.equals(newTaskID) && currentTaskComplete):"); logger.debug(currTaskID + " != null " + "&& !" + currTaskID + ".equals(" + newTaskID + ") && " + currentTaskComplete + ")"); logger.debug("value = " + (currTaskID != null && !currTaskID.equals(newTaskID) && currentTaskComplete)); if(currTaskID != null && !currTaskID.equals(newTaskID) && currentTaskComplete) { qBuffer.append(", ").append(Sch_EndOfDayMonitor.LAST_COMPLETED_REF_EOD_TASK_ID).append(" = ").append(currTaskID); qBuffer.append(", ").append(Sch_EndOfDayMonitor.LAST_TASK_COMPLETED_DATE).append(" = '"); qBuffer.append(currSysDate).append("'"); } qBuffer.append("\nWHERE ").append(Sch_EndOfDayMonitor.LOC).append(" = ").append(m_loc); logger.info("UPDATE TASK SQL: " + qBuffer.toString()); // logger.debug("monitor update with new task sql = " + qBuffer.getSQL()); conn = ServerUtil.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate(qBuffer.getSQL()); } catch(SQLException e) { logger.error("Error updating monitor task status: ", e); } finally { JDBCUtil.closeStatement(stmt); if(conn != null) { ServerUtil.releaseConnection(conn); } // reload the monitorvo m_monitorVO = getEndOfDayMonitorVO(); } } // Clear certain monitor table fields and keep the rest of them unchanged private void clearMonitorTable() { // logger.debug("clearMonitorTable"); // Connect to monitor table and reset some fields Connection conn = null; Statement stmt = null; try { FwoQueryBuffer qBuffer = new FwoQueryBuffer(); qBuffer.append("UPDATE ").append(Sch_Tables.END_OF_DAY_MONITOR).append(" SET "); qBuffer.append(Sch_EndOfDayMonitor.NEW_DAY_STARTED_DATE).append(" = '"); qBuffer.append(new Timestamp(System.currentTimeMillis())).append("'"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.EOD_BACKUP_FAILED).append(" = 'N'"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_BIN_LABEL_PRINT).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_BRANCH_STORE_INVOICE_POSTING).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_BRANCH_STORE_INVOICE_PROCESSING).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_BRANCH_STORE_TRANSMISSION_FILES).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_EMPLOYEE_TIME_REVIEW).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_FINALIZING_ORDERS).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_JOEI_ORDER_TRANSMISSION).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_MAJOR_ACCT_PRICING_CORRECTIONS).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_NAPA_ORDER_CREATION).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_REPORT_SELECTION_REVIEW).append(" = NULL"); //Added for Compressed DVD Project qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_CDVD_PROCESSING).append(" = NULL"); qBuffer.append(", ").append(Sch_EndOfDayMonitor.PWD_OF_DAY_EMPLOYEE_ID).append(" = NULL"); //Added for new EOD implementation qBuffer.append(", ").append(Sch_EndOfDayMonitor.SKIP_REVIEW_CHANGE_TRANSACTION).append(" = NULL"); qBuffer.append(" WHERE ").append(Sch_EndOfDayMonitor.LOC).append(" = ").append(m_loc); logger.info("monitor clear sql = " + qBuffer.getSQL()); conn = ServerUtil.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate(qBuffer.getSQL()); } catch(SQLException e) { logger.error(e.toString(), e); } finally { JDBCUtil.closeStatement(stmt); if(conn != null) { ServerUtil.releaseConnection(conn); } } } // Update the .pf log fle public void updateLog(String logEntry) { // logger.debug("updateLog entry = " + logEntry); if(m_log == null) { cacheLogFile(); } if(m_log != null) { // append log entry to in-memory cache m_log.append(logEntry + "\n"); } // Append to file if(m_logFile != null) { try { TsoFileWriter.appendFile(m_logFile.getParent(), m_logFile.getName(), logEntry); } catch(IOException ioe) { logger.error("Error appending to EODLOG: ", ioe); } } } public static String getLog(Integer loc) { EODServer aServer = findInstance(loc); if(aServer == null) { return ""; } else { return aServer.getLog(); } } // Return the cached log from memory // Check age of cache, and retrieve if dated before current date public String getLog() { if(m_log != null) { return m_log.toString(); } else { return ""; } } // Start an EndOfDay task without input public Hashtable startEODTask(RefEODTaskVO taskVO) { logger.debug("startEODTask " + taskVO.getId()+ " - " + taskVO.getLogText()); // logger.debug("my m_loc = " + m_loc); Hashtable result = null; if(taskVO == null) { result = EODServer.createError(ERROR_MISSING_EOD_TASK); } else { TsoTransmit.setRetransmit(isRestarted); // execute the new task try { EndOfDay eodObject = (EndOfDay)taskVO.getTaskClass().newInstance(); Hashtable eodParams = new Hashtable(); eodParams.put(KEY_RESTART, new Boolean(isRestarted)); eodParams.put(KEY_TRIGGER, isManuallyTriggered ? TRIGGER_MANUAL : TRIGGER_AUTOMATIC); eodParams.put(KEY_EOD_TYPE, getEODType()); eodParams.put(KEY_MONITOR, getMonitorVO()); eodParams.put(TsoConstant.KEY_EMPLOYEE_ID, m_manualEmpID); eodParams.put(TsoConstant.KEY_IP_ADDRESS, m_ipAddress); eodParams.put(TsoConstant.KEY_LOC, m_loc); eodParams.put(TsoConstant.KEY_LOCALE, currentLocale); eodParams.put(EndOfDay.SKIP_BACKUP, skipBackup); logger.debug("Executing startEndOfDay Process for object with params - " + eodParams.toString()); result = eodObject.startEndOfDay(eodParams); } catch(ClassNotFoundException cnfe) { // print out error to log result = EODServer.createError(ERROR_UNKNOWN_EOD_TASK); logger.error("Class Error running EOD task: ", cnfe); } catch(InstantiationException e) { // print out error to log result = EODServer.createError(ERROR_EXECUTION_FAILED); logger.error("Error running EOD task: ", e); } catch(IllegalAccessException e) { // print out error to log result = EODServer.createError(ERROR_EXECUTION_FAILED); logger.error("Error running EOD task: ", e); } } if(result == null || result.get(KEY_OUTCOME) == null) { result = EODServer.createError(ERROR_OUTCOME_NOT_SPECIFIED); } if(taskVO != null && taskVO.getTaskObjectName().endsWith(TsoConstant.END_OF_DAY_UNATTENDED_BACKUP)) { // ran unatteneded backup. must stop EOD if it failed. logger.debug("got the backup results: " + (result == null ? "null" : result.toString())); boolean backupSuccess = false; if(result != null) { if(result.containsKey(EndOfDay.KEY_OUTCOME)) { if(result.get(EndOfDay.KEY_OUTCOME).equals(EndOfDay.OUTCOME_SUCCESS)) { backupSuccess = true; } } } if(!backupSuccess) { logger.debug("Unatteneded backup failed. Must stop EOD."); result = EODServer.createError(EndOfDay.ERROR_EOD_BACKUP_FAILED); } } return result; } /** * This method converts the ST*.WIP to ST*.WIP.copy file if executionOrder is less than * UNATTENDED_CATALOG_UPDATE task's executionOrder else set to ST*.WIP. * @param executionOrder of the task */ private void convertWipFile(int executionOrder) { FileStateManager fileStateManager = FileStateManager.getInstance(); if (!isoriginalFileRenamedToCopyFile && executionOrder < TsoConstant.END_OF_DAY_UNATTENDED_CATALOG_UPDATE_ORDER ) { isoriginalFileRenamedToCopyFile = true; if (fileStateManager.getWipOriginalFile().exists()) { fileStateManager.getWipOriginalFile().renameTo( fileStateManager.getWipCopyFile()); } fileStateManager.setWipFile(fileStateManager.getWipCopyFile()); } else if(executionOrder >= TsoConstant.END_OF_DAY_UNATTENDED_CATALOG_UPDATE_ORDER) { if (fileStateManager.getWipCopyFile().exists()) { fileStateManager.getWipCopyFile().renameTo( fileStateManager.getWipOriginalFile()); } fileStateManager.setWipFile(fileStateManager.getWipOriginalFile()); } } public static Hashtable createError(String errorText) { // logger.debug("createError error = " + errorText); Hashtable result = new Hashtable(); result.put(KEY_OUTCOME, OUTCOME_FAILURE); result.put(KEY_ERROR_TEXT, errorText); return result; } public Hashtable startEndOfDay(Hashtable params) { // currently does nothing return null; } public RefEODTaskVO getEODTaskVO(Integer taskId) { if(m_eodTasks == null){ readTaskTable(); } Iterator i = m_eodTasks.iterator(); while (i.hasNext()) { RefEODTaskVO task = (RefEODTaskVO) i.next(); if (task.getId().equals(taskId)) { return task; } } return null; } private Timestamp getUpdateTimestamp() { Integer userID = m_manualEmpID; String currIpAddress = TamsMisc.getIPAddress(); if(userID == null) { userID = new Integer(0); } if(currIpAddress == null) { currIpAddress = ""; } return ServerUtil.getTransactionTimestamp(m_loc, userID, currIpAddress, ""); } public Hashtable runFromServer(ArrayList taskList) { logger.debug("runFromServer()"); boolean taskCompleted = true; boolean updateTaskLog = true; // EndOfDayTaskVO task = null; RefEODTaskVO task = null; Hashtable results; final ArrayList skipTasks = new ArrayList(); skipTasks.add(49); // Process Received Communications skipTasks.add(81); // Inventory Status Report skipTasks.add(74); // RADS Discrepancy Report skipTasks.add(54); // Create Start of Day Messages skipTasks.add(82); // Run EOD Scripts skipTasks.add(57); // Run Off Line Tasks skipTasks.add(50); // Unattended Backup skipTasks.add(58); // Multi Store Purge skipTasks.add(59); // Database Log Trim skipTasks.add(62); // TAMS Software Update skipTasks.add(63); // Convert and Post Sales History skipTasks.add(75); // Generate and Print Bin Labels skipTasks.add(52); // Automatic Min/Max Review boolean isNewEODFlagInUse = RefStoreConfigurationUtil.isUseNewEODEnabled(); if(isNewEODFlagInUse){ skipTasks.add(68); // Catalog Update skipTasks.add(37); // Update Inventory from DVD } logger.warn("Is Restarted EOD: " + isRestarted + " EOD TriggerType : "+isManuallyTriggered); for(int i = 0; i < taskList.size(); i++) { // updateTaskLog = true; task = (RefEODTaskVO)taskList.get(i); //TAMSIIS-1545 skip backup and offline tasks when skip backup us selected if (getSkipBackup().booleanValue() && skipTasks.contains(task.getId())) { logger.debug("Skip backup and offline tasks when skip backup is selected >>>>>>>: " + task.getId()); continue; } updateTaskStatus(task.getId(), updateTaskLog, taskCompleted); Hashtable taskResults = null; m_profileVO = getProfileVO(); if(task.getId().equals(PROCESS_TRANSIN_TASK) && m_profileVO != null && m_profileVO.getRebootBeforeTransinProcessing() != null && m_profileVO.getRebootBeforeTransinProcessing().booleanValue() && rebootServer("ProcessTransin")){ java.util.Date currSysDate = new java.util.Date(); String eodStopMsg = ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText(ResourceBundleReader.UI, PROPERTY_EOD_STOP_MESSAGE, getLocale()); updateLog(TsoPrintFormat.format(eodStopMsg, LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(currSysDate)); taskResults = EODServer.createError(ERROR_OUTCOME_NOT_SPECIFIED); return taskResults; } convertWipFile(task.getExecutionOrder().intValue()); Hashtable taskParams = new Hashtable(); taskParams.put(EndOfDay.KEY_RESTART, new Boolean(isRestarted)); taskParams.put(EndOfDay.KEY_SINGLE_TASK, task); taskParams.put(EndOfDay.KEY_TRIGGER, isManuallyTriggered ? EndOfDay.TRIGGER_MANUAL : EndOfDay.TRIGGER_AUTOMATIC); taskParams.put(EndOfDay.KEY_EOD_TYPE, getEODType()); taskParams.put(TsoConstant.KEY_EMPLOYEE_ID, m_manualEmpID); taskParams.put(TsoConstant.KEY_IP_ADDRESS, m_ipAddress); taskParams.put(TsoConstant.KEY_LOC, m_loc); // if form task, then launch client-side form //if(task.isFormTask().booleanValue() || task.isOffLineEODTask().booleanValue()) { if(task.isOffLineEODTask().booleanValue()) { // skip it. form should have handled it. logger.debug("form tasks (" + task.getTaskObjectName() + ") can not run from EODServer"); } else if (task.isFormTask().booleanValue()) { logger.error("Error EOD failed while running form tasks"); stopEOD(); updateTaskLog = true; taskCompleted = false; break; } else if(task.isInvokedTask().booleanValue()) { try { logger.debug("invoked task name = " + task.getTaskObjectName()); taskResults = (Hashtable)SilverStreamExceptionHelper.invokeBusinessObject(m_invoker, task.getTaskObjectName(), taskParams); } catch(ApplicationException e) { logger.error("Error launching EOD server-invoked task: "+e.toString(), e); } catch(Exception e) { logger.error("Error launching EOD server-invoked task: "+e.toString(), e); } if(taskResults == null || taskResults.get(KEY_OUTCOME) == null) { taskResults = EODServer.createError(ERROR_OUTCOME_NOT_SPECIFIED); } } else if(task.isEODTask().booleanValue()) { try { // if eod task, then invoked the single task action logger.warn("run task: " + task.getTaskObjectName() + " locally"); taskResults = startEODTask(task); } catch(Exception e) { logger.error("Error executing eod task: "+e.toString(), e); } if(taskResults == null || taskResults.get(KEY_OUTCOME) == null) { taskResults = EODServer.createError(ERROR_OUTCOME_NOT_SPECIFIED); } } else { logger.error("We should never come here."); updateTaskLog = false; taskResults = EODServer.createError(ERROR_UNKNOWN_EOD_TASK); } //at this point, taskResults should not be null. EODServer uses this info to determine what to do next. if(taskResults.get(EndOfDay.KEY_OUTCOME).equals(EndOfDay.OUTCOME_FAILURE)) { // don't stop at error, but add to error log logger.error("EOD Task Failed: Task Name = " + task.getLogText() + "\n Error = " + taskResults.get(EndOfDay.KEY_ERROR_TEXT)); // have to stop EOD if this was offline tasks if(task.getTaskObjectName().endsWith(TsoConstant.END_OF_DAY_OFFLINE_TASKS)) { logger.debug("offline tasks failed"); updateTaskLog = true; taskCompleted = true; updateLog(TsoPrintFormat.format(task.getLogText(), LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format((Timestamp)getMonitorVO().getCurrentTaskStartDate()) + " - " + ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText( ResourceBundleReader.UI, PROPERTY_EOD_OFFLINE_TASK_FAILED_MESSAGE, getLocale())); break; } if(task.isCritical().booleanValue()) { logger.error("CRITICAL TASK FAILED; END OF DAY HAS BEEN STOPPED, updateTaskLog = " + updateTaskLog); // stop eod and break task loop stopEOD(); taskCompleted = false; break; } } else { // success logger.info("EOD Task Succeeded: Task Name = " + task.getLogText()); } // update the log regardless of the outcome unless the update log flag is false if(taskResults.get(EndOfDay.KEY_UPDATE_LOG) != null && taskResults.get(EndOfDay.KEY_UPDATE_LOG).equals(Boolean.FALSE)) { updateTaskLog = false; } else { updateTaskLog = true; } taskCompleted = true; taskResults = null; } logger.debug("update the last task?------------>"); if (task != null && task.getId() != null) // updateTaskStatus(task.getId(), updateTaskLog, taskCompleted); updateTaskStatus(null, updateTaskLog, taskCompleted); // logger.info("********Prepare parameters for the invoked business object finish process"); finishEOD(); m_eodRunning = false; results = new Hashtable(); results.put(EndOfDay.KEY_OUTCOME, EndOfDay.OUTCOME_SUCCESS); return results; } /* private SBReport getReportBean() { if(sbReport == null) { JNDILocator jndiLocator = JNDILocator.getInstance(); SBReportHome sbReportBeanHome = (SBReportHome)jndiLocator.getEJBHome( SBReportHome.class, JNDILocatorConstants.SBREPORT_RMISTR); try { sbReport = sbReportBeanHome.create(); return sbReport; } catch (RemoteException e) { EJBRemoteExceptionHelper.HandleRemoteException(e); } catch (CreateException e) { logger.error(e.toString(), e); throw new ApplicationRuntimeException(e); } } return sbReport; } */ public boolean isRestarted() { return this.isRestarted; } // Bug 27132 added new method public boolean getSendToMcGladrey(String rpNumber) { Connection conn = null; Statement stmt = null; ResultSet rs = null; String sendToMcgladrey = null; try{ conn = ServerUtil.getConnection(); stmt = conn.createStatement(); rs=stmt.executeQuery("SELECT REF_REPORT.SEND_TO_MCGLADREY FROM REF_REPORT WHERE REPORT_NUMBER = '"+rpNumber+"'"); if(rs.next()){ sendToMcgladrey = rs.getString("SEND_TO_MCGLADREY"); } else{ sendToMcgladrey = "0"; } } catch(SQLException e) { logger.error(e.toString(), e); } finally { if(rs != null){ JDBCUtil.closeResultSet(rs); } if(stmt != null){ JDBCUtil.closeStatement(stmt); } if(conn != null) { ServerUtil.releaseConnection(conn); } } int send = Integer.parseInt(sendToMcgladrey); if(send == 1){ return true; } else if((send == 2)&&(getMonitorVO().getEndOfMonth().booleanValue())){ return true; } return false; } /** * @return the skipBackup */ public Boolean getSkipBackup() { return skipBackup; } /** * @param skipBackup the skipBackup to set */ public void setSkipBackup(Boolean skipBackup) { this.skipBackup = skipBackup; } public boolean rebootServer(String processName) { boolean rebootSuccess = false; RuntimeMXBean rumTimeBean = ManagementFactory.getRuntimeMXBean(); long upTime = rumTimeBean.getUptime(); logger.warn("Reboot Before " + processName + " flag is ON and uptime is : " + upTime / 60000 + "min"); if (upTime > ONE_HOUR) { ProcessControlStatusVO status = new ProcessControlStatusVO(); status = ApplicationContext.getInstance().getProcessControlDAO().shutdownSystem(false, true, m_loc); if (status != null && status.isSuccess().booleanValue()) { logger.warn("EOD Reboot status : " + status.isSuccess().booleanValue()); ShutdownMessageVO message = new ShutdownMessageVO(); message.setMessageNumber(new Integer(1636)); message.setSessionID("SERVER"); ApplicationContext.getInstance().getApplicationMessageDAO().sendMessageToAll(message); rebootSuccess = true; } } else if (upTime < 90000) { try { Thread.sleep(60000); logger.warn("EODServer thread sleep for 60 sec"); }catch (InterruptedException e) { logger.error("got the InterruptedException...."); } } return rebootSuccess; } /** * This method is used to trigger the passed task via API */ public Hashtable runSingleTaskViaAPI(HashMap params) { logger.warn("runSingleTaskViaAPI()"); RefEODTaskVO task = null; boolean taskCompleted = true; boolean updateTaskLog = true; Hashtable results; if(params.containsKey(EndOfDay.KEY_REF_EOD_TASK_VO)){ task = (RefEODTaskVO) params.get(EndOfDay.KEY_REF_EOD_TASK_VO); } if(params.containsKey(TsoConstant.KEY_EMPLOYEE_ID)){ m_manualEmpID = (Integer) params.get(TsoConstant.KEY_EMPLOYEE_ID); } if(params.containsKey(TsoConstant.KEY_IP_ADDRESS)){ m_ipAddress = (String) params.get(TsoConstant.KEY_IP_ADDRESS); } if(params.containsKey(TsoConstant.KEY_INVOKER)){ m_invoker = (AgiInvokeBusinessObject) params.get(TsoConstant.KEY_INVOKER); } if(params.containsKey(TsoConstant.KEY_LOCALE)){ currentLocale = (Locale) params.get(TsoConstant.KEY_LOCALE); } if(params.containsKey(TsoConstant.KEY_LOC)){ m_loc = (Integer) params.get(TsoConstant.KEY_LOC); } // the below method is to check if the record with the task id exist in the DB or not. if exist then we update the record else insert the record. if (task != null && !isStatusRestarted(task.getId())) { if (isEntryAlreadyExist(task)) { updateEODTriggerApi(task, RefEODApiStatus.STARTED, TsoConstant.GENERIC_Y); } else { insertIntoEODTriggerApi(task, RefEODApiStatus.STARTED); } } if(task != null && m_manualEmpID != null && m_ipAddress != null && m_invoker != null && currentLocale != null && m_loc != null){ updateTaskStatus(task.getId(),updateTaskLog,taskCompleted); convertWipFile(task.getExecutionOrder()); Hashtable taskParams = new Hashtable(); taskParams.put(EndOfDay.KEY_RESTART, new Boolean(isRestarted)); taskParams.put(EndOfDay.KEY_SINGLE_TASK, task); taskParams.put(EndOfDay.KEY_TRIGGER, EndOfDay.TRIGGER_MANUAL ); taskParams.put(EndOfDay.KEY_EOD_TYPE, getEODType()); taskParams.put(TsoConstant.KEY_EMPLOYEE_ID, m_manualEmpID); taskParams.put(TsoConstant.KEY_IP_ADDRESS, m_ipAddress); taskParams.put(TsoConstant.KEY_LOC, m_loc); Hashtable taskResults = null; // if form task, then launch client-side form if(Boolean.TRUE.equals(task.isOffLineEODTask())) { // skip it. form should have handled it. logger.warn("form tasks (" + task.getTaskObjectName() + ") can not run from EODServer"); updateEODTriggerApi(task,RefEODApiStatus.ERROR,""); } else if(Boolean.TRUE.equals(task.isInvokedTask())) { try { logger.warn("invoked task name = " + task.getTaskObjectName()); taskResults = (Hashtable)SilverStreamExceptionHelper.invokeBusinessObject(m_invoker, task.getTaskObjectName(), taskParams); } catch(Exception e) { logger.error("Error launching EOD server-invoked task: "+e.toString(), e); } if(taskResults == null || taskResults.get(KEY_OUTCOME) == null) { taskResults = EODServer.createError(ERROR_OUTCOME_NOT_SPECIFIED); logger.warn("Inside error status for the invoked task : Task details :"+task.getTaskObjectName()); updateEODTriggerApi(task,RefEODApiStatus.ERROR,TsoConstant.GENERIC_Y); } } else if(Boolean.TRUE.equals(task.isEODTask())) { try { // if eod task, then invoked the single task action logger.warn("run task: " + task.getTaskObjectName() + " locally"); taskResults = startEODTask(task); } catch(Exception e) { logger.error("Error executing eod task: "+e.toString(), e); } if(taskResults == null || taskResults.get(KEY_OUTCOME) == null) { taskResults = EODServer.createError(ERROR_OUTCOME_NOT_SPECIFIED); logger.warn("Inside error status for the Eod task : Task details :"+task.getTaskObjectName()); updateEODTriggerApi(task,RefEODApiStatus.ERROR,TsoConstant.GENERIC_Y); } } else { logger.error("We should never come here."); updateTaskLog = false; taskResults = EODServer.createError(ERROR_UNKNOWN_EOD_TASK); logger.warn("Inside error status in the else part : Task details :"+task.getTaskObjectName()); updateEODTriggerApi(task, RefEODApiStatus.ERROR,TsoConstant.GENERIC_Y); } //at this point, taskResults should not be null. EODServer uses this info to determine what to do next. if(taskResults.get(EndOfDay.KEY_OUTCOME).equals(EndOfDay.OUTCOME_FAILURE)) { results = new Hashtable(); // don't stop at error, but add to error log logger.error("EOD Task Failed: Task Name = " + task.getLogText() + "\n Error = " + taskResults.get(EndOfDay.KEY_ERROR_TEXT)); // have to stop EOD if this was offline tasks if(task.getTaskObjectName().endsWith(TsoConstant.END_OF_DAY_OFFLINE_TASKS)) { logger.warn("offline tasks failed"); updateLog(TsoPrintFormat.format(task.getLogText(), LOG_TEXT_MAX_WIDTH, TsoPrintFormat.LEFT_JUSTIFIED) + LOG_DIVIDER + DT_FORMAT.format(getMonitorVO().getCurrentTaskStartDate()) + " - " + ApplicationContext.getInstance().getResourceBundleReader().getLocalizedText( ResourceBundleReader.UI, PROPERTY_EOD_OFFLINE_TASK_FAILED_MESSAGE, getLocale())); updateEODTriggerApi(task,RefEODApiStatus.CRITICAL_TASK_FAILED,TsoConstant.GENERIC_Y); results.put(EndOfDay.KEY_IS_LAST_EOD_TASK,"TRUE"); return results; } if(Boolean.TRUE.equals(task.isCritical())) { logger.error("CRITICAL TASK FAILED; END OF DAY HAS BEEN STOPPED, updateTaskLog = "+updateTaskLog); updateEODTriggerApi(task,RefEODApiStatus.CRITICAL_TASK_FAILED,TsoConstant.GENERIC_Y); stopEOD(); taskCompleted = false; results.put(EndOfDay.KEY_IS_LAST_EOD_TASK,"TRUE"); updateTaskStatus(null,updateTaskLog,taskCompleted); } else { logger.warn("Non Critical Task Failed: Task details :"+task.getTaskObjectName()); updateEODTriggerApi(task,RefEODApiStatus.ERROR,TsoConstant.GENERIC_Y); } results.put(EndOfDay.KEY_OUTCOME, EndOfDay.OUTCOME_FAILURE); return results; } else { // success logger.warn("EOD Task Succeeded: Task Name = " + task.getLogText()); } if(task.getTaskObjectName().endsWith(TsoConstant.END_OF_DAY_OFFLINE_TASKS)) { if(isOfflineNonCriticalTaskFailed()){ updateEODTriggerApi(task,RefEODApiStatus.ERROR,TsoConstant.GENERIC_Y); } else { updateEODTriggerApi(task,RefEODApiStatus.COMPLETED,TsoConstant.GENERIC_Y); } } else { updateEODTriggerApi(task,RefEODApiStatus.COMPLETED,TsoConstant.GENERIC_Y); } } else { logger.warn("Passed Parameters having null value task => : "+task+" m_manualEmpID => "+m_manualEmpID+ " m_ipAddress => "+m_ipAddress +" m_invoker => "+m_invoker+" currentLocale => "+currentLocale+" m_loc => "+m_loc); } results = new Hashtable(); results.put(EndOfDay.KEY_OUTCOME, EndOfDay.OUTCOME_SUCCESS); return results; } /** * Using this method data will be inserted into the EOD_API_TRIGGER_STATUS. */ public void insertIntoEODTriggerApi(RefEODTaskVO refEODTaskVO, String status){ String insertSqlQuery = "INSERT INTO "+ Sch_Tables.EOD_API_TRIGGER_STATUS + "( " + Sch_EodApiTriggerStatus.REF_EOD_TASK_ID + ", " + Sch_EodApiTriggerStatus.LOC + ", " + Sch_EodApiTriggerStatus.EXECUTION_ORDER_ID + ", " + Sch_EodApiTriggerStatus.TASK_NAME + ", " + Sch_EodApiTriggerStatus.STATUS +"," + Sch_EodApiTriggerStatus.START_DATE+"," + Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+")" + " VALUES (?, ?, ?, ?, ?,?,?)"; Connection connection = null; PreparedStatement statement = null; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(insertSqlQuery); statement.setObject(1, refEODTaskVO.getId()); statement.setObject(2, refEODTaskVO.getLoc()); statement.setObject(3, refEODTaskVO.getExecutionOrder()); statement.setObject(4, refEODTaskVO.getLogText()); statement.setObject(5, status); statement.setTimestamp(6, new Timestamp(Calendar.getInstance().getTimeInMillis())); statement.setString(7, TsoConstant.GENERIC_Y); statement.execute(); } catch (SQLException e) { logger.error("Unable to insert value into the database"+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } } /** * This method will use to update the EOD_API_TRIGGER_STATUS table and following columns will be updated STATUS, START_DATE, END_DATE * EOD_TRIGGERED_TODAY. */ public void updateEODTriggerApi(RefEODTaskVO refEODTaskVO, String status, String today) { String updateSqlQuery = "UPDATE "+ Sch_Tables.EOD_API_TRIGGER_STATUS + " SET "+ Sch_EodApiTriggerStatus.STATUS +" =?, "+ Sch_EodApiTriggerStatus.START_DATE+" =?, "+ Sch_EodApiTriggerStatus.END_DATE+" = NULL, "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+"=? WHERE "+ Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =?"; String updateSqlQuery2 = "UPDATE "+ Sch_Tables.EOD_API_TRIGGER_STATUS + " SET "+ Sch_EodApiTriggerStatus.STATUS +" =?, "+ Sch_EodApiTriggerStatus.END_DATE+" =?, "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+"=? WHERE "+ Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =?"; String updateQuery = ((status.equalsIgnoreCase(RefEODApiStatus.STARTED)) || (status.equalsIgnoreCase(RefEODApiStatus.SERVER_RESTARTED))) ? updateSqlQuery : updateSqlQuery2; Connection con = null; PreparedStatement statement = null; try { con = ServerUtil.getConnection(); statement = con.prepareStatement(updateQuery); statement.setString(1,status); statement.setTimestamp(2, new Timestamp(Calendar.getInstance().getTimeInMillis())); statement.setString(3,today); statement.setInt(4, refEODTaskVO.getId()); statement.executeUpdate(); } catch (SQLException e) { logger.error("Unable to update value in the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(con); } } /** * Using this method data will be updated in the EOD_API_TRIGGER_STATUS table from EOD_TRIGGERED_TODAY column as N */ public void updateEODTriggerApiTodayStatus() { String updateSqlQuery = "UPDATE "+ Sch_Tables.EOD_API_TRIGGER_STATUS + " SET "+ Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY +" =?"; Connection con = null; PreparedStatement statement = null; try { con = ServerUtil.getConnection(); statement = con.prepareStatement(updateSqlQuery); statement.setString(1,TsoConstant.GENERIC_N); statement.executeUpdate(); } catch (SQLException e) { logger.error("Unable to update value in the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(con); } } /** * In this method we will check for the entry is already available in EOD_API_TRIGGER_STATUS this table or not. * And return the boolean value. */ public boolean isEntryAlreadyExist(RefEODTaskVO taskVO){ String selectSqlQuery = "SELECT * FROM "+ Sch_Tables.EOD_API_TRIGGER_STATUS + " WHERE "+ Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; boolean flag = false; try { conn = ServerUtil.getConnection(); stmt = conn.prepareStatement(selectSqlQuery); stmt.setInt(1,taskVO.getId()); rs = stmt.executeQuery(); while(rs.next()) { flag = true; } } catch (SQLException e) { logger.error("Unable to fetch value from the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(stmt); ServerUtil.releaseConnection(conn); } return flag; } /** * This method will return the boolean value. * Here we will check for the values from the EOD_API_TRIGGER_STATUS table where END_DATE not equal to null. * And EOD_TRIGGERED_TODAY equals to Y. */ public static boolean isTaskAlreadyExecutedForTheDay(RefEODTaskVO refEODTaskVO){ String sqlQuery = "SELECT "+ Sch_EodApiTriggerStatus.END_DATE+", "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+" FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS + " WHERE "+ Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean isTaskAlreadyExecuted = false; try{ connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, refEODTaskVO.getId()); resultSet = statement.executeQuery(); while(resultSet.next()){ String status = resultSet.getString(Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY); Timestamp timestamp = resultSet.getTimestamp(Sch_EodApiTriggerStatus.END_DATE); if(timestamp != null && status.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ isTaskAlreadyExecuted = true; } } } catch (SQLException e) { logger.error("Unable to fetch value from the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isTaskAlreadyExecuted; } /** * This method will return the String as per the STATUS from the EOD_API_TRIGGER_STATUS. * As per the following conditions it will return the String * 1. DATE_MISMATCH - START_DATE not equals to CURRENT_DATE & EOD_TRIGGERED_TODAY equals to NULL or N * 2. STARTED - STATUS equals to STARTED and EOD_TRIGGERED_TODAY equals to Y * 3. SERVER_RESTARTED - STATUS equals to SERVER_RESTARTED and EOD_TRIGGERED_TODAY equals to Y * 4. COMPLETED - STATUS equals to COMPLETED and EOD_TRIGGERED_TODAY equals to Y * 5. ERROR - STATUS equals to ERROR and EOD_TRIGGERED_TODAY equals to Y * 6. CRITICAL_TASK_FAILED - STATUS equals to CRITICAL_TASK_FAILED and EOD_TRIGGERED_TODAY equals to Y * 7. NOT_TRIGGERED_TODAY - START_DATE equals to CURRENT_DATE & EOD_TRIGGERED_TODAY equals to N and STATUS equals to * COMPLETED or ERROR * 8. Otherwise, it will return NULL */ public static String checkPreviousTaskStatus(Integer id){ String sqlQuery = "SELECT "+ Sch_EodApiTriggerStatus.STATUS+", "+ Sch_EodApiTriggerStatus.START_DATE+", "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY +" FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS + " WHERE " + Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; String taskStatus = null; try{ connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, id); resultSet = statement.executeQuery(); while(resultSet.next()){ Timestamp timestamp = resultSet.getTimestamp(Sch_EodApiTriggerStatus.START_DATE); String todayFlag = resultSet.getString(Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY); String status = resultSet.getString(Sch_EodApiTriggerStatus.STATUS); if(timestamp != null){ java.sql.Date dateFromTimeStamp = new java.sql.Date(timestamp.getTime()); String executionDate = String.valueOf(dateFromTimeStamp); String currentDate = String.valueOf(new java.sql.Date(new java.util.Date().getTime())); if(executionDate.equalsIgnoreCase(currentDate) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_N) && status != null && (status.equalsIgnoreCase(RefEODApiStatus.COMPLETED) || status.equalsIgnoreCase(RefEODApiStatus.ERROR))){ return RefEODApiStatus.NOT_TRIGGERED_TODAY; } if(!executionDate.equalsIgnoreCase(currentDate) && (todayFlag == null || todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_N))){ return RefEODApiStatus.DATE_MISMATCH; } } if(status != null){ if(status.equalsIgnoreCase(RefEODApiStatus.STARTED) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ return RefEODApiStatus.STARTED; } if(status.equalsIgnoreCase(RefEODApiStatus.SERVER_RESTARTED) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ return RefEODApiStatus.SERVER_RESTARTED; } if(status.equalsIgnoreCase(RefEODApiStatus.COMPLETED) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ return RefEODApiStatus.COMPLETED; } if(status.equalsIgnoreCase(RefEODApiStatus.ERROR) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ return RefEODApiStatus.ERROR; } if(status.equalsIgnoreCase(RefEODApiStatus.CRITICAL_TASK_FAILED) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ return RefEODApiStatus.CRITICAL_TASK_FAILED; } } } } catch (SQLException e) { logger.error("Unable to fetch the value from database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return taskStatus; } /** * This method will return the boolean value. * It will check for the values from the EOD_API_TRIGGER_STATUS table where START_DATE not equal to null, * END_DATE equals to null and STATUS equals to Started or Restarted if all conditions are true then it will return true otherwise * it will return false. **/ public static boolean isCurrentTaskRunning(Integer taskId){ String sqlQuery = "SELECT "+Sch_EodApiTriggerStatus.START_DATE+" , "+Sch_EodApiTriggerStatus.END_DATE+" , "+Sch_EodApiTriggerStatus.STATUS +" , "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+" FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS +" WHERE "+Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean isCurrentTaskRunning = false; try{ connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, taskId); resultSet = statement.executeQuery(); if(resultSet.next()){ Timestamp startDate = resultSet.getTimestamp(Sch_EodApiTriggerStatus.START_DATE); Timestamp endDate = resultSet.getTimestamp(Sch_EodApiTriggerStatus.END_DATE); String status = resultSet.getString(Sch_EodApiTriggerStatus.STATUS); String triggeredTodayFlag = resultSet.getString(Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY); if(startDate != null && endDate == null && TsoConstant.GENERIC_Y.equalsIgnoreCase(triggeredTodayFlag) && (status.equalsIgnoreCase(RefEODApiStatus.STARTED) || status.equalsIgnoreCase(RefEODApiStatus.SERVER_RESTARTED))){ isCurrentTaskRunning = true; } } } catch (SQLException e) { logger.error("Unable to fetch value from database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isCurrentTaskRunning; } /** * Using this method it will validate the password for passed from EMPLOYEE table. */ public static boolean validateEmployeDetails(String userName, String pass){ String selectSqlQuery = "SELECT * FROM "+ Sch_Tables.EMPLOYEE + " WHERE "+ Sch_Employee.EMPLOYEE_NUM +" =? "; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; boolean flag = false; try { conn = ServerUtil.getConnection(); stmt = conn.prepareStatement(selectSqlQuery); stmt.setString(1, userName); rs = stmt.executeQuery(); while(rs.next()) { String passVal = rs.getString(Sch_Employee.PASSWORD); if(pass.equalsIgnoreCase(passVal)){ flag = true; } } } catch (SQLException e) { logger.error("Unable to fetch value from the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(stmt); ServerUtil.releaseConnection(conn); } return flag; } /** * This method will check the STATUS from the EOD_API_TRIGGER_STATUS and it is equal to Restarted or not. */ public static boolean isStatusRestarted(Integer refEODTaskId){ String sqlQuery = "SELECT "+Sch_EodApiTriggerStatus.STATUS+", "+Sch_EodApiTriggerStatus.START_DATE+ " FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS+" WHERE " +Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean isDateMatched = false; boolean isStatusRestarted = false; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, refEODTaskId); resultSet = statement.executeQuery(); while (resultSet.next()) { String status = resultSet.getString(Sch_EodApiTriggerStatus.STATUS); Timestamp timestamp = resultSet.getTimestamp(Sch_EodApiTriggerStatus.START_DATE); if(timestamp != null){ java.sql.Date dateFromTimeStamp = new java.sql.Date(timestamp.getTime()); String startDate = String.valueOf(dateFromTimeStamp); String currentDate = String.valueOf(new java.sql.Date(new java.util.Date().getTime())); if(currentDate.equalsIgnoreCase(startDate)){ isDateMatched = true; } } if(isDateMatched && status != null && status.equalsIgnoreCase(RefEODApiStatus.SERVER_RESTARTED)){ isStatusRestarted = true; } } } catch (SQLException e) { logger.error("Unable to fetch value from the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isStatusRestarted; } /** * This method will check the STATUS from the EOD_API_TRIGGER_STATUS and it is equal to Completed or not. */ public static boolean isTaskStatusCompleted(Integer refEODTaskId){ String sqlQuery = "SELECT "+Sch_EodApiTriggerStatus.STATUS+", "+Sch_EodApiTriggerStatus.END_DATE+ " FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS+" WHERE " +Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean isDateMatched = false; boolean isStatusRestarted = false; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, refEODTaskId); resultSet = statement.executeQuery(); while (resultSet.next()) { String status = resultSet.getString(Sch_EodApiTriggerStatus.STATUS); Timestamp timestamp = resultSet.getTimestamp(Sch_EodApiTriggerStatus.END_DATE); if(timestamp != null){ java.sql.Date dateFromTimeStamp = new java.sql.Date(timestamp.getTime()); String endDate = String.valueOf(dateFromTimeStamp); String currentDate = String.valueOf(new java.sql.Date(new java.util.Date().getTime())); if(currentDate.equalsIgnoreCase(endDate)){ isDateMatched = true; } } if(isDateMatched && status != null && (status.equalsIgnoreCase(RefEODApiStatus.COMPLETED) || status.equalsIgnoreCase(RefEODApiStatus.ERROR) || status.equalsIgnoreCase(RefEODApiStatus.CRITICAL_TASK_FAILED))){ isStatusRestarted = true; } } } catch (SQLException e) { logger.error("Unable to fetch value from the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isStatusRestarted; } /** * This method will return the boolean value. * Here we will check for the values from the EOD_API_TRIGGER_STATUS table where END_DATE equals to the CURRENT_DATE. * And EOD_TRIGGERED_TODAY equals to N. Only for the first task we were validating this case. */ public static boolean isFirstTaskAlreadyExecutedForTheDay(RefEODTaskVO refEODTaskVO){ String sqlQuery = "SELECT "+ Sch_EodApiTriggerStatus.END_DATE+", "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+" FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS + " WHERE "+ Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" =? "; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean isTaskAlreadyExecuted = false; try{ connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, refEODTaskVO.getId()); resultSet = statement.executeQuery(); while(resultSet.next()){ String status = resultSet.getString(Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY); Timestamp timestamp = resultSet.getTimestamp(Sch_EodApiTriggerStatus.END_DATE); if(timestamp != null && status != null){ java.sql.Date timeStampDate = new java.sql.Date(timestamp.getTime()); String timeStampDateString = String.valueOf(timeStampDate); String currentDate = String.valueOf(new java.sql.Date(new java.util.Date().getTime())); isTaskAlreadyExecuted = timeStampDateString.equalsIgnoreCase(currentDate); } } } catch (SQLException e) { logger.error("Unable to fetch value from the database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isTaskAlreadyExecuted; } /** * Using this method it will check the status for the offline tasks from EOD_API_TRIGGER_STATUS if it is error then * it will return true. */ public static boolean isOfflineNonCriticalTaskFailed(){ String sqlQuery = "SELECT "+Sch_EodApiTriggerStatus.STATUS+" FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS+" WHERE "+Sch_EodApiTriggerStatus.REF_EOD_TASK_ID +" IN (SELECT "+Sch_RefEODTask.ID+" FROM "+Sch_Tables.REF_EOD_TASK+" WHERE "+Sch_RefEODTask.TASK_OBJECT_TYPE+" = 'O')"; Connection connection = null; Statement statement = null; ResultSet resultSet = null; boolean isOfflineNonCriticalTaskFailed = false; try{ connection = ServerUtil.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery(sqlQuery); while(resultSet.next()){ String status = resultSet.getString(Sch_EodApiTriggerStatus.STATUS); if(status != null && status.equalsIgnoreCase(RefEODApiStatus.ERROR)){ logger.error("Non critical offline task failed"); isOfflineNonCriticalTaskFailed = true; break; } } } catch (SQLException e) { logger.error("Unable to fetch the value from database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isOfflineNonCriticalTaskFailed; } /** * This method will check the STATUS from the EOD_API_TRIGGER_STATUS, and it is equal to Completed or not. */ public static boolean isPrerequisiteTaskCompleted(Integer refEodTaskId){ String sqlQuery = "SELECT "+Sch_EodApiTriggerStatus.STATUS+", "+Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY+ " FROM "+Sch_Tables.EOD_API_TRIGGER_STATUS+" WHERE " +Sch_EodApiTriggerStatus.REF_EOD_TASK_ID+" =?"; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean isPrerequisiteTaskCompleted = false; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setInt(1, refEodTaskId); resultSet = statement.executeQuery(); while (resultSet.next()){ String status = resultSet.getString(Sch_EodApiTriggerStatus.STATUS); String todayFlag = resultSet.getString(Sch_EodApiTriggerStatus.EOD_TRIGGERED_TODAY); if(status != null && status.equalsIgnoreCase(RefEODApiStatus.COMPLETED) && todayFlag.equalsIgnoreCase(TsoConstant.GENERIC_Y)){ isPrerequisiteTaskCompleted = true; } } } catch (SQLException e) { logger.error("Unable to fetch the value from database "+e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return isPrerequisiteTaskCompleted; } /** * isStoreCloudBackUpType method checks BackUpType. * @return boolean * @param storeBackupTypeURL fetch the url dynamically * */ public boolean isStoreCloudBackUpType(String storeBackupTypeURL) { logger.debug("isStoreCloudBackUpType = " + storeBackupTypeURL); String backupType = null; HttpClient client = new HttpClient(); HttpMethod httpGet = new GetMethod(storeBackupTypeURL); try { client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); int statusCode = client.executeMethod(httpGet); logger.debug("statusCode = " + statusCode); if (statusCode == HttpStatus.SC_OK) { final byte[] backUpTypeResponse = httpGet.getResponseBody(); String result = backUpTypeResponse != null ? new String(backUpTypeResponse) : null; if (result != null && !result.trim().isEmpty()) { JSONObject jsonObject = JSONObject.fromObject(result); if (!jsonObject.isNullObject() && jsonObject.containsKey("backupType")) { backupType = jsonObject.getString("backupType"); logger.debug("backupType = " + backupType); if(backupType!=null && backupType.trim().equalsIgnoreCase("cloud_only")){ return true; } } } } } catch (HttpException httpConnection) { logger.error("HttpException occured while getting Details of isStoreCloudBackUpType "); } catch (IOException ioException) { logger.error("I/O Exception occured while getting Details of isStoreCloudBackUpType "); } catch (Exception exception) { logger.error("Exception occured while getting Details of isStoreCloudBackUpType "); } finally { httpGet.releaseConnection(); } logger.info("isStoreCloudBackUpType method is going for USB Backup"); return false; } /** * getCloudBackup method checks the Status * @returns ture/false based on the url response * @param cloudBackUpStatusURL -will fetch the URl dynamically. */ public boolean getCloudBackup(String cloudBackUpStatusURL) { logger.debug("getCloudBackup =" + cloudBackUpStatusURL); boolean retValue = true; FwoDatePattern fwoDatePattern = (FwoDatePattern) FwoPattern.getDatePatternInstance( getLocale(), new Integer(ApplicationContext.getInstance().getProfile(Profile.SERVER, m_loc.intValue() ).getStoreProfile().getRefDateFormatId().intValue())); fwoDatePattern.setFourDigitYear(true); fwoDatePattern.setDateStyle(DateStyle.MDY); Date currentDate = new Date(); HttpClient client = new HttpClient(); HttpMethod httpGet = new GetMethod(cloudBackUpStatusURL); try { client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); int statusCode = client.executeMethod(httpGet); logger.debug("statusCode = " + statusCode); if (statusCode == HttpStatus.SC_OK) { final byte[] backstatusResponse = httpGet.getResponseBody(); String result = backstatusResponse!=null ? new String(backstatusResponse):null; if (result != null && !result.trim().isEmpty()) { JSONObject jsonObject = JSONObject.fromObject(result); if(!jsonObject.isNullObject() && jsonObject.containsKey("bmStatusList")){ JSONArray resultArray = (JSONArray) jsonObject.get("bmStatusList"); if(resultArray!=null && !resultArray.isEmpty()) { JSONObject ResponseResults = JSONObject.fromObject(resultArray.getJSONObject(0)); if (ResponseResults != null && ResponseResults.containsKey("modifieddts")) { Long modified_DTS = ResponseResults.getLong("modifieddts"); if (modified_DTS != null) { Timestamp modifiedtest_DTS = new Timestamp(modified_DTS); String modifiedDateTimeStamp = fwoDatePattern.format(modifiedtest_DTS); Date previousDate = new Date(currentDate.getTime() - (ONE_DAY)); String formattedPreviousDate = fwoDatePattern.format(previousDate); if (modifiedDateTimeStamp.equals(formattedPreviousDate) ) { retValue = false; } } } } } } } } catch (HttpException httpConnection) { logger.error("HttpException occured while getting Details of getCloudBackup "); } catch (IOException ioException) { logger.error("I/O Exception occured while getting Details of getCloudBackup "); } catch (Exception exception) { logger.error("Exception occured while getting Details of getCloudBackup "); } finally { httpGet.releaseConnection(); } logger.info("getCloudBackup condition got failed No Alert is created.."); return retValue; } public Hashtable runCloseOfDayServerTasks(HashMap map, ArrayList closeOfBusinessDayTask) { Hashtable results = new Hashtable(); for (Object closeOfDayTask : closeOfBusinessDayTask) { RefEODTaskVO refEODTaskVO = (RefEODTaskVO) closeOfDayTask; if(refEODTaskVO != null) { if (Boolean.TRUE.equals(refEODTaskVO.isFormTask())) { String status = checkPreviousTaskStatus(refEODTaskVO.getId()); if (RefEODApiStatus.CRITICAL_TASK_FAILED.equalsIgnoreCase(status)) { results.put(EndOfDay.KEY_OUTCOME, EndOfDay.OUTCOME_FAILURE); return results; } continue; } logger.warn("The current EOD task is "+refEODTaskVO.getLogText()); map.put(EndOfDay.KEY_REF_EOD_TASK_VO, refEODTaskVO); results = runSingleTaskViaAPI(map); } else { logger.warn("Provided RefEODTaskVO is null"); } } if (results != null && results.containsKey(EndOfDay.KEY_OUTCOME) && EndOfDay.OUTCOME_SUCCESS .equals(results.get(EndOfDay.KEY_OUTCOME))) { updateEndOfDayProfileTable(Sch_EndOfDayProfile.BMC_EOD_READY ,TsoConstant.GENERIC_Y); } return results; } public ArrayList closeOfDayTasksList(Integer[] taskIds, Integer loc) { updatePostponeEodFlagAndCloseOfDayReady(); ArrayList taskList = new ArrayList(); for (Integer id : taskIds) { RefEODTaskVO refEODTaskVO = EODTask.getRefEODTaskVO(id, loc); if(refEODTaskVO != null) { if(Boolean.FALSE.equals(refEODTaskVO.isActive())){ logger.warn("The close of day task is disabled - "+refEODTaskVO.getLogText()); continue; } taskList.add(refEODTaskVO); } else { logger.warn("Receiving RefEODTaskVO null for the id "+id); } } return taskList; } public void updateEndOfDayProfileTable(String columnName, String fieldValue){ if(columnName != null) { String sqlQuery = "UPDATE " + Sch_Tables.END_OF_DAY_PROFILE + " SET " + columnName + " = ?"; Connection connection = null; PreparedStatement statement = null; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setString(1, fieldValue); statement.executeUpdate(); } catch (SQLException e) { logger.error("Unable to update the END_OF_DAY_PROFILE table " + e.getMessage()); } finally { JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } } else { logger.error("Provided column name is null "); } } public void updateFormTaskStatus(RefEODTaskVO refEODTaskVO, String status) { if(refEODTaskVO != null) { if (isEntryAlreadyExist(refEODTaskVO)) { updateEODTriggerApi(refEODTaskVO, status, TsoConstant.GENERIC_Y); } else { insertIntoEODTriggerApi(refEODTaskVO, status); } } else { logger.error("Failed to update Form Task Status provided RefEODTaskVO is null"); } } public static boolean checkCloseOfDayTriggeredStatus(String closeOfDayTriggered, String bmcEODReady, Integer loc){ boolean checkCloseOfDayTriggeredStatus = false; String sqlQuery = "SELECT " + Sch_EndOfDayProfile.CLOSE_OF_DAY_TRIGGERED + ", " + Sch_EndOfDayProfile.BMC_EOD_READY + " FROM " + Sch_Tables.END_OF_DAY_PROFILE + " WHERE " + Sch_EndOfDayProfile.LOC + " = ?"; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setObject(1, loc); resultSet = statement.executeQuery(); while(resultSet.next()){ String codTriggered = resultSet.getString(Sch_EndOfDayProfile.CLOSE_OF_DAY_TRIGGERED); String bmcReady = resultSet.getString(Sch_EndOfDayProfile.BMC_EOD_READY); if(closeOfDayTriggered != null && bmcEODReady != null){ return (closeOfDayTriggered.equalsIgnoreCase(codTriggered) && bmcEODReady.equalsIgnoreCase(bmcReady)); } } } catch (SQLException e) { logger.error("Unable to fetch values from the END_OF_DAY_PROFILE table " + e.getMessage()); } finally { JDBCUtil.closeResultSet(resultSet); JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } return checkCloseOfDayTriggeredStatus; } public static void updateCloseOfDayAndBMCReady(String status, Integer loc){ String sqlQuery = "UPDATE "+Sch_Tables.END_OF_DAY_PROFILE+" SET "+Sch_EndOfDayProfile.CLOSE_OF_DAY_TRIGGERED+ " = ?,"+Sch_EndOfDayProfile.BMC_EOD_READY+" = ?"+" WHERE "+Sch_EndOfDayProfile.LOC+" = ?"; Connection connection = null; PreparedStatement statement = null; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.setObject(1, status); statement.setObject(2, status); statement.setObject(3, loc); statement.executeUpdate(); } catch(SQLException e) { logger.error("Unable to update the END_OF_DAY_PROFILE table "+e.getMessage()); }finally{ JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } } public static void updatePostponeEodFlagAndCloseOfDayReady(){ String sqlQuery = "UPDATE "+Sch_Tables.END_OF_DAY_PROFILE+" SET "+Sch_EndOfDayProfile.POSTPONE_EOD_FLAG+"= 'N'"+ ","+Sch_EndOfDayProfile.CLOSE_OF_DAY_TRIGGERED+" = 'Y'"; Connection connection = null; PreparedStatement statement = null; try { connection = ServerUtil.getConnection(); statement = connection.prepareStatement(sqlQuery); statement.executeUpdate(); } catch(SQLException e) { logger.error("Unable to update the END_OF_DAY_PROFILE table "+e.getMessage()); }finally{ JDBCUtil.closeStatement(statement); ServerUtil.releaseConnection(connection); } } }