1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.sonar.plugins.scala.language;
21
22 import java.io.IOException;
23 import java.util.List;
24
25 import org.apache.commons.lang3.builder.EqualsBuilder;
26 import org.apache.commons.lang3.builder.HashCodeBuilder;
27 import org.apache.commons.lang3.builder.ToStringBuilder;
28 import org.sonar.plugins.scala.util.StringUtils;
29
30
31
32
33
34
35
36
37 public class Comment {
38
39 private final CommentType type;
40 private final List<String> lines;
41
42 public Comment(String content, CommentType type) throws IOException {
43 lines = StringUtils.convertStringToListOfLines(content);
44 this.type = type;
45 }
46
47 public int getNumberOfLines() {
48 return lines.size() - getNumberOfBlankLines() - getNumberOfCommentedOutLinesOfCode();
49 }
50
51 public int getNumberOfBlankLines() {
52 int numberOfBlankLines = 0;
53 for (String comment : lines) {
54 boolean isBlank = true;
55
56 for (int i = 0; isBlank && i < comment.length(); i++) {
57 char character = comment.charAt(i);
58 if (!Character.isWhitespace(character) && character != '*' && character != '/') {
59 isBlank = false;
60 }
61 }
62
63 if (isBlank) {
64 numberOfBlankLines++;
65 }
66 }
67 return numberOfBlankLines;
68 }
69
70 public int getNumberOfCommentedOutLinesOfCode() {
71 if (isDocComment()) {
72 return 0;
73 }
74
75 int numberOfCommentedOutLinesOfCode = 0;
76 for (String line : lines) {
77 String strippedLine = org.apache.commons.lang3.StringUtils.strip(line, " /*");
78 if (CodeDetector.hasDetectedCode(strippedLine)) {
79 numberOfCommentedOutLinesOfCode++;
80 }
81 }
82 return numberOfCommentedOutLinesOfCode;
83 }
84
85 public boolean isDocComment() {
86 return type == CommentType.DOC;
87 }
88
89 public boolean isHeaderComment() {
90 return type == CommentType.HEADER;
91 }
92
93 @Override
94 public int hashCode() {
95 return new HashCodeBuilder().append(type).append(lines).toHashCode();
96 }
97
98 @Override
99 public boolean equals(Object obj) {
100 if (!(obj instanceof Comment)) {
101 return false;
102 }
103
104 Comment other = (Comment) obj;
105 return new EqualsBuilder().append(type, other.type).append(lines, other.lines).isEquals();
106 }
107
108 @Override
109 public String toString() {
110 final String firstLine = lines.isEmpty() ? "" : lines.get(0);
111 final String lastLine = lines.isEmpty() ? "" : lines.get(lines.size() - 1);
112 return new ToStringBuilder(this).append("type", type)
113 .append("firstLine", firstLine)
114 .append("lastLine", lastLine)
115 .append("numberOfLines", getNumberOfLines())
116 .append("numberOfCommentedOutLinesOfCode", getNumberOfCommentedOutLinesOfCode())
117 .toString();
118 }
119 }