View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.configuration2.reloading;
18  
19  import java.io.File;
20  import java.net.MalformedURLException;
21  import java.net.URL;
22  
23  import org.apache.commons.configuration2.io.FileHandler;
24  import org.apache.commons.configuration2.io.FileLocatorUtils;
25  
26  /**
27   * <p>
28   * A specialized implementation of {@code ReloadingDetector} which monitors a file specified by a {@link FileHandler}.
29   * </p>
30   * <p>
31   * An instance of this class is passed a {@code FileHandler} at construction time. Each time the
32   * {@code isReloadingRequired()} method is called, it checks whether the {@code FileHandler} points to a valid location.
33   * If this is the case, the file's last modification time is obtained and compared with the last stored time. If it has
34   * changed, a reload operation should be performed.
35   * </p>
36   * <p>
37   * Because file I/O may be expensive it is possible to configure a refresh delay as a time in milliseconds. This is the
38   * minimum interval between two checks. If the {@code isReloadingRequired()} method is called in shorter intervals, it
39   * does not perform a check, but directly returns <strong>false</strong>.
40   * </p>
41   * <p>
42   * To initialize an instance either {@code isReloadingRequired()} or {@code reloadingPerformed()} can be called. The
43   * first call of {@code isReloadingRequired} does not perform a check, but obtains the initial modification date of the
44   * monitored file. {@code reloadingPerformed()} always obtains the file's modification date and stores it internally.
45   * </p>
46   *
47   * @since 2.0
48   */
49  public class FileHandlerReloadingDetector implements ReloadingDetector {
50      /** Constant for the jar URL protocol. */
51      private static final String JAR_PROTOCOL = "jar";
52  
53      /** Constant for the default refresh delay. */
54      private static final int DEFAULT_REFRESH_DELAY_MILLIS = 5000;
55  
56      /**
57       * Helper method for transforming a URL into a file object. This method handles file: and jar: URLs.
58       *
59       * @param url the URL to be converted
60       * @return the resulting file or <strong>null </strong>
61       */
62      private static File fileFromURL(final URL url) {
63          if (JAR_PROTOCOL.equals(url.getProtocol())) {
64              final String path = url.getPath();
65              try {
66                  return FileLocatorUtils.fileFromURL(new URL(path.substring(0, path.indexOf('!'))));
67              } catch (final MalformedURLException mex) {
68                  return null;
69              }
70          }
71          return FileLocatorUtils.fileFromURL(url);
72      }
73  
74      /** The associated file handler. */
75      private final FileHandler fileHandler;
76  
77      /** The refresh delay. */
78      private final long refreshDelayMillis;
79  
80      /** The last time the configuration file was modified. */
81      private long lastModifiedMillis;
82  
83      /** The last time the file was checked for changes. */
84      private long lastCheckedMillis;
85  
86      /**
87       * Creates a new instance of {@code FileHandlerReloadingDetector} with an uninitialized {@code FileHandler} object. The
88       * file to be monitored has to be set later by manipulating the handler object returned by {@code getFileHandler()}.
89       */
90      public FileHandlerReloadingDetector() {
91          this(null);
92      }
93  
94      /**
95       * Creates a new instance of {@code FileHandlerReloadingDetector} and initializes it with the {@code FileHandler} to
96       * monitor and a default refresh delay.
97       *
98       * @param handler the {@code FileHandler} associated with this detector (can be <strong>null</strong>)
99       */
100     public FileHandlerReloadingDetector(final FileHandler handler) {
101         this(handler, DEFAULT_REFRESH_DELAY_MILLIS);
102     }
103 
104     /**
105      * Creates a new instance of {@code FileHandlerReloadingDetector} and initializes it with the {@code FileHandler} to
106      * monitor and the refresh delay. The handler is directly used, no copy is created. So it is possible to change the
107      * location monitored by manipulating the {@code FileHandler} object.
108      *
109      * @param handler the {@code FileHandler} associated with this detector (can be <strong>null</strong>)
110      * @param refreshDelayMillis the refresh delay; a value of 0 means that a check is performed in all cases
111      */
112     public FileHandlerReloadingDetector(final FileHandler handler, final long refreshDelayMillis) {
113         fileHandler = handler != null ? handler : new FileHandler();
114         this.refreshDelayMillis = refreshDelayMillis;
115     }
116 
117     /**
118      * Gets the monitored {@code File} or <strong>null</strong> if it does not exist.
119      *
120      * @return the monitored {@code File} or <strong>null</strong>
121      */
122     private File getExistingFile() {
123         File file = getFile();
124         if (file != null && !file.exists()) {
125             file = null;
126         }
127 
128         return file;
129     }
130 
131     /**
132      * Gets the {@code File} object which is monitored by this object. This method is called every time the file's last
133      * modification time is needed. If it returns <strong>null</strong>, no check is performed. This base implementation obtains the
134      * {@code File} from the associated {@code FileHandler}. It can also deal with URLs to jar files.
135      *
136      * @return the {@code File} to be monitored (can be <strong>null</strong>)
137      */
138     protected File getFile() {
139         final URL url = getFileHandler().getURL();
140         return url != null ? fileFromURL(url) : getFileHandler().getFile();
141     }
142 
143     /**
144      * Gets the {@code FileHandler} associated with this object. The underlying handler is directly returned, so changing
145      * its location also changes the file monitored by this detector.
146      *
147      * @return the associated {@code FileHandler}
148      */
149     public FileHandler getFileHandler() {
150         return fileHandler;
151     }
152 
153     /**
154      * Gets the date of the last modification of the monitored file. A return value of 0 indicates, that the monitored
155      * file does not exist.
156      *
157      * @return the last modification date in milliseconds.
158      */
159     protected long getLastModificationDate() {
160         final File file = getExistingFile();
161         return file != null ? file.lastModified() : 0;
162     }
163 
164     /**
165      * Gets the refresh delay. This is a time in milliseconds. The {@code isReloadingRequired()} method first checks
166      * whether the time since the previous check is more than this value in the past. Otherwise, no check is performed. This
167      * is a means to limit file I/O caused by this class.
168      *
169      * @return the refresh delay used by this object
170      */
171     public long getRefreshDelay() {
172         return refreshDelayMillis;
173     }
174 
175     /**
176      * {@inheritDoc} This implementation checks whether the associated {@link FileHandler} points to a valid file and
177      * whether the last modification time of this time has changed since the last check. The refresh delay is taken into
178      * account, too; a check is only performed if at least this time has passed since the last check.
179      */
180     @Override
181     public boolean isReloadingRequired() {
182         final long nowMillis = System.currentTimeMillis();
183         if (nowMillis >= lastCheckedMillis + getRefreshDelay()) {
184             lastCheckedMillis = nowMillis;
185 
186             final long modifiedMillis = getLastModificationDate();
187             if (modifiedMillis > 0) {
188                 if (lastModifiedMillis != 0) {
189                     return modifiedMillis != lastModifiedMillis;
190                 }
191                 // initialization
192                 updateLastModified(modifiedMillis);
193             }
194         }
195 
196         return false;
197     }
198 
199     /**
200      * Tells this implementation that the internally stored state should be refreshed. This method is intended to be called
201      * after the creation of an instance.
202      */
203     public void refresh() {
204         updateLastModified(getLastModificationDate());
205     }
206 
207     /**
208      * {@inheritDoc} This implementation updates the internally stored last modification date with the current modification
209      * date of the monitored file. So the next change is detected when this file is changed again.
210      */
211     @Override
212     public void reloadingPerformed() {
213         updateLastModified(getLastModificationDate());
214     }
215 
216     /**
217      * Updates the last modification date of the monitored file. The need for a reload is detected only if the file's
218      * modification date is different from this value.
219      *
220      * @param timeMillis the new last modification date
221      */
222     protected void updateLastModified(final long timeMillis) {
223         lastModifiedMillis = timeMillis;
224     }
225 }