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.FormulaData;
023 import org.sonar.api.measures.Measure;
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.List;
029
030 /**
031 * @since 1.11
032 */
033 public class FormulaDecorator implements Decorator {
034
035 private Metric metric;
036 private DefaultFormulaContext formulaContext;
037
038 public FormulaDecorator(Metric metric) {
039 if (metric.getFormula() == null) {
040 throw new IllegalArgumentException("No formula defined on metric");
041 }
042 this.metric = metric;
043 this.formulaContext = new DefaultFormulaContext(metric);
044 }
045
046 public boolean shouldExecuteOnProject(Project project) {
047 return true;
048 }
049
050 @DependedUpon
051 public Metric generatesMetric() {
052 return metric;
053 }
054
055 @DependsUpon
056 public List<Metric> dependsUponMetrics() {
057 return metric.getFormula().dependsUponMetrics();
058 }
059
060 public void decorate(Resource resource, DecoratorContext context) {
061 if (context.getMeasure(metric) != null) {
062 return;
063 }
064
065 formulaContext.setDecoratorContext(context);
066 FormulaData data = new DefaultFormulaData(context);
067 Measure measure = metric.getFormula().calculate(data, formulaContext);
068 if (measure != null) {
069 context.saveMeasure(measure);
070 }
071 }
072
073 @Override
074 public boolean equals(Object o) {
075 if (this == o) {
076 return true;
077 }
078 if (o == null || getClass() != o.getClass()) {
079 return false;
080 }
081
082 FormulaDecorator that = (FormulaDecorator) o;
083
084 if (metric != null ? !metric.equals(that.metric) : that.metric != null) {
085 return false;
086 }
087 return true;
088 }
089
090 @Override
091 public int hashCode() {
092 return metric != null ? metric.hashCode() : 0;
093 }
094
095 @Override
096 public String toString() {
097 return new StringBuilder().append("f(").append(metric).append(")").toString();
098 }
099 }