List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:beans.BL.java
/** * Upload FTP Server//from w w w . j av a 2 s . com * * @param filename * @throws IOException */ public void upload(String filename) throws IOException { FTPClient client = new FTPClient(); FileInputStream fis = null; client.connect("ftp.sunlime.at", 990); client.login("admin", "secret"); fis = new FileInputStream(filename); client.storeFile(filename, fis); client.logout(); fis.close(); }
From source file:erigo.filepump.FilePumpWorker.java
public void run() { String output_dir_name = pumpSettings.getOutputFolder(); double files_per_sec = pumpSettings.getFilesPerSec(); int total_num_files = pumpSettings.getTotNumFiles(); FilePumpSettings.FileMode mode = pumpSettings.getMode(); String ftpHost = pumpSettings.getFTPHost(); String ftpUsername = pumpSettings.getFTPUser(); String ftpPassword = pumpSettings.getFTPPassword(); double desired_period = 1 / files_per_sec; double sleep_time_millis = desired_period * 1000; long time_used_in_last_filename = 0; Random random_generator = new Random(); int random_range = 999999; if (mode == FilePumpSettings.FileMode.LOCAL_FILESYSTEM) { if (bJustWriteEndFile) { System.err.println("\nWrite \"end.txt\" file to " + output_dir_name); } else {//from w w w . j ava 2s . co m System.err.println("\nWrite files to " + output_dir_name); } } else if (mode == FilePumpSettings.FileMode.FTP) { ftpClient = new FTPClient(); try { login(ftpHost, ftpUsername, ftpPassword); } catch (Exception e) { System.err.println("Caught exception connecting to FTP server:\n" + e); return; } // Make sure we are only using "/" in output_dir_name output_dir_name = output_dir_name.replace('\\', '/'); if (bJustWriteEndFile) { System.err.println("\nWrite \"end.txt\" file out using FTP: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } else { System.err.println("\nFTP files: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } } else if (mode == FilePumpSettings.FileMode.SFTP) { // Make sure output_dir_name starts with an "/" if (output_dir_name.charAt(0) != '/') { output_dir_name = "/" + output_dir_name; } manager = new StandardFileSystemManager(); try { manager.init(); // Just use the default logger // manager.setTemporaryFileStore(new DefaultFileReplicator(new File("C:\\TEMP"))); // Code to set SFTP configuration is largely copied from a submission to the following Stack Overflow post: // https://stackoverflow.com/questions/44763915/how-to-skip-password-prompt-during-sftp-using-commons-vfs // Sample author: Som, https://stackoverflow.com/users/6416340/som // License: Stack Overflow content is covered by the Creative Commons license, https://creativecommons.org/licenses/by-sa/3.0/legalcode // Setup our SFTP configuration fileSystemOptions = new FileSystemOptions(); SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fileSystemOptions, "no"); // VFS file system root: // setting this parameter false = cause VFS to choose File System's Root as VFS's root // setting this parameter true = cause VFS to choose user's home directory as VFS's root SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileSystemOptions, true); SftpFileSystemConfigBuilder.getInstance().setTimeout(fileSystemOptions, 10000); // The following line was used by the Stack Overflow post author to be able to skip a credentials prompt // SftpFileSystemConfigBuilder.getInstance().setPreferredAuthentications(fileSystemOptions, "publickey,keyboard-interactive,password"); } catch (Exception e) { System.err.println("Caught exception setting up Apache Commons VFS manager for SFTP:\n" + e); e.printStackTrace(); return; } // Make sure we are only using "/" in output_dir_name output_dir_name = output_dir_name.replace('\\', '/'); // Create the base connection String // For example, for username "fooUser" and password "fooPW" trying to connect to 192.168.2.56 and put files in folder FooFolder: // sftp://fooUser:fooPW@192.168.2.56/FooFolder // Note that up above we made sure that output_dir_name starts with "/" baseConnectionStr = "sftp://" + ftpUsername + ":" + ftpPassword + "@" + ftpHost + output_dir_name; if (bJustWriteEndFile) { System.err.println("\nWrite \"end.txt\" file out using SFTP: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } else { System.err.println("\nSFTP files: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } } // // If out only task is to send an end.txt file, go ahead and do it and then return // if (bJustWriteEndFile) { String filename = "end.txt"; if (mode == FilePumpSettings.FileMode.FTP) { writeToFTP(output_dir_name, filename, 1); } else if (mode == FilePumpSettings.FileMode.SFTP) { writeToSFTP(filename, 1); } else { File full_filename = new File(output_dir_name, filename); FileWriter fw; try { fw = new FileWriter(full_filename, false); } catch (IOException e) { System.err.println("Caught IOException trying to create the FileWriter:\n" + e + "\n"); e.printStackTrace(); return; } PrintWriter pw = new PrintWriter(fw); pw.format("1\n"); pw.close(); } if (mode == FilePumpSettings.FileMode.FTP) { logout(); } else if (mode == FilePumpSettings.FileMode.SFTP) { manager.close(); } System.err.println("Wrote out \"end.txt\""); return; } // // Setup a periodic timer to update the file count on the GUI // TimerTask timerTask = new FileCountTimerTask(pumpGUI, this); // run timer task as daemon thread Timer timer = new Timer(true); timer.scheduleAtFixedRate(timerTask, 0, 5 * 1000); while (pumpGUI.bPumpRunning) { long start_time = System.currentTimeMillis(); // Create the next file // Always have time move forward // NOTE: The computer's clock being adjusted backward could activate this code if (start_time <= time_used_in_last_filename) { while (true) { try { Thread.sleep(1); } catch (InterruptedException ie) { // nothing to do } start_time = System.currentTimeMillis(); if (start_time > time_used_in_last_filename) { break; } } } ++file_index; String filename = Long.toString(start_time) + "_" + Integer.toString(file_index) + ".txt"; int random_num = (int) ((double) random_range * random_generator.nextDouble()); if (mode == FilePumpSettings.FileMode.FTP) { writeToFTP(output_dir_name, filename, random_num); } else if (mode == FilePumpSettings.FileMode.SFTP) { writeToSFTP(filename, random_num); } else { File full_filename = new File(output_dir_name, filename); FileWriter fw; try { fw = new FileWriter(full_filename, false); } catch (IOException e) { System.err.println("Caught IOException trying to create the FileWriter:\n" + e + "\n"); e.printStackTrace(); break; } PrintWriter pw = new PrintWriter(fw); // Write out a random number to the file pw.format("%06d\n", random_num); pw.close(); } if ((!pumpGUI.bPumpRunning) || (file_index == total_num_files)) { break; } // Sleep try { long actual_sleep_amount = (long) Math.round(sleep_time_millis); if (actual_sleep_amount > 0) { Thread.sleep(actual_sleep_amount); } } catch (InterruptedException ie) { // nothing to do } // Check how we are doing on timing and adjust the sleep time if needed long stop_time = System.currentTimeMillis(); double time_err_secs = desired_period - (double) (stop_time - start_time) / 1000.0; // Adjust sleep_time_millis based on this timing error sleep_time_millis = sleep_time_millis + 0.25 * time_err_secs * 1000.0; // Smallest sleep time is 0 if (sleep_time_millis < 0) { sleep_time_millis = 0.0; } time_used_in_last_filename = start_time; } if (mode == FilePumpSettings.FileMode.FTP) { logout(); } else if (mode == FilePumpSettings.FileMode.SFTP) { manager.close(); } timer.cancel(); // Make sure the final file count is displayed in the GUI pumpGUI.updateNumFiles_nonEDT(file_index); // If we are exiting because the requested number of files have been // reached (ie, exiting of our own volition as opposed to someone else // canceling the run), then reset the user interface if (file_index == total_num_files) { pumpGUI.resetGUI_nonEDT(); } if (!pumpGUI.bShowGUI) { System.err.print("\n"); } System.err.println("Exiting FilePumpWorker; wrote out " + file_index + " files."); }
From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java
public void fetch(final FtpSubscription ftpSubscription) { if (_log.isDebugEnabled()) { _log.debug("fetching " + ftpSubscription); }/*from w ww . j a v a 2 s .c om*/ final FTPClient ftp = new FTPClient(); ftp.setControlKeepAliveTimeout(30); ftp.setControlKeepAliveReplyTimeout(30); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; ftp.connect(ftpSubscription.getFtpHost()); _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (final IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } boolean error = false; __main: try { if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) { ftp.logout(); error = true; break __main; } _log.info("Remote system is " + ftp.getSystemType()); ftp.setFileType(FTP.BINARY_FILE_TYPE); //ftp.enterLocalActiveMode(); ftp.enterLocalPassiveMode(); //final FTPClientConfig config = new FTPClientConfig(); ////config.setLenientFutureDates(true); //ftp.configure(config); if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) { ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder()); } final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile()); if (is == null) { _log.error("FIle not found: " + ftp.getSystemType()); } else { unzip(ftpSubscription, is); is.close(); } ftp.completePendingCommand(); } catch (final FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (final IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException e) { _log.error(e); } } } }
From source file:com.maxl.java.amikodesk.Emailer.java
private void uploadToFTPServer(Author author, String name, String path) { FTPClient ftp_client = new FTPClient(); try {//from ww w .j a v a2 s . c o m ftp_client.connect(author.getS(), 21); ftp_client.login(author.getL(), author.getP()); ftp_client.enterLocalPassiveMode(); ftp_client.changeWorkingDirectory(author.getO()); ftp_client.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } File local_file = new File(path); String remote_file = name + ".csv"; InputStream is = new FileInputStream(local_file); System.out.print("Uploading file " + name + " to server " + author.getS() + "... "); boolean done = ftp_client.storeFile(remote_file, is); if (done) System.out.println("file uploaded successfully."); else System.out.println("error."); is.close(); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftp_client.isConnected()) { ftp_client.logout(); ftp_client.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:edu.mda.bioinfo.ids.DownloadFiles.java
private void downloadFromFtpToFile(String theServer, String theServerFile, String theLocalFile) throws IOException, Exception { FTPClient ftp = new FTPClient(); try {//from w w w . ja v a 2s . c om int reply = 0; boolean replyB = false; ftp.connect(theServer); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } else { ftp.login("anonymous", "anonymous"); replyB = ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.print(ftp.getReplyString()); System.out.println("replyB= " + replyB); if (false == replyB) { throw new Exception("Unable to login to " + theServer); } OutputStream output = new FileOutputStream(theLocalFile); replyB = ftp.retrieveFile(theServerFile, output); System.out.print(ftp.getReplyString()); System.out.println("replyB= " + replyB); if (false == replyB) { throw new Exception("Unable to retrieve " + theServerFile); } } ftp.logout(); } catch (IOException rethrownExp) { System.err.println("exception " + rethrownExp.getMessage()); throw rethrownExp; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignore) { // do nothing } } } }
From source file:facturacion.ftp.FtpServer.java
public static InputStream getTokenInputStream(String remote_file_ruta) { FTPClient ftpClient = new FTPClient(); try {/*from w w w. j a v a 2 s . co m*/ //ftpClient.connect("127.0.0.1", 21 ); //ftpClient.login("erpftp", "Tribut@2014"); ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken), Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken))); ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken), Config.getInstance().getProperty(Config.PassFtpToken)); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftpClient.getReplyCode(); System.out.println("Respuesta recibida de conexin FTP:" + reply); if (!FTPReply.isPositiveCompletion(reply)) { System.out.println("Imposible conectarse al servidor"); //return -1; } else { System.out.println("se conecto al servidor"); } //ftpClient.enterLocalPassiveMode(); // crear directorio //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta)); //System.out.println("File #1 has been downloaded successfully. 1"); //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12"); //InputStream is = fis; System.out.println("File rutaqq=" + "1-/" + remote_file_ruta); InputStream is = ftpClient.retrieveFileStream(remote_file_ruta); if (is == null) System.out.println("File #1 es null token"); else System.out.println("File #1 no es null token"); //return ftpClient.retrieveFileStream(remote_file_ruta); return is; } catch (IOException ex) { System.out.println("File #1 has been downloaded successfully. 222"); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { System.out.println("File #1 has been downloaded successfully. 3"); return null; //ex.printStackTrace(); } } return null; }
From source file:ftp.search.Index.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try {/*from w ww .j a v a 2 s . c o m*/ // TODO add your handling code here: Class.forName("com.mysql.jdbc.Driver"); String uid = "root"; String pwd = "clever"; String dbURL = "jdbc:mysql://localhost:3306/ftp"; Connection conn = DriverManager.getConnection(dbURL, uid, pwd); Statement statement = conn.createStatement(); FTPClient ftpClient = new FTPClient(); String ftp = jTextField1.getText(); int port = 21; try { ftpClient.connect(ftp, port); int a = ftpClient.getConnectTimeout(); ftpClient.login("anonymous", ""); // lists files and directories in the current working directory insertFiles(ftp, "/", statement, ftpClient); JOptionPane.showMessageDialog(this, "Files Indexed Successfully"); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex); } } catch (ClassNotFoundException ex) { Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:autonomouspathplanner.ftp.FTP.java
/** * Attempts to connect to server to check if it is possible * @return true if the client can connect to the server and false otherwise. */// w w w . jav a2 s . c o m public boolean canConnect() { try { FTPClient c = new FTPClient(); c.connect(IP, port); c.login(user, pass); if (c.isConnected()) { c.logout(); c.disconnect(); return true; } else return false; } catch (UnknownHostException x) { return false; } catch (IOException ex) { ex.printStackTrace(); return false; } }
From source file:com.ephesoft.dcma.ftp.service.FTPServiceImpl.java
/** * API to download a particular directory from FTP Server. * /*from ww w. j av a 2s . c o m*/ * @param sourceDirName {@link String} - Name of the source directory to be copied. * @param destDirectoryPath {@link String} - Full path where directory need to be copied. * @param retryCounter - Start with zero. * @param isDeletedFTPServerSourceContent - set true for deleted the ftp server content. * @throws FTPDataDownloadException if any error occurs while downloading the file. */ @Override public void downloadDirectory(final String sourceDirName, final String destDirectoryPath, final int numberOfRetryCounter, boolean isDeletedFTPServerSourceContent) throws FTPDataDownloadException { boolean isValid = true; if (sourceDirName == null) { isValid = false; LOGGER.error(var_source_dir); throw new FTPDataDownloadException(var_source_dir); } if (destDirectoryPath == null) { isValid = false; LOGGER.error(var_source_des); throw new FTPDataDownloadException(var_source_des); } if (isValid) { FTPClient client = new FTPClient(); String outputFileName = null; File file = new File(destDirectoryPath); if (!file.exists()) { file.mkdir(); } try { createConnection(client); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { LOGGER.info("Starting File Download..."); } else { LOGGER.error("Invalid Connection to FTP server. Disconnecting from FTP server...."); client.disconnect(); isValid = false; throw new FTPDataDownloadException( "Invalid Connection to FTP server. Disconnecting from FTP server...."); } if (isValid) { client.setFileType(FTP.BINARY_FILE_TYPE); String ftpDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator, sourceDirName); LOGGER.info("Downloading files from FTP server"); try { FTPUtil.retrieveFiles(client, ftpDirectory, destDirectoryPath); } catch (IOException e) { int retryCounter = numberOfRetryCounter; LOGGER.info("Retrying download Attempt#-" + (retryCounter + 1)); if (retryCounter < numberOfRetries) { retryCounter = retryCounter + 1; downloadDirectory(sourceDirName, destDirectoryPath, retryCounter, isDeletedFTPServerSourceContent); } else { LOGGER.error("Error in getting file from FTP server :" + outputFileName); } } if (isDeletedFTPServerSourceContent) { FTPUtil.deleteExistingFTPData(client, ftpDirectory, true); } } } catch (FileNotFoundException e) { LOGGER.error("Error in generating output Stream for file :" + outputFileName); } catch (SocketException e) { LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e); } catch (IOException e) { LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e); } finally { try { client.disconnect(); } catch (IOException e) { LOGGER.error("Error in disconnecting from FTP server." + e); } } } }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * /* www . ja v a 2s. c om*/ * @throws UnknownHostException * If the hostname cannot be resolved. * * @throws SocketException * If the socket timeout could not be set. * * @throws FTPConnectionClosedException * If the connection is closed by the server. * * @throws LoginFailedException * If the login fails. * * @throws DirectoryChangeFailedException * If changing to the directory provided by the internet * archive fails. * * @throws CopyStreamException * If an I/O error occurs while in the middle of * transferring a file. * * @throws IOException * If an I/O error occurs while sending a command or * receiving a reply from the server * * @throws IllegalStateException * If the contribution object is not ready to upload * (no username, password, server, etc. set) * or if java's xml parser is configured badly */ public void upload() throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException, DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException { final int NUM_XML_FILES = 2; final String META_XML_SUFFIX = "_meta.xml"; final String FILES_XML_SUFFIX = "_files.xml"; final String username = getUsername(); final String password = getPassword(); if (getFtpServer() == null) { throw new IllegalStateException("ftp server not set"); } if (getFtpPath() == null) { throw new IllegalStateException("ftp path not set"); } if (username == null) { throw new IllegalStateException("username not set"); } if (password == null) { throw new IllegalStateException("password not set"); } // calculate total number of files and bytes final String metaXmlString = serializeDocument(getMetaDocument()); final String filesXmlString = serializeDocument(getFilesDocument()); final byte[] metaXmlBytes = metaXmlString.getBytes(); final byte[] filesXmlBytes = filesXmlString.getBytes(); final int metaXmlLength = metaXmlBytes.length; final int filesXmlLength = filesXmlBytes.length; final Collection files = getFiles(); final int totalFiles = NUM_XML_FILES + files.size(); final String[] fileNames = new String[totalFiles]; final long[] fileSizes = new long[totalFiles]; final String metaXmlName = getIdentifier() + META_XML_SUFFIX; fileNames[0] = metaXmlName; fileSizes[0] = metaXmlLength; final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX; fileNames[1] = filesXmlName; fileSizes[1] = filesXmlLength; int j = 2; for (Iterator i = files.iterator(); i.hasNext();) { final File f = (File) i.next(); fileNames[j] = f.getRemoteFileName(); fileSizes[j] = f.getFileSize(); j++; } // init the progress mapping for (int i = 0; i < fileSizes.length; i++) { _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i])); _totalUploadSize += fileSizes[i]; } FTPClient ftp = new FTPClient(); try { // first connect if (isCancelled()) { return; } ftp.enterLocalPassiveMode(); if (isCancelled()) { return; } ftp.connect(getFtpServer()); final int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new RefusedConnectionException(getFtpServer() + "refused FTP connection"); } // now login if (isCancelled()) { return; } if (!ftp.login(username, password)) { throw new LoginFailedException(); } try { // try to change the directory if (!ftp.changeWorkingDirectory(getFtpPath())) { // if changing fails, make the directory if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } // now change directory, if it fails again bail if (isCancelled()) { return; } if (!ftp.changeWorkingDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } } if (isCancelled()) { return; } connected(); // upload xml files uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp); uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp); // now switch to binary mode if (isCancelled()) { return; } ftp.setFileType(FTP.BINARY_FILE_TYPE); // upload contributed files for (final Iterator i = files.iterator(); i.hasNext();) { final File f = (File) i.next(); uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp); } } catch (InterruptedIOException ioe) { // we've been requested to cancel return; } finally { ftp.logout(); // we don't care if logging out fails } } finally { try { ftp.disconnect(); } catch (IOException e) { } // don't care if disconnecting fails } // now tell the Internet Archive that we're done if (isCancelled()) { return; } checkinStarted(); if (isCancelled()) { return; } checkin(); if (isCancelled()) { return; } checkinCompleted(); }