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

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

Introduction

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

Prototype

public int cwd(String directory) throws IOException 

Source Link

Document

A convenience method to send the FTP CWD command to the server, receive the reply, and return the reply code.

Usage

From source file:org.limy.common.util.FtpUtils.java

/**
 * FTP????/*from w ww. j a  v a  2 s. co m*/
 * <p>
 * ?????disconnect?????
 * </p>
 * @param client FTP
 * @param info FTP
 * @throws IOException I/O
 */
public static void connectFtp(FTPClient client, FtpInfo info) throws IOException {

    client.connect(info.getServerAddress());
    if (!client.login(info.getUserName(), info.getPassword())) {
        throw new IOException("?????");
    }
    if (info.getPath() != null) {
        client.cwd(info.getPath());
    }
}

From source file:org.limy.common.util.FtpUtils.java

/**
 * FTP????/*www . j  av  a 2 s .c  o  m*/
 * @param client FTP
 * @param rootPath 
 * @param relativePath ??
 * @param contents 
 * @return ????
 * @throws IOException I/O
 */
public static boolean uploadFileFtp(FTPClient client, String rootPath, String relativePath,
        InputStream contents) throws IOException {

    int cwd = client.cwd(rootPath);
    if (cwd == FTPReply.FILE_UNAVAILABLE) {
        // ???????
        if (rootPath.startsWith("/")) {
            mkdirsAbsolute(client, rootPath);
        } else {
            mkdirs(client, rootPath);
        }
    }

    LOG.debug("uploadFileFtp : " + rootPath + " ->" + relativePath);
    String targetDir = UrlUtils.getParent(relativePath);
    if (targetDir.startsWith("/")) {
        mkdirsAbsolute(client, targetDir);
    } else {
        mkdirs(client, targetDir);
    }
    client.cwd(rootPath);
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.site("chmod 664 " + relativePath);
    return client.storeFile(relativePath, contents);
}

From source file:org.limy.common.util.FtpUtils.java

/**
 * ???????/*w  w w.  jav a 2s . c  o  m*/
 * @param client FTP
 * @param remotePath ??
 * @throws IOException I/O
 */
private static void mkdirs(FTPClient client, String remotePath) throws IOException {
    if (client.cwd(remotePath) == FTPReply.FILE_UNAVAILABLE) {
        LOG.debug("Mkdir(ftp) : " + remotePath);

        StringTokenizer tokenizer = new StringTokenizer(remotePath, "/");
        StringBuilder subDir = new StringBuilder();
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            subDir.append(token);
            client.mkd(subDir.toString());
            subDir.append("/");
        }
    }
}

From source file:org.limy.common.util.FtpUtils.java

/**
 * ???????/*from www.j  av  a2 s . c  o m*/
 * @param client FTP
 * @param absolutePath 
 * @throws IOException I/O
 */
private static void mkdirsAbsolute(FTPClient client, String absolutePath) throws IOException {
    String baseDir = absolutePath;
    while (client.cwd(baseDir) == FTPReply.FILE_UNAVAILABLE) {
        if (baseDir.lastIndexOf('/') < 0) {
            break;
        }
        baseDir = baseDir.substring(0, baseDir.lastIndexOf('/'));
    }
    if (baseDir.length() == absolutePath.length()) {
        return;
    }
    int pos = absolutePath.indexOf('/', baseDir.length() + 1);
    client.mkd(absolutePath.substring(0, pos));
    mkdirsAbsolute(client, absolutePath);
}

From source file:org.n52.sos.importer.controller.Step1Controller.java

@Override
public boolean isFinished() {

    if (step1Panel != null && step1Panel.getFeedingType() == Step1Panel.CSV_FILE) {
        final String filePath = step1Panel.getCSVFilePath();
        if (filePath == null) {
            JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing",
                    JOptionPane.WARNING_MESSAGE);
            return false;
        }/* ww w  . j  av  a  2  s .  c  o m*/
        // checks one-time feed input data for validity
        if (filePath.equals("")) {
            JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing",
                    JOptionPane.WARNING_MESSAGE);
            return false;
        }

        final File dataFile = new File(filePath);
        if (!dataFile.exists()) {
            JOptionPane.showMessageDialog(null, "The specified file does not exist.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!dataFile.isFile()) {
            JOptionPane.showMessageDialog(null, "Please specify a file, not a directory.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!dataFile.canRead()) {
            JOptionPane.showMessageDialog(null, "No reading access on the specified file.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }
        readFile(dataFile, step1Panel.getFileEncoding());
    } else if (step1Panel != null && (step1Panel.getFeedingType() == Step1Panel.FTP_FILE)) {
        // checks repetitive feed input data for validity
        if (step1Panel.getUrl() == null || step1Panel.getUrl().equals("")) {
            JOptionPane.showMessageDialog(null, "No ftp server was specified.", "Server missing",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (step1Panel.getFilenameSchema() == null || step1Panel.getFilenameSchema().equals("")) {
            JOptionPane.showMessageDialog(null, "No file/file schema was specified.",
                    "File/file schema missing", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        // ftp client
        FTPClient client;

        // proxy
        final String pHost = System.getProperty("proxyHost", "proxy");
        int pPort = -1;
        if (System.getProperty("proxyPort") != null) {
            pPort = Integer.parseInt(System.getProperty("proxyPort"));
        }
        final String pUser = System.getProperty("http.proxyUser");
        final String pPassword = System.getProperty("http.proxyPassword");
        if (pHost != null && pPort != -1) {
            if (pUser != null && pPassword != null) {
                client = new FTPHTTPClient(pHost, pPort, pUser, pPassword);
            }
            client = new FTPHTTPClient(pHost, pPort);
        } else {
            client = new FTPClient();
        }

        // get first file
        if (step1Panel.getFeedingType() == Step1Panel.FTP_FILE) {
            final String csvFilePath = System.getProperty("user.home") + File.separator + ".SOSImporter"
                    + File.separator + "tmp_" + step1Panel.getFilenameSchema();

            // if back button was used: delete old file
            if (new File(csvFilePath).exists()) {
                new File(csvFilePath).delete();
            }

            try {
                client.connect(step1Panel.getUrl());
                final boolean login = client.login(step1Panel.getUser(), step1Panel.getPassword());
                if (login) {
                    // download file
                    final int result = client.cwd(step1Panel.getDirectory());
                    if (result == 250) { // successfully connected
                        final File outputFile = new File(csvFilePath);
                        final FileOutputStream fos = new FileOutputStream(outputFile);
                        client.retrieveFile(step1Panel.getFilenameSchema(), fos);
                        fos.flush();
                        fos.close();
                    }
                    final boolean logout = client.logout();
                    if (logout) {
                        logger.info("Step1Controller: cannot logout!");
                    }
                } else {
                    logger.info("Step1Controller: cannot login!");
                }

                final File csv = new File(csvFilePath);
                if (csv.length() != 0) {
                    step1Panel.setCSVFilePath(csvFilePath);
                    readFile(new File(csvFilePath), step1Panel.getFileEncoding());
                } else {
                    csv.delete();
                    throw new IOException();
                }

            } catch (final SocketException e) {
                System.err.println(e);
                JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            } catch (final IOException e) {
                System.err.println(e);
                JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            }
        }
    }

    return true;
}

From source file:org.n52.sos.importer.feeder.task.OneTimeFeeder.java

private DataFile getRemoteFile(final Configuration config) {
    File dataFile = null;//from   ww w .ja  va2  s .  c o  m

    // ftp client
    FTPClient client;

    // proxy
    final String pHost = System.getProperty("proxyHost", "proxy");
    int pPort = -1;
    if (System.getProperty("proxyPort") != null) {
        pPort = Integer.parseInt(System.getProperty("proxyPort"));
    }
    final String pUser = System.getProperty("http.proxyUser");
    final String pPassword = System.getProperty("http.proxyPassword");
    if (pHost != null && pPort != -1) {
        LOG.info("Using proxy for FTP connection!");
        if (pUser != null && pPassword != null) {
            client = new FTPHTTPClient(pHost, pPort, pUser, pPassword);
        }
        client = new FTPHTTPClient(pHost, pPort);
    } else {
        LOG.info("Using no proxy for FTP connection!");
        client = new FTPClient();
    }

    // get first file
    final String directory = config.getConfigFile().getAbsolutePath();
    dataFile = FileHelper.createFileInImporterHomeWithUniqueFileName(directory + ".csv");

    // if back button was used: delete old file
    if (dataFile.exists()) {
        dataFile.delete();
    }

    try {
        client.connect(config.getFtpHost());
        final boolean login = client.login(config.getUser(), config.getPassword());
        if (login) {
            LOG.info("FTP: connected...");
            // download file
            final int result = client.cwd(config.getFtpSubdirectory());
            LOG.info("FTP: go into directory...");
            if (result == 250) { // successfully connected
                final FileOutputStream fos = new FileOutputStream(dataFile);
                LOG.info("FTP: download file...");
                client.retrieveFile(config.getFtpFile(), fos);
                fos.flush();
                fos.close();
            } else {
                LOG.info("FTP: cannot go to subdirectory!");
            }
            final boolean logout = client.logout();
            if (!logout) {
                LOG.info("FTP: cannot logout!");
            }
        } else {
            LOG.info("FTP:  cannot login!");
        }

    } catch (final SocketException e) {
        LOG.error("The file you specified cannot be obtained.");
        return null;
    } catch (final IOException e) {
        LOG.error("The file you specified cannot be obtained.");
        return null;
    }

    return new DataFile(config, dataFile);
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * @param/* w  w w  .  j  a v  a 2s  .  c om*/
 * @return
 *
 * @param config
 * @param ftpC
 * @throws SocketException
 * @throws IOException
 */
private boolean configSetup(FtpConfig config, FTPClient ftpC) throws IOException {
    boolean rc;
    ftpC.connect(config.getHostAddress(), config.getPort());
    rc = ftpC.login(config.getUserName(), config.getPassword());
    if (!rc) {
        logger.error("Ftp could not log to remote server with " + config.getUserName());
        return false;
    }
    if (StringUtils.hasText(config.getServerPath())) {
        int cwdCode = ftpC.cwd(config.getServerPath());
        if (!FTPReply.isPositiveCompletion(cwdCode)) {
            logger.error("Ftp could not change working dir to " + config.getServerPath()
                    + " - Server returned Code " + cwdCode);
            return false;
        }
    }
    rc = ftpC.setFileType(config.getFileType());
    if (!rc) {
        logger.error("Ftp could not change FileType for transmission");
        return false;
    }
    return true;
}