]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/Throughput.java
Improve minimal web app.
[lgpl/argeo-commons.git] / org.argeo.util / src / 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 public class Throughput {
8 private final static NumberFormat usNumberFormat = NumberFormat
9 .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 UtilsException("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 UtilsException(def + " no a proper throughput definition"
45 + " (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 UtilsException("Cannot parse " + valueStr
52 + " as a number.", e);
53 }
54 this.unit = Unit.valueOf(unitStr);
55 }
56
57 public Long asMsPeriod() {
58 if (unit.equals(Unit.s))
59 return Math.round(1000d / value);
60 else if (unit.equals(Unit.m))
61 return Math.round((60d * 1000d) / value);
62 else if (unit.equals(Unit.h))
63 return Math.round((60d * 60d * 1000d) / value);
64 else if (unit.equals(Unit.d))
65 return Math.round((24d * 60d * 60d * 1000d) / value);
66 else
67 throw new UtilsException("Unsupported unit " + unit);
68 }
69
70 @Override
71 public String toString() {
72 return usNumberFormat.format(value) + '/' + unit;
73 }
74
75 public Double getValue() {
76 return value;
77 }
78
79 public Unit getUnit() {
80 return unit;
81 }
82
83 }