View Javadoc

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 net.sourceforge.pmd.PMD;
7   
8   import java.io.FileReader;
9   import java.io.IOException;
10  import java.io.LineNumberReader;
11  import java.io.Reader;
12  import java.lang.ref.SoftReference;
13  import java.util.ArrayList;
14  import java.util.List;
15  
16  public class SourceCode {
17  
18      private String fileName;
19      private SoftReference code;
20  
21      public SourceCode(String fileName) {
22          this.fileName = fileName;
23      }
24  
25      public List getCode() {
26          List c = null;
27          if (code != null) {
28              c = (List) code.get();
29          }
30          if (c != null) {
31              return c;
32          }
33          try {
34              readSource(new FileReader(this.fileName));
35          } catch (IOException e) {
36              throw new RuntimeException("Couldn't read " + fileName);
37          }
38          return (List) code.get();
39      }
40  
41      public void setCode(List l) {
42          this.code = new SoftReference(l);
43      }
44  
45      public StringBuffer getCodeBuffer() {
46          StringBuffer sb = new StringBuffer();
47          List lines = getCode();
48          for (int i = 0; i < lines.size(); i++) {
49              sb.append((String) lines.get(i));
50              sb.append(PMD.EOL);
51          }
52          return sb;
53      }
54  
55      public void readSource(Reader input) throws IOException {
56          List lines = new ArrayList();
57          LineNumberReader r = new LineNumberReader(input);
58          String currentLine;
59          while ((currentLine = r.readLine()) != null) {
60              lines.add(currentLine);
61          }
62          input.close();
63          this.code = new SoftReference(lines);
64      }
65  
66      public String getSlice(int startLine, int endLine) {
67          StringBuffer sb = new StringBuffer();
68          List lines = getCode();
69          for (int i = startLine - 1; i < endLine && i < lines.size(); i++) {
70              if (sb.length() != 0) {
71                  sb.append(PMD.EOL);
72              }
73              sb.append((String) lines.get(i));
74          }
75          return sb.toString();
76      }
77  
78      public String getFileName() {
79          return fileName;
80      }
81  
82      public boolean equals(Object other) {
83          SourceCode o = (SourceCode) other;
84          return o.fileName.equals(fileName);
85      }
86  
87      public int hashCode() {
88          return fileName.hashCode();
89      }
90  }