1 package net.sourceforge.pmd.cpd;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Iterator;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.TreeMap;
9
10 public class MatchAlgorithm {
11
12 private Map pool = new TreeMap();
13 private List code = new ArrayList();
14 private List marks = new ArrayList();
15 private List matches;
16 private Map source;
17 private Tokens tokens;
18 private CPDListener cpdListener;
19
20 public MatchAlgorithm(Map sourceCode, Tokens tokens) {
21 this.source = sourceCode;
22 this.tokens = tokens;
23 for (Iterator i = tokens.iterator(); i.hasNext();) {
24 add((TokenEntry)i.next());
25 }
26 }
27
28 public void setListener(CPDListener listener) {
29 this.cpdListener = listener;
30 }
31
32 public void add(TokenEntry token) {
33 if (!pool.containsKey(token)) {
34 pool.put(token, token);
35 }
36 code.add(pool.get(token));
37 if (!(token.equals(TokenEntry.EOF))) {
38 marks.add(new Mark(code.size(), token.getTokenSrcID(), token.getIndex(), token.getBeginLine()));
39 }
40 }
41
42 public void findMatches(int min) {
43 /*
44 Assign sort codes to all the pooled code. This should speed
45 up sorting them.
46 */
47 int count = 1;
48 for (Iterator iter = pool.keySet().iterator(); iter.hasNext();) {
49 TokenEntry token = (TokenEntry)iter.next();
50 token.setSortCode(count++);
51 }
52
53 MarkComparator mc = new MarkComparator(cpdListener, code);
54 Collections.sort(marks, mc);
55
56 MatchCollector coll = new MatchCollector(marks, mc);
57 matches = coll.collect(min);
58 Collections.sort(matches);
59
60 for (Iterator i = matches(); i.hasNext();) {
61 Match match = (Match)i.next();
62 for (Iterator occurrences = match.iterator(); occurrences.hasNext();) {
63 Mark mark = (Mark)occurrences.next();
64 match.setLineCount(tokens.getLineCount(mark, match));
65 if (!occurrences.hasNext()) {
66 int start = mark.getBeginLine();
67 int end = start + match.getLineCount() - 1;
68 SourceCode sourceCode = (SourceCode)source.get(mark.getTokenSrcID());
69 match.setSourceCodeSlice(sourceCode.getSlice(start, end));
70 }
71 }
72 }
73 }
74
75 public Iterator matches() {
76 return matches.iterator();
77 }
78 }
79
This page was automatically generated by Maven