1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package org.eluder.coveralls.maven.plugin.util;
25
26 import org.apache.commons.lang3.StringUtils;
27 import org.eluder.coveralls.maven.plugin.ProcessingException;
28
29 import java.text.DateFormat;
30 import java.text.ParseException;
31 import java.text.SimpleDateFormat;
32 import java.util.Date;
33
34 public class TimestampParser {
35
36 public static final String EPOCH_MILLIS = "EpochMillis";
37
38 public static final String DEFAULT_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
39
40 private final Parser parser;
41
42 public TimestampParser(final String format) {
43 try {
44 if (EPOCH_MILLIS.equalsIgnoreCase(format)) {
45 this.parser = new EpochMillisParser();
46 } else if (StringUtils.isNotBlank(format)) {
47 this.parser = new DateFormatParser(format);
48 } else {
49 this.parser = new DateFormatParser(DEFAULT_FORMAT);
50 }
51 } catch (IllegalArgumentException ex) {
52 throw new IllegalArgumentException("Invalid timestamp format \"" + format + "\"", ex);
53 }
54 }
55
56 public Date parse(final String timestamp) throws ProcessingException {
57 if (StringUtils.isBlank(timestamp)) {
58 return null;
59 }
60 try {
61 return parser.parse(timestamp);
62 } catch (Exception ex) {
63 throw new ProcessingException("Unable to parse timestamp \"" + timestamp + "\"", ex);
64 }
65 }
66
67 private interface Parser {
68 Date parse(String timestamp) throws Exception;
69 }
70
71 private static class DateFormatParser implements Parser {
72
73 final DateFormat format;
74
75 DateFormatParser(final String format) {
76 this.format = new SimpleDateFormat(format);
77 }
78
79 @Override
80 public synchronized Date parse(final String timestamp) throws ParseException {
81 return format.parse(timestamp);
82 }
83 }
84
85 private static class EpochMillisParser implements Parser {
86
87 @Override
88 public Date parse(final String timestamp) {
89 return new Date(Long.valueOf(timestamp));
90 }
91 }
92 }