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:com.dp2345.plugin.ftp.FtpPlugin.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 www  .  j  a va  2  s.  c  om*/
            inputStream = 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 (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) throws SocketException, IOException {
    String[] vehicles = controlledVehicles.split(",");
    jTextArea1.setText("");
    jTextArea1.repaint();// w w  w  .  ja  va 2s  .  c  om
    showText("Initializing Control Structures");

    try {
        startLocalStructures(vehicles);
    } catch (Exception e) {
        GuiUtils.errorMessage(getConsole(), e);
        return;
    }

    AUVS = positions.keySet().size();

    showText("Initializing server connection");

    FTPClient client = new FTPClient();

    boolean PathNameCreated = false;
    try {
        client.connect("www.convcao.com", 21);
        client.login(jTextField1.getText(), new String(jPasswordField1.getPassword()));
        PathNameCreated = client.makeDirectory("/NEPTUS/" + SessionID);
        client.logout();

    } catch (IOException e) {
        jLabel6.setText("Connection Error");
        throw e;
    }

    showText("Sending session data");
    InputData initialState = new InputData();
    initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
    initialState.SessionID = SessionID;
    initialState.DemoMode = "1";
    initialState.AUVs = "" + positions.keySet().size();
    String fileName = SessionID + ".txt";

    Gson gson = new Gson();
    String json = gson.toJson(initialState);

    PrintWriter writer = new PrintWriter(fileName, "UTF-8");
    writer.write(json);
    writer.close();

    if (PathNameCreated) {
        jLabel6.setText("Connection Established");
        jLabel1.setVisible(true);
        System.out.println("Uploading first file");
        Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(),
                new String(jPasswordField1.getPassword()), fileName); //send first file
        System.out.println("Uploading second file");
        Upload("www.convcao.com", "NEPTUS/" + SessionID, "plugins-dev/caoAgent/convcao/com/caoAgent/",
                jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); //send sparse map
        System.out.println("Both files uploaded");
        jButton1.setEnabled(true);
        jButton2.setEnabled(true);
        jTextPane1.setEditable(false);
        jTextField1.setEditable(false);
        jPasswordField1.setEditable(false);
        connectButton.setEnabled(false);
        renewButton.setEnabled(false);
    } else {
        jLabel6.setText(client.getReplyString());
        jLabel1.setVisible(false);
    }

    myDeleteFile(fileName);

    showText("ConvCAO control has started");

}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    Map<String, String> ftpInfo = getFtpInfo(contentType);
    if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username"))
            && !"".equals(ftpInfo.get("password"))) {
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//  w ww. j a  va  2  s .c  om
            inputStream = new FileInputStream(file);
            ftpClient.connect(ftpInfo.get("host"), 21);
            ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            path = ftpInfo.get("path") + path;
            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 (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

private void connectButtonActionPerformed(ActionEvent evt) throws SocketException, IOException {
    String[] vehicles = controlledVehicles.split(",");
    jTextArea1.setText("");
    jTextArea1.repaint();//from   w  w w .  j  a va  2 s.co m
    showText("Initializing Control Structures");

    try {
        startLocalStructures(vehicles);
    } catch (Exception e) {
        GuiUtils.errorMessage(getConsole(), e);
        return;
    }

    auvs = positions.keySet().size();

    showText("Initializing server connection");

    FTPClient client = new FTPClient();

    boolean PathNameCreated = false;
    try {
        client.connect("www.convcao.com", 21);
        client.login(jTextField1.getText(), new String(jPasswordField1.getPassword()));
        PathNameCreated = client.makeDirectory("/NEPTUS/" + sessionID);
        client.logout();

    } catch (IOException e) {
        jLabel6.setText("Connection Error");
        throw e;
    }

    showText("Sending session data");
    InputData initialState = new InputData();
    initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
    initialState.SessionID = sessionID;
    initialState.DemoMode = "1";
    initialState.AUVs = "" + positions.keySet().size();
    String fileName = sessionID + ".txt";

    Gson gson = new Gson();
    String json = gson.toJson(initialState);

    PrintWriter writer = new PrintWriter(fileName, "UTF-8");
    writer.write(json);
    writer.close();

    if (PathNameCreated) {
        jLabel6.setText("Connection Established");
        jLabel1.setVisible(true);
        System.out.println("Uploading first file");
        upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(),
                new String(jPasswordField1.getPassword()), fileName); // send first file
        System.out.println("Uploading second file");
        String mapFxStr = FileUtil.getResourceAsFileKeepName("convcao/com/caoAgent/mapPortoSparse.txt");
        File mapFx = new File(mapFxStr);
        upload("www.convcao.com", "NEPTUS/" + sessionID, mapFx.getParent(), jTextField1.getText(),
                new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); // send sparse map
        System.out.println("Both files uploaded");
        jButton1.setEnabled(true);
        jButton2.setEnabled(true);
        jTextPane1.setEditable(false);
        jTextField1.setEditable(false);
        jPasswordField1.setEditable(false);
        connectButton.setEnabled(false);
        renewButton.setEnabled(false);
    } else {
        jLabel6.setText(client.getReplyString());
        jLabel1.setVisible(false);
    }

    myDeleteFile(fileName);

    showText("ConvCAO control has started");
}

From source file:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * /*  ww  w .ja  v a  2 s.  co  m*/
 * @throws UnknownHostException
 *         If the hostname cannot be resolved.
 *         
 * @throws SocketException
 *         If the socket timeout could not be set.
 *         
 * @throws FTPConnectionClosedException
 *         If the connection is closed by the server.
 *         
 * @throws LoginFailedException
 *         If the login fails.
 *         
 * @throws DirectoryChangeFailedException
 *         If changing to the directory provided by the internet
 *         archive fails.
 *         
 * @throws CopyStreamException
 *         If an I/O error occurs while in the middle of
 *         transferring a file.
 *         
 * @throws IOException
 *         If an I/O error occurs while sending a command or
 *         receiving a reply from the server
 *         
 * @throws IllegalStateException
 *          If the contribution object is not ready to upload
 *          (no username, password, server, etc. set)
 *          or if java's xml parser is configured badly
 */

public void upload()
        throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException,
        DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException {

    final int NUM_XML_FILES = 2;
    final String META_XML_SUFFIX = "_meta.xml";
    final String FILES_XML_SUFFIX = "_files.xml";

    final String username = getUsername();
    final String password = getPassword();

    if (getFtpServer() == null) {
        throw new IllegalStateException("ftp server not set");
    }
    if (getFtpPath() == null) {
        throw new IllegalStateException("ftp path not set");
    }
    if (username == null) {
        throw new IllegalStateException("username not set");
    }
    if (password == null) {
        throw new IllegalStateException("password not set");
    }

    // calculate total number of files and bytes

    final String metaXmlString = serializeDocument(getMetaDocument());
    final String filesXmlString = serializeDocument(getFilesDocument());

    final byte[] metaXmlBytes = metaXmlString.getBytes();
    final byte[] filesXmlBytes = filesXmlString.getBytes();

    final int metaXmlLength = metaXmlBytes.length;
    final int filesXmlLength = filesXmlBytes.length;

    final Collection files = getFiles();

    final int totalFiles = NUM_XML_FILES + files.size();

    final String[] fileNames = new String[totalFiles];
    final long[] fileSizes = new long[totalFiles];

    final String metaXmlName = getIdentifier() + META_XML_SUFFIX;
    fileNames[0] = metaXmlName;
    fileSizes[0] = metaXmlLength;

    final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX;
    fileNames[1] = filesXmlName;
    fileSizes[1] = filesXmlLength;

    int j = 2;
    for (Iterator i = files.iterator(); i.hasNext();) {
        final File f = (File) i.next();
        fileNames[j] = f.getRemoteFileName();
        fileSizes[j] = f.getFileSize();
        j++;
    }

    // init the progress mapping
    for (int i = 0; i < fileSizes.length; i++) {
        _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i]));
        _totalUploadSize += fileSizes[i];
    }

    FTPClient ftp = new FTPClient();

    try {
        // first connect

        if (isCancelled()) {
            return;
        }
        ftp.enterLocalPassiveMode();

        if (isCancelled()) {
            return;
        }
        ftp.connect(getFtpServer());

        final int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new RefusedConnectionException(getFtpServer() + "refused FTP connection");
        }
        // now login
        if (isCancelled()) {
            return;
        }
        if (!ftp.login(username, password)) {
            throw new LoginFailedException();
        }

        try {

            // try to change the directory
            if (!ftp.changeWorkingDirectory(getFtpPath())) {
                // if changing fails, make the directory
                if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) {
                    throw new DirectoryChangeFailedException();
                }

                // now change directory, if it fails again bail
                if (isCancelled()) {
                    return;
                }
                if (!ftp.changeWorkingDirectory(getFtpPath())) {
                    throw new DirectoryChangeFailedException();
                }
            }

            if (isCancelled()) {
                return;
            }
            connected();

            // upload xml files
            uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp);

            uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp);

            // now switch to binary mode
            if (isCancelled()) {
                return;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            // upload contributed files
            for (final Iterator i = files.iterator(); i.hasNext();) {
                final File f = (File) i.next();

                uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp);
            }
        } catch (InterruptedIOException ioe) {
            // we've been requested to cancel
            return;
        } finally {
            ftp.logout(); // we don't care if logging out fails
        }
    } finally {
        try {
            ftp.disconnect();
        } catch (IOException e) {
        } // don't care if disconnecting fails
    }

    // now tell the Internet Archive that we're done
    if (isCancelled()) {
        return;
    }
    checkinStarted();

    if (isCancelled()) {
        return;
    }
    checkin();

    if (isCancelled()) {
        return;
    }
    checkinCompleted();
}

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

/**
 * Transfers files to the FTP account//from ww  w  .j  a v  a 2 s .c  om
 *
 * @param files
 *            - files to be transferred
 * @param monitor
 *            - progress monitor
 * @param adaptable
 *            - adaptable instance. Must at least provide a Shell instance
 * @param deleteTransferred
 *            - true if transferred files shall be deleted on the client
 *            site
 * @return number of transferred files or -1 in case of abort
 * @throws IOException
 */
public int transferFiles(File[] files, IProgressMonitor monitor, IAdaptable adaptable,
        boolean deleteTransferred) throws IOException {
    filecount = countFiles(files);
    monitor.beginTask(Messages.FtpAccount_uploading_files, filecount + 1);
    FTPClient ftp = null;
    try {
        ftp = login();
        String dir = stripSlashes(getDirectory());
        int n = 0;
        boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(dir));
        if (!result) {
            if (monitor.isCanceled())
                return -1;
            boolean createDir = true;
            IDbErrorHandler errorHandler = Core.getCore().getErrorHandler();
            if (errorHandler != null)
                createDir = errorHandler.question(Messages.FtpAccount_directory_does_not_exist,
                        Messages.FtpAccount_specified_dir_does_not_exist, adaptable);
            if (createDir) {
                StringTokenizer st = new StringTokenizer(dir, "/"); //$NON-NLS-1$
                while (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    ftp.makeDirectory(token);
                    result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(token));
                    if (!result)
                        throw new IOException(Messages.FtpAccount_directory_creation_failed);
                }

            } else
                throw new IOException(Messages.FtpAccount_target_dir_does_not_exist);
        }
        if (files != null) {
            monitor.worked(1);
            skipAll = false;
            replaceAll = false;
            if (monitor.isCanceled())
                return -1;
            n = transferFiles(ftp, files, monitor, adaptable, deleteTransferred);
        }

        // transfer files
        if (isPassiveMode())
            ftp.enterLocalActiveMode();
        ftp.logout();
        return n;
    } finally {
        monitor.done();
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

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 w  ww .j  a  v  a 2 s  .  co  m
    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.jmeter.alfresco.utils.FtpUtils.java

/**
 * Upload directory.//from  w w  w .jav  a 2 s.co  m
 *
 * @param ftpClient the ftp client
 * @param toRemoteDir the to remote dir
 * @param fromLocalParentDir the from local parent dir
 * @param remoteParentDir the remote parent dir
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void uploadDirectory(final FTPClient ftpClient, final String toRemoteDir, String fromLocalParentDir,
        final String remoteParentDir) throws IOException {
    fromLocalParentDir = convertToLinuxFormat(fromLocalParentDir);
    fromLocalParentDir = checkLinuxSeperator(fromLocalParentDir);
    LOG.debug("Listing the directory tree: " + fromLocalParentDir);
    final File localDir = new File(fromLocalParentDir);
    final File[] listedFiles = localDir.listFiles();
    List<File> subFiles = null;
    if (listedFiles != null) {
        subFiles = Arrays.asList(listedFiles);
    }
    if (subFiles != null && !subFiles.isEmpty()) {
        for (final File item : subFiles) {
            String remoteFilePath = toRemoteDir + FILE_SEPERATOR_LINUX + remoteParentDir + FILE_SEPERATOR_LINUX
                    + item.getName();
            if (EMPTY.equals(remoteParentDir)) {
                remoteFilePath = toRemoteDir + FILE_SEPERATOR_LINUX + item.getName();
            }
            if (item.isFile()) {
                // Upload the file
                final String localFilePath = convertToLinuxFormat(item.getAbsolutePath());
                LOG.debug("Thread-" + Thread.currentThread().getName() + ", uploading file: " + localFilePath);
                final boolean isFileUploaded = uploadFile(ftpClient, localFilePath, remoteFilePath);
                if (isFileUploaded) {
                    LOG.debug("File uploaded: " + remoteFilePath);
                } else {
                    LOG.warn("Could not upload the file: " + localFilePath
                            + " on remote host, file may be existing!");
                }
            } else {
                //Recursively traverse the directory and create the directory.
                //Create directory on the server
                LOG.debug("Thread-" + Thread.currentThread().getName() + ", creating remote dir: "
                        + remoteFilePath);
                final boolean isDirCreated = ftpClient.makeDirectory(remoteFilePath);
                if (isDirCreated) {
                    LOG.debug("Created the directory: " + remoteFilePath + " on remote host");
                } else {
                    LOG.warn("Could not create the directory: " + remoteFilePath
                            + " on remote host, directory may be existing!");
                }
                //Directory created, now upload the sub directory
                String parentDirectory = remoteParentDir + FILE_SEPERATOR_LINUX + item.getName();
                if (EMPTY.equals(remoteParentDir)) {
                    parentDirectory = item.getName();
                }
                fromLocalParentDir = item.getAbsolutePath();
                //Call to uploadDirectory to upload the sub-directories
                uploadDirectory(ftpClient, toRemoteDir, fromLocalParentDir, parentDirectory);
            }
        }
    }
}

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/*ww  w . j  av  a 2  s  . c  o  m*/
        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 w w w. ja  v a2  s .co  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);
    }
}