2 * SonarQube, open source software quality management tool.
3 * Copyright (C) 2008-2013 SonarSource
4 * mailto:contact AT sonarsource DOT com
6 * SonarQube is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * SonarQube is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.plugins.core.timemachine;
22 import com.google.common.collect.ArrayListMultimap;
23 import com.google.common.collect.ListMultimap;
24 import com.google.common.collect.Sets;
25 import org.apache.commons.lang.StringUtils;
26 import org.sonar.api.batch.Decorator;
27 import org.sonar.api.batch.DecoratorBarriers;
28 import org.sonar.api.batch.DecoratorContext;
29 import org.sonar.api.batch.DependedUpon;
30 import org.sonar.api.batch.DependsUpon;
31 import org.sonar.api.measures.CoreMetrics;
32 import org.sonar.api.measures.Measure;
33 import org.sonar.api.measures.MeasureUtils;
34 import org.sonar.api.measures.MeasuresFilters;
35 import org.sonar.api.measures.Metric;
36 import org.sonar.api.measures.RuleMeasure;
37 import org.sonar.api.notifications.Notification;
38 import org.sonar.api.notifications.NotificationManager;
39 import org.sonar.api.resources.Project;
40 import org.sonar.api.resources.Resource;
41 import org.sonar.api.resources.ResourceUtils;
42 import org.sonar.api.resources.Scopes;
43 import org.sonar.api.rules.Rule;
44 import org.sonar.api.rules.RulePriority;
45 import org.sonar.api.rules.Violation;
46 import org.sonar.batch.components.PastSnapshot;
47 import org.sonar.batch.components.TimeMachineConfiguration;
49 import java.text.DateFormat;
50 import java.text.SimpleDateFormat;
51 import java.util.Arrays;
52 import java.util.Collection;
53 import java.util.Date;
54 import java.util.List;
57 @DependsUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
58 public class NewViolationsDecorator implements Decorator {
60 private TimeMachineConfiguration timeMachineConfiguration;
61 private NotificationManager notificationManager;
63 public NewViolationsDecorator(TimeMachineConfiguration timeMachineConfiguration, NotificationManager notificationManager) {
64 this.timeMachineConfiguration = timeMachineConfiguration;
65 this.notificationManager = notificationManager;
68 public boolean shouldExecuteOnProject(Project project) {
69 return project.isLatestAnalysis();
73 public List<Metric> generatesMetric() {
75 CoreMetrics.NEW_VIOLATIONS,
76 CoreMetrics.NEW_BLOCKER_VIOLATIONS,
77 CoreMetrics.NEW_CRITICAL_VIOLATIONS,
78 CoreMetrics.NEW_MAJOR_VIOLATIONS,
79 CoreMetrics.NEW_MINOR_VIOLATIONS,
80 CoreMetrics.NEW_INFO_VIOLATIONS);
83 @SuppressWarnings("rawtypes")
84 public void decorate(Resource resource, DecoratorContext context) {
85 if (shouldDecorateResource(resource, context)) {
86 computeNewViolations(context);
87 computeNewViolationsPerSeverity(context);
88 computeNewViolationsPerRule(context);
90 if (ResourceUtils.isRootProject(resource)) {
91 notifyNewViolations((Project) resource, context);
95 private boolean shouldDecorateResource(Resource<?> resource, DecoratorContext context) {
96 return (StringUtils.equals(Scopes.PROJECT, resource.getScope()) || StringUtils.equals(Scopes.DIRECTORY, resource.getScope()) || StringUtils
97 .equals(Scopes.FILE, resource.getScope()))
98 && (context.getMeasure(CoreMetrics.NEW_VIOLATIONS) == null);
101 private void computeNewViolations(DecoratorContext context) {
102 Measure measure = new Measure(CoreMetrics.NEW_VIOLATIONS);
103 for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
104 int variationIndex = pastSnapshot.getIndex();
105 Collection<Measure> children = context.getChildrenMeasures(CoreMetrics.NEW_VIOLATIONS);
106 int count = countViolations(context.getViolations(), pastSnapshot.getTargetDate());
107 double sum = MeasureUtils.sumOnVariation(true, variationIndex, children) + count;
108 measure.setVariation(variationIndex, sum);
110 context.saveMeasure(measure);
113 private void computeNewViolationsPerSeverity(DecoratorContext context) {
114 ListMultimap<RulePriority, Violation> violationsPerSeverities = ArrayListMultimap.create();
115 for (Violation violation : context.getViolations()) {
116 violationsPerSeverities.put(violation.getSeverity(), violation);
119 for (RulePriority severity : RulePriority.values()) {
120 Metric metric = severityToMetric(severity);
121 Measure measure = new Measure(metric);
122 for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
123 int variationIndex = pastSnapshot.getIndex();
124 int count = countViolations(violationsPerSeverities.get(severity), pastSnapshot.getTargetDate());
125 Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.metric(metric));
126 double sum = MeasureUtils.sumOnVariation(true, variationIndex, children) + count;
127 measure.setVariation(variationIndex, sum);
129 context.saveMeasure(measure);
133 private void computeNewViolationsPerRule(DecoratorContext context) {
134 for (RulePriority severity : RulePriority.values()) {
135 Metric metric = severityToMetric(severity);
136 ListMultimap<Rule, Measure> childMeasuresPerRule = ArrayListMultimap.create();
137 ListMultimap<Rule, Violation> violationsPerRule = ArrayListMultimap.create();
138 Set<Rule> rules = Sets.newHashSet();
140 Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
141 for (Measure child : children) {
142 RuleMeasure childRuleMeasure = (RuleMeasure) child;
143 Rule rule = childRuleMeasure.getRule();
145 childMeasuresPerRule.put(rule, childRuleMeasure);
150 for (Violation violation : context.getViolations()) {
151 if (violation.getSeverity().equals(severity)) {
152 rules.add(violation.getRule());
153 violationsPerRule.put(violation.getRule(), violation);
157 for (Rule rule : rules) {
158 RuleMeasure measure = RuleMeasure.createForRule(metric, rule, null);
159 measure.setSeverity(severity);
160 for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
161 int variationIndex = pastSnapshot.getIndex();
162 int count = countViolations(violationsPerRule.get(rule), pastSnapshot.getTargetDate());
163 double sum = MeasureUtils.sumOnVariation(true, variationIndex, childMeasuresPerRule.get(rule)) + count;
164 measure.setVariation(variationIndex, sum);
166 context.saveMeasure(measure);
171 int countViolations(Collection<Violation> violations, Date targetDate) {
172 if (violations == null) {
176 for (Violation violation : violations) {
177 if (isAfter(violation, targetDate)) {
184 private boolean isAfter(Violation violation, Date date) {
188 return violation.getCreatedAt() != null && violation.getCreatedAt().after(date);
191 private Metric severityToMetric(RulePriority severity) {
193 if (severity.equals(RulePriority.BLOCKER)) {
194 metric = CoreMetrics.NEW_BLOCKER_VIOLATIONS;
195 } else if (severity.equals(RulePriority.CRITICAL)) {
196 metric = CoreMetrics.NEW_CRITICAL_VIOLATIONS;
197 } else if (severity.equals(RulePriority.MAJOR)) {
198 metric = CoreMetrics.NEW_MAJOR_VIOLATIONS;
199 } else if (severity.equals(RulePriority.MINOR)) {
200 metric = CoreMetrics.NEW_MINOR_VIOLATIONS;
201 } else if (severity.equals(RulePriority.INFO)) {
202 metric = CoreMetrics.NEW_INFO_VIOLATIONS;
204 throw new IllegalArgumentException("Unsupported severity: " + severity);
209 protected void notifyNewViolations(Project project, DecoratorContext context) {
210 List<PastSnapshot> projectPastSnapshots = timeMachineConfiguration.getProjectPastSnapshots();
211 if (projectPastSnapshots.size() >= 1) {
212 // we always check new violations against period1
213 PastSnapshot pastSnapshot = projectPastSnapshots.get(0);
214 Double newViolationsCount = context.getMeasure(CoreMetrics.NEW_VIOLATIONS).getVariation1();
215 // Do not send notification if this is the first analysis or if there's no violation
216 if (pastSnapshot.getTargetDate() != null && newViolationsCount != null && newViolationsCount > 0) {
217 // Maybe we should check if this is the first analysis or not?
218 DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
219 Notification notification = new Notification("new-violations")
220 .setDefaultMessage(newViolationsCount.intValue() + " new violations on " + project.getLongName() + ".")
221 .setFieldValue("count", String.valueOf(newViolationsCount.intValue()))
222 .setFieldValue("projectName", project.getLongName())
223 .setFieldValue("projectKey", project.getKey())
224 .setFieldValue("projectId", String.valueOf(project.getId()))
225 .setFieldValue("fromDate", dateformat.format(pastSnapshot.getTargetDate()));
226 notificationManager.scheduleForSending(notification);
232 public String toString() {
233 return getClass().getSimpleName();