[Schmitzm-commits] r2399 - trunk/schmitzm-core/src/main/java/de/schmitzm/io

scm-commit at wald.intevation.org scm-commit at wald.intevation.org
Mon Feb 10 19:10:44 CET 2014


Author: mojays
Date: 2014-02-10 19:10:44 +0100 (Mon, 10 Feb 2014)
New Revision: 2399

Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtilBasic.java
Log:
IOUtilBasic: Command line tools to check whether file or directory exists

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtilBasic.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtilBasic.java	2013-10-12 20:04:41 UTC (rev 2398)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtilBasic.java	2014-02-10 18:10:44 UTC (rev 2399)
@@ -30,6 +30,9 @@
 package de.schmitzm.io;
 
 import java.io.File;
+import java.io.FileFilter;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
 
 /**
  * This class contains IO utility methods which only depend on standard JDK
@@ -39,7 +42,77 @@
  *
  */
 public class IOUtilBasic {
+  private static final long       DAY_MILLIS   = 24 * 60 * 60 * 1000;
+  private static final long       CURR_MILLIS  = System.currentTimeMillis();
+  private static final long       TODAY_MILLIS = CURR_MILLIS / DAY_MILLIS * DAY_MILLIS;
+  private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+  
   /**
+   * Checks whether a file (or directory) exists which modifying date is in
+   * the given range.
+   * @param filepath path to directory or file (may include "*" wildcard)
+   * @param mode additional filter mode (0 = files and directories; 1 = files only; 2 = directories only)
+   * @param modMillisFrom modification date has to be newer or equal than this date (if 0 this parameter is ignored)
+   * @param modMillisTo   modification date has to be older or equal than this date (if 0 this parameter is ignored)
+   */
+  public static boolean checkFileExists(String filepath, int mode, long modMillisFrom, long modMillisTo) {
+    // Replace masked wildcard
+//    System.out.println("filepath    = "+filepath);
+    filepath = filepath.replaceAll("\\\\\\\\\\*", "*"); // "\\*" -> RegEx "\\\\\*" -> Java "\\\\\\\\*"
+    
+    File             f         = new File(filepath);
+    File             dir       = f.getParentFile(); //f.isDirectory() ? f : f.getParentFile();
+    String           filterStr = f.getName();
+    final FileFilter filter    = createSimpleFileFilter(filterStr,mode); 
+    
+//    System.out.println("filepath    = "+filepath);
+//    System.out.println("f           = "+f.getAbsolutePath());
+//    System.out.println("dir         = "+dir.getAbsolutePath());
+//    System.out.println("filterStr   = "+filterStr);
+    
+    if ( dir == null )
+      dir = new File(".");
+    if ( !dir.exists() || !dir.isDirectory() )
+      return false;
+    
+    final long _modMillisFrom = modMillisFrom;
+    final long _modMillisTo   = modMillisTo;
+    FileFilter filter2 = new FileFilter() {
+      @Override
+      public boolean accept(File pathname) {
+        // only check files which satisfy given filter
+        if ( !filter.accept(pathname) )
+          return false;
+        long modMillis = pathname.lastModified();
+        // Check date range
+        if ( _modMillisFrom > 0 && modMillis < _modMillisFrom )
+          return false;
+        if ( _modMillisTo > 0 && modMillis > _modMillisTo )
+          return false;
+        
+        return true;
+      }
+    };
+    
+    File[] files = dir.listFiles(filter2);
+    return files != null && files.length > 0;
+  }
+
+  /**
+   * Checks whether a file exists (as file, not directory!).
+   */
+  public static boolean checkFileExists(File f) {
+    return f.exists() && f.isFile();
+  }
+  
+  /**
+   * Checks whether a directory exists.
+   */
+  public static boolean checkDirExists(File f) {
+    return f.exists() && f.isDirectory();
+  }
+  
+  /**
    * Renames (or moves) a file.
    * @param source file to rename (or move) 
    * @param dest destination directory for move or simply the new filename (if {@code dest} does
@@ -102,67 +175,304 @@
      * Executes one of the following commands:
      * <ul>
      * <li>{@code MOVE source dest delaMillis}<br>
-     *     Moved a file on the file system.</li>
+     *     Moves a file on the file system.</li>
      * <li>{@code EXEC delayMillies command args}<br>
      *     Executes an OS command.</li>
+     * <li>{@code FILEEXISTS path_pattern [yyyy-mm-dd [yyyy-mm-dd]]}<br>
+     *     Checks whether a file exists for the given path with last modification date
+     *     satisfies the given date range.</li>
+     * <li>{@code DIREXISTS path_pattern [yyyy-mm-dd [yyyy-mm-dd]]}<br>
+     *     Checks whether a directory exists for the given path with last modification date
+     *     satisfies the given date range.</li>
+     * <li>{@code EXISTS path_pattern [yyyy-mm-dd [yyyy-mm-dd]]}<br>
+     *     Checks whether a file or directory exists for the given path with last modification date
+     *     satisfies the given date range.</li>
      * </ul>
    */
   public static void main(String[] arg) throws Exception {
 //TEST
-//    arg = new String[] {"EXEC",
-//                        "4000",
-//                        "D:\\java\\Majordomo\\majordomomanager-trunk\\dist\\majordomo-1.0-SNAPSHOT\\majordomo-manager-1.0.exe",
-//                        "/L",
-//                        "de"
+//    arg = new String[] {};
+//    arg = new String[] {"DIREXISTS",
+//                        "M:\\Games"
+//                        "TODAY",
+//                        "TODAY"
 //    };
+//    for (String a : arg) {
+//      System.out.println(a);
+//    }
 
+    try {
+      if (arg.length == 0 || isHelpParameter(arg[0]))
+        showCommandLineHelp("", 0);
+  
+      // Parameter 1 = command
+      String func = arg[0].toUpperCase();
+      // If parameter 2 is "help", show command help
+      if (arg.length >= 2 && isHelpParameter(arg[1]))
+        showCommandLineHelp(func, 0);
+        
+      if ( func.equals("MOVE") ) {
+        // ###### MOVE ######
+        if (arg.length < 3)
+          throw new IllegalArgumentException(func);
+        if (arg.length > 3) {
+          long delay = Integer.parseInt(arg[3]);
+          Thread.sleep(delay);
+        }
+        File source = new File(arg[1]);
+        File sourceMoved = renameFile(source, arg[2], true);
+        if ( sourceMoved == null )
+          throw new HandledException("Could not move "+arg[1]+" to "+arg[2]);
+      } else if ( func.equals("EXEC") ) {
+        // ###### EXEC ######      
+        if (arg.length < 3)
+          throw new IllegalArgumentException(func);
+        long delay = Integer.parseInt(arg[1]);
+  // Funktioniert nicht, da StatusDialog SwingUtil nutzt, das wiederum z.B. Log4J
+  // referenziert, also nicht pur SCHMITZM-CORE!
+  //      final StatusDialog status = new StatusDialog(null, "Please wait...", null);
+  //      SwingUtilities.invokeLater( new Runnable() {
+  //        @Override
+  //        public void run() {
+  //          status.setVisible(true);
+  //        }
+  //      });
+        Thread.sleep(delay);
+  //      status.setVisible(false);
+        String command = "";
+        for (int i=2; i<arg.length; i++)
+          command += " " + maskPath(arg[i]);
+        Runtime.getRuntime().exec(command);
+      } else if ( func.equals("EXISTS")  || func.equals("FILEEXISTS")  || func.equals("DIREXISTS") ) {
+        // ###### EXISTS / FILE EXISTS / DIRECTORY EXISTS ######      
+        if (arg.length < 2) {
+          throw new IllegalArgumentException(func);
+        }
+        int    mode       = func.equals("EXISTS") ? 0 : func.equals("FILEEXISTS") ? 1 : 2;
+        String path       = arg[1];
+        long   millisFrom = arg.length < 3 ? 0 : "TODAY".equals(arg[2]) ? TODAY_MILLIS                 : DATE_FORMAT.parse(arg[2]).getTime();
+        long   millisTo   = arg.length < 4 ? 0 : "TODAY".equals(arg[3]) ? TODAY_MILLIS + DAY_MILLIS -1 : DATE_FORMAT.parse(arg[3]).getTime() + DAY_MILLIS -1;
+        
+        boolean exists = checkFileExists(path, mode, millisFrom, millisTo);
+//        System.out.println("File exists: "+exists);
+        if ( !exists )
+          System.exit(3);
+
+      } else {
+        System.err.println("Unknown function: " + func + "\n");
+        showCommandLineHelp("", 1);
+      }
+    } catch (Exception err) {
+      if ( err instanceof HandledException ) {
+        System.err.println(err.getMessage());
+        System.exit(1);
+      }
+      if ( err instanceof IllegalArgumentException ) {
+        String mess = "Missing arguments";
+        if ( err.getMessage() != null )
+          mess += " for "+err.getMessage()+" command";
+        System.err.println(mess+"!\n");
+        showCommandLineHelp(err.getMessage(), 1);
+      }
+      err.printStackTrace();
+      System.exit(2);
+    }
+    // Successful termination
+    System.exit(0);
+  }
+  
+  /**
+   * Checks whether the given parameter is a "help" parameter (?, -h, --help, ...).
+   */
+  private static boolean isHelpParameter(String param) {
+    return "?".equals(param)
+        || "-?".equals(param)
+        || "-h".equals(param)
+        || "--help".equals(param);
+  }
+  
+  /**
+   * Shows the command line help.
+   * @param commandID if empty a general help is show. Otherwise the corresponding command
+   *                  specific information
+   * @param exitCode  if >= 0 the function terminates the programm with the given code.
+   */
+  private static void showCommandLineHelp(String commandID, int exitCode) throws IllegalArgumentException {
+    if ( commandID == null )
+      commandID = "";
+    commandID = commandID.toUpperCase().trim();
     
-    if (arg.length == 0) {
-      System.err.println("Missing arguments.");
-      return;
-    }
+    String command = IOUtilBasic.class.getSimpleName() + " " + commandID;
+    command = command.trim();
 
-    String func = arg[0].toUpperCase();
-    if ( func.equals("MOVE") ) {
-      // ###### MOVE ######
-      if (arg.length < 3) {
-        System.err.println("Missing arguments for "+func+".");
+    try {
+      // General command line help
+      if ( "".equals(commandID) ) {
+        System.err.println(command+" executes one of several shell commands.");
+        System.err.println("Usage:");
+        System.err.println("  "+command+" <command> [<command-args>]");
+        System.err.println("Parameters:");
+        System.err.println("  command = MOVE        moves a file on the file system");
+        System.err.println("            EXEC        executes one or more individual OS command(s)");
+        System.err.println("            FILEEXISTS  checks whether a file exists on the file system");
+        System.err.println("            DIREXISTS   checks whether a directory exists on the file system");
+        System.err.println("            EXISTS      checks whether a file or directory exists on the file system");
+        System.err.println("  command-args = arguments depend on command");
+        System.err.println("                 Call '"+IOUtilBasic.class.getSimpleName()+" <command>' for");
+        System.err.println("                 details about the command argurments");
         return;
       }
-      if (arg.length > 3) {
-        long delay = Integer.parseInt(arg[3]);
-        Thread.sleep(delay);
+      
+      // MOVE command line help
+      if ( "MOVE".equals(commandID) ) {
+        System.err.println(command+" moves a file on the file system.");
+        System.err.println("Usage:");
+        System.err.println("  "+command+" <source> <dest> [<delay>]");
+        System.err.println("Parameters:");
+        System.err.println("  source = Source file path");
+        System.err.println("  dest   = Destination file path.");
+        System.err.println("           If destination is an existing directory the file name remains unchanged.");
+        System.err.println("           Otherwise the move includes file name change.");
+        System.err.println("  delay  = Delay in ms executed before command.");
+        return;
       }
-      File source = new File(arg[1]);
-      File sourceMoved = renameFile(source, arg[2], true);
-      if ( sourceMoved == null )
-        System.err.println("Could not move "+arg[1]+" to "+arg[2]);
-    } else if ( func.equals("EXEC") ) {
-      // ###### EXEC ######      
-      if (arg.length < 3) {
-        System.err.println("Missing arguments for "+func+".");
+  
+      // EXEC command line help
+      if ( "EXEC".equals(commandID) ) {
+        System.err.println(command+" executes one or more individual OS command(s).");
+        System.err.println("Usage:");
+        System.err.println("  "+command+" <delay> <command> [<command> [<command> [...]]]");
+        System.err.println("Parameters:");
+        System.err.println("  delay   = Delay in ms executed before first command.");
+        System.err.println("  command = Individual IO command (as called on OS shell)");
         return;
       }
-      long delay = Integer.parseInt(arg[1]);
-// Funktioniert nicht, da StatusDialog SwingUtil nutzt, das wiederum z.B. Log4J
-// referenziert, also nicht pur SCHMITZM-CORE!
-//      final StatusDialog status = new StatusDialog(null, "Please wait...", null);
-//      SwingUtilities.invokeLater( new Runnable() {
-//        @Override
-//        public void run() {
-//          status.setVisible(true);
-//        }
-//      });
-      Thread.sleep(delay);
-//      status.setVisible(false);
-      String command = "";
-      for (int i=2; i<arg.length; i++)
-        command += " " + maskPath(arg[i]);
-      Runtime.getRuntime().exec(command);
-    } else {
-      System.err.println("Unknown function: " + func);
+  
+      // EXISTS command line help
+      if ( "EXISTS".equals(commandID) ||
+           "FILEEXISTS".equals(commandID) ||
+           "DIREXISTS".equals(commandID) ) {
+        String filedir = commandID.equals("EXISTS") ? "file or directory" : commandID.equals("FILEEXISTS") ? "file" : "directory";
+        System.err.println(command+" checks whether a "+filedir+" exists on the file system.");
+        System.err.println("Usage:");
+        System.err.println("  "+command+" <path> [<date-from> [<date-to>]]");
+        System.err.println("Parameters:");
+        System.err.println("  path      = "+filedir+" path to check. May include *-wildcard.");
+        System.err.println("              NOTE: If you get a ParseException when using *-wildcard, your shell");
+        System.err.println("                    automatically expands the wildcard. To avoid this behaviour,");
+        System.err.println("                    mask the wildcard (e.g. with \\\\ on Windows OS; in this case");
+        System.err.println("                    you should separate your path with / characters).");
+        System.err.println("  date-from = If set, "+filedir+" modifying date is additionally checked to");
+        System.err.println("              be newer or equal this date (Format: YYYY-MM-DD).");
+        System.err.println("              Special value 'TODAY' can be specified to indicate current date.");
+        System.err.println("  date-to   = If set, "+filedir+" modifying date is additionally checked to");
+        System.err.println("              be older or equal this date (Format: YYYY-MM-DD).");
+        System.err.println("              Special value 'TODAY' can be specified to indicate current date.");
+        return;
+      }
+      System.err.println("Unknown function: " + commandID + "\n");
+      showCommandLineHelp("", 1);
+   } finally {
+      if ( exitCode >= 0 )
+        System.exit(exitCode);
     }
-//    System.exit(0);
   }
+  
+  private static class HandledException extends RuntimeException {
+    public HandledException(String mess) {
+      super(mess);
+    }
+  }
 
+  //////////////////////////////////////////////////////////////////////////
+  ///////////  COPY OF FilterUtil.createSimpleFileFilter(..)  //////////////
+  //////////////////////////////////////////////////////////////////////////
+  /**
+   * Creates einen Filter fuer einen Filter-String. Dieser kann als Wildcard
+   * das Zeichen "*" enthalten. Alle anderen Zeichen werden direkt als Filter
+   * verwendet.
+   * 
+   * @param filterStr
+   *            definiert den Filter
+   */
+  public static FileFilter createSimpleFileFilter(String filterStr,
+          final int mode) {
+      if ( filterStr == null || "".equals(filterStr.trim()) )
+        filterStr = "*";
+      
+      // Gross/Klein-Schreibung ignorieren
+      filterStr = filterStr.toLowerCase();
+
+      // ##### Filter definiert den "inneren" Teil eines Dateinames #####
+      if (filterStr.startsWith("*") && filterStr.endsWith("*")) {
+          // Filter besteht nur aus "*" --> alle Dateien akzeptieren
+          if (filterStr.length() <= 2)
+              return new FileFilter() {
+                  public boolean accept(File file) {
+                      return fileFitsFilterMode(file, mode);
+                  }
+              };
+          // "inneren" Teil des Filters extrahieren
+          final String condStr = filterStr.substring(1,
+                  filterStr.length() - 1);
+          return new FileFilter() {
+              public boolean accept(File file) {
+                  return fileFitsFilterMode(file, mode)
+                          && file.getName().toLowerCase().contains(condStr);
+              }
+          };
+      }
+
+      // ##### Filter definiert den Anfang eines Dateinames #####
+      if (filterStr.endsWith("*")) {
+          // Anfang des Filters extrahieren
+          final String condStr = filterStr.substring(0,
+                  filterStr.length() - 1);
+          return new FileFilter() {
+              public boolean accept(File file) {
+                  return fileFitsFilterMode(file, mode)
+                          && file.getName().toLowerCase().startsWith(condStr);
+              }
+          };
+      }
+      // ##### Filter definiert das Ende eines Dateinames #####
+      if (filterStr.startsWith("*")) {
+          // Ende des Filters extrahieren
+          final String condStr = filterStr.substring(1);
+          return new FileFilter() {
+              public boolean accept(File file) {
+                  return fileFitsFilterMode(file, mode)
+                          && file.getName().toLowerCase().endsWith(condStr);
+              }
+          };
+      }
+      // ##### Filter definiert den genauen Dateinamen #####
+      final String condStr = filterStr;
+      return new FileFilter() {
+          public boolean accept(File file) {
+              return fileFitsFilterMode(file, mode)
+                      && file.getName().equalsIgnoreCase(condStr);
+          }
+      };
+  }
+
+  /**
+   * Checks, whether a {@link File} satisfies one of the following filter modes:<br>
+   * 0 = Files and folders<br>
+   * 1 = Files only<br>
+   * 2 = Folders only
+   * 
+   * @param file a file or folder
+   * @param mode filter mode (see above)
+   * @return {@code false} if given file is {@code null}
+   */
+  public static boolean fileFitsFilterMode(File file, int mode) {
+    final boolean acceptFiles = mode == 0 || mode == 1;
+    final boolean acceptDirs  = mode == 0 || mode == 2;
+
+    return file != null
+        && (file.isDirectory() && acceptDirs || 
+            file.isFile() && acceptFiles);
+  }
+  
 }



More information about the Schmitzm-commits mailing list