package th.co.muangthai.endrprint.controller.service.ftp; import java.io.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; /** * Ftp */ public class FTPUtil { public FTPUtil() { } /** * open server * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @return connection result * @throws Exception */ public static FtpClient openFtpServer(String hostname, int port, String username, String password) throws Exception { Logger log = Logger.getLogger(FTPUtil.class); try { // jdk 1.6 // FtpClient ftp = new FtpClient(); // ftp.setConnectTimeout(1000); // ftp.openServer(hostname, port); // log.info("FTP Connected " + hostname + " port " + port); // log.info("FTP logging on " + username); // ftp.login(username, password); // if (ftp.serverIsOpen()) { // log.info("FTP logged on " + username); // return ftp; // } else { // return null; // } //jdk 1.7 and High SocketAddress addr = new InetSocketAddress(hostname, port); FtpClient ftp = FtpClient.create(); ftp.setConnectTimeout(1000); ftp.connect(addr); log.info("FTP Connected " + hostname + " port " + port); log.info("FTP logging on " + username); ftp.login(username, password.toCharArray()); if (ftp.isLoggedIn()) { log.info("FTP logged on " + username); return ftp; } else { return null; } } catch (Exception ex) { throw ex; } } /** * close ftp server * @param ftp - FtpClient */ public static void closeFtpServer(final FtpClient ftp) { Logger log = Logger.getLogger(FTPUtil.class); try { //if (ftp != null && ftp.serverIsOpen()) { //jdk 1.6 if (ftp != null && ftp.isLoggedIn()) { log.info("close ftp server start..."); Thread t=new Thread( new Runnable() { public void run() { try { //ftp.closeServer(); //jdk 1.6 ftp.close(); //jdk 1.7 and High } catch (Exception ex) { ex.printStackTrace(); } } } ); t.start(); log.info("close ftp server success..."); } } catch (Exception ex) { ex.printStackTrace(); log.error(ex); // do nothing } } /** * upload file * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - destination file * @param localFileName - file to transfer (upload) * @param ftpDirectory - directory to upload file * @return upload result */ public boolean putFile(String hostname, int port, String username, String password, String remoteFileName, String localFileName ,String ftpDirectory) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; boolean putFileStatus = false; try { log.info("start putFile to FTP ..."); log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { //jdk 1.6 if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High try { //ftp.cd(ftpDirectory); //jdk 1.6 ftp.changeDirectory(ftpDirectory);//jdk 1.7 and High } catch (IOException e) { log.info(ftpDirectory + " dose not exist try to create directory......"); mkdir(hostname, port, username, password, ftpDirectory); //ftp.cd(ftpDirectory); //jdk 1.6 ftp.changeDirectory(ftpDirectory); //jdk 1.7 and High //ftp.sendServer("mkd "+remotePath+EOL); } //ftp.cd("fbi"); //ftp.binary(); //jdk 1.6 ftp.setBinaryType();//jdk 1.7 and High log.info("uploading file " + localFileName); //TelnetOutputStream out = ftp.put(remoteFileName); //jdk 1.6 OutputStream out = ftp.putFileStream(remoteFileName); //jdk 1.7 and High DataInputStream input = new DataInputStream(new FileInputStream(localFileName)); int b; long count = 0; while ((b = input.read()) > -1) { out.write(b); count++; } input.close(); out.close(); log.info("upload file " + localFileName + "(" + count + ")bytes to " + remoteFileName + " done."); log.info("PutFile to FTP Success..."); putFileStatus = true; } else { log.info("PutFile to FTP Fail..."); putFileStatus = false; } } catch (Exception e) { e.printStackTrace(); log.error(e); } finally { FTPUtil.closeFtpServer(ftp); } return putFileStatus; } /** * upload file * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - destination file * @param localStream - InputStream * @return upload result */ public static boolean putFile(String hostname, int port, String username, String password, String remoteFileName, InputStream localStream) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { //jdk 1.6 if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd("fbi"); //ftp.binary(); //jdk 1.6 ftp.setBinaryType(); //jdk 1.7 and High log.info("uploading file to " + remoteFileName); //TelnetOutputStream out = ftp.put(remoteFileName); //jdk 1.6 OutputStream out = ftp.putFileStream(remoteFileName); //jdk 1.7 and High DataInputStream input = new DataInputStream(localStream); int b; while ((b = input.read()) > -1) { out.write(b); } input.close(); out.close(); log.info("upload file " + "Stream data" + " to " + remoteFileName + " done."); return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); log.error(e); return false; } finally { FTPUtil.closeFtpServer(ftp); } } /** * download file * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - source file on server * @param localFileName - file to transfer (download) * @return download result */ public static boolean getFile(String hostname, int port, String username, String password, String remoteFileName, String localFileName) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { //jdk 1.6 if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd(filePath + "/"); log.info("downloading file " + remoteFileName + " to " + localFileName + "."); //ftp.binary(); //jdk 1.6 ftp.setBinaryType(); //jdk 1.7 and High //TelnetInputStream telNetInputStream = ftp.get(remoteFileName); //jdk 1.6 InputStream telNetInputStream = ftp.getFileStream(remoteFileName); //jdk 1.7 and High File localFile = new File(localFileName); //fileKeep.mkd(); BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(localFile)); // //byte bytesFile[] = new byte[4096]; // for (int nBytesRead = -1; (nBytesRead = telNetInputStream.read(bytesFile)) != -1;) { // bOut.write(bytesFile, 0, nBytesRead); // } int b; long count = 0; while ((b = telNetInputStream.read()) > -1) { bOut.write(b); count++; } bOut.close(); telNetInputStream.close(); log.info("download file " + remoteFileName + "(" + count + ")bytes to " + localFileName + " done."); return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); log.error(e); return false; } finally { FTPUtil.closeFtpServer(ftp); } } /** * download multiple files * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - are files to transfer(download) * @param localPath - directory to transfer(download) * @return download result */ public static boolean getMultipleFileForBpgsResult(String hostname, int port, String username, String password, String[] remoteFileName, String localPath) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { //jdk 1.6 if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd(filePath + "/"); //ftp.binary(); ftp.setBinaryType(); for (int i = 0; i < remoteFileName.length; i++) { try { String remoteFile = remoteFileName[i]; log.info("downloading file " + remoteFile); //TelnetInputStream telNetInputStream = ftp.get(remoteFile); InputStream telNetInputStream = ftp.getFileStream(remoteFile); //jdk 1.7 and High String actualFileName = remoteFile.substring(remoteFile.lastIndexOf("\\") + 1, remoteFile.length()); log.info("actualFileName : " + actualFileName); File localFile = new File(localPath + "/" + actualFileName); log.info("local file name : " + (localPath + "/" + actualFileName)); BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(localFile)); int b; long count = 0; while ((b = telNetInputStream.read()) > -1) { bOut.write(b); count++; } bOut.close(); telNetInputStream.close(); log.info("download file " + remoteFileName[i] + "(" + count + ")bytes to " + localFile.getAbsolutePath() + " done."); } catch (Exception e) { log.error("Download file " + remoteFileName[i] + " error " + e.getMessage(), e); } } return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); log.error(e); return false; } finally { FTPUtil.closeFtpServer(ftp); } } /** * download multiple files * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - are files to transfer(download) * @param localPath - directory to transfer(download) * @return download result */ public static boolean getMultipleFile(String hostname, int port, String username, String password, String[] remoteFileName, String localPath) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd(filePath + "/"); //ftp.binary(); ftp.setBinaryType(); //jdk 1.7 and High if (localPath != null) { File inputDir = new File(localPath); if (inputDir.isDirectory()) { File[] files = inputDir.listFiles(); //delete locally file for (File file : files) { if (file.isFile()) { log.info("Deleting file " + file.getAbsolutePath()); boolean delResult = file.delete(); log.info(" file " + file.getAbsolutePath() + " delete " + (delResult ? " success." : "failed.")); } } } else { inputDir.mkdirs(); } } for (int i = 0; i < remoteFileName.length; i++) { try { String remoteFile = remoteFileName[i]; log.info("downloading file " + remoteFile); //TelnetInputStream telNetInputStream = ftp.get(remoteFile); InputStream telNetInputStream = ftp.getFileStream(remoteFile); //jdk 1.7 and High String actualFileName = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length()); log.info("actualFileName : " + actualFileName); File localFile = new File(localPath + "/" + actualFileName); log.info("local file name : " + (localPath + "/" + actualFileName)); BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(localFile)); int b; long count = 0; while ((b = telNetInputStream.read()) > -1) { bOut.write(b); count++; } bOut.close(); telNetInputStream.close(); log.info("download file " + remoteFileName[i] + "(" + count + ")bytes to " + localFile.getAbsolutePath() + " done."); } catch (Exception e) { log.error("Download file " + remoteFileName[i] + " error " + e.getMessage(), e); } } return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); log.error(e); return false; } finally { FTPUtil.closeFtpServer(ftp); } } /** * upload multiple files * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remotePath - directory to transfer (upload) * @param localFileNames - list of files to transfer (upload) * @return upload result */ public boolean putMultipleFile(String hostname, int port, String username, String password, String remotePath, String[] localFileNames) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //ftp.setConnectTimeout(60000); String EOL = "\r\n"; //if (ftp != null && ftp.serverIsOpen()) { if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.binary(); ftp.setBinaryType(); //jdk 1.7 and High try { //ftp.cd(remotePath); ftp.changeDirectory(remotePath); ////jdk 1.7 and High } catch (IOException e) { log.info(remotePath + " dose not exist try to create directory......"); mkdir(hostname, port, username, password, remotePath); //ftp.cd(remotePath); ftp.changeDirectory(remotePath); //jdk 1.7 and High //ftp.sendServer("mkd "+remotePath+EOL); } for (int i = 0; i < localFileNames.length; i++) { try { String actualFileName = localFileNames[i]; log.info("uploading file from " + actualFileName); File localFile = new File(actualFileName); String remoteFile = localFile.getName();//actualFileName.substring(actualFileName.lastIndexOf("/")+1, actualFileName.length()); try { //ftp.sendServer("DELE " + remoteFile + EOL); deleteFile(hostname, port, username, password, remotePath + "/" + remoteFile); } catch (Exception e) { log.info("delete ftp file error " + e.getMessage(), e); } //TelnetOutputStream out = ftp.put(remoteFile); OutputStream out = ftp.putFileStream(remoteFile); //jdk 1.7 and High DataInputStream input = new DataInputStream(new FileInputStream(localFile)); int b; long count = 0; while ((b = input.read()) > -1) { out.write(b); count++; } input.close(); out.close(); log.info("uploaded file " + localFile.getAbsolutePath() + "(" + count + ")bytes to " + remotePath + "/" + remoteFile + " done."); } catch (Exception e) { log.error("upload file error " + e.getMessage(), e); } } return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); log.error(e); return false; } finally { FTPUtil.closeFtpServer(ftp); } } /** * create directory * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remotePath - directoryName to create */ public static void mkdir(String hostname, int port, String username, String password, String remotePath) { Logger log = Logger.getLogger(FTPUtil.class); try { FtpClient ftp = FTPUtil.openFtpServer(hostname, port, username, password); //ftp.sendServer("mkd " + remotePath + "\r\n"); ftp.makeDirectory(remotePath); //jdk 1.7 and High FTPUtil.closeFtpServer(ftp); } catch (Exception ex) { ex.printStackTrace();log.error(ex); } } /** * get file to Stream * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - destination file * @param out - Writer */ public static void getFileToStream(String hostname, int port, String username, String password, String remoteFileName, Writer out) { Logger log = Logger.getLogger(FTPUtil.class); FtpClient ftp = null; try { log.debug("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd(filePath + "/"); //ftp.binary(); ftp.setBinaryType(); //jdk 1.7 and High //TelnetInputStream telNetInputStream = ftp.get(remoteFileName); InputStream telNetInputStream = ftp.getFileStream(remoteFileName); //jdk 1.7 and High //File localFile = new File(localFileName); //fileKeep.mkd(); //BufferedOutputStream bOut = new BufferedOutputStream(out.); // //byte bytesFile[] = new byte[4096]; // for (int nBytesRead = -1; (nBytesRead = telNetInputStream.read(bytesFile)) != -1;) { // bOut.write(bytesFile, 0, nBytesRead); // } int b; long count = 0; while ((b = telNetInputStream.read()) > -1) { out.write(b); count++; } //bOut.close(); telNetInputStream.close(); log.info("download file " + remoteFileName + "(" + count + ")bytes done."); } } catch (Exception e) { e.printStackTrace(); log.error(e); } finally { FTPUtil.closeFtpServer(ftp); } } /** * list file * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remotePath - directoryName to list file * @return list of file name in the directory */ public static List listFile(String hostname, int port, String username, String password, String remotePath) { Logger log = Logger.getLogger(FTPUtil.class); List list = null; FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //String line = System.getProperty("line.separator"); //if (ftp != null && ftp.serverIsOpen()) { if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd(remotePath); //ftp.binary(); ftp.setBinaryType(); //jdk 1.7 and High //TelnetInputStream telNetInputStream = ftp.nameList(remotePath); InputStream telNetInputStream = ftp.list(remotePath); //jdk 1.7 and High BufferedReader reader = new BufferedReader(new InputStreamReader(telNetInputStream)); String line = null; list = new ArrayList(); while ((line = reader.readLine()) != null) { list.add(line); //log.info(line); } // for (Iterator it = list.iterator(); it.hasNext();) { // Object object = it.next(); // //log.info("XX"+object); // } telNetInputStream.close(); //log.info(out.toString()); //log.debug("download file " + remoteFileName + "("+count+")bytes to " + localFileName + " done."); return list; } else { return null; } } catch (FileNotFoundException ex) { ex.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); log.error(e); return null; } finally { FTPUtil.closeFtpServer(ftp); } } /** * list all file in the directory * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remotePath - directoryName to list file * @return list all file name in the directory */ public static List listAllFile(String hostname, int port, String username, String password, String remotePath) { Logger log = Logger.getLogger(FTPUtil.class); List list = null; FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //String line = System.getProperty("line.separator"); //if (ftp != null && ftp.serverIsOpen()) { if (ftp != null && ftp.isLoggedIn()) { //jdk 1.7 and High //ftp.cd(remotePath); //ftp.binary(); ftp.setBinaryType(); //jdk 1.7 and High //TelnetInputStream telNetInputStream = ftp.nameList(remotePath); InputStream telNetInputStream = ftp.list(remotePath); //jdk 1.7 and High BufferedReader reader = new BufferedReader(new InputStreamReader(telNetInputStream)); String line = null; list = new ArrayList(); while ((line = reader.readLine()) != null) { String actualFileName = null; String realPath = null; log.info("line is " + line); if (line.lastIndexOf("\\") >= 0) { actualFileName = line.substring(line.lastIndexOf("\\") + 1, line.length()); } if (actualFileName == null) { actualFileName = line; } if (actualFileName.lastIndexOf("/") >= 0) { actualFileName = actualFileName.substring(actualFileName.lastIndexOf("/") + 1, actualFileName.length()); } log.info("actualFileName is " + actualFileName); realPath = remotePath + "/" + actualFileName; log.info("----Real Path---- : " + realPath); list.add(realPath); } telNetInputStream.close(); return list; } else { return null; } } catch (FileNotFoundException ex) { ex.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); log.error(e); return null; } finally { FTPUtil.closeFtpServer(ftp); } } /** * delete file * @param hostname - ip * @param port - port (default 21) * @param username - username * @param password - password * @param remoteFileName - destination file * @return delete result */ public static boolean deleteFile(String hostname, int port, String username, String password, String remoteFileName) { Logger log = Logger.getLogger(FTPUtil.class); String EOL = "\r\n"; FtpClient ftp = null; try { log.info("opening ftp server " + hostname + " port " + port); log.info("remote file name " + remoteFileName); ftp = FTPUtil.openFtpServer(hostname, port, username, password); //if (ftp != null && ftp.serverIsOpen()) { if (ftp != null && ftp.isConnected()) { //ftp.cd("fbi"); //ftp.binary(); ftp.setBinaryType(); //jdk 1.7 and High //TelnetOutputStream telNetInputStream = ftp.put(remoteFileName); //ftp.sendServer("DELE " + remoteFileName + EOL); ftp.deleteFile(remoteFileName); //jdk 1.7 and High //telNetInputStream.close(); log.info("delete file from remote file " + remoteFileName); return true; } else { return false; } } catch (Exception e) { //e.printStackTrace(); log.error("Delete FTP file error" + e.getMessage(), e); return false; } finally { FTPUtil.closeFtpServer(ftp); } } }