01: /*
02: * Copyright 2006 Luca Garulli (luca.garulli@assetdata.it)
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.romaframework.core.resource;
18:
19: import java.io.File;
20: import java.util.HashMap;
21: import java.util.Iterator;
22: import java.util.Map;
23:
24: import org.apache.commons.logging.Log;
25: import org.apache.commons.logging.LogFactory;
26:
27: /**
28: * Check for file chamges and propagates update to all registered listeners for that file.
29: *
30: * @author Luca Garulli (luca.garulli@assetdata.it)
31: */
32: public class AutoReloadManager {
33:
34: private Map<String, ResourceInfo> resources;
35: @SuppressWarnings("unused")
36: private PollerThread poller;
37: private static Log log = LogFactory.getLog(AutoReloadManager.class);
38:
39: /**
40: * Construct the object using a delay time.
41: *
42: * @param iMilliseconds
43: * Millisecond to wait between polls
44: */
45: public AutoReloadManager(int iMilliseconds) {
46: resources = new HashMap<String, ResourceInfo>();
47: poller = new PollerThread(this , iMilliseconds);
48: }
49:
50: /**
51: * Add a resource to be monitoring
52: *
53: * @param iFile
54: * @param iListener
55: */
56: public synchronized void addResource(File iFile,
57: AutoReloadListener iListener) {
58: String absolutePath = iFile.getAbsolutePath();
59: ResourceInfo resource = resources.get(absolutePath);
60: if (resource == null) {
61: resource = new ResourceInfo(iFile);
62: resources.put(absolutePath, resource);
63: }
64:
65: // REGISTER THE LISTENER
66: resource.listeners.add(iListener);
67: }
68:
69: protected synchronized void checkResources() {
70: ResourceInfo currentResource;
71: long lastModified;
72:
73: for (Iterator<ResourceInfo> it = resources.values().iterator(); it
74: .hasNext();) {
75: currentResource = it.next();
76: lastModified = currentResource.file.lastModified();
77:
78: if (lastModified > currentResource.lastModified) {
79: // SIGNAL ALL REGISTERED LISTENERS
80: for (AutoReloadListener listener : currentResource.listeners) {
81: try {
82: listener
83: .signalUpdatedFile(currentResource.file);
84: currentResource.lastModified = lastModified;
85: } catch (Exception e) {
86: log.error(
87: "[AutoReloadManager.checkResources] Error on reloading resource: "
88: + currentResource.file, e);
89: }
90: }
91: }
92: }
93: }
94: }
|