File exchange with timer example

Click here to download eclipse supported ZIP file



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




key_authentication.source.fileLocation=C:/temp/cv/
key_authentication.backup.fileLocation=C:/temp/cv/sent/
key_authentication.destination.fileLocation=C:/temp/cv/dest/
MODE_OF_CONNECTIONS=key
#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]
runsAt=10.00.PM
message=There is a problem in the server.
host=smtp.sendgrid.net
port=25
toAddress=cvXXXXXX@gmail.com
ccAddress=cvXXXXXX@gmail.com
fromAddress=cvXXXXXX@gmail.com
username=XXXXX
password=XXXXX
time_difference_between_executions = 1000*60*60*24


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



 

    
package com.cv.file.backup.write;

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 keyAuthDestinationDirectory = null;
  static String keyAuthSourceDirectory = null;
  static String keyAuthBackupDirectory = null;
  
  static String authMode = null;
  static String timeToSchedule = 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 String timeDifferenceBetweenExecutions = 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) {      
      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");
      timeDifferenceBetweenExecutions = readPropertiesFile2.getProperty("time_difference_between_executions");
      timeToSchedule = readPropertiesFile2.getProperty("runsAt");
      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 {
      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 URL readAuthKeyFile() {
    URL url = null;
    try {
      LOGGER.debug("key file read successfully...");
      url = AppInit.class.getClassLoader().getResource("ssh1_one");
    catch (Exception e) {
      LOGGER.error("Problem while reading auth-key file : : "+e.getMessage());
    }
    return url;
  }

}

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



 

    
package com.cv.file.backup.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;
import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 *
 */
public class EmailUtility {
  private static final Logger LOGGER = Logger.getLogger(EmailUtility.class);

  public static void sendEmail(final String subject, final String content) {
    LOGGER.debug("In EmailUtility.sendEmail(- -) method");
    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("SFTP - Foxtel : " + subject);
      message.setText(content);
      Transport.send(message);
      LOGGER.debug("mail sent successfully....");

    catch (AddressException e) {
      e.printStackTrace();
    catch (MessagingException e) {
      e.printStackTrace();
    }
    LOGGER.debug("Out EmailUtility.sendEmail(- -) method");
  }
}




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



 

    
package com.cv.file.backup.write;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

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

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

  private Date sourceLastModifiedTime = null;

  public static void main(String[] args) {

    FileSystemTimer fs = new FileSystemTimer();

    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);
        }
      }
    }
    String timeToSchedule = AppInit.timeToSchedule;
    Calendar date = Calendar.getInstance();
    if (timeToSchedule != null) {
      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]));
        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, 11);
      date.set(Calendar.MINUTE, 0);
      date.set(Calendar.AM_PM, 1);
    }
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND, 0);
    Timer timer = new Timer();
    TimerTask dailyTask = new TimerTask() {
      @Override
      public void run() {
        LOGGER.debug("Timer executing at : : " new Date());
        String authMode = AppInit.authMode;
        if (authMode != null && authMode.equalsIgnoreCase("key")) {
          fs.fileSentBackup();
        else {
          fs.fileSentBackup();
        }
      }
    };

    // schedule the task to run starting now and then every hour...
    timer.schedule(dailyTask, date.getTime(), timeDifferenceForExec);
  }

  public void fileSentBackup() {
    LOGGER.debug("In FileSystemTimer.fileSentBackup() method");

    try {
      File[] listOfFiles = new File(AppInit.keyAuthSourceDirectory).listFiles();
      String destination = AppInit.keyAuthDestinationDirectory;
      if (destination != null) {
        File desFile = new File(destination);
        if (!desFile.exists()) {
          desFile.mkdirs();
        }
      }
      if (listOfFiles != null && listOfFiles.length > 0) {
        for (File file : listOfFiles) {
          if (file != null && file.isFile()) {
            String fileName = file.getName();
            try {
              if (fileName != null) {
                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) {
                  EmailUtility.sendEmail(" No file to process today !!!",
                      "No file to process today : : " new Date());
                  break;
                }

                String dateStr = sdf.format(new Date());
                dateStr = dateStr.replaceAll("/""_");
                dateStr = dateStr.replaceAll(" ""_");
                dateStr = dateStr.replaceAll(":""_");
                dateStr = dateStr.replaceAll("\\.""_");
                InputStream inputStream = new FileInputStream(file);
                LOGGER.debug("Coping file to SFTP location ...");
                IOUtils.copy(inputStream, new FileOutputStream(destination + "\\" + fileName));
                LOGGER.debug(fileName + " File has been copied to SFTP location ...");
                String backUpDir = AppInit.keyAuthBackupDirectory;
                File backDir = new File(backUpDir);
                if (backDir != null && !backDir.exists()) {
                  backDir.mkdirs();
                }
                String backupFile = dateStr + "_" + fileName;
                try {
                  InputStream inputStream2 = new FileInputStream(file);
                  LOGGER.debug("Coping file to backup location : : " + backDir + "\\" + backupFile);
                  IOUtils.copy(inputStream2, new FileOutputStream(backDir + "\\" + backupFile));
                  LOGGER.debug("File has been copied to backup location : : " + backDir + "\\"
                      + backupFile);
                catch (Exception e) {
                  EmailUtility.sendEmail("Problem while taking the file backup !!!",
                      "There is a problem while taking the file backup !!!");

                  LOGGER.error("Problem while taking the file backup !!!");

                }
              }
            catch (Exception e) {
              EmailUtility.sendEmail("Problem while accessing source directory",
                  "Problem while accessing source directory");
              LOGGER.error("Problem while accessing source directory" + e.getLocalizedMessage());

            }
          }
        }
      else {
        EmailUtility.sendEmail(
            "There are no files available in the " + AppInit.keyAuthSourceDirectory + " directory!!!",
            "There are no files available in the " + AppInit.keyAuthSourceDirectory + " directory!!!");
        LOGGER.debug("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.");
      LOGGER.error("There is a problem while accessing the Source directory " + e.getMessage());

    finally {

    }
    LOGGER.debug("Out FileSystemTimer.fileSentBackup() method");

  }

}


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.file.backup.write</groupId> <artifactId>FileExchangeWithTimer</artifactId> <version>1.0</version> <url>http://maven.apache.org</url> <properties> <log4j-version>1.2.17</log4j-version> 1.8 FileExchangeWithTimer </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