]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/util/Throughput.java
Prepare next development cycle
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / util / Throughput.java
1 package org.argeo.cms.util;
2
3 import java.text.NumberFormat;
4 import java.text.ParseException;
5 import java.util.Locale;
6
7 /** A throughput, that is, a value per unit of time. */
8 public class Throughput {
9 private final static NumberFormat usNumberFormat = NumberFormat.getInstance(Locale.US);
10
11 public enum Unit {
12 s, m, h, d
13 }
14
15 private final Double value;
16 private final Unit unit;
17
18 public Throughput(Double value, Unit unit) {
19 this.value = value;
20 this.unit = unit;
21 }
22
23 public Throughput(Long periodMs, Long count, Unit unit) {
24 if (unit.equals(Unit.s))
25 value = ((double) count * 1000d) / periodMs;
26 else if (unit.equals(Unit.m))
27 value = ((double) count * 60d * 1000d) / periodMs;
28 else if (unit.equals(Unit.h))
29 value = ((double) count * 60d * 60d * 1000d) / periodMs;
30 else if (unit.equals(Unit.d))
31 value = ((double) count * 24d * 60d * 60d * 1000d) / periodMs;
32 else
33 throw new IllegalArgumentException("Unsupported unit " + unit);
34 this.unit = unit;
35 }
36
37 public Throughput(Double value, String unitStr) {
38 this(value, Unit.valueOf(unitStr));
39 }
40
41 public Throughput(String def) {
42 int index = def.indexOf('/');
43 if (def.length() < 3 || index <= 0 || index != def.length() - 2)
44 throw new IllegalArgumentException(
45 def + " no a proper throughput definition" + " (should be <value>/<unit>, e.g. 3.54/s or 1500/h");
46 String valueStr = def.substring(0, index);
47 String unitStr = def.substring(index + 1);
48 try {
49 this.value = usNumberFormat.parse(valueStr).doubleValue();
50 } catch (ParseException e) {
51 throw new IllegalArgumentException("Cannot parse " + valueStr + " as a number.", e);
52 }
53 this.unit = Unit.valueOf(unitStr);
54 }
55
56 public Long asMsPeriod() {
57 if (unit.equals(Unit.s))
58 return Math.round(1000d / value);
59 else if (unit.equals(Unit.m))
60 return Math.round((60d * 1000d) / value);
61 else if (unit.equals(Unit.h))
62 return Math.round((60d * 60d * 1000d) / value);
63 else if (unit.equals(Unit.d))
64 return Math.round((24d * 60d * 60d * 1000d) / value);
65 else
66 throw new IllegalArgumentException("Unsupported unit " + unit);
67 }
68
69 @Override
70 public String toString() {
71 return usNumberFormat.format(value) + '/' + unit;
72 }
73
74 public Double getValue() {
75 return value;
76 }
77
78 public Unit getUnit() {
79 return unit;
80 }
81
82 }