List of usage examples for org.apache.commons.net.ftp FTPClient getReplyCode
public int getReplyCode()
From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java
/** * Sends a single file to the remote host. <code>filename</code> may * contain a relative path specification. When this is the case, <code>sendFile</code> * will attempt to create any necessary parent directories before sending * the file. The file will then be sent using the entire relative path * spec - no attempt is made to change directories. It is anticipated that * this may eventually cause problems with some FTP servers, but it * simplifies the coding.//from w ww .j a v a2s . c o m * @param ftp ftp client * @param dir base directory of the file to be sent (local) * @param filename relative path of the file to be send * locally relative to dir * remotely relative to the remotedir attribute * @throws IOException in unknown circumstances * @throws BuildException in unknown circumstances */ protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException { InputStream instream = null; try { // TODO - why not simply new File(dir, filename)? File file = getProject().resolveFile(new File(dir, filename).getPath()); if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) { if (verbose) log("No need to transfer " + filename + " (" + file.getAbsolutePath() + " is up-to-date)"); return; } if (verbose) { // Fix for an obvious bug in ANT 1.8.4: // log("transferring " + filename + " to " + file.getAbsolutePath()); log("transferring " + file.getAbsolutePath() + " to " + filename); } instream = new BufferedInputStream(new FileInputStream(file)); createParents(ftp, filename); ftp.storeFile(resolveFile(filename), instream); boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); if (!success) { String s = "could not put file: " + ftp.getReplyString(); if (skipFailedTransfers) { log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { // see if we should issue a chmod command if (chmod != null) { doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename)); } log("File " + file.getAbsolutePath() + " copied to " + server, Project.MSG_VERBOSE); transferred++; } } finally { FileUtils.close(instream); } }
From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java
/** * Runs the task.// w ww . j a v a 2 s. co m * * @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.blue.star.plugins.check_ftp.java
public boolean execute_check() { /* Declare variables */ FTPClient ftp = new FTPClient(); File filename = null;//from w ww. j a v a 2s .co m 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.drftpd.tests.ConnectionStressTest.java
public void run() { try {//from ww w. jav a 2 s.co m FTPClient c = new FTPClient(); c.configure(ftpConfig); logger.debug("Trying to connect"); c.connect("127.0.0.1", 21211); logger.debug("Connected"); c.setSoTimeout(5000); if (!FTPReply.isPositiveCompletion(c.getReplyCode())) { logger.debug("Houston, we have a problem. D/C"); c.disconnect(); throw new Exception(); } if (c.login("drftpd", "drftpd")) { logger.debug("Logged-in, now waiting 5 secs and kill the thread."); _sc.addSuccess(); Thread.sleep(5000); c.disconnect(); } else { logger.debug("Login failed, D/C!"); throw new Exception(); } } catch (Exception e) { logger.debug(e, e); _sc.addFailure(); } logger.debug("exiting"); }
From source file:org.gogpsproject.parser.rinex.RinexNavigation.java
private RinexNavigationParser getFromFTP(String url) throws IOException { RinexNavigationParser rnp = null;//from w w w .j a v a 2 s.c o m String origurl = url; if (negativeChache.containsKey(url)) { if (System.currentTimeMillis() - negativeChache.get(url).getTime() < 60 * 60 * 1000) { throw new FileNotFoundException("cached answer"); } else { negativeChache.remove(url); } } String filename = url.replaceAll("[ ,/:]", "_"); if (filename.endsWith(".Z")) filename = filename.substring(0, filename.length() - 2); File rnf = new File(RNP_CACHE, filename); if (!rnf.exists()) { System.out.println(url + " from the net."); FTPClient ftp = new FTPClient(); try { int reply; System.out.println("URL: " + url); url = url.substring("ftp://".length()); String server = url.substring(0, url.indexOf('/')); String remoteFile = url.substring(url.indexOf('/')); String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/')); remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1); ftp.connect(server); ftp.login("anonymous", "info@eriadne.org"); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return null; } System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath)); System.out.println(ftp.getReplyString()); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println(ftp.getReplyString()); System.out.println("open " + remoteFile); InputStream is = ftp.retrieveFileStream(remoteFile); InputStream uis = is; System.out.println(ftp.getReplyString()); if (ftp.getReplyString().startsWith("550")) { negativeChache.put(origurl, new Date()); throw new FileNotFoundException(); } if (remoteFile.endsWith(".Z")) { uis = new UncompressInputStream(is); } rnp = new RinexNavigationParser(uis, rnf); rnp.init(); is.close(); ftp.completePendingCommand(); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } } else { System.out.println(url + " from cache file " + rnf); rnp = new RinexNavigationParser(rnf); rnp.init(); } return rnp; }
From source file:org.gogpsproject.parser.sp3.SP3Navigation.java
private SP3Parser getFromFTP(String url) throws IOException { SP3Parser sp3p = null;//from ww w . java2 s . c o m String filename = url.replaceAll("[ ,/:]", "_"); if (filename.endsWith(".Z")) filename = filename.substring(0, filename.length() - 2); File sp3f = new File(SP3_CACHE, filename); if (!sp3f.exists()) { System.out.println(url + " from the net."); FTPClient ftp = new FTPClient(); try { int reply; System.out.println("URL: " + url); url = url.substring("ftp://".length()); String server = url.substring(0, url.indexOf('/')); String remoteFile = url.substring(url.indexOf('/')); String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/')); remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1); ftp.connect(server); ftp.login("anonymous", "info@eriadne.org"); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return null; } System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath)); System.out.println(ftp.getReplyString()); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println(ftp.getReplyString()); System.out.println("open " + remoteFile); InputStream is = ftp.retrieveFileStream(remoteFile); InputStream uis = is; System.out.println(ftp.getReplyString()); if (ftp.getReplyString().startsWith("550")) { throw new FileNotFoundException(); } if (remoteFile.endsWith(".Z")) { uis = new UncompressInputStream(is); } sp3p = new SP3Parser(uis, sp3f); sp3p.init(); is.close(); ftp.completePendingCommand(); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } } else { System.out.println(url + " from cache file " + sp3f); sp3p = new SP3Parser(sp3f); sp3p.init(); } return sp3p; }
From source file:org.grouter.core.readers.FtpReaderJob.java
/** * Use configuration parameters to create a connection to the ftp endpoint. * @return a FTPClient instance//from w w w. j a va 2s .c o m * @throws Exception if connection problems */ private FTPClient initConnection() throws Exception { FTPClient client; String host = null; String strPort; try { Map map = node.getInBound().getEndPointContext(); host = node.getInBound().getUri(); strPort = (String) map.get(FTP_PORT); client = new FTPClient(); int port = FTP_DEFAULT_PORT; if (StringUtils.isNotEmpty(strPort)) { port = Integer.parseInt(strPort); client.connect(host, port); int reply = client.getReplyCode(); logger.debug("reply :" + reply); if (FTPReply.isPositiveCompletion(reply)) { logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress()); } } else { client.connect(host, port); int reply = client.getReplyCode(); logger.debug("reply :" + reply); if (FTPReply.isPositiveCompletion(reply)) { logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress()); } } String user = (String) map.get(FTP_AUTH_USER); String pwd = (String) map.get(FTP_AUTH_PASSWORD); if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(pwd)) { client.login(user, pwd); int replyCode = client.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { logger.info("Logged into ftp server :" + host); } } else { client.login("anonymous", "mymail@mail.com"); int replyCode = client.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { logger.info("Logged into ftp server :" + host); } } } catch (Exception e) { throw new Exception("Could not establish connection with ftp endpoint using host:" + host, e); } return client; }
From source file:org.jason.mapmaker.server.service.ShapefileMetadataServiceImpl.java
private List<String> getRemoteFilenames(String url, String directory) { FTPClient ftp = new FTPClient(); List<String> filenameList = new ArrayList<String>(); try {//from w w w. ja v a 2 s .co m int reply; ftp.connect(url); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.out.println("FTP connection failed for " + url); } ftp.enterLocalPassiveMode(); ftp.login("anonymous", ""); FTPFile[] files = ftp.listFiles(directory); for (FTPFile f : files) { filenameList.add(f.getName()); } ftp.logout(); } catch (IOException ex) { ex.printStackTrace(); } return filenameList; }
From source file:org.jboss.ejb3.examples.ch06.filetransfer.FileTransferBean.java
/** * Ensures that the last operation succeeded with a positive * reply code. Otherwise a {@link FileTransferException} * is raised, noting the reply code denoting the error. * //from w ww . ja v a 2 s .c o m * @throws FileTransferException */ protected void checkLastOperation() throws FileTransferException { // Get the client final FTPClient client = this.getClient(); // Obtain and check the reply from the connection final int connectReply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectReply)) { // Indicate the problem throw new FileTransferException( "Did not receive positive completion code from server, instead code was: " + connectReply); } }
From source file:org.jnode.protocol.ftp.FTPURLConnection.java
/** * @see java.net.URLConnection#getInputStream() *//* w w w. ja va 2 s .c om*/ public InputStream getInputStream() throws IOException { FTPClient client = new FTPClient(); client.connect(host); String replyString = client.getReplyString(); int replyCode = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { client.disconnect(); throw new IOException(replyString); } if (!client.login(username, password)) { replyString = client.getReplyString(); client.logout(); throw new IOException(replyString); } client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); try { client.retrieveFile(path, os); client.logout(); } finally { client.disconnect(); } return new ByteArrayInputStream(os.toByteArray()); }