Example usage for org.apache.commons.net.ftp FTPClient FTPClient

List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure.
 * //from   w w  w  .  j  av  a 2 s  .c o m
 * @param sourceDirectoryPath the directory to be uploaded
 * @param destDirName the path on ftp where directory will be uploaded
 * @param numberOfRetryCounter number of attempts to be made for uploading the directory
 * @throws FTPDataUploadException if an error occurs while uploading the file
 * @throws IOException if an error occurs while making the ftp connection
 * @throws SocketException if an error occurs while making the ftp connection
 */
public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData)
        throws FTPDataUploadException, SocketException, IOException {
    boolean isValid = true;
    if (ftpInformation.getSourceDirectoryPath() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DIR);
        throw new FTPDataUploadException(VAR_SOURCE_DIR);
    }
    if (ftpInformation.getDestDirName() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DES);
        throw new FTPDataUploadException(VAR_SOURCE_DES);
    }
    if (isValid) {
        FTPClient client = new FTPClient();
        String destDirName = ftpInformation.getDestDirName();
        String destinationDirectory = ftpInformation.getUploadBaseDir();
        if (destDirName != null && !destDirName.isEmpty()) {
            String uploadBaseDir = ftpInformation.getUploadBaseDir();
            if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) {
                destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator,
                        destDirName);
            } else {
                destinationDirectory = destDirName;
            }

        }
        FileInputStream fis = null;
        try {
            createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(),
                    ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut());

            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                LOGGER.info("Starting File Upload...");
            } else {
                LOGGER.info("Invalid Connection to FTP server. Disconnecting Client");
                client.disconnect();
                isValid = false;
                throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client");
            }
            if (isValid) {

                // code changed for keeping the control connection busy.
                client.setControlKeepAliveTimeout(300);
                client.setFileType(FTP.BINARY_FILE_TYPE);
                createFtpDirectoryTree(client, destinationDirectory);
                // client.makeDirectory(destinationDirectory);
                if (deleteExistingFTPData) {
                    deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData);
                }
                File file = new File(ftpInformation.getSourceDirectoryPath());
                if (file.isDirectory()) {
                    String[] fileList = file.list();
                    for (String fileName : fileList) {
                        String inputFile = EphesoftStringUtil
                                .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName);
                        File checkFile = new File(inputFile);
                        if (checkFile.isFile()) {
                            LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName));
                            fis = new FileInputStream(inputFile);
                            try {
                                client.storeFile(fileName, fis);
                            } catch (IOException e) {
                                int retryCounter = ftpInformation.getNumberOfRetryCounter();
                                LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-",
                                        (retryCounter + 1)));
                                if (retryCounter < ftpInformation.getNumberOfRetries()) {
                                    retryCounter = retryCounter + 1;
                                    uploadDirectory(ftpInformation, deleteExistingFTPData);
                                } else {
                                    LOGGER.error("Error in uploading the file to FTP server");
                                }
                            } finally {
                                try {
                                    if (fis != null) {
                                        fis.close();
                                    }
                                } catch (IOException e) {
                                    LOGGER.info(EphesoftStringUtil
                                            .concatenate("Could not close stream for file.", inputFile));
                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("File does not exist..");
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                LOGGER.error("Disconnecting from FTP server....", e);
            }
        }
    }
}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        String urlPrefix = pluginConfig.getAttribute("urlPrefix");
        FTPClient ftpClient = new FTPClient();
        try {//  www. ja  v a 2  s . com
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())
                    && ftpClient.changeWorkingDirectory(path)) {
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(ftpFile.getName());
                    fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                    fileInfo.setIsDirectory(ftpFile.isDirectory());
                    fileInfo.setSize(ftpFile.getSize());
                    fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                    fileInfos.add(fileInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    return fileInfos;
}

From source file:com.glaf.core.util.FtpUtils.java

/**
 * /* w  w w  .ja va  2s. c  o  m*/
 * @param ip
 *            ???IP?
 * @param port
 *            ?
 * @param user
 *            ??
 * @param password
 *            ?
 */
public static FTPClient connectServer(String ip, int port, String user, String password) {
    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ip, port);
        ftpClient.login(user, password);
        ftpClientLocal.set(ftpClient);
        logger.info("login success!");
        return ftpClient;
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error("login failed", ex);
        throw new RuntimeException(ex);
    }
}

From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java

@Override
public void run(ActionContext context) throws Exception {
    Path destination = new Path(config.getDestDirectory());
    FileSystem fileSystem = FileSystem.get(new Configuration());
    destination = fileSystem.makeQualified(destination);
    if (!fileSystem.exists(destination)) {
        fileSystem.mkdirs(destination);//from  w  w w  .j  a  v a  2s  . c  o m
    }

    FTPClient ftp;
    if ("ftp".equals(config.getProtocol().toLowerCase())) {
        ftp = new FTPClient();
    } else {
        ftp = new FTPSClient();
    }
    ftp.setControlKeepAliveTimeout(5);
    // UNIX type server
    FTPClientConfig ftpConfig = new FTPClientConfig();
    // Set additional parameters required for the ftp
    // for example config.setServerTimeZoneId("Pacific/Pitcairn")
    ftp.configure(ftpConfig);
    try {
        ftp.connect(config.getHost(), config.getPort());
        ftp.enterLocalPassiveMode();
        String replyString = ftp.getReplyString();
        LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(),
                config.getPort(), replyString);

        // Check the reply code for actual success
        int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.",
                    replyCode, replyString));
        }

        if (!ftp.login(config.getUserName(), config.getPassword())) {
            LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString());
            ftp.logout();
            throw new RuntimeException(String.format(
                    "Login to the FTP server %s and port %s failed. " + "Please check user name and password.",
                    config.getHost(), config.getPort()));
        }

        FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory());
        LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString());
        // Check the reply code for listFiles call.
        // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted
        if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) {
            // encrypt data channel and listFiles again
            ((FTPSClient) ftp).execPROT("P");
            LOG.info("Attempting command listFiles on encrypted data channel.");
            ftpFiles = ftp.listFiles(config.getSrcDirectory());
        }
        for (FTPFile file : ftpFiles) {
            String source = config.getSrcDirectory() + "/" + file.getName();

            LOG.info("Current file {}, source {}", file.getName(), source);
            if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) {
                copyZip(ftp, source, fileSystem, destination);
            } else {
                Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName()));
                LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString());
                try (OutputStream output = fileSystem.create(destinationPath)) {
                    InputStream is = ftp.retrieveFileStream(source);
                    ByteStreams.copy(is, output);
                }
            }
            if (!ftp.completePendingCommand()) {
                LOG.error("Error completing command.");
            }
        }
        ftp.logout();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Throwable e) {
                LOG.error("Failure to disconnect the ftp connection.", e);
            }
        }
    }
}

From source file:adams.core.io.lister.FtpDirectoryLister.java

/**
 * Returns a new client for the host defined in the options.
 *
 * @return      the client, null if failed to create
 *///from   ww  w. ja va  2 s.c  om
protected FTPClient newClient() {
    FTPClient result;
    int reply;

    try {
        result = new FTPClient();
        result.addProtocolCommandListener(this);
        result.connect(m_Host);
        reply = result.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            getLogger().severe("FTP server refused connection: " + reply);
        } else {
            if (!result.login(m_User, m_Password.getValue())) {
                getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'");
            } else {
                if (m_UsePassiveMode)
                    result.enterLocalPassiveMode();
                if (m_UseBinaryMode)
                    result.setFileType(FTPClient.BINARY_FILE_TYPE);
            }
        }
    } catch (Exception e) {
        Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e);
        result = null;
    }

    return result;
}

From source file:com.github.wuic.nut.ftp.FtpNutDao.java

/**
 * <p>// www.  j  av a  2s.  c  om
 * Builds a new instance.
 * </p>
 *
 * @param ftps use FTPS or FTP protocol
 * @param host the host name
 * @param p the port
 * @param path default the path
 * @param basePathAsSysProp {@code true} if the base path is a system property
 * @param user the user name ({@code null} to skip the the authentication)
 * @param pwd the password (will be ignored if user is {@code null})
 * @param proxies proxy URIs serving the nut
 * @param pollingSeconds interleave in seconds for polling feature (-1 to disable)
 * @param regex consider path as regex or not
 */
public FtpNutDao(final Boolean ftps, final String host, final int p, final String path,
        final Boolean basePathAsSysProp, final String user, final String pwd, final String[] proxies,
        final int pollingSeconds, final Boolean regex) {
    super(path, basePathAsSysProp, proxies, pollingSeconds);
    ftpClient = ftps ? new FTPSClient(Boolean.TRUE) : new FTPClient();
    hostName = host;
    userName = user;
    password = pwd;
    port = p;
    regularExpression = regex;
}

From source file:deincraftlauncher.IO.download.FTPSync.java

public static String[] listFiles(String dir) {

    FTPClient client = new FTPClient();

    try {//from  ww w  .  j a  v  a  2s.c  o m
        client.connect(ftpServer);
        client.login(ftpUsername, ftpPassword);
        client.changeWorkingDirectory(dir);

        // Obtain a list of filenames in the current working
        // directory. When no file found an empty array will 
        // be returned.
        String[] names = client.listNames();

        client.logout();

        return names;

    } catch (IOException e) {
        System.err.println("Error connecting to ftp (listfiles): " + e);
    } finally {

        try {
            client.disconnect();
        } catch (IOException e) {
            System.err.println("Error disconnecting to ftp (listfiles): " + e);
        }
    }

    return null;

}

From source file:com.cisco.dvbu.ps.utils.net.FtpFile.java

public void ftpFile(String fileName) throws CustomProcedureException, SQLException {

    // new ftp client
    FTPClient ftp = new FTPClient();
    OutputStream output = null;/* www.j a v  a 2 s  .  c  om*/

    success = false;
    try {
        //try to connect
        ftp.connect(hostIp);

        //login to server
        if (!ftp.login(userId, userPass)) {
            ftp.logout();
            qenv.log(LOG_ERROR, "Ftp server refused connection user/password incorrect.");
        }
        int reply = ftp.getReplyCode();

        //FTPReply stores a set of constants for FTP Reply codes
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            qenv.log(LOG_ERROR, "Ftp server refused connection.");
        }

        //enter passive mode
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();

        //get system name
        //System.out.println("Remote system is " + ftp.getSystemType());

        //change current directory
        ftp.changeWorkingDirectory(ftpDirName);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        System.out.println("File is " + fileName);

        output = new FileOutputStream(dirName + "/" + fileName);

        //get the file from the remote system
        success = ftp.retrieveFile(fileName, output);

        //close output stream
        output.close();

    } catch (IOException ex) {
        throw new CustomProcedureException("Error in CJP " + getName() + ": " + ex.toString());
    }
}

From source file:com.claim.controller.FileTransferController.java

public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception {
    FTPClient ftpClient = new FTPClient();
    int replyCode;
    boolean completed = false;
    try {//from  www.  ja va  2  s.c om

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        try {
            ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
            FtpUtil.showServerReply(ftpClient);
        } catch (ConnectException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("ConnectException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (SocketException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("SocketException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (UnknownHostException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("UnknownHostException: " + ex.getMessage());
            ex.printStackTrace();
        }

        replyCode = ftpClient.getReplyCode();
        FtpUtil.showServerReply(ftpClient);

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            FtpUtil.showServerReply(ftpClient);
            ftpClient.disconnect();
            Console.LOG("Exception in connecting to FTP Serve ", 0);
            throw new Exception("Exception in connecting to FTP Server");
        } else {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG("Success in connecting to FTP Serve ", 1);
        }

        try {
            boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
            FtpUtil.showServerReply(ftpClient);
            if (!success) {
                throw new Exception("Could not login to the FTP server.");
            } else {
                Console.LOG("login to the FTP server. Successfully ", 1);
            }
            //ftpClient.enterLocalPassiveMode();
        } catch (FTPConnectionClosedException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();

        // APPROACH #2: uploads second file using an OutputStream
        File files = new File(ftpObj.getFtp_directory_path());

        String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator
                + ftpObj.getFtp_report_type();
        FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType);
        FtpUtil.showServerReply(ftpClient);

        String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp();
        FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp);
        FtpUtil.showServerReply(ftpClient);

        for (File file : files.listFiles()) {
            if (file.isFile()) {
                System.out.println("file ::" + file.getName());
                InputStream in = new FileInputStream(file);
                ftpClient.changeWorkingDirectory(workingDirectoryStmp);
                completed = ftpClient.storeFile(file.getName(), in);
                in.close();
                Console.LOG(
                        "  " + file.getName() + " ",
                        1);
                FtpUtil.showServerReply(ftpClient);
            }
        }
        Console.LOG(" ?... ", 1);

        //completed = ftpClient.completePendingCommand();
        FtpUtil.showServerReply(ftpClient);
        completed = true;
        ftpClient.disconnect();

    } catch (IOException ex) {
        Console.LOG(ex.getMessage(), 0);
        FtpUtil.showServerReply(ftpClient);
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            ex.printStackTrace();
        }
    }
    return completed;
}

From source file:com.dngames.mobilewebcam.UploadFTPPhoto.java

@Override
public void run() {
    doInBackgroundBegin();/*from  www .j a  v a  2 s  . c  o m*/

    if (mSettings.mRefreshDuration >= 10
            && (mSettings.mFTPBatch == 1 || ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) == 0)))
        publishProgress(mContext.getString(R.string.uploading, mSettings.mFTP + mSettings.mFTPDir));
    else if (mSettings.mFTPBatch > 1 || ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) != 0))
        publishProgress("batch ftp store");

    ftpupload: {
        try {
            BufferedInputStream buffIn = null;
            buffIn = new BufferedInputStream(new ByteArrayInputStream(mJpeg));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            String filename = mSettings.mDefaultname;
            if (mSettings.mFTPKeepPics == 0) {
                if (mSettings.mFTPNumbered) {
                    if (mSettings.mFTPTimestamp)
                        filename = MobileWebCam.gPictureCounter + sdf.format(mDate) + ".jpg";
                    else
                        filename = MobileWebCam.gPictureCounter + ".jpg";
                } else if (mSettings.mFTPTimestamp) {
                    filename = sdf.format(mDate) + ".jpg";
                }
            }

            boolean result = false;
            boolean deletetmpfile = false;
            boolean upload_now = true;
            if (mSettings.mStoreGPS) {
                try {
                    byte[] buffer = new byte[1024 * 8];
                    // Creates a file in the internal, app private storage
                    FileOutputStream fos;
                    fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
                    int r = 0;
                    while ((r = buffIn.read(buffer)) > -1)
                        fos.write(buffer, 0, r);
                    buffIn.close();
                    fos.close();
                    deletetmpfile = true;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    MobileWebCam.LogE("No file to write EXIF gps tag!");
                }

                File filePath = mContext.getFilesDir();
                File file = new File(filePath, filename);
                ExifWrapper.addCoordinates(file.getAbsolutePath(), WorkImage.gLatitude, WorkImage.gLongitude,
                        WorkImage.gAltitude);

                buffIn = new BufferedInputStream(mContext.openFileInput(filename));
            } else if (mSettings.mFTPBatch > 1 && ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) != 0)) {
                // store picture for later upload!
                byte[] buffer = new byte[1024 * 8];
                FileOutputStream fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
                int r = 0;
                while ((r = buffIn.read(buffer)) > -1)
                    fos.write(buffer, 0, r);
                buffIn.close();
                fos.close();
                upload_now = false;
            }

            if (upload_now) {
                FTPConnection.client = new FTPClient();
                FTPConnection.client.connect(InetAddress.getByName(mSettings.mFTP), mSettings.mFTPPort);

                FTPConnection.client.login(mSettings.mFTPLogin, mSettings.mFTPPassword);
                if (!FTPConnection.client.getReplyString().contains("230")) {
                    publishProgress("wrong ftp login response: " + FTPConnection.client.getReplyString()
                            + "\nAre your credentials correct?");
                    MobileWebCam.LogE("wrong ftp login response: " + FTPConnection.client.getReplyString()
                            + "\nAre your credentials correct?");
                    FTPConnection.client = null;
                    break ftpupload;
                }

                FTPConnection.client.changeWorkingDirectory(mSettings.mFTPDir);
                if (!FTPConnection.client.getReplyString().contains("250")) {
                    publishProgress("wrong ftp cwd response: " + FTPConnection.client.getReplyString()
                            + "\nIs the directory correct?");
                    MobileWebCam.LogE("wrong ftp cwd response: " + FTPConnection.client.getReplyString()
                            + "\nIs the directory correct?");
                    FTPConnection.client = null;
                    break ftpupload;
                }

                FTPConnection.client.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);

                if (mSettings.mFTPPassive)
                    FTPConnection.client.enterLocalPassiveMode();
                else
                    FTPConnection.client.enterLocalActiveMode();

                if (mSettings.mFTPKeepPics > 0) {
                    String replacename = filename.replace(".jpg", "");
                    // rename old pictures first
                    for (int i = mSettings.mFTPKeepPics - 1; i > 0; i--) {
                        try {
                            FTPConnection.client.rename(replacename + i + ".jpg",
                                    replacename + (i + 1) + ".jpg");
                        } catch (IOException e) {
                        }
                    }
                    try {
                        FTPConnection.client.rename(mSettings.mDefaultname, replacename + "1.jpg");
                    } catch (Exception e) {
                        if (e.getMessage() != null)
                            MobileWebCam.LogE(e.getMessage());
                        e.printStackTrace();
                    }
                }

                do {
                    // upload now
                    result = FTPConnection.client.storeFile(filename, buffIn);
                    buffIn.close();
                    buffIn = null;

                    if (deletetmpfile)
                        mContext.deleteFile(filename);

                    if (mSettings.mFTPBatch > 1 || mSettings.mReliableUpload) {
                        // find older pictures not sent yet
                        File file = mContext.getFilesDir();
                        String[] pics = file.list(new FilenameFilter() {
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg"))
                                    return true;
                                return false;
                            }
                        });
                        if (pics.length > 0) {
                            filename = pics[0];
                            buffIn = new BufferedInputStream(mContext.openFileInput(filename));
                            deletetmpfile = true; // delete this file after upload!
                            // rerun
                            MobileWebCam.LogI("ftp batched upload: " + filename);
                        }
                    }
                } while (buffIn != null);

                InputStream logIS = null;
                if (mSettings.mLogUpload) {
                    String log = MobileWebCam.GetLog(mContext,
                            mContext.getSharedPreferences(MobileWebCam.SHARED_PREFS_NAME, 0), mSettings);
                    logIS = new ByteArrayInputStream(log.getBytes("UTF-8"));
                    if (logIS != null) {
                        result &= FTPConnection.client.storeFile("log.txt", logIS);
                    }
                }

                if (result) {
                    publishProgress("ok");
                    MobileWebCam.LogI("ok");
                } else {
                    publishProgress("ftp error: " + FTPConnection.client.getReplyString());
                    MobileWebCam.LogE("ftp error: " + FTPConnection.client.getReplyString());
                }

                if (!mSettings.mFTPKeepConnected) {
                    FTPConnection.client.logout();
                    FTPConnection.client.disconnect();
                    FTPConnection.client = null;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            publishProgress("Ftp socket exception!");
            MobileWebCam.LogE("Ftp socket exception!");
            FTPConnection.client = null;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            publishProgress("Unknown ftp host!");
            MobileWebCam.LogE("Unknown ftp host!");
            FTPConnection.client = null;
        } catch (IOException e) {
            e.printStackTrace();
            if (e.getMessage() != null) {
                publishProgress("IOException: ftp\n" + e.getMessage());
                MobileWebCam.LogE("IOException: ftp\n" + e.getMessage());
            } else {
                publishProgress("ftp IOException");
                MobileWebCam.LogE("ftp IOException");
            }
            FTPConnection.client = null;
        } catch (NullPointerException e) {
            MobileWebCam.LogE("NullPointerException:\n" + e.getMessage());
            FTPConnection.client = null;
        }
    }

    doInBackgroundEnd(mSettings.mFTPBatch == 1 || ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) == 0));
}