se.natusoft.maven.plugin.ftp.FTPMojo.java Source code

Java tutorial

Introduction

Here is the source code for se.natusoft.maven.plugin.ftp.FTPMojo.java

Source

/* 
 * 
 * PROJECT
 *     Name
 *         FTPMavenPlugin Maven Mojo
 *     
 *     Code Version
 *         1.0
 *     
 *     Description
 *         A Simple FTP plugin for maven that allows you to ftp any files, not just jars.
 *         
 * COPYRIGHTS
 *     Copyright (C) 2013 by Natusoft AB All rights reserved.
 *     
 * LICENSE
 *     Apache 2.0 (Open Source)
 *     
 *     Licensed under the Apache License, Version 2.0 (the "License");
 *     you may not use this file except in compliance with the License.
 *     You may obtain a copy of the License at
 *     
 *       http://www.apache.org/licenses/LICENSE-2.0
 *     
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *     
 * AUTHORS
 *     Tommy Svensson (tommy@natusoft.se)
 *         Changes:
 *         2013-01-23: Created!
 *         
 */
package se.natusoft.maven.plugin.ftp;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Goal which touches a timestamp file.
 *
 * @goal upload
 * 
 * @phase deploy
 */
public class FTPMojo extends AbstractMojo {

    /**
     * The files to FTP.
     *
     * @parameter
     * @required
     */
    private String files;

    /**
     * Host to ftp to.
     *
     * @parameter
     * @required
     */
    private String targetHost;

    /**
     * Port to ftp to.
     *
     * @parameter expression="21"
     */
    private int targetPort;

    /**
     * The name of the user to login as.
     *
     * @parameter
     * @required
     */
    private String userName;

    /**
     * The password for the user.
     *
     * @parameter
     * @required
     */
    private String password;

    /**
     * Target root path on host.
     *
     * @parameter
     * @required
     */
    private String targetPath;

    /**
     * The projects base directory.
     *
     * @parameter expression="${basedir}"
     */
    private String baseDir;

    /**
     * Executes the mojo.
     *
     * @throws MojoExecutionException
     */
    public void execute() throws MojoExecutionException {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(this.targetHost, this.targetPort);
            if (!ftpClient.login(this.userName, this.password)) {
                throw new MojoExecutionException("Failed to login user '" + this.userName + "'!");
            }
            this.getLog()
                    .info("FTP: Connected to '" + this.targetHost + ":" + this.targetPort + "':" + this.targetPath);

            ftpClient.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
            ftpClient.setBufferSize(1024 * 60);

            SourcePaths sourcePaths = new SourcePaths(new File(this.baseDir), this.files);
            this.getLog().info("Files to upload: " + sourcePaths.getSourceFiles().size());

            int fileNo = 0;

            for (File transferFile : sourcePaths.getSourceFiles()) {
                String relPath = this.targetPath
                        + transferFile.getParentFile().getAbsolutePath().substring(this.baseDir.length());

                boolean havePath = ftpClient.changeWorkingDirectory(relPath);
                if (!havePath) {
                    if (!mkdir(ftpClient, relPath)) {
                        throw new MojoExecutionException("Failed to create directory '" + relPath + "'!");
                    }
                    if (!ftpClient.changeWorkingDirectory(relPath)) {
                        throw new MojoExecutionException(
                                "Failed to change to '" + relPath + "' after its been created OK!");
                    }
                }

                FileInputStream sendFileStream = new FileInputStream(transferFile);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.storeFile(transferFile.getName(), sendFileStream);
                sendFileStream.close();
                this.getLog().info(
                        "Transferred [" + ++fileNo + "]: " + relPath + File.separator + transferFile.getName());
            }
            this.getLog().info("All files transferred!");
        } catch (IOException ioe) {
            throw new MojoExecutionException(ioe.getMessage(), ioe);
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException ioe) {
                this.getLog().error("Failed to disconnect from FTP site! [" + ioe.getMessage() + "]", ioe);
            }
        }
    }

    /**
     * Create a full path directory by creating one part at a time.
     *
     * @param ftpClient A connected FTPClient instance.
     * @param dir The directory to create.
     *
     * @return true on success.
     *
     * @throws IOException on failure.
     */
    private boolean mkdir(FTPClient ftpClient, String dir) throws IOException {
        boolean result = true;

        for (String part : dir.split("/")) {
            if (!ftpClient.changeWorkingDirectory(part)) {
                result = ftpClient.makeDirectory(part);
                if (!result)
                    return result;
                result = ftpClient.changeWorkingDirectory(part);
                if (!result)
                    return result;
            }
        }

        return result;
    }

}