實現異構系統的數據非實時同步 接口

     寫了個接口,核心思想是兩個異構系統之間實現數據的非實時同步。  也就是說平臺1生成的數據在天天規定時間放到FTP服務器地址中去,平臺2在規定的時間去取數據。這樣就能夠實現了非實時數據同步。  思想雖然說不難理解,可是實現起來仍是費了不少功夫。其中涉及的到的技術就有FTP 協議、定時器原理、服務器集羣分佈思想、ServletContextListener原理。 本代碼已經對接成功 ,現分享代碼以下,在此拋磚引玉------(相關jar包就不提供了,網上都有) java


具體代碼以下: web

1.監聽器類 sql

package com.usermsgsync.servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.usermsgsync.time.TimerManagerDay;
import com.usermsgsync.time.TimerManagerMon;


/**
 * @see 用於監聽WEB 應用啓動和銷燬的事件,監聽器類須要實現ServletContextListener接口
 * @author 
 *
 */
public class ContextListener implements ServletContextListener 
{
    
	//獲取容器中的ServletContext(上下文),爲了取到配置中的鍵值
	public void contextInitialized(ServletContextEvent event) 
	{
		//定時器管理方法,以構造方法獲取<context-param>中的鍵值
		new TimerManagerDay(event.getServletContext());
		new TimerManagerMon(event.getServletContext());
	}
	
	//在服務器中止運行的時候中止全部的定時任務
	public void contextDestroyed(ServletContextEvent event)
	{
	
	}
}


2.處理具體業務類 apache

package com.usermsgsync;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.entity.Userreg;
import com.usermsgsync.time.DateUtil;
import com.userreg.dao.UserRegDao;



public class UserSyncMsg 
{

	private static UserRegDao userDao = UserRegDao.getInstance();
	
	private static final String VersionNo = UserSyncMsgConfig.getValue("userSyncMsg_VersionNo");        //版本信息,4位,採用VXXX格式,本版本填V010
	private static final String PlatformID = UserSyncMsgConfig.getValue("userSyncMsg_PlatformID");      //XXX平臺分配給XX共享平臺的編號,6位
	private static final String InterfaceNo = UserSyncMsgConfig.getValue("userSyncMsg_InterfaceNo");    //同步接口編號,兩位。(01: 用戶狀態信息通知接口)

	private static String createDate;      //文件產生日期,14位。格式爲YYYYMMDDHHMMSS 
	private static String day = "Day";   //文件標示   Day表示增量文件
	private static String mon = "Mon";   //文件標示   Mon表示按月的全量文件
	
	//服務器端的:每日/月源文件的保存目錄  
	private static String userMsgfileDir = "//home//stemp//ROOT//fileDir//"; 
	
	
//	本地調試用的
//	private static String userMsgfileDir = "F:\\" + VersionNo + "\\" + InterfaceNo + "\\" + PlatformID ;  //請求文件目錄:每日/月源文件的保存目錄  
//	private static String ReturnDir  = RequestDir + "\\RSP";   //回執文件目錄
	
	
	
	/**
	 * 生成天天的增量同步源文件,並遠程上傳到FTP服務器
	 */
	public static void createFileDay() 
	{
		
		//判斷目錄是否存在 不存在建立
		directoryExists(userMsgfileDir);
		
         //獲取前一天的增量內容
		List<Userreg> list = getUserListDay();
		String fileContent = getFileContent(list);
		
		//日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDDHHmmss");
		// 請求文件名:
		createDate = sdf.format(new Date());
		String fileName = InterfaceNo + PlatformID + createDate + "_" + day;
		
		String requestFileName = fileName + ".txt"; //請求文件名
		System.out.println("--請求文件名---->"+requestFileName);
		
		// 生成天天增量請求文件,並將內容寫入文件
		File file = new File(userMsgfileDir, requestFileName);
		createFile(file, fileContent);
		uploadFile(requestFileName);
	}
		

	/**
	 * 生成每個月的全量的同步文件
	 */
	public static void createFileMon() 
	{
//		System.out.println("--請求文件目錄(每個月的)---->"+userMsgfileDir);
		//判斷目錄是否存在 不存在建立
		directoryExists(userMsgfileDir);
		
               //獲取全量內容
		List<Userreg> list = getUserListAll(); 
		String fileContent = getFileContent(list);
		
		//日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDDHHmmss");
		//請求文件名:
		createDate = sdf.format(new Date());
		String fileName = InterfaceNo + PlatformID + createDate + "_" + mon;
		String requestFileName = fileName + ".txt";
		
		// 生成請求文件,並將內容寫入文件
		File file = new File(userMsgfileDir, requestFileName);
		createFile(file, fileContent);
	}
		
	
	/**
	 * 獲得每日的增量信息(注意:因爲此處的定時器的優先級過高,尚未徹底啓動完就已經執行了,因此取不到數據)
	 */
	public static List<Userreg> getUserListDay() 
	{
		// 獲得當前時間 的前一天
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = DateUtil.getSpecifiedDayBefore(sdf.format(new Date()));
		// 獲取前一天的增量
		String hql = "from Userreg u where u.regtime BETWEEN '"+date+" 00:00:00' AND '"+date+" 24:00:00'";
//		String sql = "select *from userreg where bak2 between '"+date+" 00:00:00' and '"+date+" 24:00:00'";
		
		System.out.println("--進入查詢每日增量---->"+hql);
		return userDao.getUserList(hql);
	}
	
	
	/**
	 * 每個月一次的全量信息
	 */
	public static List<Userreg> getUserListAll() 
	{
		Date nowDate = new Date() ;
		String firstDay = DateUtil.getFirstDayOfMonth(nowDate);
		String lastDay = DateUtil.getLastDayOfMonth(nowDate);
		
		String hql = "from Userreg u where u.regtime BETWEEN '"+firstDay+" 00:00:00' AND '"+lastDay+" 24:00:00'";
		
		return userDao.getUserList(hql);
	}


	/**
	 * 文件內容格式
	 * @param list
	 * @return
	 */
	private static String getFileContent(List<Userreg> list) 
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) 
		{
			sb.append(list.get(i).getUserphone() + "," + list.get(i).getEmail()+ "," + list.get(i).getUserstate());
			sb.append("\r\n");
		}
		System.out.println("--獲取文件內容格式---->"+sb.toString());
		return sb.toString();
	}


	/**
	 * 判斷目錄是否存在,若是不存在,則建立
	 * @param dir
	 */
	private static void directoryExists(String dir) 
	{
		// 保存目錄
		File saveDirectory = new File(dir);
		// 若是不存在則建立多級目錄
		if (!saveDirectory.exists()) 
		{
			saveDirectory.mkdirs();
		}
	}
	
	
	/**
	 * 建立文件 並將內容寫入文件
	 * @param file
	 * @param content
	 */
	private static void createFile(File file, String content) 
	{
		try 
		{
			if (file.exists()) 
			{
				file.delete();
				file.createNewFile();
				// 將內容寫入文件
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
				bos.write(content.getBytes());
				bos.flush();
				bos.close();
			} 
			else 
			{
				System.out.println("--寫入文件內容方法---->");
				file.createNewFile();
				// 將內容寫入文件
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
				bos.write(content.getBytes());
				bos.flush();
				bos.close();
			}
		}
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 遠程上傳文件到FTP服務器
	 * @param requestFileName
	 */
	private static void uploadFile(String requestFileName)
	{
		String ip =  UserSyncMsgConst.IP ;
		int port  =  UserSyncMsgConst.Port ; 
		String user =UserSyncMsgConst.User ;  
		String pwd = UserSyncMsgConst.Pwd ;  
		String requestDir = UserSyncMsgConst.RequestDir ;
		System.out.println("----ftp請求文件目錄--->"+ requestDir);
		
		
		List<File> fileList = new ArrayList<File>();
		File onefile = new File(userMsgfileDir,requestFileName); 	
		System.out.println("----服務器端的文件路徑--->"+ onefile.getAbsolutePath());
		fileList.add(onefile);
		
		FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd);
		try 
		{
			ftpupload.uploadFile(requestDir, fileList);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 遠程刪除FTP服務器下的請求文件目錄
	 */
	public static void deleteFilesDay()
	{
		String ip =  UserSyncMsgConst.IP ; //第1臺FTP服務器
		int port  =  UserSyncMsgConst.Port ; 
		String user =UserSyncMsgConst.User ;  
		String pwd = UserSyncMsgConst.Pwd ;  
		String requestDir = UserSyncMsgConst.RequestDir ;
		
//		String ip1 =  UserSyncMsgConst.IP1 ; //第2臺FTP服務器
		
		FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd);
//		FTPUtil ftpupload1 = new FTPUtil(ip1,port,user,pwd);
		try 
		{
			ftpupload.deleteAllFile(requestDir);
//			ftpupload1.deleteAllFile(remotePath);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
}


3. 常量類,其實能夠去掉,由於已經有了properties文件 服務器

package com.usermsgsync;

/**
 * 配置用戶同步信息常量
 * @author 
 *
 */
public class UserSyncMsgConst 
{
	public static final String IP = UserSyncMsgConfig.getValue("userSyncMsg_FTP_IP") ;                      //FTP服務器的ip
	public static final int Port = Integer.parseInt(UserSyncMsgConfig.getValue("userSyncMsg_FTP_port"));    //FTP服務器的端口
	public static final String User = UserSyncMsgConfig.getValue("userSyncMsg_FTP_userName");               //FTP服務器的用戶名
	public static final String Pwd = UserSyncMsgConfig.getValue("userSyncMsg_FTP_passWord") ;               //FTP服務器的密碼
	
	
	public static final String RequestDir =UserSyncMsgConfig.getValue("userSyncMsg_FTP_RequestDir") ;         //FTP服務器的配置的上傳目錄(請求文件目錄)
	
}


4. 讀取配置文件方法 app

package com.usermsgsync;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import com.weibo.weibo4j.util.URLEncodeUtils;

@SuppressWarnings("static-access") 
public class UserSyncMsgConfig
{
    
    private static String filePath = UserSyncMsgConfig.class.getResource("/").getPath() + "userSyncMsgConfig.properties";

    public UserSyncMsgConfig()
    {
    }

    private static Properties props = new Properties();
    static
    {
        try
        {
            String filePaths = new URLEncodeUtils().decodeURL(filePath);
            System.out.println(filePaths);
            props.load(new FileInputStream(filePaths));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static String getValue(String key)
    {
        return props.getProperty(key);
    }

    public static void updateProperties(String key, String value)
    {
        props.setProperty(key, value);
    }

}


5.遠程FTP處理類 ide

package com.usermsgsync;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
//import org.apache.commons.net.ftp.FTPClientConfig; 
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/** 遠程FTP處理類
 * 
 * @author suchiheng
 * @version 1.0, 2012/09/15 */
public class FTPUtil
{

    private Logger logger = Logger.getLogger(FTPUtil.class);
    private String ip;
    private int port;
    private String pwd;
    private String user;
    private FTPClient ftpClient;

    private FTPUtil()
    {
    }

    public FTPUtil(String ip, int port, String user, String pwd)
    {

        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pwd = pwd;
    }

    /** 鏈接遠程FTP服務器
     * 
     * @param ip
     *            地址
     * @param port
     *            端口號
     * @param user
     *            用戶名
     * @param pwd
     *            密碼
     * @return
     * @throws Exception */
    public boolean connectServer(String ip, int port, String user, String pwd) throws Exception
    {

        boolean isSuccess = false;
        try
        {
            ftpClient = new FTPClient();
            ftpClient.connect(ip, port);
            ftpClient.setControlEncoding("GBK");
//    		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); //此類commons-net-2.0不提供
//    		conf.setServerLanguageCode("zh");
            ftpClient.login(user, pwd);
            ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
            {
                isSuccess = true;
                System.out.println("--鏈接ftp服務器成功!!!");
            }
            else
            {
                ftpClient.disconnect();
                logger.error("連不上ftp服務器!");
//				throw new BossOperException();
            }
        }
        catch (Exception e)
        {
            logger.error("鏈接FTP服務器異常..", e);
            e.printStackTrace();
        }

        return isSuccess;
    }

    /** 遠程FTP上傳文件
     * 
     * @param remotePath
     * @param localPath
     * @param files
     * @return
     * @throws Exception */
    public File uploadFile(String remotePath, List<File> files) throws Exception
    {
        File fileIn = null;
        OutputStream os = null;
        FileInputStream is = null;
        try
        {
            for (File file : files)
            {
                if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
                {
                    System.out.println("----進入文件上傳到FTP服務器--->");
                    ftpClient.changeWorkingDirectory(remotePath);
                    os = ftpClient.storeFileStream(file.getName());
                    fileIn = file;
                    is = new FileInputStream(fileIn);
                    byte[] bytes = new byte[1024];
                    int c;
                    while ((c = is.read(bytes)) != -1)
                    {
                        os.write(bytes, 0, c);
                    }
                }
            }
        }
        catch (Exception e)
        {
            logger.error("上傳FTP文件異常: ", e);
        }
        finally
        {
            os.close();
            is.close();
            ftpClient.logout();
            if (ftpClient.isConnected())
            {
                ftpClient.disconnect();
            }
        }

        return fileIn;
    }

    /** 遠程FTP上刪除一個文件
     * 
     * @param remotefilename
     * @return */
    public boolean deleteFile(String remotefilename)
    {
        boolean flag = true;
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                flag = ftpClient.deleteFile(remotefilename);
                if (flag)
                {
                    System.out.println("遠程刪除FTP文件成功!");
                }
                else
                {
                    System.out.println("-----遠程刪除FTP文件失敗!----");
                }
            }
        }
        catch (Exception ex)
        {
            logger.error("遠程刪除FTP文件異常: ", ex);
            ex.printStackTrace();
        }
        return flag;
    }

    /** 遠程FTP刪除目錄下的全部文件
     * 
     * @param remotePath
     * @return
     * @throws Exception */
    public void deleteAllFile(String remotePath) throws Exception
    {
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                ftpClient.changeWorkingDirectory(remotePath);
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile file : ftpFiles)
                {
                    System.out.println("----刪除遠程FTP服務器文件--->" + file.getName());
                    ftpClient.deleteFile(file.getName());

                }
            }
        }
        catch (Exception e)
        {
            logger.error("從FTP服務器刪除文件異常:", e);
            e.printStackTrace();
        }
        finally
        {
            ftpClient.logout();
            if (ftpClient.isConnected())
            {
                ftpClient.disconnect();
            }
        }
    }

    /** 遠程FTP上建立目錄
     * 
     * @param dir
     * @return */
    public boolean makeDirectory(String dir)
    {
        boolean flag = true;
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                flag = ftpClient.makeDirectory(dir);
                if (flag)
                {
                    System.out.println("make Directory " + dir + " succeed");
                }
                else
                {
                    System.out.println("make Directory " + dir + " false");
                }
            }
        }
        catch (Exception ex)
        {
            logger.error("遠程FTP生成目錄異常:", ex);
            ex.printStackTrace();
        }
        return flag;
    }

    /** 遠程FTP下載文件
     * 
     * @param remotePath
     * @param localPath
     * @return
     * @throws Exception */
    public List<File> downloadFile(String remotePath, String localPath) throws Exception
    {
        List<File> result = new ArrayList<File>();
        File fileOut = null;
        InputStream is = null;
        FileOutputStream os = null;
        try
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd()))
            {
                ftpClient.changeWorkingDirectory(remotePath);
                FTPFile[] ftpFiles = ftpClient.listFiles();

                for (FTPFile file : ftpFiles)
                {
                    is = ftpClient.retrieveFileStream(file.getName());
                    if (localPath != null && !localPath.endsWith(File.separator))
                    {
                        localPath = localPath + File.separator;
                        File path = new File(localPath);
                        if (!path.exists())
                        {
                            path.mkdirs();
                        }
                    }
                    fileOut = new File(localPath + file.getName());
                    os = new FileOutputStream(fileOut);
                    byte[] bytes = new byte[1024];
                    int c;
                    while ((c = is.read(bytes)) != -1)
                    {
                        os.write(bytes, 0, c);
                    }

                    result.add(fileOut);
                    ftpClient.completePendingCommand();
                    os.flush();
                    is.close();
                    os.close();
                }

                for (FTPFile file : ftpFiles)
                {
                    ftpClient.deleteFile(file.getName());
                }
            }
        }
        catch (Exception e)
        {
            logger.error("從FTP服務器下載文件異常:", e);
            e.printStackTrace();
        }
        finally
        {
            ftpClient.logout();
            if (ftpClient.isConnected())
            {
                ftpClient.disconnect();
            }
        }

        return result;
    }

    public String getIp()
    {
        return ip;
    }

    public void setIp(String ip)
    {
        this.ip = ip;
    }

    public int getPort()
    {
        return port;
    }

    public void setPort(int port)
    {
        this.port = port;
    }

    public String getPwd()
    {
        return pwd;
    }

    public void setPwd(String pwd)
    {
        this.pwd = pwd;
    }

    public String getUser()
    {
        return user;
    }

    public void setUser(String user)
    {
        this.user = user;
    }

    /** 測試方法
     * 
     * @param args */
    public static void main(String[] args)
    {
        String ip = UserSyncMsgConst.IP;
        int port = UserSyncMsgConst.Port;
        String user = UserSyncMsgConst.User;
        String pwd = UserSyncMsgConst.Pwd;
        String requestDir = UserSyncMsgConst.RequestDir;

        // 上傳文件配置
//		List<File> fileList = new ArrayList<File>();
////		File onefile = new File("F:\\V010\\01\\000011\\RSP\\0100001120120701122712_Day.txt");
//		File onefile = new File("F:\\V010\\01\\000011\\RSP\\" ,"01000011201209263112839_Day.txt");
//		System.out.println("----本地文件路徑--->"+ onefile.getAbsolutePath());
//		fileList.add(onefile);

        FTPUtil ftpupload = new FTPUtil(ip, port, user, pwd);
        try
        {
//			ftpupload.uploadFile(remotePath, fileList);  //測試上傳文件

            // 刪除文件
//			String remotefilename = remotePath+"01000011201209263112839_Day.txt";
//			System.out.println("----遠程FTF上的文件名----"+remotefilename);
//			ftpupload.deleteFile(remotefilename);

            // 刪除目錄下全部的文件
//			ftpupload.deleteAllFile(RequestDir);

            // 下載目錄下全部的文件
//			String localPath = "F:\\TEST\\" ;
//			ftpupload.downloadFile(remotePath, localPath);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}


6. 相關時間處理類和定時器類 測試

package com.usermsgsync.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;



/**
 * 相關時間處理類
 * @author suchiheng
 * @version 1.0,  2012/09/15
 */
public class DateUtil 
{
	/**
	 * 得到指定日期的前一天
	 * 
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static String getSpecifiedDayBefore(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		Date date = null;
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		try 
		{
			
			date = simpleDateFormat.parse(specifiedDay);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);

		String dayBefore = simpleDateFormat.format(c.getTime());
		return dayBefore;
	}

	/**
	 * 得到指定日期的後一天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static String getSpecifiedDayAfter(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		Date date = null;
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		try 
		{
			date = simpleDateFormat.parse(specifiedDay);
		}
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + 1);

		String dayAfter = simpleDateFormat.format(c.getTime());
		return dayAfter;
	}
	
	/**
	 * 獲取指定時間的上個月的最後一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getLastDayOfMonth(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try 
		{
			date = simpleDateFormat.parse(specifiedDay); //轉化爲Date格式
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		c.setTime(date);
		
		c.add(Calendar.MONTH, -1); //獲取上一個月
		
		int maxDate = c.getActualMaximum(Calendar.DAY_OF_MONTH);
	    c.set(Calendar.DAY_OF_MONTH, maxDate);
		
		String LastDayOfMonth = simpleDateFormat.format(c.getTime()); //格式化時間格式
		return LastDayOfMonth;
	}
	
	
	/**
	 * 獲取指定時間的上個月的最後一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getLastDayOfMonth(Date specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		c.setTime(specifiedDay);
		c.add(Calendar.MONTH, -1); //設置上一個月
		
		int maxDate = c.getActualMaximum(Calendar.DAY_OF_MONTH); //設置最後一天
	    c.set(Calendar.DAY_OF_MONTH, maxDate);
		
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		String LastDayOfMonth = simpleDateFormat.format(c.getTime());   //格式化時間格式
		return LastDayOfMonth;
	}
	
	/**
	 * 獲取指定時間的上個月的第一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getFirstDayOfMonth(String specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try 
		{
			date = simpleDateFormat.parse(specifiedDay); //轉化爲Date格式
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		c.setTime(date);
		c.add(Calendar.MONTH, -1); //設置上一個月
		
		int MiniDate = c.getActualMinimum(Calendar.DAY_OF_MONTH);
	    c.set(Calendar.DAY_OF_MONTH, MiniDate);
		
		String FirstDayOfMonth = simpleDateFormat.format(c.getTime());
		return FirstDayOfMonth ;
	}
	
	/**
	 * 獲取上個月的第一天
	 * @param specifiedDay
	 * @return
	 */
	public static String getFirstDayOfMonth(Date specifiedDay) 
	{
		Calendar c = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat =	new SimpleDateFormat("yyyy-MM-dd");

		c.setTime(specifiedDay);
		
		c.add(Calendar.MONTH, -1); //設置上一個月
		
		int MiniDate = c.getActualMinimum(Calendar.DAY_OF_MONTH);
	    c.set(Calendar.DAY_OF_MONTH, MiniDate);
		
		String FirstDayOfMonth = simpleDateFormat.format(c.getTime());
		return FirstDayOfMonth ;
	}
	
	
	
	/**
	 *  
	 * 方法描述:取得當前日期的上月或下月日期 ,amount=-1爲上月日期,amount=1爲下月日期;建立人:
	 * @param s_DateStr
	 * @param s_FormatStr
	 * @return
	 * @throws Exception
	 */
	public static String getFrontBackStrDate(String strDate,int amount) throws Exception 
	{
		if (null == strDate) 
		{
			return null;
		}
		try 
		{

			SimpleDateFormat fmt = new SimpleDateFormat("yy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTime(fmt.parse(strDate));
			c.add(Calendar.MONTH, amount);
			return fmt.format(c.getTime());
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return "";
	}

	
	/**
	 * 返回兩時間差,拼接成字符串返回
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static String getTimeSub(Long time1, Long time2 )
	{
		String result = "";
		try 
		{
			Long diff = time2 - time1;   //兩時間差,精確到毫秒 
			
			Long day = diff / (1000 * 60 * 60 * 24);         //以天數爲單位取整
			Long hour=(diff/(60*60*1000)-day*24);            //以小時爲單位取整 
			Long min=((diff/(60*1000))-day*24*60-hour*60);        //以分鐘爲單位取整 
			Long secone=(diff/1000-day*24*60*60-hour*60*60-min*60);
			
			result = day + "|" + hour+ "|" + min ; 
			System.out.println("---兩時間差---> " +day+"天"+hour+"小時"+min+"分"+secone+"秒");
	
		} 
		catch (RuntimeException e) 
		{
			e.printStackTrace();
		}
		return result ;
	}
	
	
}


7. 定時器 ui

package com.usermsgsync.time;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContext;

public class TimerManagerDay
{

    // 時間間隔 一天
    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
    // 調試時間(1分)
//	private static final long PERIOD_DAY = 60 * 1000;
    private ServletContext servletContext = null;

    public TimerManagerDay(ServletContext context)
    {
        this.servletContext = context;
        // 獲取配置中的時間信息
        String hour = this.servletContext.getInitParameter("hour");
        String minute = this.servletContext.getInitParameter("minute");

        Calendar calendar = Calendar.getInstance();

        // 定製每日00:00點執行方法
        calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));
        calendar.set(Calendar.MINUTE, Integer.valueOf(minute));

        // 第一次執行定時任務的時間
        Date date = calendar.getTime();

        // 若是第一次執行任務的時間小於當前時間 ,此時要在第一次任務的時間上加上一天,若是不加上一天 ,任務會當即執行
        if (date.before(new Date()))
        {
            date = this.addDay(date, 1);
        }

        Timer time = new Timer();
        // 安排指定的任務 在指定的時間 執行
        UserMsgTimerTask dataTask = new UserMsgTimerTask();
        time.schedule(dataTask, date, PERIOD_DAY);

    }

    /** 給時間加任意一天
     * 
     * @param date
     * @param num
     * @return */
    public Date addDay(Date date, int num)
    {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, 1); // 加一天
        return startDT.getTime();
    }

}


package com.usermsgsync.time;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContext;

public class TimerManagerMon 
{

	private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;  //由於每個月第一天不是固定的頻率,因此設置爲天天某個時間
	private ServletContext servletContext = null;

	public TimerManagerMon(ServletContext context)
	{
		this.servletContext = context;
		// 獲取配置中的時間信息
		String hour = this.servletContext.getInitParameter("hour");
		String minute = this.servletContext.getInitParameter("minute");

		// 安排指定的任務 在指定的時間 執行
		UserMsgTimerTask2 dataTask = new UserMsgTimerTask2();

		// 判斷時間
		Date d = new Date();// 獲取服務器的時間。。。
		Calendar c = Calendar.getInstance();
		Timer timer = new Timer();
		c.setTime(d);

		//設置定時器的啓動時間
		if (c.get(Calendar.DAY_OF_MONTH) == 1) // 當前是1號
		{
			if (c.get(Calendar.HOUR_OF_DAY) == 0 && c.get(Calendar.MINUTE) == 0) 
			{
				timer.scheduleAtFixedRate(dataTask, c.getTime(), PERIOD_DAY); // 天天執行一次run()方法...
			} 
			else 
			{
				// 下月一號開始
				c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);    // 設置爲下月
				c.set(Calendar.DAY_OF_MONTH, 1);					 // 設置爲下月的1號
				c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));  //定製每日00:00點執行方法
				c.set(Calendar.MINUTE, Integer.valueOf(minute));
				timer.scheduleAtFixedRate(dataTask, c.getTime(), PERIOD_DAY); // 天天執行一次run()方法...
			}
		} 
		else // 當前不是1號 則從下個月1號開始執行按期任務
		{
			c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);     // 設置爲下月
			c.set(Calendar.DAY_OF_MONTH, 1);					  // 設置爲下月的1號
			c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));   //定製每日00:00點執行方法
			c.set(Calendar.MINUTE, Integer.valueOf(minute));
			timer.scheduleAtFixedRate(dataTask, c.getTime(), PERIOD_DAY); // 天天執行一次run()方法...
		}
	}
}



package com.usermsgsync.time;

import java.util.TimerTask;

import com.usermsgsync.UserSyncMsg;

public class UserMsgTimerTask extends TimerTask 
{
	
	@Override
	public void run() 
	{
		try 
		{
			UserSyncMsg.deleteFilesDay(); //此方法必須放在生成當天文件前面,由於獲取java代碼獲取服務器時間並不能保證每次都能生成的是如出一轍的值
			UserSyncMsg.createFileDay();
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
		}
	}

}




package com.usermsgsync.time;

import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;

import com.usermsgsync.UserSyncMsg;

public class UserMsgTimerTask2 extends TimerTask 
{

	@Override
	public void run() 
	{
		try 
		{
			//在方法內部判斷是否爲每個月的第一天
			Date date = new Date(); //獲取服務器的時間
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			if (calendar.get(Calendar.DAY_OF_MONTH) == 1 )
			{
				UserSyncMsg.createFileMon();		
			}
		}
		catch (Exception e) 
		{
			// TODO: handle exception
		}
	}

}


8.  在web.xml中的配置 this

<!--生成增量同步文件監聽器 -->
	<listener>
		<listener-class>
			com.usermsgsync.servlet.ContextListener
		</listener-class>
	</listener>
	<!--一天一次增量同步 時間設置 -->
	<context-param>
		<param-name>hour</param-name>
		<param-value>0</param-value>
	</context-param>
	<context-param>
		<param-name>minute</param-name>
		<param-value>0</param-value>
	</context-param>


9. properties文件

userSyncMsg_VersionNo = V010
userSyncMsg_PlatformID = 000011
userSyncMsg_InterfaceNo = 01

userSyncMsg_FTP_IP = 211.94.123.188
userSyncMsg_FTP_port = 21
userSyncMsg_FTP_userName = Beau Virgill
userSyncMsg_FTP_passWord = Beau Virgill

userSyncMsg_FTP_RequestDir = //home//V010//01//000011
userSyncMsg_FTP_ReturnDir = //home//V010//01//000011//RSP


相關業務規範以下(截圖):

相關文章
相關標籤/搜索