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
pull/14331/head
Protobuf Team Bot 1 year ago committed by Copybara-Service
parent f74de36fb5
commit 8f8513835c
  1. 8
      java/util/src/main/java/com/google/protobuf/util/Timestamps.java
  2. 18
      java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java

@ -510,7 +510,13 @@ public final class Timestamps {
}
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 {

@ -28,6 +28,7 @@ import org.junit.runners.JUnit4;
/** 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;
@ -169,6 +170,7 @@ public class TimestampsTest {
}
@Override
@SuppressWarnings("ProtoTimestampGetSecondsGetNano")
public void run() {
int index = 0;
while (!stopParsingThreads) {
@ -350,6 +352,22 @@ public class TimestampsTest {
}
}
@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 {

Loading…
Cancel
Save