1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.protocol;
29
30 import java.time.Instant;
31 import java.time.ZoneId;
32 import java.time.format.DateTimeFormatter;
33 import java.time.format.DateTimeFormatterBuilder;
34 import java.util.TimeZone;
35 import java.util.concurrent.locks.ReentrantLock;
36
37 import org.apache.hc.core5.annotation.Contract;
38 import org.apache.hc.core5.annotation.ThreadingBehavior;
39
40
41
42
43
44
45 @Contract(threading = ThreadingBehavior.SAFE)
46 public class HttpDateGenerator {
47
48 private static final int GRANULARITY_MILLIS = 1000;
49
50
51
52
53 @Deprecated
54 public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
55 public static final String INTERNET_MESSAGE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
56
57
58
59
60
61 @Deprecated
62 public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
63
64 public static final ZoneId GMT_ID = ZoneId.of("GMT");
65
66
67 public static final HttpDateGenerator INSTANCE = new HttpDateGenerator(INTERNET_MESSAGE_FORMAT, GMT_ID);
68
69 private final DateTimeFormatter dateTimeFormatter;
70 private long dateAsMillis;
71 private String dateAsText;
72 private ZoneId zoneId;
73
74 private final ReentrantLock lock;
75
76 private HttpDateGenerator(final String pattern, final ZoneId zoneId) {
77 dateTimeFormatter = new DateTimeFormatterBuilder()
78 .parseLenient()
79 .parseCaseInsensitive()
80 .appendPattern(pattern)
81 .toFormatter();
82 this.zoneId = zoneId;
83 this.lock = new ReentrantLock();
84 }
85
86 public String getCurrentDate() {
87 lock.lock();
88 try {
89 final long now = System.currentTimeMillis();
90 if (now - this.dateAsMillis > GRANULARITY_MILLIS) {
91
92 dateAsText = dateTimeFormatter.format(Instant.now().atZone(zoneId));
93 dateAsMillis = now;
94 }
95 return dateAsText;
96 } finally {
97 lock.unlock();
98 }
99 }
100
101 }