1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.sonar.maven;
21
22 import org.apache.commons.lang.StringUtils;
23 import org.apache.maven.project.MavenProject;
24 import org.sonar.maven.Collector;
25 import org.sonar.plugins.api.MissingDataException;
26 import org.sonar.plugins.utils.XmlReportParser;
27
28 import java.io.File;
29 import java.math.BigDecimal;
30 import java.math.RoundingMode;
31 import java.text.NumberFormat;
32 import java.text.ParseException;
33 import java.util.List;
34 import java.util.Locale;
35
36 public abstract class AbstractCollector implements Collector {
37 protected double parseNumber(String number, Locale locale) throws ParseException {
38 if (number.equals("")){
39 return Double.NaN;
40 }
41 return NumberFormat.getNumberInstance(locale).parse(number).doubleValue();
42 }
43
44 protected double parseNumber(String number) throws ParseException {
45 return parseNumber(number, Locale.getDefault());
46 }
47
48 protected double scaleValue(double value) {
49 return scaleValue(value, 2);
50 }
51
52 protected double scaleValue(double value, int decimals) {
53 BigDecimal bd = new BigDecimal(value);
54 return bd.setScale(decimals, RoundingMode.HALF_UP).doubleValue();
55 }
56
57 protected XmlReportParser loadAndParseXmlReport(File xmlFile) throws MissingDataException {
58 if (!xmlFile.exists()) {
59 throw new MissingDataException("File does not exist : " + xmlFile.toString());
60 }
61 XmlReportParser parser = new XmlReportParser();
62 parser.parse(xmlFile);
63 return parser;
64 }
65
66 protected File findFileFromBuildDirectory( MavenProject project, String filename ) {
67 String xmlOutputDirectory = project.getBuild().getDirectory() + "/" + filename;
68 java.io.File file = new java.io.File( xmlOutputDirectory );
69 if ( !file.exists() ) {
70 file = null;
71 }
72 return file;
73 }
74
75 protected String[] getPackageAndClass(String absoluteFilename, List<String> sourceDirs) {
76 String unixFilename = absoluteFilename.replace('\\', '/');
77 String filename = StringUtils.substringAfterLast(unixFilename, "/");
78 String namespace = StringUtils.substringBeforeLast(unixFilename, filename);
79
80 if (! filename.toLowerCase(Locale.ENGLISH).endsWith(".java")) {
81 return null;
82 }
83
84
85 for (String sourceDir : sourceDirs) {
86 sourceDir = sourceDir.replace('\\', '/');
87 if (!sourceDir.endsWith("/")) {
88 sourceDir += "/";
89 }
90 if (namespace.startsWith(sourceDir) || namespace.contains(sourceDir)) {
91 namespace = StringUtils.substringAfter(namespace, sourceDir);
92
93
94 if (namespace.startsWith("/")) {
95 namespace = StringUtils.substringAfter(namespace, "/");
96 }
97 if (namespace.endsWith("/")) {
98 namespace = StringUtils.substringBeforeLast(namespace, "/");
99 }
100
101
102 namespace = namespace.replace('/', '.');
103
104
105 if ("".equals(namespace)) {
106 namespace = null;
107 }
108
109 return new String[]{namespace, StringUtils.substringBeforeLast(filename, ".")};
110 }
111 }
112
113 return null;
114 }
115 }