List of usage examples for org.apache.commons.net.ftp FTPClient getReplyCode
public int getReplyCode()
From source file:org.jumpmind.metl.core.runtime.resource.FtpDirectory.java
protected FTPClient createClient() { FTPClient ftpClient = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftpClient.configure(config);/*from w w w.j a v a 2s . co m*/ if (connectTimeout != null) { ftpClient.setConnectTimeout(connectTimeout); } try { if (port != null) { ftpClient.connect(hostname, port); } else { ftpClient.connect(hostname); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new RuntimeException( String.format("Failed to connect to %s. Recevied a reply code of %d", hostname, reply)); } if (isNotBlank(username)) { if (!ftpClient.login(username, password)) { throw new AuthenticationException(); } } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (isNotBlank(basePath)) { ftpClient.changeWorkingDirectory(basePath); } return ftpClient; } catch (Exception e) { close(); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new IoException(e); } } }
From source file:org.jumpmind.metl.core.runtime.resource.FtpDirectory.java
@Override public InputStream getInputStream(String relativePath, boolean mustExist) { FTPClient ftpClient = null; try {/*from w ww . ja v a2s . c o m*/ ftpClient = createClient(); InputStream is = ftpClient.retrieveFileStream(relativePath); if (is != null) { return new CloseableInputStreamStream(is, ftpClient); } else { if (!mustExist) { String msg = String.format("Failed to open %s. The ftp return code was %s", relativePath, ftpClient.getReplyCode()); throw new IoException(msg); } else { return null; } } } catch (Exception e) { throw new IoException(e); } }
From source file:org.kuali.kfs.module.cg.service.impl.CfdaServiceImpl.java
/** * @return//from w w w .j a v a 2s .co m * @throws IOException */ public SortedMap<String, CFDA> getGovCodes() throws IOException { Calendar calendar = dateTimeService.getCurrentCalendar(); SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>(); // ftp://ftp.cfda.gov/programs09187.csv String govURL = parameterService.getParameterValueAsString(CfdaBatchStep.class, KFSConstants.SOURCE_URL_PARAMETER); String fileName = StringUtils.substringAfterLast(govURL, "/"); govURL = StringUtils.substringBeforeLast(govURL, "/"); if (StringUtils.contains(govURL, "ftp://")) { govURL = StringUtils.remove(govURL, "ftp://"); } // need to pull off the '20' in 2009 String year = "" + calendar.get(Calendar.YEAR); year = year.substring(2, 4); fileName = fileName + year; // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday" fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1); fileName = fileName + ".csv"; LOG.info("Getting government file: " + fileName + " for update"); InputStream inputStream = null; FTPClient ftp = new FTPClient(); try { ftp.connect(govURL); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOG.error("FTP connection to server not established."); throw new IOException("FTP connection to server not established."); } boolean isLoggedIn = ftp.login("anonymous", ""); if (!isLoggedIn) { LOG.error("Could not login as anonymous."); throw new IOException("Could not login as anonymous."); } LOG.info("Successfully connected and logged in"); ftp.enterLocalPassiveMode(); inputStream = ftp.retrieveFileStream(fileName); if (inputStream != null) { LOG.info("reading input stream"); InputStreamReader screenReader = new InputStreamReader(inputStream); BufferedReader screen = new BufferedReader(screenReader); CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1); List<String[]> lines = csvReader.readAll(); for (String[] line : lines) { String title = line[0]; String number = line[1]; CFDA cfda = new CFDA(); cfda.setCfdaNumber(number); cfda.setCfdaProgramTitleName(title); govMap.put(number, cfda); } } ftp.logout(); ftp.disconnect(); } finally { if (ftp.isConnected()) { ftp.disconnect(); } } return govMap; }
From source file:org.kuali.kra.external.Cfda.service.impl.CfdaServiceImpl.java
/** * This method connects to the FTP server. * @param url//w ww .java 2 s.com * @return ftp */ public FTPClient connect(String url) { FTPClient ftp = new FTPClient(); try { ftp.connect(getGovURL()); // Entering passive mode to prevent firewall issues. The client will establish a data transfer // connection. ftp.enterLocalPassiveMode(); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOG.error("FTP connection to server not established."); throw new IOException("FTP connection to server not established."); } boolean loggedIn = ftp.login(Constants.CFDA_GOV_LOGIN_USERNAME, ""); LOG.info("Logged in as " + Constants.CFDA_GOV_LOGIN_USERNAME); if (!loggedIn) { LOG.error("Could not login as anonymous."); throw new IOException("Could not login as anonymous."); } } catch (IOException io) { LOG.error(io.getMessage()); } return ftp; }
From source file:org.kuali.ole.coa.service.impl.CfdaServiceImpl.java
/** * @return//from ww w .j a v a 2s .co m * @throws IOException */ public SortedMap<String, CFDA> getGovCodes() throws IOException { Calendar calendar = SpringContext.getBean(DateTimeService.class).getCurrentCalendar(); SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>(); // ftp://ftp.cfda.gov/programs09187.csv String govURL = SpringContext.getBean(ParameterService.class).getParameterValueAsString(CfdaBatchStep.class, OLEConstants.SOURCE_URL_PARAMETER); String fileName = StringUtils.substringAfterLast(govURL, "/"); govURL = StringUtils.substringBeforeLast(govURL, "/"); if (StringUtils.contains(govURL, "ftp://")) { govURL = StringUtils.remove(govURL, "ftp://"); } // need to pull off the '20' in 2009 String year = "" + calendar.get(Calendar.YEAR); year = year.substring(2, 4); fileName = fileName + year; // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday" fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1); fileName = fileName + ".csv"; LOG.info("Getting government file: " + fileName + " for update"); InputStream inputStream = null; FTPClient ftp = new FTPClient(); try { ftp.connect(govURL); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOG.error("FTP connection to server not established."); throw new IOException("FTP connection to server not established."); } boolean loggedIn = ftp.login("anonymous", ""); if (!loggedIn) { LOG.error("Could not login as anonymous."); throw new IOException("Could not login as anonymous."); } LOG.info("Successfully connected and logged in"); ftp.enterLocalPassiveMode(); inputStream = ftp.retrieveFileStream(fileName); if (inputStream != null) { LOG.info("reading input stream"); InputStreamReader screenReader = new InputStreamReader(inputStream); BufferedReader screen = new BufferedReader(screenReader); CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1); List<String[]> lines = csvReader.readAll(); for (String[] line : lines) { String title = line[0]; String number = line[1]; CFDA cfda = new CFDA(); cfda.setCfdaNumber(number); cfda.setCfdaProgramTitleName(title); govMap.put(number, cfda); } } ftp.logout(); ftp.disconnect(); } finally { if (ftp.isConnected()) { ftp.disconnect(); } } return govMap; }
From source file:org.kuali.ole.module.purap.transmission.service.impl.TransmissionServiceImpl.java
/** * This method is to perform file upload * * @param ftpHostname/*from w w w . ja v a 2s.co m*/ * @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************************************"); }
From source file:org.moxie.ftp.FTP.java
/** * Create the specified directory on the remote host. * * @param ftp The FTP client connection/*from w ww. java 2 s .c o m*/ * @param dir The directory to create (format must be correct for host * type) * @throws IOException in unknown circumstances * @throws BuildException if ignoreNoncriticalErrors has not been set to true * and a directory could not be created, for instance because it was * already existing. Precisely, the codes 521, 550 and 553 will trigger * a BuildException */ protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException { String workingDirectory = ftp.printWorkingDirectory(); if (verbose) { if (dir.indexOf("/") == 0 || workingDirectory == null) { log("Creating directory: " + dir + " in /"); } else { log("Creating directory: " + dir + " in " + workingDirectory); } } if (dir.indexOf("/") == 0) { ftp.changeWorkingDirectory("/"); } String subdir = ""; StringTokenizer st = new StringTokenizer(dir, "/"); while (st.hasMoreTokens()) { subdir = st.nextToken(); log("Checking " + subdir, Project.MSG_DEBUG); if (!ftp.changeWorkingDirectory(subdir)) { if (!ftp.makeDirectory(subdir)) { // codes 521, 550 and 553 can be produced by FTP Servers // to indicate that an attempt to create a directory has // failed because the directory already exists. int rc = ftp.getReplyCode(); if (!(ignoreNoncriticalErrors && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) { throw new BuildException("could not create directory: " + ftp.getReplyString()); } if (verbose) { log("Directory already exists"); } } else { if (verbose) { log("Directory created OK"); } ftp.changeWorkingDirectory(subdir); } } } if (workingDirectory != null) { ftp.changeWorkingDirectory(workingDirectory); } }
From source file:org.moxie.ftp.FTPTaskMirrorImpl.java
/** * auto find the time difference between local and remote * @param ftp handle to ftp client//from w w w . ja v a2 s . com * @return number of millis to add to remote time to make it comparable to local time * @since ant 1.6 */ private long getTimeDiff(FTPClient ftp) { long returnValue = 0; File tempFile = findFileName(ftp); try { // create a local temporary file FILE_UTILS.createNewFile(tempFile); long localTimeStamp = tempFile.lastModified(); BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile)); ftp.storeFile(tempFile.getName(), instream); instream.close(); boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); if (success) { FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName()); if (ftpFiles.length == 1) { long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime(); returnValue = localTimeStamp - remoteTimeStamp; } ftp.deleteFile(ftpFiles[0].getName()); } // delegate the deletion of the local temp file to the delete task // because of race conditions occuring on Windows Delete mydelete = new Delete(); mydelete.bindToOwner(task); mydelete.setFile(tempFile.getCanonicalFile()); mydelete.execute(); } catch (Exception e) { throw new BuildException(e, task.getLocation()); } return returnValue; }
From source file:org.moxie.ftp.FTPTaskMirrorImpl.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.// w ww. j a v a2 s. 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 { // XXX - why not simply new File(dir, filename)? File file = task.getProject().resolveFile(new File(dir, filename).getPath()); if (task.isNewer() && isUpToDate(ftp, file, resolveFile(filename))) { return; } if (task.isVerbose()) { task.log("transferring " + file.getAbsolutePath()); } 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 (task.isSkipFailedTransfers()) { task.log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { // see if we should issue a chmod command if (task.getChmod() != null) { doSiteCommand(ftp, "chmod " + task.getChmod() + " " + resolveFile(filename)); } task.log("File " + file.getAbsolutePath() + " copied to " + task.getServer(), Project.MSG_VERBOSE); transferred++; } } finally { if (instream != null) { try { instream.close(); } catch (IOException ex) { // ignore it } } } }
From source file:org.moxie.ftp.FTPTaskMirrorImpl.java
/** * Retrieve a single file from the remote host. <code>filename</code> may * contain a relative path specification. <p> * * The file will then be retreived 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.</p>//from www.j a v a 2s .co m * @param ftp the ftp client * @param dir local base directory to which the file should go back * @param filename relative path of the file based upon the ftp remote directory * and/or the local base directory (dir) * @throws IOException in unknown circumstances * @throws BuildException if skipFailedTransfers is false * and the file cannot be retrieved. */ protected void getFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException { OutputStream outstream = null; try { File file = task.getProject().resolveFile(new File(dir, filename).getPath()); if (task.isNewer() && isUpToDate(ftp, file, resolveFile(filename))) { return; } if (task.isVerbose()) { task.log("transferring " + filename + " to " + file.getAbsolutePath()); } File pdir = file.getParentFile(); if (!pdir.exists()) { pdir.mkdirs(); } outstream = new BufferedOutputStream(new FileOutputStream(file)); ftp.retrieveFile(resolveFile(filename), outstream); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { String s = "could not get file: " + ftp.getReplyString(); if (task.isSkipFailedTransfers()) { task.log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { task.log("File " + file.getAbsolutePath() + " copied from " + task.getServer(), Project.MSG_VERBOSE); transferred++; if (task.isPreserveLastModified()) { outstream.close(); outstream = null; FTPFile[] remote = ftp.listFiles(resolveFile(filename)); if (remote.length > 0) { FILE_UTILS.setFileLastModified(file, remote[0].getTimestamp().getTime().getTime()); } } } } finally { if (outstream != null) { try { outstream.close(); } catch (IOException ex) { // ignore it } } } }