package com.eactive.eai.batch.ftp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;

public class FTPAdaptor {

//	private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_ADAPTER);

	protected static FTPFile[] listFiles(String server, int port, String username, String password, String path, HashMap<Integer, String> extmap, Logger logger) throws IOException {
		logger.debug("[FTP connect]server  -->" + server);
		logger.debug("[FTP connect]port    -->" + port);
		logger.debug("[FTP connect]username-->" + username);
		logger.debug("[FTP connect]password-->" + password);
		logger.debug("[FTP listFiles]path-->" + path);

		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");
			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
			}

			if (extmap == null) {
				FTPFile[] tmpfiles = ftpClient.listFiles(path);
				for (int jnx = 0; jnx < tmpfiles.length; jnx++) {
					String filename = tmpfiles[jnx].getName();
					tmpfiles[jnx].setName(filename.replace(path, ""));
				}
				return tmpfiles;
			} else {
				ArrayList<FTPFile> list = new ArrayList<FTPFile>();
				int returnCnt = 0;
				for (int inx = 0; inx < extmap.size(); inx++) {
					String ext = extmap.get(inx);
					FTPFile[] tmpfiles = ftpClient.listFiles(path + "/*." + ext);
					for (int jnx = 0; jnx < tmpfiles.length; jnx++) {
						String filename = tmpfiles[jnx].getName();
						tmpfiles[jnx].setName(filename.replace(path, ""));
						list.add(tmpfiles[jnx]);
						returnCnt++;
					}
				}
				FTPFile[] files = new FTPFile[returnCnt];
				list.toArray(files);
				return files;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new IOException(e.getMessage());
		} finally {
			ftpClient.quit();
		}

	}
	
	// 20241008 FTPFileObject 사용
	protected static FTPFileObject[] listFiles2(String server, int port, String username, String password, String path, Logger logger) throws IOException {
		logger.debug("[FTP connect]server  -->" + server);
		logger.debug("[FTP connect]port    -->" + port);
		logger.debug("[FTP connect]username-->" + username);
		logger.debug("[FTP connect]password-->" + password);
		logger.debug("[FTP listFiles]path-->" + path);

		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");
			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
			}
			
			FTPFile[] tmpfiles = ftpClient.listFiles(path);
			for (int jnx = 0; jnx < tmpfiles.length; jnx++) {
				String filename = tmpfiles[jnx].getName();
				tmpfiles[jnx].setName(filename.replace(path, ""));
			}
			
			ArrayList<FTPFileObject> oFiles = new ArrayList<FTPFileObject>();
			FTPFileObject[] rFiles = new FTPFileObject[tmpfiles.length];
			FTPFileObject nFile;
			for(FTPFile file :tmpfiles){
				nFile = new FTPFileObject();
				nFile.setFile(file.isFile());
				nFile.setName(file.getName());
				nFile.setSize(file.getSize());
				oFiles.add(nFile);
			}
			oFiles.toArray(rFiles);
			
			return rFiles;
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new IOException(e.getMessage());
		} finally {
			ftpClient.quit();
		}

	}

	protected static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String localPath, int bandWidthLimit, Logger logger, String ftpFileType) throws Exception {

		logger.debug("[FTP retrieve]remote-->" + remote);
		logger.debug("[FTP retrieve]localPath-->" + localPath);
		long size = -1;

		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");

			ftpClient.connect(server, port);
			if("ASCII".equals(ftpFileType))
				ftpClient.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
			else 
				ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
			}

			File chkDir = new File(localPath);
			String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(localPath);
			String fName = remote.substring(remote.lastIndexOf(delimiter) + 1);
			logger.debug("[retrieve]fName  ------->" + fName);

			if (!chkDir.exists() && !chkDir.mkdirs()) {
				logger.error("[체크파일을 생성할 수 없습니다.]"); // 상위 디렉토리 미 존재시에도 write 한다.
				return -1;
			}

			File file = new File(localPath + delimiter + fName);
			OutputStream output = new FileOutputStream(file);
			
			if(bandWidthLimit > 0){
					/**
					 * 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit),
					 */
					//Buffer buffer = new Buffer(1024);
					//int bandWidth = 1024*8;
					long bufferSize = bandWidthLimit/8;
					byte[] bufferArr = new byte[(int)bufferSize];
					
					try {
							bos = new BufferedOutputStream(output);
							bis = new BufferedInputStream(ftpClient.retrieveFileStream(remote));
							batchDoc.setIOStream(bis);
							
							int readCount = 0;
							int lootCnt = 0;
							
							long[] timeMillis = new long[2];
							timeMillis[0] = System.currentTimeMillis();
							
							long rtt = 0;//round trip time 1회 전송시간 millisecond
							long rttMax = 0;
							long rttMin = 0;
							double rttAve = 0;
							long rttSum = 0;
							
							long realBandWidth = 0;
							long realBandWidthMax = 0;
							long realBandWidthMin = 0;
							double realBandWidthAve = 0;
							long realBandWidthSum = 0;
							long readByteSum = 0;
							
							long sizeStartTime = 0;
							long sizePerSecond = 0;
							int sleepTimeCriteria = 990;

							while (true){
								
								lootCnt++;
								sleepTimeCriteria = 990; //여유 10milli
								
								//강제중지 설정시
								if (batchDoc.isUserCancel()){
									throw new Exception("사용자가 전송을 중지 했습니다.");
								}
								
								timeMillis[0] = System.currentTimeMillis();
								readCount = bis.read(bufferArr);
								timeMillis[1] = System.currentTimeMillis();
								if(readCount<=0) break;
								
								bos.write(bufferArr,0,readCount);
								
								readByteSum += readCount;
								batchDoc.setCurrIODataByte(readByteSum);
								
								if (sizePerSecond > 0){
									rtt = timeMillis[1] - sizeStartTime;
								} else {
									rtt = timeMillis[1] - timeMillis[0];
								}
								
								
								if(rtt<=0 ){
									//rtt=1;//local test시 0이 발생 divide by zero오류 발생, 방어코드
									if(sizeStartTime==0)sizeStartTime = timeMillis[0];
									sizePerSecond += readCount;
									
									if(sizePerSecond >= bufferArr.length){
										logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 990 sec,  readCount["+readCount+"]sizePerSecond["+sizePerSecond+"]readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]");
										Thread.sleep(990);
										sizePerSecond = 0;
										sizeStartTime = 0;
									} else {
										logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 0 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]");
									}
									continue;
								} 
								
								if ( readCount < bufferArr.length || sizePerSecond> 0){
									
									if(sizeStartTime==0)sizeStartTime = timeMillis[0];
									sizePerSecond += readCount;
									
									if(sizePerSecond>0 && sizePerSecond < bufferArr.length){
										logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] SLEEP 0 sec readCount["+readCount+"] sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]");
										
										continue;			
									}
									
								}
								
								if (sizePerSecond > 0){
									realBandWidth = (long) (sizePerSecond * 8  * 1000 / rtt);
								} else {
									realBandWidth = (long) (bufferSize * 8  * 1000 / rtt);
								}
								
								
								//min, max, sum
								rttSum += rtt;
								if (rtt > rttMax)rttMax = rtt;
								else if (rtt < rttMin)rttMin = rtt;
								
								realBandWidthSum += realBandWidth;
								if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth;
								else if(realBandWidth<realBandWidthMin)realBandWidthMin=realBandWidth;
								
								if (sizePerSecond > 0 && sizePerSecond>bufferSize){
									sleepTimeCriteria = (int) (sleepTimeCriteria*sizePerSecond/bufferSize);								
								} 
									
								
								
								if(rtt < sleepTimeCriteria){ 
									logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"]  readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(sleepTimeCriteria-rtt)+"]sleepTimeCriteria["+sleepTimeCriteria+"]");
									
									Thread.sleep((long) (sleepTimeCriteria-rtt));
								} else {
									logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]sleepTimeCriteria["+sleepTimeCriteria+"]");
									
								}
								
								sizePerSecond = 0;
								sizeStartTime = 0;
								
							}
							
							realBandWidthAve = realBandWidthSum/lootCnt;
							rttAve = rttSum/lootCnt;
							
							logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize
									+"] loopCnt["+lootCnt
									+"] readByteSum["+readByteSum
									+"] rttAve["+rttAve
									+"] rttMax["+rttMax
									+"] rttMin["+rttMin
									+"] bandWidthLimit["+bandWidthLimit
									+"] realBandWidthAve["+realBandWidthAve
									+"] realBandWidthMax["+realBandWidthMax
									+"] realBandWidthMin["+realBandWidthMin
									+"]");

					} finally {
							if (bos != null){
								bos.flush();
								bos.close();
							}
							
							if (bis != null)bis.close();
							if(output!=null) output.close();
					}
			} else {			
				ftpClient.retrieveFile(remote, output);
				if(output!=null) output.close();
			}
			
			if ( file.exists() )
				size = file.length();

			// check the reply code to verify success
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				logger.warn("Command failed: " + ftpClient.getReplyString());
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {

			if (ftpClient != null)
				ftpClient.quit();
		}
		return size;
	}
	
	protected static long retrieve(String server, int port, String username, String password, String remote, String localPath, Logger logger) throws Exception {

		logger.debug("[FTP retrieve]remote-->" + remote);
		logger.debug("[FTP retrieve]localPath-->" + localPath);
		long size = -1;

		//BufferedOutputStream bos = null;// 20250910 
		//BufferedInputStream bis = null;// 20250910 
		
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");

			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
			}

			File chkDir = new File(localPath);
			String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(localPath);
			String fName = remote.substring(remote.lastIndexOf(delimiter) + 1);
			logger.debug("[retrieve]fName  ------->" + fName);

			if (!chkDir.exists() && !chkDir.mkdirs()) {
				logger.error("[체크파일을 생성할 수 없습니다.]"); // 상위 디렉토리 미 존재시에도 write 한다.
				return -1;
			}

			File file = new File(localPath + delimiter + fName);
			OutputStream output = new FileOutputStream(file);
		
			ftpClient.retrieveFile(remote, output);
			output.close();

			if ( file.exists() )
				size = file.length();

			// check the reply code to verify success
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				logger.warn("Command failed: " + ftpClient.getReplyString());
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			if (ftpClient != null)
				ftpClient.quit();
		}
		return size;
	}

	protected static boolean store(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String localPath, int bandWidthLimit, Logger logger) throws Exception {
		logger.debug("[FTP store]remote-->" + remote);
		logger.debug("[FTP store]localPath-->" + localPath);

		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		FileInputStream input = null;
		
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");

			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
			}

			File file = new File(localPath);

			String delimiter  = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(remote);
			String remotePath = remote.substring(0,remote.lastIndexOf(delimiter));
			String fileName   = remote.substring(remote.lastIndexOf(delimiter) + 1);

			logger.debug("[FTP store]remotePath-->" + remotePath);
			logger.debug("[FTP store]fileName-->" + fileName);

			boolean cd = ftpClient.changeWorkingDirectory(remotePath);
			if ( !cd ){
				ftpClient.makeDirectory(remotePath);
				ftpClient.changeWorkingDirectory(remotePath);
			}
			
			input = new FileInputStream(file);
			
			if(bandWidthLimit > 0){
				/**
				 * 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit),
				 */
				//Buffer buffer = new Buffer(1024);
				//int bandWidth = 1024*8;
				long bufferSize = bandWidthLimit/8;
				byte[] bufferArr = new byte[(int)bufferSize];
				
				try {
						bos = new BufferedOutputStream(ftpClient.storeFileStream(remote));
						bis = new BufferedInputStream(input);
						batchDoc.setIOStream(bos);
						
						int readCount = 0;
						int lootCnt = 0;
						
						long[] timeMillis = new long[2];
						timeMillis[0] = System.currentTimeMillis();
						
						long rtt = 0;//round trip time 1회 전송시간 millisecond
						long rttMax = 0;
						long rttMin = 0;
						double rttAve = 0;
						long rttSum = 0;
						
						long realBandWidth = 0;
						long realBandWidthMax = 0;
						long realBandWidthMin = 0;
						double realBandWidthAve = 0;
						long realBandWidthSum = 0;
						long writeByteSum = 0;
						
						long sizeStartTime = 0;
						long sizePerSecond = 0;
						
						while (true){
							
							lootCnt++;
							
							
							//강제중지 설정시
							if (batchDoc.isUserCancel()){
								throw new Exception("사용자가 전송을 중지 했습니다.");
							}
							
							readCount = bis.read(bufferArr);
							if(readCount<=0) break;
							
							
							//****sftp send......
							timeMillis[0] = System.currentTimeMillis();
							bos.write(bufferArr,0,readCount);
							timeMillis[1] = System.currentTimeMillis();
							
							writeByteSum += readCount;
							batchDoc.setCurrIODataByte(writeByteSum);
							
							if (sizePerSecond > 0){
								rtt = timeMillis[1] - sizeStartTime;
							} else {
								rtt = timeMillis[1] - timeMillis[0];
							}
							
							if(rtt<=0){
								if(sizeStartTime==0)sizeStartTime = timeMillis[0];		
								sizePerSecond += readCount;
								realBandWidth = 0;
							}else {
								//rtt가 0보다 커야 bandwidth계산
								realBandWidth = (long) ((sizePerSecond+bufferSize) * 8  * 1000 / rtt);
								
								sizeStartTime = 0;
								sizePerSecond = 0;
							}
							
							realBandWidthSum += realBandWidth;
							if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth;
							else if(realBandWidth<realBandWidthMin)realBandWidthMin=realBandWidth;
							
							rttSum += rtt;
							if (rtt > rttMax)rttMax = rtt;
							else if (rtt < rttMin)rttMin = rtt;
							
							//1초이내로 처리가 된경우sleep,, 여유 10milli
							if(rtt < 990){ //여유 10milli
								logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(990-rtt)+"]");
								
								Thread.sleep((long) (990-rtt));
								
								
							} else {
								logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]");											
							}
						}
						
						realBandWidthAve = realBandWidthSum/lootCnt;
						rttAve = rttSum/lootCnt;
						
						logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize
								+"] loopCnt["+lootCnt
								+"] writeByteSum["+writeByteSum
								+"] rttAve["+rttAve
								+"] rttMax["+rttMax
								+"] rttMin["+rttMin
								+"] bandWidthLimit["+bandWidthLimit
								+"] realBandWidthAve["+realBandWidthAve
								+"] realBandWidthMax["+realBandWidthMax
								+"] realBandWidthMin["+realBandWidthMin
								+"]");

				} finally {
					try {
						if (bos != null){
							bos.flush();
							bos.close();
						}
						
						if (bis != null)bis.close();
						if(input!=null) input.close();
					} catch (Throwable t){
						logger.error("Closing Error:"+t.getMessage());
					}
				}
			} else {			
				ftpClient.storeFile(fileName, input);
				if(input!=null) input.close();// 20250910 obl
			}
			

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			if (ftpClient != null) ftpClient.disconnect();
		}
		return true;
	}
	
	protected static boolean store(String server, int port, String username, String password, String remote, String localPath, Logger logger) throws Exception {

		logger.debug("[FTP store]remote-->" + remote);
		logger.debug("[FTP store]localPath-->" + localPath);

		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");

			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
			}

			File file = new File(localPath);

			String delimiter  = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(remote);
			String remotePath = remote.substring(0,remote.lastIndexOf(delimiter));
			String fileName   = remote.substring(remote.lastIndexOf(delimiter) + 1);

			logger.debug("[FTP store]remotePath-->" + remotePath);
			logger.debug("[FTP store]fileName-->" + fileName);

			boolean cd = ftpClient.changeWorkingDirectory(remotePath);
			if ( !cd ){
				ftpClient.makeDirectory(remotePath);
				ftpClient.changeWorkingDirectory(remotePath);
			}
			
			FileInputStream input = new FileInputStream(file);
			ftpClient.storeFile(fileName, input);
			input.close();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			if (ftpClient != null)
				ftpClient.quit();
		}
		return true;
	}

	protected static boolean rename(String server, int port, String username, String password, String srcname, String tarname, Logger logger) throws Exception {

		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");

			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode(
						"BECEAIMEU016", arg));
			}

			ftpClient.rename(srcname, tarname);

			ftpClient.quit();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			if (ftpClient != null)
				ftpClient.quit();
		}
		return true;
	}

	protected static boolean delete(String server, int port, String username, String password, String srcname, Logger logger) throws Exception {

		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.setControlEncoding("euc-kr");

			ftpClient.connect(server, port);
			ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				String arg[] = new String[1];
				arg[0] = username;
				throw new IOException(ExceptionUtil.getErrorCode(
						"BECEAIMEU016", arg));
			}

			ftpClient.deleteFile(srcname);

			ftpClient.quit();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			if (ftpClient != null)
				ftpClient.quit();
		}
		return true;
	}

}
