Example usage for org.apache.commons.net.ftp FTPFile getName

List of usage examples for org.apache.commons.net.ftp FTPFile getName

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPFile getName.

Prototype

public String getName() 

Source Link

Document

Return the name of the file.

Usage

From source file:savant.thousandgenomes.FTPBrowser.java

@Override
public Object getValueAt(int row, int col) {
    FTPFile f = files.get(row);
    switch (col) {
    case 0:/*from w  w  w . j ava2 s  . c o  m*/
        return getIcon(f);
    case 1:
        return f == null ? ".." : f.getName();
    case 2:
        return getSizeString(f);
    }
    return null;
}

From source file:savant.thousandgenomes.FTPBrowser.java

/**
 * Use the Swing FileSystemView to get a system icon corresponding to the given
 * file.//from  w w w.j  a  v  a 2  s. c  o m
 *
 * @param f the FTP entry whose icon we want to retrieve
 * @return a system icon representing f
 */
private static Icon getIcon(FTPFile f) {
    if (f == null || f.isDirectory()) {
        return FileSystemView.getFileSystemView().getSystemIcon(new File("."));
    } else {
        String name = f.getName();
        int ind = name.lastIndexOf(".");
        if (ind > 0) {
            String ext = name.substring(ind + 1);
            try {
                File tempFile = File.createTempFile("temp_icon.", "." + ext);
                Icon i = FileSystemView.getFileSystemView().getSystemIcon(tempFile);
                tempFile.delete();
                return i;
            } catch (IOException ex) {
            }
        }
    }
    return null;
}

From source file:se.sll.reimbursementadapter.mule.NonDeletingFtpMessageReceiver.java

@Override
protected void postProcess(FTPClient client, FTPFile file, MuleMessage message) throws Exception {
    if (connector.isStreaming()) {
        if (!client.completePendingCommand()) {
            throw new IOException(MessageFormat.format(
                    "Failed to complete a pending command. Retrieveing file {0}. Ftp error: {1}",
                    file.getName(), client.getReplyCode()));
        }/*from   ww w .j a v a 2  s. c  o m*/
    }
}

From source file:simplehttpdb.net.FTPHelper.java

/**
 * searches the FTP directory for a fitting file to add a new entry
 * creates a new file as necessary// w  ww  . j ava 2s  .c  o m
 * TODO: add support for multiple encryption keys
 *
 * @param ftpClient
 * @param rootDir
 * @param relPath
 * @return
 * @throws IOException
 */
public String findFileToAddNewEntry(FTPClient ftpClient, String rootDir, String relPath) throws IOException {

    String localDir = rootDir + relPath;

    Logger.getLogger(getClass().getName()).log(Level.INFO,
            "search for files in:" + localDir + " relPath:" + relPath);

    FTPFile[] files = ftpClient.listFiles(localDir);
    String result = "";
    for (FTPFile file : files) {

        //just handle files with name.legth>2 (avoiding "." and ".." as filenames)
        if (file.getName().length() < 3) {
            continue;
        }

        if (file.getSize() < 1024 * Definitions.MAX_FILE_SIZE) {
            result = relPath + file.getName();
            break;
        }
    }
    if (result.equals("")) {
        //we have to create a new file
        result = relPath + UUID.randomUUID() + ".xml";
    }
    return result;
}

From source file:sos.net.SOSFTP.java

/**
 * return a listing of the contents of a directory in short format on
 * the remote machine (without subdirectory)
 * /*from   w w  w. j av  a  2 s. c  o m*/
 * @param pstrPathName on remote machine
 * @return a listing of the contents of a directory on the remote machine
 * @throws IOException 
 *
 * @exception Exception
 * @see #dir()
 */
private Vector<String> getFilenames(final String pstrPathName, final boolean flgRecurseSubFolders)
        throws IOException {
    Vector<String> vecListFileItems = new Vector<String>();
    // setListHiddenFiles(true);
    String[] fileList = null;
    String strCurrentDirectoryName = DoPWD();
    String lstrPathName = pstrPathName.trim();

    if (lstrPathName.length() <= 0) {
        lstrPathName = ".";
    }

    if (lstrPathName.equals(".")) {
        lstrPathName = strCurrentDirectoryName;
    }

    objLogger.debug("nlist with " + lstrPathName);
    if (1 == 1) {
        fileList = listNames(lstrPathName);
    } else {
        FTPFile[] objFtpFiles = listFiles(lstrPathName);
        if (objFtpFiles != null) {
            int i = 0;
            for (FTPFile ftpFile : objFtpFiles) {
                fileList[i++] = ftpFile.getName();
            }
        }
    }
    if (fileList == null) {
        return vecListFileItems;
    }

    for (String strCurrentFileName : fileList) {
        if (isNotHiddenFile(strCurrentFileName)) {
            DoCD(strCurrentFileName); // is this file-entry a subfolder?
            if (isNegativeCommandCompletion()) {
                /**
                 * kb 2011-04-27  add Directory-name if flgRecurseSubFolders == true
                 */
                if (flgRecurseSubFolders && strCurrentFileName.startsWith(strCurrentDirectoryName) == false) {
                    if (strCurrentDirectoryName.length() > 0) {
                        strCurrentFileName = strCurrentDirectoryName + "/" + strCurrentFileName;
                    }
                }
                /**
                 * \change
                 * kb: 2011-06-17
                 * bei sBroker gibt der FTP-Server (oder wer auch immer) einen backslash vor dem 
                 * Dateinamen an, der Pfad selbst ist mit "/" maskiert.
                 * beispiel:  /a/b/c\dateiname.pdf
                 * siehe auch http://www.mail-archive.com/gnu-arch-users@gnu.org/msg02884.html
                 * 
                 * wird ein solcher Pfad an den Server gesendet, um die Datei zu holen, so gibt
                 * es die Meldung, da eine solche Datei nicht vorhanden ist. Das scheint eine konfig-sache
                 * zu sein. 8of9 - liefert auch den backslash - erlaubt die angabe beider Pfadtrenner und zickt nicht rum.
                 * 
                 * Um dies zu vermeiden wird hier ein eventueller backslash in einen normalen
                 * Schrgstrich umgewandelt.
                 */
                strCurrentFileName = strCurrentFileName.replaceAll(conRegExpBackslash, "/");
                vecListFileItems.add(strCurrentFileName);
            } else { // yes, it's a subfolder. undo the cd now
                // String[] strSubFolders = strCurrentFile.split("/"); // get number of subfolders in path
                // for (int s = 0; s < strSubFolders.length; s++) {
                // DoCDUP();
                // }
                DoCDUP();
                if (flgRecurseSubFolders) {
                    Vector<String> vecNames = getFilenames(strCurrentFileName);
                    if (vecNames != null) {
                        vecListFileItems.addAll(vecNames);
                    }
                }
            }
        }
    }

    objLogger.debug("strCurrentDirectory = " + strCurrentDirectoryName);
    DoCD(strCurrentDirectoryName);
    DoPWD();
    return vecListFileItems;

}

From source file:tv.icntv.log.crawl.core.FtpImpl.java

/**
 * /*  ww  w  .  j  a v  a2s  .com*/
 *
 * @param remoteFileName     ??
 * @param localDires         
 * @param remoteDownLoadPath remoteFileName
 */
public boolean downloadFile(FTPFile remoteFileName, String localDires, String remoteDownLoadPath) {
    String strFileSuffix = (localDires.equals(File.separator) ? localDires : (localDires + File.separator));
    OutputStream outStream = null;
    boolean success = false;

    FileStoreData store = (FileStoreData) FtpConfig.SortTypeClass
            .valueOf(getFtpConfig().getFtpStoreType().toUpperCase()).getFileStoreTypeClass();
    try {
        String file = strFileSuffix + remoteFileName.getName();
        if (store.isExist(file) && store.isExist(file + ".writed")) {
            if (remoteFileName.getSize() != store.getSize(file)) {
                logger.info("file={} is problem,", file);
                store.delete(file);
                store.delete(file + ".writed");
                logger.info("delete file {}, {}", file, file + ".writed");
            } else {
                logger.info("file {} is down load", strFileSuffix + remoteFileName.getName());
                return true;
            }
        }
        if (!store.isExist(strFileSuffix + remoteFileName.getName() + ".writing")) {
            logger.info("create file writing....");
            store.createFile(strFileSuffix + remoteFileName.getName() + ".writing");
        }

        getFtpClient().changeWorkingDirectory(remoteDownLoadPath);
        outStream = store.getOutputStream(strFileSuffix + remoteFileName.getName());
        logger.info(remoteDownLoadPath + File.separator + remoteFileName.getName() + "....");
        success = getFtpClient().retrieveFile(remoteFileName.getName(), outStream);
        if (success == true) {
            logger.info(remoteDownLoadPath + File.separator + remoteFileName.getName() + "?"
                    + strFileSuffix + remoteFileName.getName());
            store.rename(strFileSuffix + remoteFileName.getName() + ".writing",
                    strFileSuffix + remoteFileName.getName() + ".writed");
            return success;
        }
    } catch (Exception e) {
        success = false;
        store.delete(strFileSuffix + remoteDownLoadPath + ".writing");
        logger.error(remoteFileName.getName() + "", e);
    } finally {
        if (null != outStream) {
            try {
                outStream.flush();
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}

From source file:tv.icntv.log.crawl.core.FtpImpl.java

@Override
public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory,
        DirectoryFilter directoryFilter, FileFilter fileFilter) {
    try {/*  w  w w . ja v  a  2 s. c o m*/
        FTPFile[] allFile = getFtpClient().listFiles(remoteDirectory);
        logger.info("ftp src size={}", allFile.length);
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {

            FTPFile file = allFile[currentFile];
            String name = file.getName();
            if (!file.isDirectory()) {
                if (getFileFilter().accept(name)) {
                    String prefix = null;
                    if (getFtpConfig().getFtpDstNameAppendLocal()) {
                        prefix = localDirectoryPath + remoteDirectory;
                    } else {
                        prefix = localDirectoryPath;
                    }
                    boolean success = false;
                    success = downloadFile(file, prefix, remoteDirectory);
                    int downloadCnt = 1;

                    for (int i = 0; i < 5; i++) {
                        if (success == false) {
                            logger.warn("?!");
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            login(getIp(), getPort(), getUser(), getPwd());
                            success = downloadFile(file, prefix, remoteDirectory);
                            downloadCnt += 1;
                        } else {
                            break;
                        }
                    }
                    if (downloadCnt > 1 && success == true) {
                        logger.warn("?, {} ", downloadCnt);
                    } else if (downloadCnt > 1 && success == false) {
                        logger.error(", {} ", downloadCnt);
                    }

                } else {
                    logger.error("file suffix {},not include", getFtpConfig().getFileSuffixs());
                    continue;
                }
            } else {
                //directory exclude logic
                if (!getDirectoryFilter().accept(name)) {
                    logger.info("directory exclude name=" + remoteDirectory + " \t regular="
                            + getFtpConfig().getFtpDirectoryExclude());
                    continue;
                }
                if (!getDirectoryInclude().accept(name)) {
                    logger.info("ftp directory {}", name);
                    // create directory if necessary
                    if (!localDirectoryPath.equals(File.separator)) {
                        FileStoreData store = (FileStoreData) FtpConfig.SortTypeClass
                                .valueOf(getFtpConfig().getFtpStoreType().toUpperCase())
                                .getFileStoreTypeClass();
                        if (!store.createDirectory(localDirectoryPath)) {
                            continue;
                        }
                    }
                    downLoadDirectory(localDirectoryPath,
                            (remoteDirectory.equals("/") ? remoteDirectory : (remoteDirectory + File.separator))
                                    + name,
                            directoryFilter, fileFilter);

                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        logger.info("");
        return false;
    }
    return true;
}

From source file:uk.nhs.cfh.dsp.srth.distribution.FileDownloader.java

public void getFileFromTRUDArchive(String trudArchiveName, String fileName, String outputURL) {

    logger.info("Now getting file... ");
    if (ftpClient.isConnected()) {
        logger.info("ftp client is connected... ");
        // now get file specified by inputURL
        try {/*ww w  .  ja v a2 s.  co m*/
            ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            logger.info("Sending NOOP command... ");
            // send NOOP command to see if connection is still active
            if (ftpClient.sendNoOp()) {
                logger.info("ftpClient.getReplyString() = " + ftpClient.getReplyString());
                FTPFile[] files = ftpClient.listFiles(getPackPath());
                for (FTPFile file : files) {
                    logger.info("file.getName() = " + file.getName());
                    logger.info("file.getSize() = " + file.getSize());
                    if (file.getName().equals(trudArchiveName) && file.getSize() > 0) {
                        InputStream is = ftpClient.retrieveFileStream(getPackPath() + trudArchiveName);

                        if (is != null) {
                            ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(is);
                            ZipArchiveEntry zipArchiveEntry = zipArchiveInputStream.getNextZipEntry();
                            while (zipArchiveEntry != null) {
                                String zippedArchiveEntryName = zipArchiveEntry.getName();
                                logger.info("zippedArchiveEntryName = " + zippedArchiveEntryName);
                                logger.info("fileName = " + fileName);
                                if (zippedArchiveEntryName.equals(fileName)) {
                                    logger.info("Extracting: " + zippedArchiveEntryName);
                                    File outputLocation = new File(outputURL);
                                    boolean canWrite = outputLocation.exists();
                                    logger.info("canWrite = " + canWrite);
                                    if (!canWrite) {
                                        canWrite = outputLocation.mkdirs();
                                        logger.info("canWrite after mkdirs = " + canWrite);
                                    }

                                    if (canWrite && outputLocation.canWrite()) {
                                        logger.info("outputLocation.getPath() = " + outputLocation.getPath());
                                        File destinationFile = new File(outputLocation.getAbsolutePath(),
                                                zippedArchiveEntryName);
                                        OutputStream out = new FileOutputStream(destinationFile);
                                        IOUtils.copy(zipArchiveInputStream, out);
                                        out.close();

                                        if (zippedArchiveEntryName.indexOf(".zip") > -1) {
                                            // unpackZip file
                                            extractZipFileContents(destinationFile);
                                        }
                                    }
                                } else {
                                    logger.info("Resetting zipArchiveEntry");
                                    zipArchiveEntry = zipArchiveInputStream.getNextZipEntry();
                                    if (zipArchiveEntry != null) {
                                        logger.info("zipArchiveEntry.getName() = " + zipArchiveEntry.getName());
                                    }
                                }

                            }

                            zipArchiveInputStream.close();
                            is.close();
                        }
                        break;
                    }
                }

                // complete pending commands; needed after opening and closing streams
                ftpClient.completePendingCommand();
            } else {
                logger.warning("FTP connection might have timed out.");
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            logger.warning("FTP connection might have timed out. " + ERR_MESSAGE + e.fillInStackTrace());
        }
    } else {
        logger.warning("No connection to TRUD is available. Ensure FTP connection is open");
    }
}

From source file:uk.nhs.cfh.dsp.srth.distribution.FileDownloader.java

public void getFileFromTRUD(String fileName, String outputURL) {

    logger.info("Now getting file... ");
    if (ftpClient.isConnected()) {
        // now get file specified by inputURL
        try {//from  w  w w . j a v a2s.  c om
            // send NOOP command to see if connection is still active
            if (ftpClient.sendNoOp()) {
                logger.info("Now listing directory... ");
                FTPFile[] files = ftpClient.listFiles(getPackPath());
                for (FTPFile file : files) {
                    logger.info("file.getName() = " + file.getName());
                    logger.info("file.getSize() = " + file.getSize());
                    if (file.getName().equals(fileName) && file.getSize() > 0) {
                        InputStream is = ftpClient.retrieveFileStream(getPackPath() + fileName);
                        if (is != null) {
                            getFileFromStream(is, outputURL);
                        }
                        break;
                    }
                }
            } else {
                ftpClient.disconnect();
                checkAndOpenFTPConnection();
            }
        } catch (IOException e) {
            logger.warning(
                    "FTP connection might have timed out. Nested exception is : " + e.fillInStackTrace());
        }
    } else {
        logger.warning("No connection to TRUD is available. Ensure FTP connection is open");
    }
}

From source file:us.mn.state.dot.tms.client.camera.FTPStream.java

/** Create a new JPEG stream 
 * @throws IOException *//*from   w w  w  .  j av  a 2s  .  co  m*/
public FTPStream(Scheduler s, VideoRequest req, Camera c) throws IOException {
    size = UI.dimension(req.getSize().width, req.getSize().height);
    ftpClient = new FTPClient();

    /** Get ip and port from encoder field */
    baseUrl = c.getEncoder();
    String[] params = baseUrl.split(":");
    ip = params[0];

    /** Default port is 80 if no port is provided */
    if (params.length > 1) {
        port = Integer.parseInt(params[1]);
    } else {
        port = 80;
    }

    /** Get base directory of images, provide root (/) if null or blank */
    ftpPath = c.getFtpPath();
    if (ftpPath == null || ftpPath.trim().equals("")) {
        ftpPath = "/";
    }

    /** Get filename if static image path */
    same_filename = c.getSameFilename();
    if (same_filename) {
        ftp_filename = c.getFtpFilename();
    }

    /** Use anonymous with blank password if username field is left blank */
    ftpUsername = c.getFtpUsername();
    ftpPassword = c.getFtpPassword();
    if (ftpUsername == null || ftpUsername.trim().equals("")) {
        ftpUsername = "anonomymous";
        ftpPassword = "";
    }

    ftpFilter = new FTPFileFilter() {
        @Override
        public boolean accept(FTPFile ftpFile) {
            return (ftpFile.isFile()
                    && (ftpFile.getName().endsWith(".jpg") || ftpFile.getName().endsWith(".png")));
        }
    };

    /** Get the FTP Image */
    getFtpImage();

    /** Create thread to read image based on refresh interval */
    /** @throws IOException */
    final Job job = new Job(Calendar.MINUTE, c.getRefInterval()) {
        public void perform() throws IOException {
            if (running) {
                getFtpImage();
            }
        }

        public boolean isRepeating() {
            return running;
        }
    };
    s.addJob(job);

}