ftp quartz angular

package com.ceair.api;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;

@Controller
public class ApiContorller {
	private Logger LOG = LoggerFactory.getLogger(ApiContorller.class) ;
	
	private static final String srcServer = PropertiesUtils.getProperty("src.server") ; 
	private static final String srcUser = PropertiesUtils.getProperty("src.user") ;
	private static final String srcPassword = PropertiesUtils.getProperty("src.password") ;
	private static final String srcPath = PropertiesUtils.getProperty("src.path") ;
	private static final String destServer = PropertiesUtils.getProperty("dest.server") ;
	private static final String destUser = PropertiesUtils.getProperty("dest.user") ;
	private static final String destPassword = PropertiesUtils.getProperty("dest.password") ;
	private static final String destPath = PropertiesUtils.getProperty("dest.path") ;
	private static final String localFtpFilesDirectory = PropertiesUtils.getProperty("local.ftp.files.directory") ;  
	

	@RequestMapping(value = "home")
	public String homeWeb() { 
		return "home";
	} 

	@RequestMapping(value = "/getAllFile",  produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public  JSONObject getAllFile() throws SocketException, IOException{
		 FtpUtil srcFftpUtil = new FtpUtil();  
		 srcFftpUtil.connectServer(srcServer, FTPClient.DEFAULT_PORT, srcUser, srcPassword, null) ;  
		 List<String> srcFiles = srcFftpUtil.getFileList(srcPath) ;  
		 srcFftpUtil.closeServer(); 
		 
		 FtpUtil destFftpUtil = new FtpUtil();  
		 destFftpUtil.connectServer(destServer, FTPClient.DEFAULT_PORT, destUser, destPassword, null) ;  
		 List<String> destFiles = destFftpUtil.getFileList(destPath);
		 destFftpUtil.closeServer();
		 Set<String> destFileSet = new HashSet<String>(destFiles) ;
		 
		 List<FileRecord> fileRecords = Lists.newArrayList() ;
		 Long notInSize = 0L ;
		 Long canUploadSize = 0L ;
		 Long notInCanUploadSize = 0L ; 
		 JSONObject result = new JSONObject() ; 
		 for(String srcFile : srcFiles){
			 FileRecord fileRecord = new FileRecord() ;
			 fileRecord.setSrcFileName(srcFile);
			 
			 if(srcFile.contains("AETLK78120")){
				 fileRecord.setCanUpload(Boolean.FALSE);
			 }
			 else{ 
				 if(srcFile.substring(8, 14).compareTo("171209") >= 0){
					 fileRecord.setCanUpload(Boolean.TRUE);
					 canUploadSize++ ;
				 }
				 else{
					 fileRecord.setCanUpload(Boolean.FALSE); 
				 }
			 } 
			 
			 if(destFileSet.contains(srcFile)){ 
				 fileRecord.setDestExisted(Boolean.TRUE);
			 }
			 else{
				 notInSize++ ;  
				 if((!srcFile.contains("AETLK78120")) && (srcFile.substring(8, 14).compareTo("171209") >= 0)){
					 notInCanUploadSize++ ;
				 }
				 fileRecord.setDestExisted(Boolean.FALSE);
			 } 
			 fileRecords.add(fileRecord) ;
		 } 
		 Collections.sort(fileRecords) ;
		 result.put("fileRecords", fileRecords) ;
		 result.put("notInSize", notInSize) ;
		 result.put("canUploadSize", canUploadSize) ;
		 result.put("notInCanUploadSize", notInCanUploadSize) ;
		 return result ;
	}  
	
	@RequestMapping(value="/downloadFileByName" )
	public void downloadFileByName(
			       @RequestParam("fileName") String fileName, 
			       HttpServletRequest request , 
			       HttpServletResponse response) throws SocketException, IOException  {
		 FtpUtil ftpUtil=new FtpUtil();  
		 ftpUtil.connectServer(srcServer, FTPClient.DEFAULT_PORT, srcUser, srcPassword, srcPath) ;  
		 String localFilePath = localFtpFilesDirectory + File.separator + fileName ;
		 if(ftpUtil.download(fileName , localFilePath)){
				File file = new File(localFilePath) ;
				if(!file.exists()){
					String errorMessage = "Sorry. The file you are looking for does not exist";
					OutputStream outputStream = response.getOutputStream();
					outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
					outputStream.close();
					return;
				}
		
				String mimeType = URLConnection.guessContentTypeFromName(file.getName());
				if (Strings.isNullOrEmpty(mimeType)) {
					mimeType = "application/octet-stream";
				}
				response.setContentType(mimeType);
				response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));
				response.setContentLength((int) file.length());
				InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
				FileCopyUtils.copy(inputStream, response.getOutputStream());
		 } 
		 else{
			 String errorMessage = "Sorry. The file you are looking for does not exist";
			 OutputStream outputStream = response.getOutputStream();
			 outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
			 outputStream.close();
			 return;
		 }
	}  
	
	@RequestMapping(value = "/uploadFile",  produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public  List<Record> uploadFile(@RequestParam("fileName") String fileName , HttpServletRequest request){
		 try{
			 FtpUtil srcFftpUtil = new FtpUtil();  
			 srcFftpUtil.connectServer(srcServer, FTPClient.DEFAULT_PORT, srcUser, srcPassword, srcPath) ;  
			 String localFilePath = localFtpFilesDirectory + File.separator + fileName ;
			 if(srcFftpUtil.download(fileName , localFilePath)){
				 srcFftpUtil.closeServer();
				 FtpUtil destFftpUtil = new FtpUtil();  
				 destFftpUtil.connectServer(destServer, FTPClient.DEFAULT_PORT, destUser, destPassword, destPath) ;  
				 destFftpUtil.uploadFile(localFilePath, fileName) ;
				 destFftpUtil.closeServer();
				 RecordDao.readOrWrite(RecordDao.WRITE , fileName , RecordDao.MAN_SECCESS) ; 
			}
		 }catch(IOException  e){
			 RecordDao.readOrWrite(RecordDao.WRITE , fileName , RecordDao.MAN_FAILED) ; 
		} 
		return RecordDao.readOrWrite(RecordDao.READ, null, null) ;
	} 
	
	@RequestMapping(value = "/getRecords",  produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public  List<Record> getRecords(){
		return RecordDao.readOrWrite(RecordDao.READ, null, null) ;
	} 
	
	@RequestMapping(value = "/removeDirectory",  produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public  Boolean removeDirectory(@RequestParam("fileName") String fileName){
		 Boolean result = Boolean.FALSE ;
		 FtpUtil destFftpUtil = new FtpUtil();  
		 try {
			destFftpUtil.connectServer(destServer, FTPClient.DEFAULT_PORT, destUser, destPassword, destPath) ;
			result = destFftpUtil.removeDirectory(fileName) ;
			destFftpUtil.closeServer();
		 } catch (Exception e) {
			 LOG.error(e.getMessage()) ;
		} 
		return result ; 
	}  
	
}

package com.ceair.api;

public class FileRecord implements Comparable<FileRecord>{
	private String srcFileName ;
	private Boolean destExisted ;
	private Boolean canUpload ;

	@Override
	public int compareTo(FileRecord other) { 
		if(this.srcFileName.length() != other.srcFileName.length()){
			return Integer.compare(this.srcFileName.length() , other.srcFileName.length()) ;
		}
		else{
			return other.srcFileName.compareTo(this.srcFileName) ;
		}
	}

	public String getSrcFileName() {
		return srcFileName;
	}

	public void setSrcFileName(String srcFileName) {
		this.srcFileName = srcFileName;
	}

	public Boolean getDestExisted() {
		return destExisted;
	}

	public void setDestExisted(Boolean destExisted) {
		this.destExisted = destExisted;
	}
 
	public FileRecord() {
		super();
	}

	public Boolean getCanUpload() {
		return canUpload;
	}

	public void setCanUpload(Boolean canUpload) {
		this.canUpload = canUpload;
	} 
}

package com.ceair.api;

public class FtpConfig {  
    //服务器地址名称  
    private String server;  
    //端口号  
    private int port;  
    //用户名称  
    private String username;  
    //密码  
    private String password;  
    //工作目录  
    private String location;  
     
    public String getServer() {  
        return server;  
    }  
  
    public void setServer(String server) {  
        this.server = server;  
    }  
  
    public int getPort() {  
        return port;  
    }  
  
    public void setPort(int port) {  
        this.port = port;  
    }  
  
    public String getUsername() {  
        return username;  
    }  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
    public String getPassword() {  
        return password;  
    }  
  
    public void setPassword(String password) {  
        this.password = password;  
    }  
  
    public String getLocation() {  
        return location;  
    }  
  
    public void setLocation(String location) {  
        this.location = location;  
    }  
}  


package com.ceair.api; 

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

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
public class FtpUtil {  
	private Logger LOG = LoggerFactory.getLogger(FtpUtil.class) ;
    private FTPClient ftpClient;  
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;  
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;  
      
    /**
     * 利用FtpConfig进行服务器连接
     * @param ftpConfig 参数配置Bean类
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(FtpConfig ftpConfig) throws SocketException,  
            IOException {  
        String server = ftpConfig.getServer();  
        int port = ftpConfig.getPort();  
        String user = ftpConfig.getUsername();  
        String password = ftpConfig.getPassword();  
        String location = ftpConfig.getLocation();  
        connectServer(server, port, user, password, location);  
    }  
      
    /**
     * 使用详细信息进行服务器连接
     * @param server:服务器地址名称
     * @param port:端口号
     * @param user:用户名
     * @param password:用户密码
     * @param path:转移到FTP服务器目录 
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(String server, int port, String user,  
            String password, String path) throws SocketException, IOException {  
        ftpClient = new FTPClient();  
        ftpClient.connect(server, port);  
        LOG.info("Connected to " + server + ".");  
        ftpClient.login(user, password);  
        if (path!=null&&path.length() != 0) {  
            ftpClient.changeWorkingDirectory(path);  
        }  
    	ftpClient.setBufferSize(1024);//设置上传缓存大小
    	ftpClient.setControlEncoding("UTF-8");//设置编码
    	ftpClient.setFileType(BINARY_FILE_TYPE);//设置文件类型
    	ftpClient.setRemoteVerificationEnabled(false);
    }  
    
    /**
     * 设置传输文件类型:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE  
     * 二进制文件或文本文件
     * @param fileType
     * @throws IOException
     */
    public void setFileType(int fileType) throws IOException {  
        ftpClient.setFileType(fileType);  
    }  
  
    /**
     * 关闭连接
     * @throws IOException
     */
    public void closeServer() throws IOException {  
        if (ftpClient!=null&&ftpClient.isConnected()) {  
        	ftpClient.logout();//退出FTP服务器 
            ftpClient.disconnect();//关闭FTP连接 
        }  
    }
    
    /**
     * 转移到FTP服务器工作目录
     * @param path
     * @return
     * @throws IOException
     */
    public boolean changeDirectory(String path) throws IOException {  
        return ftpClient.changeWorkingDirectory(path);  
    }  
    
    /**
     * 在服务器上创建目录
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean createDirectory(String pathName) throws IOException {  
        return ftpClient.makeDirectory(pathName);  
    }  
    
    /**
     * 在服务器上删除目录
     * @param path
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path) throws IOException {  
        return ftpClient.removeDirectory(path);  
    }  
      
    /**
     * 删除所有文件和目录
     * @param path
     * @param isAll true:删除所有文件和目录
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path, boolean isAll)  
            throws IOException {  
          
        if (!isAll) {  
            return removeDirectory(path);  
        }  
  
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);  
        if (ftpFileArr == null || ftpFileArr.length == 0) {  
            return removeDirectory(path);  
        }  
        //   
        for (FTPFile ftpFile : ftpFileArr) {  
            String name = ftpFile.getName();  
            if (ftpFile.isDirectory()) {  
            	System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");               
                removeDirectory(path + "/" + name, true);  
            } else if (ftpFile.isFile()) {  
            	System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                          
                deleteFile(path + "/" + name);  
            } else if (ftpFile.isSymbolicLink()) {  
  
            } else if (ftpFile.isUnknown()) {  
  
            }  
        }  
        return ftpClient.removeDirectory(path);  
    }  
    
    /**
     * 检查目录在服务器上是否存在 true:存在  false:不存在
     * @param path
     * @return
     * @throws IOException
     */
    public boolean existDirectory(String path) throws IOException {  
        boolean flag = false;  
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);  
        for (FTPFile ftpFile : ftpFileArr) {  
            if (ftpFile.isDirectory()  
                    && ftpFile.getName().equalsIgnoreCase(path)) {  
                flag = true;  
                break;  
            }  
        }  
        return flag;  
    }  
  
    /**
     * 得到文件列表,listFiles返回包含目录和文件,它返回的是一个FTPFile数组
     * listNames():只包含目录的字符串数组
     * String[] fileNameArr = ftpClient.listNames(path); 
     * @param path:服务器上的文件目录:/DF4
     */
    public List<String> getFileList(String path) throws IOException {  
        FTPFile[] ftpFiles= ftpClient.listFiles(path);  
        //通过FTPFileFilter遍历只获得文件
/*      FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
			@Override
			public boolean accept(FTPFile ftpFile) {
				return ftpFile.isFile();
			}
		});  */
        List<String> retList = new ArrayList<String>();  
        if (ftpFiles == null || ftpFiles.length == 0) {  
            return retList;  
        }  
        for (FTPFile ftpFile : ftpFiles) {  
            if (ftpFile.isFile()) {  
                retList.add(ftpFile.getName());  
            }  
        }  
        return retList;  
    }  
  
    /**
     * 删除服务器上的文件
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean deleteFile(String pathName) throws IOException {  
        return ftpClient.deleteFile(pathName);  
    }  
  
    /**
     * 上传文件到ftp服务器
     * 在进行上传和下载文件的时候,设置文件的类型最好是:
     * ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE)
     * localFilePath:本地文件路径和名称
     * remoteFileName:服务器文件名称
     */
    public boolean uploadFile(String localFilePath, String remoteFileName)  
            throws IOException {  
        boolean flag = false;  
        InputStream iStream = null;  
        try {  
            iStream = new FileInputStream(localFilePath);  
            //我们可以使用BufferedInputStream进行封装
            //BufferedInputStream bis=new BufferedInputStream(iStream);
            //flag = ftpClient.storeFile(remoteFileName, bis); 
            flag = ftpClient.storeFile(remoteFileName, iStream);  
        } catch (IOException e) {  
            flag = false;  
            return flag;  
        } finally {  
            if (iStream != null) {  
                iStream.close();  
            }  
        }  
        return flag;  
    }  
  
    /**
     * 上传文件到ftp服务器,上传新的文件名称和原名称一样
     * @param fileName:文件名称
     * @return
     * @throws IOException
     */
    public boolean uploadFile(String fileName) throws IOException {  
        return uploadFile(fileName, fileName);  
    }  
  
    /**
     * 上传文件到ftp服务器
     * @param iStream 输入流
     * @param newName 新文件名称
     * @return
     * @throws IOException
     */
    public boolean uploadFile(InputStream iStream, String newName)  
            throws IOException {  
        boolean flag = false;  
        try {  
            flag = ftpClient.storeFile(newName, iStream);  
        } catch (IOException e) {  
            flag = false;  
            return flag;  
        } finally {  
            if (iStream != null) {  
                iStream.close();  
            }  
        }  
        return flag;  
    }  
  
    /**
     * 从ftp服务器上下载文件到本地
     * @param remoteFileName:ftp服务器上文件名称
     * @param localFileName:本地文件名称
     * @return
     * @throws IOException
     */
    public boolean download(String remoteFileName, String localFileName)  
            throws IOException {  
        boolean flag = false;  
        File outfile = new File(localFileName);  
        OutputStream oStream = null;  
        try {  
            oStream = new FileOutputStream(outfile);  
            //我们可以使用BufferedOutputStream进行封装
         	//BufferedOutputStream bos=new BufferedOutputStream(oStream);
         	//flag = ftpClient.retrieveFile(remoteFileName, bos); 
            flag = ftpClient.retrieveFile(remoteFileName, oStream);  
        } catch (IOException e) {  
            flag = false;  
            return flag;  
        } finally {  
            oStream.close();  
        }  
        return flag;  
    }  
      
    /**
     * 从ftp服务器上下载文件到本地
     * @param sourceFileName:服务器资源文件名称
     * @return InputStream 输入流
     * @throws IOException
     */
    public InputStream downFile(String sourceFileName) throws IOException {  
        return ftpClient.retrieveFileStream(sourceFileName);  
    }  
    
}

package com.ceair.api;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

public class FtpUploadQuartz {
	private Logger LOG = LoggerFactory.getLogger(FtpUtil.class) ;
	private static final String srcServer = PropertiesUtils.getProperty("src.server") ; 
	private static final String srcUser = PropertiesUtils.getProperty("src.user") ;
	private static final String srcPassword = PropertiesUtils.getProperty("src.password") ;
	private static final String srcPath = PropertiesUtils.getProperty("src.path") ;
	private static final String destServer = PropertiesUtils.getProperty("dest.server") ;
	private static final String destUser = PropertiesUtils.getProperty("dest.user") ;
	private static final String destPassword = PropertiesUtils.getProperty("dest.password") ;
	private static final String destPath = PropertiesUtils.getProperty("dest.path") ;
	private static final String localFtpFilesDirectory = PropertiesUtils.getProperty("local.ftp.files.directory") ;  
	
	public void refrshFtpUpload(){ 
	   List<String> toUploadFiles = Lists.newArrayList() ;
	   try{
		 FtpUtil srcFftpUtil = new FtpUtil();  
		 srcFftpUtil.connectServer(srcServer, FTPClient.DEFAULT_PORT, srcUser, srcPassword, null) ;  
		 List<String> srcFiles = srcFftpUtil.getFileList(srcPath) ;  
		 srcFftpUtil.closeServer(); 
		 
		 FtpUtil destFftpUtil = new FtpUtil();  
		 destFftpUtil.connectServer(destServer, FTPClient.DEFAULT_PORT, destUser, destPassword, null) ;  
		 List<String> destFiles = destFftpUtil.getFileList(destPath);
		 destFftpUtil.closeServer();
		 Set<String> destFileSet = new HashSet<String>(destFiles) ;
		 for(String srcFile : srcFiles){  
			 if(srcFile.contains("AETLK78120")){
				 continue ;
			 } 
			 if((srcFile.substring(8, 14).compareTo("171209") >= 0) && (! destFileSet.contains(srcFile))){ 
				 toUploadFiles.add(srcFile) ;
			 }
		 }
	   }catch(IOException e){
		   LOG.error(e.getMessage()) ;
	   }
	   
	   LOG.info("toUploadFiles:" + toUploadFiles) ;
	   
	   for(String fileName : toUploadFiles){
		     FtpUtil destFftpUtil = null , srcFftpUtil = null ; 
			 try{
				 destFftpUtil = new FtpUtil();  
				 destFftpUtil.connectServer(destServer, FTPClient.DEFAULT_PORT, destUser, destPassword, destPath) ;  
				 if(destFftpUtil.existDirectory(fileName)){
					 destFftpUtil.closeServer();
					 continue ;
				 }
				 srcFftpUtil = new FtpUtil();  
				 srcFftpUtil.connectServer(srcServer, FTPClient.DEFAULT_PORT, srcUser, srcPassword, srcPath) ;  
				 String localFilePath = localFtpFilesDirectory + File.separator + fileName ;
				 if(srcFftpUtil.download(fileName , localFilePath)){
					 srcFftpUtil.closeServer(); 
					 destFftpUtil.uploadFile(localFilePath, fileName) ;
					 destFftpUtil.closeServer();
					 RecordDao.readOrWrite(RecordDao.WRITE , fileName , RecordDao.AUTO_SECCESS) ; 
				}
			 }catch(IOException  e){
				 RecordDao.readOrWrite(RecordDao.WRITE , fileName , RecordDao.AUTO_FAILED) ; 
			 }
			 finally{
				 if(srcFftpUtil != null){
					 try {
						srcFftpUtil.closeServer() ;
					} catch (IOException e) {
					} 
				 }
				 if(destFftpUtil != null){
					 try {
						destFftpUtil.closeServer() ;
					} catch (IOException e) {
					} 
				 }
			 }
			 
			 try {
				Thread.sleep(3000) ;
			 } catch (InterruptedException e){
			 }
	   } 
	}

}


package com.ceair.api;	

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
  
public class PropertiesUtils extends PropertyPlaceholderConfigurer {  
	private static final Logger logger = Logger.getLogger(PropertiesUtils.class);  
  
    private static final Map<String, String> map = new HashMap<String, String>() ;   
    private static final String localFtpFilesDirectory = "local.ftp.files.directory" ; 
  
    @Override  
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) {  
        super.processProperties(beanFactory, props) ;  
    	for (Object key : props.keySet()) {  
            String keyStr = key.toString().replace(" ", "") ;  
            String value = props.getProperty(keyStr).replace(" ", "") ;  
            logger.info(key+"="+value);
            map.put(keyStr, value) ;  
            if(localFtpFilesDirectory.equals(keyStr)){ 
            	  File file =new File(value);    
                  if(!file.exists()  && !file.isDirectory()){     
                      file.mkdirs();    
                  } 
            }
        }  
    }  
      
    public static String getProperty(String key) {  
        return map.get(key);  
    }  
      
}  

package com.ceair.api;

import com.alibaba.fastjson.JSONObject;

public class Record implements Comparable<Record>{
	private String fileName ;
	private String time ;
	private String status ; 
	public Record() {
		super();
	}
	public Record(String fileName, String time, String status) {
		super();
		this.fileName = fileName;
		this.time = time;
		this.status = status;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getTime() {
		return time;
	}
	public void setTime(String time) {
		this.time = time;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	} 
	@Override
	public String toString() { 
		return JSONObject.toJSONString(this) ;
	}
	@Override
	public int compareTo(Record other) { 
		return other.getTime().compareTo(this.getTime()) ;
	}
}

package com.ceair.api;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

public class RecordDao {
	private static final DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") ;
	private static final String recordFilePath = PropertiesUtils.getProperty("record.file.path") ;  
	
	public static final int READ = 0 ;
	public static final int WRITE = 1 ;
	public static final String AUTO_SECCESS = "自动同步,成功!" ; 
	public static final String AUTO_FAILED = "自动同步,失败!" ;   
	public static final String MAN_SECCESS = "强制同步,成功!" ; 
	public static final String MAN_FAILED = "强制同步,失败!" ;  
	
	public static synchronized List<Record> readOrWrite(int type , String fileName , String status) {
		List<Record> records = Lists.newArrayList() ;
		try{ 
			if(type == RecordDao.READ){
				@SuppressWarnings("resource")
				Scanner in = new Scanner(new File(recordFilePath)) ;
				while(in.hasNext()){
					String line = in.nextLine() ; 
					Record record = JSON.parseObject(line, Record.class) ;
					records.add(record) ;
				}
				Collections.sort(records);
			}
			else{
				FileWriter writer = null;   
			    writer = new FileWriter(recordFilePath, true);     
			    String time = LocalDateTime.now().format(dateTimeFormatter);
			    writer.write(new Record(fileName, time, status).toString());
			    writer.write("\n");
			    writer.close();     
			}
		}catch(IOException e){ 
		}
		return records ; 
	}  
	
}

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
			    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
			    http://www.springframework.org/schema/tx    
			    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   
			    http://www.springframework.org/schema/context   
			    http://www.springframework.org/schema/context/spring-context-4.0.xsd   
			    http://www.springframework.org/schema/mvc   
			    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
			    http://www.springframework.org/schema/task
			    http://www.springframework.org/schema/task/spring-task-4.0.xsd
			    http://code.alibabatech.com/schema/dubbo            
			    http://code.alibabatech.com/schema/dubbo/dubbo.xsd">       
    <context:component-scan base-package="com.ceair" />
    <task:annotation-driven/> 
    <mvc:annotation-driven/>
	<mvc:default-servlet-handler/>


	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="page/app/html/" />
		<property name="suffix" value=".html" />
	</bean>

	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
				p:supportedMediaTypes="*/*" />
		</mvc:message-converters>
	</mvc:annotation-driven>

	<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
	
	
    <bean id="propertyConfigurer" class="com.ceair.api.PropertiesUtils">
		<property name="locations">
			<list>
				<value>classpath:app.properties</value>
			</list>
		</property>
	</bean>
	

     <bean id="SpringQtzJob" class="com.ceair.api.FtpUploadQuartz"/>  
		    <bean id="SpringQtzJobMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
		    <property name="targetObject">  
		        <ref bean="SpringQtzJob"/>  
		    </property>  
		    <property name="targetMethod">  
		        <value>refrshFtpUpload</value>  
		    </property>  
	 </bean>  
  

	<bean id="CronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
		    <property name="jobDetail" ref="SpringQtzJobMethod"></property>  
		    <property name="cronExpression" value="0 0/30 * * * ?"></property>  
	</bean>  
	  
	  
	<bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
		    <property name="triggers">  
		        <list>  
		            <ref bean="CronTriggerBean"/>  
		        </list>  
		    </property>  
	</bean>    


</beans>  


<!DOCTYPE html>
<html ng-app="home.controller">

	<head>

		<meta charset="utf-8">
		<title> Ftp Tool</title>

		<link href="page/common/css/bootstrap.min.css" rel="stylesheet">

		<script src="page/common/js/angular.js"></script>
		<script src="page/common/js/angular-animate.min.js"></script>
		<script src="page/common/js/angular-route.min.js"></script>
		<script src="page/common/js/ui-bootstrap-tpls.js"></script>
 
		<script src="page/app/js/home-controller.js"></script> 

		<style type="text/css">
			.login_header {
				background: url(./page/pictures/logo_idm.jpg) center left no-repeat;
				width: 100%;
				height: 101px;
				margin-left: 40px;
			}
			.spinner {
			  left: 30% ;
			  width: 60px;
			  height: 60px;
			  background-color: #67CF22;
			 
			  margin: 100px auto;
			  -webkit-animation: rotateplane 1.2s infinite ease-in-out;
			  animation: rotateplane 1.2s infinite ease-in-out;
			}
			 
			@-webkit-keyframes rotateplane {
			  0% { -webkit-transform: perspective(120px) }
			  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
			  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
			}
			 
			@keyframes rotateplane {
			  0% {
			    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
			    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
			  } 50% {
			    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
			    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
			  } 100% {
			    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
			    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
			  }
			}
		</style>

	</head>

	<body ng-controller="homeCtrl">
		<div class="login_header">
		</div>

		<div>
	
			<div class="col-xs-7" >
				 <br>
				 <br>
				 <h2>10.1.2.56:21/LKDATA/DELKDOC_MU/ </h2>
				 <h4>文件总数:{{DELKDOC_MU_SIZE}}  未同步:{{notInSize}}</h4>
				 <h4>2017.12.09后文件总数:{{canUploadSize}}  未同步:{{notInCanUploadSize}}</h4>
				 <br>
				 <table class="table table-striped">  
			        <tbody class="row pre-scrollable">  
			            <tr>  				
			                <th>文件名称</th>   
			                <th>同步状态</th>
			                <th>补偿操作</th>
			            </tr>  
			            <tr ng-repeat="row in fileRecords">     
			                  <td>  
                                    <a href="" ng-click="downloadFileByName(row.srcFileName)">{{row.srcFileName}}</a>  
                              </td>  
                              <td ng-if="row.destExisted">  
                                  <font color="#009100">
                                    Yes
                                  </font>
                              </td>  
                              <td ng-if="!row.destExisted">  
                                  <font color="red">
                                    No  
                                  </font>
                              </td>  
                              <td ng-if="row.canUpload">  
                                    <a href="" ng-click="uploadFile(row.srcFileName)">强制补偿</a>  
                              </td> 
                              <td ng-if="!row.canUpload">  
                                            
                              </td> 
			            </tr>  
			        </tbody>  
    			</table>   
    			
			</div>
			
		 	<div class="col-xs-5">
		 	
				 <br>
				 <br>
				 
				 	<div class="panel panel-primary">
						<div class="panel-heading">
							<h3 class="panel-title">同步日志</h3>
						</div>
						<div class="panel-body" style="background: #000000"> 
							<div ng-repeat="row in records">
							    	    <font color="#FFFFF0">{{row.fileName}}</font>     
									<font color="#FFFFF0">{{row.time}}</font>     
									<font color="#FFFFF0">{{row.status}}</font> 
							</div>
						</div>
					</div> 
			     
			     
			</div>  
			
			
			
		</div>
		
		
	</body>

</html>


var app = angular.module("home.controller", []);

app.controller("homeCtrl" , ["$scope", '$http', '$q', '$location'  ,  function($scope, $http, $q , $location) {
    
    $scope.uploadFile = function(fileName){    
        var deferred = $q.defer();  
        $http.get("uploadFile?fileName=" + fileName)  
             .success(function(data) {  
                    deferred.resolve(data);   
                    $scope.records = data ;   
              })  
              .error(function(data) {  
                    deferred.reject(data);  
              }) ;  
        return deferred.promise;  
    };   
    
    $scope.getAllFile = function(){  
        var deferred = $q.defer();  
        $http.get("getAllFile")  
             .success(function(data) {  
                    deferred.resolve(data);  
                    $scope.fileRecords = data.fileRecords ;
                    $scope.DELKDOC_MU_SIZE = $scope.fileRecords.length  ;
                    $scope.canUploadSize = data.canUploadSize ;
                    $scope.notInCanUploadSize = data.notInCanUploadSize ;
                    $scope.notInSize = data.notInSize ; 
              })  
              .error(function(data) {  
                    deferred.reject(data);  
              }) ;  
        return deferred.promise;  
    };   
    
    $scope.getAllFile() ; 
    
    $scope.getRecords = function(){  
        var deferred = $q.defer();  
        $http.get("getRecords")  
             .success(function(data) {  
                    deferred.resolve(data);   
                    $scope.records = data ;   
              })  
              .error(function(data) {  
                    deferred.reject(data);  
              }) ;  
        return deferred.promise;  
    };  
    
    $scope.getRecords() ; 
    
    
    $scope.downloadFileByName = function (fileName) {  
        $http.get("downloadFileByName?fileName=" + fileName, { responseType: 'arraybuffer' })  
            .success(function (data, status, headers) {  
                var octetStreamMime = 'application/octet-stream';  
                var success = false;  
                headers = headers();  
                filename = fileName ;   
                var contentType = headers['content-type'] || octetStreamMime;  
                try {  
                    var blob = new Blob([data], { type: contentType });  
                    if (navigator.msSaveBlob)  
                        navigator.msSaveBlob(blob, filename);  
                    else {  
                        var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;  
                        if (saveBlob === undefined) throw "Not supported";  
                        saveBlob(blob, filename);  
                    }  
                    success = true;  
                } catch (ex) { }  
  
                if (!success) {  
                    var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;  
                    if (urlCreator) {  
                        var link = document.createElement('a');  
                        if ('download' in link) {  
                            try {  
                                var blob = new Blob([data], { type: contentType });  
                                var url = urlCreator.createObjectURL(blob);  
                                link.setAttribute('href', url);  
                                link.setAttribute("download", filename);  
                                var event = document.createEvent('MouseEvents');  
                                event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);  
                                link.dispatchEvent(event);  
                                success = true;  
                            } catch (ex) {  
                                console.log(ex);  
                            }  
                        }  
                        if (!success) {  
                            try {  
                                var blob = new Blob([data], { type: octetStreamMime });  
                                var url = urlCreator.createObjectURL(blob);  
                                window.location = url;  
                                success = true;  
                            } catch (ex) {  
                                console.log(ex);  
                            }  
                        }  
  
                    }  
                }  
  
                if (!success) {  
                    window.open(httpPath, '_blank', '');  
                }  
            })  
            .error(function (data, status) {  
                console.log("Request failed with status: " + status);  
                $scope.errorDetails = "Request failed with status: " + status;  
            });  
    };  
     

}]);


app.filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
}]);





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值