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:com.tumblr.maximopro.iface.router.FTPHandler.java

private boolean createDirectoryStructure(FTPClient ftp, String[] dirNameList) throws IOException {
    if (dirNameList.length > 0) {
        String dirName = dirNameList[0];
        if (StringUtil.isEmpty(dirName) || ftp.changeWorkingDirectory(dirName)) {
            return createDirectoryStructure(ftp,
                    (String[]) Arrays.copyOfRange(dirNameList, 1, dirNameList.length));
        } else {//from  w  w w  . j a v a  2 s  . co m
            if (ftp.makeDirectory(dirName)) {
                return ftp.changeWorkingDirectory(dirName) && createDirectoryStructure(ftp,
                        (String[]) Arrays.copyOfRange(dirNameList, 1, dirNameList.length));
            } else {
                return false;
            }
        }
    }

    return true;
}

From source file:com.bdaum.zoom.net.ui.internal.NetActivator.java

public InputStream retrieveFile(Object ticket, URL url) throws IOException {
    FTPClient client = getClient(ticket, url);
    String path = url.getPath();/*  w  ww.  j a  v  a  2  s .c om*/
    int p = path.lastIndexOf('/');
    if (p >= 0) {
        String dir = path.substring(0, p);
        if (!client.changeWorkingDirectory(dir))
            throw new FileNotFoundException(dir);
        path = path.substring(p + 1);
    }
    return client.retrieveFileStream(path);
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * //from  w  ww  .  j  a v  a 2 s. c o m
 *
 * @param fileName   ??
 * @param path       ftp?
 * @param fileStream ?
 * @return true/false ?
 */
public boolean uploadFile(String fileName, String path, InputStream fileStream) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(path);
        ftpClient.storeFile(fileName, fileStream);
        fileStream.close();
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * //from   w  w  w . j a  v a 2  s.c o  m
 *
 * @param remotePath ftp
 * @param fileName   ???
 * @param localPath  ???
 * @return true/false ?
 */
public boolean downloadFile(String remotePath, String fileName, String localPath) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(remotePath);
        FTPFile[] files = ftpClient.listFiles();
        for (FTPFile file : files) {
            if (file.getName().equals(fileName)) {
                File localFile = new File(localPath + File.separator + file.getName());
                OutputStream outputStream = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), outputStream);
                outputStream.close();
            }
        }
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}

From source file:eu.prestoprime.plugin.fprint.FPrintTasks.java

@WfService(name = "fprint_upload", version = "0.8.0")
public void upload(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    logger.debug("Called " + this.getClass().getName());

    // prepare dynamic variables
    String id = dParamsString.get("id");
    String targetName = id + ".webm";
    String fileLocation = null;/*  www .j av a 2s.c om*/

    // prepare static variables
    String host = sParams.get("host");
    int port = Integer.parseInt(sParams.get("port"));
    String username = sParams.get("username");
    String password = sParams.get("password");
    String workdir = sParams.get("workdir");

    // retrieve AIP
    try {
        DIP dip = P4DataManager.getInstance().getDIPByID(id);
        List<String> fLocatList = dip.getAVMaterial("video/webm", "FILE");
        fileLocation = fLocatList.get(0);
    } catch (DataException | IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve the fileLocation of the Master Quality...");
    }

    logger.debug("Found video/webm location: " + fileLocation);

    // send to remote FTP folder
    FTPClient client = new FTPClient();
    try {
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                if (client.changeWorkingDirectory(workdir)) {
                    // TODO add behavior if file name is already present in
                    // remote ftp folder
                    // now OVERWRITES
                    File file = new File(fileLocation);
                    if (file.isFile()) {
                        if (client.storeFile(targetName, new FileInputStream(file))) {
                            logger.info("Stored file on server " + host + ":" + port + workdir);
                        } else {
                            throw new TaskExecutionFailedException("Cannot store file on server");
                        }
                    } else {
                        throw new TaskExecutionFailedException("Local file doesn't exist or is not acceptable");
                    }
                } else {
                    throw new TaskExecutionFailedException("Cannot browse directory " + workdir + " on server");
                }
            } else {
                throw new TaskExecutionFailedException("Username and Password not accepted by the server");
            }
        } else {
            throw new TaskExecutionFailedException(
                    "Cannot establish connection with server " + host + ":" + port);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("General exception with FTPClient");
    }

    logger.debug("Executed without errors " + this.getClass().getName());
}

From source file:com.globalsight.smartbox.util.FtpHelper.java

public boolean ftpDirExists(String p_path) {
    FTPClient ftpClient = getFtpClient();
    if (ftpClient != null && ftpClient.isConnected()) {
        try {//from  w  w w  .j ava  2s.  com
            return ftpClient.changeWorkingDirectory(p_path);
        } catch (Exception e) {
            return false;
        } finally {
            closeFtpClient(ftpClient);
        }
    }

    return true;
}

From source file:com.alexkasko.netty.ftp.FtpServerTest.java

@Test
public void test() throws IOException, InterruptedException {
    final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate(
            new ConsoleReceiver());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*  w  w  w. ja v  a 2 s  .com*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast("decoder", new CrlfStringDecoder());
                    pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate));
                }

            });
    b.localAddress(2121).bind();
    FTPClient client = new FTPClient();
    //        https://issues.apache.org/jira/browse/NET-493

    client.setBufferSize(0);
    client.connect("127.0.0.1", 2121);
    assertEquals(230, client.user("anonymous"));

    // active
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    assertEquals("/", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.listFiles("/foo").length == 0);
    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    //  assertTrue(client.deleteFile("baz"));

    // passive
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    client.enterLocalPassiveMode();
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());

    //TODO make a virtual filesystem that would work with directory
    //assertTrue(client.listFiles("/foo").length==1);

    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    // client.deleteFile("baz");

    assertEquals(221, client.quit());
    try {
        client.noop();
        fail("Should throw exception");
    } catch (IOException e) {
        //expected;
    }

}

From source file:com.jsystem.j2autoit.AutoItAgent.java

private static void getFileFtp(String user, String password, String host, int port, String fileName,
        String location) throws Exception {
    Log.info("\nretrieve " + fileName + NEW_LINE);
    FTPClient client = new FTPClient();

    client.connect(host, port); //connect to the management ftp server
    int reply = client.getReplyCode(); // check connection

    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new Exception("FTP fail to connect");
    }/*from  w  w  w .  java  2 s  . c  om*/

    if (!client.login(user, password)) { //check login
        throw new Exception("FTP fail to login");
    }

    //      FileOutputStream fos = null;
    try {
        File locationFile = new File(location);
        File dest = new File(locationFile, fileName);
        if (dest.exists()) {
            dest.delete();
        } else {
            locationFile.mkdirs();
        }
        boolean status = client.changeWorkingDirectory("/");
        Log.info("chdir-status:" + status + NEW_LINE);
        client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        client.setFileType(FTPClient.BINARY_FILE_TYPE);
        client.enterLocalActiveMode();

        InputStream in = client.retrieveFileStream(fileName);
        if (in == null) {
            Log.error("Input stream is null\n");
            throw new Exception("Fail to retrieve file " + fileName);
        }
        Thread.sleep(3000);
        saveInputStreamToFile(in, new File(location, fileName));
    } finally {
        client.disconnect();
    }

}

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 {/* w  w  w  .j av  a 2 s  .  co  m*/
            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.eryansky.common.utils.ftp.FtpFactory.java

/**
 * ?FTP?.//from www  .ja  va 2s  . c  om
 * 
 * @param path
 *            FTP??
 * @param filename
 *            FTP???
 * @param input
 *            ?
 * @return ?true?false
 */
public boolean ftpUploadFile(String path, String filename, InputStream input) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("UTF-8");
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(path);
        ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        // 
        ftp.storeFile(filename, input);
        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}