1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.james.util;
22
23 import java.util.HashMap;
24
25 import org.apache.oro.text.regex.MalformedPatternException;
26 import org.apache.oro.text.regex.MatchResult;
27 import org.apache.oro.text.regex.Pattern;
28 import org.apache.oro.text.regex.Perl5Compiler;
29 import org.apache.oro.text.regex.Perl5Matcher;
30
31 public class TimeConverter {
32
33 private static HashMap multipliers = new HashMap(10);
34
35 private static final String PATTERN_STRING = "\\s*([0-9]+)\\s*([a-z,A-Z]+)\\s*";
36
37 private static Pattern PATTERN = null;
38
39 static {
40
41 multipliers.put("msec", new Integer(1));
42 multipliers.put("msecs", new Integer(1));
43 multipliers.put("sec", new Integer(1000));
44 multipliers.put("secs", new Integer(1000));
45 multipliers.put("minute", new Integer(1000 * 60));
46 multipliers.put("minutes", new Integer(1000 * 60));
47 multipliers.put("hour", new Integer(1000 * 60 * 60));
48 multipliers.put("hours", new Integer(1000 * 60 * 60));
49 multipliers.put("day", new Integer(1000 * 60 * 60 * 24));
50 multipliers.put("days", new Integer(1000 * 60 * 60 * 24));
51
52 try {
53 Perl5Compiler compiler = new Perl5Compiler();
54 PATTERN = compiler.compile(PATTERN_STRING,
55 Perl5Compiler.READ_ONLY_MASK);
56 } catch (MalformedPatternException mpe) {
57
58 }
59
60 }
61
62
63 private TimeConverter() {
64 }
65
66
67
68
69
70
71
72
73
74
75
76
77 public static long getMilliSeconds(long amount, String unit)
78 throws NumberFormatException {
79 Object multiplierObject = multipliers.get(unit);
80 if (multiplierObject == null) {
81 throw new NumberFormatException("Unknown unit: " + unit);
82 }
83 int multiplier = ((Integer) multiplierObject).intValue();
84 return (amount * multiplier);
85 }
86
87
88
89
90
91
92
93
94
95
96
97 public static long getMilliSeconds(String rawString)
98 throws NumberFormatException {
99 Perl5Matcher matcher = new Perl5Matcher();
100
101 try {
102 Perl5Compiler compiler = new Perl5Compiler();
103 PATTERN = compiler.compile(PATTERN_STRING,
104 Perl5Compiler.READ_ONLY_MASK);
105 } catch (MalformedPatternException mpe) {
106
107 }
108
109 if (matcher.matches(rawString, PATTERN)) {
110 MatchResult res = matcher.getMatch();
111
112 if (res.group(1) != null && res.group(2) != null) {
113 long time = Integer.parseInt(res.group(1).trim());
114 String unit = res.group(2);
115 return getMilliSeconds(time, unit);
116 } else {
117
118
119 throw new NumberFormatException(
120 "The supplied String is not a supported format "
121 + rawString);
122 }
123 } else {
124
125 throw new NumberFormatException(
126 "The supplied String is not a supported format "
127 + rawString);
128 }
129 }
130
131 }