package CoreFS.UpLoadManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import CoreFS.SA01.CoreException;
import CoreFS.Util.StringUtils;

public class CoreFTPClient {   

    /**
     * 连接到服务器
     * @throws IOException 
    */
   public static FTPClient connectServer() throws IOException {
	   FTPClient ftpClient=null;
	   if (ftpClient == null) {
           int reply;
           try {               
                ftpClient=new FTPClient();
                ftpClient.setDefaultPort(StringUtils.port);
               // ftpClient.configure(getFtpConfig());
                ftpClient.connect(StringUtils.ip);
                ftpClient.login(StringUtils.userName, StringUtils.password);
                ftpClient.setDefaultPort(StringUtils.port);                
                reply = ftpClient.getReplyCode();

               if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    System.err.println("FTP server refused connection.");
                    ftpClient=null;
                    return null;
                }
            } catch (Exception e) {
            	//ftpClient.disconnect();
                
                ftpClient=null;
//                System.err.println("登录ftp服务器【"+StringUtils.ip+"】失败");                
//                e.printStackTrace();
                throw new CoreException("登录ftp服务器失败,请与管理员联系");
                //return false;
            }
            return ftpClient;
        }
       return ftpClient;
    }
   /**
    * 关闭连接
   */
  public static void closeConnect(FTPClient ftpClient){
      try{
          if(ftpClient!=null){
               ftpClient.logout();
               ftpClient.disconnect();
               ftpClient=null;
           }
       }catch(Exception e){
          throw new CoreException("关闭FTP连接异常"+e.getMessage());
       }
   }

    
    public static boolean createFiles(String path) throws IOException
    {
    	FTPClient ftpClient=null;
    	try {
    		ftpClient=connectServer();
    		if(ftpClient==null) return false;
			return createDir(ftpClient, path);
		} finally {
			closeConnect(ftpClient);
		}
    }
	/**
	 * 创建多层文件夹
	 * */
	private static boolean createDir(FTPClient ftpClient, String path)
			throws IOException {
		if (path == null || path == "" || ftpClient == null) {
			return false;
		}
		if (path.startsWith("/")) {
			path = path.substring(1, path.length());
		}
		String[] paths = path.split("/");
		String workPath = "/";
		for (int i = 0; i < paths.length; i++) {
			ftpClient.makeDirectory(paths[i]);
			workPath = workPath + "/" + paths[i];
			ftpClient.changeWorkingDirectory(workPath);
		}
		return true;
	}
	

	/**
	 * FTP上传单个文件
	 * @throws IOException 
	 */
	public static void Upload(byte[] b, String name, String path) throws IOException {
		FTPClient ftpClient=null;		
		FileInputStream fis = null;
		try {
			ftpClient=connectServer();
			if(ftpClient==null) return;
			ByteArrayInputStream stream = new ByteArrayInputStream(b);

			// 设置上传目录
			boolean bn = ftpClient.changeWorkingDirectory(path);
			if (!bn) {
				createDir(ftpClient, path);
			}
			ftpClient.setBufferSize(1024);
			ftpClient.setControlEncoding("GBK");
			// 设置文件类型（二进制）
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.storeFile(new String(name.getBytes("GBK"), "iso-8859-1"), stream);
		} catch (IOException e) {
			//e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally {
			IOUtils.closeQuietly(fis);
			closeConnect(ftpClient);
		}
	}

	/**
	 * FTP下载单个文件
	 * @throws IOException 
	 */
	public static byte[] Download(String path,String fileName) throws IOException {
		FTPClient ftpClient=null;
		
		InputStream is = null;
		byte[] bytess = null;
		try {
			ftpClient=connectServer();
			if(ftpClient==null) return null;
			boolean bn = ftpClient.changeWorkingDirectory(path);
			if (!bn) {
				return null;
			}
			// fos = new FileOutputStream("c:/down.gif");
			ftpClient.setBufferSize(1024);
			ftpClient.setControlEncoding("UTF-8");
			// 设置文件类型（二进制）
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);		
			is = ftpClient.retrieveFileStream(fileName);
			bytess = CoreUtil.toByteArray(is);
			is.close();
			Thread.sleep(50);
		} catch (Exception e) {
			//e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally {
			closeConnect(ftpClient);
		}
		return bytess;
	}
	 /**
     * 列出服务器上所有文件及目录
	 * @throws IOException 
    */
   @SuppressWarnings("unchecked")
public static void listAllRemoteFiles(String path,List directory) throws IOException{
	   FTPClient ftpClient=null;
	   try {
		   
		   ftpClient=connectServer();
		   if(ftpClient==null) return;
			ftpClient.changeWorkingDirectory(path);
			traverse(ftpClient, ftpClient.printWorkingDirectory(),"", directory);
		} finally {
			closeConnect(ftpClient);
		}
    }
   
   @SuppressWarnings("unchecked")
public static void traverse(FTPClient client,String path,String rootpath,List directory) {
	   
		String prefix = "";
		try {
			FTPFile[] files = client.listFiles(path);
			for (int i = 0; i < files.length; i++) {
				// 如果是文件夹就递归方法继续遍历
				if (files[i].isDirectory()) {
					/*
					 * 创建新目录时会自动创建两个文件名: . 和 .. 点指当前目录 点点指父目录
					 */
					// 注意这里的判断，否则会出现死循环
					if (!files[i].getName().equals(".")
							&& !files[i].getName().equals("..")) {
						String tempDir = StringUtils.mainPath+"/"+rootpath+"/"//client.printWorkingDirectory() + "/"
								+ files[i].getName();
						String temppath=tempDir.replace(StringUtils.mainPath, "");
						Map result=new ListOrderedMap();
						result.put("filename", files[i].getName());
						result.put("ftype", "directory");								
						result.put("path", temppath);						
						result.put("root", rootpath);
						directory.add(result);
						//rootpath=ftpClient.printWorkingDirectory();
						client.changeWorkingDirectory(tempDir);
						// 是文件夹就递归调用
						
						traverse(client, tempDir,temppath,directory);
						prefix += client.printWorkingDirectory();
						client.changeToParentDirectory();
					}
					// 如果是文件就扫描信息
				} else {
					String temp = client.printWorkingDirectory();
					temp=temp.replace(StringUtils.mainPath, "");
					// 根目录下的文件
					if (temp.equals("/")) {
						Map result=new ListOrderedMap();
						result.put("filename", files[i].getName());
						result.put("ftype", "file");							
						result.put("path", temp+"/"+files[i].getName());
						result.put("root", rootpath);
						directory.add(result);
					} else {// 不是根目录下的文件
						Map result=new ListOrderedMap();
						result.put("filename", files[i].getName());
						result.put("ftype", "file");							
						result.put("path", temp+"/"+files[i].getName());
						result.put("root", rootpath);
						directory.add(result);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}




	
	/**
	 * 删除文件的方法
	 * @throws IOException 
	 * */
	public static boolean delFile(String path) throws IOException {
		//FTPClient ftpClient = open();
		 FTPClient ftpClient=null;		  
		
		boolean falg = false;
		try {
			 ftpClient=connectServer();
			 if(ftpClient==null) return false;
			falg = ftpClient.deleteFile(path);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeConnect(ftpClient);
		}
		return falg;
	}
	
	public static boolean delDirectory(String path) throws IOException
	{
		 FTPClient ftpClient=null;		  
		 ftpClient=connectServer();	
		 if(ftpClient==null) return false;
		  try {
			FTPFile[] files = ftpClient.listFiles(path);
			for (FTPFile f : files) {
				if (!f.getName().equals(".") && !f.getName().equals("..")) {
					if (f.isDirectory()) {
						ftpClient.removeDirectory(path + "/" + f.getName());
						ftpClient.removeDirectory(path);
					}
					if (f.isFile()) {
						ftpClient.deleteFile(path + "/" + f.getName());
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally
		{
			closeConnect(ftpClient);
		}
		return true;
	}
	
   public static byte[] getContent(String filePath) throws IOException  
     {  
        FileInputStream in=new FileInputStream(filePath);  
          
        ByteArrayOutputStream out=new ByteArrayOutputStream(1024);  
         
       System.out.println("bytes available:"+in.available());  
         
       byte[] temp=new byte[1024];  
         
       int size=0;  
          
        while((size=in.read(temp))!=-1)  
       {  
            out.write(temp,0,size);  
       }  
          
       in.close();  
          
       byte[] bytes=out.toByteArray();  
       System.out.println("bytes size got is:"+bytes.length);  
         out.close();
         return bytes;  
    }  
        //将byte数组写入文件   
      public static void createFile(String path, byte[] content) throws IOException {  
    
        FileOutputStream fos = new FileOutputStream(path);  
   
        fos.write(content);  
        fos.close();  
    } 

	public static void main(String[] args) {
//		try {
//			byte[] content=getContent("d:\\CoreBpm.dmp");
//			Upload(content, "CoreBpm.dmp", "test");
//			
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//listAllRemoteFiles();
		//connectServer();
		ArrayList directory = new ArrayList();	
		try {
			listAllRemoteFiles("/CoreFS.AutoUpdate",directory);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(directory.size());
		
	}
	

}
