List of usage examples for org.apache.commons.net.ftp FTPClient getReplyCode
public int getReplyCode()
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[]) {/*from ww w . j a v a 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.kcs.core.utilities.FtpUtil.java
public static boolean checkFileExists(String hostname, int port, String username, String password, String fileName) throws IOException, Exception { FTPClient ftp = null; boolean result = true; try {/*from ww w . j av a 2 s.c o m*/ ftp = FtpUtil.openFtpConnect(hostname, port, username, password); if (null != ftp && ftp.isConnected()) { InputStream inputStream = ftp.retrieveFileStream(fileName); int returnCode = ftp.getReplyCode(); if (inputStream == null || returnCode == 550) { System.out.println("File [ " + fileName + " ] not found in server."); return false; } } } catch (Exception e) { e.printStackTrace(); throw e; } finally { FtpUtil.closeFtpServer(ftp); } return result; }
From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java
/** * Description: FTP?/* w ww. java 2 s . co m*/ * * @Version1.0 * @param url FTP?hostname * @param port FTP?? * @param username FTP? * @param password FTP? * @param remotePath FTP? * @param fileName ??? * @param localPath ?? * @return */ public static boolean downloadFile(String url, int port, String username, String password, String remotePath, String fileName, String localPath) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; // FTP? if (port > -1) { ftp.connect(url, port); } else { ftp.connect(url); } ftp.login(username, password);// ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(remotePath);//FTP? 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(); } } ftp.logout(); success = true; } catch (IOException e) { } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { } } } return success; }
From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java
/** * Description: ?FTP?/*w w w. j av a2s. c o m*/ * * @param url FTP?hostname * @param port FTP???-1 * @param username FTP? * @param password FTP? * @param path FTP?? * @param filename FTP??? * @param input ? * @return ?true?false */ public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; // FTP? if (port > -1) { ftp.connect(url, port); } else { ftp.connect(url); } // FTP ftp.login(username, password); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { success = false; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { } } } return success; }
From source file:joshuatee.wx.UtilityFTP.java
public static String[] GetNidsArr(Context c, String url, String path, String frame_cnt_str) { int frame_cnt = Integer.parseInt(frame_cnt_str); String[] nids_arr = new String[frame_cnt]; try {//from w w w .jav a 2s . c om FTPClient ftp = new FTPClient(); //String user = "ftp"; //String pass = "anonymous"; ftp.connect(url); if (!ftp.login("ftp", "anonymous")) { ftp.logout(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } ftp.enterLocalPassiveMode(); ftp.changeWorkingDirectory(path); //reply = ftp.getReplyCode(); FTPFile[] ftpFiles = ftp.listFiles(); //get newest .xml file name from ftp server java.util.Date lastMod = ftpFiles[0].getTimestamp().getTime(); FTPFile choice = ftpFiles[0]; for (FTPFile file : ftpFiles) { if (file.getTimestamp().getTime().after(lastMod) && !file.getName().equals("sn.last")) { choice = file; lastMod = file.getTimestamp().getTime(); } } int seq = Integer.parseInt(choice.getName().replace("sn.", "")); // was ALl int j = 0; int k = seq - frame_cnt + 1; for (j = 0; j < frame_cnt; j++) { // files range from 0000 to 0250, if num is negative add 251 int tmp_k = k; if (tmp_k < 0) tmp_k = tmp_k + 251; nids_arr[j] = "sn." + String.format("%4s", Integer.toString(tmp_k)).replace(' ', '0'); k++; } FileOutputStream fos; for (j = 0; j < frame_cnt; j++) { fos = c.openFileOutput(nids_arr[j], Context.MODE_PRIVATE); ftp.retrieveFile(nids_arr[j], fos); fos.close(); } ftp.logout(); ftp.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } return nids_arr; }
From source file:com.jason.thrift.TransmitHandler.java
/** * Description: ?FTP?/* www . ja va2 s . co m*/ * * @Version1.0 Jul 27, 2008 4:31:09 PM by ?cuihongbao@d-heaven.com * @param url * FTP?hostname * @param port * FTP?? * @param username * FTP? * @param password * FTP? * @param path * FTP?? * @param filename * FTP??? * @param input * ? * @return ?true?false */ public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url, port);// FTP? // ??ftp.connect(url)?FTP? ftp.login(username, password);// reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
From source file:joshuatee.wx.UtilityFTP.java
public static void GetNids(Context c, String url, String path) { try {/*from www . jav a2s. co m*/ FTPClient ftp = new FTPClient(); //String url = "tgftp.nws.noaa.gov"; //String user = "ftp"; //String pass = "anonymous"; ftp.connect(url); if (!ftp.login("ftp", "anonymous")) { ftp.logout(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } ftp.enterLocalPassiveMode(); ftp.changeWorkingDirectory(path); //reply = ftp.getReplyCode(); //String fn = "sn.last"; FileOutputStream fos = c.openFileOutput("nids", Context.MODE_PRIVATE); ftp.retrieveFile("sn.last", fos); //reply = ftp.getReplyCode(); fos.close(); ftp.logout(); ftp.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:main.TestManager.java
/** * Deletes all local tests, downloads tests from the server * and saves all downloaded test in the local directory. */// www . jav a2 s . co m 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 . java 2s . c om*/ */ 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:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java
public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) { Log.v(TAG, "upload " + uploadConfig); // Make sure we have a file to upload if (!uploadConfig.file.exists()) return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE); FTPClient ftp = new FTPClient(); // For debugging, we'll log all the ftp commands if (BuildConfig.DEBUG) { PrintCommandListener printCommandListener = new PrintCommandListener(System.out); ftp.addProtocolCommandListener(printCommandListener); }//w w w. ja v a2 s .co m InputStream is = null; try { // Set buffer size of FTP client ftp.setBufferSize(1048576); // Open a connection to the FTP server ftp.connect(uploadConfig.server, uploadConfig.port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } // Login to the FTP server if (!ftp.login(uploadConfig.user, uploadConfig.password)) { ftp.disconnect(); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE); } // Try to change directories if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) { Log.v(TAG, "Upload: could not change path to " + uploadConfig.path); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE); } // set the file type to be read as a binary file ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); // Upload the file is = new FileInputStream(uploadConfig.file); long before = System.currentTimeMillis(); long txBytesBefore = TrafficStats.getTotalTxBytes(); if (!ftp.storeFile(uploadConfig.file.getName(), is)) { ftp.disconnect(); Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: " + ftp.getReplyCode() + ", error string: " + ftp.getReplyString()); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } // Calculate stats long after = System.currentTimeMillis(); long txBytesAfter = TrafficStats.getTotalTxBytes(); ftp.logout(); ftp.disconnect(); Log.v(TAG, "Upload complete"); return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before, SpeedTestStatus.SUCCESS); } catch (SocketException e) { Log.e(TAG, "upload " + e.getMessage(), e); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } catch (IOException e) { Log.e(TAG, "upload " + e.getMessage(), e); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } finally { IoUtil.closeSilently(is); } }