]> source.dussan.org Git - sonarqube.git/blob
48b97f0a60e19f3810de1c7991a722b766bec7ab
[sonarqube.git] /
1 /*
2  * Sonar, open source software quality management tool.
3  * Copyright (C) 2008-2012 SonarSource
4  * mailto:contact AT sonarsource DOT com
5  *
6  * Sonar 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  * Sonar 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
17  * License along with Sonar; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
19  */
20 package org.sonar.plugins.core.timemachine;
21
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Date;
25 import java.util.List;
26 import java.util.Set;
27
28 import org.apache.commons.lang.StringUtils;
29 import org.sonar.api.batch.Decorator;
30 import org.sonar.api.batch.DecoratorBarriers;
31 import org.sonar.api.batch.DecoratorContext;
32 import org.sonar.api.batch.DependedUpon;
33 import org.sonar.api.batch.DependsUpon;
34 import org.sonar.api.measures.CoreMetrics;
35 import org.sonar.api.measures.Measure;
36 import org.sonar.api.measures.MeasureUtils;
37 import org.sonar.api.measures.MeasuresFilters;
38 import org.sonar.api.measures.Metric;
39 import org.sonar.api.measures.RuleMeasure;
40 import org.sonar.api.notifications.Notification;
41 import org.sonar.api.notifications.NotificationManager;
42 import org.sonar.api.resources.Project;
43 import org.sonar.api.resources.Resource;
44 import org.sonar.api.resources.ResourceUtils;
45 import org.sonar.api.resources.Scopes;
46 import org.sonar.api.rules.Rule;
47 import org.sonar.api.rules.RulePriority;
48 import org.sonar.api.rules.Violation;
49 import org.sonar.batch.components.PastSnapshot;
50 import org.sonar.batch.components.TimeMachineConfiguration;
51
52 import com.google.common.collect.ArrayListMultimap;
53 import com.google.common.collect.ListMultimap;
54 import com.google.common.collect.Sets;
55
56 @DependsUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
57 public class NewViolationsDecorator implements Decorator {
58
59   private TimeMachineConfiguration timeMachineConfiguration;
60   private NotificationManager notificationManager;
61
62   public NewViolationsDecorator(TimeMachineConfiguration timeMachineConfiguration, NotificationManager notificationManager) {
63     this.timeMachineConfiguration = timeMachineConfiguration;
64     this.notificationManager = notificationManager;
65   }
66
67   public boolean shouldExecuteOnProject(Project project) {
68     return project.isLatestAnalysis();
69   }
70
71   @DependedUpon
72   public List<Metric> generatesMetric() {
73     return Arrays.asList(
74         CoreMetrics.NEW_VIOLATIONS,
75         CoreMetrics.NEW_BLOCKER_VIOLATIONS,
76         CoreMetrics.NEW_CRITICAL_VIOLATIONS,
77         CoreMetrics.NEW_MAJOR_VIOLATIONS,
78         CoreMetrics.NEW_MINOR_VIOLATIONS,
79         CoreMetrics.NEW_INFO_VIOLATIONS);
80   }
81
82   @SuppressWarnings("rawtypes")
83   public void decorate(Resource resource, DecoratorContext context) {
84     if (shouldDecorateResource(resource, context)) {
85       computeNewViolations(context);
86       computeNewViolationsPerSeverity(context);
87       computeNewViolationsPerRule(context);
88     }
89     if (ResourceUtils.isRootProject(resource)) {
90       notifyNewViolations((Project) resource, context);
91     }
92   }
93
94   private boolean shouldDecorateResource(Resource<?> resource, DecoratorContext context) {
95     return (StringUtils.equals(Scopes.PROJECT, resource.getScope()) || StringUtils.equals(Scopes.DIRECTORY, resource.getScope()) || StringUtils
96         .equals(Scopes.FILE, resource.getScope()))
97       && !ResourceUtils.isUnitTestClass(resource)
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.setRulePriority(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     Integer lastAnalysisPeriodIndex = timeMachineConfiguration.getLastAnalysisPeriodIndex();
211     if (lastAnalysisPeriodIndex != null) {
212       Double newViolationsCount = context.getMeasure(CoreMetrics.NEW_VIOLATIONS).getVariation(lastAnalysisPeriodIndex);
213       if (newViolationsCount != null && newViolationsCount > 0) {
214         // Maybe we should check if this is the first analysis or not?
215         Notification notification = new Notification("new-violations")
216             .setFieldValue("count", String.valueOf(newViolationsCount.intValue()))
217             .setFieldValue("projectName", project.getLongName())
218             .setFieldValue("projectKey", project.getKey())
219             .setFieldValue("projectId", String.valueOf(project.getId()))
220             .setFieldValue("period", lastAnalysisPeriodIndex.toString());
221         notificationManager.scheduleForSending(notification);
222       }
223     }
224   }
225
226   @Override
227   public String toString() {
228     return getClass().getSimpleName();
229   }
230 }