SFTP connection with credentials example

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.sftp.address=<IP>
basic_authentication.sftp.user=UserName
basic_authentication.sftp.password=Password
basic_authentication.sftp.destination.fileLocation=./test/
#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


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



 

    
package com.cv.sftp.auth;

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 authMode = null;

  static Properties readPropertiesFile = new Properties();
  static URL url = null;

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

  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.sftp.address");
      basicAuthUserId = readPropertiesFile2.getProperty("basic_authentication.sftp.user");
      basicAuthPassword = readPropertiesFile2.getProperty("basic_authentication.sftp.password");
      basciAuthDestinationDirectory = readPropertiesFile2
          .getProperty("basic_authentication.sftp.destination.fileLocation");
    
      authMode = readPropertiesFile2.getProperty("MODE_OF_CONNECTIONS");

    }
  }

  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;
  }

  

}


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



 

    
package com.cv.sftp.auth;

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

import org.apache.commons.io.FileUtils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

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

  public static void main(String[] args) {

    SFTPConnection fs = new SFTPConnection();
    String authMode = AppInit.authMode;
    if (authMode != null && authMode.equalsIgnoreCase("basic")) {
      fs.jschBasicAuth();
    else {
      fs.jschBasicAuth();
    }

  }

  public void jschBasicAuth() {
    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) {

                      e.printStackTrace();

                    }
                  catch (Exception e) {

                    e.printStackTrace();

                  }
                }
              }
            else {

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

          catch (Exception e) {

            e.printStackTrace();

          }
        else {

          System.err.println("Problem while getting the SFTP channel!");
        }
      }
    catch (Exception e) {

      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>SFTPConnectionWithCredentials</artifactId> <version>1.0</version> <url>http://maven.apache.org</url> <properties> <log4j-version>1.2.17</log4j-version> 1.8 SFTPConnectionWithCredentials </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