Skip to content

Commit 22bf190

Browse files
committed
refactor: Use java.time API for thread-safe cookie expiration handling
- Replaced the usage of `SimpleDateFormat` with `DateTimeFormatter` to ensure thread-safe date formatting.
1 parent df1b787 commit 22bf190

File tree

1 file changed

+7
-15
lines changed
  • aws-serverless-java-container-core/src/main/java/com/amazonaws/serverless/proxy/internal/servlet

1 file changed

+7
-15
lines changed

aws-serverless-java-container-core/src/main/java/com/amazonaws/serverless/proxy/internal/servlet/AwsCookieProcessor.java

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44
import jakarta.servlet.http.Cookie;
55
import org.slf4j.Logger;
66
import org.slf4j.LoggerFactory;
7-
8-
import java.text.DateFormat;
9-
import java.text.FieldPosition;
10-
import java.text.SimpleDateFormat;
7+
import java.time.Instant;
8+
import java.time.ZoneId;
9+
import java.time.format.DateTimeFormatter;
1110
import java.util.*;
1211

1312
/**
@@ -32,16 +31,9 @@ public class AwsCookieProcessor implements CookieProcessor {
3231
// BitSet to validate domain characters
3332
static final BitSet domainValid = createDomainValidSet();
3433

35-
static final String COOKIE_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
36-
37-
// ThreadLocal to ensure thread-safe creation of DateFormat instances for each thread
38-
static final ThreadLocal<DateFormat> COOKIE_DATE_FORMAT = ThreadLocal.withInitial(() -> {
39-
DateFormat df = new SimpleDateFormat(COOKIE_DATE_PATTERN, Locale.US);
40-
df.setTimeZone(TimeZone.getTimeZone("GMT"));
41-
return df;
42-
});
34+
static final DateTimeFormatter COOKIE_DATE_FORMATTER = DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneId.of("GMT"));
4335

44-
static final String ANCIENT_DATE = COOKIE_DATE_FORMAT.get().format(new Date(10000));
36+
static final String ANCIENT_DATE = COOKIE_DATE_FORMATTER.format(Instant.ofEpochMilli(10000));
4537

4638
static BitSet createTokenValidSet() {
4739
BitSet tokenSet = new BitSet(128);
@@ -127,8 +119,8 @@ public String generateHeader(Cookie cookie) {
127119
if (maxAge == 0) {
128120
header.append(ANCIENT_DATE);
129121
} else {
130-
COOKIE_DATE_FORMAT.get().format(
131-
new Date(System.currentTimeMillis() + maxAge * 1000L), header, new FieldPosition(0));
122+
Instant expiresAt = Instant.now().plusSeconds(maxAge);
123+
header.append(COOKIE_DATE_FORMATTER.format(expiresAt));
132124
header.append("; Max-Age=").append(maxAge);
133125
}
134126
}

0 commit comments

Comments
 (0)