View Javadoc

1   /*
2    * $Id: AbstractFileWatcher.java 21431 2011-03-03 16:55:13Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.launcher;
12  
13  import java.io.File;
14  import java.util.Arrays;
15  import java.util.Collection;
16  
17  import org.apache.commons.logging.Log;
18  import org.apache.commons.logging.LogFactory;
19  
20  public abstract class AbstractFileWatcher implements Runnable
21  {
22  
23      protected Log logger = LogFactory.getLog(getClass());
24  
25      private long timeStamp;
26      private Collection<File> files;
27  
28      public AbstractFileWatcher(File file)
29      {
30          this(Arrays.asList(file));
31      }
32  
33      public AbstractFileWatcher(Collection<File> files)
34      {
35          this.files = files;
36          this.timeStamp = System.currentTimeMillis();
37      }
38      
39      public final void run()
40      {
41          long lastTimeStamp = timeStamp;
42          File latestFile = null;
43          
44          for (File file : files)
45          {
46              long timestamp = file.lastModified();
47              if (timestamp > lastTimeStamp)
48              {
49                  lastTimeStamp = timeStamp;
50                  latestFile = file;
51              }
52          }
53          
54          if (latestFile != null)
55          {
56              this.timeStamp = lastTimeStamp;
57              try
58              {
59                  onChange(latestFile);
60              }
61              catch (Throwable t)
62              {
63                  logger.error(String.format("Monitor for %s threw an exception", latestFile), t);
64              }
65          }
66      }
67  
68      protected abstract void onChange(File file);
69  }