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:simplehttpdb.net.FTPHelper.java

/**
 * searches the FTP directory for a fitting file to add a new entry
 * creates a new file as necessary//from w ww.j a  v  a  2s  .  com
 * 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:TrabajoFinalJava.DescargaFichero.java

@Override
public void run() {

    //************************INICIO****INTERFAZ**************************************************************************

    JFrame principal = new JFrame("GESTOR DESCARGAS");
    //Colores//www . j a  v a2  s  .  c o m

    Color nuevoColor = new Color(167, 220, 231);

    principal.getContentPane().setBackground(nuevoColor);

    JLabel tituloPrincipal = new JLabel("GESTOR DESCARGAS");
    JLabel tituloVentana = new JLabel("DESCARGA FICHERO FTP");
    //Recojo la fuente que se esta utilizando actualmente.
    Font auxFont = tituloPrincipal.getFont();

    //Aplico la fuente actual, y al final le doy el tamao del texto...
    tituloPrincipal.setFont(new Font(auxFont.getFontName(), auxFont.getStyle(), 30));
    tituloVentana.setFont(new Font(auxFont.getFontName(), auxFont.getStyle(), 30));
    //tituloVentana.setAlignmentY(0);

    JLabel nombreArchivo = new JLabel("INTRODUCE EL NOMBRE DEL FICHERO A DESCARGAR.");
    JTextField nombreArchivoIn = new JTextField();
    JButton descarga = new JButton("DESCARGA FICHERO.");
    JButton atras = new JButton("ATRAS");

    JButton salir = new JButton("Salir");

    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();

    //Asignamos la constante EXIT_ON_CLOSE, cierra la ventana al pulsar la X.
    principal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Asignamos al JFrame el Layout que usaremos, GridBagLayout
    principal.setLayout(gridbag);
    //aadir botones al layout

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1; // La fila 0 debe estirarse, le ponemos un 1.0
    gbc.fill = GridBagConstraints.HORIZONTAL;
    principal.add(tituloPrincipal, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1; // La fila 0 debe estirarse, le ponemos un 1.0
    gbc.fill = GridBagConstraints.NONE;
    principal.add(tituloVentana, gbc);

    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    principal.add(nombreArchivo, gbc);

    gbc.gridx = 1;
    gbc.gridy = 3;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    principal.add(nombreArchivoIn, gbc);

    gbc.gridx = 1;
    gbc.gridy = 4;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.0;
    gbc.fill = GridBagConstraints.NONE;
    principal.add(descarga, gbc);

    gbc.gridx = 0;
    gbc.gridy = 5;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.NONE;
    principal.add(atras, gbc);

    gbc.gridx = 1;
    gbc.gridy = 5;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1; // La fila 0 debe estirarse, le ponemos un 1.0
    gbc.fill = GridBagConstraints.HORIZONTAL;
    principal.add(salir, gbc);

    //Hace visible el panel
    principal.setVisible(true);
    principal.setSize(650, 350);
    principal.setLocationRelativeTo(null);
    principal.setResizable(false);
    //principal.pack();

    descarga.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            if (descargasUsuarioLog <= 9) {
                try {
                    cFtp.connect(ftpSsrver);
                    boolean login = cFtp.login(ftpUser, ftpPass);
                    System.out.print("conexion establecida");

                    cFtp.enterLocalPassiveMode();

                    nombreFichero = nombreArchivoIn.getText();
                    nombrePc = nombreArchivoIn.getText();

                    CrearListaFicheros listarFicheros = new CrearListaFicheros();
                    listarFicheros.start();

                    for (int i = 0; i < CrearListaFicheros.arrayArchivos.size(); i++) {

                        System.out.println(CrearListaFicheros.arrayArchivos.get(i));

                    }

                    if (CrearListaFicheros.arrayArchivos.contains(nombreFichero)) {
                        FTPFile file = cFtp.mlistFile(nombreFichero);
                        long size = file.getSize();
                        System.out.println("Tamao del fichero= " + size);

                        if (size > 1000000) {
                            System.out.println("El fichero es muy grande......");
                        } else {

                            FileOutputStream fos = new FileOutputStream(nombreFichero);
                            cFtp.retrieveFile(nombreFichero, fos);

                            System.out.println("");
                            System.out.println("Archivo recibido");

                            nombreArchivoIn.setBackground(Color.green);
                            descargasUsuarioLog = descargasUsuarioLog + 1;
                            System.out.println(descargasUsuarioLog);

                            //modificamos las descargas totales del usuario en la BBDD
                            Connection conn;

                            try {
                                try {
                                    Class.forName("com.mysql.jdbc.Driver");
                                } catch (Exception y) {
                                    y.printStackTrace();
                                }

                                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/midb", "root",
                                        "");
                                System.out.println("Conn OK!");

                                stmt = conn.createStatement();

                                stmt.executeUpdate("UPDATE usuarios SET bajadas = '" + descargasUsuarioLog
                                        + "' WHERE usuario = '" + usuarioLog + "';");

                                System.out.print("Descargas modificadas correctamente.");

                                conn.close();
                            } catch (Exception i) {
                                System.out.println(e);
                            }
                        }

                    } else {
                        System.out.println("El fichero no existe...");
                        nombreArchivoIn.setText("El fichero no existe");
                    }

                } catch (IOException r) {
                    r.printStackTrace();
                }

            } else {
                System.out.println(
                        "No te quedan descargas... por favor comuniquese con el administrador del servidor. Gracias.");
                nombreArchivoIn.setText(
                        "No te quedan descargas... por favor comuniquese con el administrador del servidor. Gracias.");

            }

        }

    });

    atras.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            FormularioAccesoFtp accesoFtp = new FormularioAccesoFtp();
            accesoFtp.inicioFtp();
            principal.setVisible(false);

        }

    });

    salir.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            System.exit(1000);

        }

    });

}

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

/**
 * /*from  w ww  . j  a v  a 2s. c  o m*/
 *
 * @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: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 {//from w  w  w  . jav  a 2s .  c om
            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   ww  w .  jav  a  2 s  . c  o  m
            // 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:uk.trainwatch.io.ftp.FTPClient.java

/**
 * Simple test to see if a remote file should be retrieved.
 * <p>//from  w  ww .  j  a v  a  2s .c  om
 * This returns true if file does not exist, if the lengths don't match or the remote file's date is newer than the local file
 * <p>
 * @param file
 * @param ftp
 *             <p>
 * @return
 * @throws java.io.IOException
 */
default boolean isFileRetrievable(File file, FTPFile ftp) throws IOException {
    return !file.exists() || file.length() != ftp.getSize()
            || file.lastModified() < ftp.getTimestamp().getTimeInMillis();
}