List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java
@Override public void run(ActionContext context) throws Exception { Path destination = new Path(config.getDestDirectory()); FileSystem fileSystem = FileSystem.get(new Configuration()); destination = fileSystem.makeQualified(destination); if (!fileSystem.exists(destination)) { fileSystem.mkdirs(destination);/*from ww w . j av a2s .c om*/ } FTPClient ftp; if ("ftp".equals(config.getProtocol().toLowerCase())) { ftp = new FTPClient(); } else { ftp = new FTPSClient(); } ftp.setControlKeepAliveTimeout(5); // UNIX type server FTPClientConfig ftpConfig = new FTPClientConfig(); // Set additional parameters required for the ftp // for example config.setServerTimeZoneId("Pacific/Pitcairn") ftp.configure(ftpConfig); try { ftp.connect(config.getHost(), config.getPort()); ftp.enterLocalPassiveMode(); String replyString = ftp.getReplyString(); LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(), config.getPort(), replyString); // Check the reply code for actual success int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.", replyCode, replyString)); } if (!ftp.login(config.getUserName(), config.getPassword())) { LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString()); ftp.logout(); throw new RuntimeException(String.format( "Login to the FTP server %s and port %s failed. " + "Please check user name and password.", config.getHost(), config.getPort())); } FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory()); LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString()); // Check the reply code for listFiles call. // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) { // encrypt data channel and listFiles again ((FTPSClient) ftp).execPROT("P"); LOG.info("Attempting command listFiles on encrypted data channel."); ftpFiles = ftp.listFiles(config.getSrcDirectory()); } for (FTPFile file : ftpFiles) { String source = config.getSrcDirectory() + "/" + file.getName(); LOG.info("Current file {}, source {}", file.getName(), source); if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) { copyZip(ftp, source, fileSystem, destination); } else { Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName())); LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString()); try (OutputStream output = fileSystem.create(destinationPath)) { InputStream is = ftp.retrieveFileStream(source); ByteStreams.copy(is, output); } } if (!ftp.completePendingCommand()) { LOG.error("Error completing command."); } } ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (Throwable e) { LOG.error("Failure to disconnect the ftp connection.", e); } } } }
From source file:com.ephesoft.dcma.util.FTPUtil.java
/** * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure. * //from w w w . j a v a2s .co m * @param sourceDirectoryPath the directory to be uploaded * @param destDirName the path on ftp where directory will be uploaded * @param numberOfRetryCounter number of attempts to be made for uploading the directory * @throws FTPDataUploadException if an error occurs while uploading the file * @throws IOException if an error occurs while making the ftp connection * @throws SocketException if an error occurs while making the ftp connection */ public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData) throws FTPDataUploadException, SocketException, IOException { boolean isValid = true; if (ftpInformation.getSourceDirectoryPath() == null) { isValid = false; LOGGER.error(VAR_SOURCE_DIR); throw new FTPDataUploadException(VAR_SOURCE_DIR); } if (ftpInformation.getDestDirName() == null) { isValid = false; LOGGER.error(VAR_SOURCE_DES); throw new FTPDataUploadException(VAR_SOURCE_DES); } if (isValid) { FTPClient client = new FTPClient(); String destDirName = ftpInformation.getDestDirName(); String destinationDirectory = ftpInformation.getUploadBaseDir(); if (destDirName != null && !destDirName.isEmpty()) { String uploadBaseDir = ftpInformation.getUploadBaseDir(); if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) { destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator, destDirName); } else { destinationDirectory = destDirName; } } FileInputStream fis = null; try { createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(), ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut()); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { LOGGER.info("Starting File Upload..."); } else { LOGGER.info("Invalid Connection to FTP server. Disconnecting Client"); client.disconnect(); isValid = false; throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client"); } if (isValid) { // code changed for keeping the control connection busy. client.setControlKeepAliveTimeout(300); client.setFileType(FTP.BINARY_FILE_TYPE); createFtpDirectoryTree(client, destinationDirectory); // client.makeDirectory(destinationDirectory); if (deleteExistingFTPData) { deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData); } File file = new File(ftpInformation.getSourceDirectoryPath()); if (file.isDirectory()) { String[] fileList = file.list(); for (String fileName : fileList) { String inputFile = EphesoftStringUtil .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName); File checkFile = new File(inputFile); if (checkFile.isFile()) { LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName)); fis = new FileInputStream(inputFile); try { client.storeFile(fileName, fis); } catch (IOException e) { int retryCounter = ftpInformation.getNumberOfRetryCounter(); LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-", (retryCounter + 1))); if (retryCounter < ftpInformation.getNumberOfRetries()) { retryCounter = retryCounter + 1; uploadDirectory(ftpInformation, deleteExistingFTPData); } else { LOGGER.error("Error in uploading the file to FTP server"); } } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { LOGGER.info(EphesoftStringUtil .concatenate("Could not close stream for file.", inputFile)); } } } } } } } catch (FileNotFoundException e) { LOGGER.error("File does not exist.."); } finally { try { client.disconnect(); } catch (IOException e) { LOGGER.error("Disconnecting from FTP server....", e); } } } }
From source file:com.github.wuic.nut.ftp.FtpNutDao.java
/** * <p>/*w w w .ja va2 s. c o m*/ * Opens a connection with the current FtpClient if its not already opened. * </p> * * @throws IOException if any I/O error occurs, the connection is refused or if the credentials are not correct */ private void connect() throws IOException { if (!ftpClient.isConnected()) { log.debug("Connecting to FTP server."); ftpClient.connect(hostName, port); log.debug(ftpClient.getReplyString()); // After connection attempt, you should check the reply code to verify success final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("FTP server refused connection."); } if (userName != null && !ftpClient.login(userName, password)) { throw new IOException("Bad FTP credentials."); } } }
From source file:com.naryx.tagfusion.cfm.tag.net.ftp.cfFTPData.java
public FTPFile[] listFiles(String directory) { if (!ftpclient.isConnected()) { errorText = "not connected"; succeeded = false;//from w ww . j ava 2s . c o m return null; } FTPFile[] files = null; try { files = ftpclient.listFiles(directory); errorCode = ftpclient.getReplyCode(); succeeded = FTPReply.isPositiveCompletion(errorCode); } catch (Exception e) { errorCode = ftpclient.getReplyCode(); errorText = e.getMessage(); } finally { setStatusData(); } return files; }
From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java
public void fetch(final FtpSubscription ftpSubscription) { if (_log.isDebugEnabled()) { _log.debug("fetching " + ftpSubscription); }//from ww w . ja va 2 s . com final FTPClient ftp = new FTPClient(); ftp.setControlKeepAliveTimeout(30); ftp.setControlKeepAliveReplyTimeout(30); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; ftp.connect(ftpSubscription.getFtpHost()); _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (final IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } boolean error = false; __main: try { if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) { ftp.logout(); error = true; break __main; } _log.info("Remote system is " + ftp.getSystemType()); ftp.setFileType(FTP.BINARY_FILE_TYPE); //ftp.enterLocalActiveMode(); ftp.enterLocalPassiveMode(); //final FTPClientConfig config = new FTPClientConfig(); ////config.setLenientFutureDates(true); //ftp.configure(config); if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) { ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder()); } final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile()); if (is == null) { _log.error("FIle not found: " + ftp.getSystemType()); } else { unzip(ftpSubscription, is); is.close(); } ftp.completePendingCommand(); } catch (final FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (final IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException e) { _log.error(e); } } } }
From source file:com.mirth.connect.connectors.file.filesystems.FtpsConnection.java
@Override public List<String> listDirectories(String fromDir) throws Exception { List<String> directories = new ArrayList<String>(); if (!cwd(fromDir)) { logger.error(//from w w w . ja v a 2 s .c om "listFiles.changeWorkingDirectory: " + client.getReplyCode() + "-" + client.getReplyString()); throw new IOException("Ftps error: " + client.getReplyCode()); } FTPFile[] ftpDirectories = client.listDirectories(); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { logger.error("listFiles.listFiles: " + client.getReplyCode() + "-" + client.getReplyString()); throw new IOException("Ftps error: " + client.getReplyCode()); } for (FTPFile directory : ftpDirectories) { if (directory != null) { directories.add(new FtpsFileInfo(fromDir, directory).getAbsolutePath()); } } return directories; }
From source file:edu.mda.bioinfo.ids.DownloadFiles.java
private void downloadFromFtpToFile(String theServer, String theServerFile, String theLocalFile) throws IOException, Exception { FTPClient ftp = new FTPClient(); try {//from w w w. ja v a 2s. com int reply = 0; boolean replyB = false; ftp.connect(theServer); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } else { ftp.login("anonymous", "anonymous"); replyB = ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.print(ftp.getReplyString()); System.out.println("replyB= " + replyB); if (false == replyB) { throw new Exception("Unable to login to " + theServer); } OutputStream output = new FileOutputStream(theLocalFile); replyB = ftp.retrieveFile(theServerFile, output); System.out.print(ftp.getReplyString()); System.out.println("replyB= " + replyB); if (false == replyB) { throw new Exception("Unable to retrieve " + theServerFile); } } ftp.logout(); } catch (IOException rethrownExp) { System.err.println("exception " + rethrownExp.getMessage()); throw rethrownExp; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignore) { // do nothing } } } }
From source file:com.maxl.java.amikodesk.Emailer.java
private void uploadToFTPServer(Author author, String name, String path) { FTPClient ftp_client = new FTPClient(); try {/*from ww w. j a v a2s . c o m*/ ftp_client.connect(author.getS(), 21); ftp_client.login(author.getL(), author.getP()); ftp_client.enterLocalPassiveMode(); ftp_client.changeWorkingDirectory(author.getO()); ftp_client.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } File local_file = new File(path); String remote_file = name + ".csv"; InputStream is = new FileInputStream(local_file); System.out.print("Uploading file " + name + " to server " + author.getS() + "... "); boolean done = ftp_client.storeFile(remote_file, is); if (done) System.out.println("file uploaded successfully."); else System.out.println("error."); is.close(); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftp_client.isConnected()) { ftp_client.logout(); ftp_client.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:net.sf.webphotos.sync.FTP.SyncObject.java
/** * Cria um novo subdiretrio no servidor FTP, no diretrio atual (se um * pathname relativo dado) ou onde especificado (se um pathname absoluto * dado). Esta uma verso recurssiva que cria os diretrios somente quando * so precisos.//w w w . j av a 2 s . co m * * @param pathName O nome do diretrio a ser criado. * @return True se completou com sucesso, ou false caso no. * @exception IOException Se um erro de I/O ocorrer enquanto est enviando * comando para o servidor ou recebendo resposta dele. */ @Override public boolean makeDirectory(String pathName) throws IOException { if (pathName.startsWith("/")) { changeWorkingDirectory("/"); pathName = pathName.substring(1); } Util.out.println(super.printWorkingDirectory()); String[] dirs = pathName.split("/"); for (String dir : dirs) { if (!super.printWorkingDirectory().endsWith(dir)) { super.changeWorkingDirectory(dir); if (!FTPReply.isPositiveCompletion(super.getReplyCode())) { super.makeDirectory(dir); super.changeWorkingDirectory(dir); if (!FTPReply.isPositiveCompletion(super.getReplyCode())) { return false; } } } } return (getReplyCode() == FTPReply.CODE_250 || getReplyCode() == FTPReply.CODE_250); }
From source file:com.claim.controller.FileTransferController.java
public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception { FTPClient ftpClient = new FTPClient(); int replyCode; boolean completed = false; try {// www . j a va2s.c o m FtpProperties properties = new ResourcesProperties().loadFTPProperties(); try { ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); FtpUtil.showServerReply(ftpClient); } catch (ConnectException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("ConnectException: " + ex.getMessage()); ex.printStackTrace(); } catch (SocketException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("SocketException: " + ex.getMessage()); ex.printStackTrace(); } catch (UnknownHostException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("UnknownHostException: " + ex.getMessage()); ex.printStackTrace(); } replyCode = ftpClient.getReplyCode(); FtpUtil.showServerReply(ftpClient); if (!FTPReply.isPositiveCompletion(replyCode)) { FtpUtil.showServerReply(ftpClient); ftpClient.disconnect(); Console.LOG("Exception in connecting to FTP Serve ", 0); throw new Exception("Exception in connecting to FTP Server"); } else { FtpUtil.showServerReply(ftpClient); Console.LOG("Success in connecting to FTP Serve ", 1); } try { boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); FtpUtil.showServerReply(ftpClient); if (!success) { throw new Exception("Could not login to the FTP server."); } else { Console.LOG("login to the FTP server. Successfully ", 1); } //ftpClient.enterLocalPassiveMode(); } catch (FTPConnectionClosedException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); // APPROACH #2: uploads second file using an OutputStream File files = new File(ftpObj.getFtp_directory_path()); String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator + ftpObj.getFtp_report_type(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType); FtpUtil.showServerReply(ftpClient); String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp); FtpUtil.showServerReply(ftpClient); for (File file : files.listFiles()) { if (file.isFile()) { System.out.println("file ::" + file.getName()); InputStream in = new FileInputStream(file); ftpClient.changeWorkingDirectory(workingDirectoryStmp); completed = ftpClient.storeFile(file.getName(), in); in.close(); Console.LOG( " " + file.getName() + " ", 1); FtpUtil.showServerReply(ftpClient); } } Console.LOG(" ?... ", 1); //completed = ftpClient.completePendingCommand(); FtpUtil.showServerReply(ftpClient); completed = true; ftpClient.disconnect(); } catch (IOException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); ex.printStackTrace(); } } return completed; }