PageRenderTime 29ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/org/andya/confluence/utils/MathUtils.java

https://bitbucket.org/jwalton/metadata-confluence-plugin
Java | 168 lines | 111 code | 12 blank | 45 comment | 43 complexity | 4b9425dc755fd9a32376dc35b8d219da MD5 | raw file
  1. /*
  2. * Copyright (c) 2006, 2007 Andy Armstrong, Kelsey Grant and other contributors.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * * The names of contributors may not
  14. * be used to endorse or promote products derived from this software without
  15. * specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  18. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  21. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  24. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. package org.andya.confluence.utils;
  29. import com.atlassian.renderer.v2.macro.MacroException;
  30. import java.util.List;
  31. /**
  32. * Useful math utilities for use in macros.
  33. */
  34. public class MathUtils {
  35. /**
  36. * Parse a string as a number in the following order: 1. If the value is in
  37. * Confluence duration format return a {@link Duration}. 2. If the value is
  38. * an Integer return an integer. 3. If all else fails try to parse the
  39. * number as a double.
  40. */
  41. public static Number parseNumber(String value) {
  42. Duration duration = Duration.parseDuration(value);
  43. if (duration != null)
  44. return duration;
  45. try {
  46. // clean the value by stripping out non digits.
  47. // this lets people put $ signs and other misc units into
  48. // integer fields safely.
  49. char[] chars = value.toCharArray();
  50. StringBuffer out = new StringBuffer();
  51. for (int i = 0; i < chars.length; i++) {
  52. char c = chars[i];
  53. if (c >= '0' && c <= '9') {
  54. out.append(c);
  55. } else if (c == '.' || c == '-') {
  56. out.append(c);
  57. }
  58. }
  59. value = out.toString();
  60. int intValue = Integer.parseInt(value);
  61. return new Integer(intValue);
  62. } catch (NumberFormatException e) {
  63. try {
  64. double doubleValue = Double.parseDouble(value);
  65. return new Double(doubleValue);
  66. } catch (NumberFormatException e2) {
  67. return null;
  68. }
  69. }
  70. }
  71. /** Converts a number to the best string representation. */
  72. public static String toString(Number number) {
  73. if (number instanceof Duration)
  74. return ((Duration) number).getDurationString();
  75. else if (number instanceof Integer)
  76. return Integer.toString(number.intValue());
  77. else
  78. return Double.toString(number.doubleValue());
  79. }
  80. /** Apply the specified function to a list of values. */
  81. public static Number doCalculation(String function, List<Number> values)
  82. throws MacroException {
  83. function = function.trim().toLowerCase();
  84. if ("sum".equals(function))
  85. return sum(values);
  86. else if ("avg".equals(function) || "average".equals(function))
  87. return average(values);
  88. else if ("min".equals(function) || "minimum".equals(function))
  89. return min(values);
  90. else if ("max".equals(function) || "maximum".equals(function))
  91. return max(values);
  92. throw new MacroException("Unknown function \"" + function + "\"");
  93. }
  94. /** Calculate the sum of a list of numbers. */
  95. public static Number sum(List<Number> values) {
  96. double sum = 0;
  97. boolean integerOnly = true;
  98. boolean duration = false;
  99. for (Number number : values) {
  100. if (number instanceof Double)
  101. integerOnly = false;
  102. else if (number instanceof Duration)
  103. duration = true;
  104. sum += number.doubleValue();
  105. }
  106. if (duration)
  107. return new Duration((long) sum);
  108. if (integerOnly)
  109. return new Integer((int) sum);
  110. return new Double(sum);
  111. }
  112. /** Calculate the average of a list of numbers. */
  113. public static Number average(List<Number> values) {
  114. Number total = sum(values);
  115. double average = total.doubleValue() / values.size();
  116. if (total instanceof Duration)
  117. return new Duration((long) average);
  118. return new Double(average);
  119. }
  120. /** Calculate the minimum of a list of numbers. */
  121. public static Number min(List<Number> values) {
  122. double min = Double.MAX_VALUE;
  123. boolean integerOnly = true;
  124. boolean duration = false;
  125. for (Number number : values) {
  126. if (number instanceof Duration)
  127. duration = true;
  128. else if (number instanceof Double)
  129. integerOnly = false;
  130. min = Math.min(min, number.doubleValue());
  131. }
  132. if (duration)
  133. return new Duration((long) min);
  134. else if (integerOnly)
  135. return new Integer((int) min);
  136. return new Double(min);
  137. }
  138. /** Calculate the maximum of a list of numbers. */
  139. public static Number max(List<Number> values) {
  140. double max = Double.MIN_VALUE;
  141. boolean integerOnly = true;
  142. boolean duration = false;
  143. for (Number number : values) {
  144. if (number instanceof Duration)
  145. duration = true;
  146. else if (number instanceof Double)
  147. integerOnly = false;
  148. max = Math.max(max, number.doubleValue());
  149. }
  150. if (duration)
  151. return new Duration((long) max);
  152. if (integerOnly)
  153. return new Integer((int) max);
  154. return new Double(max);
  155. }
  156. }