Wednesday, 2 May 2018

ftps client |ftps client java code |ftp client |ftp client java

ftps client |ftps client java code |ftp client |ftp client java


For,FTPS

The client side of the FTP protocol and SSL must be implemented in Java.

FTPS extends the FTP protocol with support for SSL and TLS.

The standard FTP protocol is encrypted via secure sockets, or SSL. For Java clients to communicate to FTPS servers

FTPS is a protocol for transferring files securely via FTP.

The data connection can also be secured using the commands PBSZ and PROT.

Here, demostrate FTPS example in java

Example :-
Note :- dependency must be on pom.xml file

<dependencies>
        <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>       
        <dependency> 
            <groupId>commons-io</groupId> 
            <artifactId>commons-io</artifactId> 
            <version>2.4</version> 
        </dependency> 
</dependencies>



package SecureFTP.ftpclient;

import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;

/**
 *
 * @author vishal.khokhar
 */
public class FTPSecureUpload {

    String server = "SFTP host";
    //your port number must be integer value
    int port = 22;
    String username = "SFTP username";
    String password = "SFTP password";

    String localFileName = "/Data/vishal.khokhar/first.zip";
    String FTPdirectoryName = "Data";
    String ftpSaveFilename = "999.zip";

    public static void main(String[] args) {
        //Calling for file Upload
        FTPSecureUpload FTPSecureUploadobj = new FTPSecureUpload();
        FTPSecureUploadobj.uploadFile();
    }

    public void uploadFile() {
        try {
            FTPSClient ftpClient = new FTPSClient(false);
            ftpClient.connect(server, port);
            int reply = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {

                if (ftpClient.login(username, password)) {

            // Set protection buffer size
                    ftpClient.execPROT("P");
            // Set data channel protection to private
                    ftpClient.execPBSZ(0);
            // Enter local passive mode
                    ftpClient.enterLocalPassiveMode();

             //For Make directory if not present on FTP
                    ftpClient.makeDirectory(FTPdirectoryName);

                    InputStream is = new FileInputStream(localFileName);
                    if (ftpClient.storeFile(FTPdirectoryName + ftpSaveFilename, is)) {
                        is.close();
                    } else {
                        System.out.println("File Could not store on FTP ...");
                    }
                    ftpClient.logout();

                } else {
                    System.out.println("FTP login has failed ...");
                }
                ftpClient.disconnect();

            } else {
                System.out.println("FTP host Connection failed ...");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            System.out.println("FTP client could not use SSL protocol");
        }
    }
}

-------------------------------------------------------------------------------------------------------------------
Example :- FTP

useage     :- FTP-Client encapsulates all the functionality necessary to store and retrieve files from an FTP server.

how use :- you must first connect to the server with connect before doing anything, AND finally,have to disconnect after you're completely finished interacting with the server.

PORT :- the FTP Client automatically issues a new PORT command prior to every transfer requiring that the server connect to the client's data port. This ensures identical problem-free behavior on Windows, Unix, and Macintosh platforms. Additionally, it relieves programmers from having to issue the PORT command themselves and dealing with platform dependent issues.

here, ftp i use jsch lib

steps for ftp using jsch
1) first create JSch() Object.
2) initialize Session using username, server and port.
3) initialize Properties() using StrictHostKeyChecking.
4) set Properties() into Session.
5) than connect session for ftp.
6) openChannel into Channel object using Session.
7) connect Channel.
8) than cast Channel into ChannelSftp.
9) now you can perform operation using ChannelSftp on ftp here, example of upload a file on ftp.

Example :- FTP

Note :- dependency must be on pom.xml file

<dependencies>
    <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.52</version>
        </dependency>
</dependencies>


package NormalFTP.ftpclient;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.HashMap;

/**
 *
 * @author vishal.khokhar
 */
public class FTPSecureUploadZymeTest {

    String server = "SFTP host";
    //your port number must be integer value
    int port = 22;
    String username = "SFTP username";
    String password = "SFTP password";

    String localFileName = "/home/vishal.khokhar/Projects/RND/first.zip";
    String ftpSaveFilename = "999.zip";

    //FTP use only
    JSch jsch;
    private Session session;
    private Channel channel;
    private ChannelSftp channelSftp;
    private final HashMap sessionMap = new HashMap();
    private SftpATTRS attrs;

    public static void main(String[] args) {
        FTPSecureUploadZymeTest FTPSecureUploadobj = new FTPSecureUploadZymeTest();
        FTPSecureUploadobj.uploadFile();
    }

    public void uploadFile() {
        try {
        //Establish connction to ftp
            openConnection();

        //createDir to create directory on ftp
        //changeDir to go inside directory on ftp
        //Argument is directory name

            createDir("Data");
            changeDir("Data");
            createDir("Projects");
            changeDir("Projects");
            createDir("RND");
            changeDir("RND");
   
       
            getChannelSftp().put(new FileInputStream(localFileName), ftpSaveFilename, ChannelSftp.OVERWRITE);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            getChannelSftp().quit();
            session.disconnect();
        }

    }

    public void openConnection() {
        System.out.println("SFTPUpload:openConnection() -  Begin!");
        do {
            try {
                System.out.println("Opening Connection...");
                jsch = new JSch();

                session = jsch.getSession(username, server, port);
                System.out.println("Upload Session created with following properties " + server);
                session.setPassword(password);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                System.out.println("Connecting Upload Session...");
                session.connect();
                System.out.println("Upload Session connected.");
                System.out.println("Opening Upload sftp Channel...");
                channel = session.openChannel("sftp");
                channel.connect();
                setChannelSftp((ChannelSftp) channel);
                System.out.println("Upload Channel Opened.");
                System.out.println("Connection Opened.");
                break;
            } catch (Exception ex) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex1) {
                }
            }
        } while (true);
        System.out.println("SFTPUpload:openConnection() -  End!");
    }

    /**
     * @return the channelSftp
     */
    public ChannelSftp getChannelSftp() {
        return channelSftp;
    }

    /**
     * @param channelSftp the channelSftp to set
     */
    public void setChannelSftp(ChannelSftp channelSftp) {
        this.channelSftp = channelSftp;
    }

    public boolean createDir(String dirName) {
        System.out.println("SFTPUpload:createDir() -  Begin!");
        boolean success = false;
        boolean isExist = true;
        if (!sessionMap.keySet().contains(dirName)) {
            try {
                attrs = getChannelSftp().stat(dirName);
            } catch (Exception e) {
                isExist = false;
            }

            if (attrs != null) {
                if (attrs.isDir()) {
                    System.out.println("SFTPUpload:createDir() -" + dirName + " dir already exist.");
                    sessionMap.put(dirName, "Dir:Exist");
                } else {
                    isExist = false;
                }
            }

            if (!isExist) {
                System.out.println("SFTPUpload:createDir() - " + dirName + " not found");
                System.out.println("Creating dir " + dirName);
                try {
                    getChannelSftp().mkdir(dirName);
                    sessionMap.put(dirName, "Dir:Ok");
                    success = true;
                } catch (SftpException ex) {
                    System.out.println("SFTPUpload:createDir() - " + dirName + " dir creation failed." + ex.getMessage());
                    sessionMap.put(dirName, "Dir:Fail");
                }
            }
        }

        System.out.println("SFTPUpload:createDir() -  End!");
        return success;
    }

    public boolean changeDir(String dirName) {
        System.out.println("SFTPUpload:changeDir() -  Begin!");
        boolean success = false;
        try {
            System.out.println("SFTPUpload:changeDir() -  Changing Directory To: " + server + dirName);
            if (dirName != null && !dirName.isEmpty()) {
                getChannelSftp().cd(dirName);
            }
            success = true;
        } catch (SftpException ex) {
        }

        System.out.println("SFTPUpload:changeDir() -  End!");
        return success;
    }
}

No comments:

Post a Comment