001    /*
002     * SonarQube, open source software quality management tool.
003     * Copyright (C) 2008-2014 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * SonarQube is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * SonarQube is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public License
017     * along with this program; if not, write to the Free Software Foundation,
018     * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019     */
020    package org.sonar.batch.qualitygate;
021    
022    import org.sonar.api.batch.*;
023    import org.sonar.api.measures.CoreMetrics;
024    import org.sonar.api.measures.Measure;
025    import org.sonar.api.measures.Metric;
026    import org.sonar.api.measures.Metric.Level;
027    import org.sonar.api.notifications.Notification;
028    import org.sonar.api.notifications.NotificationManager;
029    import org.sonar.api.resources.Project;
030    import org.sonar.api.resources.Resource;
031    import org.sonar.api.resources.ResourceUtils;
032    
033    import java.util.List;
034    
035    public class GenerateQualityGateEvents implements Decorator {
036    
037      private final QualityGate qualityGate;
038      private final TimeMachine timeMachine;
039      private NotificationManager notificationManager;
040    
041      public GenerateQualityGateEvents(QualityGate qualityGate, TimeMachine timeMachine, NotificationManager notificationManager) {
042        this.qualityGate = qualityGate;
043        this.timeMachine = timeMachine;
044        this.notificationManager = notificationManager;
045      }
046    
047      public boolean shouldExecuteOnProject(Project project) {
048        return qualityGate.isEnabled();
049      }
050    
051      @DependsUpon
052      public Metric dependsUponAlertStatus() {
053        return CoreMetrics.ALERT_STATUS;
054      }
055    
056      public void decorate(Resource resource, DecoratorContext context) {
057        if (!shouldDecorateResource(resource)) {
058          return;
059        }
060        Measure currentStatus = context.getMeasure(CoreMetrics.ALERT_STATUS);
061        if (currentStatus == null) {
062          return;
063        }
064    
065        TimeMachineQuery query = new TimeMachineQuery(resource).setOnlyLastAnalysis(true).setMetrics(CoreMetrics.ALERT_STATUS);
066        List<Measure> measures = timeMachine.getMeasures(query);
067    
068        Measure pastStatus = measures != null && measures.size() == 1 ? measures.get(0) : null;
069        checkQualityGateStatusChange(resource, context, currentStatus, pastStatus);
070    
071      }
072    
073      private void checkQualityGateStatusChange(Resource resource, DecoratorContext context, Measure currentStatus, Measure pastStatus) {
074        String alertText = currentStatus.getAlertText();
075        Level alertLevel = currentStatus.getDataAsLevel();
076        String alertName = null;
077        boolean isNewAlert = true;
078        if (pastStatus != null && pastStatus.getDataAsLevel() != alertLevel) {
079          // The alert status has changed
080          alertName = getName(pastStatus, currentStatus);
081          if (pastStatus.getDataAsLevel() != Metric.Level.OK) {
082            // There was already a Orange/Red alert, so this is no new alert: it has just changed
083            isNewAlert = false;
084          }
085          createEvent(context, alertName, alertText);
086          notifyUsers(resource, alertName, alertText, alertLevel, isNewAlert);
087    
088        } else if (pastStatus == null && alertLevel != Metric.Level.OK) {
089          // There were no defined alerts before, so this one is a new one
090          alertName = getName(currentStatus);
091          createEvent(context, alertName, alertText);
092          notifyUsers(resource, alertName, alertText, alertLevel, isNewAlert);
093        }
094      }
095    
096      protected void notifyUsers(Resource resource, String alertName, String alertText, Level alertLevel, boolean isNewAlert) {
097        Notification notification = new Notification("alerts")
098          .setDefaultMessage("Alert on " + resource.getLongName() + ": " + alertName)
099          .setFieldValue("projectName", resource.getLongName())
100          .setFieldValue("projectKey", resource.getKey())
101          .setFieldValue("projectId", String.valueOf(resource.getId()))
102          .setFieldValue("alertName", alertName)
103          .setFieldValue("alertText", alertText)
104          .setFieldValue("alertLevel", alertLevel.toString())
105          .setFieldValue("isNewAlert", Boolean.toString(isNewAlert));
106        notificationManager.scheduleForSending(notification);
107      }
108    
109      private boolean shouldDecorateResource(Resource resource) {
110        return ResourceUtils.isRootProject(resource);
111      }
112    
113      private String getName(Measure pastStatus, Measure currentStatus) {
114        return getName(currentStatus) + " (was " + getName(pastStatus) + ")";
115    
116      }
117    
118      private String getName(Measure currentStatus) {
119        return currentStatus.getDataAsLevel().getColorName();
120      }
121    
122      private void createEvent(DecoratorContext context, String name, String description) {
123        context.createEvent(name, description, Event.CATEGORY_ALERT, null);
124      }
125    }