1. 程式人生 > >定時任務,定時下載FTP指定檔案

定時任務,定時下載FTP指定檔案

FTP下載類:

package com.log.generateXML.util;>

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.log.generateXML.dao.LogTableDao;
import com.log.generateXML.dao.impl.LogTableDaoImpl;
import com.novomss.idc.entity.FtpDownloadLog;


/***
 * 功能描述:FTP下載檔案類
 * 定時任務配置applicationContext-idc-uploadTimer.xml
 * 
 */
public class DownLoadXML {

	private LogTableDao lts;
	// 日誌記錄物件
	private final Log log = LogFactoryImpl.getLog(DownLoadXML.class);

	// Xmls下載日誌記錄
	private FtpDownloadLog ftpdown ;
	// FTP主機
	private String ftpHost = null;
	// FTP連線埠
	private String port = null;
	private int ftpPort ;
	// FTP連線使用者
	private String ftpuser = null;
	// FTP使用者密碼
	private String ftppasswd = null;
	// FTP下載描述
	private String descript ;
	// FTP上傳成功與否狀態
	private int status;
	
	// 假定錯誤值
	/***
	 * 1 FTP登陸狀態失敗
	 * 2 FTP目錄設定錯誤
	 * 3 FTP工作路徑切換失敗
	 * 4 要下載的檔案不存在
	 */
	private int flag;
	
	/****
	 * FTP下載
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public boolean ftpDownload(String filename) throws Exception {
		
		// 如果引數為空,直接返回提示
		if(filename==null || filename ==""){
			log.info( "filename is null.");
			return false;
		}
		// 儲存檔案路徑
		String downsavefilePath = FtpConfig.getValue("localDir"); // 本地儲存目錄
		if(downsavefilePath == null || downsavefilePath.length() == 0){
			log.info("本地儲存目錄屬性未設定!");
			return false;
		}
		File downfilePath = new File(downsavefilePath);
		if(!downfilePath.exists()&&!downfilePath.isDirectory()){
			log.info("本地下載檔案儲存路徑不存在!");
			return false;
		}
		
		// 下載檔名
		File file = new File(filename);
		
		// 例項化FTP客戶端物件
		FTPClient ftp = new FTPClient();
		// 伺服器連線狀態
		int reply = 0;
		try {
			
			// 如果FTP未連線則連線伺服器
			if (!ftp.isConnected()) {
				// 設定連線屬性
				ftpHost = FtpConfig.getValue("ftpHost");	
				port = FtpConfig.getValue("ftpPort");	
				ftpPort = Integer.parseInt(port);
				// 連線伺服器
				ftp.connect(ftpHost,ftpPort);
				log.info("連線ftp伺服器:" + ftpHost);
				// 連線伺服器狀態
				reply = ftp.getReplyCode();
				log.info("連線ftp伺服器reply:" + reply);
			}
			// 登陸伺服器,判斷是否登陸成功
			ftpuser = FtpConfig.getValue("userName");
			ftppasswd = FtpConfig.getValue("password");
			boolean isLogin = ftp.login(ftpuser,ftppasswd);	//	登陸FTP使用者名稱、密碼
			//log.info("登入ftp伺服器isLogin:" + isLogin);
			if(!isLogin){
				log.info("登陸FTP失敗");
				flag = 1;
			}else{ log.info("登陸FTP已成功"); }
			
			// 獲取FTP工作目錄
			String workDir = FtpConfig.getValue("workDir");
			if (workDir == null){
				log.info("workdir is null.");
				flag = 2;
			}
			
			// 上傳目錄
			String uploadDir = "";
			// 拼接FTP工作路徑
			uploadDir += "" + workDir;
			// 切換當前工作路徑,更改FTP連線位置
			boolean change = ftp.changeWorkingDirectory(uploadDir);
			if(change == false){
				log.info("changeWorkingDirectory: “"+uploadDir+"” failed.");
				flag=3;
			}
			log.info("切換工作路徑狀態:"+change);
			
			// 獲得下載開始時間
			long starTime = System.currentTimeMillis();
			
			// 初始化檔名,獲得當前目錄檔案
			String savedFileName = "";
			savedFileName = file.getName();
			if(savedFileName==null || savedFileName.length()==0){
				log.info("get file “"+savedFileName+"” failed.");
				flag=4;
			}
			
			/*//驗證伺服器端檔案是否存在
			FileOutputStream fos = new FileOutputStream(savedFileName);
			if(ftp.retrieveFile(filename, fos)){
				log.info("伺服器端檔案已驗證存在:");
			}else {
				flag=4;
				log.info("要下載的檔案伺服器端不存在:");
			}*/
			
			// 檔案流儲存路徑
			File tempFile = new File(downsavefilePath+"temp_"+savedFileName);
			File destFile = new File(downsavefilePath+savedFileName);
			
			//輸出流,輸出檔案內容到臨時檔案
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile));
			
			// 設定檔案型別
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setBufferSize(4 * 1048);
			ftp.setControlEncoding("GB2312");
			ftp.enterLocalPassiveMode();
			
			// 下載XML檔案,從伺服器檢索指定檔案savedFileName,並寫入BufferedOutputStream
			boolean download = ftp.retrieveFile(savedFileName, bos);
			
			// 當前FTP狀態
			reply = ftp.getReplyCode();
			bos.close();
			log.info("檔案下載:" + download + "時間為:"+ (System.currentTimeMillis() - starTime) + "ms");
			
			//儲存檔案到指定目標目錄
			if(download){
				if(destFile.exists())
					destFile.delete();
				tempFile.renameTo(destFile);
				status = 1;
				descript = "檔案下載成功!";
				log.info("檔案下載成功!");
			}else {
				tempFile.delete();
				status = 0;
				if(flag==1) descript="FTP登陸狀態失敗";
				if(flag==2) descript="FTP目錄設定錯誤";
				if(flag==3) descript="FTP工作路徑切換失敗";
				if(flag==4) descript="要下載的檔案不存在";
				log.info( "download: “"+destFile.getPath()+"” faild." );
			}
			
			//寫入成功日誌並加入告警
			
			lts = new LogTableDaoImpl();
			ftpdown = new FtpDownloadLog();
			
			ftpdown.setFilename(filename);
			ftpdown.setFtphost(ftpHost);
			ftpdown.setFtpport(Long.valueOf(port));
			ftpdown.setFtpuser(ftpuser);
			ftpdown.setFtppasswd(ftppasswd);
			ftpdown.setLocaldir(downsavefilePath);
			ftpdown.setWorkdir(workDir);
			ftpdown.setDescript(descript);
			ftpdown.setStatus(Long.valueOf(status));
			
			boolean flag = lts.saveFtpDownLog(ftpdown);
			if(flag)
				log.info("寫入日誌成功!");
			
			log.info("接收下載檔案的引數:"+ftpdown.getFilename());
			
			//下載失敗返回false
			if(status==0)
				return false;
			// 判斷FTP連線性
			if (!FTPReply.isPositiveCompletion(reply)) {
				System.err.println("FTP server reply." + reply);
			}
			// 退出登陸
			ftp.logout();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} finally {
			ftp.disconnect();	// 釋放FTP連線
		}
		return true;
	}
	
	/*public static void main(String[] args) throws Exception{
		
		DownLoadXML dlx = new DownLoadXML();
		String filename =  "20121119999.xml-";
		boolean a = dlx.ftpDownload(filename);
		System.out.println("返回:"+a);
	}*/
	
	public LogTableDao getLts() {
		return lts;
	}
	public void setLts(LogTableDao lts) {
		this.lts = lts;
	}
	
}

定時任務配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<!-- 定時上傳-->
	<bean id="uploadTimer" class="com.generatexml.UploadTimer">
		<property name="generator" ref="generator" />
	</bean>
	
	<!-- 定時下載-->
	<bean id="downloadTimer" class="com.log.generateXML.DownloadTimer">
	</bean>

	<!-- 定時處理計費資料業務方法 -->
	<bean id="ccTimer"
		class="com.timer.CalcChargeTimer">
		<!-- 注入方法,引用 -->
	</bean>

	<!-- 定時排程 -->
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
		<property name="triggers">
		 	<list>
				<ref local="loadTask"/>
				<ref local="loadCc" />
				<ref local="ddownTask"/>
			</list>
		</property>
	</bean>
	
	<bean id="loadTask" class="org.springframework.scheduling.quartz.CronTriggerBean">        
		<property name="jobDetail"><ref bean="jobTask"/></property>        
		<property name="cronExpression">
			<!--<value>0 0/2 * * * ?</value>-->
			 <value>0 10 0 * * ?</value>
		</property>
	</bean>
	
	<bean id="jobTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!--具體執行類 -->        
		<property name="targetObject" ref="uploadTimer" />
		<!--執行類的方法名稱-->  
		<property name="targetMethod"><value>run</value></property>
	</bean>
	<!-- XML定時 呼叫檔案下載方法 -->
	<bean id="downTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!--具體執行類 -->        
		<property name="targetObject" ref="downloadTimer" />
		<!--執行類的方法名稱-->  
		<property name="targetMethod"><value>down</value></property>
	</bean>
	
	<!-- XML定時任務時間配置  秒 分 時 * * ? 每天幾點幾分執行 -->
	<bean id="ddownTask" class="org.springframework.scheduling.quartz.CronTriggerBean">        
		<property name="jobDetail"><ref bean="downTask"/></property>        
		<property name="cronExpression">
			<!--<value>0 0/2 * * * ?</value>-->
			 <value>0 0 2 * * ?</value>
		</property>
	</bean>
	
	<!-- 任務執行,執行日期   1秒  2分  3時  4日   5月   6星期幾 1-7 or SUN  7年份 -->
	<bean id="loadCc" class="org.springframework.scheduling.quartz.CronTriggerBean">        
		<property name="jobDetail"><ref bean="jobCc"/></property>
		<property name="cronExpression">
			 <value>0 0 1 1 * ?</value>
		</property>
	</bean>
	
	<bean id="jobCc" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject"><ref bean="ccTimer"/></property><!--具體執行類 -->
		<property name="targetMethod"><value>operatorData</value></property> <!--執行類的方法名稱-->
	</bean>
	
</beans>