]> source.dussan.org Git - sonarqube.git/blob
cabaeb5e5dbaddfba026aa6b7df2f47112fcb2a4
[sonarqube.git] /
1 /*
2  * SonarQube, open source software quality management tool.
3  * Copyright (C) 2008-2013 SonarSource
4  * mailto:contact AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.plugins.core.timemachine;
21
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;
48
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;
55 import java.util.Set;
56
57 @DependsUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
58 public class NewViolationsDecorator implements Decorator {
59
60   private TimeMachineConfiguration timeMachineConfiguration;
61   private NotificationManager notificationManager;
62
63   public NewViolationsDecorator(TimeMachineConfiguration timeMachineConfiguration, NotificationManager notificationManager) {
64     this.timeMachineConfiguration = timeMachineConfiguration;
65     this.notificationManager = notificationManager;
66   }
67
68   public boolean shouldExecuteOnProject(Project project) {
69     return project.isLatestAnalysis();
70   }
71
72   @DependedUpon
73   public List<Metric> generatesMetric() {
74     return Arrays.asList(
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);
81   }
82
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);
89     }
90     if (ResourceUtils.isRootProject(resource)) {
91       notifyNewViolations((Project) resource, context);
92     }
93   }
94
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);
99   }
100
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);
109     }
110     context.saveMeasure(measure);
111   }
112
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);
117     }
118
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);
128       }
129       context.saveMeasure(measure);
130     }
131   }
132
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();
139
140       Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
141       for (Measure child : children) {
142         RuleMeasure childRuleMeasure = (RuleMeasure) child;
143         Rule rule = childRuleMeasure.getRule();
144         if (rule != null) {
145           childMeasuresPerRule.put(rule, childRuleMeasure);
146           rules.add(rule);
147         }
148       }
149
150       for (Violation violation : context.getViolations()) {
151         if (violation.getSeverity().equals(severity)) {
152           rules.add(violation.getRule());
153           violationsPerRule.put(violation.getRule(), violation);
154         }
155       }
156
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);
165         }
166         context.saveMeasure(measure);
167       }
168     }
169   }
170
171   int countViolations(Collection<Violation> violations, Date targetDate) {
172     if (violations == null) {
173       return 0;
174     }
175     int count = 0;
176     for (Violation violation : violations) {
177       if (isAfter(violation, targetDate)) {
178         count++;
179       }
180     }
181     return count;
182   }
183
184   private boolean isAfter(Violation violation, Date date) {
185     if (date == null) {
186       return true;
187     }
188     return violation.getCreatedAt() != null && violation.getCreatedAt().after(date);
189   }
190
191   private Metric severityToMetric(RulePriority severity) {
192     Metric metric;
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;
203     } else {
204       throw new IllegalArgumentException("Unsupported severity: " + severity);
205     }
206     return metric;
207   }
208
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);
227       }
228     }
229   }
230
231   @Override
232   public String toString() {
233     return getClass().getSimpleName();
234   }
235 }