List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:com.glaf.core.util.FtpUtils.java
/** * ???FTP?/* w ww.j a v a 2 s .co m*/ */ public static FTPClient connectServer() { String ip = conf.get("ftp.host", "127.0.0.1"); int port = conf.getInt("ftp.port", 21); String user = conf.get("ftp.user", "admin"); String password = conf.get("ftp.password", "admin"); try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(ip, port); ftpClient.login(user, password); ftpClientLocal.set(ftpClient); logger.info("login success!"); return ftpClient; } catch (IOException ex) { ex.printStackTrace(); logger.error("login failed", ex); throw new RuntimeException(ex); } }
From source file:com.datatorrent.lib.io.FtpInputOperator.java
@Override public void setup(OperatorContext arg0) { ftp = new FTPClient(); if (ftpServer == null) { throw new RuntimeException("The ftp server can't be null"); }//from www. ja v a 2 s. com if (filePath == null) { throw new RuntimeException("The file Path can't be null"); } try { if (port != 0) { ftp.connect(ftpServer, port); } else { ftp.connect(ftpServer); } if (localPassiveMode) { ftp.enterLocalPassiveMode(); } ftp.login(getUserName(), getPassword()); InputStream is = ftp.retrieveFileStream(filePath); InputStreamReader reader; if (isGzip) { GZIPInputStream gzis = new GZIPInputStream(is); reader = new InputStreamReader(gzis); } else { reader = new InputStreamReader(is); } in = new BufferedReader(reader); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.thebigbang.ftpclient.FTPOperation.java
/** * will force keep the device turned on for all the operation duration. * @param params/* ww w . j a v a 2 s . co m*/ * @return */ @SuppressLint("Wakelock") @SuppressWarnings("deprecation") @Override protected Boolean doInBackground(FTPBundle... params) { Thread.currentThread().setName("FTPOperationWorker"); for (final FTPBundle bundle : params) { FTPClient ftp = new FTPClient(); PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client"); try { // setup ftp connection: InetAddress addr = InetAddress.getByName(bundle.FTPServerHost); //set here the timeout. TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() { @Override public void Occurred(TimeoutException e) { bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; publishProgress(bundle); } }); timeout.start(); ftp.connect(addr, bundle.FTPServerPort); int reply = ftp.getReplyCode(); timeout.Stop(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("connection refuse"); } ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword); if (bundle.OperationType == FTPOperationType.Connect) { bundle.OperationStatus = FTPOperationStatus.Succed; publishProgress(bundle); continue; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); w.acquire(); // then switch between enum of operation types. if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.GetData) { String finalFPFi = bundle.LocalFilePathName; // The remote filename to be downloaded. if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") { File f = new File(bundle.LocalWorkingDirectory); f.mkdirs(); finalFPFi = bundle.LocalWorkingDirectory + finalFPFi; } FileOutputStream fos = new FileOutputStream(finalFPFi); // Download file from FTP server String finalFileN = bundle.RemoteFilePathName; if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") { finalFileN = bundle.RemoteWorkingDirectory + finalFileN; } boolean b = ftp.retrieveFile(finalFileN, fos); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; fos.close(); } else if (bundle.OperationType == FTPOperationType.SendData) { InputStream istr = new FileInputStream(bundle.LocalFilePathName); ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr); istr.close(); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; } else if (bundle.OperationType == FTPOperationType.DeleteData) { throw new IOException("DeleteData is Not yet implemented"); } ftp.disconnect(); // then finish/return. //publishProgress(bundle); } catch (IOException e) { e.printStackTrace(); bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; } try { w.release(); } catch (RuntimeException ex) { ex.printStackTrace(); } publishProgress(bundle); } return true; }
From source file:net.paissad.jcamstream.utils.FTPUtils.java
public void estabishConnection() throws SocketException, IOException, FTPException { this.setFtpClient(new FTPClient()); String errMsg;// www. j av a 2s . c o m FTPClient client = this.getFtpClient(); PrintCommandListener listener = new PrintCommandListener(System.out); client.addProtocolCommandListener(listener); // Connects to the FTP server String host = this.getFtpServerHost(); int port = this.getFtpServerPort(); client.connect(host, port); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); errMsg = "Unable to connect to the server " + this.getFtpServerHost(); this.verifyReplyCode(errMsg); } // Login to the FTP server String username = this.getFtpUser(); String pass = this.getFtpPassword(); if (!client.login(username, pass)) { errMsg = "Unable to login to " + this.getFtpServerHost(); this.verifyReplyCode(errMsg); } // Change the current directory String dirname = this.getFtpServerDir(); if (!client.changeWorkingDirectory(dirname)) { System.out.println("Unable to change to the directory '" + dirname + "'."); System.out.println("Going to create the directory !"); this.mkdirs(dirname); System.out.println("Creation of the directory is successful."); } client.changeWorkingDirectory(dirname); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { errMsg = "Unable to change to the directory : " + dirname; this.verifyReplyCode(errMsg); } client.pwd(); }
From source file:com.tumblr.maximopro.iface.router.FTPHandler.java
@Override public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException { byte[] encodedData = super.invoke(metaData, data); this.metaData = metaData; FTPClient ftp;/*from w w w .j a v a2 s .c o m*/ if (enableSSL()) { FTPSClient ftps = new FTPSClient(isImplicit()); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); ftp = ftps; } else { ftp = new FTPClient(); } InputStream is = null; try { if (getTimeout() > 0) { ftp.setDefaultTimeout(getTimeout()); } if (getBufferSize() > 0) { ftp.setBufferSize(getBufferSize()); } if (getNoDelay()) { ftp.setTcpNoDelay(getNoDelay()); } ftp.connect(getHostname(), getPort()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } if (!ftp.login(getUsername(), getPassword())) { ftp.logout(); ftp.disconnect(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (enableActive()) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } is = new ByteArrayInputStream(encodedData); String remoteFileName = getFileName(metaData); ftp.changeWorkingDirectory("/"); if (createDirectoryStructure(ftp, getDirName().split("/"))) { ftp.storeFile(remoteFileName, is); } else { throw new MXApplicationException("iface", "cannotcreatedir"); } ftp.logout(); } catch (MXException e) { throw e; } catch (SocketException e) { throw new MXApplicationException("iface", "ftpsocketerror", e); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } } return null; }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient ftp = null;/* w w w .ja v a 2 s . c o m*/ try { ftp = new FTPClient(); // For debug // f.addProtocolCommandListener(new PrintCommandListener( // new PrintWriter(System.out))); ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(fpi.getHost()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); ftp.login(fpi.getUsername(), fpi.getPassword()); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); if (fpi.isFtpUsePassiveMode()) ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); FTPClient ftpReturn = ftp; ftp = null; return ftpReturn; } finally { if (ftp != null) ftpQuietDisconnect(ftp); } }
From source file:edu.cmu.cs.in.hoop.hoops.load.HoopFTPReader.java
/** * //w w w. j a v a 2s. c o m */ private String retrieveFTP(String aURL) { debug("retrieveFTP (" + aURL + ")"); URL urlObject = null; try { urlObject = new URL(aURL); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String downloadPath = this.projectToFullPath("<PROJECTPATH>/tmp/download/"); HoopLink.fManager.createDirectory(downloadPath); File translator = new File(urlObject.getFile()); String localFileName = "<PROJECTPATH>/tmp/download/" + translator.getName(); OutputStream fileStream = null; if (HoopLink.fManager.openStreamBinary(this.projectToFullPath(localFileName)) == false) { this.setErrorString("Error opening temporary output file"); return (null); } fileStream = HoopLink.fManager.getOutputStreamBinary(); if (fileStream == null) { this.setErrorString("Error opening temporary output file"); return (null); } debug("Starting FTP client ..."); FTPClient ftp = new FTPClient(); try { int reply; debug("Connecting ..."); ftp.connect(urlObject.getHost()); debug("Connected to " + urlObject.getHost() + "."); debug(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); debug("FTP server refused connection."); return (null); } else { ftp.login("anonymous", "hoop-dev@gmail.com"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); debug("Unable to login to FTP server"); return (null); } debug("Logged in"); boolean rep = true; String pathFixed = translator.getParent().replace("\\", "/"); rep = ftp.changeWorkingDirectory(pathFixed); if (rep == false) { debug("Unable to change working directory to: " + pathFixed); return (null); } else { debug("Current working directory: " + pathFixed); debug("Retrieving file " + urlObject.getFile() + " ..."); try { rep = ftp.retrieveFile(urlObject.getFile(), fileStream); } catch (FTPConnectionClosedException connEx) { debug("Caught: FTPConnectionClosedException"); connEx.printStackTrace(); return (null); } catch (CopyStreamException strEx) { debug("Caught: CopyStreamException"); strEx.printStackTrace(); return (null); } catch (IOException ioEx) { debug("Caught: IOException"); ioEx.printStackTrace(); return (null); } debug("File retrieved"); } ftp.logout(); } } catch (IOException e) { debug("Error retrieving FTP file"); e.printStackTrace(); return (null); } finally { if (ftp.isConnected()) { debug("Closing ftp connection ..."); try { ftp.disconnect(); } catch (IOException ioe) { debug("Exception closing ftp connection"); } } } debug("Closing local file stream ..."); try { fileStream.close(); } catch (IOException e) { e.printStackTrace(); } String result = HoopLink.fManager.loadContents(this.projectToFullPath(localFileName)); return (result); }
From source file:net.seedboxer.common.ftp.FtpUploaderCommons.java
@Override public void configure(String server, String username, String password, String remotePath, boolean ssl) throws Exception { if (ssl) {/*from w w w .j a va 2 s . c o m*/ this.ftpClient = new FTPSClient("SSL", true); } else { this.ftpClient = new FTPClient(); } this.server = server; this.username = username; this.password = password; this.remotePath = remotePath; }
From source file:de.ep3.ftpc.model.CrawlerThread.java
private void runStatusCheck() { switch (crawler.getStatus()) { case IDLE:/*from w ww .ja v a 2 s . c om*/ tryDisconnect(); currentSleep = defaultSleep; break; case RUNNING: if (ftpClient == null) { ftpClient = new FTPClient(); } if (!ftpClient.isConnected()) { currentServer = crawler.getServer(); try { setTranslatedStatusMessage("crawlerTryConnect"); ftpClient.connect(currentServer.need("server.ip"), Integer.parseInt(currentServer.need("server.port"))); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new IOException(i18n.translate("crawlerServerRefused")); } if (currentServer.has("user.name")) { String userName = currentServer.get("user.name"); String userPassword = ""; if (currentServer.hasTemporary("user.password")) { userPassword = currentServer.getTemporary("user.password"); } loggedIn = ftpClient.login(userName, userPassword); if (!loggedIn) { throw new IOException(i18n.translate("crawlerServerAuthFail")); } } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); setTranslatedStatusMessage("crawlerConnected"); /* Prepare directories */ crawlerDirectories = new CrawlerDirectories(ftpClient, currentServer.get("include-paths"), currentServer.get("exclude-paths")); crawlerResults.clear(); } catch (IOException e) { messageQueue.add(i18n.translate("crawlerConnectionFailed", currentServer.need("server.name"), e.getMessage())); tryStop(); return; } } try { runSearch(); } catch (IOException e) { messageQueue.add(i18n.translate("crawlerProblem", e.getMessage())); tryStop(); } currentSleep = runningSleep; break; case PAUSED: if (ftpClient != null && ftpClient.isConnected()) { try { ftpClient.noop(); setTranslatedStatusMessage("crawlerPaused"); } catch (IOException e) { messageQueue.add(e.getMessage()); tryStop(); } } currentSleep = pausedSleep; break; } }
From source file:main.TestManager.java
/** * Deletes all local tests, downloads tests from the server * and saves all downloaded test in the local directory. */// w ww. j a v a 2 s . c om public static void syncTestsWithServer() { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; String server = "zajicek.endora.cz"; ftp.connect(server, 21); // After connection attempt, we check the reply code to verify // success. reply = ftp.getReplyCode(); //Not connected successfully - inform the user if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); Debugger.println("FTP server refused connection."); ErrorInformer.failedSyncing(); return; } // LOGIN boolean success = ftp.login("plakato", "L13nK4"); Debugger.println("Login successful: " + success); if (success == false) { ftp.disconnect(); ErrorInformer.failedSyncing(); return; } ftp.enterLocalPassiveMode(); // Get all files from the server FTPFile[] files = ftp.listFiles(); System.out.println("Got files! Count: " + files.length); // Delete all current test to be replaced with // actulized version File[] locals = new File("src/tests/").listFiles(); for (File f : locals) { if (f.getName() == "." || f.getName() == "..") { continue; } f.delete(); } // Copy the files from server to local folder int failed = 0; for (FTPFile f : files) { if (f.isFile()) { Debugger.println(f.getName()); if (f.getName() == "." || f.getName() == "..") { continue; } File file = new File("src/tests/" + f.getName()); file.createNewFile(); OutputStream output = new FileOutputStream(file); if (!ftp.retrieveFile(f.getName(), output)) failed++; output.close(); } } // If we failed to download some file, inform the user if (failed != 0) { ftp.disconnect(); ErrorInformer.failedSyncing(); return; } // Disconnect ftp client or resolve the potential error ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } if (error) { ErrorInformer.failedSyncing(); } Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Download hotov"); alert.setHeaderText(null); alert.setContentText("Vetky testy boli zo servru spene stiahnut."); alert.showAndWait(); alert.close(); }