List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:org.apache.sqoop.connector.ftp.ftpclient.FtpConnectorClient.java
/** * Constructor to initialize client.//from w w w . j a va2 s. co m * * @param server Hostname of FTP server. * @param port Port number of FTP server. Pass in null to use default port * of 21. */ public FtpConnectorClient(String server, Integer port) { ftpClient = new FTPClient(); ftpServer = server; if (port != null) { ftpPort = port.intValue(); } }
From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(TransferableContext context, LinkConfiguration linkConfiguration) throws IOException { FTPClient ftp = null;//from w w w . j a va 2 s. c om try { String username = linkConfiguration.linkConfig.username; String password; if (username == null) { username = "anonymous"; password = ""; } else { password = linkConfiguration.linkConfig.password; } String connectString = linkConfiguration.linkConfig.uri; 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(); } // The following section to get the system key for FTPClientConfig is just there for testing purposes String systemKey = null; String systemTypeString = context.getString("spark.mainframe.connector.system.type", "MVS"); if (systemTypeString.equals("MVS")) { systemKey = FTPClientConfig.SYST_MVS; } else if (systemTypeString.equals("UNIX")) { systemKey = FTPClientConfig.SYST_UNIX; } else { assert (false); } FTPClientConfig config = new FTPClientConfig(systemKey); ftp.configure(config); 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())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set ASCII transfer mode ftp.setFileType(FTP.ASCII_FILE_TYPE); // 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:org.apache.sqoop.util.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(Configuration conf) throws IOException { FTPClient ftp = null;/* ww w . j a v a2s. c o m*/ try { 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())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set ASCII transfer mode ftp.setFileType(FTP.ASCII_FILE_TYPE); // Use passive mode as default. ftp.enterLocalPassiveMode(); LOG.info("System type detected: " + ftp.getSystemType()); } 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:org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Runs the task./*from ww w .j av a 2 s . c om*/ * * @throws BuildException if the task fails or is not configured * correctly. */ public void execute() throws BuildException { checkAttributes(); FTPClient ftp = null; try { log("Opening FTP connection to " + server, Project.MSG_VERBOSE); ftp = new FTPClient(); if (this.isConfigurationSet) { ftp = FTPConfigurator.configure(ftp, this); } ftp.setRemoteVerificationEnabled(enableRemoteVerification); ftp.connect(server, port); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } log("connected", Project.MSG_VERBOSE); log("logging in to FTP server", Project.MSG_VERBOSE); if ((this.account != null && !ftp.login(userid, password, account)) || (this.account == null && !ftp.login(userid, password))) { throw new BuildException("Could not login to FTP server"); } log("login succeeded", Project.MSG_VERBOSE); if (binary) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (passive) { log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } // If an initial command was configured then send it. // Some FTP servers offer different modes of operation, // E.G. switching between a UNIX file system mode and // a legacy file system. if (this.initialSiteCommand != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.initialSiteCommand); } }, "initial site command: " + this.initialSiteCommand); } // For a unix ftp server you can set the default mask for all files // created. if (umask != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + umask); } }, "umask " + umask); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (action == MK_DIR) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, remotedir); } }, remotedir); } else if (action == SITE_CMD) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.siteCommand); } }, "Site Command: " + this.siteCommand); } else { if (remotedir != null) { log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE); ftp.changeWorkingDirectory(remotedir); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (newerOnly && timeDiffAuto) { // in this case we want to find how much time span there is between local // and remote timeDiffMillis = getTimeDiff(ftp); } log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { // ignore it } } } }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java
public void doFTP() throws BuildException { FTPClient ftp = null;//from w ww.j ava 2 s . c o m try { task.log("Opening FTP connection to " + task.getServer(), Project.MSG_VERBOSE); ftp = new FTPClient(); if (task.isConfigurationSet()) { ftp = FTPConfigurator.configure(ftp, task); } ftp.setRemoteVerificationEnabled(task.getEnableRemoteVerification()); ftp.connect(task.getServer(), task.getPort()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } task.log("connected", Project.MSG_VERBOSE); task.log("logging in to FTP server", Project.MSG_VERBOSE); if ((task.getAccount() != null && !ftp.login(task.getUserid(), task.getPassword(), task.getAccount())) || (task.getAccount() == null && !ftp.login(task.getUserid(), task.getPassword()))) { throw new BuildException("Could not login to FTP server"); } task.log("login succeeded", Project.MSG_VERBOSE); if (task.isBinary()) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (task.isPassive()) { task.log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } // If an initial command was configured then send it. // Some FTP servers offer different modes of operation, // E.G. switching between a UNIX file system mode and // a legacy file system. if (task.getInitialSiteCommand() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getInitialSiteCommand()); } }, "initial site command: " + task.getInitialSiteCommand()); } // For a unix ftp server you can set the default mask for all files // created. if (task.getUmask() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + task.getUmask()); } }, "umask " + task.getUmask()); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (task.getAction() == FTPTask.MK_DIR) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, task.getRemotedir()); } }, task.getRemotedir()); } else if (task.getAction() == FTPTask.SITE_CMD) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getSiteCommand()); } }, "Site Command: " + task.getSiteCommand()); } else { if (task.getRemotedir() != null) { task.log("changing the remote directory", Project.MSG_VERBOSE); ftp.changeWorkingDirectory(task.getRemotedir()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (task.isNewer() && task.isTimeDiffAuto()) { // in this case we want to find how much time span there is between local // and remote task.setTimeDiffMillis(getTimeDiff(ftp)); } task.log( FTPTask.ACTION_STRS[task.getAction()] + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { task.log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { // ignore it } } } }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTest.java
@Before public void setUp() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml"); Project project = buildRule.getProject(); project.executeTarget("setup"); tmpDir = project.getProperty("tmp.dir"); ftp = new FTPClient(); ftpFileSep = project.getProperty("ftp.filesep"); myFTPTask.setSeparator(ftpFileSep);//from www . j a v a 2 s . co m myFTPTask.setProject(project); remoteTmpDir = myFTPTask.resolveFile(tmpDir); String remoteHost = project.getProperty("ftp.host"); int port = Integer.parseInt(project.getProperty("ftp.port")); String remoteUser = project.getProperty("ftp.user"); String password = project.getProperty("ftp.password"); boolean connectionSucceeded = false; try { ftp.connect(remoteHost, port); connectionSucceeded = true; } catch (Exception ex) { loginFailureMessage = "could not connect to host " + remoteHost + " on port " + port; } if (connectionSucceeded) { try { ftp.login(remoteUser, password); loginSuceeded = true; } catch (IOException ioe) { loginFailureMessage = "could not log on to " + remoteHost + " as user " + remoteUser; } } }
From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java
/** * Runs the task./*from w w w .ja v a 2s.c om*/ * * @throws BuildException if the task fails or is not configured * correctly. */ @Override public void execute() throws BuildException { checkAttributes(); FTPClient ftp = null; try { log("Opening FTP connection to " + server, Project.MSG_VERBOSE); ftp = new FTPClient(); if (this.isConfigurationSet) { ftp = FTPConfigurator.configure(ftp, this); } ftp.setRemoteVerificationEnabled(enableRemoteVerification); if (this.proxyServer != null) { // Connect through an FTP proxy. // Get FTP proxy credentials (optional). String proxyUserId; char[] proxyPassword; { PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.proxyServer, this.proxyPort, this.proxyUserid, this.proxyPassword, RequestorType.PROXY); if (pa == null) { proxyUserId = null; proxyPassword = null; } else { proxyUserId = pa.getUserName(); if (proxyUserId == null) throw new BuildException("Proxy user ID missing"); proxyPassword = pa.getPassword(); if (proxyPassword == null) throw new BuildException("Proxy password missing"); } } // Get remote FTP server credentials (mandatory). String serverUserId; char[] serverPassword; { PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid, this.password, RequestorType.SERVER); if (pa == null) throw new BuildException("User ID and password missing"); serverUserId = pa.getUserName(); if (serverUserId == null) throw new BuildException("User ID missing"); serverPassword = pa.getPassword(); if (serverPassword == null) throw new BuildException("Password missing"); } // Connect to the FTP proxy. this.log("Opening FTP connection to proxy server \"" + this.proxyServer + "\" on port " + this.proxyPort, Project.MSG_VERBOSE); ftp.connect(this.proxyServer, this.proxyPort); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection to proxy server failed: " + ftp.getReplyString()); } this.log("connected to proxy server", Project.MSG_VERBOSE); // Authenticate with the FTP proxy (optional). if (proxyUserId != null) { this.log("logging in to FTP proxy server", Project.MSG_VERBOSE); if (!ftp.login(proxyUserId, new String(proxyPassword))) { throw new BuildException("Could not login to FTP proxy server"); } } // Log in to the remote FTP server. this.log("logging in to FTP server", Project.MSG_VERBOSE); String userid2 = serverUserId + '@' + this.server; if (this.port != FTP2.DEFAULT_FTP_PORT) userid2 += ":" + this.port; if (this.account == null ? !ftp.login(userid2, new String(serverPassword)) : !ftp.login(userid2, new String(serverPassword), this.account)) throw new BuildException("Could not login to FTP server"); this.log("login succeeded", Project.MSG_VERBOSE); } else { // Direct connection to remote FTP server. // Get remote FTP server credentials (mandatory). String serverUserId; char[] serverPassword; { PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid, this.password, RequestorType.SERVER); if (pa == null) throw new BuildException("User ID and password missing"); serverUserId = pa.getUserName(); if (serverUserId == null) throw new BuildException("User ID missing"); serverPassword = pa.getPassword(); if (serverPassword == null) throw new BuildException("Password missing"); } // Connect to the remote FTP server. this.log("Opening FTP connection to " + this.server, Project.MSG_VERBOSE); ftp.connect(this.server, this.port); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } this.log("connected", Project.MSG_VERBOSE); // Log in to the remote FTP server. this.log("logging in to FTP server", Project.MSG_VERBOSE); if (this.account == null ? !ftp.login(serverUserId, new String(serverPassword)) : !ftp.login(serverUserId, new String(serverPassword), this.account)) throw new BuildException("Could not login to FTP server"); this.log("login succeeded", Project.MSG_VERBOSE); } if (binary) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (passive) { log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } // If an initial command was configured then send it. // Some FTP servers offer different modes of operation, // E.G. switching between a UNIX file system mode and // a legacy file system. if (this.initialSiteCommand != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { @Override public void execute() throws IOException { doSiteCommand(lftp, FTP2.this.initialSiteCommand); } }, "initial site command: " + this.initialSiteCommand); } // For a unix ftp server you can set the default mask for all files // created. if (umask != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { @Override public void execute() throws IOException { doSiteCommand(lftp, "umask " + umask); } }, "umask " + umask); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (action == MK_DIR) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { @Override public void execute() throws IOException { makeRemoteDir(lftp, remotedir); } }, remotedir); } else if (action == SITE_CMD) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { @Override public void execute() throws IOException { doSiteCommand(lftp, FTP2.this.siteCommand); } }, "Site Command: " + this.siteCommand); } else { if (remotedir != null) { log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE); ftp.changeWorkingDirectory(remotedir); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (newerOnly && timeDiffAuto) { // in this case we want to find how much time span there is between local // and remote timeDiffMillis = getTimeDiff(ftp); } log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { // ignore it } } } }
From source file:org.apdplat.platform.util.FtpUtils.java
/** * FTP?/*from w w w . j ava 2 s .c om*/ * @param host FTP?? * @param port FTP??? * @param username ?? * @param password ? * @return */ public boolean connect(String host, int port, String username, String password) { try { ftpClient = new FTPClient(); ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); LOG.error("FTP???" + reply); return false; } } catch (IOException e) { LOG.error("FTP?", e); return false; } return true; }
From source file:org.blue.star.plugins.check_ftp.java
public boolean execute_check() { /* Declare variables */ FTPClient ftp = new FTPClient(); File filename = null;//from w w w . j a v a 2 s .c om FileChannel channel; InputStream is; OutputStream os; int reply; if (super.verbose > 0) verbose = true; /* Configure client to meet our requirements */ ftp.setDefaultPort(port); ftp.setDefaultTimeout(timeout); if (verbose) { System.out.println("Using FTP Server: " + hostname); System.out.println("Using FTP Port: " + port); System.out.println("Using Timeout of: " + timeout); } if (passive) { ftp.enterLocalPassiveMode(); if (verbose) System.out.println("Using Passive Mode"); } try { filename = new File(file); channel = new RandomAccessFile(filename, "rw").getChannel(); if (verbose) System.out.println("Attempting FTP Connection to " + hostname); ftp.connect(hostname); reply = ftp.getReplyCode(); /* Test to see if we actually managed to connect */ if (!FTPReply.isPositiveCompletion(reply)) { if (verbose) System.out.println("FTP Connection to " + hostname + " failed"); check_state = common_h.STATE_CRITICAL; check_message = ftp.getReplyString(); filename.delete(); ftp.disconnect(); return true; } /* Try and login if we're using username/password */ if (username != null && password != null) { if (verbose) System.out.println("Attempting to log in into FTP Server " + hostname); if (!ftp.login(username, password)) { if (verbose) System.out.println("Unable to log in to FTP Server " + hostname); check_state = common_h.STATE_CRITICAL; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } } if (verbose) System.out.println("Attempting to change to required directory"); /* Try and change to the given directory */ if (!ftp.changeWorkingDirectory(directory)) { if (verbose) System.out.println("Required directory cannot be found!"); check_state = common_h.STATE_WARNING; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } if (verbose) System.out.println("Attempting to retrieve specified file!"); /* Try to get Stream on Remote File! */ is = ftp.retrieveFileStream(file); if (is == null) { if (verbose) System.out.println("Unable to locate required file."); check_state = common_h.STATE_WARNING; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } /* OutputStream */ os = Channels.newOutputStream(channel); /* Create the buffer */ byte[] buf = new byte[4096]; if (verbose) System.out.println("Beginning File transfer..."); for (int len = -1; (len = is.read(buf)) != -1;) os.write(buf, 0, len); if (verbose) { System.out.println("...transfer complete."); System.out.println("Attempting to finalise Command"); } /* Finalise the transfer details */ if (!ftp.completePendingCommand()) { if (verbose) System.out.println("Unable to finalise command"); check_state = common_h.STATE_WARNING; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } /* Clean up */ if (verbose) System.out.println("Check Completed."); check_state = common_h.STATE_OK; check_message = ftp.getReplyString(); /* Close out things */ is.close(); os.close(); channel.close(); filename.delete(); } catch (IOException e) { check_state = common_h.STATE_CRITICAL; check_message = e.getMessage(); if (filename != null) filename.delete(); } finally { if (ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (Exception e) { } } } return true; }
From source file:org.codice.alliance.nsili.source.NsiliSource.java
/** * Uses FTPClient to obtain the IOR string from the provided URL via FTP. *//* ww w . j a v a 2 s .co m*/ private void getIorStringFromFtpSource() { URI uri = null; try { uri = new URI(iorUrl); } catch (URISyntaxException e) { LOGGER.error("{} : Invalid URL specified for IOR string: {} {}", id, iorUrl, e.getMessage()); LOGGER.debug("{} : Invalid URL specified for IOR string: {}", id, iorUrl, e); } FTPClient ftpClient = new FTPClient(); try { if (uri.getPort() > 0) { ftpClient.connect(uri.getHost(), uri.getPort()); } else { ftpClient.connect(uri.getHost()); } if (!ftpClient.login(serverUsername, serverPassword)) { LOGGER.error("{} : FTP server log in unsuccessful.", id); } else { int timeoutMsec = clientTimeout * 1000; ftpClient.setConnectTimeout(timeoutMsec); ftpClient.setControlKeepAliveReplyTimeout(timeoutMsec); ftpClient.setDataTimeout(timeoutMsec); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); InputStream inputStream = ftpClient.retrieveFileStream(uri.getPath()); iorString = IOUtils.toString(inputStream, StandardCharsets.ISO_8859_1.name()); //Remove leading/trailing whitespace as the CORBA init can't handle that. iorString = iorString.trim(); } } catch (Exception e) { LOGGER.warn("{} : Error retrieving IOR file for {}. {}", id, iorUrl, e.getMessage()); LOGGER.debug("{} : Error retrieving IOR file for {}.", id, iorUrl, e); } }