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:org.teiid.resource.adapter.ftp.FtpManagedConnectionFactory.java

private void afterConnectProcessing(FTPClient client) throws IOException {

    if (this.parentDirectory == null) {
        throw new IOException(UTIL.getString("parentdirectory_not_set")); //$NON-NLS-1$
    }//from ww w. j ava2  s  .  c om

    if (!client.changeWorkingDirectory(this.getParentDirectory())) {
        throw new IOException(UTIL.getString("ftp_dir_not_exist", this.getParentDirectory())); //$NON-NLS-1$
    }

    updateClientMode(client);

    client.setFileType(this.fileType);
    client.setBufferSize(this.bufferSize);

    if (this.isFtps) {
        FTPSClient ftpsClient = (FTPSClient) client;
        if (this.getAuthValue() != null) {
            ftpsClient.setAuthValue(this.authValue);
        }
        if (this.trustManager != null) {
            ftpsClient.setTrustManager(this.trustManager);
        }
        if (this.cipherSuites != null) {
            ftpsClient.setEnabledCipherSuites(this.cipherSuites);
        }
        if (this.protocols != null) {
            ftpsClient.setEnabledProtocols(this.protocols);
        }
        if (this.sessionCreation != null) {
            ftpsClient.setEnabledSessionCreation(this.sessionCreation);
        }
        if (this.useClientMode != null) {
            ftpsClient.setUseClientMode(this.useClientMode);
        }
        if (this.sessionCreation != null) {
            ftpsClient.setEnabledSessionCreation(this.sessionCreation);
        }
        if (this.keyManager != null) {
            ftpsClient.setKeyManager(this.keyManager);
        }
        if (this.needClientAuth != null) {
            ftpsClient.setNeedClientAuth(this.needClientAuth);
        }
        if (this.wantsClientAuth != null) {
            ftpsClient.setWantClientAuth(this.wantsClientAuth);
        }
    }
}

From source file:org.teiid.test.teiid4441.FTPClientFactory.java

private void afterConnectProcessing(FTPClient client) throws IOException {

    if (this.parentDirectory == null) {
        throw new IOException("parentdirectory_not_set");
    }//from   ww  w  .  j a  v a2  s  . co  m

    if (!client.changeWorkingDirectory(this.getParentDirectory())) {
        throw new IOException("ftp_dir_not_exist");
    }

    updateClientMode(client);

    client.setFileType(this.fileType);
    client.setBufferSize(this.bufferSize);

    if (this.isFtps) {
        FTPSClient ftpsClient = (FTPSClient) client;
        if (this.getAuthValue() != null) {
            ftpsClient.setAuthValue(this.authValue);
        }
        if (this.trustManager != null) {
            ftpsClient.setTrustManager(this.trustManager);
        }
        if (this.cipherSuites != null) {
            ftpsClient.setEnabledCipherSuites(this.cipherSuites);
        }
        if (this.protocols != null) {
            ftpsClient.setEnabledProtocols(this.protocols);
        }
        if (this.sessionCreation != null) {
            ftpsClient.setEnabledSessionCreation(this.sessionCreation);
        }
        if (this.useClientMode != null) {
            ftpsClient.setUseClientMode(this.useClientMode);
        }
        if (this.sessionCreation != null) {
            ftpsClient.setEnabledSessionCreation(this.sessionCreation);
        }
        if (this.keyManager != null) {
            ftpsClient.setKeyManager(this.keyManager);
        }
        if (this.needClientAuth != null) {
            ftpsClient.setNeedClientAuth(this.needClientAuth);
        }
        if (this.wantsClientAuth != null) {
            ftpsClient.setWantClientAuth(this.wantsClientAuth);
        }
    }
}

From source file:org.wso2.carbon.connector.FileFtpOverProxy.java

/**
 * Send file FTP over Proxy./*from   ww  w . j  a v a  2 s  .  c  o  m*/
 *
 * @param proxyHost      Name of the proxy host.
 * @param proxyPort      Proxy port number.
 * @param proxyUsername  User name of the proxy.
 * @param proxyPassword  Password of the proxy.
 * @param ftpServer      FTP server.
 * @param ftpPort        Port number of FTP.
 * @param ftpUsername    User name of the FTP.
 * @param ftpPassword    Password of the FTP.
 * @param messageContext he message context that is generated for processing the ftpOverHttp method.
 * @return true, if the FTP client tunnels over an HTTP proxy connection or stores a file on the server.
 */
public boolean ftpOverHttp(String proxyHost, String proxyPort, String proxyUsername, String proxyPassword,
        String ftpServer, String ftpPort, String ftpUsername, String ftpPassword,
        MessageContext messageContext) {
    String keepAliveTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.KEEP_ALIVE_TIMEOUT);
    String controlKeepAliveReplyTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.CONTROL_KEEP_ALIVE_REPLY_TIMEOUT);
    String targetPath = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.TARGET_PATH);
    String targetFile = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.TARGET_FILE);
    String binaryTransfer = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.BINARY_TRANSFER);
    String localActive = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.LOCAL_ACTIVE);
    boolean resultStatus = false;
    InputStream inputStream = null;

    final FTPClient ftp;
    if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)
            && StringUtils.isNotEmpty(proxyUsername) && StringUtils.isNotEmpty(proxyPassword)) {
        proxyHost = proxyHost.trim();
        proxyPort = proxyPort.trim();
        proxyUsername = proxyUsername.trim();
        proxyPassword = proxyPassword.trim();
        ftp = new FTPHTTPClient(proxyHost, Integer.parseInt(proxyPort), proxyUsername, proxyPassword);
    } else {
        ftp = new FTPClient();
    }
    //Set the time to wait between sending control connection keep alive messages when
    // processing file upload or download (Zero (or less) disables).
    keepAliveTimeout = keepAliveTimeout.trim();
    if (StringUtils.isNotEmpty(keepAliveTimeout)) {
        ftp.setControlKeepAliveTimeout(Long.parseLong(keepAliveTimeout.trim()));
    }
    //Set how long to wait for control keep-alive message replies.(defaults to 1000 milliseconds.)
    if (StringUtils.isNotEmpty(controlKeepAliveReplyTimeout)) {
        ftp.setControlKeepAliveReplyTimeout(Integer.parseInt(controlKeepAliveReplyTimeout.trim()));
    }
    try {
        int reply;
        ftpPort = ftpPort.trim();
        int IntFtpPort = Integer.parseInt(ftpPort);
        if (IntFtpPort > 0) {
            ftp.connect(ftpServer, IntFtpPort);
        } else {
            ftpServer = ftpServer.trim();
            ftp.connect(ftpServer);
        }
        if (log.isDebugEnabled()) {
            log.debug(
                    " Connected to " + ftpServer + " on " + (IntFtpPort > 0 ? ftpPort : ftp.getDefaultPort()));
        }
        // After connection attempt, should check the reply code to verify success.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP ftpServer refused connection.");
        }
        if (ftp.login(ftpUsername, ftpPassword)) {
            if (StringUtils.isNotEmpty(binaryTransfer)) {
                if (Boolean.valueOf(binaryTransfer.trim())) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                } else {
                    // in theory this should not be necessary as servers should default to ASCII
                    // but they don't all do so - see NET-500
                    ftp.setFileType(FTP.ASCII_FILE_TYPE);
                }
            } else {
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
            }
            // Use passive mode as default because most of us are behind firewalls these days.
            if (StringUtils.isNotEmpty(localActive)) {
                if (Boolean.valueOf(localActive.trim())) {
                    ftp.enterLocalActiveMode();
                } else {
                    ftp.enterLocalPassiveMode();
                }
            } else {
                ftp.enterLocalPassiveMode();
            }
            inputStream = new ByteArrayInputStream(
                    messageContext.getEnvelope().getBody().getFirstElement().toString().getBytes());
            if (StringUtils.isNotEmpty(targetPath)) {
                ftp.changeWorkingDirectory(targetPath);
                ftp.storeFile(targetFile, inputStream);
                if (log.isDebugEnabled()) {
                    log.debug("Successfully FTP transfered the File");
                }
            }
            // check that control connection is working
            if (log.isDebugEnabled()) {
                log.debug("The code received from the server." + ftp.noop());
            }
            resultStatus = true;
        } else {
            ftp.logout();
            handleException("Error while login ftp server.", messageContext);
        }
    } catch (FTPConnectionClosedException e) {
        // log.error("Server closed connection " + e.getMessage(), e);
        handleException("Server closed connection: " + e.getMessage(), e, messageContext);
    } catch (IOException e) {
        //log.error("Error occurred while uploading:" + e.getMessage(), e);
        handleException("Could not connect to FTP ftpServer: " + e.getMessage(), e, messageContext);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
                ftp.logout();
            } catch (IOException f) {
                log.error("Error while disconnecting/logging out ftp server");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException f) {
                log.error("Error while closing inputStream");
            }
        }
    }
    return resultStatus;
}

From source file:org.wso2.carbon.connector.FileFtpOverProxyConnector.java

/**
 * Send file FTP over Proxy./*from www  .jav  a2s  . c  o m*/
 *
 * @param messageContext The message context that is generated for processing the file.
 * @return true, if the FTP client tunnels over an HTTP proxy connection or stores a file on the server.
 *
 */
public boolean ftpOverHttpProxy(MessageContext messageContext) {
    String proxyHost = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_HOST));
    String proxyPort = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_PORT));
    String proxyUsername = StringUtils.trim(
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_USERNAME));
    String proxyPassword = StringUtils.trim(
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_PASSWORD));
    String ftpHost = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_SERVER));
    String ftpPort = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_PORT));
    String ftpUsername = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_USERNAME));
    String ftpPassword = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_PASSWORD));
    String keepAliveTimeout = StringUtils.trim(
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.KEEP_ALIVE_TIMEOUT));
    String controlKeepAliveReplyTimeout = StringUtils.trim((String) ConnectorUtils
            .lookupTemplateParamater(messageContext, FileConstants.CONTROL_KEEP_ALIVE_REPLY_TIMEOUT));
    String targetPath = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.TARGET_PATH));
    String targetFile = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.TARGET_FILE));
    String activeMode = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.ACTIVE_MODE));
    String fileType = StringUtils
            .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_TYPE));
    boolean activeModeParameter = false;

    if (StringUtils.isEmpty(keepAliveTimeout)) {
        keepAliveTimeout = FileConstants.DEFAULT_KEEP_ALIVE_TIMEOUT;
    }
    if (StringUtils.isEmpty(controlKeepAliveReplyTimeout)) {
        controlKeepAliveReplyTimeout = FileConstants.DEFAULT_CONTROL_KEEP_ALIVE_REPLY_TIMEOUT;
    }
    if (StringUtils.isNotEmpty(activeMode)) {
        activeModeParameter = Boolean.parseBoolean(activeMode);
    }

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)
            && StringUtils.isNotEmpty(proxyUsername) && StringUtils.isNotEmpty(proxyPassword)) {
        ftp = new FTPHTTPClient(proxyHost, Integer.parseInt(proxyPort), proxyUsername, proxyPassword);
    }
    //Set the time to wait between sending control connection keep alive messages when processing file upload or
    // download (Zero (or less) disables).
    ftp.setControlKeepAliveTimeout(Long.parseLong(keepAliveTimeout));
    //Set how long to wait for control keep-alive message replies.(defaults to 1000 milliseconds.)
    ftp.setControlKeepAliveReplyTimeout(Integer.parseInt(controlKeepAliveReplyTimeout));
    try {
        int reply;
        int IntFtpPort = Integer.parseInt(ftpPort);
        if (IntFtpPort > 0) {
            ftp.connect(ftpHost, IntFtpPort);
        } else {
            ftp.connect(ftpHost);
        }
        if (log.isDebugEnabled()) {
            log.debug(" Connected to " + ftpHost + " on " + (IntFtpPort > 0 ? ftpPort : ftp.getDefaultPort()));
        }
        // After connection attempt, should check the reply code to verify success.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP ftpServer refused connection.");
        }
        if (!ftp.login(ftpUsername, ftpPassword)) {
            ftp.logout();
            throw new SynapseException("Error while login ftp server.");
        }
        setFileType(fileType, ftp);

        // Use passive mode as default because most of us are behind firewalls these days.
        if (activeModeParameter) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }
        inputStream = new ByteArrayInputStream(
                messageContext.getEnvelope().getBody().getFirstElement().toString().getBytes());
        if (StringUtils.isNotEmpty(targetPath)) {
            ftp.changeWorkingDirectory(targetPath);
            ftp.storeFile(targetFile, inputStream);
            if (log.isDebugEnabled()) {
                log.debug("Successfully FTP server transferred the File");
            }
        }
        // check that control connection is working
        if (log.isDebugEnabled()) {
            log.debug("The code received from the server." + ftp.noop());
        }
    } catch (IOException e) {
        throw new SynapseException("Could not connect to FTP Server", e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
                ftp.logout();
            } catch (IOException f) {
                log.error("Error while disconnecting/logging out ftp server");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException f) {
                log.error("Error while closing inputStream");
            }
        }
    }
    return true;
}

From source file:org.wso2.iot.agent.services.FileDownloadService.java

/**
 * This method downloads the file using sftp client.
 *
 * @param operation      - operation object.
 * @param host           - host address.
 * @param ftpUserName    - ftp user name.
 * @param ftpPassword    - ftp password.
 * @param savingLocation - location in the device to save the file.
 * @param fileName       - name of the file to download.
 * @param serverPort     - ftp server port.
 * @param fileDirectory  - the directory of the file in FTP server.
 * @throws AndroidAgentException - Android agent exception.
 *//*from   w  w  w.  j a  v  a2  s  . co  m*/
private void downloadFileUsingFTPClient(Operation operation, String host, String ftpUserName,
        String ftpPassword, String savingLocation, String fileName, int serverPort, String fileDirectory)
        throws AndroidAgentException {

    FTPClient ftpClient = new FTPClient();
    FileOutputStream fileOutputStream = null;
    OutputStream outputStream = null;
    String response;
    try {
        ftpClient.connect(host, serverPort);
        if (ftpClient.login(ftpUserName, ftpPassword)) {
            ftpClient.enterLocalPassiveMode();
            fileOutputStream = new FileOutputStream(savingLocation + File.separator + fileName);
            outputStream = new BufferedOutputStream(fileOutputStream);
            ftpClient.changeWorkingDirectory(fileDirectory);
            if (ftpClient.retrieveFile(fileName, outputStream)) {
                response = "File uploaded to the device successfully ( " + fileName + " ).";
                operation.setStatus(resources.getString(R.string.operation_value_completed));
            } else {
                response = "File uploaded to the device not completed ( " + fileName + " ).";
                operation.setStatus(resources.getString(R.string.operation_value_error));
            }
            operation.setOperationResponse(response);
        } else {
            downloadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, savingLocation, fileName,
                    serverPort, fileDirectory);
        }
    } catch (FTPConnectionClosedException | ConnectException e) {
        downloadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, savingLocation, fileName,
                serverPort, fileDirectory);
    } catch (IOException e) {
        handleOperationError(operation, fileTransferExceptionCause(e, fileName), e);
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ignored) {
        }
        cleanupStreams(null, outputStream, null, fileOutputStream, null, null, null, null);
    }
}

From source file:org.wso2.iot.agent.services.FileUploadService.java

/**
 * File upload operation using an FTP client.
 *
 * @param operation       - operation object.
 * @param host            - host name./*from   ww  w  . j  a v a 2 s  .  c  o  m*/
 * @param ftpUserName     - ftp user name.
 * @param ftpPassword     - ftp password.
 * @param uploadDirectory - ftp directory to upload file.
 * @param fileLocation    - local file location.
 * @param serverPort      - ftp port to connect.
 * @throws AndroidAgentException - AndroidAgent exception.
 */
private void uploadFileUsingFTPClient(Operation operation, String host, String ftpUserName, String ftpPassword,
        String uploadDirectory, String fileLocation, int serverPort) throws AndroidAgentException {
    FTPClient ftpClient = new FTPClient();
    String fileName = null;
    InputStream inputStream = null;
    String response;
    try {
        File file = new File(fileLocation);
        fileName = file.getName();
        ftpClient.connect(host, serverPort);
        ftpClient.enterLocalPassiveMode();
        ftpClient.login(ftpUserName, ftpPassword);
        inputStream = new FileInputStream(file);
        ftpClient.changeWorkingDirectory(uploadDirectory);
        if (ftpClient.storeFile(file.getName(), inputStream)) {
            response = "File uploaded from the device completed ( " + fileName + " ).";
            operation.setStatus(resources.getString(R.string.operation_value_completed));
        } else {
            response = "File uploaded from the device not completed ( " + fileName + " ).";
            operation.setStatus(resources.getString(R.string.operation_value_error));
        }
        operation.setOperationResponse(response);
    } catch (FTPConnectionClosedException e) {
        uploadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, uploadDirectory, fileLocation,
                serverPort);
    } catch (IOException e) {
        handleOperationError(operation, fileTransferExceptionCause(e, fileName), e, resources);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.logout();
            } catch (IOException ignored) {
            }
        }
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException ignored) {
            }
        }
        cleanupStreams(inputStream, null, null, null, null, null, null, null);
    }
}

From source file:Proiect.uploadFTP.java

public void actionFTP() {
    adressf.addCaretListener(new CaretListener() {
        public void caretUpdate(CaretEvent e) {
            InetAddress thisIp;/*  w w  w  .  j av  a  2s  .c  om*/
            try {
                thisIp = InetAddress.getLocalHost();
                titleFTP.setText("Connection: " + thisIp.getHostAddress() + " -> " + adressf.getText());
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
        }
    });

    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            saveState();
            uploadFTP.dispose();
            tree.dispose();
        }
    });

    connect.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            FTPClient client = new FTPClient();
            FileInputStream fis = null;
            String pass = String.valueOf(passf.getPassword());
            try {
                if (filename == null) {
                    status.setText("File does not exist!");
                } else {
                    // Server address
                    client.connect(adressf.getText());
                    // Login credentials
                    client.login(userf.getText(), pass);
                    if (client.isConnected()) {
                        status.setText("Succesfull transfer!");
                        // File type
                        client.setFileType(FTP.BINARY_FILE_TYPE);
                        // File location
                        File file = new File(filepath);
                        fis = new FileInputStream(file);
                        // Change the folder on the server
                        client.changeWorkingDirectory(folderf.getText());
                        // Save the file on the server
                        client.storeFile(filename, fis);
                    } else {
                        status.setText("Transfer failed!");
                    }
                }
                client.logout();
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }
        }
    });

    browsef.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int retval = chooserf.showOpenDialog(chooserf);
            if (retval == JFileChooser.APPROVE_OPTION) {
                status.setText("");
                filename = chooserf.getSelectedFile().getName().toString();
                filepath = chooserf.getSelectedFile().getPath();
                filenf.setText(chooserf.getSelectedFile().getName().toString());
            }
        }
    });

    adv.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            tree.setSize(220, uploadFTP.getHeight());
            tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
            tree.setResizable(false);
            tree.setIconImage(Toolkit.getDefaultToolkit()
                    .getImage(getClass().getClassLoader().getResource("assets/ico.png")));
            tree.setUndecorated(true);
            tree.getRootPane().setBorder(BorderFactory.createLineBorder(Encrypter.color_black, 2));
            tree.setVisible(true);
            tree.setLayout(new BorderLayout());

            JLabel labeltree = new JLabel("Server documents");
            labeltree.setOpaque(true);
            labeltree.setBackground(Encrypter.color_light);
            labeltree.setBorder(BorderFactory.createMatteBorder(8, 10, 10, 0, Encrypter.color_light));
            labeltree.setForeground(Encrypter.color_blue);
            labeltree.setFont(Encrypter.font16);

            JButton refresh = new JButton("");
            ImageIcon refresh_icon = getImageIcon("assets/icons/refresh.png");
            refresh.setIcon(refresh_icon);
            refresh.setBackground(Encrypter.color_light);
            refresh.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
            refresh.setForeground(Encrypter.color_black);
            refresh.setFont(Encrypter.font16);
            refresh.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

            final FTPClient client = new FTPClient();
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(adressf.getText());
            DefaultMutableTreeNode files = null;
            DefaultMutableTreeNode leaf = null;

            final JTree tree_view = new JTree(top);
            tree_view.setForeground(Encrypter.color_black);
            tree_view.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
            tree_view.putClientProperty("JTree.lineStyle", "None");
            tree_view.setBackground(Encrypter.color_light);
            JScrollPane scrolltree = new JScrollPane(tree_view);
            scrolltree.setBackground(Encrypter.color_light);
            scrolltree.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));

            UIManager.put("Tree.textBackground", Encrypter.color_light);
            UIManager.put("Tree.selectionBackground", Encrypter.color_blue);
            UIManager.put("Tree.selectionBorderColor", Encrypter.color_blue);

            tree_view.updateUI();

            final String pass = String.valueOf(passf.getPassword());
            try {
                client.connect(adressf.getText());
                client.login(userf.getText(), pass);
                client.enterLocalPassiveMode();
                if (client.isConnected()) {
                    try {
                        FTPFile[] ftpFiles = client.listFiles();
                        for (FTPFile ftpFile : ftpFiles) {
                            files = new DefaultMutableTreeNode(ftpFile.getName());
                            top.add(files);
                            if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) {
                                FTPFile[] ftpFiles1 = client.listFiles(ftpFile.getName());
                                for (FTPFile ftpFile1 : ftpFiles1) {
                                    leaf = new DefaultMutableTreeNode(ftpFile1.getName());
                                    files.add(leaf);
                                }
                            }
                        }
                    } catch (IOException e1) {
                        Encrypter.printException(e1);
                    }
                    client.disconnect();
                } else {
                    status.setText("Failed connection!");
                }
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }

            tree.add(labeltree, BorderLayout.NORTH);
            tree.add(scrolltree, BorderLayout.CENTER);
            tree.add(refresh, BorderLayout.SOUTH);

            uploadFTP.addComponentListener(new ComponentListener() {

                public void componentMoved(ComponentEvent e) {
                    tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
                }

                public void componentShown(ComponentEvent e) {
                }

                public void componentResized(ComponentEvent e) {
                }

                public void componentHidden(ComponentEvent e) {
                }
            });

            uploadFTP.addWindowListener(new WindowListener() {
                public void windowActivated(WindowEvent e) {
                    tree.toFront();
                }

                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                }

                public void windowClosed(WindowEvent e) {
                }
            });

            refresh.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    tree.dispose();
                    tree.setVisible(true);
                }
            });
        }
    });

}

From source file:rapture.ftp.common.FTPConnection.java

public boolean sendFile(InputStream stream, String fileName) throws IOException {
    int slash = fileName.lastIndexOf('/');
    FTPClient client = getFtpClient();
    if (slash > 0) {
        client.changeWorkingDirectory(fileName.substring(0, slash));
    }// www .ja va2  s.  co m
    return client.storeFile(fileName.substring(slash + 1), stream);
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

private static List<Object> _checkResourcePath(FTPClient connection, String remoteResourcePath,
        String actionName, boolean isDirectory) throws Exception {
    FTPFile[] resources = null;/*from   w  ww  .  j a va 2s. co  m*/
    List<Object> connectionObject = new LinkedList<Object>();

    boolean remoteDirectoryExists = connection.changeWorkingDirectory(remoteResourcePath);

    if (isDirectory) {
        int returnCode = connection.getReplyCode();

        // check if the remote directory exists
        if (returnCode == 550) {
            throw new Exception(ErrorMessages.err_FTC003);
        }
    }

    connectionObject.add(remoteDirectoryExists);

    // check if the user has rights as to the resource
    resources = connection.listFiles(remoteResourcePath);

    //      if (!actionName.equals("list-resources") && !remoteDirectoryExists) {
    //         // System.out.println("permissions; "
    //         // + resources[0].hasPermission(FTPFile.USER_ACCESS,
    //         // FTPFile.READ_PERMISSION));
    //      }

    // if (!remoteDirectoryExists) {
    // FTPconnection.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
    // is = FTPconnection.retrieveFileStream(remoteResourcePath);
    // if (is == null || resources.length == 0) {
    // throw new
    // Exception(ErrorMessages.err_FTC004);
    // }
    // }

    connectionObject.add(resources);

    return connectionObject;
}

From source file:ru.in360.FTPUtil.java

public static void saveFilesToServer(FTPClient ftp, String remoteDest, File localSrc) throws IOException {
    //        FTPClient ftp = new FTPClient();
    ////from  ww  w  . j  av  a 2s. c  o m
    //        ftp.connect("46.8.19.232", 21);
    //
    //
    //        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
    //            ftp.disconnect();
    //            System.out.println("FTP not disconnected");
    //        }
    //        ftp.login("admin", "fa43limited");
    //        ftp.enterLocalPassiveMode();
    System.out.println("Connected to server .");

    System.out.println("remote directory: " + remoteDest);
    ftp.changeWorkingDirectory(remoteDest);
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

    System.out.println("upload: " + localSrc.getPath());
    upload(localSrc, ftp);
    System.out.println(ftp.getReplyString());

}