List of usage examples for org.apache.commons.net.ftp FTPClient isConnected
public boolean isConnected()
From source file:ServeurFTP.java
public ServeurFTP(String server10, String username10, String password10, String file10, String server20, String username20, String password20, String file20) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts;//from w w w.j a va 2s .com int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; server1 = server10; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = username10; password1 = password10; file1 = file10; server2 = server20; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = username20; password2 = password20; file2 = file20; listener = new PrintCommandListener(new PrintWriter(System.out), true); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { int reply; if (port1 > 0) { ftp1.connect(server1, port1); } else { ftp1.connect(server1); } System.out.println("Connected to " + server1 + "."); reply = ftp1.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp1.disconnect(); System.err.println("FTP server1 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp1.isConnected()) { try { ftp1.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server1."); e.printStackTrace(); System.exit(1); } try { int reply; if (port2 > 0) { ftp2.connect(server2, port2); } else { ftp2.connect(server2); } System.out.println("Connected to " + server2 + "."); reply = ftp2.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp2.disconnect(); System.err.println("FTP server2 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp2.isConnected()) { try { ftp2.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server2."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp1.login(username1, password1)) { System.err.println("Could not login to " + server1); break __main; } if (!ftp2.login(username2, password2)) { System.err.println("Could not login to " + server2); break __main; } // Let's just assume success for now. ftp2.enterRemotePassiveMode(); ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort()); // Although you would think the store command should be sent to server2 // first, in reality, ftp servers like wu-ftpd start accepting data // connections right after entering passive mode. Additionally, they // don't even send the positive preliminary reply until after the // transfer is completed (in the case of passive mode transfers). // Therefore, calling store first would hang waiting for a preliminary // reply. if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) { // if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) { // We have to fetch the positive completion reply. ftp1.completePendingCommand(); ftp2.completePendingCommand(); } else { System.err.println("Couldn't initiate transfer. Check that filenames are valid."); break __main; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (ftp1.isConnected()) { ftp1.logout(); ftp1.disconnect(); } } catch (IOException e) { // do nothing } try { if (ftp2.isConnected()) { ftp2.logout(); ftp2.disconnect(); } } catch (IOException e) { // do nothing } } }
From source file:com.jmeter.alfresco.utils.FtpUtils.java
/** * Upload directory or file.//from w ww .ja v a2 s.co m * * @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.savy3.util.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(Configuration conf) throws IOException { FTPClient ftp = null; try {/* w w w . j ava2 s . c om*/ String username = conf.get(DBConfiguration.USERNAME_PROPERTY); String password; if (username == null) { username = "anonymous"; password = ""; } else { password = DBConfiguration.getPassword((JobConf) conf); } String connectString = conf.get(DBConfiguration.URL_PROPERTY); String server = connectString; int port = 0; String[] parts = connectString.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { LOG.warn("Invalid port number: " + e.toString()); } } if (null != mockFTPClient) { ftp = mockFTPClient; } else { ftp = new FTPClient(); } FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS); ftp.configure(config); if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); } try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } } catch (IOException ioexp) { throw new IOException("Could not connect to server " + server, ioexp); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString()); } LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set Binary transfer mode ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.featureValue("LITERAL SITE RDW"); ftp.doCommand("SITE", "RDW"); System.out.println("reply for LITERAL" + ftp.getReplyString()); // Use passive mode as default. ftp.enterLocalPassiveMode(); } catch (IOException ioe) { if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } ftp = null; throw ioe; } return ftp; }
From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java
@Override public void upload(String path, File file, String contentType) { Map<String, String> ftpInfo = getFtpInfo(contentType); if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username")) && !"".equals(ftpInfo.get("password"))) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {/*from ww w .j av a 2s.c o m*/ inputStream = new FileInputStream(file); ftpClient.connect(ftpInfo.get("host"), 21); ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password")); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); path = ftpInfo.get("path") + path; if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } } }
From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java
@Override public void upload(String path, File file, String contentType) { PluginConfig pluginConfig = getPluginConfig(); if (pluginConfig != null) { String host = pluginConfig.getAttribute("host"); Integer port = Integer.valueOf(pluginConfig.getAttribute("port")); String username = pluginConfig.getAttribute("username"); String password = pluginConfig.getAttribute("password"); FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {//from w w w . jav a 2s . c o m inputStream = new BufferedInputStream(new FileInputStream(file)); ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (SocketException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); try { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } catch (IOException e) { } } } }
From source file:main.TestManager.java
/** * Deletes all local tests, downloads tests from the server * and saves all downloaded test in the local directory. *//*from ww w. j a v a 2 s. c o m*/ public static void syncTestsWithServer() { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; String server = "zajicek.endora.cz"; ftp.connect(server, 21); // After connection attempt, we check the reply code to verify // success. reply = ftp.getReplyCode(); //Not connected successfully - inform the user if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); Debugger.println("FTP server refused connection."); ErrorInformer.failedSyncing(); return; } // LOGIN boolean success = ftp.login("plakato", "L13nK4"); Debugger.println("Login successful: " + success); if (success == false) { ftp.disconnect(); ErrorInformer.failedSyncing(); return; } ftp.enterLocalPassiveMode(); // Get all files from the server FTPFile[] files = ftp.listFiles(); System.out.println("Got files! Count: " + files.length); // Delete all current test to be replaced with // actulized version File[] locals = new File("src/tests/").listFiles(); for (File f : locals) { if (f.getName() == "." || f.getName() == "..") { continue; } f.delete(); } // Copy the files from server to local folder int failed = 0; for (FTPFile f : files) { if (f.isFile()) { Debugger.println(f.getName()); if (f.getName() == "." || f.getName() == "..") { continue; } File file = new File("src/tests/" + f.getName()); file.createNewFile(); OutputStream output = new FileOutputStream(file); if (!ftp.retrieveFile(f.getName(), output)) failed++; output.close(); } } // If we failed to download some file, inform the user if (failed != 0) { ftp.disconnect(); ErrorInformer.failedSyncing(); return; } // Disconnect ftp client or resolve the potential error ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } if (error) { ErrorInformer.failedSyncing(); } Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Download hotov"); alert.setHeaderText(null); alert.setContentText("Vetky testy boli zo servru spene stiahnut."); alert.showAndWait(); alert.close(); }
From source file:main.TestManager.java
/** * Deletes all files on the server and uploads all the * tests from the local directory./* ww w . ja v a 2s. c o m*/ */ public static void syncServerWithTest() { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; String server = "zajicek.endora.cz"; ftp.connect(server, 21); // After connection attempt, we check the reply code to verify // success. reply = ftp.getReplyCode(); //Not connected successfully - inform the user if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); Debugger.println("FTP server refused connection."); ErrorInformer.failedSyncing(); return; } // LOGIN boolean success = ftp.login("plakato", "L13nK4"); Debugger.println("Login successful: " + success); if (success == false) { ftp.disconnect(); ErrorInformer.failedSyncing(); return; } ftp.enterLocalPassiveMode(); // Get all files from the server FTPFile[] files = ftp.listFiles(); System.out.println("Got files! Count: " + files.length); // Delete all current tests on the server to be replaced with // actualized version from local directory for (FTPFile f : files) { if (f.getName() == "." || f.getName() == "..") { continue; } if (f.isFile()) { ftp.deleteFile(f.getName()); } } // Copy the files from local folder to server File localFolder = new File("src/tests/"); File[] localFiles = localFolder.listFiles(); int failed = 0; for (File f : localFiles) { if (f.getName() == "." || f.getName() == "..") { continue; } if (f.isFile()) { Debugger.println(f.getName()); File file = new File("src/tests/" + f.getName()); InputStream input = new FileInputStream(file); if (!ftp.storeFile(f.getName(), input)) failed++; input.close(); } } // If we failed to upload some file, inform the user if (failed != 0) { ftp.disconnect(); ErrorInformer.failedSyncing(); return; } // Disconnect ftp client or resolve the potential error ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } if (error) { ErrorInformer.failedSyncing(); return; } } Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Upload hotov"); alert.setHeaderText(null); alert.setContentText("spene sa podarilo skoprova vetky testy na server!"); alert.showAndWait(); alert.close(); }
From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java
/** * FTP????????//from w w w . ja va 2s. c o m * * @param addressText * @return FTP */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); FTPClient client = new FTPClient(); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } else { retry = false; isReachable = false; } } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(FTP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.cladonia.xngreditor.URLUtilities.java
public static InputStream open(URL url) throws IOException { // System.out.println( "URLUtilities.open( "+url+")"); InputStream stream = null;// w w w . ja v a 2s .com String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) { try { DefaultAuthenticator authenticator = Main.getDefaultAuthenticator(); URL newURL = new URL(URLUtilities.toString(url)); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication( new PasswordAuthentication(username, password.toCharArray())); } stream = newURL.openStream(); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication(null); } } catch (Exception e) { // System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage()); // try it with webdav WebdavResource webdav = createWebdavResource(toString(url), username, password); stream = webdav.getMethodData(toString(url)); webdav.close(); } } else if (protocol.equals("ftp")) { FTPClient client = null; String host = url.getHost(); try { // System.out.println( "Connecting to: "+host+" ..."); client = new FTPClient(); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Could not connect."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in using: "+username+", "+password+" ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Opening file \""+url.getFile()+"\" ..."); stream = client.retrieveFileStream(url.getFile()); // System.out.println( "File opened."); // System.out.println( "Disconnecting ..."); client.disconnect(); // System.out.println( "Disconnected."); } catch (IOException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException f) { // do nothing e.printStackTrace(); } } throw new IOException("Could not connect to FTP Server \"" + host + "\"."); } } else if (protocol.equals("file")) { stream = url.openStream(); } else { //unknown protocol but try anyways try { stream = url.openStream(); } catch (IOException ioe) { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } } return stream; }
From source file:com.tumblr.maximopro.iface.router.FTPHandler.java
@Override public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException { byte[] encodedData = super.invoke(metaData, data); this.metaData = metaData; FTPClient ftp; if (enableSSL()) { FTPSClient ftps = new FTPSClient(isImplicit()); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); ftp = ftps;//from www . ja v a 2 s.c o m } else { ftp = new FTPClient(); } InputStream is = null; try { if (getTimeout() > 0) { ftp.setDefaultTimeout(getTimeout()); } if (getBufferSize() > 0) { ftp.setBufferSize(getBufferSize()); } if (getNoDelay()) { ftp.setTcpNoDelay(getNoDelay()); } ftp.connect(getHostname(), getPort()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } if (!ftp.login(getUsername(), getPassword())) { ftp.logout(); ftp.disconnect(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (enableActive()) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } is = new ByteArrayInputStream(encodedData); String remoteFileName = getFileName(metaData); ftp.changeWorkingDirectory("/"); if (createDirectoryStructure(ftp, getDirName().split("/"))) { ftp.storeFile(remoteFileName, is); } else { throw new MXApplicationException("iface", "cannotcreatedir"); } ftp.logout(); } catch (MXException e) { throw e; } catch (SocketException e) { throw new MXApplicationException("iface", "ftpsocketerror", e); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } } return null; }