All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.uvm.ccts.common.ftp.FTPClient Maven / Gradle / Ivy

Go to download

A library of useful generic objects and tools consolidated here to simplify all UVM CCTS projects

There is a newer version: 1.1.5
Show newest version
/*
 * Copyright 2015 The University of Vermont and State
 * Agricultural College.  All rights reserved.
 *
 * Written by Matthew B. Storer 
 *
 * This file is part of CCTS Common.
 *
 * CCTS Common is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CCTS Common is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CCTS Common.  If not, see .
 */

package edu.uvm.ccts.common.ftp;

import edu.uvm.ccts.common.model.FileMetadata;
import edu.uvm.ccts.common.util.FileUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mstorer on 11/26/13.
 */
public class FTPClient {
    private static final Log log = LogFactory.getLog(FTPClient.class);

    private org.apache.commons.net.ftp.FTPClient ftp = new org.apache.commons.net.ftp.FTPClient();
    private String host;
    private String user;
    private String pass;

    public FTPClient(String host, String user, String pass) {
        this.host = host;
        this.user = user;
        this.pass = pass;
    }

    public void connect() throws IOException {
        try {
            ftp.connect(host);
            ftp.login(user, pass);
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            log.info("connected to '" + host + "'");

        } catch (IOException e) {
            try { if (ftp != null) ftp.logout(); } catch (Exception e1) {}
            try { if (ftp != null) ftp.disconnect(); } catch (Exception e1) {}

            throw e;
        }
    }

    public void disconnect() {
        log.info("disconnected from '" + host + "'");

        try { if (ftp != null) ftp.logout(); } catch (Exception e1) {}
        try { if (ftp != null) ftp.disconnect(); } catch (Exception e1) {}
    }

    public void chdir(String dir) throws IOException {
        ftp.changeWorkingDirectory(dir);
    }

    public void download(String remoteFilename, String localFilename) throws IOException {
        String localPath = FileUtil.getPathPart(localFilename);
        if ( ! localPath.isEmpty() ) {
            FileUtil.createDirectory(localPath);
        }

        boolean success = false;
        int attempt = 0;
        int maxAttempts = 2;

        while ( ! success && attempt < maxAttempts ) {
            OutputStream output = null;

            try {
                output = new BufferedOutputStream(new FileOutputStream(localFilename));

                ftp.retrieveFile(remoteFilename, output);

                success = true;

            } catch (FTPConnectionClosedException e) {
                log.debug("remote server disconnected - attempting to re-establish connection -");
                connect();

            } finally {
                attempt ++;
                try { if (output != null) output.flush(); } catch (Exception e1) {}
                try { if (output != null) output.close(); } catch (Exception e1) {}
            }
        }
    }

    public List listFiles(String filenameFilter) throws IOException {
        List list = new ArrayList();

        for (FileMetadata metadata : listFilesWithMetadata(filenameFilter)) {
            list.add(metadata.getFilename());
        }

        return list;
    }

    public List listFilesWithMetadata(String filenameFilter) throws IOException {
        List list = new ArrayList();

        String remotePath = ftp.printWorkingDirectory();
        boolean includePath = FileUtil.getPathPart(filenameFilter).isEmpty();

        FTPFile[] files = ftp.listFiles(filenameFilter);
        if (files != null && files.length > 0) {
            for (FTPFile file : files) {
                String filename = includePath ? remotePath + "/" + file.getName() : file.getName();
                long timestamp = file.getTimestamp().getTime().getTime();
                long size = file.getSize();

                list.add(new FileMetadata(filename, timestamp, size));
            }
        }

        return list;
    }

    public String getHost() {
        return host;
    }

    public String getUser() {
        return user;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy