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.measures;
021
022 import org.apache.commons.lang.StringUtils;
023
024 import java.util.Collection;
025
026 /**
027 * @since 1.10
028 */
029 public final class MeasureUtils {
030
031 private MeasureUtils() {
032 }
033
034 /**
035 * Return true if all measures have numeric value.
036 */
037 public static boolean haveValues(Measure... measures) {
038 if (measures == null || measures.length == 0) {
039 return false;
040 }
041 for (Measure measure : measures) {
042 if (!hasValue(measure)) {
043 return false;
044 }
045 }
046 return true;
047 }
048
049 /**
050 * Get the measure value. Return <code>defaultValue</code> if measure is null or has no values.
051 */
052 public static Double getValue(Measure measure, Double defaultValue) {
053 if (MeasureUtils.hasValue(measure)) {
054 return measure.getValue();
055 }
056 return defaultValue;
057 }
058
059 public static boolean hasValue(Measure measure) {
060 return measure != null && measure.getValue() != null;
061 }
062
063 public static boolean hasData(Measure measure) {
064 return measure != null && StringUtils.isNotBlank(measure.getData());
065 }
066
067 public static Double sum(boolean zeroIfNone, Collection<Measure> measures) {
068 if (measures != null) {
069 return sum(zeroIfNone, measures.toArray(new Measure[measures.size()]));
070 }
071 return zeroIfNone(zeroIfNone);
072 }
073
074 public static Double sum(boolean zeroIfNone, Measure... measures) {
075 if (measures == null) {
076 return zeroIfNone(zeroIfNone);
077 }
078 Double sum = 0d;
079 boolean hasValue = false;
080 for (Measure measure : measures) {
081 if (measure != null && measure.getValue() != null) {
082 hasValue = true;
083 sum += measure.getValue();
084 }
085 }
086
087 if (hasValue) {
088 return sum;
089 }
090 return zeroIfNone(zeroIfNone);
091 }
092
093 private static Double zeroIfNone(boolean zeroIfNone) {
094 return zeroIfNone ? 0d : null;
095 }
096 }