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

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

Introduction

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

Prototype

public boolean makeDirectory(String pathname) throws IOException 

Source Link

Document

Creates a new subdirectory on the FTP server in the current directory (if a relative pathname is given) or where specified (if an absolute pathname is given).

Usage

From source file:facturacion.ftp.FtpServer.java

public static int sendImgFile(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {/*w  w  w . j a v a2  s. c o  m*/
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1 = " + success);
        success = ftpClient.makeDirectory(hostDirServer + "/img");
        System.out.println("sucess 233 = " + success);
        success = ftpClient.storeFile(hostDirServer + "/img/" + fileNameServer, buffIn);
        System.out.println("sucess 3 = " + success);
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}

From source file:facturacion.ftp.FtpServer.java

public static int sendTokenInputStream(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {//from   w w  w .j a v  a2 s  . c o  m
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        System.out.println(hostDirServer);
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1133 = " + success);
        //showServerReply(ftpClient);
        success = ftpClient.makeDirectory(hostDirServer + "/token");
        /*
        System.out.println("sucess 1 = "+success);
        success = ftpClient.makeDirectory("casa111");
        System.out.println("sucess 111 = "+success);
        success = ftpClient.makeDirectory("/usr/erp/token/casa");
        System.out.println("sucess 111 = "+success);
        success = ftpClient.makeDirectory("/casa2");
        System.out.println("sucess 1 = "+success);
        */
        success = ftpClient.storeFile(hostDirServer + "/token/" + fileNameServer, buffIn);
        //success = ftpClient.storeFile("prueba", buffIn);
        System.out.println("sucess 2 = " + success);
        //return (success)? 1:0;
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}

From source file:net.paissad.jcamstream.utils.FTPUtils.java

/**
 * Create a directory onto the FTP server and recursively when necessary.
 * /*  w  ww .  ja  v a  2  s. c  o  m*/
 * @param dirname
 *            - The directory to create.
 * @throws IOException
 * @throws FTPException
 */
private void mkdirs(String dirname) throws IOException, FTPException {
    FTPClient client = this.getFtpClient();
    String errMsg;

    char firstChar = dirname.charAt(0);
    String currentRoot = (firstChar == '/') ? "/" : "";

    String[] subDirnames = dirname.split("/");

    for (String name : subDirnames) {
        if (!name.isEmpty()) {
            currentRoot += name + "/";
            client.makeDirectory(currentRoot);
            errMsg = "Error while creating the directory " + currentRoot;
            this.verifyReplyCode(errMsg);
        }
    }
}

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 {//  w w w  .  jav a 2s  . c o 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.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public void ensureDirectoryExists(final FlowFile flowFile, final File directoryName) throws IOException {
    if (directoryName.getParent() != null && !directoryName.getParentFile().equals(new File(File.separator))) {
        ensureDirectoryExists(flowFile, directoryName.getParentFile());
    }//from   w w w. j a  va  2 s  .c o  m

    final String remoteDirectory = directoryName.getAbsolutePath().replace("\\", "/").replaceAll("^.\\:", "");
    final FTPClient client = getClient(flowFile);
    final boolean cdSuccessful = setWorkingDirectory(remoteDirectory);

    if (!cdSuccessful) {
        logger.debug("Remote Directory {} does not exist; creating it", new Object[] { remoteDirectory });
        if (client.makeDirectory(remoteDirectory)) {
            logger.debug("Created {}", new Object[] { remoteDirectory });
        } else {
            throw new IOException("Failed to create remote directory " + remoteDirectory);
        }
    }
}

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

/**
 * create a remote directory/*from  ww  w .j  a  v  a 2s.c  o  m*/
 * @return FTPCLient
 * @throws IOException
 * @throws PageException 
 */
private FTPClient actionCreateDir() throws IOException, PageException {
    required("directory", directory);

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

From source file:madkitgroupextension.export.Export.java

private static void sendToWebSite() throws IOException {
    System.out.println("Enter your password :");
    byte b[] = new byte[100];
    int l = System.in.read(b);
    String pwd = new String(b, 0, l);

    boolean reconnect = true;
    long time = System.currentTimeMillis();
    File current_file_transfert = null;
    File current_directory_transfert = null;

    while (reconnect) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(FTPURL, 21);//from w  ww  .  j a  v  a 2  s  . com
        try {
            if (ftpClient.isConnected()) {
                System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !");
                if (ftpClient.login(FTPLOGIN, pwd)) {
                    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                    System.out.println("Logged as " + FTPLOGIN + " !");
                    System.out.print("Updating...");

                    FTPFile files[] = ftpClient.listFiles("");
                    FTPFile downloadroot = null;
                    FTPFile docroot = null;

                    for (FTPFile f : files) {
                        if (f.getName().equals("downloads")) {
                            downloadroot = f;
                            if (docroot != null)
                                break;
                        }
                        if (f.getName().equals("doc")) {
                            docroot = f;
                            if (downloadroot != null)
                                break;
                        }
                    }
                    if (downloadroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("downloads")) {
                            System.err.println("Impossible to create directory: downloads");
                        }
                    }
                    if (docroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("doc")) {
                            System.err.println("Impossible to create directory: doc");
                        }
                    }

                    updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert,
                            current_directory_transfert);
                    updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert,
                            current_directory_transfert);
                    reconnect = false;

                    System.out.println("[OK]");
                    if (ftpClient.logout()) {
                        System.out.println("Logged out from " + FTPLOGIN + " succesfull !");
                    } else
                        System.err.println("Logged out from " + FTPLOGIN + " FAILED !");
                } else
                    System.err.println("Impossible to log as " + FTPLOGIN + " !");

                ftpClient.disconnect();
                System.out.println("Disconnected from " + FTPURL + " !");
            } else {
                System.err.println("Impossible to get a connection to the server " + FTPURL + " !");
            }
            reconnect = false;
        } catch (TransfertException e) {
            if (System.currentTimeMillis() - time > 30000) {
                System.err.println("A problem occured during the transfert...");
                System.out.println("Reconnection in progress...");
                try {
                    ftpClient.disconnect();
                } catch (Exception e2) {
                }
                current_file_transfert = e.current_file_transfert;
                current_directory_transfert = e.current_directory_transfert;
                time = System.currentTimeMillis();
            } else {
                System.err.println("A problem occured during the transfert. Transfert aborded.");
                throw e.original_exception;
            }
        }
    }
}

From source file:madkitgroupextension.export.Export.java

public static void updateFTP(FTPClient ftpClient, String _directory_dst, File _directory_src,
        File _current_file_transfert) throws IOException, TransfertException {
    ftpClient.changeWorkingDirectory("./");
    FTPListParseEngine ftplpe = ftpClient.initiateListParsing(_directory_dst);
    FTPFile files[] = ftplpe.getFiles();

    File current_file_transfert = _current_file_transfert;

    try {//from   w  w  w  . j  a v a 2s . co  m
        for (File f : _directory_src.listFiles()) {
            if (f.isDirectory()) {
                if (!f.getName().equals("./") && !f.getName().equals("../")) {
                    if (_current_file_transfert != null) {
                        if (!_current_file_transfert.getCanonicalPath().startsWith(f.getCanonicalPath()))
                            continue;
                        else
                            _current_file_transfert = null;
                    }
                    boolean found = false;
                    for (FTPFile ff : files) {
                        if (f.getName().equals(ff.getName())) {
                            if (ff.isFile()) {
                                ftpClient.deleteFile(_directory_dst + ff.getName());
                            } else
                                found = true;
                            break;
                        }
                    }

                    if (!found) {
                        ftpClient.changeWorkingDirectory("./");
                        if (!ftpClient.makeDirectory(_directory_dst + f.getName() + "/"))
                            System.err.println(
                                    "Impossible to create directory " + _directory_dst + f.getName() + "/");
                    }
                    updateFTP(ftpClient, _directory_dst + f.getName() + "/", f, _current_file_transfert);
                }
            } else {
                if (_current_file_transfert != null) {
                    if (!_current_file_transfert.equals(f.getCanonicalPath()))
                        continue;
                    else
                        _current_file_transfert = null;
                }
                current_file_transfert = _current_file_transfert;
                FTPFile found = null;
                for (FTPFile ff : files) {
                    if (f.getName().equals(ff.getName())) {
                        if (ff.isDirectory()) {
                            FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName());
                        } else
                            found = ff;
                        break;
                    }
                }
                if (found == null || (found.getTimestamp().getTimeInMillis() - f.lastModified()) < 0
                        || found.getSize() != f.length()) {
                    FileInputStream fis = new FileInputStream(f);
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    if (!ftpClient.storeFile(_directory_dst + f.getName(), fis))
                        System.err.println("Impossible to send file: " + _directory_dst + f.getName());
                    fis.close();
                    for (FTPFile ff : ftplpe.getFiles()) {
                        if (f.getName().equals(ff.getName())) {
                            f.setLastModified(ff.getTimestamp().getTimeInMillis());
                            break;
                        }
                    }
                }
            }

        }
    } catch (IOException e) {
        throw new TransfertException(current_file_transfert, null, e);
    }
    for (FTPFile ff : files) {
        if (!ff.getName().equals(".") && !ff.getName().equals("..")) {
            boolean found = false;
            for (File f : _directory_src.listFiles()) {
                if (f.getName().equals(ff.getName()) && f.isDirectory() == ff.isDirectory()) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (ff.isDirectory()) {
                    FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName());
                } else {
                    ftpClient.deleteFile(_directory_dst + ff.getName());
                }
            }
        }
    }
}

From source file:GridFDock.DataDistribute.java

public Status CreateDirectory(String remote, FTPClient ftpClient) throws IOException {
    Status status = Status.Create_Directory_Success;
    String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
    if (!directory.equalsIgnoreCase("/")
            && !ftpClient.changeWorkingDirectory(new String(directory.getBytes(CODING_1), CODING_2))) {
        int start = 0;
        int end = 0;
        if (directory.startsWith("/")) {
            start = 1;/*from  w w  w .  java 2  s . c o m*/
        } else {
            start = 0;
        }
        end = directory.indexOf("/", start);
        while (true) {
            String subDirectory = new String(remote.substring(start, end).getBytes(CODING_1), CODING_2);
            if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                if (ftpClient.makeDirectory(subDirectory)) {
                    ftpClient.changeWorkingDirectory(subDirectory);
                } else {
                    System.out.println("the failure for creating directory.");
                    return Status.Create_Directory_Fail;
                }
            }

            start = end + 1;
            end = directory.indexOf("/", start);// "/" is a token for making
            // fold.

            if (end <= start) {
                break;
            }
        }
    }
    return status;
}

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  ww . j  a  va 2s. co  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) {
            }
        }
    }
}