Skip to content

Commit 8f85138

Browse files
Timestamps.parse: Add error handling for invalid hours/minutes in the timezone offset.
Before this CL, bad offsets result in a NumberFormatException (from parseLong) instead of the documented ParseException/IllegalArgumentException. PiperOrigin-RevId: 572266056
1 parent f74de36 commit 8f85138

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

java/util/src/main/java/com/google/protobuf/util/Timestamps.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,13 @@ private static long parseTimezoneOffset(String value) throws ParseException {
510510
}
511511
String hours = value.substring(0, pos);
512512
String minutes = value.substring(pos + 1);
513-
return (Long.parseLong(hours) * 60 + Long.parseLong(minutes)) * 60;
513+
try {
514+
return (Long.parseLong(hours) * 60 + Long.parseLong(minutes)) * 60;
515+
} catch (NumberFormatException e) {
516+
ParseException ex = new ParseException("Invalid offset value: " + value, 0);
517+
ex.initCause(e);
518+
throw ex;
519+
}
514520
}
515521

516522
static int parseNanos(String value) throws ParseException {

java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
/** Unit tests for {@link Timestamps}. */
3030
@RunWith(JUnit4.class)
31+
@SuppressWarnings("JavaUtilDate")
3132
public class TimestampsTest {
3233
private static final int MILLIS_PER_SECOND = 1000;
3334
private static final long MILLIS = 1409130915111L;
@@ -169,6 +170,7 @@ public ParseTimestampThread(String[] strings, Timestamp[] values) {
169170
}
170171

171172
@Override
173+
@SuppressWarnings("ProtoTimestampGetSecondsGetNano")
172174
public void run() {
173175
int index = 0;
174176
while (!stopParsingThreads) {
@@ -350,6 +352,22 @@ public void testTimestampInvalidOffset() {
350352
}
351353
}
352354

355+
@Test
356+
public void testTimestampInvalidOffsetWithDot() {
357+
try {
358+
Timestamps.parse("2021-08-19T10:24:25-07.:00");
359+
assertWithMessage("ParseException is expected.").fail();
360+
} catch (ParseException expected) {
361+
assertThat(expected).hasMessageThat().isNotNull();
362+
}
363+
try {
364+
Timestamps.parseUnchecked("2021-08-19T10:24:25-07.:00");
365+
assertWithMessage("IllegalArgumentException is expected.").fail();
366+
} catch (IllegalArgumentException expected) {
367+
assertThat(expected).hasMessageThat().isNotNull();
368+
}
369+
}
370+
353371
@Test
354372
public void testTimestampInvalidTrailingText() {
355373
try {

0 commit comments

Comments
 (0)