List of usage examples for org.apache.commons.net.ftp FTPClient connect
public void connect(InetAddress host, int port) throws SocketException, IOException
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. jav a 2 s . c om*/ 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); } }
From source file:facturacion.ftp.FtpServer.java
public static InputStream getTokenInputStream2(String remote_file_ruta) { FTPClient ftpClient = new FTPClient(); File downloadFile1 = null;/*from ww w .ja v a 2 s. c om*/ try { downloadFile1 = File.createTempFile("tmptokenEmpresa", ".p12"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { 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.connect(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_SERVER), Integer.parseInt( ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_PORT)) ); //ftpClient.login(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_USER), ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FT_PSWD)); //ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); boolean success; String remoteFile1 = "/0702144833/kepti_lenin_pereira_tinoco.p12"; downloadFile1 = new File("C:/Users/aaguerra/Desktop/firmado2.p12"); OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1)); success = ftpClient.retrieveFile(remoteFile1, outputStream1); outputStream1.close(); //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\arpr\\documentacion\\kepti_lenin_pereira_tinoco.p12"); FileInputStream fis = new FileInputStream( "C:\\Users\\aaguerra\\Desktop\\arpr\\archivos\\0702144833\\kepti_lenin_pereira_tinoco.p12"); InputStream is = fis; if (success) { System.out.println("File #1 has been downloaded successfully. 222adadfsdfadf"); } else { System.out.println("File #1 has been downloaded successfully. 3333"); } ; 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:madkitgroupextension.export.Export.java
private static void sendToWebSite() throws IOException { System.out.println("Enter your password :"); byte b[] = new byte[100]; int l = System.in.read(b); String pwd = new String(b, 0, l); boolean reconnect = true; long time = System.currentTimeMillis(); File current_file_transfert = null; File current_directory_transfert = null; while (reconnect) { FTPClient ftpClient = new FTPClient(); ftpClient.connect(FTPURL, 21); try {//from w w w . j a va2 s .c o m if (ftpClient.isConnected()) { System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !"); if (ftpClient.login(FTPLOGIN, pwd)) { ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); System.out.println("Logged as " + FTPLOGIN + " !"); System.out.print("Updating..."); FTPFile files[] = ftpClient.listFiles(""); FTPFile downloadroot = null; FTPFile docroot = null; for (FTPFile f : files) { if (f.getName().equals("downloads")) { downloadroot = f; if (docroot != null) break; } if (f.getName().equals("doc")) { docroot = f; if (downloadroot != null) break; } } if (downloadroot == null) { //ftpClient.changeWorkingDirectory("/"); if (!ftpClient.makeDirectory("downloads")) { System.err.println("Impossible to create directory: downloads"); } } if (docroot == null) { //ftpClient.changeWorkingDirectory("/"); if (!ftpClient.makeDirectory("doc")) { System.err.println("Impossible to create directory: doc"); } } updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert, current_directory_transfert); updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert, current_directory_transfert); reconnect = false; System.out.println("[OK]"); if (ftpClient.logout()) { System.out.println("Logged out from " + FTPLOGIN + " succesfull !"); } else System.err.println("Logged out from " + FTPLOGIN + " FAILED !"); } else System.err.println("Impossible to log as " + FTPLOGIN + " !"); ftpClient.disconnect(); System.out.println("Disconnected from " + FTPURL + " !"); } else { System.err.println("Impossible to get a connection to the server " + FTPURL + " !"); } reconnect = false; } catch (TransfertException e) { if (System.currentTimeMillis() - time > 30000) { System.err.println("A problem occured during the transfert..."); System.out.println("Reconnection in progress..."); try { ftpClient.disconnect(); } catch (Exception e2) { } current_file_transfert = e.current_file_transfert; current_directory_transfert = e.current_directory_transfert; time = System.currentTimeMillis(); } else { System.err.println("A problem occured during the transfert. Transfert aborded."); throw e.original_exception; } } } }
From source file:com.zxy.commons.net.ftp.FtpUtils.java
/** * FTP handle/*from ww w . j a va 2 s. c om*/ * * @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:com.mendhak.gpslogger.senders.ftp.Ftp.java
public static boolean Upload(String server, String username, String password, int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream, String fileName) { FTPClient client = null; try {// w ww . ja va 2s . c o m if (useFtps) { client = new FTPSClient(protocol, implicit); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(null, null); KeyManager km = kmf.getKeyManagers()[0]; ((FTPSClient) client).setKeyManager(km); } else { client = new FTPClient(); } } catch (Exception e) { e.printStackTrace(); } try { Utilities.LogDebug("Connecting to FTP"); client.connect(server, port); Utilities.LogDebug("Logging in to FTP server"); if (client.login(username, password)) { client.enterLocalPassiveMode(); Utilities.LogDebug("Uploading file to FTP server"); FTPFile[] existingDirectory = client.listFiles("GPSLogger"); if (existingDirectory.length <= 0) { client.makeDirectory("GPSLogger"); } client.changeWorkingDirectory("GPSLogger"); boolean result = client.storeFile(fileName, inputStream); inputStream.close(); if (result) { Utilities.LogDebug("Successfully FTPd file"); } else { Utilities.LogDebug("Failed to FTP file"); } } else { Utilities.LogDebug("Could not log in to FTP server"); return false; } } catch (Exception e) { Utilities.LogError("Could not connect or upload to FTP server.", e); } finally { try { Utilities.LogDebug("Logging out of FTP server"); client.logout(); Utilities.LogDebug("Disconnecting from FTP server"); client.disconnect(); } catch (Exception e) { Utilities.LogError("Could not logout or disconnect", e); } } return true; }
From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java
public synchronized static boolean Upload(String server, String username, String password, String directory, int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream, String fileName) {// w w w.j a v a 2 s . com FTPClient client = null; try { if (useFtps) { client = new FTPSClient(protocol, implicit); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(null, null); KeyManager km = kmf.getKeyManagers()[0]; ((FTPSClient) client).setKeyManager(km); } else { client = new FTPClient(); } } catch (Exception e) { tracer.error("Could not create FTP Client", e); return false; } try { tracer.debug("Connecting to FTP"); client.connect(server, port); showServerReply(client); tracer.debug("Logging in to FTP server"); if (client.login(username, password)) { client.enterLocalPassiveMode(); showServerReply(client); tracer.debug("Uploading file to FTP server " + server); tracer.debug("Checking for FTP directory " + directory); FTPFile[] existingDirectory = client.listFiles(directory); showServerReply(client); if (existingDirectory.length <= 0) { tracer.debug("Attempting to create FTP directory " + directory); //client.makeDirectory(directory); ftpCreateDirectoryTree(client, directory); showServerReply(client); } client.changeWorkingDirectory(directory); boolean result = client.storeFile(fileName, inputStream); inputStream.close(); showServerReply(client); if (result) { tracer.debug("Successfully FTPd file " + fileName); } else { tracer.debug("Failed to FTP file " + fileName); return false; } } else { tracer.debug("Could not log in to FTP server"); return false; } } catch (Exception e) { tracer.error("Could not connect or upload to FTP server.", e); return false; } finally { try { tracer.debug("Logging out of FTP server"); client.logout(); showServerReply(client); tracer.debug("Disconnecting from FTP server"); client.disconnect(); showServerReply(client); } catch (Exception e) { tracer.error("Could not logout or disconnect", e); return false; } } return true; }
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"); }//from w w w . ja v a2 s.c o 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.microsoft.azuretools.utils.WebAppUtils.java
public static FTPClient getFtpConnection(PublishingProfile pp) throws IOException { FTPClient ftp = new FTPClient(); System.out.println("\t\t" + pp.ftpUrl()); System.out.println("\t\t" + pp.ftpUsername()); System.out.println("\t\t" + pp.ftpPassword()); URI uri = URI.create("ftp://" + pp.ftpUrl()); ftp.connect(uri.getHost(), 21); final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect();// ww w . j a va 2s. c om throw new ConnectException("Unable to connect to FTP server"); } if (!ftp.login(pp.ftpUsername(), pp.ftpPassword())) { throw new ConnectException("Unable to login to FTP server"); } ftp.setControlKeepAliveTimeout(Constants.connection_read_timeout_ms); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode();//Switch to passive mode return ftp; }
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"); }//from w w w . j a v a 2 s.c o m }
From source file:conf.FTPConf.java
public String subirArchivo(File archivo) { FTPClient ftpClient = new FTPClient(); try {//from w w w. j av a 2 s.com 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; }