1package junit.runner;
2
3import java.util.*;
4import java.io.*;
5
6/**
7 * An implementation of a TestCollector that consults the
8 * class path. It considers all classes on the class path
9 * excluding classes in JARs. It leaves it up to subclasses
10 * to decide whether a class is a runnable Test.
11 *
12 * @see TestCollector
13 * {@hide} - Not needed for 1.0 SDK
14 */
15public abstract class ClassPathTestCollector implements TestCollector {
16
17    static final int SUFFIX_LENGTH= ".class".length();
18
19    public ClassPathTestCollector() {
20    }
21
22    public Enumeration collectTests() {
23        String classPath= System.getProperty("java.class.path");
24        Hashtable result = collectFilesInPath(classPath);
25        return result.elements();
26    }
27
28    public Hashtable collectFilesInPath(String classPath) {
29        Hashtable result= collectFilesInRoots(splitClassPath(classPath));
30        return result;
31    }
32
33    Hashtable collectFilesInRoots(Vector roots) {
34        Hashtable result= new Hashtable(100);
35        Enumeration e= roots.elements();
36        while (e.hasMoreElements())
37            gatherFiles(new File((String)e.nextElement()), "", result);
38        return result;
39    }
40
41    void gatherFiles(File classRoot, String classFileName, Hashtable result) {
42        File thisRoot= new File(classRoot, classFileName);
43        if (thisRoot.isFile()) {
44            if (isTestClass(classFileName)) {
45                String className= classNameFromFile(classFileName);
46                result.put(className, className);
47            }
48            return;
49        }
50        String[] contents= thisRoot.list();
51        if (contents != null) {
52            for (int i= 0; i < contents.length; i++)
53                gatherFiles(classRoot, classFileName+File.separatorChar+contents[i], result);
54        }
55    }
56
57    Vector splitClassPath(String classPath) {
58        Vector result= new Vector();
59        String separator= System.getProperty("path.separator");
60        StringTokenizer tokenizer= new StringTokenizer(classPath, separator);
61        while (tokenizer.hasMoreTokens())
62            result.addElement(tokenizer.nextToken());
63        return result;
64    }
65
66    protected boolean isTestClass(String classFileName) {
67        return
68                classFileName.endsWith(".class") &&
69                classFileName.indexOf('$') < 0 &&
70                classFileName.indexOf("Test") > 0;
71    }
72
73    protected String classNameFromFile(String classFileName) {
74        // convert /a/b.class to a.b
75        String s= classFileName.substring(0, classFileName.length()-SUFFIX_LENGTH);
76        String s2= s.replace(File.separatorChar, '.');
77        if (s2.startsWith("."))
78            return s2.substring(1);
79        return s2;
80    }
81}
82