List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:org.runmyprocess.sec.FTP.java
public FTP() { // TODO Auto-generated constructor stub this.client = new FTPClient(); }
From source file:org.runmyprocess.sec.FTP.java
/** * receives the object with the path to look for the file and read the configuration file * @param jsonObject// w ww . ja v a 2 s .c o m * @param configPath */ @Override public void accept(JSONObject jsonObject, String configPath) { try { LOG.log("NEW REQUEST", Level.INFO); Config config = new Config("configFiles" + File.separator + "FTP.config", true);//finds and reads the config file // get an ftpClient object if (client == null || jsonObject.containsKey("FTPType")) { if (jsonObject.getString("FTPType") == "FTP") { this.client = new FTPClient(); } else if (jsonObject.getString("FTPType") == "FTPS") { this.client = new FTPSClient(); } } LOG.log("NEW REQUEST CLIENT SET", Level.INFO); try { // pass directory path on server to connect if (!this.connect(config.getProperty("host"), jsonObject.getString("user"), jsonObject.getString("password"), Integer.parseInt(config.getProperty("port")))) { throw new Exception("Unable to loggin to FTP"); } LOG.log("Connection established...", Level.INFO); Task task = Task.DEFAULT; if (jsonObject.containsKey("task")) try { task = Task.valueOf(jsonObject.getString("task")); } catch (Exception ex) { //do NOTHING task not found } LOG.log(task.name(), Level.INFO); switch (task) { case PING: ping(jsonObject); break; case GET: fetchFile(jsonObject); break; case PUT: upload(jsonObject); break; case LIST: listFiles(jsonObject); break; case DELETE: remove(jsonObject); break; case RENAME: rename(jsonObject); break; case MKDIR: createDir(jsonObject); break; case RMDIR: removeDir(jsonObject); break; case DEFAULT: throw new Exception("Task not found"); } } catch (SocketException e) { e.printStackTrace(); throw new Exception(e); } catch (IOException e) { e.printStackTrace(); throw new Exception(e); } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } finally { try { if (this.logged) this.client.logout(); this.client.disconnect(); LOG.log("Disconnected", Level.INFO); } catch (IOException e) { e.printStackTrace(); throw new Exception(e); } } } catch (Exception e) { response.setData(this.FTPError(e.toString())); SECErrorManager errorManager = new SECErrorManager(); errorManager.logError(e.toString(), Level.SEVERE); e.printStackTrace(); } }
From source file:org.schedoscope.export.ftp.FtpExportCSVMRTest.java
private int getFileCount() throws IOException { FTPClient ftp = new FTPClient(); ftp.connect("localhost", 2221); ftp.login(EmbeddedFtpSftpServer.FTP_USER_FOR_TESTING, EmbeddedFtpSftpServer.FTP_PASS_FOR_TESTING); FTPFile[] files = ftp.listFiles();// w w w . j a v a 2 s . c o m int fileCounter = 0; for (FTPFile f : files) { if (f.getName().contains(filePrefix)) { fileCounter += 1; } } return fileCounter; }
From source file:org.shept.util.FtpFileCopy.java
public int ftpSyncLocal(FtpConfig config, String localPath, String filePattern) { boolean rc = false; FTPClient ftpC = new FTPClient(); int num = -1; try {/*from w w w .ja v a 2 s . c o m*/ rc = configSetup(config, ftpC); if (!rc) { return 0; } num = syncPull(ftpC, localPath, filePattern); } catch (Exception ex) { logger.error("Ftp preparing fileCopy did not succeed: " + config.toString(), ex); } try { ftpC.disconnect(); } catch (Exception ex) { } ; return num; }
From source file:org.shept.util.FtpFileCopy.java
public int ftpSyncRemote(FtpConfig config, String remotePath, String filePattern) { boolean rc = false; FTPClient ftpC = new FTPClient(); int num = -1; try {//ww w .j a v a 2 s . c o m rc = configSetup(config, ftpC); if (!rc) { return 0; } num = syncPush(remotePath, ftpC, filePattern); } catch (Exception ex) { logger.error("Ftp preparing fileCopy did not succeed: " + config.toString(), ex); } try { ftpC.disconnect(); } catch (Exception ex) { } ; return num; }
From source file:org.sipfoundry.preflight.FTP.java
public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService, InetAddress bindAddress) { ResultCode results = NONE;/*from ww w. j a v a 2 s.c o m*/ InetAddress ftpServerAddress = null; String testFile = new String("00D01EFFFFFE"); String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server", "[PROVISION]", "decrypt_key" }; if (networkResources.configServer == null) { journalService.println("No FTP server provided, skipping test.\n"); return CONFIG_SERVER_MISSING; } journalService.println("Starting FTP server test."); if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) { try { ftpServerAddress = InetAddress.getByName(networkResources.configServer); } catch (UnknownHostException e) { // Should never get here. e.printStackTrace(); } journalService.println("Using FTP server literal address: " + networkResources.configServer); } else { // Try to retrieve A RECORD for FTP server, checking each DNS server. SimpleResolver resolver = null; try { resolver = new SimpleResolver(); resolver.setLocalAddress(bindAddress); resolver.setTimeout(timeout); } catch (UnknownHostException e) { e.printStackTrace(); } for (InetAddress dnsServer : networkResources.domainNameServers) { journalService.println( "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName()); String targetMessage = new String(" FTP server address \"" + networkResources.configServer + "\""); resolver.setAddress(dnsServer); Lookup aLookup = null; try { aLookup = new Lookup(networkResources.configServer, Type.A); } catch (TextParseException e) { journalService.println(" is malformed.\n"); journalService.println(targetMessage); return FTP_ADDRESS_MALFORMED; } aLookup.setResolver(resolver); Record[] aRecords = aLookup.run(); switch (aLookup.getResult()) { case Lookup.SUCCESSFUL: if (aRecords != null) { InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress(); targetMessage += " resolves to: " + targetAddress.getHostAddress(); journalService.println(targetMessage); if (ftpServerAddress == null) { ftpServerAddress = targetAddress; } else { // Check that multiple lookups result in same // address. if (!ftpServerAddress.equals(targetAddress)) { journalService.println(" FTP server address does not match prior lookup."); results = MULTIPLE_CONFIG_TARGETS; } } } else { targetMessage += " could not be resolved."; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; } break; case Lookup.UNRECOVERABLE: targetMessage += " [Unrecoverable error]"; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; case Lookup.TRY_AGAIN: targetMessage += " [Lookup timeout]"; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; case Lookup.HOST_NOT_FOUND: targetMessage += " could not be resolved."; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; case Lookup.TYPE_NOT_FOUND: targetMessage += " could not be resolved."; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; } } } if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) { journalService.println("Cannot recover from previous errors, aborting FTP test.\n"); return results; } journalService.println("Beginning FTP get request of test file: " + testFile); // Open the FTP connection. FTPClient ftp = new FTPClient(); ftp.setDefaultTimeout(timeout * 1000); ftp.addProtocolCommandListener(new PrintCommandListener(journalService)); try { int reply; ftp.connect(ftpServerAddress, 21, bindAddress, bindPort); // After connection, check reply code to verify. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); journalService.println("FTP client failure: " + reply + "\n"); return FTP_CLIENT_FAILURE; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // Ignore. } } journalService.println("FTP client failure: " + e.getMessage() + "\n"); return FTP_CLIENT_FAILURE; } try { if (!ftp.login(ftpUser, ftpPassword)) { ftp.logout(); journalService.println("FTP client unable to log in.\n"); return FTP_GET_FAILED; } journalService.println("FTP client connected to: " + ftp.getSystemName()); ftp.enterLocalPassiveMode(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ftp.retrieveFile(testFile, output); // After receiving, check reply code to verify. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); journalService.println("FTP get failure: " + reply + "\n"); return FTP_GET_FAILED; } ftp.logout(); String testFileContents = output.toString(); boolean verified = true; for (String verificationString : verificationStrings) { if (!testFileContents.contains(verificationString)) { verified = false; } } if (verified) { journalService.println("File received successfully."); } else { journalService.println("File received but contents do not verify."); System.err.println(testFileContents); results = FTP_CONTENTS_FAILED; } } catch (FTPConnectionClosedException e) { journalService.println("FTP server closed connection prematurely.\n"); return FTP_GET_FAILED; } catch (IOException e) { journalService.println("FTP client failure. " + e.getMessage() + "\n"); return FTP_CLIENT_FAILURE; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // Ignore. } } } journalService.println(""); return results; }
From source file:org.sipfoundry.sipxconfig.admin.ftp.FtpContextImpl.java
public void openConnection() { if (m_client != null) { return;/*www . j av a2 s . c o m*/ } m_client = new FTPClient(); try { m_client.connect(m_host); int reply = m_client.getReplyCode(); // After connection attempt, you should check the reply code to verify // success. if (!FTPReply.isPositiveCompletion(reply)) { closeConnection(); throw new UserException("&message.refusedConnection"); } if (!m_client.login(m_userId, m_password)) { closeConnection(); throw new UserException("&message.userPass"); } m_client.setFileType(FTP.BINARY_FILE_TYPE); m_client.enterLocalPassiveMode(); } catch (IOException e) { LOG.error(e); throw new UserException("&message.notConnect"); } }
From source file:org.smartfrog.avalanche.client.sf.ftp.FTPDownload.java
/** * @param server/*from w w w.ja v a 2s .com*/ * @param uname * @param passwd */ public FTPDownload(String server, String uname, String passwd) { ftpServer = server; userName = uname; passWord = passwd; ftp = new FTPClient(); }
From source file:org.smartfrog.avalanche.server.ftp.FTPRepository.java
/** * /*w ww.ja v a2 s. c o m*/ */ protected FTPRepository(RepositoryConfig cfg) throws RepositoryConfigException { this.config = cfg; super.ftp = new FTPClient(); super.repository = this; /* * validate mandatory attributes */ ftpServer = config.getAttribute(FTPSERVER); if (null == ftpServer) { log.error("FTP server location not specified"); throw new RepositoryConfigException("FTP server location not specified"); } userName = config.getAttribute(USERNAME); if (null == userName) { log.error("FTP username location not specified"); throw new RepositoryConfigException("FTP username location not specified"); } password = config.getAttribute(PASSWORD); path = config.getAttribute(PATH); // get optional attributes for proxy settings. String ftpProxyHost = config.getAttribute(PROXYHOST); if (null != ftpProxyHost) { System.getProperties().put("ftp.proxyHost", ftpProxyHost); } String ftpProxyPort = config.getAttribute(PROXYPORT); if (null != ftpProxyPort) { System.getProperties().put("ftp.proxyPort", ftpProxyPort); } // socks proxy .. String socksProxyHost = config.getAttribute(SOCKSPROXYHOST); if (null != socksProxyHost) { System.getProperties().put("socksProxyHost", socksProxyHost); } String socksProxyPort = config.getAttribute(SOCKSPROXYPORT); if (null != socksProxyPort) { System.getProperties().put("socksProxyPort", socksProxyPort); } fileFormat = config.getAttribute(FILEFORMAT); if (fileFormat == null) //default is BINARY format fileFormat = "binary"; //super.filePath=path; }
From source file:org.smartfrog.services.net.FTPClientImpl.java
/** * Sends or retrieve files over FTP using attributes specified in the * SmartFrog description of the component. * * @throws SmartFrogException in case of error in sending email * @throws RemoteException in case of network/emi error */// w ww . ja v a 2 s . co m public synchronized void sfStart() throws SmartFrogException, RemoteException { super.sfStart(); try { ftpClient = new FTPClient(); int reply; // get password from password provider password = pwdProvider.getPassword(); ftpClient.connect(ftpServer); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); throw new SmartFrogLifecycleException("FTP Server:[" + ftpServer + "] refused connection"); } //login if (!ftpClient.login(user, password)) { ftpClient.logout(); } //check type of file transfer if (BINARY.equals(transferMode)) { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. ftpClient.enterLocalPassiveMode(); if (GET.equals(transferType)) { getFiles(remoteFileList, localFileList); } else if (PUT.equals(transferType)) { putFiles(remoteFileList, localFileList); } else { throw new SmartFrogLifecycleException("Unsupported transfer type:" + transferType); } //logout ftpClient.logout(); // check if it should terminate by itself if (shouldTerminate) { TerminationRecord termR = TerminationRecord.normal("FTP finished: ", sfCompleteName()); TerminatorThread terminator = new TerminatorThread(this, termR); terminator.start(); } } catch (FTPConnectionClosedException e) { throw new SmartFrogLifecycleException("Server Closed Connection" + e, e); } catch (IOException ioe) { throw new SmartFrogLifecycleException(ioe); } finally { disconnectQuietly(); } }