Skip to content

Commit e51240a

Browse files
matmat
authored andcommitted
moving file monitoring to separate project
1 parent cc1fe60 commit e51240a

8 files changed

Lines changed: 302 additions & 0 deletions

File tree

‎file-monitor/.classpath‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" path="src"/>
4+
<classpathentry kind="src" path="test"/>
5+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
6+
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
7+
<classpathentry kind="output" path="bin"/>
8+
</classpath>

‎file-monitor/.project‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<projectDescription>
3+
<name>file-monitor</name>
4+
<comment></comment>
5+
<projects>
6+
</projects>
7+
<buildSpec>
8+
<buildCommand>
9+
<name>org.eclipse.jdt.core.javabuilder</name>
10+
<arguments>
11+
</arguments>
12+
</buildCommand>
13+
</buildSpec>
14+
<natures>
15+
<nature>org.eclipse.jdt.core.javanature</nature>
16+
</natures>
17+
</projectDescription>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
eclipse.preferences.version=1
2+
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3+
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
4+
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5+
org.eclipse.jdt.core.compiler.compliance=1.6
6+
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7+
org.eclipse.jdt.core.compiler.debug.localVariable=generate
8+
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9+
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10+
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11+
org.eclipse.jdt.core.compiler.source=1.6
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
import java.io.FileInputStream;
5+
import java.io.FileOutputStream;
6+
import java.io.ObjectInputStream;
7+
import java.io.ObjectOutputStream;
8+
9+
/**
10+
* Handles persistence to/from a filesystem, and makes assumption instances of T
11+
* are mutated after retrieval. Their mutations are saved to file on app
12+
* shutdown automatically.
13+
*
14+
* @param <T>
15+
*/
16+
public class DataFileHelper<T> {
17+
18+
private File dataFile;
19+
private T lastRetrieval;
20+
21+
public DataFileHelper(File dataFile, T defaultState){
22+
this.dataFile = dataFile;
23+
if(!dataFile.exists()){
24+
dataFile.getParentFile().mkdirs();
25+
save(defaultState);
26+
}
27+
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
28+
public void run() {
29+
if(lastRetrieval != null){
30+
save(lastRetrieval);
31+
}
32+
}
33+
}));
34+
}
35+
36+
@SuppressWarnings("unchecked")
37+
public T readLastModifiedTimes(){
38+
ObjectInputStream objectInputStream = null;
39+
try {
40+
objectInputStream = new ObjectInputStream(new FileInputStream(getDataFile()));
41+
return lastRetrieval = (T)objectInputStream.readObject();
42+
} catch (Exception e) {
43+
try{
44+
if(objectInputStream != null){
45+
objectInputStream.close();
46+
}
47+
}catch(Exception e2){
48+
throw new RuntimeException(e2);
49+
}
50+
throw new RuntimeException(e);
51+
}
52+
}
53+
54+
public void save(T state){
55+
ObjectOutputStream objectOutputStream = null;
56+
try {
57+
objectOutputStream = new ObjectOutputStream(new FileOutputStream(getDataFile()));
58+
objectOutputStream.writeObject(state);
59+
} catch (Exception e) {
60+
try{
61+
if(objectOutputStream != null){
62+
objectOutputStream.close();
63+
}
64+
}catch(Exception e2){
65+
throw new RuntimeException(e2);
66+
}
67+
throw new RuntimeException(e);
68+
}
69+
}
70+
71+
private File getDataFile() {
72+
return dataFile;
73+
}
74+
75+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
6+
public interface FileAction {
7+
8+
void sourceToDestination(File src, File dest) throws IOException;
9+
10+
File makeDestination(File dest, String fileInDirectory);
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
5+
public interface FileListener {
6+
7+
void fileSaved(File file);
8+
void newFile(File file);
9+
void fileDeleted(File file);
10+
11+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.Vector;
9+
10+
public class FileMonitor {
11+
12+
private final List<FileListener> listeners = new Vector<FileListener>();
13+
private final DataFileHelper<Map<String, Long>> fileHashesHelper;
14+
15+
private final Map<String, Long> fileHashesByDirectory;
16+
17+
final File fileSystemPath;
18+
19+
public FileMonitor(File fileSystemPath, File dataFile) {
20+
this.fileSystemPath = fileSystemPath;
21+
if(!this.fileSystemPath.exists()){
22+
throw new IllegalArgumentException(fileSystemPath+ " cannot be found.");
23+
}
24+
fileHashesHelper = new DataFileHelper<Map<String,Long>>(
25+
dataFile, new HashMap<String,Long>());
26+
fileHashesByDirectory = fileHashesHelper.readLastModifiedTimes();
27+
}
28+
29+
public String getFilesystemPath() {
30+
return fileSystemPath.getAbsolutePath();
31+
}
32+
33+
public void close(){
34+
listeners.clear();
35+
}
36+
37+
public void addFileSavedListener(FileListener listener){
38+
listeners.add(listener);
39+
}
40+
41+
public void removeFileSavedListener(FileListener listener){
42+
listeners.remove(listener);
43+
}
44+
45+
synchronized void notifyListeners(){
46+
try {
47+
Map<String, Long> currentHashes = getFilesystemHashes();
48+
for(String fileName : currentHashes.keySet()){
49+
Long currentHash = currentHashes.get(fileName);
50+
Long previousHash = fileHashesByDirectory.get(fileName);
51+
if(previousHash != null && !currentHash.equals(previousHash)){
52+
fileHashesByDirectory.put(fileName, currentHash);
53+
File file = new File(fileName);
54+
for(FileListener listener : listeners){
55+
listener.fileSaved(file);
56+
}
57+
break;
58+
}
59+
}
60+
} catch (IOException e) {
61+
throw new RuntimeException(e);
62+
}
63+
}
64+
65+
Map<String, Long> getFilesystemHashes() throws IOException {
66+
final HashMap<String,Long> fileHashes = new HashMap<String,Long>();
67+
forEachFile(fileSystemPath, fileSystemPath, new FileAction(){
68+
public File makeDestination(File dest, String fileInDirectory) {
69+
return new File(dest, fileInDirectory);
70+
}
71+
public void sourceToDestination(File src, File dest) throws IOException {
72+
fileHashes.put(src.getAbsolutePath(), src.lastModified());
73+
}
74+
});
75+
return fileHashes;
76+
}
77+
78+
public boolean isFileModifiedSinceLastPoll(String filePath, Long lastModified) {
79+
Long previousHash = fileHashesByDirectory.get(filePath);
80+
return !lastModified.equals(previousHash);
81+
}
82+
83+
public void updateFileSaveTime(File file) {
84+
fileHashesByDirectory.put(file.getAbsolutePath(), file.lastModified());
85+
}
86+
87+
public static void forEachFile(File src, File dest, FileAction fileAction) throws IOException {
88+
if((src == null || !src.exists()) && dest == null){
89+
throw new IllegalArgumentException("Both path's must actually exist");
90+
}
91+
if (src.isDirectory()) {
92+
if (!dest.exists()) {
93+
dest.mkdir();
94+
}
95+
String files[] = src.list();
96+
for (int i = 0; i < files.length; i++) {
97+
forEachFile(new File(src, files[i]), fileAction.makeDestination(dest, files[i]), fileAction);
98+
}
99+
} else {
100+
if (!src.exists()) {
101+
throw new IOException("File or directory does not exist: "+src);
102+
} else {
103+
fileAction.sourceToDestination(src, dest);
104+
}
105+
}
106+
}
107+
108+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
import java.util.LinkedHashMap;
5+
import java.util.Map;
6+
import java.util.Map.Entry;
7+
8+
public class FileMonitorFactory {
9+
10+
private static Map<String, FileMonitor> monitors = new LinkedHashMap<String, FileMonitor>();
11+
public static final int SLEEP_TIME_IN_MS = 500;
12+
13+
static {
14+
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
15+
@Override
16+
public void run() {
17+
for(FileMonitor monitor : monitors.values()){
18+
monitor.close();
19+
}
20+
monitors.clear();
21+
}
22+
}));
23+
new Thread(new Runnable(){
24+
public void run() {
25+
do{
26+
try {
27+
Thread.sleep(SLEEP_TIME_IN_MS);
28+
} catch (InterruptedException e) {
29+
throw new RuntimeException(e);
30+
}
31+
for(Entry<String, FileMonitor> filePathAndMonitor : monitors.entrySet()){
32+
FileMonitor monitor = filePathAndMonitor.getValue();
33+
if(monitor != null){
34+
monitor.notifyListeners();
35+
}
36+
}
37+
}while(true);
38+
}
39+
}).start();
40+
}
41+
42+
public static FileMonitor getInstance(File monitoredFile, File dataFile) {
43+
String key = monitoredFile.getAbsolutePath() + dataFile.getAbsolutePath();
44+
FileMonitor monitor = monitors.get(key);
45+
if(monitor == null){
46+
monitor = new FileMonitor(monitoredFile, dataFile);
47+
monitors.put(key, monitor);
48+
}
49+
return monitor;
50+
}
51+
52+
public static void removeInstance(FileMonitor monitor){
53+
monitor.close();
54+
monitors.remove(monitor.getFilesystemPath());
55+
}
56+
57+
public static void removeInstance(String absolutePath) {
58+
monitors.remove(absolutePath);
59+
}
60+
61+
}

0 commit comments

Comments
 (0)