Showing posts with label FILE. Show all posts
Showing posts with label FILE. Show all posts

Wednesday, September 10, 2014

File Retention or Cleanup in java

How to cleanup files from file store based on retention period

Sample Java Program:



public class McatSRSFileUtil {

     
     private static Logger logger = LoggerFactory.getLogger(McatSRSFileUtil.class); 
   
     private Date currDate = new Date(); 
     private String pathToBeExcluded = ""; 
     
     /**
      * Main method would be invioked by quartz job to clean up the file which is older than 90 days
      * 
      * @throws Exception
      */ 
    public void processFileRetention(String srcDir, int retentionPeriod)
            throws Exception {
        logger.info("HOUSE KEEPING PROCESS - START");

        executeFileRetention(new File(srcDir), retentionPeriod);

        logger.info("HOUSE KEEPING PROCESS - COMPLETED");
    }
     
     /**
      * DELETE FILES OLDER THAN SPECIFED RETENTION PERIOD
      * 
      * @param deleteDir
      * @param retentionPeriod
      * @throws IOException
      */ 
    private void executeFileRetention(File deleteDir, int retentionPeriod)
            throws IOException {
        if (!deleteDir.exists()) {
            logger.warn("SKIP RETENTION... INVALID DIRECTORY TO DELETE FILE FROM -"
                    + deleteDir);
            return;
        }

        if (retentionPeriod == 0) {
            logger.warn("SKIP RETENTION... RETENTION PERIOD NOT SPECIFIED");
            return;
        }

        logger.info("CHECKING FOR OLD FILES IN DIR - "
                + deleteDir.getCanonicalPath());

        File[] dirList = deleteDir.listFiles();
        if (dirList.length == 0) {
            logger.info("NO FILES FOUND IN " + deleteDir.getCanonicalPath());
            return;
        }
        for (File file : dirList) {
            logger.trace("processing file:" + file);
            if (file.isDirectory()) {
                // DO NOT DELETE DIRECTORIES!!!!
                // RECURSIVELY CHECK SUB-DIRECTORIES FOR OLDER FILES
                executeFileRetention(file, retentionPeriod);
            } else if (file.isFile()) {
                // TODO CHEK FOR FILENAME PATTERN
                if (isFileOld(file, retentionPeriod)) {
                    deleteFile(file);
                }
            }
        }

    }
     
     /**
      * 
      * @param file
      *            file to be verified
      * @param retentionPeriod
      *            number of days to retain files
      * @return
      * @throws IOException
      */ 
     private boolean isFileOld(File file, int retentionPeriod) 
       throws IOException { 
      Date lastModifiedDate; 
      lastModifiedDate = new Date(file.lastModified()); 
      logger.trace(file + " last modified on " + lastModifiedDate); 
      int diffInDays = getDifferenceInDays(currDate, lastModifiedDate); 
      logger.trace("DIFF IN DAYS:" + diffInDays); 
     
      if (diffInDays > retentionPeriod) { 
       logger.trace(file.getCanonicalPath() + " IS OLD. DAYS-" 
         + diffInDays); 
       return true; 
      } 
      return false; 
     } 
      
     
     /**
      * DELETE SPECIFIED FILE
      * 
      * @param file
      *            file to be deleted
      * @throws IOException
      */ 
     public void deleteFile(File file) throws IOException { 
      String strCanonicalPath = file.getCanonicalPath(); 
      logger.debug("DELETING FILE " + strCanonicalPath); 
      // DO NOT DELETE ANY DIRECTORIES 
      if (!file.exists() || !file.isFile()) { 
       logger.error("INVALID FILE " + strCanonicalPath); 
       return; 
      } 
      boolean deleteStatus = file.delete(); 
      if (!deleteStatus) { 
       logger.error("FAILED TO DELETE FILE " + strCanonicalPath); 
      } 
     } 
     
     /**
      * derive file name to be used in tar. basically removes the directory path.
      * 
      * @param file
      * @return file name to be used in tar
      * @throws IOException
      */ 
     private String getFileName(File file) throws IOException { 
      // filename to be used in tar 
      String strCanonicalPath = file.getCanonicalPath(); 
      String fileName = ""; 
      // INDEX OF SRC 
      int index = strCanonicalPath.indexOf(pathToBeExcluded); 
      if (index >= 0) { 
       fileName = strCanonicalPath.substring(index 
         + pathToBeExcluded.length() + 1); 
      } 
      logger.trace("Name to be used in TAR-" + fileName); 
      return fileName; 
     } 
     
     // ************ COMMON UTILITY FUNCTIONS **************** 
     
     /**
      * CLOSE STREAM
      * 
      * @param stream
      * @throws IOException
      */ 
     private void close(Closeable stream) throws IOException { 
      try { 
       if (stream != null) { 
        stream.close(); 
       } 
      } catch (IOException ioEx) { 
       logger.warn("error closing stream", ioEx); 
       throw ioEx; 
      } 
     } 
   
     /**
      * This method checks whether the string is empty or not
      * 
      * @param strToCheck
      *            the string to be checked
      * @return it returns true if the string is null or empty, otherwise it
      *         returns false
      */ 
     public static boolean isStringEmpty(String strToCheck) { 
      if ((null == strToCheck) || strToCheck.trim().isEmpty()) { 
       return true; 
      } else { 
       return false; 
      } 
     } 
     
     /**
      * get the difference in days between two dates. considers DST.
      * 
      * @param date1
      *            the first date
      * @param date1
      *            the second date
      * 
      * @return int the difference in days (-ve if date1 < date2)
      * @throws ParseException
      */ 
     public static int getDifferenceInDays(Date date1, Date date2) { 
     
      Calendar cal1 = Calendar.getInstance(); 
      cal1.setTime(date1); 
     
      Calendar cal2 = Calendar.getInstance(); 
      cal2.setTime(date2); 
     
      // HAVE TO CONVERT BOTH THE INPUT DATES TO GMT TIMEZONE 
     
      // cal.getTimeZone().getOffset(cal.getTimeInMillis()) -> amount of time 
      // in milliseconds to add to GMT to get local time 
     
      long timeDiff = (cal1.getTimeInMillis() + cal1.getTimeZone().getOffset( 
        cal1.getTimeInMillis())) 
        - (cal2.getTimeInMillis() + cal2.getTimeZone().getOffset( 
          cal2.getTimeInMillis())); 
      return (int) TimeUnit.MILLISECONDS.toDays(timeDiff); 
     
      // long timeDiff = Math.abs(date1.getTime() - date2.getTime()); 
      // return (int) TimeUnit.MILLISECONDS.toDays(timeDiff); 
     } 
     
     /**
      * get current date
      * 
      * @param dateFormat
      * @return
      */ 
     public static String getCurrentDateTime(String dateFormat) { 
      Date today = new Date(); 
      DateFormat formatter = new SimpleDateFormat(dateFormat); 
      return formatter.format(today); 
     } 
     
    public static void main(String[] args) {
        String srcDir = "C:\\opt\\filestore\\appdata\\ci\\import";
        McatSRSFileUtil tester = new McatSRSFileUtil();
        try {
            tester.processFileRetention(srcDir, 60);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
   
}

Wednesday, July 9, 2014

Findout the File Extension in java

How to findout the file extension in java



    public String getFileExtension(File file) {
        String fileName = file.getAbsolutePath()+ file.getName();
       
        String extn = FilenameUtils.getExtension(fileName);
        return extn;
    }




Tuesday, February 8, 2011

Writing A text/xml file into a Tomcat WEB-INF folder

How to write a file(text or xml) file into a TOMCAT WEB-INF folder


code snippet  for writing a text file into the Tomcat WEB-INF folder:

...
...
String realPath = getServletContext().getRealPath("/WEB-INF/log");
// it returns  D:\apps\apache-tomcat-6.0.24\webapps\CodeAnalyser\WEB-INF\log  as realPath value

File curFile = File.createTempFile("SopOut", ".txt", new File(realPath));

// it will creat a file SopOUt.txt in to the  D:\apps\apache-tomcat-6.0.24\webapps\CodeAnalyser\WEB-INF\log  folder

// write to file
FileWriter fw = new FileWriter(curFile);

try {
      fw.write(sb); // sb contains the content to be written into the file
} finally {
    fw.flush();
    fw.close();
}

...
...