List of usage examples for org.apache.commons.net.ftp FTPClient connect
public void connect(InetAddress host) throws SocketException, IOException
From source file:com.cladonia.xngreditor.URLUtilities.java
public static InputStream open(URL url) throws IOException { // System.out.println( "URLUtilities.open( "+url+")"); InputStream stream = null;// w w w .jav a 2s. c om String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) { try { DefaultAuthenticator authenticator = Main.getDefaultAuthenticator(); URL newURL = new URL(URLUtilities.toString(url)); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication( new PasswordAuthentication(username, password.toCharArray())); } stream = newURL.openStream(); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication(null); } } catch (Exception e) { // System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage()); // try it with webdav WebdavResource webdav = createWebdavResource(toString(url), username, password); stream = webdav.getMethodData(toString(url)); webdav.close(); } } else if (protocol.equals("ftp")) { FTPClient client = null; String host = url.getHost(); try { // System.out.println( "Connecting to: "+host+" ..."); client = new FTPClient(); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Could not connect."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in using: "+username+", "+password+" ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Opening file \""+url.getFile()+"\" ..."); stream = client.retrieveFileStream(url.getFile()); // System.out.println( "File opened."); // System.out.println( "Disconnecting ..."); client.disconnect(); // System.out.println( "Disconnected."); } catch (IOException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException f) { // do nothing e.printStackTrace(); } } throw new IOException("Could not connect to FTP Server \"" + host + "\"."); } } else if (protocol.equals("file")) { stream = url.openStream(); } else { //unknown protocol but try anyways try { stream = url.openStream(); } catch (IOException ioe) { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } } return stream; }
From source file:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java
public void conectarFTP(Archivo archivo) { FTPClient client = new FTPClient(); /*String sFTP = "127.0.0.1"; String sUser = "tae";/*from w w w. j av a 2 s. c o m*/ String sPassword = "tae";*/ String sFTP = buscarParametros(FTP_SERVER); String sUser = buscarParametros(FTP_USER); String sPassword = buscarParametros(FTP_PASSWORD); /////////////////////////////////// //String[] lista; try { client.connect(sFTP); boolean login = client.login(sUser, sPassword); System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory()); client.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = null; buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre())); client.enterLocalPassiveMode(); StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta. int i = 0; String nombre = ""; while (tokens.hasMoreTokens()) { if (i == 1) { nombre = tokens.nextToken(); i++; } else { i++; } } client.storeFile(nombre, buffIn); buffIn.close(); /*lista = client.listNames(); for (String lista1 : lista) { System.out.println(lista1); }*/ //client.changeWorkingDirectory("\\done"); //System.out.println("2. Working Directory: " + client.printWorkingDirectory()); client.logout(); client.disconnect(); System.out.println("Termin de conectarme al FTP!!"); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java
public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName, String originalFileName) { if (logger.isDebugEnabled()) { logger.debug("SampleUploadCluster.process called"); }//www . j a v a 2 s . c o m FTPClient ftp = new FTPClient(); OutputStream out = null; File file = new File(sourceRepositoryPath + "/" + maskingFileName); FileInputStream fin = null; BufferedInputStream bin = null; String storeFileName = null; String server = "?IP";//?? ? . ex) 210.25.3.21 try { ftp.connect(server); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); storeFileName = maskingFileName + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()); fin = new FileInputStream(file); bin = new BufferedInputStream(fin); ftp.login("testId", "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length())); if (logger.isDebugEnabled()) { logger.debug(server + " connect success !!! "); } ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/"); out = ftp.storeFileStream(storeFileName); FileCopyUtils.copy(fin, out); if (logger.isDebugEnabled()) { logger.debug(" cluster success !!! "); } } else { ftp.disconnect(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); if (bin != null) bin.close(); ftp.logout(); out = null; bin = null; } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:net.siegmar.japtproxy.fetcher.FetcherFtp.java
/** * {@inheritDoc}//w ww . j a v a 2 s. com */ @Override public FetchedResourceFtp fetch(final URL targetResource, final long lastModified, final String originalUserAgent) throws IOException, ResourceUnavailableException { final FTPClient ftpClient = new FTPClient(); ftpClient.setSoTimeout(socketTimeout); ftpClient.setDataTimeout(dataTimeout); try { final String host = targetResource.getHost(); final String resourceName = targetResource.getPath(); LOG.debug("Configured FetcherFtp: Host '{}', Resource '{}'", host, resourceName); ftpClient.connect(host); ftpClient.enterLocalPassiveMode(); if (!ftpClient.login("anonymous", "japt-proxy")) { throw new IOException("Can't login to FTP server"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); final FTPFile[] files = ftpClient.listFiles(resourceName); if (files.length == 0) { throw new ResourceUnavailableException("Resource '" + resourceName + "' not found"); } if (files.length > 1) { throw new IOException("Multiple files found"); } final FTPFile file = files[0]; final FetchedResourceFtp fetchedResourceFtp = new FetchedResourceFtp(ftpClient, file); fetchedResourceFtp .setModified(lastModified == 0 || lastModified < file.getTimestamp().getTimeInMillis()); return fetchedResourceFtp; } catch (final IOException e) { // Closing only in case of an exception - otherwise closed by FetchedResourceFtp if (ftpClient.isConnected()) { ftpClient.disconnect(); } throw e; } }
From source file:adams.gui.chooser.FtpRemoteDirectorySetup.java
/** * Returns a new client for the host/port defined in the options. * * @return the client//w w w.j a v a 2s. com */ public FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:adams.core.io.lister.FtpDirectoryLister.java
/** * Returns a new client for the host defined in the options. * * @return the client, null if failed to create *//*w ww . j a v a 2 s . c om*/ protected FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient ftp = null; try {/*from w w w .j a v a2s. co m*/ ftp = new FTPClient(); // For debug // f.addProtocolCommandListener(new PrintCommandListener( // new PrintWriter(System.out))); ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(fpi.getHost()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); ftp.login(fpi.getUsername(), fpi.getPassword()); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); if (fpi.isFtpUsePassiveMode()) ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); FTPClient ftpReturn = ftp; ftp = null; return ftpReturn; } finally { if (ftp != null) ftpQuietDisconnect(ftp); } }
From source file:com.wheelermarine.android.publicAccesses.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {//from w ww . j a v a 2s .c om final DatabaseHelper db = new DatabaseHelper(context); SQLiteDatabase database = db.getWritableDatabase(); if (database == null) throw new IllegalStateException("Unable to open database!"); database.beginTransaction(); try { // Clear out the old data. database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null); // Connect to the web server and locate the FTP download link. Log.v(TAG, "Finding update: " + urls[0]); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Locating update..."); progress.setIndeterminate(true); } }); Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get(); URL dataURL = null; for (Element element : doc.select("a")) { if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) { dataURL = new URL(element.attr("href")); } } // Make sure the download URL was fund. if (dataURL == null) throw new FileNotFoundException("Unable to locate data URL."); // Connect to the FTP server and download the update. Log.v(TAG, "Downloading update: " + dataURL); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Downloading update..."); progress.setIndeterminate(true); } }); FTPClient ftp = new FTPClient(); try { ftp.setConnectTimeout(timeout * 1000); ftp.setDefaultTimeout(timeout * 1000); ftp.connect(dataURL.getHost()); ftp.enterLocalPassiveMode(); // After connection attempt, you should check the reply code // to verify success. if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); throw new IOException("FTP server refused connection: " + ftp.getReplyString()); } // Login using the standard anonymous credentials. if (!ftp.login("anonymous", "anonymous")) { ftp.disconnect(); throw new IOException("FTP Error: " + ftp.getReplyString()); } Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); ftp.setFileType(FTP.BINARY_FILE_TYPE); InputStream in = ftp.retrieveFileStream(dataURL.getFile()); if (in == null) throw new FileNotFoundException(dataURL.getFile() + " was not found!"); try { ZipInputStream zin = new ZipInputStream(in); try { // Locate the .dbf entry in the ZIP archive. ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().endsWith(entryName)) { readDBaseFile(zin, database); } else if (entry.getName().endsWith(shapeEntryName)) { locations = readShapeFile(zin); } } } finally { try { zin.close(); } catch (Exception e) { // Ignore this error. } } } finally { in.close(); } if (locations != null) { final int recordCount = locations.size(); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setIndeterminate(false); progress.setMessage("Updating locations..."); progress.setMax(recordCount); } }); int progress = 0; for (int recordNumber : locations.keySet()) { PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber); Location loc = locations.get(recordNumber); access.setLatitude(loc.getLatitude()); access.setLongitude(loc.getLongitude()); db.updatePublicAccess(access); publishProgress(++progress); } } } finally { if (ftp.isConnected()) ftp.disconnect(); } database.setTransactionSuccessful(); return db.getPublicAccessesCount(); } finally { database.endTransaction(); } } catch (Exception e) { error = e; Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e); return -1; } }
From source file:com.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java
private void checkConnect(FTPClient ftp, String server, String login, String password) throws IOException { try {//from www . jav a 2 s .co m if (ftp.isConnected()) if (ftp.sendNoOp()) return; } catch (FTPConnectionClosedException e) { Logging.warn(e); } ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(server); ftp.login(login, password); }
From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java
public void fetch(final FtpSubscription ftpSubscription) { if (_log.isDebugEnabled()) { _log.debug("fetching " + ftpSubscription); }/* w w w . ja v a 2 s . com*/ final FTPClient ftp = new FTPClient(); ftp.setControlKeepAliveTimeout(30); ftp.setControlKeepAliveReplyTimeout(30); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; ftp.connect(ftpSubscription.getFtpHost()); _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (final IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } boolean error = false; __main: try { if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) { ftp.logout(); error = true; break __main; } _log.info("Remote system is " + ftp.getSystemType()); ftp.setFileType(FTP.BINARY_FILE_TYPE); //ftp.enterLocalActiveMode(); ftp.enterLocalPassiveMode(); //final FTPClientConfig config = new FTPClientConfig(); ////config.setLenientFutureDates(true); //ftp.configure(config); if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) { ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder()); } final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile()); if (is == null) { _log.error("FIle not found: " + ftp.getSystemType()); } else { unzip(ftpSubscription, is); is.close(); } ftp.completePendingCommand(); } catch (final FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (final IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException e) { _log.error(e); } } } }