List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:com.mirth.connect.connectors.file.filesystems.FtpsConnection.java
@Override public List<FileInfo> listFiles(String fromDir, String filenamePattern, boolean isRegex, boolean ignoreDot) throws Exception { FilenameFilter filenameFilter; if (isRegex) { filenameFilter = new RegexFilenameFilter(filenamePattern); } else {//w w w . j a v a2s . c o m filenameFilter = new WildcardFileFilter(filenamePattern.trim().split("\\s*,\\s*")); } if (!cwd(fromDir)) { logger.error( "listFiles.changeWorkingDirectory: " + client.getReplyCode() + "-" + client.getReplyString()); throw new IOException("Ftps error: " + client.getReplyCode()); } FTPFile[] files = client.listFiles(); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { logger.error("listFiles.listFiles: " + client.getReplyCode() + "-" + client.getReplyString()); throw new IOException("Ftps error: " + client.getReplyCode()); } if (files == null || files.length == 0) { return new ArrayList<FileInfo>(); } List<FileInfo> v = new ArrayList<FileInfo>(files.length); for (int i = 0; i < files.length; i++) { if ((files[i] != null) && files[i].isFile()) { if ((filenameFilter == null || filenameFilter.accept(null, files[i].getName())) && !(ignoreDot && files[i].getName().startsWith("."))) { v.add(new FtpsFileInfo(fromDir, files[i])); } } } return v; }
From source file:com.claim.support.FtpUtil.java
public void uploadMutiFileWithFTP(String targetDirectory, FileTransferController fileTransferController) { try {//w w w. ja va 2 s . c om FtpProperties properties = new ResourcesProperties().loadFTPProperties(); FTPClient ftp = new FTPClient(); ftp.connect(properties.getFtp_server()); if (!ftp.login(properties.getFtp_username(), properties.getFtp_password())) { ftp.logout(); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } ftp.enterLocalPassiveMode(); System.out.println("Remote system is " + ftp.getSystemName()); ftp.changeWorkingDirectory(targetDirectory); System.out.println("Current directory is " + ftp.printWorkingDirectory()); FTPFile[] ftpFiles = ftp.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { for (FTPFile file : ftpFiles) { if (!file.isFile()) { continue; } System.out.println("File is " + file.getName()); OutputStream output; output = new FileOutputStream( properties.getFtp_remote_directory() + File.separator + file.getName()); ftp.retrieveFile(file.getName(), output); output.close(); } } ftp.logout(); ftp.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.eryansky.common.utils.ftp.FtpFactory.java
/** * FTP?./*from w ww . j a va2s .co m*/ * * @param remotePath * FTP? * @param fileName * ??? * @param localPath * ?? * @return */ public boolean ftpDownFile(String remotePath, String fileName, String localPath) { // ? boolean success = false; // FTPClient FTPClient ftp = new FTPClient(); ftp.setControlEncoding("GBK"); try { int reply; // FTP? // ??ftp.connect(url)?FTP? ftp.connect(url, port); // ftp ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } // ftp.changeWorkingDirectory(remotePath); // FTPFile[] fs = ftp.listFiles(); // ?? for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { // ??? File localFile = new File(localPath + "/" + ff.getName()); // ? OutputStream is = new FileOutputStream(localFile); // ftp.retrieveFile(ff.getName(), is); is.close(); success = true; } } ftp.logout(); // ? } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
From source file:com.cloudhopper.commons.rfs.provider.FtpRemoteFileSystem.java
public void connect() throws FileSystemException { // make sure we don't connect twice if (ftp != null) { throw new FileSystemException("Already connected to FTP(s) server"); }// w ww.j ava2 s .c om // either create an SSL FTP client or normal one if (getProtocol() == Protocol.FTPS) { try { ftp = new FTPSClient(); } catch (Exception e) { //} catch (NoSuchAlgorithmException e) { throw new FileSystemException("Unable to create FTPS client: " + e.getMessage(), e); } } else { ftp = new FTPClient(); } // // connect to ftp(s) server // try { int reply; // either connect to the default port or an overridden one if (getURL().getPort() == null) { ftp.connect(getURL().getHost()); } else { ftp.connect(getURL().getHost(), getURL().getPort().intValue()); } // After connection attempt, check reply code to verify we're connected reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // make sure we're definitely disconnected before we throw exception try { ftp.disconnect(); } catch (Exception e) { } ftp = null; throw new FileSystemException("FTP server refused connection (replyCode=" + reply + ")"); } logger.info("Connected to remote FTP server @ " + getURL().getHost() + " (not authenticated yet)"); } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (Exception ex) { } } ftp = null; throw new FileSystemException("Unabled to connect to FTP server @ " + getURL().getHost(), e); } // // login either anonymously or with user/pass combo // try { boolean loggedIn = false; if (getURL().getUsername() == null) { logger.info("Logging in anonymously to FTP server"); loggedIn = ftp.login("anonymous", ""); } else { logger.info("Logging in with username and password to FTP server"); loggedIn = ftp.login(getURL().getUsername(), (getURL().getPassword() == null ? "" : getURL().getPassword())); } // did the login work? if (!loggedIn) { throw new FileSystemException("Login failed with FTP server (reply=" + ftp.getReplyString() + ")"); } // // if we're using a secure protocol, encrypt the data channel // if (getProtocol() == Protocol.FTPS) { logger.info("Requesting FTP data channel to also be encrypted with SSL/TLS"); ((FTPSClient) ftp).execPROT("P"); // ignore if this actually worked or not -- file just fail to copy } // // make sure we're using binary files // ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException( "FTP server failed to switch to binary file mode (reply=" + ftp.getReplyString() + ")"); } // should we go into passive or active mode? if (mode == Mode.ACTIVE) { ftp.enterLocalActiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException( "FTP server failed to switch to active mode (reply=" + ftp.getReplyString() + ")"); } } else if (mode == Mode.PASSIVE) { ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException( "FTP server failed to switch to passive mode (reply=" + ftp.getReplyString() + ")"); } } // // handle making or changing directories // // if the path is not empty if (!StringUtil.isEmpty(getURL().getPath())) { // recursively iterate thru directory path and attempt to create the path StringTokenizer path = new StringTokenizer(getURL().getPath(), "/"); // create an array list of tokens ArrayList<String> pathParts = new ArrayList<String>(); while (path.hasMoreTokens()) { pathParts.add(path.nextToken()); } // index we'll start searching for int i = 0; // determine path of directories we're going to take if (pathParts.size() > 0 && pathParts.get(i).equals("~")) { // stay in home directory once logged in // just increment what we'll search from i = 1; } else { // change to root directory first if (!ftp.changeWorkingDirectory("/")) { throw new FileSystemException("FTP server failed to change to root directory (reply=" + ftp.getReplyString() + ")"); } } for (; i < pathParts.size(); i++) { // try to change to this directory String pathPart = pathParts.get(i); boolean changedDir = ftp.changeWorkingDirectory(pathPart); if (!changedDir) { if (!mkdir) { // now try to change to it again if (!ftp.changeWorkingDirectory(pathPart)) { throw new FileSystemException("Unable to change to directory " + getURL().getPath() + " on FTP server: " + pathPart + " does not exist"); } } else { // try to create it logger.info("Making new directory on FTP server: " + pathPart); if (!ftp.makeDirectory(pathPart)) { throw new FileSystemException( "Unable to make directory '" + pathPart + "' on FTP server"); } // now try to change to it again if (!ftp.changeWorkingDirectory(pathPart)) { throw new FileSystemException( "Unable to change to new directory '" + pathPart + "' on FTP server"); } } } } // just print out our working directory } else { // staying in whatever directory we were assigned by default // for information purposeds, let's try to print out that dir String currentDir = ftp.printWorkingDirectory(); logger.info("Current FTP working directory: " + currentDir); } } catch (FileSystemException e) { // make sure to disconnect, then rethrow error try { ftp.disconnect(); } catch (Exception ex) { } ftp = null; throw e; } catch (IOException e) { // make sure we're definitely disconnected before we throw exception try { ftp.disconnect(); } catch (Exception ex) { } ftp = null; throw new FileSystemException("Underlying IO exception with FTP server during login and setup process", e); } }
From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java
@Override public List<FileInfo> browser(String path) { List<FileInfo> fileInfos = new ArrayList<FileInfo>(); // PluginConfig pluginConfig = getPluginConfig(); // if (pluginConfig != null) { Map<String, String> ftpInfo = getFtpInfo("all"); String urlPrefix = DataConfig.getConfig("IMGFTPROOT"); FTPClient ftpClient = new FTPClient(); try {//from w w w .jav a2 s.c om 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(); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) { for (FTPFile ftpFile : ftpClient.listFiles()) { FileInfo fileInfo = new FileInfo(); fileInfo.setName(ftpFile.getName()); fileInfo.setUrl(urlPrefix + path + ftpFile.getName()); fileInfo.setIsDirectory(ftpFile.isDirectory()); fileInfo.setSize(ftpFile.getSize()); fileInfo.setLastModified(ftpFile.getTimestamp().getTime()); fileInfos.add(fileInfo); } } } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } // } return fileInfos; }
From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java
@Nullable private static String uploadFileToFTP(final File reportPath, @NonNls final String ftpSite, @NonNls final String directory, final ProgressIndicator indicator) { FTPClient ftp = new FTPClient(); ftp.setConnectTimeout(30 * 1000);// ww w . j a v a 2 s. co m try { indicator.setText("Connecting to server..."); ftp.connect(ftpSite); indicator.setText("Connected to server"); if (!ftp.login("anonymous", "anonymous@jetbrains.com")) { return "Failed to login"; } indicator.setText("Logged in"); // After connection attempt, you should check the reply code to verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return "FTP server refused connection: " + reply; } if (!ftp.changeWorkingDirectory(directory)) { return "Failed to change directory"; } // else won't work behind FW ftp.enterLocalPassiveMode(); if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) { return "Failed to switch to binary mode"; } indicator.setText("Transferring (" + StringUtil.formatFileSize(reportPath.length()) + ")"); FileInputStream readStream = new FileInputStream(reportPath); try { if (!ftp.storeFile(reportPath.getName(), readStream)) { return "Failed to upload file"; } } catch (IOException e) { return "Error during transfer: " + e.getMessage(); } finally { readStream.close(); } ftp.logout(); return null; } catch (IOException e) { return "Failed to upload: " + e.getMessage(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } }
From source file:adams.core.io.lister.FtpDirectoryLister.java
/** * Returns a new client for the host defined in the options. * * @return the client, null if failed to create */// w ww . j av a 2s . c o m protected FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:com.dp2345.plugin.ftp.FtpPlugin.java
@Override public List<FileInfo> browser(String path) { List<FileInfo> fileInfos = new ArrayList<FileInfo>(); PluginConfig pluginConfig = getPluginConfig(); if (pluginConfig != null) { String host = pluginConfig.getAttribute("host"); Integer port = Integer.valueOf(pluginConfig.getAttribute("port")); String username = pluginConfig.getAttribute("username"); String password = pluginConfig.getAttribute("password"); String urlPrefix = pluginConfig.getAttribute("urlPrefix"); FTPClient ftpClient = new FTPClient(); try {//from w ww .j ava2s .c om ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) { for (FTPFile ftpFile : ftpClient.listFiles()) { FileInfo fileInfo = new FileInfo(); fileInfo.setName(ftpFile.getName()); fileInfo.setUrl(urlPrefix + path + ftpFile.getName()); fileInfo.setIsDirectory(ftpFile.isDirectory()); fileInfo.setSize(ftpFile.getSize()); fileInfo.setLastModified(ftpFile.getTimestamp().getTime()); fileInfos.add(fileInfo); } } } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } } return fileInfos; }
From source file:com.datos.vfs.provider.ftp.FTPClientWrapper.java
private FTPFile[] listFilesInDirectory(final String relPath) throws IOException { FTPFile[] files;// www. j a v a2 s . c o m // VFS-307: no check if we can simply list the files, this might fail if there are spaces in the path files = getFtpClient().listFiles(relPath); if (FTPReply.isPositiveCompletion(getFtpClient().getReplyCode())) { return files; } // VFS-307: now try the hard way by cd'ing into the directory, list and cd back // if VFS is required to fallback here the user might experience a real bad FTP performance // as then every list requires 4 ftp commands. String workingDirectory = null; if (relPath != null) { workingDirectory = getFtpClient().printWorkingDirectory(); if (!getFtpClient().changeWorkingDirectory(relPath)) { return null; } } files = getFtpClient().listFiles(); if (relPath != null && !getFtpClient().changeWorkingDirectory(workingDirectory)) { throw new FileSystemException("vfs.provider.ftp.wrapper/change-work-directory-back.error", workingDirectory); } return files; }
From source file:com.consol.citrus.ftp.client.FtpClient.java
/** * Opens a new connection and performs login with user name and password if set. * @throws IOException//from w ww . j a v a 2s . c o m */ protected void connectAndLogin() throws IOException { if (!ftpClient.isConnected()) { ftpClient.connect(getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()); log.info("Connected to FTP server: " + ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new CitrusRuntimeException("FTP server refused connection."); } log.info("Successfully opened connection to FTP server"); if (getEndpointConfiguration().getUser() != null) { log.info(String.format("Login as user: '%s'", getEndpointConfiguration().getUser())); boolean login = ftpClient.login(getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword()); if (!login) { throw new CitrusRuntimeException(String.format( "Failed to login to FTP server using credentials: %s:%s", getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword())); } } } }