List of usage examples for org.apache.commons.net.ftp FTPClient connect
public void connect(InetAddress host) throws SocketException, IOException
From source file:org.kuali.kra.external.Cfda.service.impl.CfdaServiceImpl.java
/** * This method connects to the FTP server. * @param url/*from w ww . j ava 2s . 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//w ww . j a va 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 ww.j av a 2 s . 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.limy.common.util.FtpUtils.java
/** * FTP????//from w ww. j a va 2 s .com * <p> * ?????disconnect????? * </p> * @param client FTP * @param info FTP * @throws IOException I/O */ public static void connectFtp(FTPClient client, FtpInfo info) throws IOException { client.connect(info.getServerAddress()); if (!client.login(info.getUserName(), info.getPassword())) { throw new IOException("?????"); } if (info.getPath() != null) { client.cwd(info.getPath()); } }
From source file:org.middleheaven.io.repository.ftp.TestFTP.java
private FTPClient connect() { try {/*from w w w . java 2s. co m*/ FTPClient ftp = new FTPClient(); if (!ftp.isConnected()) { ftp.connect("184.107.197.226"); ftp.login("javabuil", "%Q&4pr|!O}="); } return ftp; } catch (IOException e) { throw ManagedIOException.manage(e); } }
From source file:org.n52.sos.importer.controller.Step1Controller.java
@Override public boolean isFinished() { if (step1Panel != null && step1Panel.getFeedingType() == Step1Panel.CSV_FILE) { final String filePath = step1Panel.getCSVFilePath(); if (filePath == null) { JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing", JOptionPane.WARNING_MESSAGE); return false; }/* w w w . j av a2 s . com*/ // checks one-time feed input data for validity if (filePath.equals("")) { JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing", JOptionPane.WARNING_MESSAGE); return false; } final File dataFile = new File(filePath); if (!dataFile.exists()) { JOptionPane.showMessageDialog(null, "The specified file does not exist.", "Error", JOptionPane.ERROR_MESSAGE); return false; } if (!dataFile.isFile()) { JOptionPane.showMessageDialog(null, "Please specify a file, not a directory.", "Error", JOptionPane.ERROR_MESSAGE); return false; } if (!dataFile.canRead()) { JOptionPane.showMessageDialog(null, "No reading access on the specified file.", "Error", JOptionPane.ERROR_MESSAGE); return false; } readFile(dataFile, step1Panel.getFileEncoding()); } else if (step1Panel != null && (step1Panel.getFeedingType() == Step1Panel.FTP_FILE)) { // checks repetitive feed input data for validity if (step1Panel.getUrl() == null || step1Panel.getUrl().equals("")) { JOptionPane.showMessageDialog(null, "No ftp server was specified.", "Server missing", JOptionPane.ERROR_MESSAGE); return false; } if (step1Panel.getFilenameSchema() == null || step1Panel.getFilenameSchema().equals("")) { JOptionPane.showMessageDialog(null, "No file/file schema was specified.", "File/file schema missing", JOptionPane.ERROR_MESSAGE); return false; } // ftp client FTPClient client; // proxy final String pHost = System.getProperty("proxyHost", "proxy"); int pPort = -1; if (System.getProperty("proxyPort") != null) { pPort = Integer.parseInt(System.getProperty("proxyPort")); } final String pUser = System.getProperty("http.proxyUser"); final String pPassword = System.getProperty("http.proxyPassword"); if (pHost != null && pPort != -1) { if (pUser != null && pPassword != null) { client = new FTPHTTPClient(pHost, pPort, pUser, pPassword); } client = new FTPHTTPClient(pHost, pPort); } else { client = new FTPClient(); } // get first file if (step1Panel.getFeedingType() == Step1Panel.FTP_FILE) { final String csvFilePath = System.getProperty("user.home") + File.separator + ".SOSImporter" + File.separator + "tmp_" + step1Panel.getFilenameSchema(); // if back button was used: delete old file if (new File(csvFilePath).exists()) { new File(csvFilePath).delete(); } try { client.connect(step1Panel.getUrl()); final boolean login = client.login(step1Panel.getUser(), step1Panel.getPassword()); if (login) { // download file final int result = client.cwd(step1Panel.getDirectory()); if (result == 250) { // successfully connected final File outputFile = new File(csvFilePath); final FileOutputStream fos = new FileOutputStream(outputFile); client.retrieveFile(step1Panel.getFilenameSchema(), fos); fos.flush(); fos.close(); } final boolean logout = client.logout(); if (logout) { logger.info("Step1Controller: cannot logout!"); } } else { logger.info("Step1Controller: cannot login!"); } final File csv = new File(csvFilePath); if (csv.length() != 0) { step1Panel.setCSVFilePath(csvFilePath); readFile(new File(csvFilePath), step1Panel.getFileEncoding()); } else { csv.delete(); throw new IOException(); } } catch (final SocketException e) { System.err.println(e); JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error", JOptionPane.ERROR_MESSAGE); return false; } catch (final IOException e) { System.err.println(e); JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error", JOptionPane.ERROR_MESSAGE); return false; } } } return true; }
From source file:org.n52.sos.importer.feeder.task.OneTimeFeeder.java
private DataFile getRemoteFile(final Configuration config) { File dataFile = null;//www. j a v a 2 s . co m // ftp client FTPClient client; // proxy final String pHost = System.getProperty("proxyHost", "proxy"); int pPort = -1; if (System.getProperty("proxyPort") != null) { pPort = Integer.parseInt(System.getProperty("proxyPort")); } final String pUser = System.getProperty("http.proxyUser"); final String pPassword = System.getProperty("http.proxyPassword"); if (pHost != null && pPort != -1) { LOG.info("Using proxy for FTP connection!"); if (pUser != null && pPassword != null) { client = new FTPHTTPClient(pHost, pPort, pUser, pPassword); } client = new FTPHTTPClient(pHost, pPort); } else { LOG.info("Using no proxy for FTP connection!"); client = new FTPClient(); } // get first file final String directory = config.getConfigFile().getAbsolutePath(); dataFile = FileHelper.createFileInImporterHomeWithUniqueFileName(directory + ".csv"); // if back button was used: delete old file if (dataFile.exists()) { dataFile.delete(); } try { client.connect(config.getFtpHost()); final boolean login = client.login(config.getUser(), config.getPassword()); if (login) { LOG.info("FTP: connected..."); // download file final int result = client.cwd(config.getFtpSubdirectory()); LOG.info("FTP: go into directory..."); if (result == 250) { // successfully connected final FileOutputStream fos = new FileOutputStream(dataFile); LOG.info("FTP: download file..."); client.retrieveFile(config.getFtpFile(), fos); fos.flush(); fos.close(); } else { LOG.info("FTP: cannot go to subdirectory!"); } final boolean logout = client.logout(); if (!logout) { LOG.info("FTP: cannot logout!"); } } else { LOG.info("FTP: cannot login!"); } } catch (final SocketException e) { LOG.error("The file you specified cannot be obtained."); return null; } catch (final IOException e) { LOG.error("The file you specified cannot be obtained."); return null; } return new DataFile(config, dataFile); }
From source file:org.opennms.systemreport.formatters.FtpSystemReportFormatter.java
@Override public void end() { m_zipFormatter.end();// w w w . ja v a 2 s.c o m IOUtils.closeQuietly(m_outputStream); final FTPClient ftp = new FTPClient(); FileInputStream fis = null; try { if (m_url.getPort() == -1 || m_url.getPort() == 0 || m_url.getPort() == m_url.getDefaultPort()) { ftp.connect(m_url.getHost()); } else { ftp.connect(m_url.getHost(), m_url.getPort()); } if (m_url.getUserInfo() != null && m_url.getUserInfo().length() > 0) { final String[] userInfo = m_url.getUserInfo().split(":", 2); ftp.login(userInfo[0], userInfo[1]); } else { ftp.login("anonymous", "opennmsftp@"); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); LOG.error("FTP server refused connection."); return; } String path = m_url.getPath(); if (path.endsWith("/")) { LOG.error("Your FTP URL must specify a filename."); return; } File f = new File(path); path = f.getParent(); if (!ftp.changeWorkingDirectory(path)) { LOG.info("unable to change working directory to {}", path); return; } LOG.info("uploading {} to {}", f.getName(), path); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); fis = new FileInputStream(m_zipFile); if (!ftp.storeFile(f.getName(), fis)) { LOG.info("unable to store file"); return; } LOG.info("finished uploading"); } catch (final Exception e) { LOG.error("Unable to FTP file to {}", m_url, e); } finally { IOUtils.closeQuietly(fis); if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } }
From source file:org.openspice.vfs.ftp.FtpVVolume.java
private void reconnect(final FTPClient ftpc) throws IOException { Print.println(Print.VFS, "Reconnecting ..."); final String user_info = this.root_url.getUserInfo(); final int n = user_info.indexOf(':'); final String user = n >= 0 ? user_info.substring(0, n) : user_info; final String pw = n >= 0 ? user_info.substring(n + 1) : ""; if (Print.wouldPrint(Print.VFS)) { Print.println("User ID : " + user); Print.println("Password: " + pw); Print.println("Host : " + root_url.getHost()); }/* w ww .j ava 2 s. c o m*/ ftpc.connect(this.root_url.getHost()); final boolean ok = ftpc.login(user, pw); if (!ok) { new Alert("Cannot connect to FTP server").culprit("host", root_url.getHost()).mishap(); } if (!ftpc.setFileType(FTP.BINARY_FILE_TYPE)) { new Alert("Cannot set file type").mishap(); } }
From source file:org.oss.digitalforms.MobileFormsImpl.java
private void ftpValidations(String ftpHost, String user, String password) throws Exception { FTPClient ftp = new FTPClient(); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect();//from w w w . ja v a 2 s . c o m throw new Exception("Exception in connecting to FTP Server"); } ftp.login(user, password); ftp.listFiles(); ftp.disconnect(); }