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:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

/**
 * Process the serversLogPresenceList and gets the actual log files/folder for each base log folder. This is done by
 * iterating the {@link LogsDownloaderWorker#getServersList()} depending on its presence.
 * //w  w w .j  a  v  a2 s.c  o m
 * @param serversLogPresenceList Map for each base log folder and servers presence as values (space separated list
 *            of servers keys)
 * @return
 */
private LinkedList<LogFolderInfo> getFromServersCompleteLogList(
        LinkedHashMap<String, String> serversLogPresenceList) {
    if (serversLogPresenceList.size() == 0)
        return new LinkedList<LogFolderInfo>();

    long timeF0 = System.currentTimeMillis();

    LinkedList<LogFolderInfo> tmpLogFolders = new LinkedList<LogFolderInfo>();

    try {
        ArrayList<String> servers = worker.getServersList();
        for (String serverKey : servers) { // Let's iterate by servers first
            if (stopLogListProcessing)
                break;

            if (!worker.isServerAvailable(serverKey))
                continue;

            FtpDownloader ftpServer = null;
            try {
                ftpServer = LogsDownloaderWorkerUtil.getOrRenewFtpDownloader(serverKey,
                        worker.getFtpDownloaders(), worker.getHostFor(serverKey), worker.getPortFor(serverKey));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ftpServer == null)
                continue;

            // String host = worker.getHostFor(serverKey); // To fill the log files host info
            String host = serverKey; // Using a key instead of host directly

            for (String logDir : serversLogPresenceList.keySet()) { // For the server go through the folders
                if (stopLogListProcessing)
                    break;

                if (!serversLogPresenceList.get(logDir).contains(serverKey))
                    continue;

                // This is needed to avoid problems with non English languages
                String isoStr = new String(logDir.getBytes(), "ISO-8859-1");

                LogFolderInfo lFolder = null;
                for (LogFolderInfo lfi : tmpLogFolders) {
                    if (lfi.getName().equals(logDir)) {
                        lFolder = lfi;
                        break;
                    }
                }
                if (lFolder == null)
                    lFolder = new LogFolderInfo(logDir);

                if (!ftpServer.isConnected())
                    ftpServer.renewClient();

                try {
                    FTPFile[] files = ftpServer.getClient().listFiles("/" + isoStr + "/");
                    for (FTPFile file : files) {
                        if (stopLogListProcessing)
                            break;

                        String name = logDir + "/" + file.getName();
                        String uriPartial = logDir + "/" + file.getName();
                        LogFileInfo logFileTmp = new LogFileInfo(name);
                        logFileTmp.setUriPartial(uriPartial);
                        logFileTmp.setSize(file.getSize());
                        logFileTmp.setFile(file);
                        logFileTmp.setHost(host);

                        // Let us see if its a directory
                        if (file.isDirectory()) {
                            logFileTmp.setSize(-1); // Set size to -1 if directory
                            long allSize = 0;

                            // Here there are no directories, considering only 2 folder layers only, e.g. "Photos/00000"
                            LinkedHashMap<String, FTPFile> dirListing = ftpServer
                                    .listDirectory(logFileTmp.getName());
                            ArrayList<LogFileInfo> directoryContents = new ArrayList<>();
                            for (String fName : dirListing.keySet()) {
                                if (stopLogListProcessing)
                                    break;

                                FTPFile fFile = dirListing.get(fName);
                                String fURIPartial = fName;
                                LogFileInfo fLogFileTmp = new LogFileInfo(fName);
                                fLogFileTmp.setUriPartial(fURIPartial);
                                fLogFileTmp.setSize(fFile.getSize());
                                fLogFileTmp.setFile(fFile);
                                fLogFileTmp.setHost(host);

                                allSize += fLogFileTmp.getSize();
                                directoryContents.add(fLogFileTmp);
                            }
                            logFileTmp.setDirectoryContents(directoryContents);
                            logFileTmp.setSize(allSize);
                        }
                        lFolder.addFile(logFileTmp);
                        tmpLogFolders.add(lFolder);
                    }
                } catch (Exception e) {
                    System.err.println(isoStr);
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    NeptusLog.pub().warn(".......Contacting remote systems for complete log file list "
            + (System.currentTimeMillis() - timeF0) + "ms");

    return tmpLogFolders;
}

From source file:rapture.ftp.common.FTPConnection.java

@Override
public List<String> listFiles(String path) {
    List<String> files = new LinkedList<>();

    try {//from ww w .  j a v  a 2s  .c  om
        if (path == null)
            path = ".";
        FTPFile[] ftpfiles = getFtpClient().listFiles(path);
        for (FTPFile f : ftpfiles) {
            files.add(f.getName());
        }
    } catch (IOException e) {
        log.error(String.format("Error listing files with path [%s] on FTP config.getAddress() [%s]. Error: %s",
                path, config.getAddress(), ExceptionToString.format(e)));
    }
    return files;
}

From source file:rems.Global.java

public static String[] GetFileList(InetAddress ftpServerAddrs, String serverAppDirectory, String dirName,
        String userName, String password) {
    String[] downloadFiles = new String[1];
    StringBuilder result = new StringBuilder();
    FTPClient ftpClient = new FTPClient();
    try {/*from www  .  ja v  a 2 s  .com*/
        // pass directory path on server to connect  
        ftpClient.connect(ftpServerAddrs);
        // pass username and password, returned true if authentication is  
        // successful  
        boolean login = ftpClient.login(userName, password);
        if (login) {
            //System.out.println("Connection established...");
            // get all files from server and store them in an array of  
            // FTPFiles  
            FTPFile[] files = ftpClient.listFiles();
            for (FTPFile file : files) {
                if (file.getType() == FTPFile.FILE_TYPE) {
                    result.append(file.getName());
                    result.append("\n");
                }
            }
            result.replace(result.toString().lastIndexOf("\n"), result.toString().length(), "");
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                System.out.println("Connection close...");
            }
        } else {
            System.out.println("Connection fail...");
        }
        return result.toString().split("\\\n");
    } catch (SocketException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += Arrays.toString(e.getStackTrace());
            Global.writeToLog();
        }
    }
    return downloadFiles;
}

From source file:restGateWay.HTMLGenerator.java

/**
 * This method return HTML source code than provide user to browse files, or retrive one
 *
 * @param file list of Files/*from w w w.j  ava2s.  com*/
 * @return String containing HTML part containing href link 
 */
private String getLinkForFileName(String cwd, FTPFile file) {
    String tmp = "";
    if (file.isDirectory())
        tmp += "<img src=\"http://agingparentsauthority.com/wp-content/plugins/sem-theme-pro/icons/folder.png\" alt=\"[   ]\" />       <a href='"
                + path + "resources/file" + cwd + "/" + file.getName() + "'>" + file.getName() + "</a></br>\n";
    if (file.isFile()) {
        tmp += "<img src=\"http://www.appropedia.org/skins/vector/images/file-icon.png\" alt=\"[   ]\" /> "
                + "<a href=\"" + path + "/resources/file/" + cwd + "/delete/" + file.getName()
                + "\"><img src=\"http://www.domainedesnoms.com/themes/site/ddn.fr/images/picto/delete.png\" /></a> "
                + "<a href=\"" + path + "/resources/file/" + cwd + "/download/" + file.getName() + "\">"
                + file.getName() + "</a></br>";
    }
    return tmp;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public StreamResult listResources(Object abstractConnection, String remoteResourcePath) throws Exception {
    long startTime = new Date().getTime();

    boolean isDirectory = checkIsDirectory(remoteResourcePath);

    if (!isDirectory) {
        throw new Exception(ErrorMessages.err_FTC008);
    }//from  w  ww . j a v a2 s  .c  o  m

    FTPClient connection = (FTPClient) abstractConnection;
    if (!connection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }

    List<Object> connectionObject = _checkResourcePath(connection, remoteResourcePath, "list-resources",
            isDirectory);

    System.out.println("resources: " + connectionObject.size());

    FTPFile[] resources = (FTPFile[]) connectionObject.get(1);
    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlWriter = null;

    try {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
        xmlWriter.setPrefix(modulePrefix, moduleNsUri);
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartElement(modulePrefix + ":resources-list");
        xmlWriter.writeNamespace(modulePrefix, moduleNsUri);
        xmlWriter.writeAttribute("absolute-path", remoteResourcePath);
        for (FTPFile resource : resources) {
            _generateResourceElement(xmlWriter, resource, null, remoteResourcePath + resource.getName());
        }
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        xmlWriter.close();
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    }

    // FTPconnection.completePendingCommand();
    StreamResult resultAsStreamResult = new StreamResult(writer);
    log.info("The FTP sub-module retrieved the list of resources in " + (new Date().getTime() - startTime)
            + " ms.");

    return resultAsStreamResult;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

private static void _generateResourceElement(XMLStreamWriter xmlWriter, FTPFile resource, InputStream is,
        String resourceAbsolutePath) throws IOException, Exception {

    String resourceName = resource.getName();
    String resourceType = ((resource.getType() == 1) ? "directory"
            : (((resource.getType() == 0) ? "file" : "link")));
    Calendar resourceTimeStamp = resource.getTimestamp();
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    String lastModified = formatter.format(resourceTimeStamp.getTimeInMillis());
    lastModified = lastModified.replace(" ", "T");
    lastModified = lastModified.substring(0, 22) + ":" + lastModified.substring(22, 24);
    long resourceSize = resource.getSize();
    String user = resource.getUser();
    String userGroup = resource.getGroup();
    String permissions = resource.getRawListing().substring(0, 10);
    String linkTo = resource.getLink();

    GenerateResourceElement.run(is, xmlWriter, modulePrefix, moduleNsUri, resourceName, resourceType,
            resourceAbsolutePath, lastModified, resourceSize, user, userGroup, permissions, linkTo);
}

From source file:s32a.Client.Startup.FTPHandler.java

/**
 * Retrieves server and codebase info from FTP server.
 * Codebase will need to be queried separately afterwards.
 * @return //from  www . ja  v a 2 s. c  o m
 */
public List<ServerInfo> getFTPData() {
    FTPClient client = null;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    List<ServerInfo> output = new ArrayList<>();

    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.username, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        // Reads codebase file from server
        File codebase = new File("codebase.properties");
        fos = new FileOutputStream(codebase.getAbsolutePath());
        client.retrieveFile("/Airhockey/Codebase/codebase.properties", fos);
        fos.close();
        this.codebaseURL = this.readCodebaseInfo(codebase);

        // Retrieves all currently active files from server
        File server = null;
        for (FTPFile f : client.listFiles("/Airhockey/Servers")) {
            server = new File(f.getName());
            fos = new FileOutputStream(server);
            client.retrieveFile("/Airhockey/Servers/" + f.getName(), fos);
            fos.close();
            output.add(this.readServerFile(server));
        }
        //Removes null entries
        output.remove(null);

        client.logout();
    } catch (IOException ex) {
        System.out.println("IOException: " + ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return output;
}

From source file:s32a.CodebaseDeployer.java

/**
 * Uploads given files to ftp server.//w w w  .  j  a  va2  s  .  com
 *
 * @param input key: desired name on server, Value: file to upload.
 */
private void uploadFiles(Map<String, File> input) {

    FTPClient client = null;
    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.userName, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        //            client.setFileType(FTP.ASCII_FILE_TYPE);

        //Creates all directories required on the server
        System.out.println("creating directories");
        client.makeDirectory("Airhockey");
        client.makeDirectory("Airhockey/Codebase");
        client.makeDirectory("Airhockey/Servers");
        client.makeDirectory("Airhockey/Codebase/s32a");
        System.out.println("default directories made");
        for (String s : directories) {
            client.makeDirectory(s);
        }

        //Uploads codebase URL
        fis = new FileInputStream(this.codebaseFile);
        boolean stored = client.storeFile("Airhockey/Codebase/codebase.properties", fis);
        //            client.completePendingCommand();
        System.out.println("Stored codebase file: " + stored);
        fis.close();

        // Removes references to all servers
        for (FTPFile f : client.listFiles("Airhockey/Servers")) {
            if (f.isFile()) {
                System.out.println("Deleting Server Listing: " + f.getName());
                client.deleteFile("/Airhockey/Servers/" + f.getName());
            }
        }

        // Uploads all class files
        System.out.println("Uploading classes");
        String defaultLoc = fs + "Airhockey" + fs + "Codebase" + fs;
        for (String dest : input.keySet()) {
            fis = new FileInputStream(input.get(dest));
            if (!client.storeFile(defaultLoc + dest, fis)) {
                System.out.println("unable to save: " + defaultLoc + dest);
            }
            fis.close();
            //                client.completePendingCommand();
        }

        client.logout();
    } catch (IOException ex) {
        System.out.println("IOException: " + ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:savant.thousandgenomes.FTPBrowser.java

public FTPBrowser(URL rootURL) throws IOException {
    setRoot(rootURL);/*from w w  w.  j  a va 2  s  . c om*/

    setLayout(new BorderLayout());

    addressField = new JTextField();
    addressField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                setRoot(new URL(addressField.getText()));
                updateDirectory();
            } catch (Exception x) {
                DialogUtils.displayException("1000 Genomes Plugin", "Unable to change root directory", x);
            }
        }

    });
    add(addressField, BorderLayout.NORTH);

    table = new JTable();
    updateDirectory();

    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent evt) {
            if (evt.getClickCount() == 2) {
                int row = table.rowAtPoint(evt.getPoint());
                try {
                    FTPFile f = ((FTPTableModel) table.getModel()).getEntry(row);
                    if (f == null) {
                        // Going up a directory.
                        curDir = curDir.getParentFile();
                        updateDirectory();
                    } else if (f.isDirectory()) {
                        curDir = new File(curDir, f.getName());
                        updateDirectory();
                    } else {
                        TrackUtils.createTrack(new URI(
                                "ftp://" + host + new File(curDir, f.getName()).getPath().replace("\\", "/")));
                    }
                } catch (Throwable x) {
                    DialogUtils.displayException("FTP Error", "Unable to process FTP request.", x);
                }
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.getViewport().setBackground(Color.WHITE);
    scrollPane.setPreferredSize(new Dimension(800, 500));
    add(scrollPane, BorderLayout.CENTER);

    this.setPreferredSize(new Dimension(800, 500));
}

From source file:savant.thousandgenomes.FTPBrowser.java

FTPTableModel(FTPFile[] files, boolean hasParent) {
    // We can't use the FTPFile array directly, because it contains some items
    // we want to suppress.  We may also want to insert a fake entry for the parent directory.
    if (hasParent) {
        this.files.add(null);
    }//  w w w. j  a  v a 2  s.  c  om
    for (FTPFile f : files) {
        if (!f.getName().startsWith(".")) {
            this.files.add(f);
        }
    }
}