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