SFTP read write examples

Click here to download eclipse supported ZIP file



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




mail.subject=SubjectGoesHere
mail.smtp.host=smtp.sendgrid.net
port=25
to.address=XXXXX@gmail.com
cc.address=XXX@gmail.com,YYY@gmail.com
bcc.address=XXX@gmail.com
from.address=XXX@gmail.com
username=username
password=password
mail.smtp.auth=true
mail.smtp.starttls.enable=true
attachment.mail.body=Hi, <br><br> Please find the file attached for the date : : APPEND_DATE. <br><br>Regards,<br> XXXXX




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




source.file.location=C:/temp/cv/source/
backup.file.location=C:/temp/cv/sent/
#The value of timeToSchedule is time in hour and followed by a dot[.] and time in minute and followed by a dot[.] and followed by Ante Meridiem[AM] or Post Meridiem[PM]
schedule.time.copy.to.sftp=1.10.PM
enable.upload.task=true
attempts=5
sent.email.file.location=C:/temp/cv/sent/email/
schedule.time.to.email.sending=3.35.PM
schedule.time.to.email.sending2=4.55.PM
enable.download.task=true
#1 day = 1000*60*60*24
#1 hour = 1000*60*60
#1 minute = 1000*60
#1 second = 1000
time.difference.between.executions=1000*60*3
#Please mention private or public key file here
key.file.location = C:/temp/cv/private_key.ppk




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




sftp.incoming.file.location=/incoming/
#This is a COMMA separated property. In case, more files to read from the incoming folder then please provide the file name  with COMMA separate. 
sftp.incoming.file.names=test.txt
sftp.address=xxxx.xxxx.xxxx.xxxx
sftp.user=user
sftp.outgoing.file.location=/outgoing/
#The below is a COMMA separated property. In case, more files to read from the outgoing folder then please provide the file name with COMMA separate.
sftp.outgoing.file.names=download.txt


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



 

    
package com.cv.sftp.service;

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

import org.apache.log4j.Logger;

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

  private static final Logger LOGGER = Logger.getLogger(AppInit.class);
  static String sourceDirectory = "";
  static String backupDirectory = "C://java//sftp//";
  static String sentEmailFileLocation = "C://java//sftp//email//sent//";
  static String timeScheduleToUploadSFTP = "10.10.PM";
  static String attempts = "3";
  static String timeDifferenceBetweenExecutions = "1000*60*60*24";
  static String timeScheduleToDownlaodFromSFTP = "10.30.PM";
  static String enableUploadTask = "false";
  static String enableDownloadTask = "false";
  //SFTP properties
  static String sftpAddress = null;
  static String sftpUserId = "XXXXX";
  static String sftpInDirectory = "/incoming/";
  static String sftpOutDirectory = "/outgoing/";
  static String sftpOutFileNames = "test.txt";
  static String sftpInFileNames= "text.txt";
  static String keyFileLocation ="";
  static Properties emailProperties = new  Properties();
  static Properties sftpProperties = new  Properties();
  static Properties readInputPropertiesFile = new Properties();
  static URL url = null;
  

  static {
    readInputPropertiesFile = readInputPropertiesFile();
    emailProperties = readEmailPropertiesFile();
    sftpProperties = readSftpPropertiesFile();
    setInputValues(readInputPropertiesFile);
    setSftpValues(sftpProperties);
    url = readAuthKeyFile();
  }

  private static void setInputValues(final Properties readPropertiesFile2) {
    if (readPropertiesFile2 != null) {
      sourceDirectory = readPropertiesFile2.getProperty("source.file.location");
      backupDirectory = readPropertiesFile2.getProperty("backup.file.location");
      sentEmailFileLocation = readPropertiesFile2.getProperty("sent.email.file.location");
      timeScheduleToUploadSFTP = readPropertiesFile2.getProperty("schedule.time.copy.to.sftp");
      attempts = readPropertiesFile2.getProperty("attempts");
      timeScheduleToDownlaodFromSFTP = readPropertiesFile2.getProperty("schedule.time.to.email.sending");
      enableUploadTask = readPropertiesFile2.getProperty("enable.upload.task");
      enableDownloadTask = readPropertiesFile2.getProperty("enable.download.task");
      timeDifferenceBetweenExecutions = readPropertiesFile2.getProperty("time.difference.between.executions");
      keyFileLocation = readPropertiesFile2.getProperty("key.file.location");
    }
  }

  private static void setSftpValues(final Properties readPropertiesFile2) {
    if (readPropertiesFile2 != null) {
      sftpAddress = readPropertiesFile2.getProperty("sftp.address");
      sftpUserId = readPropertiesFile2.getProperty("sftp.user");
      sftpInDirectory = readPropertiesFile2.getProperty("sftp.incoming.file.location");
      sftpInFileNames = readPropertiesFile2.getProperty("sftp.incoming.file.names");
      sftpOutDirectory = readPropertiesFile2.getProperty("sftp.outgoing.file.location");
      sftpOutFileNames = readPropertiesFile2.getProperty("sftp.outgoing.file.names");
    }
  }

  private static Properties readInputPropertiesFile() {
    Properties props = new Properties();
    try {
      LOGGER.debug("input.properties file read successfully...");
      props.load(AppInit.class.getClassLoader().getResourceAsStream("input.properties"));
    catch (Exception e) {
      LOGGER.error("Problem while reading input properties file : : " + e.getMessage());
    }
    return props;
  }
  
  private static Properties readSftpPropertiesFile() {
    Properties props = new Properties();
    try {
      LOGGER.debug("sftp.properties file read successfully...");
      props.load(AppInit.class.getClassLoader().getResourceAsStream("sftp.properties"));
    catch (Exception e) {
      LOGGER.error("Problem while reading sftp properties file : : " + e.getMessage());
    }
    return props;
  }
  private static Properties readEmailPropertiesFile() {
    Properties props = new Properties();
    try {
      LOGGER.debug("email.properties file read successfully...");
      props.load(AppInit.class.getClassLoader().getResourceAsStream("email.properties"));
    catch (Exception e) {
      LOGGER.error("Problem while reading email properties file : : " + e.getMessage());
    }
    return props;
  }

  private static URL readAuthKeyFile() {
    URL url = null;
    try {
      LOGGER.debug("key file read successfully...");
      url = AppInit.class.getClassLoader().getResource(keyFileLocation);
    catch (Exception e) {
      LOGGER.error("Problem while reading auth-key file : : " + e.getMessage());
    }
    return url;
  }

}


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



 

    
package com.cv.sftp.service;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

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

  private static final Logger LOGGER = Logger.getLogger(EmailUtils.class);

  public static void sendEmail(final Properties emailProperties, String content, final File attachment) {
    LOGGER.debug("In EmailUtils.sendEmail(- -) method");
    try {
      if (emailProperties != null && !emailProperties.isEmpty()) {
        // Get the session object
        final String userName = (StringemailProperties.get("username");
        final String password = (StringemailProperties.get("password");
        String log = "Mail with attachment sent successfully...";
        Session session = Session.getInstance(emailProperties, new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
          }
        });
        if (content != null) {
          content = "<p><span face=\"Calibri\" style=\"font-family: Calibri;\"><font size=\"4\">" + content + "</font></p>";
        }
        Message message = new MimeMessage(session);
        if (attachment != null) {
          log = "Mail with attachment sent successfully...";
          // Create the message part
          BodyPart messageBodyPart = new MimeBodyPart();
          // Create a multipar message
          messageBodyPart.setContent(content, "text/html");
          Multipart multipart = new MimeMultipart();
          // Set text message part
          multipart.addBodyPart(messageBodyPart);
          // Part two is attachment
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(attachment);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(attachment.getName());
          multipart.addBodyPart(messageBodyPart);
          // Send the complete message parts
          message.setContent(multipart);
        else {
          message.setContent(content, "text/html");
        }
        log = "Mail sent successfully...";
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse((StringemailProperties.get("to.address")));
        message.setRecipients(Message.RecipientType.CC,
            InternetAddress.parse((StringemailProperties.get("cc.address")));
        message.setRecipients(Message.RecipientType.BCC,
            InternetAddress.parse((StringemailProperties.get("bcc.address")));
        message.setFrom(new InternetAddress((StringemailProperties.get("from.address")));
        message.setSubject((StringemailProperties.get("mail.subject"));
        // Now set the actual message
        Transport.send(message);
        LOGGER.debug(log);
      else {
        LOGGER.error("Please provide email properties. There are no email properties.");
      }
    catch (

    AddressException e) {
      LOGGER.error("Problem while sending mail...");
      e.printStackTrace();
    catch (MessagingException e) {
      LOGGER.error("Problem while sending mail...");
      e.printStackTrace();
    }
    LOGGER.debug("Out EmailUtils.sendEmail(- -) method");
  }
}


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.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;

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

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

  private static final Logger LOGGER = Logger.getLogger(SFTPService.class);

  private Date sourceLastModifiedTime = null;
  private Date sourceLastModifiedTimeForEmail = null;

  private static List<String> outFileNames = new ArrayList<String>();
  private static List<String> inFileNames = new ArrayList<String>();

  public static void main(String[] args) {

    SFTPService fs = new SFTPService();

    final long timeDifferenceBetweenExec = getTimeDifferenceBetweenExecutions();

    final Date scheduleTimeForCoping = findScheduleTime(AppInit.timeScheduleToUploadSFTP);

    final Date scheduleTimeForDownload = findScheduleTime(AppInit.timeScheduleToDownlaodFromSFTP );

    final int attempts = calculateAttempts();

    addInFileNames();

    addOutFileNames();

    ensureDirectoryFileExist(AppInit.backupDirectory);

    final String enableCopyToSftpTask = AppInit.enableUploadTask;
    if (StringUtils.containsIgnoreCase(enableCopyToSftpTask, "true")) {
      Timer timer = new Timer();
      TimerTask dailyTask = new TimerTask() {
        @Override
        public void run() {
          LOGGER.debug("Timer executing at : : " new Date());
          fs.copyToSftp(attempts, AppInit.emailProperties, AppInit.sourceDirectory, AppInit.backupDirectory,
              AppInit.url, AppInit.sftpAddress, AppInit.sftpUserId, inFileNames,
              AppInit.sftpInDirectory);
        }
      };
      // schedule the task to run starting now and then every one day...
      timer.schedule(dailyTask, scheduleTimeForCoping, timeDifferenceBetweenExec);
    }

    final String enableDownloadTask = AppInit.enableDownloadTask;
    if (StringUtils.containsIgnoreCase(enableDownloadTask, "true")) {
      Timer timer1 = new Timer();
      TimerTask dailyTask1 = new TimerTask() {
        @Override
        public void run() {
          LOGGER.debug("Timer executing at : : " new Date());
          fs.readFileFromSftp(attempts, AppInit.url, AppInit.sftpAddress, AppInit.sftpUserId, AppInit.emailProperties,
              AppInit.sentEmailFileLocation, outFileNames, AppInit.sftpOutDirectory);
        }

      };
      // schedule the task to run starting now and then every one day...
      timer1.schedule(dailyTask1, scheduleTimeForDownload, timeDifferenceBetweenExec);
    }

  }

  private static void ensureDirectoryFileExist(final String fileAbsolutePath) {
    try {
      if (fileAbsolutePath != null) {
        File absoluteFile = new File(fileAbsolutePath);
        if (absoluteFile != null) {
          if (absoluteFile.isFile()) {
            absoluteFile.getParentFile().mkdirs();
            absoluteFile.createNewFile();
          else {
            absoluteFile.mkdirs();
          }
        }
      }
    catch (Exception e) {
      LOGGER.error("Problem while accessing the file path : : " + fileAbsolutePath);
      e.printStackTrace();
    }
  }

  private static void addInFileNames() {
    String sftpInFileNames = AppInit.sftpInFileNames;
    if (sftpInFileNames != null) {
      String[] files = sftpInFileNames.split(",");
      for (int i = 0; i < files.length; i++) {
        inFileNames.add(files[i]);
      }
    }
  }

  private static long getTimeDifferenceBetweenExecutions() {
    String timeDiff = AppInit.timeDifferenceBetweenExecutions;
    long timeDifferenceForExec = 0;
    if (timeDiff != null) {
      String[] values = timeDiff.split("\\*");
      for (String number : values) {
        if (number != null) {
          if (number.endsWith("L"|| number.endsWith("l")) {
            number = number.substring(0, number.length() 1);
          }
        }
        if (timeDifferenceForExec == 0) {
          timeDifferenceForExec = Long.parseLong(number);
        else {
          timeDifferenceForExec = timeDifferenceForExec * Long.parseLong(number);
        }
      }
    }
    return timeDifferenceForExec;
  }

  private static void addOutFileNames() {
    String sftpOutFileNames = AppInit.sftpOutFileNames;
    if (sftpOutFileNames != null) {
      String[] files = sftpOutFileNames.split(",");
      for (int i = 0; i < files.length; i++) {
        outFileNames.add(files[i]);
      }
    }
  }

  private static int calculateAttempts() {
    int tempMaxAttempts = 3;
    try {
      final String attemps = AppInit.attempts;
      if (attemps != null) {
        tempMaxAttempts = Integer.parseInt(attemps);
      }
    catch (Exception e) {
      // nothing to do here.
      LOGGER.error("Could not parse string " + ExceptionUtils.getStackTrace(e));
    }
    return tempMaxAttempts;
  }

  private static Date findScheduleTime(final String timeToSchedule) {
    Calendar date = Calendar.getInstance();
    if (timeToSchedule != null && timeToSchedule.contains(".")) {
      String[] timeValues = timeToSchedule.split("\\.");
      if (timeValues != null && timeValues.length > 1) {
        date.set(Calendar.HOUR, Integer.parseInt(timeValues[0]));
        date.set(Calendar.MINUTE, Integer.parseInt(timeValues[1]));
        final String meridian = timeValues[2];
        if (meridian != null && meridian.equalsIgnoreCase("AM")) {
          date.set(Calendar.AM_PM, 0);
        else {
          date.set(Calendar.AM_PM, 1);
        }
      }

    else {
      date.set(Calendar.HOUR, 10);
      date.set(Calendar.MINUTE, 0);
      date.set(Calendar.AM_PM, 1);
    }
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND, 0);
    Date preparedDate = date.getTime();
    Date currentDate = new Date();
    if (currentDate.after(preparedDate)) {
      date.add(Calendar.DATE, 1);
    }
    return date.getTime();
  }

  public void readFileFromSftp(final int maxAttempts, final URL url, final String sftpHost, final String userId,
      final Properties emailProperties, String sentEmailFileLocation, final List<String> outFileNames,
      final String sftpOutDirectory) {
    LOGGER.debug("In SFTPService.readFileFromSftp() method");
    boolean mailAlreadySend = false;
    ChannelSftp channel = null;
    for (int attempt = 1; attempt <= maxAttempts; ++attempt) {
      channel = getSftpConnection(url, sftpHost, userId, attempt, mailAlreadySend, emailProperties);
      if (channel == null) {
        mailAlreadySend = true;
      else {
        break;
      }
    }
    try {
      for (String outFileName : outFileNames) {
        if (sentEmailFileLocation == null) {
          sentEmailFileLocation = "C:/temp/email/sent/";
        }
        File fileInOut = new File(sentEmailFileLocation + "lastfile/" + outFileName);
        InputStream is = getInputStream(channel, outFileName, sftpOutDirectory,emailProperties);
        OutputStream os = null;
        try {
          if (!fileInOut.exists()) {
            fileInOut.getParentFile().mkdirs();
            fileInOut.createNewFile();
          }
          os = new FileOutputStream(fileInOut);
          if (is != null && os != null) {
            IOUtils.copy(is, os);
            backupFile(fileInOut, sentEmailFileLocation);
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
            String emailBody = emailProperties.getProperty("mail.body");
            emailBody = emailBody.replace("APPEND_DATE", sdf.format(new Date()));
            EmailUtils.sendEmail(emailProperties, emailBody, fileInOut);
          }
        catch (FileNotFoundException e) {
          LOGGER.error("ERROR : while accessing output file. File is : : " + fileInOut.getAbsolutePath());
          e.printStackTrace();
        catch (IOException e) {
          LOGGER.error("ERROR : while creating output file. File is : : " + fileInOut.getAbsolutePath());
          e.printStackTrace();
        }

      }
    catch (Exception e) {
      LOGGER.error("ERROR : while accessing input or output file.");
      e.printStackTrace();
    finally {
      if (channel != null && channel.isConnected()) {
        channel.disconnect();
      }
    }

    LOGGER.debug("EXIT - SFTPService.readFileFromSftp() method");

  }

  private void backupFile(final File sourceFile, final String destinationDirectory) {
    if (sourceFile != null) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
      String dateStr = sdf.format(new Date());
      dateStr = dateStr.replaceAll("/""_");
      dateStr = dateStr.replaceAll(" ""_");
      dateStr = dateStr.replaceAll(":""_");
      dateStr = dateStr.replaceAll("\\.""_");
      String newName = dateStr + "_" + sourceFile.getName();
      File destFile = new File(destinationDirectory + newName);
      try {
        if (!destFile.exists()) {
          destFile.createNewFile();
        }
        FileUtils.copyFile(sourceFile, destFile);
      catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  private InputStream getInputStream(ChannelSftp channel, final String outFileName,
      final String sftpOutDirectory,final Properties emailProperties) {

    InputStream inputStream = null;
    if (channel != null && outFileName != null) {
      try {
        LOGGER.debug("Reading file from SFTP location ...");
        if (sftpOutDirectory != null) {
          channel.cd(sftpOutDirectory);
          String lastModifiedTime = channel.lstat(outFileName).getMtimeString();
          if (appendFileLastModifiedTime(lastModifiedTime,emailProperties)) {
            inputStream = channel.get(outFileName);
            if (inputStream != null) {
              return inputStream;
            }
            LOGGER.debug("File has been read from SFTP location ...");
          }
        else {
          LOGGER.debug("Problem with the source outgoing directory is  : " + sftpOutDirectory);
        }
      catch (Exception e) {
        EmailUtils.sendEmail(emailProperties, "Problem while reading file from SFTP "null);
        LOGGER.error("There is a problem while reading  file from SFTP." + ExceptionUtils.getStackTrace(e));
      }
    else {
      EmailUtils.sendEmail(emailProperties, "Problem writing file to SFTP. Source file is empty "null);
    }
    return null;
  }

  private boolean appendFileLastModifiedTime(final String lastModifiedTime,final Properties emailPropertiesthrows ParseException {
    Date fileDate = null;
    Date nextDate = null;
    boolean flag = false;
    if (lastModifiedTime != null) {
      DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
      fileDate = dateFormat.parse(lastModifiedTime);
    }
    if (sourceLastModifiedTimeForEmail == null) {
      sourceLastModifiedTimeForEmail = fileDate;
    else {
      nextDate = fileDate;
    }
    if (nextDate != null && sourceLastModifiedTimeForEmail != null) {
      if (nextDate.after(sourceLastModifiedTimeForEmail)) {
        flag = true;
      }
      sourceLastModifiedTimeForEmail = nextDate;
    else if (sourceLastModifiedTimeForEmail != null) {
      flag = true;
    }

    if (!flag ) {
      EmailUtils.sendEmail(emailProperties, "No file to process today : : " new Date()null);
    }

    return flag;
  }

  public void copyToSftp(final int maxAttempts, final Properties emailProperties, final String sourceDirectory,
      final String backupDirectory, final URL url, final String sftpHost, final String userId,
      final List<String> inFileNames, final String sftpIncoimgDirectory) {
    LOGGER.debug("In SFTPService.copyToSftp() method");
    // writes to backup location.
    File fFile = writeToBackup(sourceDirectory, backupDirectory, emailProperties, inFileNames);
    if (fFile == null) {
      return;
    }
    boolean mailAlreadySend = false;
    ChannelSftp channel = null;
    for (int attempt = 1; attempt <= maxAttempts; ++attempt) {
      channel = getSftpConnection(url, sftpHost, userId, attempt, mailAlreadySend, emailProperties);
      if (channel == null) {
        mailAlreadySend = true;
      else {
        break;
      }
    }

    copyFileToSftp(channel, sftpHost, userId, fFile, emailProperties, sftpIncoimgDirectory);
    if (channel != null) {
      channel.disconnect();
    }
    LOGGER.debug("EXIT - SFTPService.copyToSftp() method");

  }

  private void copyFileToSftp(ChannelSftp channel, final String sftpHost, final String userId, final File file,
      final Properties emailProperties, final String sftpIncoimgDirectory) {
    if (channel != null && file != null) {
      try {
        LOGGER.debug("Coyping file to SFTP location ...");
        if (sftpIncoimgDirectory != null) {
          channel.cd(sftpIncoimgDirectory);
          channel.put(new FileInputStream(file), file.getName());
          LOGGER.debug(file.getName() " File has been copied to SFTP location ...");
        else {
          LOGGER.debug("Problem with the source incoming directory is  : " + sftpIncoimgDirectory);
        }
      catch (Exception e) {
        EmailUtils.sendEmail(emailProperties, "Problem writing file to SFTP " + ExceptionUtils.getStackTrace(e),
            null);
        LOGGER.error("There is a problem while getting the SFTP connection. Host IP : " + sftpHost
            " and User id : " + userId + " : : " + ExceptionUtils.getStackTrace(e));
      }
    else {
      EmailUtils.sendEmail(emailProperties, "Problem writing file to SFTP. Source file is empty "null);
    }
  }

  private ChannelSftp getSftpConnection(final URL keyURL, final String sftpHost, final String userId,
      final int attempt, final boolean mailAlreadySend, final Properties emailProperties) {
    Session session = null;
    ChannelSftp channel = null;
    JSch jsch = new JSch();
    try {
      if (keyURL == null || sftpHost == null || userId == null) {
        if (!mailAlreadySend) {
          EmailUtils.sendEmail(emailProperties,
              "No key found to connect to SFTP... host or userId is not proper. Host is : " + sftpHost
                  " and userId is : " + userId,
              null);
        }
        throw new RuntimeException("Key file auth-key not found in classpath");
      }
      URI keyFileURI = keyURL.toURI();
      jsch.addIdentity(new File(keyFileURI).getAbsolutePath());
      session = jsch.getSession(userId, sftpHost, 22);
      if (session != null) {
        session.setServerAliveCountMax(5);
        session.setConfig("StrictHostKeyChecking""no");

        session.setTimeout(1000);
        session.setConfig("PreferredAuthentications""publickey,keyboard-interactive,password");

        try {
          session.connect();
          channel = (ChannelSftpsession.openChannel("sftp");
          channel.connect();
          for (int i = 0; i < 5; ++i) {
            if (channel != null && channel.isConnected())
              break;
            Thread.sleep(10000);
          }
          return channel;
        catch (Exception e) {
          if (!mailAlreadySend || attempt > 4) {
            EmailUtils.sendEmail(emailProperties, "Attempt #" + attempt + ", Unable to connect to SFTP "
                + ExceptionUtils.getStackTrace(e)null);
          }
          LOGGER.error("There is a problem while getting the SFTP connection. Attempt #" + attempt
              ", Host IP : " + sftpHost + " and User id : " + userId + " : : "
              + ExceptionUtils.getStackTrace(e));
          Thread.sleep(60000 2);
        }
      }

    catch (Exception e) {
      if (!mailAlreadySend) {
        EmailUtils.sendEmail(emailProperties, "There is a problem while getting the SFTP connection. Host IP : "
            + sftpHost + " and User id : " + userId, null);
      }
      LOGGER.error("There is a problem while getting the SFTP connection. Host IP : " + sftpHost
          " and User id : " + userId + " : : " + e.getMessage());

    }
    return null;
  }

  private File writeToBackup(final String sourceDirectory, final String backupDirectory,
      final Properties emailProperties, final List<String> inFileNames) {
    File fFile = null;
    try {
      if (sourceDirectory != null && backupDirectory != null) {
        File[] listOfFiles = new File(sourceDirectory).listFiles();
        if (listOfFiles != null && listOfFiles.length > 0) {
          for (File file : listOfFiles) {
            if (file != null && file.isFile()) {
              String fileName = file.getName();
              try {
                boolean fileMatched = false;
                if (inFileNames != null && !inFileNames.isEmpty()) {
                  for (String configuredInFileName : inFileNames) {
                    if (configuredInFileName != null) {
                      if (fileName != null) {
                        if (StringUtils.containsIgnoreCase(fileName,
                            configuredInFileName)) {
                          fileMatched = true;
                          fFile = file;
                          break;
                        }
                      }
                    }
                  }
                else {
                  LOGGER.debug("There are no files name provided for the inFileNames...");
                }
                if (fileMatched) {
                  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
                  Date nextDate = null;
                  if (sourceLastModifiedTime == null) {
                    sourceLastModifiedTime = sdf.parse(sdf.format(file.lastModified()));
                  else {
                    nextDate = sdf.parse(sdf.format(file.lastModified()));
                  }
                  boolean flag = false;
                  if (nextDate != null && sourceLastModifiedTime != null) {
                    if (nextDate.after(sourceLastModifiedTime)) {
                      flag = true;
                    }
                    sourceLastModifiedTime = nextDate;
                  else if (sourceLastModifiedTime != null) {
                    flag = true;
                  }

                  if (!flag) {
                    EmailUtils.sendEmail(emailProperties,
                        "No file to process today : : " new Date()null);
                    break;
                  }

                  String dateStr = sdf.format(new Date());
                  dateStr = dateStr.replaceAll("/""_");
                  dateStr = dateStr.replaceAll(" ""_");
                  dateStr = dateStr.replaceAll(":""_");
                  dateStr = dateStr.replaceAll("\\.""_");
                  String backupFile = dateStr + "_" + fileName;
                  InputStream inputStream = null;
                  try {
                    inputStream = new FileInputStream(file);
                    LOGGER.debug("Coping file to backup location : : " + backupDirectory + "\\"
                        + backupFile);
                    IOUtils.copy(inputStream,
                        new FileOutputStream(new File(backupDirectory"/" + backupFile));
                    LOGGER.debug("File has been copied to backup location : : " + backupDirectory
                        "\\" + backupFile);
                  catch (Exception e) {
                    EmailUtils.sendEmail(emailProperties,
                        "Could not write file to backup location: "
                            + ExceptionUtils.getStackTrace(e),
                        null);

                    LOGGER.error("Problem while taking the file backup !!!"
                        + ExceptionUtils.getStackTrace(e));

                  finally {
                    if (inputStream != null) {
                      inputStream.close();
                    }
                  }
                }
              catch (Exception e) {
                LOGGER.error(e.getStackTrace());
              }
            }
          }
        else {
          EmailUtils.sendEmail(emailProperties,
              "There are no files available in the " + sourceDirectory + " directory!!!"null);
          LOGGER.debug("There are no files available in the " + sourceDirectory + " directory");
        }
      else {
        EmailUtils.sendEmail(emailProperties, "There are no files available in the source : " + sourceDirectory
            " or backup : " + backupDirectory + " directory!!!"null);
        LOGGER.debug("There are no files available in the source : " + sourceDirectory + " or backup : "
            + backupDirectory + "  directory");
      }
    catch (Exception e) {
      EmailUtils.sendEmail(emailProperties, "There is a problem while accessing the Source directory : "
          + sourceDirectory + ExceptionUtils.getStackTrace(e)null);
      LOGGER.error("There is a problem while accessing the Source directory." + e.getStackTrace());

    }
    return fFile;
  }

}


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.service</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