Skip to content

Commit b95e9c6

Browse files
committed
added ability to detect source changes outside app life cycle
1 parent 9ade77e commit b95e9c6

13 files changed

Lines changed: 213 additions & 61 deletions

File tree

‎koans-lib/src/com/sandwich/koan/constant/KoanConstants.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ private KoanConstants(){}
2323
public static String SOURCE_FOLDER = "src";
2424
public static String BIN_FOLDER = "bin";
2525
public static String DATA_FOLDER = "data";
26+
public static String FILE_HASH_FILE_NAME = "file_hashes.dat";
2627
public static String TESTS_FOLDER = "test";
2728
public static String LIB_FOLDER = "lib";
2829

‎koans-lib/src/com/sandwich/koan/path/PathToEnlightenment.java‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,12 @@ private static XmlToPathTransformer getXmlToPathTransformer(){
4343

4444
public static void filterBySuite(String suite){
4545
suiteName = suite;
46+
xmlToPathTransformer = null;
4647
}
4748

4849
public static void filterByKoan(String koan){
4950
koanMethod = koan;
51+
xmlToPathTransformer = null;
5052
}
5153

5254
public static Path getPathToEnlightment(){
@@ -65,8 +67,16 @@ public FileFormatException(String message){
6567

6668
public static class Path implements Iterable<Entry<String, Map<String, Map<String, KoanElementAttributes>>>>{
6769
private Map<String, Map<String, Map<String, KoanElementAttributes>>> koanMethodsBySuiteByPackage;
70+
private String methodName;
6871
public Path(){}
72+
public Path(String methodName, Map<String, Map<String, Map<String, KoanElementAttributes>>> koans) {
73+
stubKoanMethodsBySuiteByClass(koans);
74+
this.methodName = methodName;
75+
}
6976
public int getTotalNumberOfKoans() {
77+
if(methodName != null){
78+
return 1;
79+
}
7080
Counter total = new Counter();
7181
Iterator<Entry<String, Map<String, Map<String, KoanElementAttributes>>>> koanMethodsBySuiteByPackageIter =
7282
getKoanMethodsBySuiteByPackage();
@@ -95,7 +105,7 @@ public Iterator<Entry<String, Map<String, Map<String, KoanElementAttributes>>>>
95105
return getKoanMethodsBySuiteByPackage();
96106
}
97107

98-
public Path stubKoanMethodsBySuiteByClass(Map<String, Map<String, Map<String, KoanElementAttributes>>> koanMethodsBySuiteByPackage){
108+
protected Path stubKoanMethodsBySuiteByClass(Map<String, Map<String, Map<String, KoanElementAttributes>>> koanMethodsBySuiteByPackage){
99109
// unlike other collections in this app, this actually needs to remain mutable after the reference is
100110
// stored and utilized internally. this is so the DynamicClassLoader can swap out references to
101111
// any dynamic classes
@@ -155,5 +165,8 @@ protected Iterator<Entry<String, Map<String, Map<String, KoanElementAttributes>>
155165
@Override public String toString(){
156166
return getKoanMethodsBySuiteByPackage().toString();
157167
}
168+
public String getOnlyMethodNameToRun() {
169+
return methodName;
170+
}
158171
}
159172
}

‎koans-lib/src/com/sandwich/koan/path/xmltransformation/XmlToPathTransformerImpl.java‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public Path transform(){
6060
String pkg = node.getAttributes().getNamedItem("pkg").getNodeValue();
6161
koans.put(packageTitle, getKoanElementAttributesByMethodNameBySuite(pkg, node.getChildNodes()));
6262
}
63-
return new Path().stubKoanMethodsBySuiteByClass(koans);
63+
return new Path(methodName, koans);
6464
}catch(Exception x){
6565
throw new RuntimeException(x);
6666
}
@@ -104,9 +104,8 @@ Map<String, KoanElementAttributes> extractKoansAndRawLessons(
104104
if (rawKoanAttributesByMethodName.containsKey(name)) {
105105
throw new DuplicateKoanException(className, name);
106106
}
107-
rawKoanAttributesByMethodName.put(name,
108-
new KoanElementAttributes(rawLesson, name,
109-
displayIncompleteKoanException, className));
107+
rawKoanAttributesByMethodName.put(name, new KoanElementAttributes(
108+
rawLesson, name, displayIncompleteKoanException, className));
110109
}
111110
}
112111
return rawKoanAttributesByMethodName;

‎koans-lib/src/com/sandwich/koan/runner/RunKoans.java‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,14 @@ KoanSuiteResult runKoans() {
4848
String level = null;
4949
KoanMethodResult failure = null;
5050
DynamicClassLoader loader = new DynamicClassLoader();
51-
for (Entry<String, Map<String, Map<String, KoanElementAttributes>>> packages : getPathToEnlightement()) {
51+
Path pathToEnlightement = getPathToEnlightement();
52+
for (Entry<String, Map<String, Map<String, KoanElementAttributes>>> packages : pathToEnlightement) {
5253
for (Entry<String, Map<String, KoanElementAttributes>> e : packages.getValue().entrySet()) {
5354
String name = e.getKey().substring(e.getKey().lastIndexOf('.')+1);
5455
if(failure == null){
5556
Object suite = constructSuite(loader, e.getKey());
5657
final List<KoanElementAttributes> attributes = new ArrayList<KoanElementAttributes>(e.getValue().values());
57-
final List<KoanMethod> methods = mergeJavaFilesMethodsAndThoseInXml(suite, attributes);
58+
final List<KoanMethod> methods = mergeJavaFilesMethodsAndThoseInXml(suite, attributes, pathToEnlightement.getOnlyMethodNameToRun());
5859
Collections.sort(methods, new KoanComparator());
5960
for (final KoanMethod koan : methods) {
6061
KoanMethodResult result = KoanMethodRunner.run(suite, koan);
@@ -69,38 +70,45 @@ KoanSuiteResult runKoans() {
6970
}
7071
if (failure == null) {
7172
passingSuites.add(name);
72-
} else {
73-
level = packages.getKey();
7473
}
74+
level = packages.getKey();
7575
}else{
7676
failingSuites.add(name);
7777
}
7878
}
7979
}
8080
return new KoanResultBuilder() .level(level)
8181
.numberPassing((int)successfull.getCount())
82-
.totalNumberOfKoanMethods(getPathToEnlightement().getTotalNumberOfKoans())
82+
.totalNumberOfKoanMethods(pathToEnlightement.getTotalNumberOfKoans())
8383
.methodResult(failure)
8484
.passingCases(passingSuites).remainingCases(failingSuites).build();
8585
}
8686

8787
private List<KoanMethod> mergeJavaFilesMethodsAndThoseInXml(Object suite,
88-
final List<KoanElementAttributes> attributes) {
88+
final List<KoanElementAttributes> attributes, String onlyMethodNameToRun) {
8989
final List<KoanMethod> methods = new ArrayList<KoanMethod>();
9090
final List<String> methodNames = new ArrayList<String>();
9191
for(KoanElementAttributes attributeSet : attributes){
92-
KoanMethod method = KoanMethod.getInstance(attributeSet);
93-
methods.add(method);
94-
methodNames.add(method.getMethod().getName());
92+
if(isMethodEligibleForRunning(onlyMethodNameToRun, attributeSet.name)){
93+
KoanMethod method = KoanMethod.getInstance(attributeSet);
94+
methods.add(method);
95+
methodNames.add(method.getMethod().getName());
96+
}
9597
}
9698
for(Method method : suite.getClass().getMethods()){
97-
if(!methodNames.contains(method.getName()) && method.getAnnotation(Koan.class) != null){
99+
if(!methodNames.contains(method.getName()) &&
100+
isMethodEligibleForRunning(onlyMethodNameToRun, method.getName()) &&
101+
method.getAnnotation(Koan.class) != null){
98102
methods.add(KoanMethod.getInstance(method));
99103
}
100104
}
101105
return methods;
102106
}
103107

108+
private boolean isMethodEligibleForRunning(String onlyMethodNameToRun, String name) {
109+
return onlyMethodNameToRun == null || onlyMethodNameToRun.equals(name);
110+
}
111+
104112
private Object constructSuite(DynamicClassLoader loader, String className) {
105113
Object suite;
106114
try {
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(String absolutePath, T defaultState){
22+
dataFile = new File(absolutePath);
23+
if(!dataFile.exists()){
24+
save(defaultState);
25+
}
26+
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
27+
public void run() {
28+
if(lastRetrieval != null){
29+
save(lastRetrieval);
30+
}
31+
}
32+
}));
33+
34+
}
35+
36+
@SuppressWarnings("unchecked")
37+
public T retrieve(){
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+
}

‎koans-lib/src/com/sandwich/util/io/DynamicClassLoader.java‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ public class DynamicClassLoader extends ClassLoader {
1616

1717
private static Map<URL, Class<?>> classesByLocation = new HashMap<URL, Class<?>>();
1818
private static Map<Class<?>, URL> locationByClass = new HashMap<Class<?>, URL>();
19+
private final FileMonitor fileMonitor = FileMonitorFactory.getInstance(
20+
FileUtils.makeAbsoluteRelativeTo(KoanConstants.PROJ_MAIN_FOLDER));
1921

2022
public DynamicClassLoader(){
2123
this(ClassLoader.getSystemClassLoader());
@@ -53,19 +55,22 @@ public Class<?> loadClass(String className){
5355
+ FileCompiler.CLASS_SUFFIX;
5456
File classFile = new File(fileName);
5557
try {
58+
// file may have never been compiled, go ahead and compile it now
59+
File sourceFile = FileUtils.classToSource(classFile);
5660
if(classFile.exists()){
61+
String absolutePath = classFile.getAbsolutePath();
62+
boolean isAnonymous = absolutePath.contains("$");
63+
if(fileMonitor.isFileModifiedSinceLastPoll(sourceFile.getAbsolutePath(), sourceFile.lastModified())){
64+
if(!isAnonymous){
65+
compile(className, fileName, sourceFile);
66+
}
67+
}
5768
return loadClass(classFile.toURI().toURL(), className);
5869
}
5970
try{
6071
return super.loadClass(className);
6172
}catch(ClassNotFoundException x){
62-
// file may have never been compiled, go ahead and compile it now
63-
FileCompiler.compile(
64-
FileUtils.classToSource(classFile),
65-
new File(fileName.substring(0, fileName.length() - (className + FileCompiler.CLASS_SUFFIX).length())),
66-
FileUtils.makeAbsoluteRelativeTo(KoanConstants.PROJ_MAIN_FOLDER +
67-
KoanConstants.FILESYSTEM_SEPARATOR + KoanConstants.LIB_FOLDER +
68-
KoanConstants.FILESYSTEM_SEPARATOR + "koans.jar"));
73+
compile(className, fileName, sourceFile);
6974
classFile = new File(fileName);
7075
return loadClass(classFile.toURI().toURL(), className);
7176
}
@@ -74,6 +79,16 @@ public Class<?> loadClass(String className){
7479
}
7580
}
7681

82+
private void compile(String className, String fileName, File sourceFile)
83+
throws IOException {
84+
FileCompiler.compile(sourceFile,
85+
new File(fileName.substring(0, fileName.length() - (className + FileCompiler.CLASS_SUFFIX).length())),
86+
FileUtils.makeAbsoluteRelativeTo(KoanConstants.PROJ_MAIN_FOLDER +
87+
KoanConstants.FILESYSTEM_SEPARATOR + KoanConstants.LIB_FOLDER +
88+
KoanConstants.FILESYSTEM_SEPARATOR + "koans.jar"));
89+
fileMonitor.updateFileSaveTime(sourceFile);
90+
}
91+
7792
public Class<?> loadClass(URL url, String className){
7893
Class<?> clazz = classesByLocation.get(url);
7994
if(clazz != null){

‎koans-lib/src/com/sandwich/util/io/FileCompiler.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ public void sourceToDestination(File src, File bin) throws IOException {
3838
}
3939
String command = "javac -d "+destinationDirectory.getAbsolutePath()+" "+
4040
getClasspath(classpath)+src.getAbsolutePath();
41+
if(KoanConstants.DEBUG){
42+
System.out.println("executing command: \""+command+"\" to compile the sourcefile: "+src+".");
43+
}
4144
Process p = Runtime.getRuntime().exec(command);
4245
try{
4346
if(KoanConstants.DEBUG){

‎koans-lib/src/com/sandwich/util/io/FileMonitor.java‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package com.sandwich.util.io;
22

3+
import static com.sandwich.koan.constant.KoanConstants.DATA_FOLDER;
4+
import static com.sandwich.koan.constant.KoanConstants.FILESYSTEM_SEPARATOR;
5+
import static com.sandwich.koan.constant.KoanConstants.FILE_HASH_FILE_NAME;
6+
import static com.sandwich.koan.constant.KoanConstants.PROJ_MAIN_FOLDER;
7+
38
import java.io.File;
49
import java.io.IOException;
510
import java.util.HashMap;
@@ -10,7 +15,11 @@
1015
public class FileMonitor {
1116

1217
private final List<FileListener> listeners = new Vector<FileListener>();
13-
private static Map<String, Long> fileHashesByDirectory = new HashMap<String, Long>();
18+
private static DataFileHelper<Map<String, Long>> fileHashesHelper = new DataFileHelper<Map<String,Long>>(
19+
getFileHashesDataFilePath(), new HashMap<String,Long>());
20+
21+
private static Map<String, Long> fileHashesByDirectory = fileHashesHelper.retrieve();
22+
1423
final File fileSystemPath;
1524

1625
public FileMonitor(String fileSystemPath){
@@ -39,13 +48,10 @@ public void removeFileSavedListener(FileListener listener){
3948
synchronized void notifyListeners(){
4049
try {
4150
Map<String, Long> currentHashes = getFilesystemHashes();
42-
if(fileHashesByDirectory.isEmpty()){
43-
fileHashesByDirectory.putAll(currentHashes);
44-
}
4551
for(String fileName : currentHashes.keySet()){
4652
Long currentHash = currentHashes.get(fileName);
4753
Long previousHash = fileHashesByDirectory.get(fileName);
48-
if(!currentHash.equals(previousHash)){
54+
if(previousHash != null && !currentHash.equals(previousHash)){
4955
fileHashesByDirectory.put(fileName, currentHash);
5056
File file = new File(fileName);
5157
for(FileListener listener : listeners){
@@ -72,4 +78,19 @@ public void sourceToDestination(File src, File dest) throws IOException {
7278
return fileHashes;
7379
}
7480

81+
private static String getFileHashesDataFilePath(){
82+
return FileUtils.makeAbsoluteRelativeTo(
83+
new StringBuilder(PROJ_MAIN_FOLDER).append(FILESYSTEM_SEPARATOR).append(DATA_FOLDER)
84+
.append(FILESYSTEM_SEPARATOR).append(FILE_HASH_FILE_NAME).toString());
85+
}
86+
87+
public boolean isFileModifiedSinceLastPoll(String filePath, Long lastModified) {
88+
Long previousHash = fileHashesByDirectory.get(filePath);
89+
return !lastModified.equals(previousHash);
90+
}
91+
92+
public void updateFileSaveTime(File file) {
93+
fileHashesByDirectory.put(file.getAbsolutePath(), file.lastModified());
94+
}
95+
7596
}

‎koans-lib/src/com/sandwich/util/io/FileMonitorFactory.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public void run() {
5757
}).start();
5858
}
5959

60-
public static FileMonitor getInstance(String fileSystemPath) throws IOException{
60+
public static FileMonitor getInstance(String fileSystemPath) {
6161
FileMonitor monitor = monitors.get(fileSystemPath);
6262
if(monitor == null){
6363
monitor = new FileMonitor(fileSystemPath);

‎koans-tests/test/com/sandwich/koan/path/CommandLineTestCase.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ protected Path stubAllKoans(String packageName, List<String> path){
6969
Map<String, Map<String, Map<String, KoanElementAttributes>>> stubbedPath =
7070
new LinkedHashMap<String, Map<String, Map<String, KoanElementAttributes>>>();
7171
stubbedPath.put(packageName, tempSuitesAndMethods);
72-
PathToEnlightenment.theWay = new Path().stubKoanMethodsBySuiteByClass(stubbedPath);
72+
PathToEnlightenment.theWay = new Path(null,stubbedPath);
7373
return oldKoans;
7474
}
7575

0 commit comments

Comments
 (0)