SFTP service examples

Click here to download eclipse supported ZIP file



This is input.properties properties file and these properties are used in the application.




basic_authentication.source.fileLocation=C:/temp/cv/
basic_authentication.backup.fileLocation=C:/temp/cv/backup/
basic_authentication.ftp.address=<IP>
basic_authentication.ftp.user=UserName
basic_authentication.ftp.password=Password
basic_authentication.destination.fileLocation=./test/
key_authentication.source.fileLocation=C:/temp/cv/
key_authentication.backup.fileLocation=C:/temp/cv/backup/
key_authentication.ftp.address=<IP>
key_authentication.ftp.user=UserName
key_authentication.destination.fileLocation=./test/
key.file.location=C:/temp/cv/
#Mention the value of MODE_OF_CONNECTIONS as key for key authentication, basic for username/password authentication and all for both.
MODE_OF_CONNECTIONS=basic
message=There is a problem in the server.
host=smtp.sendgrid.net
port=25
ccAddress=XXX@gmail.com
toAddress=xxxx.xxx@gmail.com
fromAddress=info@xxxx.com
username=username
password=password


This is AppInit.java file having the source code to execute business logic.



 

    
package com.cv.sftp.write;

import java.net.URL;
import java.util.Properties;

/**
 @author Chandra Vardhan
 *
 */
public class AppInit {

  static String basicAuthSourceDirectory = null;
  static String basicAuthAddress = null;
  static String basicAuthUserId = null;
  static String basicAuthPassword = null;
  static String basciAuthDestinationDirectory = null;
  static String basciAuthBackupDirectory = null;

  static String keyAuthAddress = null;
  static String keyAuthUserId = null;
  static String keyAuthDestinationDirectory = null;
  static String keyAuthSourceDirectory = null;
  static String keyAuthBackupDirectory = null;

  static String authMode = null;

  static String message = null;
  static String host = null;
  static String port = null;
  static String ccAddress = null;
  static String fromAddress = null;
  static String toAddress = null;
  static String userName = null;
  static String password = null;
  static Properties readPropertiesFile = new Properties();
  static URL url = null;

  static {
    readPropertiesFile = readPropertiesFile();
    setValues(readPropertiesFile);
    url = readAuthKeyFile();
  }

  private static void setValues(Properties readPropertiesFile2) {
    if (readPropertiesFile2 != null) {
      basicAuthSourceDirectory = readPropertiesFile2.getProperty("basic_authentication.source.fileLocation");
      basciAuthBackupDirectory = readPropertiesFile2.getProperty("basic_authentication.backup.fileLocation");
      basicAuthAddress = readPropertiesFile2.getProperty("basic_authentication.ftp.address");
      basicAuthUserId = readPropertiesFile2.getProperty("basic_authentication.ftp.user");
      basicAuthPassword = readPropertiesFile2.getProperty("basic_authentication.ftp.password");
      basciAuthDestinationDirectory = readPropertiesFile2
          .getProperty("basic_authentication.destination.fileLocation");
      keyAuthAddress = readPropertiesFile2.getProperty("key_authentication.ftp.address");
      keyAuthUserId = readPropertiesFile2.getProperty("key_authentication.ftp.user");
      keyAuthDestinationDirectory = readPropertiesFile2
          .getProperty("key_authentication.destination.fileLocation");
      keyAuthSourceDirectory = readPropertiesFile2.getProperty("key_authentication.source.fileLocation");
      keyAuthBackupDirectory = readPropertiesFile2.getProperty("key_authentication.backup.fileLocation");
      authMode = readPropertiesFile2.getProperty("MODE_OF_CONNECTIONS");

      message = readPropertiesFile2.getProperty("message");
      host = readPropertiesFile2.getProperty("host");
      port = readPropertiesFile2.getProperty("port");
      ccAddress = readPropertiesFile2.getProperty("ccAddress");
      fromAddress = readPropertiesFile2.getProperty("fromAddress");
      toAddress = readPropertiesFile2.getProperty("toAddress");
      userName = readPropertiesFile2.getProperty("username");
      password = readPropertiesFile2.getProperty("password");
    }
  }

  private static Properties readPropertiesFile() {
    Properties props = new Properties();
    try {
      props.load(AppInit.class.getClassLoader().getResourceAsStream("input.properties"));
    catch (Exception e) {
      System.err.println("Problem while reading input properties file!!!");
    }
    return props;
  }

  private static URL readAuthKeyFile() {
    URL url = null;
    try {
      url = AppInit.class.getClassLoader().getResource("privateKey.pub");
    catch (Exception e) {
      System.err.println("Problem while reading auth-key file!!!");
    }
    return url;
  }

}




This is EmailUtility.java file having the source code to execute business logic.



 

    
package com.cv.sftp.write;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 @author Chandra Vardhan
 *
 */
public class EmailUtility {

  public static void sendEmail(final String subject, final String content) {
    try {

      // Get the session object
      Properties properties = new Properties();
      final String userName = AppInit.userName;
      final String password = AppInit.password;
      final String port = AppInit.port;
      final String host = AppInit.host;
      properties.setProperty("mail.smtp.host", host);
      properties.setProperty("port", port);
      properties.put("mail.smtp.auth""true");
      properties.put("mail.smtp.starttls.enable""true");
      properties.setProperty("username", userName);
      properties.setProperty("password", password);

      Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(userName, password);
        }
      });

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(AppInit.fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(AppInit.toAddress));
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(AppInit.ccAddress));
      message.setSubject("SFTPService : " + subject);
      message.setText(content);
      Transport.send(message);
      System.out.println("mail sent successfully....");

    catch (AddressException e) {
      e.printStackTrace();
    catch (MessagingException e) {
      e.printStackTrace();
    }

  }
}


This is SFTPService.java file having the service/business logic to call the DAO layer and get the information from database.



 

    
package com.cv.sftp.write;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;

import org.apache.commons.io.FileUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 @author Chandra Vardhan
 *
 */
public class SFTPService {

  public static void main(String[] args) {

    SFTPService fs = new SFTPService();
    String authMode = AppInit.authMode;
    if (authMode != null && authMode.equalsIgnoreCase("basic")) {
      fs.sendViaJschBasicAuth();
    else if (authMode != null && authMode.equalsIgnoreCase("key")) {
      fs.sendViaJschKeyAuth();
    else {
      // fs.sendViaJschBasicAuth();
      fs.sendViaJschKeyAuth();
    }

  }

  public void sendViaJschBasicAuth() {
    JSch conn = new JSch();
    Session session = null;
    ChannelSftp channel = null;
    try {
      session = conn.getSession(AppInit.basicAuthUserId, AppInit.basicAuthAddress);
      if (session != null) {
        session.setPassword(AppInit.basicAuthPassword);
        session.setServerAliveCountMax(10);
        session.setConfig("StrictHostKeyChecking""no");
        session.setTimeout(150000);
        session.connect();
        channel = (ChannelSftpsession.openChannel("sftp");
        if (channel != null) {
          channel.connect();
          try {
            File[] listOfFiles = new File(AppInit.basicAuthSourceDirectory).listFiles();
            if (listOfFiles != null && listOfFiles.length > 0) {
              for (File file : listOfFiles) {
                if (file.isFile()) {

                  try {
                    channel.put(new FileInputStream(file),
                        AppInit.basciAuthDestinationDirectory + file.getName());
                    String backUpDir = AppInit.basciAuthBackupDirectory;
                    File backDir = new File(backUpDir);
                    if(backDir != null && !backDir.exists()) {
                      backDir.mkdirs();
                    }
                    try {
                    FileUtils.copyFileToDirectory(file, backDir);
                    catch (Exception e) {
                      EmailUtility.sendEmail("Problem while taking the file backup !!!",
                          "There is a problem while taking the file backup !!!");

                      e.printStackTrace();

                    }
                    try {
                    FileUtils.forceDelete(file);
                    catch (Exception e) {
                      EmailUtility.sendEmail("Problem while deleting the file from source",
                          "There is a problem while deleting the file from source directory.");

                      e.printStackTrace();

                    }
                  catch (Exception e) {
                    EmailUtility.sendEmail("Problem while accessing destination directory of SFTP",
                        "There is a problem while accessing the destination directory. Host IP : "
                            + AppInit.basicAuthAddress + " and User id : "
                            + AppInit.basicAuthUserId);

                    e.printStackTrace();

                  }
                }
              }
            else {
              EmailUtility.sendEmail(
                  "There are no files available in the " + AppInit.basicAuthSourceDirectory
                      " directory!!!",
                  "There are no files available in the " + AppInit.basicAuthSourceDirectory
                      " directory!!!" + AppInit.basicAuthAddress + " and User id : "
                      + AppInit.basicAuthUserId);

              System.err.println("There are no files available in the " + AppInit.basicAuthSourceDirectory
                  " directory!!!");
            }

          catch (Exception e) {
            EmailUtility.sendEmail("Problem while accessing source directory of SFTP",
                "There is a problem while accessing the Source directory. Host IP : "
                    + AppInit.basicAuthAddress + " and User id : " + AppInit.basicAuthUserId);

            e.printStackTrace();

          }
        else {
          EmailUtility.sendEmail("Problem while connecting to SFTP",
              "There is a problem while getting the SFTP connection. Host IP : "
                  + AppInit.basicAuthAddress + " and User id : " + AppInit.basicAuthUserId);
          System.err.println("Problem while getting the SFTP channel!");
        }
      }
    catch (Exception e) {
      EmailUtility.sendEmail("Problem while connecting to SFTP",
          "There is a problem while getting the SFTP connection. Host IP : " + AppInit.basicAuthAddress
              " and User id : " + AppInit.basicAuthUserId);
      e.printStackTrace();

    finally {
      if (channel != null) {
        channel.disconnect();
      }
      if (session != null) {
        session.disconnect();
      }
    }
  }


  public void sendViaJschKeyAuth() {
    JSch jsch = new JSch();
    Session session = null;
    ChannelSftp channel = null;
    try {
      if (AppInit.url == null) {
        throw new RuntimeException("Key file auth-key not found in classpath");
      }
      URI keyFileURI = AppInit.url.toURI();
      jsch.addIdentity(new File(keyFileURI).getAbsolutePath());
      session = jsch.getSession(AppInit.keyAuthUserId, AppInit.keyAuthAddress, 22);
      if (session != null) {
        session.setServerAliveCountMax(5);
        session.setConfig("StrictHostKeyChecking""no");
        
        session.setTimeout(1000);
        session.setConfig("PreferredAuthentications"
                    "publickey,keyboard-interactive,password");
        try {
          session.connect();
        catch (JSchException e) {
          e.printStackTrace();
        }
        channel = (ChannelSftpsession.openChannel("sftp");
        if (channel != null) {
          channel.connect();
          try {
            File[] listOfFiles = new File(AppInit.keyAuthSourceDirectory).listFiles();
            if (listOfFiles != null && listOfFiles.length > 0) {
              channel.cd(AppInit.keyAuthDestinationDirectory );
              for (File file : listOfFiles) {
                if (file.isFile()) {
                  try {
                    channel.put(new FileInputStream(file),
                         file.getName());
                    String backUpDir = AppInit.keyAuthBackupDirectory;
                    File backDir = new File(backUpDir);
                    if(backDir != null && !backDir.exists()) {
                      backDir.mkdirs();
                    }
                    try {
                      FileUtils.copyFileToDirectory(file, backDir);
                      catch (Exception e) {
                        EmailUtility.sendEmail("Problem while taking the file backup !!!",
                            "There is a problem while taking the file backup !!!");

                        e.printStackTrace();

                      }
                      try {
                      FileUtils.forceDelete(file);
                      catch (Exception e) {
                        EmailUtility.sendEmail("Problem while deleting the file from source",
                            "There is a problem while deleting the file from source directory.");

                        e.printStackTrace();

                      }
                  catch (Exception e) {
                    EmailUtility.sendEmail("Problem while accessing destination directory of SFTP",
                        "There is a problem while accessing the destination directory. Host IP : "
                            + AppInit.keyAuthAddress + " and User id : "
                            + AppInit.keyAuthUserId);
                    e.printStackTrace();

                  }
                }
              }
            else {
              EmailUtility.sendEmail(
                  "There are no files available in the " + AppInit.keyAuthSourceDirectory
                      " directory!!!",
                  "There are no files available in the " + AppInit.keyAuthSourceDirectory
                      " directory!!!" + AppInit.keyAuthAddress + " and User id : "
                      + AppInit.keyAuthUserId);
              System.err.println("There are no files available in the " + AppInit.keyAuthSourceDirectory
                  " directory!!!");
            }
          catch (Exception e) {
            EmailUtility.sendEmail("Problem while accessing source directory of SFTP",
                "There is a problem while accessing the Source directory. Host IP : "
                    + AppInit.keyAuthAddress + " and User id : " + AppInit.keyAuthUserId);
            e.printStackTrace();

          }
        }
      }
    catch (Exception e) {
      EmailUtility.sendEmail("Problem while connecting to SFTP",
          "There is a problem while getting the SFTP connection. Host IP : " + AppInit.keyAuthAddress
              " and User id : " + AppInit.keyAuthUserId);
      e.printStackTrace();

    finally {
      if (channel != null) {
        channel.disconnect();
      }
      if (session != null) {
        session.disconnect();
      }
    }

  }

}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.sftp</groupId> <artifactId>SFTPService</artifactId> <version>1.0</version> <url>http://maven.apache.org</url> <properties> <log4j-version>1.2.17</log4j-version> 1.8 SFTPService </properties> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.42</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-vfs2</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <finalName>${pom.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment