List of usage examples for org.apache.commons.net.ftp FTPClient enterLocalPassiveMode
public void enterLocalPassiveMode()
PASSIVE_LOCAL_DATA_CONNECTION_MODE
. From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java
/** * _more_//from www . ja v a2s . 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.alexkasko.netty.ftp.FtpServerTest.java
@Test public void test() throws IOException, InterruptedException { final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate( new ConsoleReceiver()); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w w w .j a v a 2 s . c om protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipe = ch.pipeline(); pipe.addLast("decoder", new CrlfStringDecoder()); pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate)); } }); b.localAddress(2121).bind(); FTPClient client = new FTPClient(); // https://issues.apache.org/jira/browse/NET-493 client.setBufferSize(0); client.connect("127.0.0.1", 2121); assertEquals(230, client.user("anonymous")); // active assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE)); assertEquals("/", client.printWorkingDirectory()); assertTrue(client.changeWorkingDirectory("/foo")); assertEquals("/foo", client.printWorkingDirectory()); assertTrue(client.listFiles("/foo").length == 0); assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes()))); assertTrue(client.rename("bar", "baz")); // assertTrue(client.deleteFile("baz")); // passive assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE)); client.enterLocalPassiveMode(); assertEquals("/foo", client.printWorkingDirectory()); assertTrue(client.changeWorkingDirectory("/foo")); assertEquals("/foo", client.printWorkingDirectory()); //TODO make a virtual filesystem that would work with directory //assertTrue(client.listFiles("/foo").length==1); assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes()))); assertTrue(client.rename("bar", "baz")); // client.deleteFile("baz"); assertEquals(221, client.quit()); try { client.noop(); fail("Should throw exception"); } catch (IOException e) { //expected; } }
From source file:adams.gui.chooser.FtpRemoteDirectorySetup.java
/** * Returns a new client for the host/port defined in the options. * * @return the client//from w ww . j a v a 2 s. c o m */ public FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:com.jmeter.alfresco.utils.FtpUtils.java
/** * Upload directory or file.// www. ja va2s. c om * * @param host the host * @param port the port * @param userName the user name * @param password the password * @param fromLocalDirOrFile the local dir * @param toRemoteDirOrFile the remote dir * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String uploadDirectoryOrFile(final String host, final int port, final String userName, final String password, final String fromLocalDirOrFile, final String toRemoteDirOrFile) throws IOException { final FTPClient ftpClient = new FTPClient(); String responseMessage = Constants.EMPTY; try { // Connect and login to get the session ftpClient.connect(host, port); final int replyCode = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { final boolean loginSuccess = ftpClient.login(userName, password); if (loginSuccess) { LOG.debug("Connected to remote host!"); //Use local passive mode to pass fire-wall //In this mode a data connection is made by opening a port on the server for the client to connect //and this is not blocked by fire-wall. ftpClient.enterLocalPassiveMode(); final File localDirOrFileObj = new File(fromLocalDirOrFile); if (localDirOrFileObj.isFile()) { LOG.debug("Uploading file: " + fromLocalDirOrFile); uploadFile(ftpClient, fromLocalDirOrFile, toRemoteDirOrFile + FILE_SEPERATOR_LINUX + localDirOrFileObj.getName()); } else { uploadDirectory(ftpClient, toRemoteDirOrFile, fromLocalDirOrFile, EMPTY); } responseMessage = "Upload completed successfully!"; } else { responseMessage = "Could not login to the remote host!"; } //Log out and disconnect from the server once FTP operation is completed. if (ftpClient.isConnected()) { try { ftpClient.logout(); } catch (IOException ignored) { LOG.error("Ignoring the exception while logging out from remote host: ", ignored); } try { ftpClient.disconnect(); LOG.debug("Disconnected from remote host!"); } catch (IOException ignored) { LOG.error("Ignoring the exception while disconnecting from remote host: ", ignored); } } } else { responseMessage = "Host connection failed!"; } LOG.debug("ResponseMessage:=> " + responseMessage); } catch (IOException ioexcp) { LOG.error("IOException occured in uploadDirectoryOrFile(..): ", ioexcp); throw ioexcp; } return responseMessage; }
From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java
public FTPClient getFtpClient(HashMap<String, String> params) { String urlServer = params.get("urlServer"); String usuario = params.get("user"); String pass = params.get("pass"); // String workingDir = params.get("workingDir"); FTPClient ret = null;//from w w w .j a v a2 s .c o m try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(InetAddress.getByName(urlServer)); ftpClient.login(usuario, pass); //Verificar conexin con el servidor. int reply = ftpClient.getReplyCode(); System.out.println("Estatus de conexion FTP:" + reply); if (FTPReply.isPositiveCompletion(reply)) { System.out.println("Conectado exitosamente"); } else { System.out.println("No se pudo conectar con el servidor"); } //directorio de trabajo // ftpClient.changeWorkingDirectory(workingDir); System.out.println("Establecer carpeta de trabajo"); //Activar que se envie cualquier tipo de archivo ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ret = ftpClient; } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } return ret; }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient ftp = null; try {/*from w ww . j ava2s . c o m*/ ftp = new FTPClient(); // For debug // f.addProtocolCommandListener(new PrintCommandListener( // new PrintWriter(System.out))); ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(fpi.getHost()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); ftp.login(fpi.getUsername(), fpi.getPassword()); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); if (fpi.isFtpUsePassiveMode()) ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); FTPClient ftpReturn = ftp; ftp = null; return ftpReturn; } finally { if (ftp != null) ftpQuietDisconnect(ftp); } }
From source file:com.cisco.dvbu.ps.utils.net.FtpFile.java
public void ftpFile(String fileName) throws CustomProcedureException, SQLException { // new ftp client FTPClient ftp = new FTPClient(); OutputStream output = null;/*from www .j ava2 s .c o m*/ success = false; try { //try to connect ftp.connect(hostIp); //login to server if (!ftp.login(userId, userPass)) { ftp.logout(); qenv.log(LOG_ERROR, "Ftp server refused connection user/password incorrect."); } int reply = ftp.getReplyCode(); //FTPReply stores a set of constants for FTP Reply codes if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); qenv.log(LOG_ERROR, "Ftp server refused connection."); } //enter passive mode ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE); ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); //get system name //System.out.println("Remote system is " + ftp.getSystemType()); //change current directory ftp.changeWorkingDirectory(ftpDirName); System.out.println("Current directory is " + ftp.printWorkingDirectory()); System.out.println("File is " + fileName); output = new FileOutputStream(dirName + "/" + fileName); //get the file from the remote system success = ftp.retrieveFile(fileName, output); //close output stream output.close(); } catch (IOException ex) { throw new CustomProcedureException("Error in CJP " + getName() + ": " + ex.toString()); } }
From source file:adams.core.io.lister.FtpDirectoryLister.java
/** * Returns a new client for the host defined in the options. * * @return the client, null if failed to create *//*from w ww .ja v a 2s .c o m*/ protected FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downIBSA() { String fl = ""; String fp = ""; String fs = ""; try {/* www . j a va 2 s . c om*/ FileInputStream glnCodesCsv = new FileInputStream(Constants.DIR_IBSA + "/access.ami.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(glnCodesCsv, "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("IbsaAmiko")) { 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.changeWorkingDirectory("data"); 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; } System.out.println("- Connected to server " + fs + "..."); //get list of filenames FTPFile[] ftpFiles = ftp_client.listFiles(); List<String> list_remote_files = Arrays.asList("Konditionen.csv", "Targeting_diff.csv", "Address.csv"); List<String> list_local_files = Arrays.asList(Constants.FILE_CUST_IBSA, Constants.FILE_TARG_IBSA, Constants.FILE_MOOS_ADDR); if (ftpFiles != null && ftpFiles.length > 0) { int index = 0; for (String remote_file : list_remote_files) { OutputStream os = new FileOutputStream(Constants.DIR_IBSA + "/" + list_local_files.get(index)); System.out.print("- Downloading " + remote_file + " from server " + fs + "... "); boolean done = ftp_client.retrieveFile(remote_file, os); if (done) System.out.println("file downloaded successfully."); else System.out.println("error."); os.close(); index++; } } } 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.maxl.java.aips2sqlite.AllDown.java
public void downDesitin() { String fl = ""; String fp = ""; String fs = ""; try {//w w w . java 2 s .com FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/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("ftp_amiko")) { 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 + "..."); // Set working directory String working_dir = "ywesee_in"; ftp_client.changeWorkingDirectory(working_dir); 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("Kunden")) local_file = Constants.FILE_CUST_DESITIN; if (remote_file.startsWith("Artikel")) local_file = Constants.FILE_ARTICLES_DESITIN; OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + 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(); } } }