1
0
mirror of https://github.com/google/nomulus synced 2026-06-09 16:33:02 +00:00

Complete Joda-Time to java.time migration (#3039)

This completes the exhaustive refactoring of foundational temporal types from Joda-Time to the native java.time API across the entire codebase.

- Replaced org.joda.time.DateTime, Instant, LocalDate, and Duration with java.time equivalents.
- Audited and updated Clock implementations (FakeClock, SystemClock). Added nowMillis(), nowDate(), and nowDateTime() to eliminate repetitive conversions and maintain parallel naming.
- Replaced ZonedDateTime with OffsetDateTime globally per go/avoid-zdt. OffsetDateTime is a better fit as we use a hardcoded ZoneOffset.UTC throughout the system, making geographical time zone rules (like daylight saving time) irrelevant and preventing serialization ambiguities. Added a presubmit check.
- Completely removed all transitional bridge methods from DateTimeUtils and deleted obsolete converters (e.g., DateTimeConverter).
- Updated testing infrastructure, Apache Beam pipelines, custom JCommander parameters, and networking modules to solely rely on java.time primitives.
- Retained the lone necessary org.joda.time.Instant usage in SafeBrowsingTransforms required by the Apache Beam API.
- Cleared Gradle lockfiles and removed the joda-time dependency entirely from the build configuration.
This commit is contained in:
Ben McIlwain
2026-05-13 12:07:19 -04:00
committed by GitHub
parent b33c2f4874
commit 56fe588b56
218 changed files with 589 additions and 1390 deletions
+13 -39
View File
@@ -13,21 +13,14 @@ This document outlines foundational mandates, architectural patterns, and projec
- **Verification**: Before finalizing any change, scan the imports section for redundancy.
- **License Headers**: When creating new files, ensure the license header uses the current year (e.g., 2026). Existing files should retain their original year.
## 2. Time and Precision Handling (java.time Migration)
## 2. Time and Precision Handling
- **Idiomatic java.time Usage:** Avoid redundant conversions between `Instant` and `DateTime`. If a field or parameter is an `Instant`, use it directly. Do not convert to `DateTime` just to call a deprecated method if an `Instant` alternative exists or can be easily created. Furthermore, you should not call `toInstant()` or `toDateTime()` conversion methods when not strictly necessary; always prefer to use an alternative method that returns the correct type if one exists (e.g. use `tm().getTxTime()` which returns an `Instant` instead of calling `tm().getTransactionTime().toInstant()`).
- **CRITICAL MISTAKES TO AVOID:**
- NEVER use `toInstant(clock.nowUtc())` or `toInstant(fakeClock.nowUtc())`. Both `Clock` and `FakeClock` have a `now()` method that natively returns a `java.time.Instant`. You MUST use `clock.now()` or `fakeClock.now()` directly.
- NEVER double-wrap conversions like `toInstant(toDateTime(...))` or `toDateTime(toInstant(...))`.
- NEVER mark method parameters or local variables as `final` unnecessarily, as it clutters the codebase. For class fields and constants, use `final` where applicable (i.e. when the field is assigned once and never mutated) to enforce and communicate immutability.
- When using test helpers like `assertThatCommand().atTime(...)` or `ForeignKeyUtils.loadResource(...)`, ALWAYS use the `Instant` overloads. DO NOT wrap `Instant` instances in `toDateTime(...)` just to pass them to deprecated overloads.
- **UTC Timezones:** Do not use `ZoneId.of("UTC")`. Use a statically imported `UTC` from `ZoneOffset` instead (`import static java.time.ZoneOffset.UTC;`).
- **Millisecond Precision:** Always truncate `Instant.now()` to milliseconds (using `.truncatedTo(ChronoUnit.MILLIS)`) to maintain consistency with Joda `DateTime` and the PostgreSQL schema (which enforces millisecond precision via JPA converters).
- **Clock Injection:**
- Avoid direct calls to `Instant.now()`, `DateTime.now()`, `ZonedDateTime.now()`, or `System.currentTimeMillis()`.
- Avoid direct calls to `Instant.now()`, `OffsetDateTime.now()`, or `System.currentTimeMillis()`.
- Inject `google.registry.util.Clock` (production) or `google.registry.testing.FakeClock` (tests).
- Use `clock.nowDate()` to get a `ZonedDateTime` in UTC.
- When defining timestamps for tests, prefer using a fixed, static constant (e.g., `Instant.parse("2024-03-27T10:15:30.105Z")`) over capturing `clock.now()` to prevent flaky tests caused by the passage of real time. Avoid using the Unix epoch (`START_INSTANT`) unless specifically testing epoch-related logic; instead, use realistic dates and vary them across different test suites to ensure logic isn't dependent on a specific "standard" date.
- Use `clock.nowDate()` to get a `LocalDate` in UTC, or `clock.nowDateTime()` to get an `OffsetDateTime` in UTC.
- When defining timestamps for tests, prefer using a fixed, static constant (e.g., `Instant.parse("2024-03-27T10:15:30.105Z")`) over capturing `clock.now()` to prevent flaky tests caused by the passage of real time.
- **Beam Pipelines:**
- Ensure `Clock` is serializable (it is by default in this project) when used in Beam `DoFn`s.
- Pass the `Clock` through the constructor or via Dagger provider methods in the pipeline module.
@@ -42,7 +35,6 @@ This document outlines foundational mandates, architectural patterns, and projec
- **Test Components:** Use `TestRegistryToolComponent` for command-line tool tests to bridge the gap between `main` and `nonprod/test` source sets.
### 4. Database Consistency
- **JPA Converters:** Be aware that JPA converters (like `DateTimeConverter`) may perform truncation or transformation. Ensure application-level logic matches these transformations to avoid "dirty" state or unexpected diffs.
- **Transaction Management:**
- **Top-Level:** Define database transactions (`tm().transact(...)`) at the highest possible level in the call chain (e.g., in an Action, a Command, or a Flow). This ensures all operations are atomic and handled by the retry logic.
- **DAO Methods:** Avoid declaring transactions inside low-level DAO methods. Use `tm().assertInTransaction()` to ensure that these methods are only called within a valid transactional context.
@@ -96,9 +88,8 @@ This document captures high-level architectural patterns, lessons learned from l
- **Transaction Management:** The codebase uses a custom wrapper around JPA. Always use `tm()` (from `TransactionManagerFactory`) to interact with the database.
- **Dependency Injection:** Dagger 2 is used extensively. If you see "cannot find symbol" errors for classes starting with `Dagger...`, the project is in a state where annotation processing failed. Fix compilation in core models first to restore generated code.
- **Value Types:** AutoValue and "ImmutableObject" patterns are dominant. Most models follow a `Buildable` pattern with a nested `Builder`.
- **Temporal Logic:** The project is migrating from Joda-Time to `java.time`.
- **Temporal Logic:** The project uses `java.time` for all temporal representations.
- Core boundaries: `DateTimeUtils.START_INSTANT` (Unix Epoch) and `DateTimeUtils.END_INSTANT` (Long.MAX_VALUE / 1000).
- Year Arithmetic: Use `DateTimeUtils.plusYears()` and `DateTimeUtils.minusYears()` to handle February 29th logic correctly.
## Source Control
- **Committing:** Always create a new commit on the branch if one hasn't been created yet for the branch's specific work. Only perform amending (`git commit --amend --no-edit`) for subsequent changes once the initial commit has been successfully created.
@@ -116,14 +107,11 @@ This document captures high-level architectural patterns, lessons learned from l
## Self-Review Guidelines
Before finalizing any PR or declaring a task complete, you MUST perform a thorough, rigorous self-review of your entire diff. Run `git diff HEAD^` (or review the staged changes) and actively verify the following against every modified line:
1. **Imports & FQNs:** Did I leave any fully-qualified class names or static variables inline? Did I add the necessary imports for them? *Crucial Exception:* If the file already imports a class with the identical name (e.g., it uses both `java.time.Duration` and `org.joda.time.Duration`), one MUST remain fully qualified to avoid a compilation conflict.
2. **Redundant Conversions:** Did I use `toDateTime(clock.now())` where `clock.nowUtc()` would suffice? Did I use `toDateTime(END_INSTANT)` instead of `END_OF_TIME`? Did I use `.toInstant()` or `.toDateTime()` on something that could be avoided by using a different method overload (e.g., `tm().getTxTime()`)?
3. **Verbose Math:** Did I write any verbose time conversions inline? Are there `DateTimeUtils` methods I should be using instead? If not, should I abstract this math into `DateTimeUtils`?
4. **Assertion Cleanliness:** Am I polluting test assertions with `toDateTime(...)` wraps? If so, I need to add overloaded assertions to the Truth Subjects instead.
5. **Diff Scope:** Are there any formatting-only changes in files that I did not functionally modify? If so, revert them. Does the total line count of the diff align with the approved scope (e.g., ~1,000 lines for migrations)?
6. **Commit Message:** Does the commit message title fit within 50 characters? Does the body encapsulate the entirety of the changes across the diff cleanly and professionally?
7. **Missing Tests & Coverage:** *Perform a structured check for any new methods or modified behavior.* Did I add a new utility method (like `plusMonths(Instant, int)`) or change core logic? If so, I MUST open the corresponding test file and write tests to cover the new functionality (including edge cases, negative values, and leap years) before considering the task complete. A code review is not thorough if it only checks for compilation. I must actively ensure every new branch of logic has a test.
8. **Package Lock:** Did I include `console-webapp/package-lock.json` in my diff? If so, I MUST revert it (`git checkout console-webapp/package-lock.json`) unless I explicitly intended to modify NPM dependencies. This file is often modified by the build process and should not be committed accidentally.
1. **Imports & FQNs:** Did I leave any fully-qualified class names or static variables inline? Did I add the necessary imports for them? *Crucial Exception:* If the file already imports a class with the identical name (e.g., it uses both `java.util.Date` and `java.sql.Date`), one MUST remain fully qualified to avoid a compilation conflict.
2. **Diff Scope:** Are there any formatting-only changes in files that I did not functionally modify? If so, revert them. Does the total line count of the diff align with the approved scope (e.g., ~1,000 lines for migrations)?
3. **Commit Message:** Does the commit message title fit within 50 characters? Does the body encapsulate the entirety of the changes across the diff cleanly and professionally?
4. **Missing Tests & Coverage:** *Perform a structured check for any new methods or modified behavior.* Did I add a new utility method (like `plusMonths(Instant, int)`) or change core logic? If so, I MUST open the corresponding test file and write tests to cover the new functionality (including edge cases, negative values, and leap years) before considering the task complete. A code review is not thorough if it only checks for compilation. I must actively ensure every new branch of logic has a test.
5. **Package Lock:** Did I include `console-webapp/package-lock.json` in my diff? If so, I MUST revert it (`git checkout console-webapp/package-lock.json`) unless I explicitly intended to modify NPM dependencies. This file is often modified by the build process and should not be committed accidentally.
Only after actively confirming these checks against your diff are you permitted to finalize the task.
@@ -132,30 +120,16 @@ Only after actively confirming these checks against your diff are you permitted
### 1. Compiler Warnings are Errors (`-Werror`)
This project treats Error Prone warnings as errors.
- **`@InlineMeSuggester`**: When creating deprecated Joda-Time bridge methods (e.g., `getTimestamp() -> return toDateTime(getTimestampInstant())`), you **MUST** immediately add `@SuppressWarnings("InlineMeSuggester")`. If you don't, the build will fail.
- **Repeatable Annotations**: `@SuppressWarnings` is **NOT** repeatable in this environment. If a method or class already has a suppression (e.g., `@SuppressWarnings("unchecked")`), you must merge them:
-`@SuppressWarnings("unchecked") @SuppressWarnings("InlineMeSuggester")`
-`@SuppressWarnings({"unchecked", "InlineMeSuggester"})`
-`@SuppressWarnings("unchecked") @SuppressWarnings("MustBeClosedChecker")`
-`@SuppressWarnings({"unchecked", "MustBeClosedChecker"})`
### 2. Resolving Ambiguity
- **Null Overloads**: Adding an `Instant` overload to a method that previously took `DateTime` will break all `create(null)` calls. You must cast them: `create((Instant) null)`.
- **Type Erasure**: Methods taking `Optional<DateTime>` and `Optional<Instant>` will clash due to erasure. Use distinct names, e.g., `setAutorenewEndTimeInstant(Optional<Instant> time)`.
### 3. Build Strategy
- **Surgical Changes**: In large-scale migrations, focus on "leaf" nodes first (Utilities -> Models -> Flows -> Actions).
- **PR Size**: Minimize PR size by retaining Joda-Time bridge methods for high-level "Action" and "Flow" classes unless a full migration is requested. Reverting changes to DNS and Reporting logic while updating the underlying models is a valid strategy to keep PRs reviewable.
### 2. Build Strategy
- **Validation**: Always run `./gradlew build -x test` before attempting to run unit tests. Unit tests will not run if there are compilation errors in any part of the `core` module. Before finalizing a PR or declaring a task done, you MUST verify your changes. **Prefer scoped builds** (e.g., `./gradlew :core:build`) if you are only modifying backend Java code. Running the global `./gradlew build` triggers the frontend `console-webapp` build, which unnecessarily runs `npmInstallDeps` and modifies `package-lock.json`. If you must run a global build, you must revert `console-webapp/package-lock.json` afterwards. Do not declare success if formatting checks (e.g., `spotlessCheck` or `javaIncrementalFormatCheck`) or tests fail. If formatting fails, run `./gradlew spotlessApply` and then re-run your build command to verify everything passes.
## 🚫 Common Pitfalls to Avoid
- **Mixing Joda and Java Durations:** Methods like `Tld.get().getRenewGracePeriodLength()` return a **Joda** `Duration`, which cannot be passed directly to `Instant.plus(...)` because it doesn't implement `TemporalAmount`. You MUST use `.plusMillis(duration.getMillis())` instead.
- **Serialization Precision (`.000Z`):** When asserting against or generating XML/YAML files, remember that millisecond precision (`.000Z`) is required. Always use `DateTimeUtils.formatInstant(...)` to format `Instant` objects (it preserves the `.000Z` suffix) instead of `Instant.toString()` (which drops it for exact seconds). We have added custom Jackson `InstantKeySerializer`s for this purpose, but you must keep this precision in mind when manually updating `.xml` or `.yaml` test data.
- **Static Imports:** Methods like `toDateTime`, `toInstant`, `plusYears`, `plusMonths`, and `minusDays` from `DateTimeUtils` MUST be statically imported. Do NOT use them fully qualified (e.g., `DateTimeUtils.plusMonths(...)`).
- **Redundant Parses:** Never write `toDateTime(Instant.parse(...))` or `toInstant(DateTime.parse(...))`. If you need a `DateTime`, use `DateTime.parse(...)` directly. If you need an `Instant`, use `Instant.parse(...)` directly.
- **cloneProjectedAtTime vs cloneProjectedAtTime:** When converting tests and logic that use `clock.now()` to project resource state into the future or past, do not wrap the Java `Instant` in `toDateTime()` just to call `cloneProjectedAtTime()`. Instead, switch the method call to use the native `cloneProjectedAtTime()` method which is available on all `EppResource` models.
- **Do not go in circles with the build:** If you see an `InlineMeSuggester` error, apply the suppression to **ALL** similar methods in that file and related files in one turn. Do not fix them one by one. Furthermore, do not run a global `./gradlew build` when a scoped `./gradlew :core:build` or `./gradlew :core:test` is faster and more appropriate. Run global builds only when doing final verification.
- **Exception Conversion in Tests:** When migrating time types (e.g., from Joda `DateTime` to Java `Instant`), be extremely careful with tests that verify parsing failures (e.g., `assertThrows(IllegalArgumentException.class, ...)`). Joda's `DateTime.parse()` throws an `IllegalArgumentException` on failure, but `Instant.parse()` throws a `java.time.format.DateTimeParseException`. You must update the expected exception type in these tests to ensure they actually test the correct behavior, and verify the tests are not failing prematurely on the first line if it contains invalid data meant to be ignored.
- Dagger/AutoValue corruption: If you modify a builder or a component incorrectly, Dagger will fail to generate code, leading to hundreds of "cannot find symbol" errors. If this happens, `git checkout` the last working state of the specific file and re-apply changes more surgically.
- **`replace` tool context**: When using `replace` on large files (like `Tld.java` or `DomainBase.java`), provide significant surrounding context. These files have many similar method signatures (getters/setters) that can lead to incorrect replacements.
-1
View File
@@ -58,7 +58,6 @@ dependencies {
implementation deps['com.google.code.findbugs:jsr305']
implementation deps['com.google.guava:guava']
implementation deps['jakarta.inject:jakarta.inject-api']
implementation deps['joda-time:joda-time']
implementation deps['com.google.flogger:flogger']
implementation deps['io.github.java-diff-utils:java-diff-utils']
implementation deps['com.google.truth:truth']
-1
View File
@@ -37,7 +37,6 @@ io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotatio
io.github.java-diff-utils:java-diff-utils:4.16=compileClasspath,deploy_jar,runtimeClasspath,testCompileClasspath,testRuntimeClasspath,testing,testingCompileClasspath
jakarta.inject:jakarta.inject-api:2.0.1=compileClasspath,deploy_jar,runtimeClasspath,testCompileClasspath,testRuntimeClasspath,testing,testingCompileClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testingAnnotationProcessor
joda-time:joda-time:2.14.2=compileClasspath,deploy_jar,runtimeClasspath,testCompileClasspath,testRuntimeClasspath,testing,testingCompileClasspath
junit:junit:4.13.2=testCompileClasspath,testRuntimeClasspath,testing,testingCompileClasspath
net.sf.saxon:Saxon-HE:12.5=checkstyle
org.antlr:antlr4-runtime:4.13.2=checkstyle
@@ -16,15 +16,16 @@ package google.registry.util;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import javax.annotation.concurrent.ThreadSafe;
/**
* A clock that tells the current time in milliseconds or nanoseconds.
*
* <p>Clocks are technically serializable because they are either a stateless wrapper around the
* system clock, or for testing, are just a wrapper around a DateTime. This means that if you
* system clock, or for testing, are just a wrapper around an Instant. This means that if you
* serialize a clock and deserialize it elsewhere, you won't necessarily get the same time or time
* zone -- what you will get is a functioning clock.
*/
@@ -34,8 +35,18 @@ public interface Clock extends Serializable {
/** Returns current Instant (which is always in UTC). */
Instant now();
/** Returns the current time as a {@link ZonedDateTime} in UTC. */
default ZonedDateTime nowDate() {
return ZonedDateTime.ofInstant(now(), ZoneOffset.UTC);
/** Returns the current time as an {@link OffsetDateTime} in UTC. */
default OffsetDateTime nowDateTime() {
return OffsetDateTime.ofInstant(now(), ZoneOffset.UTC);
}
/** Returns the current time as a {@link LocalDate} in UTC. */
default LocalDate nowDate() {
return LocalDate.ofInstant(now(), ZoneOffset.UTC);
}
/** Returns the current time in milliseconds since the epoch. */
default long nowMillis() {
return now().toEpochMilli();
}
}
@@ -15,7 +15,6 @@
package google.registry.util;
import static com.google.common.base.Preconditions.checkArgument;
import static org.joda.time.DateTimeZone.UTC;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
@@ -24,14 +23,8 @@ import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.SignStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.joda.time.ReadableDuration;
public abstract class DateTimeUtils {
@@ -52,15 +45,15 @@ public abstract class DateTimeUtils {
*
* <p>Example: {@code 2024-03-27T10:15:30.105Z}
*
* <p>Handles large/negative years by using a sign prefix if necessary, compatible with {@link
* Instant#parse}.
* <p>Note: We deliberately strip the leading {@code +} sign from the formatted year field if
* present. While standard ISO 8601 specifies that years with more than 4 digits should be
* prefixed with a {@code +} sign, W3C XML Schema 1.0 (which our EPP RDE XSD uses) strictly
* forbids leading plus signs in {@code xsd:dateTime} strings. Suppressing the plus sign ensures
* our generated XML continues to pass strict XSD validation for large years (e.g. {@code
* 294247-01-10T04:00:54.775Z}).
*/
private static final DateTimeFormatter ISO_8601_FORMATTER =
new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4, 10, SignStyle.NOT_NEGATIVE)
.appendPattern("-MM-dd'T'HH:mm:ss.SSS'Z'")
.toFormatter()
.withZone(ZoneOffset.UTC);
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
/** A formatter that produces lowercase, filename-safe and job-name-safe timestamps. */
public static final DateTimeFormatter LOWERCASE_TIMESTAMP_FORMATTER =
@@ -68,7 +61,8 @@ public abstract class DateTimeUtils {
/** Formats an {@link Instant} to an ISO-8601 string. */
public static String formatInstant(Instant instant) {
return ISO_8601_FORMATTER.format(instant);
String formatted = ISO_8601_FORMATTER.format(instant);
return formatted.startsWith("+") ? formatted.substring(1) : formatted;
}
/**
@@ -79,9 +73,15 @@ public abstract class DateTimeUtils {
* large years (e.g. {@code 294247-01-10T04:00:54.775Z}).
*/
public static Instant parseInstant(String timestamp) {
if (!timestamp.startsWith("+") && !timestamp.startsWith("-")) {
int dashIndex = timestamp.indexOf('-');
if (dashIndex > 4) {
timestamp = "+" + timestamp;
}
}
try {
// Try the standard millisecond precision format first.
return Instant.from(ISO_8601_FORMATTER.parse(timestamp));
return Instant.from(DateTimeFormatter.ISO_INSTANT.parse(timestamp));
} catch (DateTimeParseException e) {
// Fall back to the standard ISO instant parser which handles varied precision.
return Instant.parse(timestamp);
@@ -93,7 +93,7 @@ public abstract class DateTimeUtils {
return earliestOf(Lists.asList(first, rest));
}
/** Returns the earliest element in a {@link Instant} iterable. */
/** Returns the earliest element in an {@link Instant} iterable. */
public static Instant earliestOf(Iterable<Instant> instants) {
checkArgument(!Iterables.isEmpty(instants));
return Ordering.<Instant>natural().min(instants);
@@ -104,24 +104,12 @@ public abstract class DateTimeUtils {
return latestOf(Lists.asList(first, rest));
}
/** Returns the latest element in a {@link Instant} iterable. */
/** Returns the latest element in an {@link Instant} iterable. */
public static Instant latestOf(Iterable<Instant> instants) {
checkArgument(!Iterables.isEmpty(instants));
return Ordering.<Instant>natural().max(instants);
}
/** Converts a Joda-Time Duration to a java.time.Duration. */
@Nullable
public static java.time.Duration toJavaDuration(@Nullable ReadableDuration duration) {
return duration == null ? null : java.time.Duration.ofMillis(duration.getMillis());
}
/** Converts a java.time.Duration to a Joda-Time Duration. */
@Nullable
public static org.joda.time.Duration toJodaDuration(@Nullable java.time.Duration duration) {
return duration == null ? null : org.joda.time.Duration.millis(duration.toMillis());
}
/** Returns whether the first {@link Instant} is equal to or earlier than the second. */
public static boolean isBeforeOrAt(Instant timeToCheck, Instant timeToCompareTo) {
return !timeToCheck.isAfter(timeToCompareTo);
@@ -134,7 +122,7 @@ public abstract class DateTimeUtils {
/**
* Adds years to a date, in the {@code Duration} sense of semantic years. Use this instead of
* {@link java.time.ZonedDateTime#plusYears} to ensure that we never end up on February 29.
* {@link java.time.OffsetDateTime#plusYears} to ensure that we never end up on February 29.
*/
public static Instant plusYears(Instant now, int years) {
checkArgument(years >= 0);
@@ -157,7 +145,7 @@ public abstract class DateTimeUtils {
/**
* Subtracts years from a date, in the {@code Duration} sense of semantic years. Use this instead
* of {@link java.time.ZonedDateTime#minusYears} to ensure that we never end up on February 29.
* of {@link java.time.OffsetDateTime#minusYears} to ensure that we never end up on February 29.
*/
public static Instant minusYears(Instant now, long years) {
checkArgument(years >= 0);
@@ -171,24 +159,6 @@ public abstract class DateTimeUtils {
return instant.atZone(ZoneOffset.UTC).toLocalDate();
}
/** Convert a joda {@link DateTime} to a java.time {@link Instant}, null-safe. */
@Nullable
public static Instant toInstant(@Nullable DateTime dateTime) {
return (dateTime == null) ? null : Instant.ofEpochMilli(dateTime.getMillis());
}
/** Convert a java.time {@link Instant} to a joda {@link DateTime}, null-safe. */
@Nullable
public static DateTime toDateTime(@Nullable Instant instant) {
return (instant == null) ? null : new DateTime(instant.toEpochMilli(), UTC);
}
/** Convert a java.time {@link java.time.Instant} to a joda {@link org.joda.time.Instant}. */
@Nullable
public static org.joda.time.Instant toJodaInstant(@Nullable java.time.Instant instant) {
return (instant == null) ? null : org.joda.time.Instant.ofEpochMilli(instant.toEpochMilli());
}
public static Instant plusHours(Instant instant, long hours) {
return instant.plus(hours, ChronoUnit.HOURS);
}
@@ -31,10 +31,9 @@ public class SystemClock implements Clock {
@Override
public Instant now() {
// Truncate to milliseconds to match the precision of Joda DateTime and our database schema
// (which uses millisecond precision via DateTimeConverter). This prevents subtle comparison
// bugs where a high-precision Instant would be considered "after" a truncated database
// timestamp.
// Truncate to milliseconds to match the precision of our database schema.
// This prevents subtle comparison bugs where a high-precision Instant would be
// considered "after" a truncated database timestamp.
return Instant.now().truncatedTo(MILLIS);
}
}
@@ -21,8 +21,6 @@ import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.concurrent.ThreadSafe;
import org.joda.time.ReadableDuration;
import org.joda.time.ReadableInstant;
/** A mock clock for testing purposes that supports telling, setting, and advancing the time. */
@ThreadSafe
@@ -41,12 +39,6 @@ public final class FakeClock implements Clock {
this(START_INSTANT);
}
/** Creates a FakeClock initialized to a specific time. */
@Deprecated
public FakeClock(ReadableInstant startTime) {
setTo(startTime);
}
/** Creates a FakeClock initialized to a specific time. */
public FakeClock(Instant startTime) {
setTo(startTime);
@@ -66,12 +58,6 @@ public final class FakeClock implements Clock {
* @param autoIncrementStep the new auto increment duration
* @return this
*/
@Deprecated
public FakeClock setAutoIncrementStep(ReadableDuration autoIncrementStep) {
this.autoIncrementStepMs = autoIncrementStep.getMillis();
return this;
}
/**
* Sets the increment applied to the clock whenever it is queried. The increment is zero by
* default: the clock is left unchanged when queried.
@@ -91,23 +77,11 @@ public final class FakeClock implements Clock {
advanceBy(Duration.ofMillis(1));
}
/** Advances clock by some duration. */
@Deprecated
public void advanceBy(ReadableDuration duration) {
currentTimeMillis.addAndGet(duration.getMillis());
}
/** Advances clock by some duration. */
public void advanceBy(Duration duration) {
currentTimeMillis.addAndGet(duration.toMillis());
}
/** Sets the time to the specified instant. */
@Deprecated
public void setTo(ReadableInstant time) {
currentTimeMillis.set(time.getMillis());
}
/** Sets the time to the specified instant. */
public void setTo(Instant time) {
currentTimeMillis.set(time.toEpochMilli());
-1
View File
@@ -409,4 +409,3 @@ if __name__ == '__main__':
sys.exit(main(sys.argv))
except Abort as ex:
sys.exit(1)
+27 -71
View File
@@ -102,6 +102,22 @@ PRESUBMITS = {
{"node_modules/", ".idea"}, REQUIRED):
"Source files must end in a newline.",
# Files must not end with extraneous blank lines
PresubmitCheck(
r".*\n\n$",
("java", "js", "soy", "sql", "py", "sh", "gradle", "ts", "xml"),
{"node_modules/", ".idea", "nomulus.golden.sql"},
):
"Source files must not end with extraneous blank lines.",
# Duplicate empty lines
PresubmitCheck(
r".*\n\n\n.*",
("java", "js", "soy", "sh", "gradle", "ts", "xml"),
{"node_modules/", ".idea"},
):
"Source files must not contain duplicate empty lines.",
# System.(out|err).println should only appear in tools/ or load-testing/
PresubmitCheck(
r".*\bSystem\s*\.\s*(?:out|err)\s*\.\s*print.*", "java", {
@@ -160,7 +176,8 @@ PRESUBMITS = {
"SelfSignedCaCertificate.java",
"X509Utils.java",
"TmchCertificateAuthority.java",
"DelegatedCredentials.java"
"DelegatedCredentials.java",
"SslInitializerTestUtils.java"
},
):
"Do not use java.util.Date. Use classes in java.time package instead.",
@@ -202,85 +219,24 @@ PRESUBMITS = {
{},
):
"Do not use .isEqualTo(Optional.of(...)). Use Truth's .hasValue(...) instead.",
# TODO: Remove the java.time migration presubmit checks below once the entire codebase has been migrated to java.time.
PresubmitCheck(
r".*toDateTime\(\s*toInstant\(.*",
"java",
{"DateTimeUtilsTest.java"},
):
"Do not double-wrap toDateTime(toInstant(...)).",
PresubmitCheck(
r".*toInstant\(\s*toDateTime\(.*",
"java",
{"DateTimeUtilsTest.java"},
):
"Do not double-wrap toInstant(toDateTime(...)).",
PresubmitCheck(
r".*toInstant\([^;]*[cC]lock\.now\(\).*",
r".*java\.time\.ZonedDateTime.*",
"java",
{},
):
"Do not use toInstant(clock.now()). Use clock.now() instead.",
PresubmitCheck(
r".*toDateTime\([^;]*[cC]lock\.now\(\).*",
"java",
{},
):
"Do not use toDateTime(clock.now()). Use clock.now() and Instant overloads instead.",
PresubmitCheck(
r".*toInstant\([^;]*tm\(\)\.getTxTime\(\).*",
"java",
{},
):
"Do not use toInstant(tm().getTxTime()). Use tm().getTxTime() instead.",
PresubmitCheck(
r".*toDateTime\([^;]*tm\(\)\.getTxTime\(\).*",
"java",
{},
):
"Do not use toDateTime(tm().getTxTime()). Use tm().getTxTime() and Instant overloads instead.",
PresubmitCheck(
r".*\(\s*Instant\s*\)\s*(?:this\.)?(?:fakeClock|clock)\.now\(\s*\).*",
"java",
{},
):
"Do not unnecessarily cast clock.now() to Instant.",
PresubmitCheck(
r".*toDateTime\(\s*Instant\.now\(.*",
"java",
{},
):
"Do not wrap Instant.now() in toDateTime. Use DateTime.now(UTC) directly.",
PresubmitCheck(
r".*toInstant\(\s*DateTime\.now\(.*",
"java",
{},
):
"Do not wrap DateTime.now() in toInstant. Use Instant.now().truncatedTo(ChronoUnit.MILLIS) directly.",
PresubmitCheck(
r".*toDateTime\(\s*Instant\.parse\(.*",
"java",
{"DateTimeUtilsTest.java"},
):
"Do not wrap Instant.parse in toDateTime. Use DateTime.parse directly.",
PresubmitCheck(
r".*toInstant\(\s*DateTime\.parse\(.*",
"java",
{"DateTimeUtilsTest.java"},
):
"Do not wrap DateTime.parse in toInstant. Use Instant.parse directly.",
PresubmitCheck(
r".*cloneProjectedAtTime\(\s*toDateTime\(.*",
"java",
{},
):
"Do not use cloneProjectedAtTime(toDateTime(...)). Use cloneProjectedAtTime(...) instead.",
"Do not use java.time.ZonedDateTime. Use java.time.OffsetDateTime per go/avoid-zdt.",
PresubmitCheck(
r".*ZoneId\.of\(\s*\"UTC\"\s*\).*",
"java",
{},
):
"Do not use ZoneId.of(\"UTC\"). Use java.time.ZoneOffset.UTC."
"Do not use ZoneId.of(\"UTC\"). Use java.time.ZoneOffset.UTC.",
PresubmitCheck(
r".*org\.joda\.time.*",
"java",
{"SafeBrowsingTransforms.java"},
):
"Do not use Joda-Time. Use java.time instead.",
}
# Note that this regex only works for one kind of Flyway file. If we want to
-3
View File
@@ -198,7 +198,6 @@ dependencies {
implementation deps['jakarta.persistence:jakarta.persistence-api']
implementation deps['jakarta.servlet:jakarta.servlet-api']
implementation deps['jakarta.xml.bind:jakarta.xml.bind-api']
implementation deps['joda-time:joda-time']
implementation deps['org.antlr:antlr4']
implementation deps['org.antlr:antlr4-runtime']
implementation deps['org.apache.avro:avro']
@@ -479,7 +478,6 @@ Optional<List<String>> getToolArgsList() {
return Optional.empty()
}
// To run the nomulus tools with these command line tokens:
// "--foo", "bar baz", "--qux=quz"
// gradle core:registryTool --args="--foo 'bar baz' --qux=quz"
@@ -819,7 +817,6 @@ test {
// TODO(weiminyu): Remove dependency on sqlIntegrationTest
}.dependsOn(fragileTest, standardTest, registryToolIntegrationTest, sqlIntegrationTest)
// When we override tests, we also break the cleanTest command.
cleanTest.dependsOn(cleanFragileTest, cleanStandardTest,
cleanRegistryToolIntegrationTest, cleanSqlIntegrationTest)
+30 -30
View File
@@ -321,26 +321,26 @@ io.opentelemetry.instrumentation:opentelemetry-instrumentation-api-incubator:2.1
io.opentelemetry.instrumentation:opentelemetry-instrumentation-api:2.1.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry.semconv:opentelemetry-semconv:1.29.0-alpha=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-api:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-api:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-api:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-bom:1.42.1=deploy_jar,nonprodRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-common:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-common:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-context:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-context:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-logging:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-context:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-logging:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-extension-incubator:1.35.0-alpha=deploy_jar,nonprodRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-common:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-sdk-common:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-common:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.47.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-logs:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-sdk-logs:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-logs:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-metrics:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-sdk-metrics:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-metrics:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-trace:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-sdk-trace:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-trace:1.62.0=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk:1.51.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath
io.opentelemetry:opentelemetry-sdk:1.60.1=testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk:1.62.0=testCompileClasspath,testRuntimeClasspath
io.outfoxx:swiftpoet:1.3.1=deploy_jar,nonprodRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
io.perfmark:perfmark-api:0.27.0=deploy_jar,nonprodRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
io.protostuff:protostuff-api:1.8.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -465,8 +465,8 @@ org.eclipse.jetty:jetty-server:12.1.9=testCompileClasspath,testRuntimeClasspath
org.eclipse.jetty:jetty-session:12.1.9=testCompileClasspath,testRuntimeClasspath
org.eclipse.jetty:jetty-util:12.1.9=testCompileClasspath,testRuntimeClasspath
org.eclipse.jetty:jetty-xml:12.1.9=testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-core:12.6.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:12.6.0=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-core:12.6.1=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:12.6.1=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.glassfish.jaxb:codemodel:4.0.8=jaxb
org.glassfish.jaxb:jaxb-core:4.0.6=deploy_jar,nonprodRuntimeClasspath,runtimeClasspath,testRuntimeClasspath
org.glassfish.jaxb:jaxb-core:4.0.8=jaxb
@@ -553,23 +553,23 @@ org.pcollections:pcollections:4.0.1=annotationProcessor,nonprodAnnotationProcess
org.postgresql:postgresql:42.7.11=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.reflections:reflections:0.10.2=checkstyle
org.rnorth.duct-tape:duct-tape:1.0.8=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-api:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-chrome-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-chromium-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-devtools-v145:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-devtools-v146:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-devtools-v147:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-edge-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-firefox-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-http:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-ie-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-java:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-json:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-manager:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-os:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-remote-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-safari-driver:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-support:4.43.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-api:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-chrome-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-chromium-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-devtools-v146:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-devtools-v147:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-devtools-v148:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-edge-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-firefox-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-http:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-ie-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-java:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-json:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-manager:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-os:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-remote-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-safari-driver:4.44.0=testCompileClasspath,testRuntimeClasspath
org.seleniumhq.selenium:selenium-support:4.44.0=testCompileClasspath,testRuntimeClasspath
org.slf4j:jcl-over-slf4j:1.7.36=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:1.7.30=testRuntimeClasspath
org.slf4j:slf4j-api:2.0.17=compileClasspath,deploy_jar,nonprodCompileClasspath,nonprodRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -92,7 +92,7 @@ public class DeleteProberDataAction implements Runnable {
// prevents accidental double-map with the same key from immediately deleting active domains)
//
// Note: creationTime must be compared to a Java object (CreateAutoTimestamp) but deletionTime can
// be compared directly to the SQL timestamp (it's a DateTime)
// be compared directly to the SQL timestamp (it's an Instant)
private static final String DOMAIN_QUERY_STRING =
"FROM Domain d WHERE d.tld IN :tlds AND d.domainName NOT LIKE 'nic.%%' AND"
+ " (d.subordinateHosts IS NULL OR array_length(d.subordinateHosts) = 0) AND"
@@ -39,8 +39,8 @@ import org.jetbrains.annotations.NotNull;
* A record representing a single billable event, parsed from a {@code SchemaAndRecord}.
*
* @param id The unique ID for the {@code BillingEvent} associated with this event.
* @param billingTime The DateTime (in UTC) this event becomes billable.
* @param eventTime The DateTime (in UTC) this event was generated.
* @param billingTime The Instant (in UTC) this event becomes billable.
* @param eventTime The Instant (in UTC) this event was generated.
* @param registrarId The billed registrar's name.
* @param billingId The billed registrar's billing account key.
* @param poNumber The Purchase Order number.
@@ -225,7 +225,6 @@ public record BillingEvent(
"UnitPriceCurrency",
"PONumber");
/** Generates the CSV header for the overall invoice. */
static String invoiceHeader() {
return Joiner.on(",").join(INVOICE_HEADERS);
@@ -22,12 +22,10 @@ import jakarta.persistence.Query;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaQuery;
import java.io.Serializable;
import java.time.Instant;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
/** Interface for query instances used by {@link RegistryJpaIO.Read}. */
public interface RegistryQuery<T> extends Serializable {
@@ -61,11 +59,7 @@ public interface RegistryQuery<T> extends Serializable {
if (parameters != null) {
parameters.forEach(
(key, value) -> {
if (value instanceof DateTime dt) {
query.setParameter(key, Instant.ofEpochMilli(dt.getMillis()));
} else {
query.setParameter(key, value);
}
query.setParameter(key, value);
});
}
JpaTransactionManager.setQueryFetchSize(query, QUERY_FETCH_SIZE);
@@ -14,7 +14,6 @@
package google.registry.beam.spec11;
import static google.registry.util.DateTimeUtils.toJodaInstant;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.http.HttpStatus.SC_OK;
@@ -132,7 +131,13 @@ public class SafeBrowsingTransforms {
if (!domainNameInfoBuffer.isEmpty()) {
ImmutableSet<KV<DomainNameInfo, ThreatMatch>> results = evaluateAndFlush();
results.forEach(
(kv) -> context.output(kv, toJodaInstant(clock.now()), GlobalWindow.INSTANCE));
kv -> {
// The Apache Beam API requires org.joda.time.Instant here.
@SuppressWarnings("UnnecessarilyFullyQualified")
org.joda.time.Instant timestamp =
org.joda.time.Instant.ofEpochMilli(clock.nowMillis());
context.output(kv, timestamp, GlobalWindow.INSTANCE);
});
}
}
@@ -114,11 +114,7 @@ public final class DownloadScheduler {
}
private boolean isTimeAgain(BsaDownload mostRecent, Duration interval) {
return mostRecent
.getCreationTime()
.plusMillis(interval.toMillis())
.minusMillis(CRON_JITTER.toMillis())
.isBefore(clock.now());
return mostRecent.getCreationTime().plus(interval).minus(CRON_JITTER).isBefore(clock.now());
}
/**
@@ -155,7 +155,7 @@ public class DelegatedCredentials extends GoogleCredentials {
@Override
public AccessToken refreshAccessToken() throws IOException {
JsonFactory jsonFactory = JSON_FACTORY;
long currentTime = clock.now().toEpochMilli();
long currentTime = clock.nowMillis();
String assertion = createAssertion(jsonFactory, currentTime);
GenericData tokenRequest = new GenericData();
@@ -50,6 +50,7 @@ import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.net.URI;
import java.net.URL;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.util.Map.Entry;
@@ -57,7 +58,6 @@ import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.joda.time.DateTimeConstants;
/**
* Central clearing-house for all configuration.
@@ -271,7 +271,7 @@ public final class RegistryConfig {
@Provides
@Config("brdaDayOfWeek")
public static int provideBrdaDayOfWeek() {
return DateTimeConstants.TUESDAY;
return DayOfWeek.TUESDAY.getValue();
}
/**
@@ -1637,7 +1637,6 @@ public final class RegistryConfig {
return CONFIG_SETTINGS.get().registryPolicy.contactAndHostRoidSuffix;
}
/** A discount for all sunrise domain creates, between 0.0 (no discount) and 1.0 (free). */
public static double getSunriseDomainCreateDiscount() {
return CONFIG_SETTINGS.get().registryPolicy.sunriseDomainCreateDiscount;
@@ -71,7 +71,6 @@
<max-backoff>180s</max-backoff>
</queue>
<!-- Queue for tasks that communicate with TMCH MarksDB webserver. -->
<queue>
<name>marksdb</name>
@@ -49,4 +49,3 @@ public class EppTlsAction implements Runnable {
inputXmlBytes);
}
}
@@ -71,6 +71,4 @@ public class StatelessRequestSessionMetadata extends SessionMetadata {
throw new UnsupportedOperationException();
}
}
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -14,7 +14,6 @@
package google.registry.flows.contact;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
@@ -41,7 +41,6 @@ import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBu
*/
public final class KeySerializer {
private KeySerializer() {}
/**
@@ -21,7 +21,6 @@ import dagger.Module;
import dagger.Provides;
import google.registry.request.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import org.joda.time.Minutes;
/**
* Dagger module for loadtest package.
@@ -42,15 +41,13 @@ public final class LoadTestModule {
@Provides
@Parameter("delaySeconds")
static int provideDelaySeconds(HttpServletRequest req) {
return extractOptionalIntParameter(req, "delaySeconds")
.orElse(Minutes.ONE.toStandardSeconds().getSeconds());
return extractOptionalIntParameter(req, "delaySeconds").orElse(60);
}
@Provides
@Parameter("runSeconds")
static int provideRunSeconds(HttpServletRequest req) {
return extractOptionalIntParameter(req, "runSeconds")
.orElse(Minutes.ONE.toStandardSeconds().getSeconds());
return extractOptionalIntParameter(req, "runSeconds").orElse(60);
}
@Provides
@@ -90,9 +90,9 @@ public class Cursor extends UpdateAutoTimestampEntity {
RECURRING_BILLING(false),
/**
* Cursor for {@link google.registry.export.sheet.SyncRegistrarsSheetAction}. The DateTime
* stored is the last time that registrar changes were successfully synced to the sheet. If
* there were no changes since the last time the action run, the cursor is not updated.
* Cursor for {@link google.registry.export.sheet.SyncRegistrarsSheetAction}. The Instant stored
* is the last time that registrar changes were successfully synced to the sheet. If there were
* no changes since the last time the action run, the cursor is not updated.
*/
SYNC_REGISTRAR_SHEET(false),
@@ -33,7 +33,7 @@ import jakarta.persistence.Embeddable;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.OffsetDateTime;
import java.util.List;
/**
@@ -63,7 +63,7 @@ public class TimeOfYear extends ImmutableObject implements UnsafeSerializable {
* February 28. It is impossible to construct a {@link TimeOfYear} for February 29th.
*/
public static TimeOfYear fromInstant(Instant instant) {
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, UTC);
OffsetDateTime zdt = OffsetDateTime.ofInstant(instant, UTC);
int month = zdt.getMonthValue();
int day = zdt.getDayOfMonth();
if (month == 2 && day == 29) {
@@ -88,8 +88,8 @@ public class TimeOfYear extends ImmutableObject implements UnsafeSerializable {
Range<Instant> normalizedRange = range.intersection(Range.closed(START_INSTANT, END_INSTANT));
Range<Integer> yearRange =
Range.closed(
ZonedDateTime.ofInstant(normalizedRange.lowerEndpoint(), UTC).getYear(),
ZonedDateTime.ofInstant(normalizedRange.upperEndpoint(), UTC).getYear());
OffsetDateTime.ofInstant(normalizedRange.lowerEndpoint(), UTC).getYear(),
OffsetDateTime.ofInstant(normalizedRange.upperEndpoint(), UTC).getYear());
return ContiguousSet.create(yearRange, integers()).stream()
.map(this::toInstantWithYear)
.filter(normalizedRange)
@@ -112,13 +112,13 @@ public class TimeOfYear extends ImmutableObject implements UnsafeSerializable {
/** Get the first {@link Instant} with this month/day/millis that is at or after the start. */
public Instant getNextInstanceAtOrAfter(Instant start) {
Instant withSameYear = toInstantWithYear(ZonedDateTime.ofInstant(start, UTC).getYear());
Instant withSameYear = toInstantWithYear(OffsetDateTime.ofInstant(start, UTC).getYear());
return isAtOrAfter(withSameYear, start) ? withSameYear : plusYears(withSameYear, 1);
}
/** Get the first {@link Instant} with this month/day/millis that is at or before the end. */
public Instant getLastInstanceBeforeOrAt(Instant end) {
Instant withSameYear = toInstantWithYear(ZonedDateTime.ofInstant(end, UTC).getYear());
Instant withSameYear = toInstantWithYear(OffsetDateTime.ofInstant(end, UTC).getYear());
return isBeforeOrAt(withSameYear, end) ? withSameYear : minusYears(withSameYear, 1);
}
@@ -17,9 +17,7 @@
xmlns = @XmlNs(prefix = "contact", namespaceURI = "urn:ietf:params:xml:ns:contact-1.0"),
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(UtcInstantAdapter.class)
})
@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(UtcInstantAdapter.class)})
package google.registry.model.contact;
import google.registry.xml.UtcInstantAdapter;
@@ -14,7 +14,6 @@
package google.registry.model.domain;
import google.registry.model.EppResource;
import google.registry.model.EppResource.ForeignKeyedEppResource;
import google.registry.model.annotations.ExternalMessagingName;
@@ -246,7 +246,7 @@ public class DomainBase extends EppResource {
*
* <p>When a domain is scheduled to not autorenew, this field is set to the current value of its
* {@link #registrationExpirationTime}, after which point the next invocation of a periodic
* cronjob will explicitly delete the domain. This field is a DateTime and not a boolean because
* cronjob will explicitly delete the domain. This field is an Instant and not a boolean because
* of edge cases that occur during the autorenew grace period. We need to be able to tell the
* difference domains that have reached their life and must be deleted now, and domains that
* happen to be in the autorenew grace period now but should be deleted in roughly a year.
@@ -14,7 +14,6 @@
package google.registry.model.domain;
import google.registry.model.eppoutput.EppResponse.ResponseData;
import google.registry.xml.UtcInstantAdapter;
import jakarta.xml.bind.annotation.XmlElement;
@@ -14,7 +14,6 @@
package google.registry.model.domain;
import google.registry.model.ImmutableObject;
import google.registry.model.UnsafeSerializable;
import google.registry.model.billing.BillingEvent;
@@ -31,8 +31,8 @@ import jakarta.xml.bind.annotation.XmlValue;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.Period;
import java.util.stream.Stream;
import org.joda.time.Period;
/** Base class for the fee and credit types. */
@XmlTransient
@@ -34,4 +34,3 @@ public abstract class FeeCheckResponseExtensionItem extends FeeQueryResponseExte
}
}
}
@@ -69,4 +69,3 @@ public class FeeInfoCommandExtensionV06
return Optional.empty();
}
}
@@ -36,7 +36,6 @@ public class FeeInfoResponseExtensionV06
/** The command that was checked. */
FeeExtensionCommandDescriptor command;
/** Builder for {@link FeeInfoResponseExtensionV06}. */
public static class Builder
extends FeeQueryResponseExtensionItem.Builder<FeeInfoResponseExtensionV06, Builder> {
@@ -34,7 +34,6 @@ public class FeeCheckResponseExtensionV11
@XmlElement(name = "cd")
ImmutableList<FeeCheckResponseExtensionItemV11> items;
@Override
public void setCurrencyIfSupported(CurrencyUnit currency) {}
@@ -17,9 +17,7 @@
xmlns = @XmlNs(prefix = "launch", namespaceURI = "urn:ietf:params:xml:ns:launch-1.0"),
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(UtcInstantAdapter.class)
})
@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(UtcInstantAdapter.class)})
package google.registry.model.domain.launch;
import google.registry.xml.UtcInstantAdapter;
@@ -335,8 +335,6 @@ public class AllocationToken extends UpdateAutoTimestampEntity implements Builda
return tokenType;
}
@JsonIgnore
public TimedTransitionProperty<TokenStatus> getTokenStatusTransitions() {
return tokenStatusTransitions;
@@ -17,9 +17,7 @@
xmlns = @XmlNs(prefix = "", namespaceURI = "urn:ietf:params:xml:ns:epp-1.0"),
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(UtcInstantAdapter.class)
})
@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(UtcInstantAdapter.class)})
package google.registry.model.eppinput;
import google.registry.xml.UtcInstantAdapter;
@@ -17,9 +17,7 @@
xmlns = @XmlNs(prefix = "", namespaceURI = "urn:ietf:params:xml:ns:epp-1.0"),
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(UtcInstantAdapter.class)
})
@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(UtcInstantAdapter.class)})
package google.registry.model.eppoutput;
import google.registry.xml.UtcInstantAdapter;
@@ -18,7 +18,7 @@ import static java.time.ZoneOffset.UTC;
import com.google.common.base.Splitter;
import google.registry.persistence.VKey;
import java.time.ZonedDateTime;
import java.time.OffsetDateTime;
import java.util.List;
/**
@@ -46,7 +46,7 @@ public final class PollMessageExternalKeyConverter {
public static String makePollMessageExternalId(PollMessage pollMessage) {
return String.format(
"%d-%d",
pollMessage.getId(), ZonedDateTime.ofInstant(pollMessage.getEventTime(), UTC).getYear());
pollMessage.getId(), OffsetDateTime.ofInstant(pollMessage.getEventTime(), UTC).getYear());
}
/**
@@ -17,9 +17,7 @@
xmlns = @XmlNs(prefix = "", namespaceURI = "urn:ietf:params:xml:ns:epp-1.0"),
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(UtcInstantAdapter.class)
})
@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(UtcInstantAdapter.class)})
package google.registry.model.poll;
import google.registry.xml.UtcInstantAdapter;
@@ -14,7 +14,6 @@
package google.registry.model.transfer;
import google.registry.model.Buildable.GenericBuilder;
import google.registry.model.ImmutableObject;
import google.registry.model.UnsafeSerializable;
@@ -14,7 +14,6 @@
package google.registry.model.transfer;
import google.registry.model.EppResource;
import google.registry.model.eppoutput.EppResponse.ResponseData;
import google.registry.xml.UtcInstantAdapter;
@@ -17,9 +17,7 @@
xmlns = @XmlNs(prefix = "", namespaceURI = "urn:ietf:params:xml:ns:epp-1.0"),
elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(UtcInstantAdapter.class)
})
@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(UtcInstantAdapter.class)})
package google.registry.model.transfer;
import google.registry.xml.UtcInstantAdapter;
@@ -81,7 +81,6 @@ public record CheckApiMetric(
}
}
public static Builder builder(Clock clock) {
return new AutoBuilder_CheckApiMetric_Builder().startTimestamp(clock.now()).setClock(clock);
}
@@ -1,43 +0,0 @@
// Copyright 2019 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.persistence.converter;
import static org.joda.time.DateTimeZone.UTC;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
/** JPA converter to for storing/retrieving {@link org.joda.time.DateTime} objects. */
@Converter(autoApply = true)
public class DateTimeConverter implements AttributeConverter<DateTime, ZonedDateTime> {
@Override
@Nullable
public ZonedDateTime convertToDatabaseColumn(@Nullable DateTime attribute) {
return attribute == null
? null
: ZonedDateTime.ofInstant(Instant.ofEpochMilli(attribute.getMillis()), ZoneOffset.UTC);
}
@Override
@Nullable
public DateTime convertToEntityAttribute(@Nullable ZonedDateTime dbData) {
return (dbData == null) ? null : new DateTime(dbData.toInstant().toEpochMilli(), UTC);
}
}
@@ -14,7 +14,6 @@
package google.registry.persistence.converter;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -14,7 +14,6 @@
package google.registry.privileges.secretmanager;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import dagger.Module;
@@ -40,7 +40,6 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
/**
* An Jsonable that can turn itself into a JSON object using reflection.
@@ -53,16 +52,12 @@ import org.joda.time.DateTime;
* will be "JSONified" and added to the generated JSON object.
*
* <p>This implementation is geared towards RDAP replies, and hence has RDAP-specific quirks.
* Specifically:
* - Fields with empty arrays are not shown at all
* - VCards are a built-in special case (Not implemented yet)
* - DateTime conversion is specifically supported as if it were a primitive
* - Arrays are considered to be SETS rather than lists, meaning repeated values are removed and the
* order isn't guaranteed
* Specifically: - Fields with empty arrays are not shown at all - VCards are a built-in special
* case (Not implemented yet) - Instant conversion is specifically supported as if it were a
* primitive - Arrays are considered to be SETS rather than lists, meaning repeated values are
* removed and the order isn't guaranteed
*
* Usage:
* {@link JsonableElement}
* -----------------------
* <p>Usage: {@link JsonableElement} -----------------------
*
* <pre>
* - JsonableElement annotates Members that become JSON object fields:
@@ -90,7 +85,7 @@ import org.joda.time.DateTime;
* "b": "value1"
* }
*
* - the supported object types are String, Boolean, Number, DateTime, Jsonable. In addition,
* - the supported object types are String, Boolean, Number, Instant, Jsonable. In addition,
* Iterable and Optional are respected.
*
* - An Optional that's empty is skipped, while a present Optional acts exactly like the object it
@@ -134,8 +129,7 @@ import org.joda.time.DateTime;
* }
* </pre>
*
* {@link RestrictJsonNames}
* -------------------------
* {@link RestrictJsonNames} -------------------------
*
* <pre>
* - RestrictJsonNames is a way to prevent typos in the JsonableElement names.
@@ -334,12 +328,6 @@ abstract class AbstractJsonableObject implements Jsonable {
if (object instanceof Boolean b) {
return new JsonPrimitive(b);
}
if (object instanceof DateTime) {
// According to RFC 9083 section 3, the syntax of dates and times is defined in RFC3339.
//
// According to RFC3339, we should use ISO8601, which is what DateTime.toString does!
return new JsonPrimitive(object.toString());
}
if (object instanceof Instant instant) {
// According to RFC 9083 section 3, the syntax of dates and times is defined in RFC3339.
//
@@ -244,7 +244,6 @@ final class RdapDataStructures {
@JsonableElement abstract ImmutableList<Link> links();
abstract static class Builder<B extends Builder<?>> {
abstract B setEventAction(EventAction eventAction);
@@ -304,7 +303,6 @@ final class RdapDataStructures {
return new AutoValue_RdapDataStructures_EventWithoutActor.Builder();
}
@AutoValue.Builder
abstract static class Builder extends EventBase.Builder<Builder> {
abstract EventWithoutActor build();
@@ -321,7 +319,6 @@ final class RdapDataStructures {
return new AutoValue_RdapDataStructures_Event.Builder();
}
@AutoValue.Builder
abstract static class Builder extends EventBase.Builder<Builder> {
abstract Builder setEventActor(String eventActor);
@@ -272,7 +272,6 @@ public class RdapMetrics {
RdapMetricInformation build();
}
static Builder builder() {
return new AutoBuilder_RdapMetrics_RdapMetricInformation_Builder()
.setSearchType(SearchType.NONE)
@@ -235,7 +235,6 @@ final class RdapObjectClasses {
this.objectClassName = objectClassName;
}
abstract static class Builder<B extends Builder<?>> {
abstract B setHandle(String handle);
abstract ImmutableList.Builder<PublicId> publicIdsBuilder();
@@ -14,7 +14,6 @@
package google.registry.rdap;
import com.google.common.base.Strings;
import google.registry.request.HttpException.BadRequestException;
import google.registry.request.HttpException.UnprocessableEntityException;
@@ -14,7 +14,6 @@
package google.registry.rde;
import static google.registry.model.common.Cursor.CursorType.BRDA;
import static google.registry.model.common.Cursor.getCursorTimeOrStartOfTime;
import static google.registry.model.rde.RdeMode.THIN;
@@ -14,7 +14,6 @@
package google.registry.rde;
import google.registry.model.common.Cursor.CursorType;
import google.registry.model.rde.RdeMode;
import java.io.IOException;
@@ -14,7 +14,6 @@
package google.registry.rde;
import static com.google.common.base.Verify.verify;
import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;
import static google.registry.model.common.Cursor.getCursorTimeOrStartOfTime;
@@ -14,7 +14,6 @@
package google.registry.rde;
import static com.google.common.base.Verify.verify;
import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;
import static com.jcraft.jsch.ChannelSftp.OVERWRITE;
@@ -16,8 +16,6 @@ package google.registry.rde;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.util.DateTimeUtils.toDateTime;
import static google.registry.util.DateTimeUtils.toInstant;
import com.google.common.io.ByteStreams;
import google.registry.util.ImprovedInputStream;
@@ -53,7 +51,7 @@ final class RydeTar {
new PosixTarHeader.Builder()
.setName(filename)
.setSize(expectedSize)
.setMtime(toDateTime(modified))
.setMtime(modified)
.build()
.getBytes());
return new ImprovedOutputStream("RydeTarWriter", os) {
@@ -96,7 +94,7 @@ final class RydeTar {
/** Returns the creation/modification time of the file archived in this TAR. */
Instant getModified() {
return toInstant(header.getMtime());
return header.getMtime();
}
}
@@ -17,7 +17,6 @@ package google.registry.reporting;
import static google.registry.request.RequestParameters.extractOptionalBooleanParameter;
import static google.registry.request.RequestParameters.extractOptionalParameter;
import static google.registry.request.RequestParameters.extractRequiredParameter;
import static java.time.ZoneOffset.UTC;
import com.google.api.services.dataflow.Dataflow;
import dagger.Module;
@@ -129,7 +128,7 @@ public class ReportingModule {
@Provides
@Parameter(PARAM_DATE)
static LocalDate provideDate(HttpServletRequest req, Clock clock) {
return provideDateOptional(req).orElseGet(() -> LocalDate.ofInstant(clock.now(), UTC));
return provideDateOptional(req).orElseGet(() -> clock.nowDate());
}
/** Constructs a {@link Dataflow} API client with default settings. */
@@ -37,7 +37,6 @@ public final class BillingModule {
static final String PARAM_SHOULD_PUBLISH = "shouldPublish";
static final String CRON_QUEUE = "retryable-cron-tasks";
@Provides
@Parameter(PARAM_SHOULD_PUBLISH)
static boolean provideShouldPublish(
@@ -100,7 +100,7 @@ public final class IcannReportingUploadAction implements Runnable {
IcannReportingUploadAction() {}
/**
* Get the scheduled time for the next month of the given {@link DateTime}.
* Get the scheduled time for the next month of the given {@link Instant}.
*
* <p>The scheduled time is always the second day of next month at 10AM UTC. This is because the
* staging action is scheduled to run at 9AM UTC on that day, and there is no reason to run the
@@ -14,7 +14,6 @@
package google.registry.request;
import google.registry.config.RegistryConfig;
import google.registry.request.auth.Auth;
import java.lang.annotation.ElementType;
@@ -30,7 +30,6 @@ import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
/** Utilities for extracting parameters from HTTP requests. */
public final class RequestParameters {
@@ -298,33 +297,6 @@ public final class RequestParameters {
* @throws BadRequestException if request parameter named {@code name} is absent, empty, or could
* not be parsed as an ISO 8601 timestamp
*/
public static DateTime extractRequiredDatetimeParameter(HttpServletRequest req, String name) {
String stringValue = extractRequiredParameter(req, name);
try {
return DateTime.parse(stringValue);
} catch (IllegalArgumentException e) {
throw new BadRequestException("Bad ISO 8601 timestamp: " + name);
}
}
/**
* Returns first request parameter associated with {@code name} parsed as an <a
* href="https://goo.gl/pk5Q2k">ISO 8601</a> timestamp, e.g. {@code 1984-12-18TZ}, {@code
* 2000-01-01T16:20:00Z}.
*
* @throws BadRequestException if request parameter is present but not a valid {@link DateTime}.
*/
public static Optional<DateTime> extractOptionalDatetimeParameter(
HttpServletRequest req, String name) {
String stringParam = req.getParameter(name);
try {
return isNullOrEmpty(stringParam)
? Optional.empty()
: Optional.of(DateTime.parse(stringParam));
} catch (IllegalArgumentException e) {
throw new BadRequestException("Bad ISO 8601 timestamp: " + name);
}
}
public static ImmutableSet<Instant> extractSetOfInstantParameters(
HttpServletRequest req, String name) {
@@ -338,26 +310,6 @@ public final class RequestParameters {
}
}
/**
* Returns all GET or POST date parameters associated with {@code name}, or an empty set if none.
*
* <p>Dates are parsed as an <a href="https://goo.gl/pk5Q2k">ISO 8601</a> timestamp, e.g. {@code
* 1984-12-18TZ}, {@code 2000-01-01T16:20:00Z}.
*
* @throws BadRequestException if one of the parameter values is not a valid {@link DateTime}.
*/
public static ImmutableSet<DateTime> extractSetOfDatetimeParameters(
HttpServletRequest req, String name) {
try {
return extractSetOfParameters(req, name).stream()
.filter(not(String::isEmpty))
.map(DateTime::parse)
.collect(toImmutableSet());
} catch (IllegalArgumentException e) {
throw new BadRequestException("Bad ISO 8601 timestamp: " + name);
}
}
private static boolean equalsFalse(@Nullable String value) {
return nullToEmpty(value).equalsIgnoreCase("false");
}
@@ -56,7 +56,7 @@ public final class XsrfTokenManager {
/** Generates an XSRF token for a given user based on email address. */
public String generateToken(String email) {
checkArgumentNotNull(email);
long timestampMillis = clock.now().toEpochMilli();
long timestampMillis = clock.nowMillis();
return encodeToken(ServerSecret.get().asBytes(), email, timestampMillis);
}
@@ -16,20 +16,18 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.toInstant;
import com.beust.jcommander.Parameter;
import google.registry.model.domain.token.AllocationToken;
import google.registry.model.domain.token.AllocationToken.TokenType;
import google.registry.model.domain.token.BulkPricingPackage;
import google.registry.persistence.VKey;
import google.registry.tools.params.DateTimeParameter;
import google.registry.tools.params.InstantParameter;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.joda.money.Money;
import org.joda.time.DateTime;
/** Shared base class for commands to create or update a {@link BulkPricingPackage} object. */
abstract class CreateOrUpdateBulkPricingPackageCommand extends MutatingCommand {
@@ -58,10 +56,10 @@ abstract class CreateOrUpdateBulkPricingPackageCommand extends MutatingCommand {
@Nullable
@Parameter(
names = "--next_billing_date",
validateWith = DateTimeParameter.class,
validateWith = InstantParameter.class,
description =
"The next date that the bulk pricing package should be billed for its annual fee")
DateTime nextBillingDate;
Instant nextBillingDate;
/** Returns the existing BulkPricingPackage or null if it does not exist. */
@Nullable
@@ -108,8 +106,7 @@ abstract class CreateOrUpdateBulkPricingPackageCommand extends MutatingCommand {
Optional.ofNullable(maxCreates).ifPresent(builder::setMaxCreates);
Optional.ofNullable(price).ifPresent(builder::setBulkPrice);
Optional.ofNullable(nextBillingDate)
.ifPresent(
nextBillingDate -> builder.setNextBillingDate(toInstant(nextBillingDate)));
.ifPresent(nextBillingDate -> builder.setNextBillingDate(nextBillingDate));
if (clearLastNotificationSent()) {
builder.setLastNotificationSent((Instant) null);
}
@@ -88,4 +88,3 @@ public class CreateRegistrarGroupsCommand extends ConfirmingCommand
return "Success!";
}
}
@@ -32,10 +32,12 @@ import com.google.common.collect.ImmutableMultimap;
import google.registry.batch.CloudTasksUtils;
import google.registry.model.rde.RdeMode;
import google.registry.rde.RdeStagingAction;
import google.registry.util.DateTimeUtils;
import jakarta.inject.Inject;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import org.joda.time.DateTime;
/**
* Command to kick off the server-side generation of an XML RDE or BRDA escrow deposit, which will
@@ -54,7 +56,7 @@ final class GenerateEscrowDepositCommand implements Command {
names = {"-w", "--watermark"},
description = "Point-in-time timestamp(s) for which time the deposit should be generated",
required = true)
private List<DateTime> watermarks;
private List<Instant> watermarks;
@Parameter(
names = {"-m", "--mode"},
@@ -88,14 +90,14 @@ final class GenerateEscrowDepositCommand implements Command {
}
// We need to test for cases where "--watermark=" is passed in as a parameter, because it would
// first be converted to an empty list, and as such the DateTime converter would not be called.
// first be converted to an empty list, and as such the Instant converter would not be called.
if (tlds.isEmpty()) {
throw new ParameterException("At least one TLD must be specified");
}
assertTldsExist(tlds);
for (DateTime watermark : watermarks) {
if (!watermark.withTimeAtStartOfDay().equals(watermark)) {
for (Instant watermark : watermarks) {
if (!watermark.truncatedTo(ChronoUnit.DAYS).equals(watermark)) {
throw new ParameterException("Each watermark date must be the start of a day");
}
}
@@ -117,7 +119,9 @@ final class GenerateEscrowDepositCommand implements Command {
.put(PARAM_TLDS, tlds.stream().collect(Collectors.joining(",")))
.put(
PARAM_WATERMARKS,
watermarks.stream().map(DateTime::toString).collect(Collectors.joining(",")));
watermarks.stream()
.map(DateTimeUtils::formatInstant)
.collect(Collectors.joining(",")));
if (revision != null) {
paramsBuilder.put(PARAM_REVISION, String.valueOf(revision));
@@ -126,5 +130,4 @@ final class GenerateEscrowDepositCommand implements Command {
RDE_REPORT_QUEUE,
cloudTasksUtils.createTask(RdeStagingAction.class, POST, paramsBuilder.build()));
}
}
@@ -15,8 +15,6 @@
package google.registry.tools;
import static google.registry.model.tld.Tlds.assertTldsExist;
import static google.registry.util.DateTimeUtils.toLocalDate;
import static java.time.ZoneOffset.UTC;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@@ -28,6 +26,7 @@ import jakarta.inject.Inject;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
@@ -61,8 +60,7 @@ final class GenerateZoneFilesCommand implements CommandWithConnection {
@Override
public void run() throws IOException {
if (exportDate == null) {
exportDate =
toLocalDate(clock.now().minus(Duration.ofMinutes(2))).atStartOfDay(UTC).toInstant();
exportDate = clock.now().minus(Duration.ofMinutes(2)).truncatedTo(ChronoUnit.DAYS);
}
assertTldsExist(mainParameters);
ImmutableMap<String, Object> params = ImmutableMap.of(
@@ -14,7 +14,6 @@
package google.registry.tools;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import google.registry.keyring.api.KeySerializer;
@@ -26,7 +26,6 @@ import google.registry.model.adapters.CurrencyJsonAdapter;
import google.registry.model.adapters.SerializableJsonTypeAdapter;
import google.registry.util.CidrAddressBlock;
import google.registry.util.CidrAddressBlock.CidrAddressBlockAdapter;
import google.registry.util.DateTimeTypeAdapter;
import google.registry.util.DurationTypeAdapter;
import google.registry.util.InstantTypeAdapter;
import java.io.IOException;
@@ -34,7 +33,6 @@ import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import org.joda.money.CurrencyUnit;
import org.joda.time.DateTime;
/** Utility class for methods related to GSON and necessary GSON processing. */
public class GsonUtils {
@@ -78,7 +76,7 @@ public class GsonUtils {
return new GsonBuilder()
.registerTypeAdapter(CidrAddressBlock.class, new CidrAddressBlockAdapter())
.registerTypeAdapter(CurrencyUnit.class, new CurrencyJsonAdapter())
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(Instant.class, new InstantTypeAdapter())
.registerTypeAdapter(Duration.class, new DurationTypeAdapter())
.registerTypeAdapter(Instant.class, new InstantTypeAdapter())
.registerTypeAdapter(Serializable.class, new SerializableJsonTypeAdapter())
@@ -126,7 +126,6 @@ final class SetupOteCommand extends ConfirmingCommand {
String.format(
"""
WARNING: Running against %s environment. Are \
you sure you didn't mean to run this against sandbox (e.g. "-e SANDBOX")?\
""",
@@ -107,4 +107,3 @@ final class UpdateKeyringSecretCommand implements Command {
secretManagerKeyringUpdater.update();
}
}
@@ -13,32 +13,32 @@
// limitations under the License.
package google.registry.tools.params;
import static org.joda.time.DateTimeZone.UTC;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import static java.time.ZoneOffset.UTC;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
/**
* {@link DateTime} CLI parameter converter/validator restricted to dates. The {@link DateTime}s
* produced by this class will always have a time zone of {@link DateTimeZone#UTC}.
* {@link Instant} CLI parameter converter/validator restricted to dates. The {@link Instant}s
* produced by this class will always have a time zone of {@link ZoneOffset#UTC}.
*/
public final class DateParameter extends ParameterConverterValidator<DateTime> {
public final class DateParameter extends ParameterConverterValidator<Instant> {
public DateParameter() {
super("not an ISO-8601 date");
}
/**
* Parser for DateTimes that permits only a restricted subset of ISO 8601 datetime syntax.
* The supported format is "YYYY-MM-DD", i.e. there must only be a complete date.
* Parser for Instants that permits only a restricted subset of ISO 8601 datetime syntax. The
* supported format is "YYYY-MM-DD", i.e. there must only be a complete date.
*/
private static final DateTimeFormatter STRICT_DATE_PARSER =
new DateTimeFormatter(null, ISODateTimeFormat.date().getParser());
private static final DateTimeFormatter STRICT_DATE_PARSER = DateTimeFormatter.ISO_LOCAL_DATE;
@Override
public DateTime convert(String value) {
return DateTime.parse(value, STRICT_DATE_PARSER).withZoneRetainFields(UTC);
public Instant convert(String value) {
return LocalDate.parse(value, STRICT_DATE_PARSER).atStartOfDay(UTC).toInstant();
}
}
@@ -1,56 +0,0 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools.params;
import static org.joda.time.DateTimeZone.UTC;
import com.google.common.primitives.Longs;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import org.joda.time.format.ISODateTimeFormat;
/** {@linkplain DateTime} CLI parameter converter/validator. Can be ISO or millis from epoch. */
public final class DateTimeParameter extends ParameterConverterValidator<DateTime> {
public DateTimeParameter() {
super("not an ISO-8601 timestamp (or millis from epoch)");
}
/**
* Parser for DateTimes that permits only a restricted subset of ISO 8601 datetime syntax.
* The supported format is "YYYY-MM-DD'T'HH:MM:SS[.SSS]ZZ", i.e. there must be a complete date
* and at least hours, minutes, seconds, and time zone; milliseconds are optional.
*
* <p>We use this instead of the default {@link ISODateTimeFormat#dateTimeParser()} because that
* parser is very flexible and accepts date times with missing dates, missing dates, and various
* other unspecified fields that can lead to confusion and ambiguity.
*/
private static final DateTimeFormatter STRICT_DATE_TIME_PARSER = new DateTimeFormatterBuilder()
.append(null, new DateTimeParser[] {
// The formatter will try the following parsers in order until one succeeds.
ISODateTimeFormat.dateTime().getParser(),
ISODateTimeFormat.dateTimeNoMillis().getParser()})
.toFormatter();
@Override
public DateTime convert(String value) {
Long millis = Longs.tryParse(value);
if (millis != null) {
return new DateTime(millis.longValue(), UTC);
}
return DateTime.parse(value, STRICT_DATE_TIME_PARSER).withZone(UTC);
}
}
@@ -14,8 +14,7 @@
package google.registry.tools.params;
import org.joda.time.Duration;
import org.joda.time.Period;
import java.time.Duration;
/** Duration CLI parameter converter/validator. */
public final class DurationParameter extends ParameterConverterValidator<Duration> {
@@ -26,6 +25,6 @@ public final class DurationParameter extends ParameterConverterValidator<Duratio
@Override
public Duration convert(String value) {
return Period.parse(value).toStandardDuration();
return Duration.parse(value);
}
}
@@ -14,26 +14,23 @@
package google.registry.tools.params;
import static google.registry.util.DateTimeUtils.toInstant;
import com.google.common.primitives.Longs;
import java.time.Instant;
import java.time.OffsetDateTime;
/** {@linkplain Instant} CLI parameter converter/validator. Can be ISO or millis from epoch. */
public final class InstantParameter extends ParameterConverterValidator<Instant> {
private static final DateTimeParameter DATE_TIME_CONVERTER = new DateTimeParameter();
public InstantParameter() {
super("not an ISO-8601 timestamp (or millis from epoch)");
}
/**
* Converts the given string to an {@link Instant}.
*
* <p>Delegates to {@link DateTimeParameter} for parsing, then converts to {@link Instant}.
*/
@Override
public Instant convert(String value) {
return toInstant(DATE_TIME_CONVERTER.convert(value));
Long millis = Longs.tryParse(value);
if (millis != null) {
return Instant.ofEpochMilli(millis);
}
return OffsetDateTime.parse(value).toInstant();
}
}
@@ -1,41 +0,0 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools.params;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
/** Interval CLI parameter converter/validator. */
public final class IntervalParameter extends ParameterConverterValidator<Interval> {
public IntervalParameter() {
super("not an ISO-8601 interval (e.g. 2004-06-09T12:30:00Z/2004-07-10T13:30:00Z)");
}
@Override
public Interval convert(String value) {
// Interval.parse(null) creates an interval with both start and end times set to now.
// Do something a little more reasonable.
if (value == null) {
throw new NullPointerException();
}
Interval interval = Interval.parse(value);
// Interval does not have a way to set the time zone, so create a new interval with the
// start and end times of the parsed interval converted to UTC.
return new Interval(
interval.getStart().withZone(DateTimeZone.UTC),
interval.getEnd().withZone(DateTimeZone.UTC));
}
}
@@ -14,8 +14,8 @@
package google.registry.tools.params;
import org.joda.time.LocalDate;
import org.joda.time.format.ISODateTimeFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/** {@linkplain LocalDate} CLI parameter converter/validator. */
public final class LocalDateParameter extends ParameterConverterValidator<LocalDate> {
@@ -26,6 +26,6 @@ public final class LocalDateParameter extends ParameterConverterValidator<LocalD
@Override
public LocalDate convert(String value) {
return LocalDate.parse(value, ISODateTimeFormat.date());
return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE);
}
}
@@ -1,21 +0,0 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools.params;
import org.joda.time.Interval;
/** Optional wrapper for IntervalParameter. */
public final class OptionalIntervalParameter
extends OptionalParameterConverterValidator<Interval, IntervalParameter> {}
@@ -17,6 +17,7 @@ package google.registry.tools.params;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
import java.time.DateTimeException;
/** Base class for parameters that do both conversion and validation (reduces boilerplate). */
public abstract class ParameterConverterValidator<T>
@@ -39,7 +40,7 @@ public abstract class ParameterConverterValidator<T>
public void validate(String name, String value) throws ParameterException {
try {
convert(value);
} catch (IllegalArgumentException e) {
} catch (IllegalArgumentException | DateTimeException e) {
throw new ParameterException(String.format("%s=%s %s", name, value, messageForInvalid), e);
}
}
@@ -20,14 +20,13 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.net.HostAndPort;
import com.google.common.net.InternetDomainName;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.logging.Level;
import javax.annotation.Nullable;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;
import org.joda.time.LocalDate;
import org.joda.time.YearMonth;
/** JCommander converter factory that works for non-internal converters. */
public final class ParameterFactory implements IStringConverterFactory {
@@ -41,17 +40,14 @@ public final class ParameterFactory implements IStringConverterFactory {
private static final ImmutableMap<Class<?>, Class<? extends IStringConverter<?>>> CONVERTERS =
new ImmutableMap.Builder<Class<?>, Class<? extends IStringConverter<?>>>()
.put(DateTime.class, DateTimeParameter.class)
.put(Instant.class, InstantParameter.class)
.put(Duration.class, DurationParameter.class)
.put(HostAndPort.class, HostAndPortParameter.class)
.put(InternetDomainName.class, InternetDomainNameParameter.class)
.put(Interval.class, IntervalParameter.class)
.put(Level.class, LoggingLevelParameter.class)
.put(LocalDate.class, LocalDateParameter.class)
.put(Money.class, MoneyParameter.class)
.put(Path.class, PathParameter.class)
.put(YearMonth.class, YearMonthParameter.class)
.build();
}
@@ -29,7 +29,7 @@ import org.joda.money.Money;
// TODO(b/19031334): Investigate making this complex generic type work with the factory.
public abstract class TransitionListParameter<V> extends KeyValueMapParameter<Instant, V> {
private static final InstantParameter DATE_TIME_CONVERTER = new InstantParameter();
private static final InstantParameter INSTANT_CONVERTER = new InstantParameter();
public TransitionListParameter() {
// This is not sentence-capitalized like most exception messages because it is appended to the
@@ -39,7 +39,7 @@ public abstract class TransitionListParameter<V> extends KeyValueMapParameter<In
@Override
protected final Instant parseKey(String rawKey) {
return DATE_TIME_CONVERTER.convert(rawKey);
return INSTANT_CONVERTER.convert(rawKey);
}
@Override
@@ -14,8 +14,7 @@
package google.registry.tools.params;
import org.joda.time.YearMonth;
import org.joda.time.format.ISODateTimeFormat;
import java.time.YearMonth;
/** {@linkplain YearMonth} CLI parameter converter/validator (e.g. 1984-12) */
public final class YearMonthParameter extends ParameterConverterValidator<YearMonth> {
@@ -26,6 +25,6 @@ public final class YearMonthParameter extends ParameterConverterValidator<YearMo
@Override
public YearMonth convert(String value) {
return YearMonth.parse(value, ISODateTimeFormat.yearMonth());
return YearMonth.parse(value);
}
}
@@ -127,7 +127,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
if (exportTime.isAfter(minusMinutes(now, 2))) {
throw new BadRequestException("Invalid export time: must be > 2 minutes ago");
}
if (exportTime.isBefore(now.minusMillis(databaseRetention.toMillis()))) {
if (exportTime.isBefore(now.minus(databaseRetention))) {
throw new BadRequestException(
String.format("Invalid export time: must be < %d days ago", databaseRetention.toDays()));
}
@@ -16,7 +16,6 @@ package google.registry.ui.server.console;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET;
import static google.registry.util.DateTimeUtils.toLocalDate;
import static java.time.ZoneOffset.UTC;
import com.google.common.collect.ImmutableList;
@@ -86,8 +85,7 @@ public class ConsoleDumDownloadAction extends ConsoleApiAction {
.setHeader("Cache-Control", "max-age=86400"); // 86400 seconds = 1 day
consoleApiParams
.response()
.setDateHeader(
"Expires", toLocalDate(clock.now()).atStartOfDay(UTC).plusDays(1).toInstant());
.setDateHeader("Expires", clock.nowDate().atStartOfDay(UTC).plusDays(1).toInstant());
try (var writer = consoleApiParams.response().getWriter()) {
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
@@ -17,8 +17,8 @@ package google.registry.xml;
import static com.google.common.base.Strings.isNullOrEmpty;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import java.time.Period;
import javax.annotation.Nullable;
import org.joda.time.Period;
/** Adapter to use Joda {@link Period} when marshalling XML. */
public class PeriodAdapter extends XmlAdapter<String, Period> {
@@ -1,68 +0,0 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.xml;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.joda.time.DateTimeZone.UTC;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
/**
* Adapter to use Joda {@link DateTime} when marshalling XML timestamps.
*
* <p>These fields shall contain timestamps indicating the date and time in UTC as specified in
* RFC3339, with no offset from the zero meridian. For example: {@code 2010-10-17T00:00:00Z}.
*/
public class UtcDateTimeAdapter extends XmlAdapter<String, DateTime> {
/** @see ISODateTimeFormat#dateTimeNoMillis */
private static final DateTimeFormatter MARSHAL_FORMAT = ISODateTimeFormat.dateTimeNoMillis();
/** @see ISODateTimeFormat#dateTimeParser */
private static final DateTimeFormatter UNMARSHAL_FORMAT = ISODateTimeFormat.dateTimeParser();
/** Same as {@link #marshal(DateTime)}, but in a convenient static format. */
public static String getFormattedString(@Nullable DateTime timestamp) {
return (timestamp == null) ? "" : MARSHAL_FORMAT.print(timestamp.toDateTime(UTC));
}
/**
* Parses an ISO timestamp string into a UTC {@link DateTime} object, converting timezones if
* necessary. If {@code timestamp} is empty or {@code null} then {@code null} is returned.
*/
@Nullable
@CheckForNull
@Override
public DateTime unmarshal(@Nullable String timestamp) {
if (isNullOrEmpty(timestamp)) {
return null;
}
return UNMARSHAL_FORMAT.parseDateTime(timestamp).withZone(UTC);
}
/**
* Converts {@link DateTime} to UTC and returns it as an RFC3339 string. If {@code timestamp} is
* {@code null} then an empty string is returned.
*/
@Override
public String marshal(@Nullable DateTime timestamp) {
return getFormattedString(timestamp);
}
}
@@ -1,4 +1,4 @@
// Copyright 2026 The Nomulus Authors. All Rights Reserved.
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -15,41 +15,34 @@
package google.registry.xml;
import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.util.DateTimeUtils.formatInstant;
import static google.registry.util.DateTimeUtils.parseInstant;
import static java.time.ZoneOffset.UTC;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/**
* Adapter to use java.time {@link Instant} when marshalling XML timestamps.
* Adapter to use an {@link Instant} when marshalling XML timestamps.
*
* <p>These fields shall contain timestamps indicating the date and time in UTC as specified in
* RFC3339, with no offset from the zero meridian. For example: {@code 2010-10-17T00:00:00Z}.
* RFC3339.
*
* @see <a href="http://tools.ietf.org/html/rfc3339">RFC3339</a>
*/
public class UtcInstantAdapter extends XmlAdapter<String, Instant> {
private static final DateTimeFormatter MARSHAL_FORMAT =
DateTimeFormatter.ofPattern("u-MM-dd'T'HH:mm:ss'Z'").withZone(UTC);
/** Same as {@link #marshal(Instant)}, but in a convenient static format. */
public static String getFormattedString(@Nullable Instant timestamp) {
if (timestamp == null) {
return "";
}
return MARSHAL_FORMAT.format(timestamp);
return (timestamp == null) ? "" : formatInstant(timestamp);
}
/**
* Parses an ISO timestamp string into a UTC {@link Instant} object. If {@code timestamp} is empty
* or {@code null} then {@code null} is returned.
* Parses an ISO timestamp string into a UTC {@link Instant} object, converting timezones if
* necessary. If {@code timestamp} is empty or {@code null} then {@code null} is returned.
*/
@Nullable
@CheckForNull
@Override
@CheckForNull
public Instant unmarshal(@Nullable String timestamp) {
if (isNullOrEmpty(timestamp)) {
return null;
@@ -83,7 +83,6 @@
<!-- Customized type converters -->
<class>google.registry.persistence.converter.BloomFilterConverter</class>
<class>google.registry.persistence.converter.CurrencyUnitConverter</class>
<class>google.registry.persistence.converter.DateTimeConverter</class>
<!-- Generated converters for VKey -->
<class>google.registry.model.billing.VKeyConverter_BillingCancellation</class>
@@ -216,8 +216,8 @@ public class CloudTasksUtilsTest {
assertThat(task.getScheduleTime().getSeconds()).isNotEqualTo(0);
Instant scheduleTime = Instant.ofEpochSecond(task.getScheduleTime().getSeconds());
Instant lowerBoundTime = Instant.ofEpochMilli(clock.now().toEpochMilli());
Instant upperBound = Instant.ofEpochMilli(clock.now().plusSeconds(100).toEpochMilli());
Instant lowerBoundTime = clock.now();
Instant upperBound = clock.now().plusSeconds(100);
assertThat(scheduleTime.isBefore(lowerBoundTime)).isFalse();
assertThat(upperBound.isBefore(scheduleTime)).isFalse();
@@ -253,7 +253,7 @@ public class CloudTasksUtilsTest {
.isEqualTo("https://backend.registry.test/the/path?key1=val1&key2=val2&key1=val3");
verifyOidcToken(task);
assertThat(Instant.ofEpochSecond(task.getScheduleTime().getSeconds()))
.isEqualTo(Instant.ofEpochMilli(clock.now().plus(Duration.ofMinutes(10)).toEpochMilli()));
.isEqualTo(clock.now().plus(Duration.ofMinutes(10)));
}
@Test

Some files were not shown because too many files have changed in this diff Show More