List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:org.glassfish.common.util.admin.MapInjectionResolver.java
private void FormatUriToFile() throws IOException { List<String> value = parameters.get("DEFAULT"); String uri = value.get(0);//from w w w .jav a2 s . c o m URL url = new URL(uri); File file = null; if (uri.startsWith("file:/")) { file = new File(url.getFile()); } else if (uri.startsWith("http://")) { InputStream inStream = url.openStream(); BufferedInputStream bufIn = new BufferedInputStream(inStream); file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/"))); if (file.exists()) { file.delete(); } OutputStream out = new FileOutputStream(file); BufferedOutputStream bufOut = new BufferedOutputStream(out); byte buffer[] = new byte[204800]; while (true) { int nRead = bufIn.read(buffer, 0, buffer.length); if (nRead <= 0) break; bufOut.write(buffer, 0, nRead); } bufOut.flush(); out.close(); inStream.close(); } else if (uri.startsWith("ftp://")) { String pattern = "^ftp://(.+?)(:.+?)?@(\\S+):(\\d+)(\\S+)$"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(uri); if (m.matches()) { String username = m.group(1); String password = ""; if (m.group(2) != null) { password = m.group(2).replace(":", ""); } String ipAddress = m.group(3); String port = m.group(4); String path = m.group(5); FTPClient ftp = new FTPClient(); ftp.connect(ipAddress); ftp.setDefaultPort(Integer.parseInt(port)); boolean isLogin = ftp.login(username, password); if (isLogin) { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); byte[] buf = new byte[204800]; int bufsize = 0; file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/"))); if (file.exists()) { file.delete(); } OutputStream ftpOut = new FileOutputStream(file); InputStream ftpIn = ftp.retrieveFileStream(path); System.out.println(ftpIn); while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) { ftpOut.write(buf, 0, bufsize); } ftpOut.flush(); ftpOut.close(); ftpIn.close(); } else { ftp.logout(); ftp.disconnect(); } } else { localStrings.getLocalString("IncorrectFtpAddress", "The ftp address is not correct, please change another one."); } } if (file != null) parameters.set("DEFAULT", file.getAbsolutePath()); }
From source file:org.gogpsproject.parser.rinex.RinexNavigation.java
private RinexNavigationParser getFromFTP(String url) throws IOException { RinexNavigationParser rnp = null;/*from w ww. j a v a 2 s. co m*/ String origurl = url; if (negativeChache.containsKey(url)) { if (System.currentTimeMillis() - negativeChache.get(url).getTime() < 60 * 60 * 1000) { throw new FileNotFoundException("cached answer"); } else { negativeChache.remove(url); } } String filename = url.replaceAll("[ ,/:]", "_"); if (filename.endsWith(".Z")) filename = filename.substring(0, filename.length() - 2); File rnf = new File(RNP_CACHE, filename); if (!rnf.exists()) { System.out.println(url + " from the net."); FTPClient ftp = new FTPClient(); try { int reply; System.out.println("URL: " + url); url = url.substring("ftp://".length()); String server = url.substring(0, url.indexOf('/')); String remoteFile = url.substring(url.indexOf('/')); String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/')); remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1); ftp.connect(server); ftp.login("anonymous", "info@eriadne.org"); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return null; } System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath)); System.out.println(ftp.getReplyString()); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println(ftp.getReplyString()); System.out.println("open " + remoteFile); InputStream is = ftp.retrieveFileStream(remoteFile); InputStream uis = is; System.out.println(ftp.getReplyString()); if (ftp.getReplyString().startsWith("550")) { negativeChache.put(origurl, new Date()); throw new FileNotFoundException(); } if (remoteFile.endsWith(".Z")) { uis = new UncompressInputStream(is); } rnp = new RinexNavigationParser(uis, rnf); rnp.init(); is.close(); ftp.completePendingCommand(); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } } else { System.out.println(url + " from cache file " + rnf); rnp = new RinexNavigationParser(rnf); rnp.init(); } return rnp; }
From source file:org.gogpsproject.parser.sp3.SP3Navigation.java
private SP3Parser getFromFTP(String url) throws IOException { SP3Parser sp3p = null;/* w w w. j ava 2 s .c o m*/ String filename = url.replaceAll("[ ,/:]", "_"); if (filename.endsWith(".Z")) filename = filename.substring(0, filename.length() - 2); File sp3f = new File(SP3_CACHE, filename); if (!sp3f.exists()) { System.out.println(url + " from the net."); FTPClient ftp = new FTPClient(); try { int reply; System.out.println("URL: " + url); url = url.substring("ftp://".length()); String server = url.substring(0, url.indexOf('/')); String remoteFile = url.substring(url.indexOf('/')); String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/')); remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1); ftp.connect(server); ftp.login("anonymous", "info@eriadne.org"); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return null; } System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath)); System.out.println(ftp.getReplyString()); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println(ftp.getReplyString()); System.out.println("open " + remoteFile); InputStream is = ftp.retrieveFileStream(remoteFile); InputStream uis = is; System.out.println(ftp.getReplyString()); if (ftp.getReplyString().startsWith("550")) { throw new FileNotFoundException(); } if (remoteFile.endsWith(".Z")) { uis = new UncompressInputStream(is); } sp3p = new SP3Parser(uis, sp3f); sp3p.init(); is.close(); ftp.completePendingCommand(); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } } else { System.out.println(url + " from cache file " + sp3f); sp3p = new SP3Parser(sp3f); sp3p.init(); } return sp3p; }
From source file:org.grouter.core.readers.FtpReaderJob.java
/** * Use configuration parameters to create a connection to the ftp endpoint. * @return a FTPClient instance/*from w ww . j a va 2 s. c o m*/ * @throws Exception if connection problems */ private FTPClient initConnection() throws Exception { FTPClient client; String host = null; String strPort; try { Map map = node.getInBound().getEndPointContext(); host = node.getInBound().getUri(); strPort = (String) map.get(FTP_PORT); client = new FTPClient(); int port = FTP_DEFAULT_PORT; if (StringUtils.isNotEmpty(strPort)) { port = Integer.parseInt(strPort); client.connect(host, port); int reply = client.getReplyCode(); logger.debug("reply :" + reply); if (FTPReply.isPositiveCompletion(reply)) { logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress()); } } else { client.connect(host, port); int reply = client.getReplyCode(); logger.debug("reply :" + reply); if (FTPReply.isPositiveCompletion(reply)) { logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress()); } } String user = (String) map.get(FTP_AUTH_USER); String pwd = (String) map.get(FTP_AUTH_PASSWORD); if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(pwd)) { client.login(user, pwd); int replyCode = client.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { logger.info("Logged into ftp server :" + host); } } else { client.login("anonymous", "mymail@mail.com"); int replyCode = client.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { logger.info("Logged into ftp server :" + host); } } } catch (Exception e) { throw new Exception("Could not establish connection with ftp endpoint using host:" + host, e); } return client; }
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 {/* ww w . j a v a2s. 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() *//*from w w w . j a v a 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.jnode.protocol.ftp.FTPURLConnection.java
/** * @see java.net.URLConnection#getInputStream() *//* w ww .ja 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.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. ja v a2s. 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.kuali.kfs.module.cg.service.impl.CfdaServiceImpl.java
/** * @return/* w w w . j a va2 s. c om*/ * @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//ww w .j a v a2 s . co m * @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; }