1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.logging.log4j.core.appender.rolling;
19
20 import java.text.NumberFormat;
21 import java.text.ParseException;
22 import java.util.Locale;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25
26 import org.apache.logging.log4j.Logger;
27 import org.apache.logging.log4j.status.StatusLogger;
28
29
30
31
32 public final class FileSize {
33 private static final Logger LOGGER = StatusLogger.getLogger();
34
35 private static final long KB = 1024;
36 private static final long MB = KB * KB;
37 private static final long GB = KB * MB;
38
39
40
41
42 private static final Pattern VALUE_PATTERN =
43 Pattern.compile("([0-9]+([\\.,][0-9]+)?)\\s*(|K|M|G)B?", Pattern.CASE_INSENSITIVE);
44
45 private FileSize() {
46 }
47
48
49
50
51
52
53
54
55
56 public static long parse(final String string, final long defaultValue) {
57 final Matcher matcher = VALUE_PATTERN.matcher(string);
58
59
60 if (matcher.matches()) {
61 try {
62
63 final long value = NumberFormat.getNumberInstance(Locale.getDefault()).parse(
64 matcher.group(1)).longValue();
65
66
67 final String units = matcher.group(3);
68
69 if (units.isEmpty()) {
70 return value;
71 } else if (units.equalsIgnoreCase("K")) {
72 return value * KB;
73 } else if (units.equalsIgnoreCase("M")) {
74 return value * MB;
75 } else if (units.equalsIgnoreCase("G")) {
76 return value * GB;
77 } else {
78 LOGGER.error("FileSize units not recognized: " + string);
79 return defaultValue;
80 }
81 } catch (final ParseException e) {
82 LOGGER.error("FileSize unable to parse numeric part: " + string, e);
83 return defaultValue;
84 }
85 }
86 LOGGER.error("FileSize unable to parse bytes: " + string);
87 return defaultValue;
88 }
89
90 }