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:convcao.com.agent.ConvcaoNeptusInteraction.java

private void upload(String ftpServer, String pathDirectory, String sourcePathDirectory, String userName,
        String password, String filename) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;/*from   w  ww  .ja  va  2s .c  om*/

    try {
        client.connect(ftpServer);
        client.login(userName, password);
        client.enterLocalPassiveMode();
        client.setFileType(FTP.BINARY_FILE_TYPE);
        fis = new FileInputStream(sourcePathDirectory + filename);
        client.changeWorkingDirectory("/" + pathDirectory);

        client.storeFile(filename, fis);

        System.out.println(
                "The file " + sourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename);
        client.logout();

        //Report = "File: " + filename + " Uploaded Successfully ";
    } catch (Exception exp) {
        exp.printStackTrace();
        report = "Server Error";
        jLabel6.setText(report);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.tumblr.maximopro.iface.router.FTPHandler.java

@Override
public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException {
    byte[] encodedData = super.invoke(metaData, data);
    this.metaData = metaData;

    FTPClient ftp;
    if (enableSSL()) {
        FTPSClient ftps = new FTPSClient(isImplicit());
        ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        ftp = ftps;/*from  w w w.  j  a v a 2 s .  c om*/
    } else {
        ftp = new FTPClient();
    }

    InputStream is = null;
    try {

        if (getTimeout() > 0) {
            ftp.setDefaultTimeout(getTimeout());
        }

        if (getBufferSize() > 0) {
            ftp.setBufferSize(getBufferSize());
        }

        if (getNoDelay()) {
            ftp.setTcpNoDelay(getNoDelay());
        }

        ftp.connect(getHostname(), getPort());

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        if (!ftp.login(getUsername(), getPassword())) {
            ftp.logout();
            ftp.disconnect();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (enableActive()) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        is = new ByteArrayInputStream(encodedData);

        String remoteFileName = getFileName(metaData);

        ftp.changeWorkingDirectory("/");
        if (createDirectoryStructure(ftp, getDirName().split("/"))) {
            ftp.storeFile(remoteFileName, is);
        } else {
            throw new MXApplicationException("iface", "cannotcreatedir");
        }

        ftp.logout();
    } catch (MXException e) {
        throw e;
    } catch (SocketException e) {
        throw new MXApplicationException("iface", "ftpsocketerror", e);
    } catch (IOException e) {
        throw new MXApplicationException("iface", "ftpioerror", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }

        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }
    }

    return null;
}

From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java

@SuppressWarnings("fallthrough")
private int transferFiles(FTPClient ftp, File[] files, IProgressMonitor monitor, IAdaptable adaptable,
        boolean deleteTransferred) throws IOException {
    if (monitor.isCanceled())
        return -1;
    FTPFile[] oldfiles = ftp.listFiles();
    if (monitor.isCanceled())
        return -1;
    Map<String, FTPFile> names = new HashMap<String, FTPFile>();
    for (FTPFile file : oldfiles)
        names.put(file.getName(), file);
    int n = 0;/*from   ww  w.  j  a  v  a 2 s .  c om*/
    for (File file : files) {
        final String filename = file.getName();
        FTPFile ftpFile = names.get(filename);
        if (file.isDirectory()) {
            if (ftpFile != null) {
                if (!ftpFile.isDirectory())
                    throw new IOException(
                            NLS.bind(Messages.FtpAccount_cannot_replace_file_with_subdir, filename));
                boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename));
                if (!result)
                    throw new IOException(NLS.bind(Messages.FtpAccount_cannot_change_to_working_dir, filename));
                // System.out.println(filename + " is new directory"); //$NON-NLS-1$
            } else {
                ftp.makeDirectory(filename);
                boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename));
                if (!result)
                    throw new IOException(Messages.FtpAccount_creation_of_subdir_failed);
                // System.out.println(filename + " is new directory"); //$NON-NLS-1$
            }
            if (monitor.isCanceled())
                return -1;
            int c = transferFiles(ftp, file.listFiles(), monitor, adaptable, deleteTransferred);
            if (c < 0)
                return -1;
            n += c;
            ftp.changeToParentDirectory();
            // System.out.println("Returned to parent directory"); //$NON-NLS-1$
        } else {
            if (ftpFile != null) {
                if (ftpFile.isDirectory())
                    throw new IOException(
                            NLS.bind(Messages.FtpAccount_cannot_replace_subdir_with_file, filename));
                if (skipAll) {
                    if (deleteTransferred)
                        file.delete();
                    continue;
                }
                if (!replaceAll) {
                    if (monitor.isCanceled())
                        return -1;
                    int ret = 4;
                    IDbErrorHandler errorHandler = Core.getCore().getErrorHandler();
                    if (errorHandler != null) {
                        String[] buttons = (filecount > 1)
                                ? new String[] { Messages.FtpAccount_overwrite,
                                        Messages.FtpAccount_overwrite_all, IDialogConstants.SKIP_LABEL,
                                        Messages.FtpAccount_skip_all, IDialogConstants.CANCEL_LABEL }
                                : new String[] { Messages.FtpAccount_overwrite, IDialogConstants.SKIP_LABEL,
                                        IDialogConstants.CANCEL_LABEL };
                        ret = errorHandler.showMessageDialog(Messages.FtpAccount_file_already_exists, null,
                                NLS.bind(Messages.FtpAccount_file_exists_overwrite, filename),
                                MessageDialog.QUESTION, buttons, 0, adaptable);
                    }
                    if (filecount > 1) {
                        switch (ret) {
                        case 0:
                            break;
                        case 1:
                            replaceAll = true;
                            break;
                        case 3:
                            skipAll = true;
                            /* FALL-THROUGH */
                        case 2:
                            if (deleteTransferred)
                                file.delete();
                            continue;
                        default:
                            return -1;
                        }
                    } else {
                        switch (ret) {
                        case 0:
                            break;
                        case 1:
                            if (deleteTransferred)
                                file.delete();
                            continue;
                        default:
                            return -1;
                        }
                    }
                }
                ftp.deleteFile(Core.encodeUrlSegment(filename));
                //               System.out.println(filename + " deleted"); //$NON-NLS-1$
            }
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
                ftp.storeFile(Core.encodeUrlSegment(filename), in);
                //               System.out.println(filename + " stored"); //$NON-NLS-1$
                n++;
            } finally {
                if (deleteTransferred)
                    file.delete();
                monitor.worked(1);
            }
        }
    }
    return n;
}

From source file:com.thebigbang.ftpclient.FTPOperation.java

/**
 * will force keep the device turned on for all the operation duration.
 * @param params//from  www.ja v a  2s  . c  o  m
 * @return 
 */
@SuppressLint("Wakelock")
@SuppressWarnings("deprecation")
@Override
protected Boolean doInBackground(FTPBundle... params) {
    Thread.currentThread().setName("FTPOperationWorker");
    for (final FTPBundle bundle : params) {

        FTPClient ftp = new FTPClient();
        PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client");
        try {
            // setup ftp connection:
            InetAddress addr = InetAddress.getByName(bundle.FTPServerHost);
            //set here the timeout.
            TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() {
                @Override
                public void Occurred(TimeoutException e) {
                    bundle.Exception = e;
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                    publishProgress(bundle);
                }
            });
            timeout.start();
            ftp.connect(addr, bundle.FTPServerPort);
            int reply = ftp.getReplyCode();
            timeout.Stop();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new IOException("connection refuse");
            }
            ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword);
            if (bundle.OperationType == FTPOperationType.Connect) {
                bundle.OperationStatus = FTPOperationStatus.Succed;
                publishProgress(bundle);
                continue;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();

            w.acquire();
            // then switch between enum of operation types.
            if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.GetData) {
                String finalFPFi = bundle.LocalFilePathName;
                // The remote filename to be downloaded.
                if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") {
                    File f = new File(bundle.LocalWorkingDirectory);
                    f.mkdirs();

                    finalFPFi = bundle.LocalWorkingDirectory + finalFPFi;
                }
                FileOutputStream fos = new FileOutputStream(finalFPFi);

                // Download file from FTP server
                String finalFileN = bundle.RemoteFilePathName;
                if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") {
                    finalFileN = bundle.RemoteWorkingDirectory + finalFileN;
                }
                boolean b = ftp.retrieveFile(finalFileN, fos);
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                fos.close();

            } else if (bundle.OperationType == FTPOperationType.SendData) {
                InputStream istr = new FileInputStream(bundle.LocalFilePathName);
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr);
                istr.close();
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
            } else if (bundle.OperationType == FTPOperationType.DeleteData) {
                throw new IOException("DeleteData is Not yet implemented");
            }

            ftp.disconnect();
            // then finish/return.
            //publishProgress(bundle);
        } catch (IOException e) {
            e.printStackTrace();
            bundle.Exception = e;
            bundle.OperationStatus = FTPOperationStatus.Failed;
        }
        try {
            w.release();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
        publishProgress(bundle);
    }
    return true;
}

From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

public void fetch(final FtpSubscription ftpSubscription) {
    if (_log.isDebugEnabled()) {
        _log.debug("fetching " + ftpSubscription);
    }/*from  w w w . ja  v  a2 s  .  c om*/
    final FTPClient ftp = new FTPClient();
    ftp.setControlKeepAliveTimeout(30);
    ftp.setControlKeepAliveReplyTimeout(30);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    try {
        int reply;
        ftp.connect(ftpSubscription.getFtpHost());
        _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (final IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }
    boolean error = false;
    __main: try {
        if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) {
            ftp.logout();
            error = true;
            break __main;
        }
        _log.info("Remote system is " + ftp.getSystemType());
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        //ftp.enterLocalActiveMode();
        ftp.enterLocalPassiveMode();
        //final FTPClientConfig config = new FTPClientConfig();
        ////config.setLenientFutureDates(true);
        //ftp.configure(config);
        if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) {
            ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder());
        }
        final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile());
        if (is == null) {
            _log.error("FIle not found: " + ftp.getSystemType());
        } else {
            unzip(ftpSubscription, is);
            is.close();
        }
        ftp.completePendingCommand();
    } catch (final FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (final IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException e) {
                _log.error(e);
            }
        }
    }
}

From source file:jenkins.plugins.publish_over_ftp.jenkins.IntegrationTest.java

@Test
public void testIntegration() throws Exception {
    final FTPClient mockFTPClient = mock(FTPClient.class);
    final int port = 21;
    final int timeout = 3000;
    final BapFtpHostConfiguration testHostConfig = new BapFtpHostConfiguration("testConfig", "testHostname",
            "testUsername", TEST_PASSWORD, "/testRemoteRoot", port, timeout, false, null, false, false) {
        @Override//from w  w  w . j av a 2s .c  om
        public FTPClient createFTPClient() {
            return mockFTPClient;
        }
    };
    new JenkinsTestHelper().setGlobalConfig(testHostConfig);
    final String dirToIgnore = "target";
    final BapFtpTransfer transfer = new BapFtpTransfer("**/*", null, "sub-home", dirToIgnore, true, false,
            false, false, false, false, null);
    final ArrayList transfers = new ArrayList(Collections.singletonList(transfer));
    final BapFtpPublisher publisher = new BapFtpPublisher(testHostConfig.getName(), false, transfers, false,
            false, null, null, null);
    final ArrayList publishers = new ArrayList(Collections.singletonList(publisher));
    final BapFtpPublisherPlugin plugin = new BapFtpPublisherPlugin(publishers, false, false, false, "master",
            null);

    final FreeStyleProject project = createFreeStyleProject();
    project.getPublishersList().add(plugin);
    final String buildDirectory = "build-dir";
    final String buildFileName = "file.txt";
    project.getBuildersList().add(new TestBuilder() {
        @Override
        public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher,
                final BuildListener listener) throws InterruptedException, IOException {
            final FilePath dir = build.getWorkspace().child(dirToIgnore).child(buildDirectory);
            dir.mkdirs();
            dir.child(buildFileName).write("Helloooooo", "UTF-8");
            build.setResult(Result.SUCCESS);
            return true;
        }
    });

    when(mockFTPClient.getReplyCode()).thenReturn(FTPReply.SERVICE_READY);
    when(mockFTPClient.login(testHostConfig.getUsername(), TEST_PASSWORD)).thenReturn(true);
    when(mockFTPClient.changeWorkingDirectory(testHostConfig.getRemoteRootDir())).thenReturn(true);
    when(mockFTPClient.setFileType(FTPClient.ASCII_FILE_TYPE)).thenReturn(true);
    when(mockFTPClient.changeWorkingDirectory(transfer.getRemoteDirectory())).thenReturn(false)
            .thenReturn(true);
    when(mockFTPClient.makeDirectory(transfer.getRemoteDirectory())).thenReturn(true);
    when(mockFTPClient.changeWorkingDirectory(buildDirectory)).thenReturn(false).thenReturn(true);
    when(mockFTPClient.makeDirectory(buildDirectory)).thenReturn(true);
    when(mockFTPClient.storeFile(eq(buildFileName), (InputStream) anyObject())).thenReturn(true);

    assertBuildStatusSuccess(project.scheduleBuild2(0).get());

    verify(mockFTPClient).connect(testHostConfig.getHostname(), testHostConfig.getPort());
    verify(mockFTPClient).storeFile(eq(buildFileName), (InputStream) anyObject());
    verify(mockFTPClient).setDefaultTimeout(testHostConfig.getTimeout());
    verify(mockFTPClient).setDataTimeout(testHostConfig.getTimeout());
}

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/*from ww w.j  a  v a  2s.  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/* w  ww.  j a  va2  s.  co 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./*from   w w w . j  a v a  2 s . co 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:com.droid.app.fotobot.FotoBot.java

public boolean files_to_ftp(List<String> FTP_files) {
    String server;/*from  w  ww.  j a v a2 s .c  o m*/
    int port;
    String user;
    String pass;

    String FTP_folder = "";

    if (FTP_server.contains("/")) {

        FTP_folder = FTP_server.substring(FTP_server.indexOf("/", 1));
        FTP_folder = FTP_folder.substring(1);

        server = FTP_server.substring(0, FTP_server.indexOf("/", 1));
    } else {
        server = FTP_server;
    }

    port = Integer.parseInt(FTP_port);
    user = FTP_username;
    pass = FTP_password;

    SendMessage("FTP user: " + "<br>" + user, MSG_PASS);
    SendMessage("FTP folder: " + "<br>" + FTP_folder, MSG_PASS);
    SendMessage("FTP server: " + "<br>" + server, MSG_PASS);

    FTPClient ftpClient = new FTPClient();

    try {
        int reply;

        ftpClient.connect(server, port);
        System.out.println("Connected to " + server + ".");
        System.out.print(ftpClient.getReplyString());
        reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");
            SendMessage("FTP   ?", MSG_FAIL);
            return false;
        }
    } catch (Exception e) {
    }

    try {
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(
                    " ?   FTP ?,      FTP  ?.",
                    MSG_FAIL);
            return false;
        }
    } catch (Exception e) {

    }

    // chdir

    if (FTP_folder.length() > 1) {
        try {
            ftpClient.changeWorkingDirectory(FTP_folder);

            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println("FTP chdir error");
                SendMessage(
                        "FTP  ?    <br>" + FTP_folder,
                        MSG_FAIL);
                return false;
            }

            SendMessage("FTP   <br>" + FTP_folder, MSG_PASS);
            System.out.println("Successfully changed working directory.");
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            SendMessage("FTP  ?    <br>" + FTP_folder,
                    MSG_FAIL);
            System.out.println("Failed to change working directory.");
            return false;
        }
    }

    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (Exception e) {
        SendMessage("FTP   BINARY_FILE_TYPE", MSG_FAIL);
        System.out.println("Failed to change to BINARY_FILE_TYPE.");
        return false;
    }

    // APPROACH #1: uploads first file using an InputStream

    for (String str : FTP_files) {
        File firstLocalFile = new File(str);

        String firstRemoteFile = firstLocalFile.getName();

        try {
            InputStream inputStream = new FileInputStream(firstLocalFile);

            SendMessage("? ", MSG_PASS);
            boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
            inputStream.close();

            if (done) {
                SendMessage(" " + "<br>" + str + "<br>" + " ", MSG_PASS);
            }
        } catch (IOException ex) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(" ?  " + "<br>" + str + "<br>"
                    + ftpClient.getReplyCode() + "\n" + ftpClient.getReplyString() + "\n" + ex.getMessage()
                    + "<br>"
                    + "     FTP  ?.",
                    MSG_FAIL);
            ex.printStackTrace();
        }

    }

    try {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
            SendMessage("FTP ???? ", MSG_PASS);
            fbpause(h, 3);
            return true;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        SendMessage("FTP ???? ", MSG_FAIL);
    }

    return false;

}