List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:org.ikasan.connector.ftp.net.FileTransferProtocolClient.java
/** * Method that handles the creation and connection for FTP. * /* w w w. j a v a2s .co m*/ * @throws ClientConnectionException if connection attempt fails */ private void doConnect() throws ClientConnectionException { this.ftpClient = new FTPClient(); String msg = new String("Attempting connection to [" + remoteHostname + "]."); //$NON-NLS-1$ //$NON-NLS-2$ logger.debug(msg); try { /* * Summer (Nov 26th 2008): Rather than relying on the FTP client to * figure out the system it is connecting to (and hence what parsers * it should use) we pass this configuration to the client and force * it to use it. */ if ((systemKey != null) && (!"".equals(systemKey))) { ftpClient.configure(new FTPClientConfig(systemKey)); } // leave local port unspecified int localPort = 0; this.ftpClient.setDefaultTimeout(this.connectionTimeout); // Keep trying to connect, until successful for (int i = 0; i < DEFAULT_MAXIMUM_LOCAL_PORT; i++) { try { logger.debug("Connecting to remote host [" + this.remoteHostname + ":" + this.remotePort + "] from local host [" + this.localHostname + ":" + localPort + "]."); // Had to update the ftpClient.connect method as the localhost was not resolving correctly //ftpClient.connect(InetAddress.getByName(this.remoteHostname), this.remotePort, InetAddress.getByName(this.localHostname), localPort); ftpClient.connect(InetAddress.getByName(this.remoteHostname), this.remotePort); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new SocketException("Connection attempt failed with replyCode [" + reply + "]"); } if (active) { this.ftpClient.enterLocalActiveMode(); } else { this.ftpClient.enterLocalPassiveMode(); } this.ftpClient.setSoTimeout(this.socketTimeout); this.ftpClient.setDataTimeout(this.dataTimeout); break; } catch (BindException be) { logger.info("Address is already in use.. will try again.", be); } } } catch (SocketException se) { msg = new String(msg + " [Failed]"); //$NON-NLS-1$ logger.info(msg, se); // Clean up after ourselves just in case try { if (this.ftpClient != null && this.ftpClient.isConnected()) { this.ftpClient.disconnect(); } } catch (IOException disconnectException) { logger.warn("Could not cleanup after a failed connect, this may leave behind open sockets.", disconnectException); } throw new ClientConnectionException(msg, se); } catch (IOException ie) { msg = new String(msg + " [Failed]"); //$NON-NLS-1$ logger.info(msg, ie); // Clean up after ourselves try { if (this.ftpClient != null && this.ftpClient.isConnected()) { this.ftpClient.disconnect(); } } catch (IOException disconnectException) { logger.warn("Could not cleanup after a failed connect, this may leave behind open sockets.", disconnectException); } throw new ClientConnectionException(msg, ie); } logger.info( "Connected to host [" + remoteHostname + "]. " + "Mode [" + (active ? "active" : "passive") + "]."); }
From source file:org.isatools.isacreator.filechooser.FTPBrowser.java
public FTPBrowser(String directory, String username, String password) throws NoSuchAlgorithmException, IOException { super(FileBrowser.REMOTE_FILE_SYSTEM); // if protocol if ftps if (directory.contains("ftps")) { ftpClient = new FTPSClient(); } else {/*from w ww. j av a 2 s . co m*/ ftpClient = new FTPClient(); } connect(directory, username, password); }
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 . j ava 2s .c o 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
/** * Called by the container when the instance has been created or re-activated * (brought out of passivated state). Will construct the underlying FTP Client * and open all appropriate connections. * * @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#connect() */// w w w . ja va 2s. c om @PostConstruct @PostActivate @Override public void connect() throws IllegalStateException, FileTransferException { /* * Precondition checks */ final FTPClient clientBefore = this.getClient(); if (clientBefore != null && clientBefore.isConnected()) { throw new IllegalStateException("FTP Client is already initialized"); } // Get the connection properties final String connectHost = this.getConnectHost(); final int connectPort = this.getConnectPort(); // Create the client final FTPClient client = new FTPClient(); final String canonicalServerName = connectHost + ":" + connectPort; log.fine("Connecting to FTP Server at " + canonicalServerName); try { client.connect(connectHost, connectPort); } catch (final IOException ioe) { throw new FileTransferException("Error in connecting to " + canonicalServerName, ioe); } // Set log.info("Connected to FTP Server at: " + canonicalServerName); this.setClient(client); // Check that the last operation succeeded this.checkLastOperation(); try { // Login client.login("user", "password"); // Check that the last operation succeeded this.checkLastOperation(); } catch (final Exception e) { throw new FileTransferException("Could not log in", e); } // If there's a pwd defined, cd into it. final String pwd = this.getPresentWorkingDirectory(); if (pwd != null) { this.cd(pwd); } }
From source file:org.jevis.ftpdatasource.FTPDataSource.java
@Override public List<InputStream> sendSampleRequest(JEVisObject channel) { List<InputStream> answerList = new ArrayList<InputStream>(); try {// ww w. j a v a2 s . c o m if (_ssl) { System.out.println("ftps connection"); _fc = new FTPSClient(); } else { _fc = new FTPClient(); } // _fc.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); if (_connectionTimeout != 0) { _fc.setConnectTimeout(_connectionTimeout.intValue() * 1000); } if (_readTimeout != 0) { _fc.setDataTimeout(_readTimeout.intValue() * 1000); } _fc.connect(_serverURL, _port); // _fc.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); if (_fc.login(_userName, _password) == false) { org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ERROR, "No Login possible"); // throw new FetchingException(_id, FetchingExceptionType.CONNECTION_ERROR); } // _fc.setFileType(FTP.BINARY_FILE_TYPE); // _fc.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE); _fc.setBufferSize(1024000); _fc.setUseEPSVwithIPv4(false); _fc.enterLocalPassiveMode(); InputStream answer = null; JEVisClass channelClass = channel.getJEVisClass(); JEVisType pathType = channelClass.getType(DataCollectorTypes.Channel.FTPChannel.PATH); String filePath = DatabaseHelper.getObjectAsString(channel, pathType); JEVisType readoutType = channelClass.getType(DataCollectorTypes.Channel.FTPChannel.LAST_READOUT); DateTime lastReadout = DatabaseHelper.getObjectAsDate(channel, readoutType, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")); // String filePath = dp.getFilePath(); org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL, "SendSampleRequest2"); List<String> fileNames = DataSourceHelper.getFTPMatchedFileNames(_fc, lastReadout, filePath); // String currentFilePath = Paths.get(filePath).getParent().toString(); org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL, "Nr of Matched Files " + fileNames.size()); for (String fileName : fileNames) { org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL, "FileInputName: " + fileName); ByteArrayOutputStream out = new ByteArrayOutputStream(); // String query = Paths.get(fileName); org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL, "FTPQuery " + fileName); boolean retrieveFile = _fc.retrieveFile(fileName, out); org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ALL, "Request status: " + retrieveFile); InputStream inputStream = new ByteArrayInputStream(out.toByteArray()); answer = new BufferedInputStream(inputStream); // InputHandler inputConverter = InputHandlerFactory.getInputConverter(answer); // inputConverter.setFilePath(fileName); answerList.add(answer); } } catch (JEVisException ex) { java.util.logging.Logger.getLogger(FTPDataSource.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FTPDataSource.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { System.out.println(ex.getMessage()); } if (answerList.isEmpty()) { org.apache.log4j.Logger.getLogger(this.getClass().getName()).log(org.apache.log4j.Level.ERROR, "Cant get any data from the device"); } return answerList; }
From source file:org.jnode.protocol.ftp.FTPURLConnection.java
/** * @see java.net.URLConnection#getInputStream() *//*from w w w. j a va2s .c o m*/ 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()); }
From source file:org.jtheque.films.services.impl.utils.file.FTPManager.java
/** * Construct a new FTP Manager./*from ww w . ja va 2 s . c o m*/ * * @param infos The connection infos. */ public FTPManager(FTPConnectionInfos infos) { super(); this.infos = infos; ftp = new FTPClient(); }
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 ww . j a v a 2s .c o 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.kuali.kfs.module.cg.service.impl.CfdaServiceImpl.java
/** * @return//from w w w. ja va 2 s.c o 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// www . j a va2 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; }