Skip to content

Commit

Permalink
Timestamps.parse: Add error handling for invalid hours/minutes in the…
Browse files Browse the repository at this point in the history
… timezone offset.

Before this CL, bad offsets result in a NumberFormatException (from parseLong) instead of the documented ParseException/IllegalArgumentException.

PiperOrigin-RevId: 572266056
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Oct 10, 2023
1 parent f74de36 commit 8f85138
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,13 @@ private static long parseTimezoneOffset(String value) throws ParseException {
}
String hours = value.substring(0, pos);
String minutes = value.substring(pos + 1);
return (Long.parseLong(hours) * 60 + Long.parseLong(minutes)) * 60;
try {
return (Long.parseLong(hours) * 60 + Long.parseLong(minutes)) * 60;
} catch (NumberFormatException e) {
ParseException ex = new ParseException("Invalid offset value: " + value, 0);
ex.initCause(e);
throw ex;
}
}

static int parseNanos(String value) throws ParseException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

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

@Override
@SuppressWarnings("ProtoTimestampGetSecondsGetNano")
public void run() {
int index = 0;
while (!stopParsingThreads) {
Expand Down Expand Up @@ -350,6 +352,22 @@ public void testTimestampInvalidOffset() {
}
}

@Test
public void testTimestampInvalidOffsetWithDot() {
try {
Timestamps.parse("2021-08-19T10:24:25-07.:00");
assertWithMessage("ParseException is expected.").fail();
} catch (ParseException expected) {
assertThat(expected).hasMessageThat().isNotNull();
}
try {
Timestamps.parseUnchecked("2021-08-19T10:24:25-07.:00");
assertWithMessage("IllegalArgumentException is expected.").fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isNotNull();
}
}

@Test
public void testTimestampInvalidTrailingText() {
try {
Expand Down

0 comments on commit 8f85138

Please sign in to comment.