List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:facturacion.ftp.FtpServer.java
public static int sendTokenInputStream(String fileNameServer, String hostDirServer, InputStream localFile) { FTPClient ftpClient = new FTPClient(); boolean success = false; BufferedInputStream buffIn = null; try {//from www. j a va 2 s.co m 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.enterLocalPassiveMode(); /*ftpClient.connect("127.0.0.1", 21); ftpClient.login("erpftp", "Tribut@2014");*/ 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; } buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar ftpClient.enterLocalPassiveMode(); //crear directorio System.out.println(hostDirServer); success = ftpClient.makeDirectory(hostDirServer); System.out.println("sucess 1133 = " + success); //showServerReply(ftpClient); success = ftpClient.makeDirectory(hostDirServer + "/token"); /* System.out.println("sucess 1 = "+success); success = ftpClient.makeDirectory("casa111"); System.out.println("sucess 111 = "+success); success = ftpClient.makeDirectory("/usr/erp/token/casa"); System.out.println("sucess 111 = "+success); success = ftpClient.makeDirectory("/casa2"); System.out.println("sucess 1 = "+success); */ success = ftpClient.storeFile(hostDirServer + "/token/" + fileNameServer, buffIn); //success = ftpClient.storeFile("prueba", buffIn); System.out.println("sucess 2 = " + success); //return (success)? 1:0; } catch (IOException ex) { } finally { try { if (ftpClient.isConnected()) { buffIn.close(); //Cerrar envio de arcivos al FTP ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { return -1; //ex.printStackTrace(); } } return (success) ? 1 : 0; }
From source file:facturacion.ftp.FtpServer.java
public static InputStream getTokenInputStream(String remote_file_ruta) { FTPClient ftpClient = new FTPClient(); try {/*from ww w .j ava 2 s. c o 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:facturacion.ftp.FtpServer.java
public static InputStream getTokenInputStream2(String remote_file_ruta) { FTPClient ftpClient = new FTPClient(); File downloadFile1 = null;//from www.ja v a 2 s . c o m 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: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 {/*from w w w .jav a2s.c om*/ 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:edu.tum.cs.ias.knowrob.utils.ResourceRetriever.java
/** * Retrieve a file to a temporary path. This temporary path will be returned. Valid protocol * types: ftp, http, package or local file If a file has already be downloaded (the file is * existing in tmp directory) it will not be redownloaded again. Simply the path to this file * will be returned.//from w w w. ja v a 2 s .c o m * * @param url * URL to retrieve * @param checkAlreadyRetrieved * if false, always download the file and ignore, if it is already existing * @return NULL on error. On success the path to the file is returned. */ public static File retrieve(String url, boolean checkAlreadyRetrieved) { if (url.indexOf("://") <= 0) { // Is local file return new File(url); } int start = url.indexOf('/') + 2; int end = url.indexOf('/', start); String serverName = url.substring(start, end); if (url.startsWith("package://")) { String filePath = url.substring(end + 1); String pkgPath = findPackage(serverName); if (pkgPath == null) return null; return new File(pkgPath, filePath); } else if (url.startsWith("http://")) { OutputStream out = null; URLConnection conn = null; InputStream in = null; String filename = url.substring(url.lastIndexOf('/') + 1); File tmpPath = getTmpName(url, filename); if (checkAlreadyRetrieved && tmpPath.exists()) { return tmpPath; } try { // Get the URL URL urlClass = new URL(url); // Open an output stream to the destination file on our local filesystem out = new BufferedOutputStream(new FileOutputStream(tmpPath)); conn = urlClass.openConnection(); in = conn.getInputStream(); // Get the data byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } // Done! Just clean up and get out } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { // Ignore if stream not possible to close } } return tmpPath; } else if (url.startsWith("ftp://")) { FTPClient client = new FTPClient(); OutputStream outStream = null; String filename = url.substring(url.lastIndexOf('/') + 1); File tmpPath = getTmpName(url, filename); if (checkAlreadyRetrieved && tmpPath.exists()) { System.out.println("Already retrieved: " + url + " to " + tmpPath.getAbsolutePath()); return tmpPath; } try { // Connect to the FTP server as anonymous client.connect(serverName); client.login("anonymous", "knowrob@example.com"); String remoteFile = url.substring(end); // Write the contents of the remote file to a FileOutputStream outStream = new FileOutputStream(tmpPath); client.retrieveFile(remoteFile, outStream); } catch (IOException ioe) { System.out.println("ResourceRetriever: Error communicating with FTP server: " + serverName + "\n" + ioe.getMessage()); } finally { try { outStream.close(); } catch (IOException e1) { // Ignore if stream not possible to close } try { client.disconnect(); } catch (IOException e) { System.out.println("ResourceRetriever: Problem disconnecting from FTP server: " + serverName + "\n" + e.getMessage()); } } return tmpPath; } return null; }
From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java
public static FTPClient connect(RepositoryLocation location, boolean showErrors) { FTPClient client = new FTPClient(); String errorMessage = ""; try {//ww w . ja v a 2 s. c om client.connect(location.getHost()); boolean ok = client.login(location.getUser(), location.getPassword()); if (ok) { boolean ok2 = client.changeWorkingDirectory(location.getRepositoryPath()); if (!ok2) { client = null; errorMessage = "Incorrect repository path"; } } else { client = null; errorMessage = "Incorrect user name and password"; } } catch (Exception e) { client = null; errorMessage = "Unknown host"; } if (!errorMessage.equals("") && showErrors) { MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Connection failed", errorMessage); } return client; }
From source file:de.jwi.ftp.FTPUploader.java
public static String upload(URL url, List files) { String rcs = ""; if (!"ftp".equals(url.getProtocol())) { return "not ftp protocol"; }// w ww . j a va 2s . com String host = url.getHost(); String userInfo = url.getUserInfo(); String path = url.getPath(); String user = null; String pass = null; int p; if ((userInfo != null) && ((p = userInfo.indexOf(':')) > -1)) { user = userInfo.substring(0, p); pass = userInfo.substring(p + 1); } else { user = userInfo; } FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(host); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return "connection refused"; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } return "could not connect to " + host; } try { if (!ftp.login(user, pass)) { ftp.logout(); return "failed to login"; } ftp.setFileType(FTP.BINARY_FILE_TYPE); // Use passive mode as default because most of us are // behind firewalls these days. ftp.enterLocalPassiveMode(); rcs = uploadFiles(ftp, path, files); ftp.logout(); } catch (FTPConnectionClosedException e) { return "connection closed"; } catch (IOException e) { return e.getMessage(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } return rcs; }
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);/*ww w . j a v a 2 s. com*/ try { 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: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); }//from ww w .jav a2s. com 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: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) {/*from w w w . j a v a 2 s.c om*/ 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; }