From 8f8513835c0c4ebe206a5ead04a1bd0c8c7d1dbf Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Tue, 10 Oct 2023 08:59:22 -0700 Subject: [PATCH] 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 --- .../com/google/protobuf/util/Timestamps.java | 8 +++++++- .../google/protobuf/util/TimestampsTest.java | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java index 3e6cdb8115..99daeb3260 100644 --- a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java +++ b/java/util/src/main/java/com/google/protobuf/util/Timestamps.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 { diff --git a/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java b/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java index e8b8625d03..e3b0dde55b 100644 --- a/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java +++ b/java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java @@ -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 {