웹 응용 프로그램의 타이머

감청기
public class ResourceCWDLoadListener implements ServletContextListener {

private Log log = LogFactory.getLog(getClass());
private static Timer timer = null;

public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
log.info("ResourceCWDLoad Timer has been removed!");
}

public void contextInitialized(ServletContextEvent event) {
long defaulttimestamp = 60;
String defaultuploadfileloc = "D:\\DOS_UPLOAD\\UPLOAD_FILES";
String defaultbackupfileloc = "D:\\DOS_UPLOAD\\BACKUP_FILES";
String defaulterrorbackupfileloc = "D:\\DOS_UPLOAD\\ERRORBACKUP_FILE";
timer = new Timer(true);

ServletContext sc = event.getServletContext();
long timestamp = Long.parseLong(sc.getInitParameter("TIMESTAMP"));
String uploadfileloc = sc.getInitParameter("UPLOADFILELOC");
String backupfileloc = sc.getInitParameter("BACKUPFILELOC");
String errorbackupfileloc = sc.getInitParameter("ERRORBACKUPFILELOC");

if(timestamp == 0)
timestamp = defaulttimestamp;
if(StringUtil.isBlankOrNull(uploadfileloc))
uploadfileloc = defaultuploadfileloc;
if(StringUtil.isBlankOrNull(backupfileloc))
backupfileloc = defaultbackupfileloc;
if(StringUtil.isBlankOrNull(errorbackupfileloc))
errorbackupfileloc = defaulterrorbackupfileloc;

timer.schedule(new FileLoad(uploadfileloc, backupfileloc,
errorbackupfileloc), 0, timestamp * 1000 * 60);
}

}

이루어지다
public class FileLoad extends TimerTask{

private String uploadfileloc = null;

private String backupfileloc = null;

private String errorbackupfileloc = null;

public FileLoad(String uploadfileloc, String backupfileloc, String errorbackupfileloc){
this.uploadfileloc = uploadfileloc;
this.backupfileloc = backupfileloc;
this.errorbackupfileloc = errorbackupfileloc;
}

//private FileTask ft = TaskFactory.getFileTask();

public void run() {
TaskFactory.getFileTask().execute(uploadfileloc, backupfileloc, errorbackupfileloc);
}

}

구체류
public class FileTaskImpl implements FileTask {

private Log log = LogFactory.getLog(getClass());
//Default excel sheet name
private final String sheetname1 = "Resource & CWD";

private FileDao fd = new FileDao();

public void execute(String uploadfileloc, String backfileloc,
String errorbackupfileloc) {
log.info("Retrieve directory: [ " + uploadfileloc + " ]");

/*System.out.println("< "
+ new Date(System.currentTimeMillis()).toString()
+ " > Retrieve: " + "[ " + uploadfileloc + " ]");
*/
scanfile(uploadfileloc, backfileloc, errorbackupfileloc);
}

/**
* This method is called to retrieve the data from excel to database
*
@param uploadfileloc
* The path of the folder which contains the file to be uploaded
*
@param backfileloc
* The path of the folder which the file should be backup to
*
@param errorbackupfileloc
* The path of the folder which the file should be backup to when error occurs
*/
private void scanfile(String uploadfileloc, String backfileloc,
String errorbackupfileloc) {
File uploadfile = new File(uploadfileloc);

//If file not exist, create it
if (!uploadfile.exists()) {
uploadfile.mkdirs();
}

if (uploadfile.isDirectory() && uploadfile.canExecute()) {
File[] files = uploadfile.listFiles();
if (files.length == 0) {
log.info("Retrieve directory: [ " + uploadfileloc + " ] ok! No new file found!");
//System.out.println("Retrieve directory ok, no new file found");
} else {
List<ResourceCWD> data = new ArrayList<ResourceCWD>();
try {
data = loaddata1(files[0].getAbsolutePath());
String save = fd.savefile(data);
if(save == null){
//If the procedure process success, it will return null
log.info("Retrieve excel file has been saved to database!");
if (backupfile(backfileloc, files[0].getAbsolutePath(),files[0].getName()))
if (files[0].delete())
log.info("Backup success! File has been backup to directory: [ " + backfileloc + " ]");
}else{
log.error(save);
if (backupfile(errorbackupfileloc, files[0].getAbsolutePath(), files[0].getName()))
if(files[0].delete())
log.error("Some error occured!Load file error!File has been backup to directory: [" + errorbackupfileloc + " ]");
}
} catch (RuntimeException e) {
log.error(e.toString());
if (backupfile(errorbackupfileloc, files[0].getAbsolutePath(), files[0].getName()))
if(files[0].delete())
log.error("Some error occured!Load file error!File has been backup to directory: [" + errorbackupfileloc + " ]");
//System.out.println("Some error occured!Load file error!File has been backup to " + errorbackupfileloc);
//e.printStackTrace();
}
}
} else {
log.error("File no exist Or File can't be execute");
//System.out.println("File no exist Or File can't be execute");
}
}

/**
* This method is called to move file from original folder to the backup folder
*
@param backfileloc
* The path of the folder which file should be backup to
*
@param tobebackupfilepath
* The path of the folder which contains the original file
*
@param filename
* Name of the file to be moved
*
@return true if move success, else false
*/
private boolean backupfile(String backfileloc, String tobebackupfilepath,
String filename) {
boolean successflag = false;
int readbyte = 0;

File backupfile = new File(backfileloc);
File tobebackupfile = new File(tobebackupfilepath);

String newpath = null;
String newfilename = null;
SimpleDateFormat sdf = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss");

newpath = sdf.format(new Date(System.currentTimeMillis()));

if (!backupfile.exists())
backupfile.mkdirs();

//excel file must be ended with .xlsx
if (filename.endsWith(".xlsx")) {
newfilename = filename.substring(0, filename.length() - 5).concat(
sdf.format(new Date(System.currentTimeMillis()))).concat(
".xlsx");
}else{
//logger should be added
return false;
}
//Change file name to originalname_yyyy_MM_dd_HH_mm_ss.xlsx
newpath = backfileloc.concat("\\").concat(newfilename);

if (tobebackupfile.exists()) {
try {
InputStream is = new FileInputStream(tobebackupfile);
FileOutputStream fs = new FileOutputStream(newpath);

byte[] buffer = new byte[1024];

while ((readbyte = is.read(buffer)) != -1) {
fs.write(buffer, 0, readbyte);
}

is.close();
fs.close();
successflag = true;
} catch (FileNotFoundException e) {
log.error(tobebackupfilepath + " Not found!");
e.printStackTrace();
} catch (IOException e) {
log.error(tobebackupfilepath + " Backup error!");
e.printStackTrace();
}
} else {
log.error(filename + " Not exist!");
//System.out.println(filename + " Not exist!");
}

return successflag;
}

/**
* This method is called to retrieve the data from excel to the object.
* If the first cell of one row is blank, the retrieve process will break <-----
*
@param filename The full path of the file to be uploaded
*
@return list the excel data converted to list
*
@exception ParseException SimpleDateFormat
*
@exception IOException read excel file
*/
public List<ResourceCWD> loaddata1(String filename) throws RuntimeException{
FileInputStream fis = null;
XSSFWorkbook xwb = null;
List<ResourceCWD> dataList = new ArrayList<ResourceCWD>();

try {
fis = new FileInputStream(filename);
xwb = new XSSFWorkbook(fis);
XSSFSheet resourceSheet = null;
XSSFRow resourcerow = null;

//To parse the start_date and Effective_end_date
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

resourceSheet = xwb.getSheet(sheetname1);

log.info("Retrieve file: [" + filename + " ]");

for (int i = resourceSheet.getFirstRowNum() + 1; i < resourceSheet
.getPhysicalNumberOfRows(); i++) {
ResourceCWD res = new ResourceCWD();
resourcerow = resourceSheet.getRow(i);
if (resourcerow.getCell(0) == null)
break;

res.setAm(resourcerow.getCell(0) == null ? "" : resourcerow
.getCell(0).getStringCellValue());
res.setP_start_date(resourcerow.getCell(1) == null ? null
: resourcerow.getCell(1).getDateCellValue());
res.setProject_end_date(resourcerow.getCell(2) == null ? null
: resourcerow.getCell(2).getDateCellValue());
res.setWon(resourcerow.getCell(3) == null ? null : resourcerow
.getCell(3).getRawValue());
res.setProject_name(resourcerow.getCell(4) == null ? ""
: resourcerow.getCell(4).getStringCellValue());
res.setEmp_no(resourcerow.getCell(5) == null ? null : resourcerow
.getCell(5).getRawValue());
res.setEmp_name(resourcerow.getCell(6) == null ? "" : resourcerow
.getCell(6).getStringCellValue());
res.setAllocation_start_date(resourcerow.getCell(7) == null ? null
: resourcerow.getCell(7).getDateCellValue());
res.setAllocation_end_date(resourcerow.getCell(8) == null ? null
: resourcerow.getCell(8).getDateCellValue());
res.setPm(resourcerow.getCell(10) == null ? "" : resourcerow
.getCell(10).getRawValue());
res.setCwd_name(resourcerow.getCell(11) == null ? "" : resourcerow
.getCell(11).getRawValue());
res.setSso_id(resourcerow.getCell(12) == null ? "" : resourcerow
.getCell(12).getRawValue());
res.setStart_date(resourcerow.getCell(15) == null ? null : sdf
.parse(resourcerow.getCell(15).getRawValue()));
res.setEff_end_date(resourcerow.getCell(16) == null ? null : sdf
.parse(resourcerow.getCell(16).getRawValue()));
dataList.add(res);
}

} catch (ParseException e) {
e.printStackTrace();
//log.error(e.toString());
throw new RuntimeException("Excel Format error!");
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e.toString());
throw new RuntimeException("File Not Found!");
} catch (IOException e) {
e.printStackTrace();
log.error(e.toString());
throw new RuntimeException("I/O Exception!");
}finally{
try {
fis.close();
} catch (IOException e) {
log.error(e.getMessage());
throw new RuntimeException("Excel Close Exception!");
}
}
log.info("Retrieve file: [" + filename + " ] success!");

return dataList;

}
}

web.xml에서 설정
<listener>
<listener-class>com.tt.emeasure.listener.ResourceCWDLoadListener</listener-class>
</listener>
    <!--Location of the excel file to be uploaded-->
<context-param>
<param-name>UPLOADFILELOC</param-name>
<param-value>D:\DOS_UPLOAD\UPLOAD_FILES</param-value>
</context-param>

<!--Location of the backup file-->
<context-param>
<param-name>BACKUPFILELOC</param-name>
<param-value>D:\DOS_UPLOAD\BACKUP_FILES</param-value>
</context-param>

<!--Location of the error backup file-->
<context-param>
<param-name>ERRORBACKUPFILELOC</param-name>
<param-value>D:\DOS_UPLOAD\ERRORBACKUP_FILE</param-value>
</context-param>

좋은 웹페이지 즐겨찾기