List of usage examples for org.apache.commons.net.ftp FTPClient connect
public void connect(InetAddress host) throws SocketException, IOException
From source file:no.imr.sea2data.stox.InstallerUtil.java
public static Boolean retrieveFromFTP(String ftpPath, String outFile, FTPFileFilter filter) { try {/*from ww w . j a v a 2 s .com*/ FTPClient ftpClient = new FTPClient(); // pass directory path on server to connect if (ftpPath == null) { return false; } ftpPath = ftpPath.replace("ftp://", ""); String[] s = ftpPath.split("/", 2); if (s.length != 2) { return false; } String server = s[0]; String subPath = s[1]; ftpClient.setConnectTimeout(5000); ftpClient.connect(server); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); if (!ftpClient.login("anonymous", "")) { return false; } ftpClient.enterLocalPassiveMode(); // bug : mac doesnt allow ftp server connect through through local firewall - thus use passive server try (FileOutputStream fos = new FileOutputStream(outFile)) { try { String path = subPath + "/"; FTPFile[] files = ftpClient.listFiles(path, filter); Optional<FTPFile> opt = Arrays.stream(files) .sorted((f1, f2) -> Integer.compare(f1.getName().length(), f2.getName().length())) .findFirst(); if (opt.isPresent()) { ftpClient.retrieveFile(path + opt.get().getName(), fos); } } finally { ftpClient.logout(); ftpClient.disconnect(); } } return true; } catch (IOException ex) { throw new UncheckedIOException(ex); } }
From source file:no.imr.sea2data.stox.InstallerUtil.java
public static boolean retrieveReferenceFromFTP() { FTPClient ftpClient = new FTPClient(); try {/*from w ww . j av a2 s . c om*/ // pass directory path on server to connect ftpClient.connect("ftp.imr.no"); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // successful if (!ftpClient.login("anonymous", "")) { return false; } ftpClient.enterLocalPassiveMode(); FTPUtil.retrieveDir(ftpClient, FTP_STOXDOWNLOAD_REFERENCE, ProjectUtils.getSystemReferenceFolder()); } catch (Exception e) { return false; } finally { try { ftpClient.disconnect(); } catch (IOException e) { } } return true; }
From source file:nz.co.jsrsolutions.ds3.provider.CMEEodDataProvider.java
public CMEEodDataProvider(String hostname, String basePath, CMEEodDataProviderExchangeDescriptor[] descriptors) throws EodDataProviderException { _hostname = hostname;/* www .j ava2 s .com*/ _basePath = basePath; _descriptors = descriptors; FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config); boolean error = false; try { int reply; ftp.connect(_hostname); _logger.info("Connected to " + _hostname); _logger.info(ftp.getReplyString()); // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); _logger.error("FTP server refused connection."); throw new EodDataProviderException("FTP server refused connection."); } boolean result = ftp.login("anonymous", "jsr@argusat.com"); result = ftp.changeWorkingDirectory(_basePath); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); _logger.error(reply); throw new EodDataProviderException("Failed to cd into " + _basePath); } for (CMEEodDataProviderExchangeDescriptor descriptor : _descriptors) { OutputStream output = new ByteArrayOutputStream(); String modificationTime = ftp.getModificationTime(descriptor.getFilename()); // 213 20131202235804\r\n result = ftp.retrieveFile(descriptor.getFilename(), output); output.close(); } ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } }
From source file:org.abstracthorizon.proximity.storage.remote.CommonsNetFtpRemotePeer.java
/** * Gets the FTP client.// w w w . ja v a2s . c om * * @return the FTP client */ public FTPClient getFTPClient() { try { logger.info("Creating CommonsNetFTPClient instance"); FTPClient ftpc = new FTPClient(); ftpc.configure(ftpClientConfig); ftpc.connect(getRemoteUrl().getHost()); ftpc.login(getFtpUsername(), getFtpPassword()); ftpc.setFileType(FTPClient.BINARY_FILE_TYPE); return ftpc; } catch (SocketException ex) { throw new StorageException("Got SocketException while creating FTPClient", ex); } catch (IOException ex) { throw new StorageException("Got IOException while creating FTPClient", ex); } }
From source file:org.alinous.ftp.FtpManager.java
public void connect(String sessionId, String connectUrl, int proxyPort, String username, String password) throws SocketException, IOException { FtpClientHolder holder = new FtpClientHolder(); this.instances.put(sessionId, holder); FTPClient ftp = holder.createHttpFtp(connectUrl, proxyPort, username, password); ftp.connect(connectUrl); }
From source file:org.amanzi.neo.geoptima.loader.ui.page.impl.SelectFtpDataPage.java
/** * *//*from www . j a v a 2 s. c om*/ private void connectToFtp() { try { if (getConfiguration().getFtpClient() != null) { getConfiguration().getFtpClient().disconnect(); } FTPClient client = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); client.configure(config); client.connect(getUrl()); client.login(userNameWidget.getText(), passwordWidget.getText()); viewer.initialize(client); getConfiguration().setFtpClient(client); } catch (IOException e) { LOGGER.error("can't connect to server", e); } }
From source file:org.apache.hive.hplsql.Ftp.java
/** * Open and initialize FTP//from w ww.j a v a2s . c o m */ FTPClient openConnection(HplsqlParser.Copy_from_ftp_stmtContext ctx) { FTPClient ftp = new FTPClient(); Timer timer = new Timer(); timer.start(); try { ftp.connect(host); ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.login(user, pwd)) { if (ftp.isConnected()) { ftp.disconnect(); } exec.signal(Signal.Type.SQLEXCEPTION, "Cannot login to FTP server: " + host); return null; } timer.stop(); if (info) { info(ctx, "Connected to ftp: " + host + " (" + timer.format() + ")"); } } catch (IOException e) { exec.signal(e); } return ftp; }
From source file:org.apache.nifi.processors.standard.util.FTPUtils.java
/** * Creates a new FTPClient connected to an FTP server. The following properties must exist: * <ul>Required Properties:/* w ww . j a v a 2 s. c om*/ * <li>remote.host - The hostname or IP address of the FTP server to connect to</li> * <li>remote.user - The username of the account to authenticate with</li> * <li>remote.password = The password for the username to authenticate with</li> * </ul> * <ul>Optional Properties: * <li>remote.port - The port on the FTP server to connect to. Defaults to FTP default.</li> * <li>transfer.mode - The type of transfer for this connection ('ascii', 'binary'). Defaults to 'binary'</li> * <li>connection.mode - The type of FTP connection to make ('active_local', 'passive_local'). Defaults to 'active_local'. In active_local the server initiates 'data connections' to the client * where in passive_local the client initiates 'data connections' to the server.</li> * <li>network.data.timeout - Default is 0. Sets the timeout in milliseconds for waiting to establish a new 'data connection' (not a control connection) when in ACTIVE_LOCAL mode. Also, this * establishes the amount of time to wait on read calls on the data connection in either mode. A value of zero means do not timeout. Users should probably set a value here unless using very * reliable communications links or else risk indefinite hangs that require a restart.</li> * <li>network.socket.timeout - Default is 0. Sets the timeout in milliseconds to use when creating a new control channel socket and also a timeout to set when reading from a control socket. A * value of zero means do not timeout. Users should probably set a value here unless using very reliable communications links or else risk indefinite hangs that require a restart.</li> * </ul> * * @param conf conf * @param monitor if provided will be used to monitor FTP commands processed but may be null * @return FTPClient connected to FTP server as configured * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if a required property is missing * @throws NumberFormatException if any argument that must be an int cannot be converted to int * @throws IOException if some problem occurs connecting to FTP server */ public static FTPClient connect(final FTPConfiguration conf, final ProtocolCommandListener monitor) throws IOException { if (null == conf) { throw new NullPointerException(); } final String portVal = conf.port; final int portNum = (null == portVal) ? -1 : Integer.parseInt(portVal); final String connectionModeVal = conf.connectionMode; final String connectionMode = (null == connectionModeVal) ? ACTIVE_LOCAL_CONNECTION_MODE : connectionModeVal; final String transferModeVal = conf.transferMode; final String transferMode = (null == transferModeVal) ? BINARY_TRANSFER_MODE : transferModeVal; final String networkDataTimeoutVal = conf.dataTimeout; final int networkDataTimeout = (null == networkDataTimeoutVal) ? 0 : Integer.parseInt(networkDataTimeoutVal); final String networkSocketTimeoutVal = conf.connectionTimeout; final int networkSocketTimeout = (null == networkSocketTimeoutVal) ? 0 : Integer.parseInt(networkSocketTimeoutVal); final FTPClient client = new FTPClient(); if (networkDataTimeout > 0) { client.setDataTimeout(networkDataTimeout); } if (networkSocketTimeout > 0) { client.setDefaultTimeout(networkSocketTimeout); } client.setRemoteVerificationEnabled(false); if (null != monitor) { client.addProtocolCommandListener(monitor); } InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(conf.remoteHostname, null); } catch (final UnknownHostException uhe) { } if (inetAddress == null) { inetAddress = InetAddress.getByName(conf.remoteHostname); } if (portNum < 0) { client.connect(inetAddress); } else { client.connect(inetAddress, portNum); } if (networkDataTimeout > 0) { client.setDataTimeout(networkDataTimeout); } if (networkSocketTimeout > 0) { client.setSoTimeout(networkSocketTimeout); } final boolean loggedIn = client.login(conf.username, conf.password); if (!loggedIn) { throw new IOException("Could not login for user '" + conf.username + "'"); } if (connectionMode.equals(ACTIVE_LOCAL_CONNECTION_MODE)) { client.enterLocalActiveMode(); } else if (connectionMode.equals(PASSIVE_LOCAL_CONNECTION_MODE)) { client.enterLocalPassiveMode(); } boolean transferModeSet = false; if (transferMode.equals(ASCII_TRANSFER_MODE)) { transferModeSet = client.setFileType(FTPClient.ASCII_FILE_TYPE); } else { transferModeSet = client.setFileType(FTPClient.BINARY_FILE_TYPE); } if (!transferModeSet) { throw new IOException("Unable to set transfer mode to type " + transferMode); } return client; }
From source file:org.apache.ofbiz.common.FtpServices.java
public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); Debug.logInfo("[putFile] starting...", module); InputStream localFile = null; try {//from www .ja v a 2s.co m localFile = new FileInputStream((String) context.get("localFilename")); } catch (IOException ioe) { Debug.logError(ioe, "[putFile] Problem opening local file", module); return ServiceUtil .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale)); } List<String> errorList = new LinkedList<String>(); FTPClient ftp = new FTPClient(); try { Integer defaultTimeout = (Integer) context.get("defaultTimeout"); if (UtilValidate.isNotEmpty(defaultTimeout)) { Debug.logInfo("[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module); ftp.setDefaultTimeout(defaultTimeout.intValue()); } Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module); ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { Debug.logInfo("[putFile] Server refused connection", module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale)); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module); if (!ftp.login(username, password)) { Debug.logInfo("[putFile] login failed", module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure", UtilMisc.toMap("username", username, "password", password), locale)); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"), module); if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) { Debug.logInfo("[putFile] store was unsuccessful", module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale)); } else { Debug.logInfo("[putFile] store was successful", module); List<String> siteCommands = checkList(context.get("siteCommands"), String.class); if (siteCommands != null) { for (String command : siteCommands) { Debug.logInfo("[putFile] sending SITE command: " + command, module); if (!ftp.sendSiteCommand(command)) { errorList.add(UtilProperties.getMessage(resource, "CommonFtpSiteCommandFailed", UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()), locale)); } } } } } ftp.logout(); } } catch (IOException ioe) { Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } finally { try { if (ftp.isConnected()) { ftp.disconnect(); } } catch (Exception e) { Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module); } try { localFile.close(); } catch (Exception e) { Debug.logWarning(e, "[putFile] Problem closing local file: ", module); } } if (errorList.size() > 0) { Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } Debug.logInfo("[putFile] finished successfully", module); return ServiceUtil.returnSuccess(); }
From source file:org.apache.ofbiz.common.FtpServices.java
public static Map<String, Object> getFile(DispatchContext dctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); String localFilename = (String) context.get("localFilename"); OutputStream localFile = null; try {/*from w w w. ja va 2 s. c o m*/ localFile = new FileOutputStream(localFilename); } catch (IOException ioe) { Debug.logError(ioe, "[getFile] Problem opening local file", module); return ServiceUtil .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale)); } List<String> errorList = new LinkedList<String>(); FTPClient ftp = new FTPClient(); try { Integer defaultTimeout = (Integer) context.get("defaultTimeout"); if (UtilValidate.isNotEmpty(defaultTimeout)) { Debug.logInfo("[getFile] Set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module); ftp.setDefaultTimeout(defaultTimeout.intValue()); } ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale)); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); if (!ftp.login(username, password)) { errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure", UtilMisc.toMap("username", username, "password", password), locale)); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) { errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale)); } } ftp.logout(); } } catch (IOException ioe) { Debug.logWarning(ioe, "[getFile] caught exception: " + ioe.getMessage(), module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } finally { try { if (ftp.isConnected()) { ftp.disconnect(); } } catch (Exception e) { Debug.logWarning(e, "[getFile] Problem with FTP disconnect: ", module); } try { localFile.close(); } catch (Exception e) { Debug.logWarning(e, "[getFile] Problem closing local file: ", module); } } if (errorList.size() > 0) { Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } return ServiceUtil.returnSuccess(); }