List of usage examples for org.apache.commons.net.ftp FTPClient retrieveFile
public boolean retrieveFile(String remote, OutputStream local) throws IOException
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; }/*www .j ava 2 s . co m*/ // 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;// w w w. ja v a2s .c om // 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.openconcerto.ftp.FTPUtils.java
static public final void saveR(FTPClient ftp, File local) throws IOException { local.mkdirs();/*from w ww . ja v a 2 s. co m*/ for (FTPFile child : ftp.listFiles()) { final String childName = child.getName(); if (childName.indexOf('.') != 0) { if (child.isDirectory()) { ftp.changeWorkingDirectory(childName); saveR(ftp, new File(local, childName)); ftp.changeToParentDirectory(); } else { final OutputStream outs = new FileOutputStream(new File(local, childName)); ftp.retrieveFile(childName, outs); outs.close(); } } } }
From source file:org.openspice.vfs.ftp.FtpVFile.java
public InputStream inputStreamContents() { if (Print.wouldPrint(Print.VFS)) { Print.println("Trying to read contents of file " + this.path); Print.println("path = " + this.path); }/*w ww . j ava 2s . co m*/ final FTPClient ftpc = this.fvol.getConnectedFTPClient(); Print.println(Print.VFS, "Connected .... "); try { final ByteArrayOutputStream output = new ByteArrayOutputStream(); if (ftpc.retrieveFile(this.path, output)) { final String s = new String(output.toByteArray()); if (Print.wouldPrint(Print.VFS)) { Print.println("Got file: " + s.length()); } if (s.length() < 100) { if (Print.wouldPrint(Print.VFS)) Print.println("s = " + s); } return new ByteArrayInputStream(output.toByteArray()); } else { if (Print.wouldPrint(Print.VFS)) Print.println("reply code = " + ftpc.getReplyCode()); throw new Alert("Cannot retrieve file from FTP server").culprit("file", this.path).mishap(); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java
private String downloadSingleFile(FTPClient ftpClient, String remoteFilePath, String savePath) throws IOException { getOut().println("About to DOWNLOAD the file: " + remoteFilePath); File downloadFile = new File(savePath); File parentDir = downloadFile.getParentFile(); if (parentDir != null && !parentDir.exists()) { parentDir.mkdirs();/*from w w w . ja va 2 s . c om*/ } try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile))) { //retrieve a single file from the FTP server ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (ftpClient.retrieveFile(remoteFilePath, outputStream)) { getOut().println( "DOWNLOADED successfully the file " + remoteFilePath + " to " + ftpLocalRelativePath); return savePath; } else { throw new IOException("Error: COULD NOT download the file: " + ftpRemoteRelativePath); } } }
From source file:org.programmatori.domotica.own.plugin.remote.FTPUtility.java
/** * Funzione che consente di leggere un file sul sito FTP remoto * //from w w w .j a v a2s .com * @param ftp Oggetto di tipo FTPClient da usare per il recupero del file * @param name Nome del file da recuperare dal server Remoto * @param output Flusso di tipo OutputStream, su cui salvare il file * @return >=0 in caso tutto vada bene; <0 in caso di errori */ public static int getFile(FTPClient ftp, String name, OutputStream output) { try { ftp.retrieveFile(name, output); } catch (IOException e) { e.printStackTrace(); return -1; } return 0; }
From source file:org.ramadda.repository.type.FtpTypeHandler.java
/** * _more_//from w ww .j a va 2 s . c om * * @param entry _more_ * * @return _more_ */ public File getFileForEntry(Entry entry) { try { File badFile = new File("badfile"); Entry parent = getMainEntry(entry.getId()); if (parent == null) { System.err.println("Could not find main entry"); return badFile; } Object[] values = parent.getValues(); if (values == null) { System.err.println("FtpTypeHandler: no values"); return badFile; } double maxSize = 0; if (values[COL_MAXSIZE] != null) { maxSize = ((Double) values[COL_MAXSIZE]).doubleValue(); } String server = (String) values[COL_SERVER]; if (entry.getResource().getFileSize() > 1000000 * maxSize) { // System.err.println("FtpTypeHandler: Bad size " // + entry.getResource().getFileSize()+" " + // entry.getResource()); return badFile; } FTPClient ftpClient = null; try { String[] pair = getEntryManager().getSynthId(entry.getId()); MyFTPFile myFtpFile = getFileFromId(parent, pair[1], (String) values[COL_BASEDIR]); ftpClient = getFtpClient(parent); if (ftpClient == null) { System.err.println("no ftp client "); return badFile; } // String path = entry.getResource().getPath(); String path = myFtpFile.path; String prefix = "ftp://" + server; if (path.startsWith(prefix)) { path = path.substring(prefix.length()); } String cacheFileName = java.net.URLEncoder.encode("ftp:" + values[COL_SERVER] + ":" + path, "UTF-8"); File cacheFile = getStorageManager().getCacheFile(cacheFileName); if (cacheFile.exists()) { return cacheFile; } // System.err.println("Fetching:" + path); // System.err.println("writing to:" + cacheFile); OutputStream fos = getStorageManager().getUncheckedFileOutputStream(cacheFile); if (ftpClient.retrieveFile(path, fos)) { fos.flush(); fos.close(); return cacheFile; } // System.err.println ("BAD FILE"); return badFile; } finally { if (ftpClient != null) { closeConnection(ftpClient); } } } catch (Exception exc) { throw new RuntimeException(exc); } }
From source file:org.ramadda.repository.type.FtpTypeHandler.java
/** * _more_//from ww w . j av a 2s .c o m * * @param server _more_ * @param baseDir _more_ * @param user _more_ * @param password _more_ * * @return _more_ * * @throws Exception _more_ */ public static String test(String server, String baseDir, String user, String password) throws Exception { FTPClient ftpClient = new FTPClient(); try { String file = baseDir; ftpClient.connect(server); //System.out.print(ftp.getReplyString()); ftpClient.login(user, password); // System.out.print(ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); boolean isDir = isDir(ftpClient, file); // System.err.println("file:" + file + " is dir: " + isDir); if (isDir) { FTPFile[] files = ftpClient.listFiles(file); for (int i = 0; i < files.length; i++) { // System.err.println ("f:" + files[i].getName() + " " + files[i].isDirectory() + " " + files[i].isFile()); } } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ftpClient.retrieveFile(file, bos)) { // System.err.println(new String(bos.toByteArray())); } else { throw new IOException("Unable to retrieve file:" + file); } } return ""; } finally { closeConnection(ftpClient); } }
From source file:org.ramadda.util.Utils.java
/** * _more_//w w w.j a va 2s . c o m * * @param url _more_ * @param os _more_ * * @return _more_ * * @throws Exception _more_ */ public static boolean writeFile(URL url, OutputStream os) throws Exception { if (url.getProtocol().equals("ftp")) { FTPClient ftpClient = null; try { ftpClient = Utils.makeFTPClient(url); if (ftpClient == null) { return false; } if (ftpClient.retrieveFile(url.getPath(), os)) { return true; } return false; } finally { closeConnection(ftpClient); } } else { InputStream is = IOUtil.getInputStream(url.toString(), Utils.class); IOUtil.writeTo(is, os); return true; } }
From source file:org.shept.util.FtpFileCopy.java
/** * Compare the source path and the destination path for filenames with the filePattern * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the * destination or if they have changed (by modifactionDate). * Copying is done through a retrieve operation. * /*from w ww . j av a 2s .c om*/ * @param ftpSource * @param localDestPat * @param filePattern * @return the number of files being copied * @throws IOException */ public Integer syncPull(FTPClient ftpSource, String localDestPat, String filePattern) throws IOException { // check for new files since the last check which need to be copied Integer number = 0; SortedMap<FileNameDate, File> destMap = FileUtils.fileMapByNameAndDate(localDestPat, filePattern); SortedMap<FileNameDate, FTPFile> sourceMap = fileMapByNameAndDate(ftpSource, filePattern); // identify the list of source files different from their destinations for (FileNameDate fk : destMap.keySet()) { sourceMap.remove(fk); } // copy the list of files from source to destination for (FTPFile file : sourceMap.values()) { logger.debug("Copying file " + file.getName() + ": " + file.getTimestamp()); File copy = new File(localDestPat, file.getName()); try { if (!copy.exists()) { // copy to tmp file first to avoid clashes during lengthy copy action File tmp = File.createTempFile("vrs", ".tmp", copy.getParentFile()); FileOutputStream writeStream = new FileOutputStream(tmp); boolean rc = ftpSource.retrieveFile(file.getName(), writeStream); writeStream.close(); if (rc) { rc = tmp.renameTo(copy); number++; } if (!rc) { tmp.delete(); // cleanup if we fail } } } catch (IOException ex) { logger.error("Ftp FileCopy did not succeed (using " + file.getName() + ")" + " FTP reported error " + ftpSource.getReplyString(), ex); } } return number; }