001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2009 SonarSource SA 004 * mailto:contact AT sonarsource DOT com 005 * 006 * Sonar 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 * Sonar 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 017 * License along with Sonar; if not, write to the Free Software 018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 019 */ 020 package org.sonar.api.batch; 021 022 import org.sonar.api.measures.Measure; 023 import org.sonar.api.measures.MeasureUtils; 024 import org.sonar.api.measures.Metric; 025 import org.sonar.api.resources.Project; 026 import org.sonar.api.resources.Resource; 027 028 import java.util.Arrays; 029 import java.util.List; 030 031 /** 032 * @since 1.10 033 */ 034 public abstract class AbstractDivisionDecorator implements Decorator { 035 036 protected abstract Metric getQuotientMetric(); 037 038 protected abstract Metric getDivisorMetric(); 039 040 protected abstract Metric getDividendMetric(); 041 042 @DependsUpon 043 public List<Metric> dependsUponMetrics() { 044 return Arrays.asList(getDividendMetric(), getDivisorMetric()); 045 } 046 047 @DependedUpon 048 public Metric generatesMetric() { 049 return getQuotientMetric(); 050 } 051 052 public boolean shouldExecuteOnProject(Project project) { 053 return true; 054 } 055 056 public void decorate(Resource resource, DecoratorContext context) { 057 if (!shouldDecorateResource(context)) { 058 return; 059 } 060 Measure dividend = context.getMeasure(getDividendMetric()); 061 Measure divisor = context.getMeasure(getDivisorMetric()); 062 063 if (MeasureUtils.hasValue(dividend) && MeasureUtils.hasValue(divisor) && divisor.getValue() > 0.0) { 064 context.saveMeasure(new Measure(getQuotientMetric(), compute(dividend, divisor, getQuotientMetric().isPercentageType()))); 065 } 066 } 067 068 protected boolean shouldDecorateResource(DecoratorContext context) { 069 return context.getMeasure(getQuotientMetric()) == null; 070 } 071 072 073 protected double compute(Measure dividend, Measure divisor, boolean shouldResultBeInPercent) { 074 double result = dividend.getValue() / divisor.getValue(); 075 return shouldResultBeInPercent ? result * 100 : result; 076 } 077 078 }