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

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

Introduction

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

Prototype

public String printWorkingDirectory() throws IOException 

Source Link

Document

Returns the pathname of the current working directory.

Usage

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();/*w  w w.j a v  a2  s  .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:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 *//* w  w  w.  j  a v a 2 s. c o m*/
@Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000)
public void checkFiles() {
    log.info("Checking FTP files at DMI.");
    FTPClient client = new FTPClient();
    try {
        client.setDataTimeout(20 * 1000);
        client.setBufferSize(1024 * 1024);
        client.connect(hostname);
        if (client.login("anonymous", "")) {
            try {
                client.enterLocalPassiveMode();
                client.setFileType(FTP.BINARY_FILE_TYPE);
                for (ForecastConfiguration configuration : configurations) {
                    // DMI creates a Newest link once all files have been created
                    if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) {
                        if (client.getReplyCode() != 250) {
                            log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode());
                        }
                        String workingDirectory = new File(client.printWorkingDirectory()).getName();
                        String previousNewest = newestDirectories.get(configuration);
                        if (!workingDirectory.equals(previousNewest)) {
                            // a new directory for this configuration is available on the server
                            FTPFile[] listFiles = client.listFiles();
                            List<FTPFile> files = Arrays.stream(listFiles)
                                    .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches())
                                    .collect(Collectors.toList());

                            try {
                                Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory,
                                        files);
                                gridWeatherService.newFiles(localFiles, configuration);
                            } catch (IOException e) {
                                log.warn("Unable to get new weather files from DMI", e);
                            }

                            if (previousNewest != null) {
                                File previous = new File(tempDirLocation, previousNewest);
                                deleteRecursively(previous);
                            }
                            newestDirectories.put(configuration, workingDirectory);
                        }

                    } else {
                        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
                        log.error("Unable to change ftp directory to {}", configuration.getFolder());
                    }
                }
            } finally {
                try {
                    client.logout();
                } catch (IOException e) {
                    log.info("Failed to logout", e);
                }
            }
        } else {
            gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
            log.error("Unable to login to {}", hostname);
        }

    } catch (IOException e) {
        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
        log.error("Unable to update weather files from DMI", e);
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            log.info("Failed to disconnect", e);
        }
    }
    log.info("Check completed.");
}

From source file:com.tobias.vocabulary_trainer.UpdateVocabularies.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_vocabularies_layout);
    prefs = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    serverAdresseEditText = (EditText) findViewById(R.id.server_adresse_edit_text);
    serverUsernameEditText = (EditText) findViewById(R.id.server_username_edit_text);
    serverPasswordEditText = (EditText) findViewById(R.id.server_password_edit_text);
    serverPortEditText = (EditText) findViewById(R.id.server_port_edit_text);
    serverFileEditText = (EditText) findViewById(R.id.server_file_edit_text);
    localFileEditText = (EditText) findViewById(R.id.local_file_edit_text);

    vocabularies = new VocabularyData(this);
    System.out.println("before updateUIFromPreferences();");
    updateUIFromPreferences();//from   w w  w. j a  va2s.  c  om
    System.out.println("after updateUIFromPreferences();");

    final Button ServerOkButton = (Button) findViewById(R.id.server_ok);
    ServerOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("ServerOKButton pressed");
            savePreferences();
            InputStream in;
            String serverAdresse = serverAdresseEditText.getText().toString();
            String serverUsername = serverUsernameEditText.getText().toString();
            String serverPassword = serverPasswordEditText.getText().toString();
            int serverPort = Integer.parseInt(serverPortEditText.getText().toString());
            String serverFile = serverFileEditText.getText().toString();

            FTPClient ftp;
            ftp = new FTPClient();
            try {
                int reply;
                System.out.println("try to connect to ftp server");
                ftp.connect(serverAdresse, serverPort);
                System.out.print(ftp.getReplyString());
                // After connection attempt, you should check the reply code to verify
                // success.
                reply = ftp.getReplyCode();
                if (FTPReply.isPositiveCompletion(reply)) {
                    System.out.println("connected to ftp server");
                } else {
                    ftp.disconnect();
                    System.out.println("FTP server refused connection.");
                }

                // transfer files
                System.out.println("try to login");
                ftp.login(serverUsername, serverPassword);
                System.out.println("current working directory: " + ftp.printWorkingDirectory());
                System.out.println("try to start downloading");
                in = ftp.retrieveFileStream(serverFile);
                // files transferred
                //write to database and textfile on sdcard
                vocabularies.readVocabularies(in, false);
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                        // do nothing
                    }
                }
            }
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button LocalFileOkButton = (Button) findViewById(R.id.local_file_ok);
    LocalFileOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            File f = new File(Environment.getExternalStorageDirectory(),
                    localFileEditText.getText().toString());
            savePreferences();
            vocabularies.readVocabularies(f, false);
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button CancelButton = (Button) findViewById(R.id.Cancel);
    CancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    vocabularies.close();
}

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

private FTPFile existsFile(FTPClient client, String strPath, boolean isFile) throws PageException, IOException {
    strPath = strPath.trim();//from  w w  w  . j  a  v  a2s.c om
    if (strPath.equals("/")) {
        FTPFile file = new FTPFile();
        file.setName("/");
        file.setType(FTPFile.DIRECTORY_TYPE);
        return file;
    }

    // get parent path
    FTPPath path = new FTPPath(client.printWorkingDirectory(), strPath);
    String p = path.getPath();
    String n = path.getName();

    strPath = p;
    if ("//".equals(p))
        strPath = "/";
    if (isFile)
        strPath += n;

    // when directory
    FTPFile[] files = null;
    try {
        files = client.listFiles(strPath);
    } catch (IOException e) {
    }

    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().equalsIgnoreCase(n)) {
                return files[i];
            }
        }

    }
    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;//from   w  ww.  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.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Create the specified directory on the remote host.
 *
 * @param ftp The FTP client connection/*  w w  w  . j  a  va 2  s.  c o m*/
 * @param dir The directory to create (format must be correct for host
 *      type)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if ignoreNoncriticalErrors has not been set to true
 *         and a directory could not be created, for instance because it was
 *         already existing. Precisely, the codes 521, 550 and 553 will trigger
 *         a BuildException
 */
protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (verbose) {
        if (dir.indexOf("/") == 0 || workingDirectory == null) {
            log("Creating directory: " + dir + " in /");
        } else {
            log("Creating directory: " + dir + " in " + workingDirectory);
        }
    }
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir = "";
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        log("Checking " + subdir, Project.MSG_DEBUG);
        if (!ftp.changeWorkingDirectory(subdir)) {
            if (!ftp.makeDirectory(subdir)) {
                // codes 521, 550 and 553 can be produced by FTP Servers
                //  to indicate that an attempt to create a directory has
                //  failed because the directory already exists.
                int rc = ftp.getReplyCode();
                if (!(ignoreNoncriticalErrors
                        && (rc == FTPReply.CODE_550 || rc == FTPReply.CODE_553 || rc == CODE_521))) {
                    throw new BuildException("could not create directory: " + ftp.getReplyString());
                }
                if (verbose) {
                    log("Directory already exists");
                }
            } else {
                if (verbose) {
                    log("Directory created OK");
                }
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * check FTPFiles to check whether they function as directories too
 * the FTPFile API seem to make directory and symbolic links incompatible
 * we want to find out if we can cd to a symbolic link
 * @param dir  the parent directory of the file to test
 * @param file the file to test/*ww w  . j a  v  a2s .c o  m*/
 * @return true if it is possible to cd to this directory
 * @since ant 1.6
 */
private boolean isFunctioningAsDirectory(FTPClient ftp, String dir, FTPFile file) {
    boolean result = false;
    String currentWorkingDir = null;
    if (file.isDirectory()) {
        return true;
    } else if (file.isFile()) {
        return false;
    }
    try {
        currentWorkingDir = ftp.printWorkingDirectory();
    } catch (IOException ioe) {
        getProject().log("could not find current working directory " + dir + " while checking a symlink",
                Project.MSG_DEBUG);
    }
    if (currentWorkingDir != null) {
        try {
            result = ftp.changeWorkingDirectory(file.getLink());
        } catch (IOException ioe) {
            getProject().log("could not cd to " + file.getLink() + " while checking a symlink",
                    Project.MSG_DEBUG);
        }
        if (result) {
            boolean comeback = false;
            try {
                comeback = ftp.changeWorkingDirectory(currentWorkingDir);
            } catch (IOException ioe) {
                getProject().log("could not cd back to " + dir + " while checking a symlink", Project.MSG_ERR);
            } finally {
                if (!comeback) {
                    throw new BuildException("could not cd back to " + dir + " while checking a symlink");
                }
            }
        }
    }
    return result;
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Creates all parent directories specified in a complete relative
 * pathname. Attempts to create existing directories will not cause
 * errors.// www .  j  a v a 2s .c  o m
 *
 * @param ftp the FTP client instance to use to execute FTP actions on
 *        the remote server.
 * @param filename the name of the file whose parents should be created.
 * @throws IOException under non documented circumstances
 * @throws BuildException if it is impossible to cd to a remote directory
 *
 */
protected void createParents(FTPClient ftp, String filename) throws IOException, BuildException {

    File dir = new File(filename);
    if (dirCache.contains(dir)) {
        return;
    }

    Vector parents = new Vector();
    String dirname;

    while ((dirname = dir.getParent()) != null) {
        File checkDir = new File(dirname);
        if (dirCache.contains(checkDir)) {
            break;
        }
        dir = checkDir;
        parents.addElement(dir);
    }

    // find first non cached dir
    int i = parents.size() - 1;

    if (i >= 0) {
        String cwd = ftp.printWorkingDirectory();
        String parent = dir.getParent();
        if (parent != null) {
            if (!ftp.changeWorkingDirectory(resolveFile(parent))) {
                throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
            }
        }

        while (i >= 0) {
            dir = (File) parents.elementAt(i--);
            // check if dir exists by trying to change into it.
            if (!ftp.changeWorkingDirectory(dir.getName())) {
                // could not change to it - try to create it
                log("creating remote directory " + resolveFile(dir.getPath()), Project.MSG_VERBOSE);
                if (!ftp.makeDirectory(dir.getName())) {
                    handleMkDirFailure(ftp);
                }
                if (!ftp.changeWorkingDirectory(dir.getName())) {
                    throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
                }
            }
            dirCache.add(dir);
        }
        ftp.changeWorkingDirectory(cwd);
    }
}

From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();//  ww  w . ja  v a  2  s . c o  m
            return client;
        } else {
            // this flowFile is going to a different destination, reset
            // session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).evaluateAttributeExpressions(flowFile)
            .getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();//from  ww  w .  j  av  a2s . co  m
            return client;
        } else {
            // this flowFile is going to a different destination, reset session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    // additional  
    FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
    final String ftpClientConfig = ctx.getProperty(FTP_CLIENT_CONFIG_SYST).getValue();
    if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_UNIX)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    } else if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_NT)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}