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