List of usage examples for org.apache.commons.net.ftp FTPClient disconnect
@Override public void disconnect() throws IOException
From source file:com.claim.support.FtpUtil.java
public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {// www. ja v a 2 s .c o m FtpProperties properties = new ResourcesProperties().loadFTPProperties(); ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); File secondLocalFile = new File(direcPath); String secondRemoteFile = "WorkshopDay2.docx"; inputStream = new FileInputStream(secondLocalFile); System.out.println("Start uploading second file"); OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile); 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) { System.out.println("The second file is uploaded successfully."); } } 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(); } } }
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 ww w . ja va 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; }
From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java
/** * Login into a account/*ww w.ja v a 2 s. c o m*/ * * @return FTPClient object or null * @throws IOException */ public FTPClient login() throws IOException { int reply = 0; FTPClient ftp = new FTPClient(); try { if (port != 0) ftp.connect(getHost(), getPort()); else ftp.connect(getHost()); if (isAnonymous()) ftp.login(ANONYMOUS, GUEST); else if (getSubAccount() != null && !getSubAccount().isEmpty()) ftp.login(getLogin(), getPassword(), getSubAccount()); else ftp.login(getLogin(), getPassword()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString())); if (isPassiveMode()) ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } throw e; } return ftp; }
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downZurRose() { String fl = ""; String fp = ""; String fs = ""; try {//from w w w . ja va2 s . c o m FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/access.ami.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8")); String line; while ((line = br.readLine()) != null) { // Semicolon is used as a separator String[] gln = line.split(";"); if (gln.length > 2) { if (gln[0].equals("P_ywesee")) { fl = gln[0]; fp = gln[1]; fs = gln[2]; } } } br.close(); } catch (Exception e) { e.printStackTrace(); } FTPClient ftp_client = new FTPClient(); try { ftp_client.connect(fs, 21); ftp_client.login(fl, fp); ftp_client.enterLocalPassiveMode(); ftp_client.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("- Connected to server " + fs + "..."); String[] working_dir = { "ywesee out", "../ywesee in" }; for (int i = 0; i < working_dir.length; ++i) { // Set working directory ftp_client.changeWorkingDirectory(working_dir[i]); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } // Get list of filenames FTPFile[] ftpFiles = ftp_client.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { // ... then download all csv files for (FTPFile f : ftpFiles) { String remote_file = f.getName(); if (remote_file.endsWith("csv")) { String local_file = remote_file; if (remote_file.startsWith("Artikelstamm")) local_file = Constants.CSV_FILE_DISPO_ZR; OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + local_file); System.out.print("- Downloading " + remote_file + " from server " + fs + "... "); boolean done = ftp_client.retrieveFile(remote_file, os); if (done) System.out.println("success."); else System.out.println("error."); os.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:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java
public void conectarFTP(Archivo archivo) { FTPClient client = new FTPClient(); /*String sFTP = "127.0.0.1"; String sUser = "tae";/* w w w. j av a 2s . com*/ String sPassword = "tae";*/ String sFTP = buscarParametros(FTP_SERVER); String sUser = buscarParametros(FTP_USER); String sPassword = buscarParametros(FTP_PASSWORD); /////////////////////////////////// //String[] lista; try { client.connect(sFTP); boolean login = client.login(sUser, sPassword); System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory()); client.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = null; buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre())); client.enterLocalPassiveMode(); StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta. int i = 0; String nombre = ""; while (tokens.hasMoreTokens()) { if (i == 1) { nombre = tokens.nextToken(); i++; } else { i++; } } client.storeFile(nombre, buffIn); buffIn.close(); /*lista = client.listNames(); for (String lista1 : lista) { System.out.println(lista1); }*/ //client.changeWorkingDirectory("\\done"); //System.out.println("2. Working Directory: " + client.printWorkingDirectory()); client.logout(); client.disconnect(); System.out.println("Termin de conectarme al FTP!!"); } catch (IOException ioe) { ioe.printStackTrace(); } }
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 {// ww w. j av a 2s . com 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:fr.acxio.tools.agia.ftp.FTPUploadTasklet.java
@Override public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception { FTPClient aClient = ftpClientFactory.getFtpClient(); RegexFilenameFilter aFilter = new RegexFilenameFilter(); aFilter.setRegex(regexFilename);/* w ww .j ava2s. c o m*/ try { File aLocalDir = new File(localBaseDir); if (LOGGER.isInfoEnabled()) { LOGGER.info("Listing : {} ({}) for upload to [{}]", localBaseDir, regexFilename, aClient.getRemoteAddress().toString()); } File[] aLocalFiles = aLocalDir.listFiles(aFilter); if (LOGGER.isInfoEnabled()) { LOGGER.info(" {} file(s) found", aLocalFiles.length); } for (File aLocalFile : aLocalFiles) { if (sContribution != null) { sContribution.incrementReadCount(); } URI aRemoteFile = new URI(remoteBaseDir).resolve(aLocalFile.getName()); InputStream aInputStream; aInputStream = new FileInputStream(aLocalFile); try { if (LOGGER.isInfoEnabled()) { LOGGER.info(" Uploading : {} => {}", aLocalFile.getAbsolutePath(), aRemoteFile.toASCIIString()); } aClient.storeFile(aRemoteFile.toASCIIString(), aInputStream); if (sContribution != null) { sContribution.incrementWriteCount(1); } } finally { aInputStream.close(); } } } finally { aClient.logout(); aClient.disconnect(); } return RepeatStatus.FINISHED; }
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 .j a v a2s .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:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java
/** * _more_//from w w w . j a va 2 s . c o m * * @param file * _more_ * @param ignoreErrors * _more_ * * @return _more_ * * @throws Exception * _more_ */ private byte[] readFile(String file, boolean ignoreErrors) throws Exception { if (new File(file).exists()) { return IOUtil.readBytes(IOUtil.getInputStream(file, getClass())); } if (!file.startsWith("ftp:")) { if (ignoreErrors) { return null; } throw new FileNotFoundException("Could not read file: " + file); } URL url = new URL(file); FTPClient ftp = new FTPClient(); try { ftp.connect(url.getHost()); ftp.login("anonymous", "password"); ftp.setFileType(FTP.IMAGE_FILE_TYPE); ftp.enterLocalPassiveMode(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ftp.retrieveFile(url.getPath(), bos)) { return bos.toByteArray(); } else { throw new IOException("Unable to retrieve file:" + url); } } catch (org.apache.commons.net.ftp.FTPConnectionClosedException fcce) { System.err.println("ftp error:" + fcce); System.err.println(ftp.getReplyString()); if (!ignoreErrors) { throw fcce; } return null; } catch (Exception exc) { if (!ignoreErrors) { throw exc; } return null; } finally { try { ftp.logout(); } catch (Exception exc) { } try { ftp.disconnect(); } catch (Exception exc) { } } }
From source file:com.mirth.connect.connectors.file.filesystems.FtpConnection.java
public FtpConnection(String host, int port, FileSystemConnectionOptions fileSystemOptions, boolean passive, int timeout, FTPClient client) throws Exception { this.client = client; // This sets the timeout for read operations on data sockets. It does not affect write operations. client.setDataTimeout(timeout);// w w w . java 2 s . co m // This sets the timeout for the initial connection. client.setConnectTimeout(timeout); try { if (port > 0) { client.connect(host, port); } else { client.connect(host); } // This sets the timeout for read operations on the command socket. As per JavaDoc comments, you should only call this after the connection has been opened by connect() client.setSoTimeout(timeout); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.login(fileSystemOptions.getUsername(), fileSystemOptions.getPassword())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IOException("Ftp error"); } initialize(); if (passive) { client.enterLocalPassiveMode(); } } catch (Exception e) { if (client.isConnected()) { client.disconnect(); } throw e; } }