List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:com.claim.controller.FileTransferController.java
public void readFilesFromServer(String targetDirectory) { FTPClient ftpClient = new FTPClient(); try {// w ww .j ava 2 s . co m FtpProperties properties = new ResourcesProperties().loadFTPProperties(); ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); FTPFile[] ftpFiles = ftpClient.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { //loop thru files for (FTPFile file : ftpFiles) { if (!file.isFile()) { continue; } System.out.println("File is " + file.getName()); //get output stream OutputStream output; //output = new FileOutputStream(FTP_REMOTE_HOME + "/" + file.getName()); output = new FileOutputStream(file.getName()); //get the file from the remote system ftpClient.retrieveFile(file.getName(), output); //close output stream output.close(); //delete the file //ftpClient.deleteFile(file.getName()); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { Logger.getLogger(FileTransferController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java
/** * FTP????????/*from www.j av a2s .co m*/ * * @param addressText * @return FTP */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); FTPClient client = new FTPClient(); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } else { retry = false; isReachable = false; } } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(FTP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.knowbout.epg.processor.Downloader.java
public Downloader(InetAddress server, String username, String password, File destinationFolder, String remoteWorkingDirectory, boolean forceDownload) { this.server = server; this.destinationFolder = destinationFolder; if (!destinationFolder.exists() || !destinationFolder.isDirectory()) { throw new IllegalArgumentException( "The destinationFolder must exist and be a directory: " + destinationFolder); }/*from ww w.j a v a 2 s . c o m*/ this.username = username; this.password = password; this.remoteWorkingDirectory = remoteWorkingDirectory; this.forceDownload = forceDownload; client = new FTPClient(); }
From source file:com.denayer.ovsr.MyFTPClient.java
public boolean ftpConnect(String host, String username, String password, int port) { try {// ww w .j av a2 s .co m mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); // now check the reply code, if positive mean connection success if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { // login using username & password boolean status = mFTPClient.login(username, password); /* Set File Transfer Mode * * To avoid corruption issue you must specified a correct * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE, * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE * for transferring text, image, and compressed files. */ mFTPClient.setFileType(FTP.ASCII_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); return status; } } catch (Exception e) { Log.d(TAG, "Error: could not connect to host " + host); } return false; }
From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java
@Override public void upload(String path, File file, String contentType) { Map<String, String> ftpInfo = getFtpInfo(contentType); if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username")) && !"".equals(ftpInfo.get("password"))) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {/*from w w w .ja v a2 s . c o m*/ inputStream = new FileInputStream(file); ftpClient.connect(ftpInfo.get("host"), 21); ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password")); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); path = ftpInfo.get("path") + path; if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } } }
From source file:GridFDock.DataDistribute.java
public void connect(String hostname, int port, String username, String password) throws IOException, NoSuchAlgorithmException { // ftpClient = new FTPSClient(false); // create with implicit TLS boolean tmp = true; int i = 0;//from w ww .j ava2 s. c o m ftpClient = new FTPClient(); ftpClient.connect(hostname, port); do { i++; if (ftpClient.login(username, password) == true) { tmp = false; } else { System.out.println("Can not connect the FTP server! And will try it again!"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } while (tmp && i <= 100); }
From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java
/** * Description: ?FTP?// w w w. j a v a 2s . c o m * * @param url FTP?hostname * @param port FTP???-1 * @param username FTP? * @param password FTP? * @param path FTP?? * @param filename FTP??? * @param input ? * @return ?true?false */ public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; // FTP? if (port > -1) { ftp.connect(url, port); } else { ftp.connect(url); } // FTP ftp.login(username, password); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { success = false; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { } } } return success; }
From source file:com.cisco.dbds.utils.ftp.FTPHandler.java
/** * Ftp connect./*from w w w . j ava2 s .com*/ */ public void ftpConnect() { try { String server = System.getProperty("dtacs.db.ip"); int port = 21; String user = System.getProperty("dtacs.ftp.username"); String pass = System.getProperty("dtacs.ftp.password"); ftpClient = new FTPClient(); ftpClient.connect(server, port); boolean loginStatus = ftpClient.login(user, pass); if (loginStatus) { LogHandler.info("FTP connection sucess"); } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:net.sourceforge.dvb.projectx.xinput.ftp.FtpServer.java
public FtpServer(FtpVO aFtpVO) { if (aFtpVO == null) { throw new IllegalArgumentException("aFtpVO mustn't be null!"); }//from w ww.java 2 s.c o m ftpVO = aFtpVO; scl = new StringCommandListener(); ftpClient = new FTPClient(); ftpClient.addProtocolCommandListener(scl); isOpen = false; }
From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java
public void upload(RunFileTransferEntity runFileTransferEntity) { log.debug("Start FTPUtil upload"); FTPClient ftpClient = new FTPClient(); ftpClient.enterLocalPassiveMode();// ww w . j a v a 2 s. co m ftpClient.setBufferSize(1024000); int retryAttempt = runFileTransferEntity.getRetryAttempt(); int attemptCount = 1; int i = 0; InputStream inputStream = null; boolean login = false; File filecheck = new File(runFileTransferEntity.getInputFilePath()); log.info("input file name" + filecheck.getName()); if (runFileTransferEntity.getFailOnError()) { if (!(filecheck.isFile() || filecheck.isDirectory()) && !(runFileTransferEntity.getInputFilePath().contains("hdfs://"))) { log.error("Invalid input file path. Please provide valid input file path."); throw new FTPUtilException("Invalid input file path"); } } boolean done = false; for (i = 0; i < retryAttempt; i++) { try { log.info("Connection attempt: " + (i + 1)); if (runFileTransferEntity.getTimeOut() != 0) if (runFileTransferEntity.getEncoding() != null) ftpClient.setControlEncoding(runFileTransferEntity.getEncoding()); ftpClient.setConnectTimeout(runFileTransferEntity.getTimeOut()); log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n" + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno" + runFileTransferEntity.getPortNo()); ftpClient.connect(runFileTransferEntity.getHostName(), runFileTransferEntity.getPortNo()); login = ftpClient.login(runFileTransferEntity.getUserName(), runFileTransferEntity.getPassword()); if (!login) { log.error("Invalid FTP details provided. Please provide correct FTP details."); throw new FTPUtilException("Invalid FTP details"); } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (runFileTransferEntity.getInputFilePath().contains("hdfs://")) { log.debug("Processing for HDFS input file path"); String inputPath = runFileTransferEntity.getInputFilePath(); String s1 = inputPath.substring(7, inputPath.length()); String s2 = s1.substring(0, s1.indexOf("/")); int index = runFileTransferEntity.getInputFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/'); String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1); File f = new File("/tmp"); if (!f.exists()) f.mkdir(); Configuration conf = new Configuration(); conf.set("fs.defaultFS", "hdfs://" + s2); FileSystem hdfsFileSystem = FileSystem.get(conf); Path local = new Path("/tmp"); String s = inputPath.substring(7, inputPath.length()); String hdfspath = s.substring(s.indexOf("/"), s.length()); File dir = new File(hdfspath); Random ran = new Random(); String tempFolder = "ftp_sftp_" + System.nanoTime() + "_" + ran.nextInt(1000); File dirs = new File("/tmp/" + tempFolder); boolean success = dirs.mkdirs(); if (hdfsFileSystem.isDirectory(new Path(hdfspath))) { log.debug("Provided HDFS input path is for directory."); InputStream is = null; OutputStream os = null; String localDirectory = hdfspath.substring(hdfspath.lastIndexOf("/") + 1); FileStatus[] fileStatus = hdfsFileSystem .listStatus(new Path(runFileTransferEntity.getInputFilePath())); Path[] paths = FileUtil.stat2Paths(fileStatus); try { String folderName = hdfspath.substring(hdfspath.lastIndexOf("/") + 1); Path hdfs = new Path(hdfspath); for (Path file : paths) { is = hdfsFileSystem.open(file); os = new BufferedOutputStream( new FileOutputStream(dirs + "" + File.separatorChar + file.getName())); IOUtils.copyBytes(is, os, conf); } ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/")); ftpClient.removeDirectory(folderName); ftpClient.makeDirectory(folderName); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath().replaceAll( Matcher.quoteReplacement("\\"), "/") + File.separatorChar + folderName); for (File files : dirs.listFiles()) { if (files.isFile()) ftpClient.storeFile(files.getName().toString(), new BufferedInputStream(new FileInputStream(files))); } } catch (IOException e) { log.error("Failed while doing FTP file", e); //throw e; } finally { IOUtils.closeStream(is); IOUtils.closeStream(os); if (dirs != null) { FileUtils.deleteDirectory(dirs); } } } else { try { Path hdfs = new Path(hdfspath); hdfsFileSystem.copyToLocalFile(false, hdfs, local); inputStream = new FileInputStream(dirs + file_name); ftpClient.storeFile(file_name, new BufferedInputStream(inputStream)); } catch (Exception e) { log.error("Failed while doing FTP file", e); throw new FTPUtilException("Failed while doing FTP file", e); } finally { FileUtils.deleteDirectory(dirs); } } } else { java.nio.file.Path file = new File(runFileTransferEntity.getInputFilePath()).toPath(); if (Files.isDirectory(file)) { log.debug("Provided input file path is for directory"); File dir = new File(runFileTransferEntity.getInputFilePath()); String folderName = new File(runFileTransferEntity.getInputFilePath()).getName(); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/")); try { ftpClient.removeDirectory(folderName); } catch (IOException e) { log.error("Failed while doing FTP file", e); throw new FTPUtilException("Failed while doing FTP file", e); } ftpClient.makeDirectory(folderName); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + folderName); for (File files : dir.listFiles()) { if (files.isFile()) ftpClient.storeFile(files.getName().toString(), new BufferedInputStream(new FileInputStream(files))); } } else { inputStream = new FileInputStream(runFileTransferEntity.getInputFilePath()); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/")); int index = runFileTransferEntity.getInputFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/'); String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1); ftpClient.storeFile(file_name, new BufferedInputStream(inputStream)); } } } catch (Exception e) { log.error("Failed while doing FTP file", e); if (!login && runFileTransferEntity.getFailOnError()) { throw new FTPUtilException("Invalid FTP details"); } try { Thread.sleep(runFileTransferEntity.getRetryAfterDuration()); } catch (Exception e1) { log.error("Failed while sleeping for retry duration", e1); } continue; } finally { try { if (inputStream != null) inputStream.close(); } catch (IOException ioe) { } } done = true; break; } try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception e) { log.error("Failed while clossing the connection", e); } catch (Error e) { log.error("Failed while clossing the connection", e); //throw new RuntimeException(e); } if (runFileTransferEntity.getFailOnError() && !done) { log.error("File transfer failed"); throw new FTPUtilException("File transfer failed"); } else if (!done) { log.error("File transfer failed but mentioned fail on error as false"); } log.debug("Finished FTPUtil upload"); }