List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:com.zxy.commons.net.ftp.FtpUtils.java
/** * FTP handle// w w w .j av a2 s . c o m * * @param <T> return object type * @param ftpConfig ftp config * @param callback ftp callback * @return value */ public static <T> T ftpHandle(FtpConfig ftpConfig, FtpCallback<T> callback) { FTPClient client = null; if (ftpConfig.isFtps() && ftpConfig.getSslContext() != null) { client = new FTPSClient(ftpConfig.getSslContext()); } else if (ftpConfig.isFtps()) { client = new FTPSClient(); } else { client = new FTPClient(); } client.configure(ftpConfig.getFtpClientConfig()); try { // client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); client.connect(ftpConfig.getHost(), ftpConfig.getPort()); client.setConnectTimeout(ftpConfig.getConnectTimeoutMs()); client.setControlKeepAliveTimeout(ftpConfig.getKeepAliveTimeoutSeconds()); if (!Strings.isNullOrEmpty(ftpConfig.getUsername())) { client.login(ftpConfig.getUsername(), ftpConfig.getPassword()); } LOGGER.trace("Connected to {}, reply: {}", ftpConfig.getHost(), client.getReplyString()); // After connection attempt, you should check the reply code to verify success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new NetException("FTP server refused connection."); } return callback.process(client); } catch (Exception e) { throw new NetException(e); } finally { if (client.isConnected()) { try { client.logout(); } catch (IOException ioe) { LOGGER.warn(ioe.getMessage()); } try { client.disconnect(); } catch (IOException ioe) { LOGGER.warn(ioe.getMessage()); } } } }
From source file:main.TestManager.java
/** * Deletes all local tests, downloads tests from the server * and saves all downloaded test in the local directory. *//*from ww w . j ava 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(); }
From source file:main.TestManager.java
/** * Deletes all files on the server and uploads all the * tests from the local directory./*from www . ja va 2 s .c o m*/ */ public static void syncServerWithTest() { 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 tests on the server to be replaced with // actualized version from local directory for (FTPFile f : files) { if (f.getName() == "." || f.getName() == "..") { continue; } if (f.isFile()) { ftp.deleteFile(f.getName()); } } // Copy the files from local folder to server File localFolder = new File("src/tests/"); File[] localFiles = localFolder.listFiles(); int failed = 0; for (File f : localFiles) { if (f.getName() == "." || f.getName() == "..") { continue; } if (f.isFile()) { Debugger.println(f.getName()); File file = new File("src/tests/" + f.getName()); InputStream input = new FileInputStream(file); if (!ftp.storeFile(f.getName(), input)) failed++; input.close(); } } // If we failed to upload 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(); return; } } Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Upload hotov"); alert.setHeaderText(null); alert.setContentText("spene sa podarilo skoprova vetky testy na server!"); alert.showAndWait(); alert.close(); }
From source file:com.peter.javaautoupdater.JavaAutoUpdater.java
public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword, boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName, String args[]) {//w w w . ja va 2 s .c o m System.out.println("jarName=" + jarName); for (String arg : args) { if (arg.toLowerCase().trim().equals("-noautoupdate")) { return; } } JavaAutoUpdater.basePath = basePath; JavaAutoUpdater.softwareName = softwareName; JavaAutoUpdater.args = args; if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) { if (isDebug) { jarName = "test.jar"; } else { return; } } JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true); d.progressBar.setIndeterminate(true); d.progressBar.setStringPainted(true); d.progressBar.setString("Updating"); // d.addCancelEventListener(this); Thread longRunningThread = new Thread() { public void run() { d.progressBar.setString("checking latest version"); System.out.println("checking latest version"); FTPClient ftp = new FTPClient(); try { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(ftpHost, ftpPort); int reply = ftp.getReplyCode(); System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply)); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP server refused connection", "error", JOptionPane.ERROR_MESSAGE); } d.progressBar.setString("connected to ftp"); System.out.println("connected to ftp"); boolean success = ftp.login(ftpUsername, ftpPassword); if (!success) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error", JOptionPane.ERROR_MESSAGE); } if (isLocalPassiveMode) { ftp.enterLocalPassiveMode(); } if (isRemotePassiveMode) { ftp.enterRemotePassiveMode(); } FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { if (file.getName().startsWith(softwareName)) { return true; } else { return false; } } }); if (ftpFiles.length > 0) { FTPFile targetFile = ftpFiles[ftpFiles.length - 1]; System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize() + "!=" + new File(jarName).length()); if (!targetFile.getName().equals(jarName) || targetFile.getSize() != new File(jarName).length()) { int r = JOptionPane.showConfirmDialog(null, "Confirm to update to " + targetFile.getName(), "Question", JOptionPane.YES_NO_OPTION); if (r == JOptionPane.YES_OPTION) { //ftp.enterRemotePassiveMode(); d.progressBar.setString("downloading " + targetFile.getName()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE); d.progressBar.setIndeterminate(false); d.progressBar.setMaximum(100); CopyStreamAdapter streamListener = new CopyStreamAdapter() { @Override public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize()); d.progressBar.setValue(percent); } }; ftp.setCopyStreamListener(streamListener); try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) { ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos); } catch (IOException e) { e.printStackTrace(); } d.progressBar.setString("restarting " + targetFile.getName()); restartApplication(targetFile.getName()); } } } ftp.logout(); ftp.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } }; d.thread = longRunningThread; d.setVisible(true); }
From source file:com.discursive.jccook.net.FTPExample.java
private void secondExample() throws SocketException, IOException { FTPClient client = new FTPClient(); client.connect("ftp.ibiblio.org"); client.login("anonymous", ""); String remoteDir = "/pub/mirrors/apache/jakarta/ecs/binaries"; FTPFile[] remoteFiles = client.listFiles(remoteDir); System.out.println("Files in " + remoteDir); for (int i = 0; i < remoteFiles.length; i++) { String name = remoteFiles[i].getName(); long length = remoteFiles[i].getSize(); String readableLength = FileUtils.byteCountToDisplaySize(length); System.out.println(name + ":\t\t" + readableLength); }//from w ww.ja v a2 s . c o m client.disconnect(); }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpsFileInstance.java
@Override protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPSClient(); f.connect(fpi.getHost());// w w w. ja v a 2 s .c o m f.login(fpi.getUsername(), fpi.getPassword()); return f; }
From source file:com.baifendian.swordfish.common.job.struct.datasource.FtpDatasource.java
@Override public void isConnectable() throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.connect(this.host, this.port); if (!ftpClient.login(this.user, this.password)) { throw new Exception("wrong user name or password"); }// w w w. j a va2 s. c om }
From source file:conf.FTPConf.java
public String subirArchivo(File archivo) { FTPClient ftpClient = new FTPClient(); try {/*from w ww. j a v a2 s .co m*/ ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // APPROACH #2: uploads second file using an OutputStream String serverFile = dir + archivo.getName(); InputStream inputStream = new FileInputStream(archivo); OutputStream outputStream = ftpClient.storeFileStream(serverFile); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftpClient.completePendingCommand(); if (completed) { String link = "ftp://" + user + "@" + server + "/" + serverFile; return link; } } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } return null; }
From source file:com.jsystem.j2autoit.AutoItAgent.java
private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception { Log.info("\nretrieve " + fileName + NEW_LINE); FTPClient client = new FTPClient(); client.connect(host, port); //connect to the management ftp server int reply = client.getReplyCode(); // check connection if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("FTP fail to connect"); }/*w ww.j a v a 2 s. co m*/ if (!client.login(user, password)) { //check login throw new Exception("FTP fail to login"); } // FileOutputStream fos = null; try { File locationFile = new File(location); File dest = new File(locationFile, fileName); if (dest.exists()) { dest.delete(); } else { locationFile.mkdirs(); } boolean status = client.changeWorkingDirectory("/"); Log.info("chdir-status:" + status + NEW_LINE); client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalActiveMode(); InputStream in = client.retrieveFileStream(fileName); if (in == null) { Log.error("Input stream is null\n"); throw new Exception("Fail to retrieve file " + fileName); } Thread.sleep(3000); saveInputStreamToFile(in, new File(location, fileName)); } finally { client.disconnect(); } }
From source file:com.discursive.jccook.net.FTPExample.java
public void start() throws IOException { FTPClient client = new FTPClient(); OutputStream outStream = null; try {//from ww w. j a va 2 s .c om client.connect("ftp.ibiblio.org"); client.login("anonymous", ""); String remoteFile = "/pub/micro/commodore/schematics/computers/c64/c64bus.gif"; outStream = new FileOutputStream("c64bus.gif"); client.retrieveFile(remoteFile, outStream); } catch (IOException ioe) { System.out.println("Error communicating with FTP server."); } finally { IOUtils.closeQuietly(outStream); try { client.disconnect(); } catch (IOException e) { System.out.println("Problem disconnecting from FTP server"); } } secondExample(); }