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

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

Introduction

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

Prototype

public boolean changeWorkingDirectory(String pathname) throws IOException 

Source Link

Document

Change the current working directory of the FTP session.

Usage

From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java

@Override
public void upload(String path, File file, String contentType) {
    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");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//from  w w w .  j  a va2  s .  c o  m
            inputStream = new BufferedInputStream(new FileInputStream(file));
            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())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (SocketException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
            }
        }
    }
}

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

@Override
public void upload(String path, File file, String contentType) {
    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");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//from  w w w.  j av  a  2  s  .  c  o m
            inputStream = new FileInputStream(file);
            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())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:lucee.runtime.tag.Ftp.java

/**
 * change working directory /*from  w w w. ja  v a  2  s.com*/
 * @return FTPCLient
 * @throws IOException
 * @throws PageException 
 */
private FTPClient actionChangeDir() throws IOException, PageException {
    required("directory", directory);

    FTPClient client = getClient();
    client.changeWorkingDirectory(directory);
    writeCfftp(client);
    return client;
}

From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java

/**
 * Transfers files to the FTP account//from w w w.  j  a v a 2 s  .  c o  m
 *
 * @param files
 *            - files to be transferred
 * @param monitor
 *            - progress monitor
 * @param adaptable
 *            - adaptable instance. Must at least provide a Shell instance
 * @param deleteTransferred
 *            - true if transferred files shall be deleted on the client
 *            site
 * @return number of transferred files or -1 in case of abort
 * @throws IOException
 */
public int transferFiles(File[] files, IProgressMonitor monitor, IAdaptable adaptable,
        boolean deleteTransferred) throws IOException {
    filecount = countFiles(files);
    monitor.beginTask(Messages.FtpAccount_uploading_files, filecount + 1);
    FTPClient ftp = null;
    try {
        ftp = login();
        String dir = stripSlashes(getDirectory());
        int n = 0;
        boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(dir));
        if (!result) {
            if (monitor.isCanceled())
                return -1;
            boolean createDir = true;
            IDbErrorHandler errorHandler = Core.getCore().getErrorHandler();
            if (errorHandler != null)
                createDir = errorHandler.question(Messages.FtpAccount_directory_does_not_exist,
                        Messages.FtpAccount_specified_dir_does_not_exist, adaptable);
            if (createDir) {
                StringTokenizer st = new StringTokenizer(dir, "/"); //$NON-NLS-1$
                while (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    ftp.makeDirectory(token);
                    result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(token));
                    if (!result)
                        throw new IOException(Messages.FtpAccount_directory_creation_failed);
                }

            } else
                throw new IOException(Messages.FtpAccount_target_dir_does_not_exist);
        }
        if (files != null) {
            monitor.worked(1);
            skipAll = false;
            replaceAll = false;
            if (monitor.isCanceled())
                return -1;
            n = transferFiles(ftp, files, monitor, adaptable, deleteTransferred);
        }

        // transfer files
        if (isPassiveMode())
            ftp.enterLocalActiveMode();
        ftp.logout();
        return n;
    } finally {
        monitor.done();
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

private FTPClient connectMe() throws IOException {
    FTPClient ftpclient = new FTPClient();
    ftpclient.connect(configurator.host, configurator.port);

    if (ftpclient.login(configurator.username, configurator.password) == false) {
        ftpclient.logout();/*from  w ww . j a va 2s  . co m*/
        throw new IOException("Can't login to server");
    }
    int reply = ftpclient.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply) == false) {
        ftpclient.disconnect();
        throw new IOException("Can't login to server");
    }

    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

    if (configurator.passive) {
        ftpclient.enterLocalPassiveMode();
    } else {
        ftpclient.enterLocalActiveMode();
    }
    ftpclient.changeWorkingDirectory("/" + path);
    if (ftpclient.printWorkingDirectory().equals("/" + path) == false) {
        throw new IOException("Can't change working dir : " + "/" + path);
    }

    return ftpclient;
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    Map<String, String> ftpInfo = getFtpInfo(contentType);
    if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username"))
            && !"".equals(ftpInfo.get("password"))) {
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {/* ww  w. ja va 2s.  co  m*/
            inputStream = new FileInputStream(file);
            ftpClient.connect(ftpInfo.get("host"), 21);
            ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            path = ftpInfo.get("path") + path;
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java

public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName,
        String originalFileName) {
    if (logger.isDebugEnabled()) {
        logger.debug("SampleUploadCluster.process called");
    }/*from  w w w  .j  a  v a  2 s . c  om*/
    FTPClient ftp = new FTPClient();
    OutputStream out = null;
    File file = new File(sourceRepositoryPath + "/" + maskingFileName);
    FileInputStream fin = null;
    BufferedInputStream bin = null;
    String storeFileName = null;
    String server = "?IP";//??  ? . ex) 210.25.3.21
    try {
        ftp.connect(server);
        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            storeFileName = maskingFileName
                    + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length());
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            ftp.login("testId",
                    "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length()));
            if (logger.isDebugEnabled()) {
                logger.debug(server + " connect success !!! ");
            }
            ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/");
            out = ftp.storeFileStream(storeFileName);
            FileCopyUtils.copy(fin, out);
            if (logger.isDebugEnabled()) {
                logger.debug(" cluster success !!! ");
            }
        } else {
            ftp.disconnect();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (bin != null)
                bin.close();
            ftp.logout();
            out = null;
            bin = null;
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downIBSA() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*from   w  w  w  . ja va2s  .c  o m*/
        FileInputStream glnCodesCsv = new FileInputStream(Constants.DIR_IBSA + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(glnCodesCsv, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("IbsaAmiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory("data");
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        System.out.println("- Connected to server " + fs + "...");
        //get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();

        List<String> list_remote_files = Arrays.asList("Konditionen.csv", "Targeting_diff.csv", "Address.csv");
        List<String> list_local_files = Arrays.asList(Constants.FILE_CUST_IBSA, Constants.FILE_TARG_IBSA,
                Constants.FILE_MOOS_ADDR);

        if (ftpFiles != null && ftpFiles.length > 0) {
            int index = 0;
            for (String remote_file : list_remote_files) {
                OutputStream os = new FileOutputStream(Constants.DIR_IBSA + "/" + list_local_files.get(index));
                System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");

                boolean done = ftp_client.retrieveFile(remote_file, os);
                if (done)
                    System.out.println("file downloaded successfully.");
                else
                    System.out.println("error.");
                os.close();
                index++;
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

/**
 * @param host FTP Host name.//from  www. j  av a2s . c o  m
 * @param port FTP port.
 * @param user FTP User.
 * @param pswd FTP Password.
 * @param c    Context
 * @return Downloaded name file or blank list if something was going wrong.
 */
private String FTPDownloadFile(String host, Integer port, String user, String pswd, Context c) {
    String result = "";
    FTPClient mFTPClient = null;

    try {
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // Now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {

            // Login using username & password
            boolean status = mFTPClient.login(user, pswd);
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA);
            FTPFile[] fileList = mFTPClient.listFiles();
            long timestamp = 0l;
            String nameFile = "";
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) {
                    timestamp = fileList[i].getTimestamp().getTimeInMillis();
                    nameFile = fileList[i].getName();
                }
            }
            Log.d(TAG, "File da scaricare: " + nameFile);

            mFTPClient.enterLocalActiveMode();
            File folder = new File(Constants.DIR_ROBOT_IMG);
            OutputStream outputStream = null;
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }

            try {
                outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile);
                success = mFTPClient.retrieveFile(nameFile, outputStream);
            } catch (Exception e) {
                return e.getMessage();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            if (success) {
                result = nameFile;
                mFTPClient.deleteFile(nameFile);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (mFTPClient != null) {
            try {
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    return result;
}

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;/*from w  w  w . ja  v  a2 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());
    }
}