List of usage examples for org.apache.commons.net.ftp FTPClient cwd
public int cwd(String directory) throws IOException
From source file:de.l3s.dlg.ncbikraken.ftp.NcbiFTPClient.java
public static void getMedline(MedlineFileType type) { FileOutputStream out = null;/*from w w w . j a v a 2 s. c om*/ FTPClient ftp = new FTPClient(); try { // Connection String LOGGER.info("Connecting to FTP server " + SERVER_NAME); ftp.connect(SERVER_NAME); ftp.login("anonymous", ""); ftp.cwd(BASELINE_PATH); ftp.cwd(type.getServerPath()); try { ftp.pasv(); } catch (IOException e) { LOGGER.error( "Can not access the passive mode. Maybe a problem with your (Windows) firewall. Just try to run as administrator: \nnetsh advfirewall set global StatefulFTP disable"); return; } for (FTPFile file : ftp.listFiles()) { if (file.isFile()) { File meshF = new File(file.getName()); LOGGER.debug("Downloading file: " + SERVER_NAME + ":" + BASELINE_PATH + "/" + type.getServerPath() + "/" + meshF.getName()); out = new FileOutputStream(Configuration.INSTANCE.getMedlineDir() + File.separator + meshF); ftp.retrieveFile(meshF.getName(), out); out.flush(); out.close(); } } } catch (IOException ioe) { LOGGER.error(ioe.getMessage()); } finally { IOUtils.closeQuietly(out); try { ftp.disconnect(); } catch (IOException e) { LOGGER.error(e.getMessage()); } } }
From source file:edu.stanford.epad.common.util.FTPUtil.java
public boolean sendFile(String filePath, boolean delete) throws Exception { String fileName = filePath;/*from w w w. j ava 2s . co m*/ int slash = fileName.lastIndexOf("/"); if (slash != -1) fileName = fileName.substring(slash + 1); slash = fileName.lastIndexOf("\\"); if (slash != -1) fileName = fileName.substring(slash + 1); boolean success = true; FTPClient ftp = new FTPClient(); try { ftp.connect(ftpHost, ftpPort); int reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(ftpUser, ftpPassword)) { if (ftpFolder != null && ftpFolder.trim().length() > 0) { ftp.cwd(ftpFolder); System.out.print("ftp cd: " + ftp.getReplyString()); } ftp.setFileType(FTP.ASCII_FILE_TYPE); FileInputStream in = new FileInputStream(filePath); success = ftp.storeFile(fileName, in); in.close(); if (delete) { File file = new File(filePath); file.delete(); } } else success = false; } } finally { ftp.disconnect(); } return success; }
From source file:net.yacy.grid.io.assets.FTPStorageFactory.java
public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread) throws IOException { this.server = server; this.username = username == null ? "" : username; this.password = password == null ? "" : password; this.port = port; this.deleteafterread = deleteafterread; this.ftpClient = new Storage<byte[]>() { @Override/*from ww w .ja va2s .c o m*/ public void checkConnection() throws IOException { return; } private FTPClient initConnection() throws IOException { FTPClient ftp = new FTPClient(); ftp.setDataTimeout(3000); ftp.setConnectTimeout(20000); if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) { ftp.connect(FTPStorageFactory.this.server); } else { ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port); } ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } throw new IOException("bad connection to ftp server: " + reply); } if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } throw new IOException("login failure"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setBufferSize(8192); return ftp; } @Override public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException { long t0 = System.currentTimeMillis(); FTPClient ftp = initConnection(); try { long t1 = System.currentTimeMillis(); String file = cdPath(ftp, path); long t2 = System.currentTimeMillis(); ftp.enterLocalPassiveMode(); boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset)); long t3 = System.currentTimeMillis(); if (!success) throw new IOException("storage to path " + path + " was not successful (storeFile=false)"); Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = " + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2)); } catch (IOException e) { throw e; } finally { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } } return FTPStorageFactory.this; } @Override public Asset<byte[]> load(String path) throws IOException { FTPClient ftp = initConnection(); ByteArrayOutputStream baos = null; byte[] b = null; try { String file = cdPath(ftp, path); baos = new ByteArrayOutputStream(); ftp.retrieveFile(file, baos); b = baos.toByteArray(); if (FTPStorageFactory.this.deleteafterread) try { boolean deleted = ftp.deleteFile(file); FTPFile[] remaining = ftp.listFiles(); if (remaining.length == 0) { ftp.cwd("/"); if (path.startsWith("/")) path = path.substring(1); int p = path.indexOf('/'); if (p > 0) path = path.substring(0, p); ftp.removeDirectory(path); } } catch (Throwable e) { Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e); } } catch (IOException e) { throw e; } finally { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } } return new Asset<byte[]>(FTPStorageFactory.this, b); } @Override public void close() { } private String cdPath(FTPClient ftp, String path) throws IOException { int success_code = ftp.cwd("/"); if (success_code >= 300) throw new IOException("cannot cd into " + path + ": " + success_code); if (path.length() == 0 || path.equals("/")) return ""; if (path.charAt(0) == '/') path = path.substring(1); // we consider that all paths are absolute to / (home) int p; while ((p = path.indexOf('/')) > 0) { String dir = path.substring(0, p); int code = ftp.cwd(dir); if (code >= 300) { // path may not exist, try to create the path boolean success = ftp.makeDirectory(dir); if (!success) throw new IOException("unable to create directory " + dir + " for path " + path); code = ftp.cwd(dir); if (code >= 300) throw new IOException("unable to cwd into directory " + dir + " for path " + path); } path = path.substring(p + 1); } return path; } }; }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test CWD for FTP server/*from w w w . ja v a2 s . co m*/ * * @throws Exception */ public void testCWD() throws Exception { logger.debug("Start testCWD"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); FTPFile[] files = ftp.listFiles(); reply = ftp.getReplyCode(); assertTrue(FTPReply.isPositiveCompletion(reply)); assertTrue(files.length == 1); boolean foundAlfresco = false; for (FTPFile file : files) { logger.debug("file name=" + file.getName()); assertTrue(file.isDirectory()); if (file.getName().equalsIgnoreCase("Alfresco")) { foundAlfresco = true; } } assertTrue(foundAlfresco); // Change to Alfresco Dir that we know exists reply = ftp.cwd("/Alfresco"); assertTrue(FTPReply.isPositiveCompletion(reply)); // relative path with space char reply = ftp.cwd("Data Dictionary"); assertTrue(FTPReply.isPositiveCompletion(reply)); // non existant absolute reply = ftp.cwd("/Garbage"); assertTrue(FTPReply.isNegativePermanent(reply)); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Wild card reply = ftp.cwd("/Alfresco/User*Homes"); assertTrue("unable to change to /Alfresco User*Homes/", FTPReply.isPositiveCompletion(reply)); // // Single char pattern match // reply = ftp.cwd("/Alfre?co"); // assertTrue("Unable to match single char /Alfre?co", FTPReply.isPositiveCompletion(reply)); // two level folder reply = ftp.cwd("/Alfresco/Data Dictionary"); assertTrue("unable to change to /Alfresco/Data Dictionary", FTPReply.isPositiveCompletion(reply)); // go up one reply = ftp.cwd(".."); assertTrue("unable to change to ..", FTPReply.isPositiveCompletion(reply)); reply = ftp.pwd(); ftp.getStatus(); assertTrue("unable to get status", FTPReply.isPositiveCompletion(reply)); // check we are at the correct point in the tree reply = ftp.cwd("Data Dictionary"); assertTrue(FTPReply.isPositiveCompletion(reply)); } finally { ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test CRUD for FTP server//w w w . j av a 2s . c om * * @throws Exception */ public void testCRUD() throws Exception { final String PATH1 = "FTPServerTest"; final String PATH2 = "Second part"; logger.debug("Start testFTPCRUD"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory ftp.makeDirectory(PATH1); ftp.cwd(PATH1); // make sub-directory in new directory ftp.makeDirectory(PATH2); ftp.cwd(PATH2); // List the files in the new directory FTPFile[] files = ftp.listFiles(); assertTrue("files not empty", files.length == 0); // Create a file String FILE1_CONTENT_1 = "test file 1 content"; String FILE1_NAME = "testFile1.txt"; ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8"))); // Get the new file FTPFile[] files2 = ftp.listFiles(); assertTrue("files not one", files2.length == 1); InputStream is = ftp.retrieveFileStream(FILE1_NAME); String content = inputStreamToString(is); assertEquals("Content is not as expected", content, FILE1_CONTENT_1); ftp.completePendingCommand(); // Update the file contents String FILE1_CONTENT_2 = "That's how it is says Pooh!"; ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); InputStream is2 = ftp.retrieveFileStream(FILE1_NAME); String content2 = inputStreamToString(is2); assertEquals("Content is not as expected", FILE1_CONTENT_2, content2); ftp.completePendingCommand(); // now delete the file we have been using. assertTrue(ftp.deleteFile(FILE1_NAME)); // negative test - file should have gone now. assertFalse(ftp.deleteFile(FILE1_NAME)); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test of obscure path names in the FTP server * /*from ww w .ja v a2 s . c om*/ * RFC959 states that paths are constructed thus... * <string> ::= <char> | <char><string> * <pathname> ::= <string> * <char> ::= any of the 128 ASCII characters except <CR> and <LF> * * So we need to check how high characters and problematic are encoded */ public void testPathNames() throws Exception { logger.debug("Start testPathNames"); FTPClient ftp = connectClient(); String PATH1 = "testPathNames"; try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User*Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory for this test boolean success = ftp.makeDirectory(PATH1); assertTrue("unable to make directory:" + PATH1, success); success = ftp.changeWorkingDirectory(PATH1); assertTrue("unable to change to working directory:" + PATH1, success); assertTrue("with a space", ftp.makeDirectory("test space")); assertTrue("with exclamation", ftp.makeDirectory("space!")); assertTrue("with dollar", ftp.makeDirectory("space$")); assertTrue("with brackets", ftp.makeDirectory("space()")); assertTrue("with hash curley brackets", ftp.makeDirectory("space{}")); //Pound sign U+00A3 //Yen Sign U+00A5 //Capital Omega U+03A9 assertTrue("with pound sign", ftp.makeDirectory("pound \u00A3.world")); assertTrue("with yen sign", ftp.makeDirectory("yen \u00A5.world")); // Test steps that do not work // assertTrue("with omega", ftp.makeDirectory("omega \u03A9.world")); // assertTrue("with obscure ASCII chars", ftp.makeDirectory("?/.,<>")); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test of rename case ALF-20584/*from w ww. j a v a2 s. com*/ * */ public void testRenameCase() throws Exception { logger.debug("Start testRenameCase"); FTPClient ftp = connectClient(); String PATH1 = "testRenameCase"; try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User*Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory for this test boolean success = ftp.makeDirectory(PATH1); assertTrue("unable to make directory:" + PATH1, success); ftp.cwd(PATH1); String FILE1_CONTENT_2 = "That's how it is says Pooh!"; ftp.storeFile("FileA.txt", new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT")); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test Setting the modification time FTP server * * @throws Exception/*from w ww . ja va2 s. co m*/ */ public void testModificationTime() throws Exception { final String PATH1 = "FTPServerTest"; final String PATH2 = "ModificationTime"; logger.debug("Start testModificationTime"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory ftp.makeDirectory(PATH1); ftp.cwd(PATH1); // make sub-directory in new directory ftp.makeDirectory(PATH2); ftp.cwd(PATH2); // List the files in the new directory FTPFile[] files = ftp.listFiles(); assertTrue("files not empty", files.length == 0); // Create a file String FILE1_CONTENT_1 = "test file 1 content"; String FILE1_NAME = "testFile1.txt"; ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8"))); String pathname = "/Alfresco/User Homes" + "/" + PATH1 + "/" + PATH2 + "/" + FILE1_NAME; logger.debug("set modification time"); // YYYYMMDDhhmmss Time set to 2012 August 30 12:39:05 String olympicTime = "20120830123905"; ftp.setModificationTime(pathname, olympicTime); String extractedTime = ftp.getModificationTime(pathname); // Feature of the commons ftp library ExtractedTime has a "status code" first and is followed by newline chars assertTrue("time not set correctly by explicit set time", extractedTime.contains(olympicTime)); // Get the new file FTPFile[] files2 = ftp.listFiles(); assertTrue("files not one", files2.length == 1); InputStream is = ftp.retrieveFileStream(FILE1_NAME); String content = inputStreamToString(is); assertEquals("Content is not as expected", content, FILE1_CONTENT_1); ftp.completePendingCommand(); // Update the file contents without setting time directly String FILE1_CONTENT_2 = "That's how it is says Pooh!"; ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); InputStream is2 = ftp.retrieveFileStream(FILE1_NAME); String content2 = inputStreamToString(is2); assertEquals("Content is not as expected", FILE1_CONTENT_2, content2); ftp.completePendingCommand(); extractedTime = ftp.getModificationTime(pathname); assertFalse("time not moved on if time not explicitly set", extractedTime.contains(olympicTime)); // now delete the file we have been using. assertTrue(ftp.deleteFile(FILE1_NAME)); // negative test - file should have gone now. assertFalse(ftp.deleteFile(FILE1_NAME)); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
From source file:org.alinous.ftp.FtpManager.java
public int changeDir(String sessionId, String remote) throws IOException { FTPClient ftp = this.instances.get(sessionId).getFtp(); int b = ftp.cwd(remote); //String cur = ftp.getReplyString(); //System.out.println(cur); return b;//from w w w . j a va 2s .co m }
From source file:org.kuali.ole.module.purap.transmission.service.impl.TransmissionServiceImpl.java
/** * This method is to perform file upload * * @param ftpHostname// ww w . j a v a2 s .c om * @param ftpUsername * @param ftpPassword * @param file * @param fileName */ @Override public void doFTPUpload(String ftpHostname, String ftpUsername, String ftpPassword, String file, String fileName) { LOG.trace("************************************doFTPUpload() started************************************"); FTPClient ftpClient = new FTPClient(); FileInputStream inputStream = null; FileOutputStream outputStream = null; try { ftpClient.connect(ftpHostname); ftpClient.login(ftpUsername, ftpPassword); ftpClient.enterLocalPassiveMode(); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { LOG.debug("Connected to FTP server."); } else { LOG.debug("FTP server refused connection."); } // upload ftpClient.setFileType(FTP.BINARY_FILE_TYPE); String fileLocation = getFileLocation(); if (LOG.isDebugEnabled()) { LOG.debug("File Location in FTP Server================>" + fileLocation); LOG.debug("File source=================================>" + file); LOG.debug("FileName====================================>" + fileName); } ftpClient.mkd(fileLocation); ftpClient.cwd(fileLocation); inputStream = new FileInputStream(file); ftpClient.storeFile(fileName, inputStream); ftpClient.logout(); inputStream.close(); } catch (Exception e) { LOG.error("Exception performing SFTP upload of " + file + " to " + ftpHostname, e); throw new RuntimeException(e); } LOG.trace( "************************************doFTPUpload() completed************************************"); }