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

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

Introduction

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

Prototype

public long getSize() 

Source Link

Document

Return the file size in bytes.

Usage

From source file:ch.cyberduck.core.ftp.parser.UnixFTPEntryParserTest.java

/**
 * http://trac.cyberduck.ch/ticket/1076// ww  w .ja v a2 s  . c  om
 *
 * @
 */
@Test
public void testSizeWithIndicator() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    parsed = parser.parseFTPEntry("-rw-rw-rw- 1 ftp operator 9.0M Mar 22 17:44 Cyberduck-2.7.3.dmg");
    assertNotNull(parsed);
    assertTrue(parsed.isFile());
    assertEquals("Cyberduck-2.7.3.dmg", parsed.getName());
    assertEquals((long) (9.0 * 1048576), parsed.getSize());
    assertEquals(parsed.getUser(), "ftp");
    assertEquals(parsed.getGroup(), "operator");
    assertNotNull(parsed.getTimestamp());
    assertEquals(Calendar.MARCH, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(22, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));

    parsed = parser.parseFTPEntry("-rw-rw-rw- 1 ftp operator 61.8M Mar 7 18:42 GC Wayfinding pics.zip ");
    assertNotNull(parsed);
    assertTrue(parsed.isFile());
    assertEquals((long) (61.8 * 1048576), parsed.getSize());
    assertEquals("ftp", parsed.getUser());
    assertEquals("operator", parsed.getGroup());
    assertNotNull(parsed.getTimestamp());
    assertEquals(Calendar.MARCH, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(7, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));

    parsed = parser.parseFTPEntry("-rw-rw-rw- 1 ftp operator 172.4k Mar 7 16:01 HEALY071.TXT ");
    assertNotNull(parsed);
    assertTrue(parsed.isFile());
    assertEquals((long) (172.4 * 1024), parsed.getSize());
    assertEquals(parsed.getUser(), "ftp");
    assertEquals(parsed.getGroup(), "operator");
    assertNotNull(parsed.getTimestamp());
    assertEquals(Calendar.MARCH, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(7, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
}

From source file:com.feilong.tools.net.filetransfer.FTPUtil.java

@Override
protected Map<String, FileInfoEntity> getLsFileMap(String remotePath) throws Exception {
    Map<String, FileInfoEntity> map = new HashMap<String, FileInfoEntity>();
    FTPFile[] ftpFiles = ftpClient.listFiles(remotePath);
    for (FTPFile ftpFile : ftpFiles) {

        String filename = ftpFile.getName();

        boolean isDirectory = ftpFile.isDirectory();

        FileInfoEntity fileEntity = new FileInfoEntity();
        fileEntity.setFileType(isDirectory ? FileType.DIRECTORY : FileType.FILE);
        fileEntity.setName(filename);//w ww .jav a 2 s  . c o m
        fileEntity.setSize(ftpFile.getSize());
        fileEntity.setLastModified(ftpFile.getTimestamp().getTimeInMillis());

        map.put(filename, fileEntity);
    }
    return map;
}

From source file:lucee.commons.io.res.type.ftp.FTPResource.java

@Override
public long length() {
    if (isRoot())
        return 0;
    FTPResourceClient client = null;/*w w  w.  j  a va  2  s  .  c  o m*/
    try {
        provider.read(this);
        client = provider.getClient(data);
        FTPFile file = client.getFTPFile(this);
        if (file == null)
            return 0;
        return file.getSize();
    } catch (IOException e) {
        return 0;
    } finally {
        provider.returnClient(client);
    }
}

From source file:net.sf.webphotos.gui.util.FtpClient.java

private void preProcessBatch() {
    String acao;//  w  w w . jav a  2 s .co  m
    Arquivo tmpArq;
    int i, j = 0;

    // calcula quantidade de bytes a transmitir (upload e download somente)
    for (i = 0; i < tabela.getRowCount(); i++) {
        acao = tabela.getValueAt(i, 1).toString();
        if (acao.equals("enviar")) {
            totalBytes += Long.parseLong(tabela.getValueAt(i, 5).toString());
        }
        if (acao.equals("receber")) {
            Util.log("Calculando bytes a serem recebidos (lbum " + tabela.getValueAt(i, 2) + ")");
            tmpArq = (Arquivo) ftp.getListaArquivos().get(i);

            if (tmpArq.getNomeArquivo().equals("* todos")) {
                // Baixando todo o lbum
                try {
                    Util.out.println("Convertendo: " + tmpArq.getAlbumID());
                    // remove o tem atual e diminui 
                    // o marcador aps a remoo
                    ftp.getListaArquivos().remove(i--);
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        ftp.getListaArquivos().add(new Arquivo(tmpArq.getLinhaComando(), 2, tmpArq.getAlbumID(),
                                tmpArq.getFotoID(), remote.getName(), remote.getSize()));
                        totalBytes += remote.getSize();
                    } // fim for
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            } else {
                // Baixando um arquivo
                try {
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = this.ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        if (tmpArq.getNomeArquivo().equals(remote.getName())) {
                            totalBytes += remote.getSize();
                            tmpArq.setTamanho(remote.getSize());
                            break;
                        }
                    } // fim for
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
        if (acao.equals("apagar")) {
            Util.log("Calculando bytes a serem apagados (lbum " + tabela.getValueAt(i, 2) + ")");
            tmpArq = (Arquivo) ftp.getListaArquivos().get(i);
            if (tmpArq.getNomeArquivo().equals("* todos")) {
                // Apagando todo o lbum
                try {
                    Util.out.println("Convertendo: " + tmpArq.getAlbumID());
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = this.ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        totalBytes += remote.getSize();
                    }
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            } else {
                // Apagando um arquivo
                try {
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = this.ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        if (tmpArq.getNomeArquivo().equals(remote.getName())) {
                            totalBytes += remote.getSize();
                            tmpArq.setTamanho(remote.getSize());
                            break;
                        }
                    }
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }
}

From source file:com.toolsverse.io.FtpUtils.java

/**
 * Gets the list of FileResource objects from the folder + filename. filename can be a mask, for example: /usr/test/*.txt. 
 * If includeFolders == true recursively includes sub-folders. 
 *
 * @see com.toolsverse.io.FileResource/*w ww. j  av a2  s  . c om*/
 *
 * @param folder the folder
 * @param filename the filename
 * @param includeFolders the include folders flag. If equals to true recursively includes sub-folders
 * @return the list of FileResource objects
 * @throws Exception in case of any error
 */
public List<FileResource> getFileList(String folder, String filename, boolean includeFolders) throws Exception {
    List<FileResource> remoteFileList = new ArrayList<FileResource>();

    folder = !Utils.isNothing(folder) ? folder : ".";

    FTPFile[] files = ftpClient.listFiles(folder);

    if (files == null || files.length == 0)
        return null;

    for (FTPFile file : files) {
        boolean isDir = file.isDirectory();

        if ((includeFolders || !isDir)
                && FilenameUtils.wildcardMatch(file.getName(), filename, IOCase.INSENSITIVE)) {
            FileResource fileResource = new FileResource();

            if (Utils.isNothing(file.getName()) || "..".equalsIgnoreCase(file.getName())
                    || ".".equalsIgnoreCase(file.getName()))
                continue;

            fileResource.setPath(folder + "/" + file.getName());
            fileResource.setName(file.getName());
            fileResource.setIsDirectory(isDir);
            fileResource.setSize(!isDir ? file.getSize() : 0);
            fileResource
                    .setLastModified(file.getTimestamp() != null ? file.getTimestamp().getTimeInMillis() : 0);

            remoteFileList.add(fileResource);
        }
    }

    return remoteFileList;
}

From source file:net.sf.webphotos.gui.util.FtpClient.java

/**
 * Executa o comando FTP. Utiliza o mtodo
 * {@link net.sf.webphotos.sync.Sync#loadSyncCache() loadSyncCache}() para
 * fazer o load do arquivos com os comandos de FTP. Checa se existem
 * comandos a executar, caso positivo, tenta a conexo com FTP e executa os
 * comandos (UPLOAD, DELETE ou DOWNLOAD).
 *//*from  ww w.  java2  s . c om*/
@Override
public void run() {

    String acao;
    String albumID;
    String arquivo;
    long tamanho;

    String arqOrigem;
    String arqDestino;

    Object streamOrigem = null;
    Object streamDestino = null;

    String ultimoID = "";
    int i, j = 0;

    String diretorioDownload = null;
    // loadSyncCache arquivo
    ftp.loadSyncCache();
    modeloTabela.refresh(ftp.getListaArquivos());
    modeloTabela.fireTableDataChanged();

    // tem algum comando  executar ?
    if (tabela.getRowCount() == 0) {
        ftp.disconnect("No h comandos ftp");
        return;
    }

    // tenta a conexao com FTP
    if (!ftp.connect()) {
        return;
    }
    preProcessBatch();
    modeloTabela.refresh(ftp.getListaArquivos());
    modeloTabela.fireTableDataChanged();
    barra.setMaximum(Integer.parseInt(Long.toString(totalBytes)));

    // executa os comandos
    for (i = 0; i < tabela.getRowCount(); i++) {

        lblArquivos.setText(i + 1 + " / " + tabela.getRowCount());
        tabela.setRowSelectionInterval(i, i);
        tabela.scrollRectToVisible(tabela.getCellRect(i + 1, 0, true));
        tabela.repaint();
        acao = tabela.getValueAt(i, 1).toString();
        albumID = tabela.getValueAt(i, 2).toString();
        arquivo = tabela.getValueAt(i, 4).toString();

        // ajusta o diretrio para /ftpRoot/albumID
        // recebe a lista de arquivos 
        if (!ultimoID.equals(albumID)) {
            Util.log("Mudando para o diretrio " + albumID);
            try {
                ftp.cd(albumID);
                remoteFiles = ftp.listFiles();
                diretorioDownload = null;
            } catch (IOException ioE) {
                Util.log("[FtpClient.run]/ERRO: comando no foi aceito ao listar o diretrio " + albumID
                        + " desconectando");
                ftp.disconnect("no foi possivel entrar no diretorio");
            } catch (SyncException se) {
                Util.log(se.getMessage());
                ftp.disconnect("no foi possivel entrar no diretorio");
            }
        }

        // UPLOAD
        switch (acao) {
        case "enviar":
            if (diretorioDownload == null) {
                diretorioDownload = albunsRoot.getAbsolutePath() + File.separator + albumID;
            }
            arqOrigem = diretorioDownload + File.separator + arquivo;
            Util.out.println(arqOrigem + " -> " + arquivo);
            try {
                streamOrigem = new FileInputStream(arqOrigem);
                streamDestino = new BufferedOutputStream(ftp.storeFileStream(arquivo), ftp.getBufferSize());
                this.transfereArquivo((InputStream) streamOrigem, (OutputStream) streamDestino,
                        Long.parseLong(tabela.getValueAt(i, 5).toString()));
                tabela.setValueAt("ok", i, 0);
            } catch (FileNotFoundException ioE) {
                Util.log("[FtpClient.run]/AVISO: " + arqOrigem + " no foi encontrado.");
                tabela.setValueAt("ok - ne", i, 0);
            } catch (IOException ioE) {
                Util.log("[FtpClient.run]/ERRO: erro na transmisso de " + arqOrigem);
                ioE.printStackTrace(Util.out);
                tabela.setValueAt("erro", i, 0);
            } catch (NumberFormatException e) {
                Util.err.println("Erro inexperado: " + e.getMessage());
                e.printStackTrace(Util.out);
                tabela.setValueAt("erro", i, 0);
            } finally {
                try {
                    ftp.printWorkingDirectory();
                } catch (IOException e) {
                }
                try {
                    ((OutputStream) streamDestino).close();
                    ((InputStream) streamOrigem).close();
                } catch (Exception e) {
                }
            }
            posTransfer(i);

            // DELETE
            break;
        case "apagar":
            // apaga o diretorio inteiro
            if (arquivo.equals("* todos")) {
                try {
                    for (FTPFile remote : remoteFiles) {
                        ftp.deleteFile(remote.getName());
                        Util.log("Removendo arquivo remoto " + remote.getName());
                        transmitido += remote.getSize();
                        Util.out.println("Processado " + transmitido + " de " + totalBytes);
                        barra.setValue((int) transmitido);
                        lblKbytes.setText(Math.round((float) transmitido / 1024) + " Kb");
                    }

                    // Volta para o diretrio principal
                    ftp.changeWorkingDirectory(ftpRoot);
                    // finalmente remove o diretorio
                    ftp.removeDirectory(albumID);
                    tabela.setValueAt("ok", i, 0);

                } catch (Exception e) {
                    tabela.setValueAt("erro", i, 0);
                    log.error(e);
                }
                // apaga somente uma foto
            } else {
                for (FTPFile remote : remoteFiles) {
                    if (remote.getName().equals(arquivo)) {
                        remoteFile = remote;
                        break;
                    }
                }
                //remoteFile=RemoteFile.findRemoteFile(remoteFiles,arquivo);
                if (remoteFile == null) {
                    tabela.setValueAt("ok - ne", i, 0);
                } else {
                    tabela.setValueAt(Long.toString(remoteFile.getSize()), i, 5);
                    try {
                        ftp.deleteFile(arquivo);
                        tabela.setValueAt("ok", i, 0);

                        posTransfer(i);
                    } catch (IOException | NumberFormatException e) {
                        tabela.setValueAt("erro", i, 0);
                    }
                }
            }

            // DOWNLOAD - recebe os arquivos (pr listado e calculado)
            break;
        // fim if
        case "receber":
            try {
                // cada vez que muda o diretrio, a varivel diretrioDownload  nula
                if (diretorioDownload == null) {
                    diretorioDownload = albunsRoot.getAbsolutePath() + File.separator + albumID;
                    File temp = new File(diretorioDownload);

                    if (!temp.isDirectory()) {
                        temp.mkdir();
                        Util.log("Criando diretrio " + diretorioDownload);
                    }
                    temp = null;
                }
                arqDestino = diretorioDownload + File.separator + arquivo;
                Util.out.println(arquivo + " -> " + arqDestino);

                streamOrigem = new BufferedInputStream(ftp.retrieveFileStream(arquivo), ftp.getBufferSize());

                streamDestino = new FileOutputStream(arqDestino);

                this.transfereArquivo((InputStream) streamOrigem, (OutputStream) streamDestino,
                        Long.parseLong(tabela.getValueAt(i, 5).toString()));
                tabela.setValueAt("ok", i, 0);

                // calcula porcentagem e atualiza barra
                posTransfer(i);

            } catch (IOException ioE) {
                Util.err.println("Erro de transmisso: " + ioE.getMessage() + " "
                        + ((CopyStreamException) ioE).getIOException().getMessage());
                tabela.setValueAt("erro", i, 0);
                log.error(ioE);
            } catch (NumberFormatException e) {
                Util.err.println("Erro: ");
                log.error(e);
                tabela.setValueAt("erro", i, 0);
            } finally {
                try {
                    ftp.printWorkingDirectory();
                } catch (IOException e) {
                }
                try {
                    ((InputStream) streamOrigem).close();
                    ((OutputStream) streamDestino).close();
                } catch (IOException e) {
                }
            }
            break;
        }

        ultimoID = albumID;
    } // fim for
    ftp.disconnect("transmisso terminada");
}

From source file:au.org.intersect.dms.wn.transports.impl.FtpConnection.java

private FileInfo makeFileInfo(String parentPath, FTPFile info) {
    Date date = info.getTimestamp().getTime();
    int ftpType = info.getType();
    if (ftpType == FTPFile.SYMBOLIC_LINK_TYPE) {
        try {/*from  w  ww. j a  v a  2  s.c  o m*/
            changeWorkingDirectory(PathUtils.joinPath(parentPath, info.getName()));
            ftpType = FTPFile.DIRECTORY_TYPE;
        } catch (IOException e) {
            throw new TransportException("Cannot get list directory (" + info.getName() + ")");
        } catch (PathNotFoundException e) {
            ftpType = FTPFile.FILE_TYPE;
        }
    }
    FileType type = ftpType == FTPFile.DIRECTORY_TYPE ? FileType.DIRECTORY : FileType.FILE;
    FileInfo item = new FileInfo(type, PathUtils.joinPath(parentPath, info.getName()), info.getName(),
            info.getSize(), date);
    return item;
}

From source file:com.connection.factory.FtpConnectionApacheLib.java

@Override
public List<RemoteFileObject> readAllFilesWalkinPath(String remotePath) {
    List<RemoteFileObject> willReturnObject = new ArrayList<>();
    Queue<RemoteFileObject> directorylist = new LinkedBlockingQueue<>();
    RemoteFileObject object = null;/*from www  . j  a v a 2 s  .co  m*/
    object = new FtpApacheFileObject(FileInfoEnum.DIRECTORY);
    object.setDirectPath(remotePath);
    directorylist.add(object);
    try {
        while (!directorylist.isEmpty()) {
            object = directorylist.poll();
            FTPFile[] fileListTemp = _ftpObj.listFiles(object.getPath());
            for (FTPFile each : fileListTemp) {
                RemoteFileObject objectTemp = null;
                if (each.isDirectory()) {
                    objectTemp = new FtpApacheFileObject(FileInfoEnum.DIRECTORY);
                    objectTemp.setFileName(each.getName());
                    objectTemp.setAbsolutePath(object.getPath());
                    directorylist.add(objectTemp);
                } else if (each.isFile()) {
                    objectTemp = new FtpApacheFileObject(FileInfoEnum.FILE);
                    objectTemp.setFileName(each.getName());
                    objectTemp.setAbsolutePath(object.getPath());
                    objectTemp.setFileSize(each.getSize());
                    objectTemp.setFileType();
                    objectTemp.setDate(each.getTimestamp().getTime());
                    willReturnObject.add(objectTemp);
                }
            }
            object = null;
            fileListTemp = null;
        }

    } catch (IOException ex) {
        return null;
    } catch (ConnectionException ex) {

    }
    return willReturnObject;
}

From source file:com.connection.factory.FtpConnectionApacheLib.java

@Override
public void readAllFilesWalkingPathWithListener(FileListener listener, String remotePath) {
    // List<RemoteFileObject> willReturnObject = new ArrayList<>();
    Queue<RemoteFileObject> directorylist = new LinkedBlockingQueue<>();
    RemoteFileObject object = null;/*from ww  w. jav  a2s. c om*/
    object = new FtpApacheFileObject(FileInfoEnum.DIRECTORY);
    object.setDirectPath(remotePath);
    directorylist.add(object);
    try {
        while (!directorylist.isEmpty()) {
            object = directorylist.poll();
            FTPFile[] fileListTemp = _ftpObj.listFiles(object.getPath());
            for (FTPFile each : fileListTemp) {
                RemoteFileObject objectTemp = null;
                if (each.isDirectory()) {
                    objectTemp = new FtpApacheFileObject(FileInfoEnum.DIRECTORY);
                    objectTemp.setFileName(each.getName());
                    objectTemp.setAbsolutePath(object.getPath());
                    directorylist.add(objectTemp);
                } else if (each.isFile()) {
                    objectTemp = new FtpApacheFileObject(FileInfoEnum.FILE);
                    objectTemp.setFileName(each.getName());
                    objectTemp.setAbsolutePath(object.getPath());
                    objectTemp.setFileSize(each.getSize());
                    objectTemp.setFileType();
                    objectTemp.setDate(each.getTimestamp().getTime());
                    listener.handleRemoteFile(object);
                }
            }
            object = null;
            fileListTemp = null;
        }

    } catch (IOException | ConnectionException ex) {
        //    return null;
    }
    //  return willReturnObject;

    //  return willReturnObject;
}

From source file:com.moosemorals.mediabrowser.FtpScanner.java

private void scrapeFTP() throws IOException {
    synchronized (ftp) {
        connect();/*from w  w  w. j av  a 2s. co  m*/
        List<PVRFolder> queue = new LinkedList<>();
        queue.add((PVRFolder) pvr.getRoot());

        int total = 0;
        int checked = 0;

        while (!queue.isEmpty() && !ftpThread.isInterrupted()) {
            PVRFolder directory = queue.remove(0);
            if (!ftp.changeWorkingDirectory(FTP_ROOT + directory.getRemotePath())) {
                throw new IOException("Can't change FTP directory to " + FTP_ROOT + directory.getRemotePath());
            }

            FTPFile[] fileList = ftp.listFiles();
            total += fileList.length;
            for (FTPFile f : fileList) {
                if (f.getName().equals(".") || f.getName().equals("..")) {
                    // skip entries for this directory and parent directory
                    total -= 1;
                    continue;
                }
                if (f.isDirectory()) {
                    PVRFolder next = pvr.addFolder(directory, f.getName());
                    next.setFtpScanned(true);
                    pvr.updateItem(next);
                    queue.add(next);
                } else if (f.isFile() && f.getName().endsWith(".ts")) {
                    PVRFile file = pvr.addFile(directory, f.getName());
                    file.setSize(f.getSize());
                    updateFromHMT(file);
                    pvr.updateItem(file);
                }
                checked += 1;
                notifyScanListeners(DeviceListener.ScanType.ftp, total, checked);
            }
        }
        disconnect();
    }
}