diff --git a/GEMINI.md b/GEMINI.md index 27f0dd4bc..cc88195ce 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -19,7 +19,7 @@ This document outlines foundational mandates, architectural patterns, and projec - **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 `Instant` parameters or local variables as `final` unnecessarily, as it clutters the codebase. + - 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). @@ -77,6 +77,7 @@ Based on historical PR reviews, avoid the following common mistakes: - **Immutable Types:** Declare variables, fields, and return types explicitly as Guava immutable types (e.g., `ImmutableList`, `ImmutableMap`) instead of their generic interfaces (`List`, `Map`) to clearly communicate immutability contracts to callers. Use `toImmutableList()` and `toImmutableMap()` collectors in streams rather than manually accumulating into an `ArrayList` or `HashMap`. - **Constructors:** Do not perform heavy logic, I/O, or external API calls inside constructors. Initialization logic should be deferred or handled in a factory method or a dedicated startup routine. - **Exception Handling:** Do not catch generic `Exception` or `Throwable` if a more specific exception is expected. Never "log and re-throw" the same exception; either handle it entirely (and log), or throw it up the chain. For batch processes, catch exceptions at the individual item/chunk level so one failure doesn't abort the entire batch. +- **Optional Assertions:** Prefer Truth's `.hasValue(...)` over `.isEqualTo(Optional.of(...))` for cleaner and more descriptive assertions on `Optional` types. - **Fail Fast:** Validate inputs and fail fast (using `Preconditions.checkArgument` or similar) at the highest level possible rather than passing invalid state (like `null`s) deeper into business logic. - **Magic Numbers:** Always document magic numbers or hardcoded limits (like `50.0` or `30`) with inline comments explaining the rationale. - **Null Safety and Optional:** Prefer using `Optional` for any variable that is expected to potentially be null. For any other variable that can be null but cannot use an `Optional` (e.g., function parameters or return types where `Optional` is not idiomatic), it MUST be annotated with `@Nullable`. Always use the `javax.annotation.Nullable` annotation. @@ -119,6 +120,7 @@ Before finalizing any PR or declaring a task complete, you MUST perform a thorou 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. Only after actively confirming these checks against your diff are you permitted to finalize the task. @@ -156,20 +158,20 @@ This project treats Error Prone warnings as errors. --- -# GitHub and Pull Request Protocol +## GitHub and Pull Request Protocol This protocol defines the standard for interacting with GitHub repositories and processing Pull Request (PR) feedback. -## 1. Interaction via `gh` CLI +### 1. Interaction via `gh` CLI - **Primary Tool:** ALWAYS use the `gh` CLI for all GitHub-related operations (listing PRs, viewing PR content, checking status, adding comments). - **Credential Safety:** Never expose tokens or credentials in shell commands. -## 2. Processing PR Feedback +### 2. Processing PR Feedback - **Systematic Review:** When asked to address PR comments, first fetch all comments using `gh pr view --json reviews,comments`. - **Minimal Scope Expansion:** Address comments surgically. If a fix requires changes beyond a few lines or expands the PR's original scope significantly, DO NOT implement it without explicit user approval. Instead, report the issue to the user. - **Verification:** After addressing feedback, run the full build (`./gradlew build`) and relevant tests to ensure no regressions were introduced. -## 3. PR Lifecycle Management +### 3. PR Lifecycle Management - **One Commit Per PR:** Ensure all changes are squashed into a single, clean commit. Use `git commit --amend --no-edit` for follow-up fixes. - **Clean Workspace:** Always run `git status` and verify the repository state before declaring a task complete. - **Package Lock:** The Gradle build automatically modifies `console-webapp/package-lock.json` via the `npmInstallDeps` task. ALWAYS revert this file (`git checkout console-webapp/package-lock.json`) before staging changes or finalizing a commit unless you explicitly modified NPM dependencies. diff --git a/common/src/main/java/google/registry/util/DateTimeUtils.java b/common/src/main/java/google/registry/util/DateTimeUtils.java index 5a7012134..b73c3dbbc 100644 --- a/common/src/main/java/google/registry/util/DateTimeUtils.java +++ b/common/src/main/java/google/registry/util/DateTimeUtils.java @@ -15,6 +15,7 @@ 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; @@ -30,14 +31,14 @@ import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import javax.annotation.Nullable; import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; +import org.joda.time.ReadableDuration; /** Utilities methods and constants related to Joda {@link DateTime} objects. */ public abstract class DateTimeUtils { /** The start of the epoch, in a convenient constant. */ - @Deprecated public static final DateTime START_OF_TIME = new DateTime(0, DateTimeZone.UTC); + @Deprecated public static final DateTime START_OF_TIME = new DateTime(0, UTC); /** The start of the UNIX epoch (which is defined in UTC), in a convenient constant. */ public static final Instant START_INSTANT = Instant.ofEpochMilli(0); @@ -49,8 +50,7 @@ public abstract class DateTimeUtils { * but Java uses milliseconds, so this is the largest representable date that will survive a * round-trip through the database. */ - @Deprecated - public static final DateTime END_OF_TIME = new DateTime(Long.MAX_VALUE / 1000, DateTimeZone.UTC); + @Deprecated public static final DateTime END_OF_TIME = new DateTime(Long.MAX_VALUE / 1000, UTC); /** * An instant in the far future that we can treat as infinity. @@ -76,6 +76,10 @@ public abstract class DateTimeUtils { .toFormatter() .withZone(ZoneOffset.UTC); + /** A formatter that produces lowercase, filename-safe and job-name-safe timestamps. */ + public static final DateTimeFormatter LOWERCASE_TIMESTAMP_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd't'HH-mm-ss'z'").withZone(ZoneOffset.UTC); + /** Formats an {@link Instant} to an ISO-8601 string. */ public static String formatInstant(Instant instant) { return ISO_8601_FORMATTER.format(instant); @@ -147,6 +151,18 @@ public abstract class DateTimeUtils { return !timeToCheck.isAfter(timeToCompareTo); } + /** 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); @@ -237,7 +253,17 @@ public abstract class DateTimeUtils { } public static LocalDate toLocalDate(Date date) { - return new LocalDate(date.getTime(), DateTimeZone.UTC); + return new LocalDate(date.getTime(), UTC); + } + + /** Converts a java.time.LocalDate to a Joda-Time LocalDate. */ + public static LocalDate toJodaLocalDate(java.time.LocalDate localDate) { + return new LocalDate(localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth()); + } + + /** Converts an Instant to a Joda-Time LocalDate in UTC. */ + public static LocalDate toJodaLocalDate(Instant instant) { + return new LocalDate(instant.toEpochMilli(), UTC); } /** Convert a joda {@link DateTime} to a java.time {@link Instant}, null-safe. */ @@ -249,7 +275,7 @@ public abstract class DateTimeUtils { /** 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(), DateTimeZone.UTC); + 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}. */ diff --git a/common/src/main/java/google/registry/util/Sleeper.java b/common/src/main/java/google/registry/util/Sleeper.java index 1ee660441..a55c2f5a3 100644 --- a/common/src/main/java/google/registry/util/Sleeper.java +++ b/common/src/main/java/google/registry/util/Sleeper.java @@ -14,6 +14,7 @@ package google.registry.util; +import java.time.Duration; import javax.annotation.concurrent.ThreadSafe; import org.joda.time.ReadableDuration; @@ -32,6 +33,15 @@ public interface Sleeper { */ void sleep(ReadableDuration duration) throws InterruptedException; + /** + * Puts the current thread to sleep. + * + * @throws InterruptedException if this thread was interrupted + */ + default void sleep(Duration duration) throws InterruptedException { + sleep(DateTimeUtils.toJodaDuration(duration)); + } + /** * Puts the current thread to sleep, ignoring interrupts. * @@ -42,6 +52,18 @@ public interface Sleeper { */ void sleepUninterruptibly(ReadableDuration duration); + /** + * Puts the current thread to sleep, ignoring interrupts. + * + *

If {@link InterruptedException} was caught, then {@code Thread.currentThread().interrupt()} + * will be called at the end of the {@code duration}. + * + * @see com.google.common.util.concurrent.Uninterruptibles#sleepUninterruptibly + */ + default void sleepUninterruptibly(Duration duration) { + sleepUninterruptibly(DateTimeUtils.toJodaDuration(duration)); + } + /** * Puts the current thread to interruptible sleep. * @@ -57,4 +79,20 @@ public interface Sleeper { throw new RuntimeException("Interrupted.", e); } } + + /** + * Puts the current thread to interruptible sleep. + * + *

This is a convenience method for {@link #sleep} that properly converts an {@link + * InterruptedException} to a {@link RuntimeException}. + */ + default void sleepInterruptibly(Duration duration) { + try { + sleep(duration); + } catch (InterruptedException e) { + // Restore current thread's interrupted state. + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted.", e); + } + } } diff --git a/common/src/main/java/google/registry/util/SystemClock.java b/common/src/main/java/google/registry/util/SystemClock.java index 8fc1c557a..632cdf9be 100644 --- a/common/src/main/java/google/registry/util/SystemClock.java +++ b/common/src/main/java/google/registry/util/SystemClock.java @@ -14,11 +14,11 @@ package google.registry.util; +import static java.time.temporal.ChronoUnit.MILLIS; import static org.joda.time.DateTimeZone.UTC; import jakarta.inject.Inject; import java.time.Instant; -import java.time.temporal.ChronoUnit; import javax.annotation.concurrent.ThreadSafe; import org.joda.time.DateTime; @@ -43,6 +43,6 @@ public class SystemClock implements Clock { // (which uses millisecond precision via DateTimeConverter). This prevents subtle comparison // bugs where a high-precision Instant would be considered "after" a truncated database // timestamp. - return Instant.now().truncatedTo(ChronoUnit.MILLIS); + return Instant.now().truncatedTo(MILLIS); } } diff --git a/common/src/main/java/google/registry/util/SystemSleeper.java b/common/src/main/java/google/registry/util/SystemSleeper.java index ec30280c6..0cafc74ab 100644 --- a/common/src/main/java/google/registry/util/SystemSleeper.java +++ b/common/src/main/java/google/registry/util/SystemSleeper.java @@ -15,11 +15,11 @@ package google.registry.util; import static com.google.common.base.Preconditions.checkArgument; +import static google.registry.util.DateTimeUtils.toJavaDuration; import com.google.common.util.concurrent.Uninterruptibles; import jakarta.inject.Inject; import java.io.Serializable; -import java.time.Duration; import javax.annotation.concurrent.ThreadSafe; import org.joda.time.ReadableDuration; @@ -41,6 +41,6 @@ public final class SystemSleeper implements Sleeper, Serializable { @Override public void sleepUninterruptibly(ReadableDuration duration) { checkArgument(duration.getMillis() >= 0); - Uninterruptibles.sleepUninterruptibly(Duration.ofMillis(duration.getMillis())); + Uninterruptibles.sleepUninterruptibly(toJavaDuration(duration)); } } diff --git a/common/src/testing/java/google/registry/testing/FakeClock.java b/common/src/testing/java/google/registry/testing/FakeClock.java index fe1936608..f455fc2ee 100644 --- a/common/src/testing/java/google/registry/testing/FakeClock.java +++ b/common/src/testing/java/google/registry/testing/FakeClock.java @@ -89,6 +89,11 @@ public final class FakeClock implements Clock { currentTimeMillis.addAndGet(duration.getMillis()); } + /** Advances clock by some duration. */ + public void advanceBy(java.time.Duration duration) { + currentTimeMillis.addAndGet(duration.toMillis()); + } + /** Sets the time to the specified instant. */ public void setTo(ReadableInstant time) { currentTimeMillis.set(time.getMillis()); diff --git a/console-webapp/package-lock.json b/console-webapp/package-lock.json index 5b0bec4b4..76eb31da5 100644 --- a/console-webapp/package-lock.json +++ b/console-webapp/package-lock.json @@ -628,6 +628,18 @@ } } }, + "node_modules/@angular/build/node_modules/@types/node": { + "version": "25.6.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/@types/node/-/node-25.6.0.tgz", + "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "undici-types": "~7.19.0" + } + }, "node_modules/@angular/build/node_modules/@vitejs/plugin-basic-ssl": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-2.1.0.tgz", @@ -641,6 +653,24 @@ "vite": "^6.0.0 || ^7.0.0" } }, + "node_modules/@angular/build/node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@angular/build/node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -664,6 +694,22 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/@angular/build/node_modules/readdirp": { + "version": "5.0.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/readdirp/-/readdirp-5.0.0.tgz", + "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@angular/build/node_modules/rxjs": { "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", @@ -697,6 +743,15 @@ "node": ">= 12" } }, + "node_modules/@angular/build/node_modules/undici-types": { + "version": "7.19.2", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/undici-types/-/undici-types-7.19.2.tgz", + "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, "node_modules/@angular/build/node_modules/vite": { "version": "7.3.0", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.0.tgz", @@ -916,6 +971,24 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/@angular/cli/node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@angular/cli/node_modules/cli-spinners": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", @@ -1019,6 +1092,22 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/@angular/cli/node_modules/readdirp": { + "version": "5.0.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/readdirp/-/readdirp-5.0.0.tgz", + "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@angular/cli/node_modules/rxjs": { "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", @@ -4606,6 +4695,24 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/@schematics/angular/node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@schematics/angular/node_modules/cli-spinners": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", @@ -4709,6 +4816,22 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/@schematics/angular/node_modules/readdirp": { + "version": "5.0.0", + "resolved": "https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/readdirp/-/readdirp-5.0.0.tgz", + "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@schematics/angular/node_modules/rxjs": { "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", diff --git a/core/src/main/java/google/registry/batch/AsyncTaskEnqueuer.java b/core/src/main/java/google/registry/batch/AsyncTaskEnqueuer.java index e1db52808..9d78b53d1 100644 --- a/core/src/main/java/google/registry/batch/AsyncTaskEnqueuer.java +++ b/core/src/main/java/google/registry/batch/AsyncTaskEnqueuer.java @@ -26,8 +26,8 @@ import google.registry.model.EppResource; import google.registry.persistence.VKey; import google.registry.request.Action; import jakarta.inject.Inject; -import org.joda.time.DateTime; -import org.joda.time.Duration; +import java.time.Duration; +import java.time.Instant; /** Helper class to enqueue tasks for handling asynchronous operations in flows. */ public final class AsyncTaskEnqueuer { @@ -41,7 +41,7 @@ public final class AsyncTaskEnqueuer { public static final String QUEUE_ASYNC_ACTIONS = "async-actions"; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); - private static final Duration MAX_ASYNC_ETA = Duration.standardDays(30); + private static final Duration MAX_ASYNC_ETA = Duration.ofDays(30); private final CloudTasksUtils cloudTasksUtils; @@ -58,12 +58,12 @@ public final class AsyncTaskEnqueuer { */ public void enqueueAsyncResave( VKey entityKey, - DateTime now, - ImmutableSortedSet whenToResave) { - DateTime firstResave = whenToResave.first(); + Instant now, + ImmutableSortedSet whenToResave) { + Instant firstResave = whenToResave.first(); checkArgument(isBeforeOrAt(now, firstResave), "Can't enqueue a resave to run in the past"); - Duration etaDuration = new Duration(now, firstResave); - if (etaDuration.isLongerThan(MAX_ASYNC_ETA)) { + Duration etaDuration = Duration.between(now, firstResave); + if (etaDuration.compareTo(MAX_ASYNC_ETA) > 0) { logger.atInfo().log( "Ignoring async re-save of %s; %s is past the ETA threshold of %s.", entityKey, firstResave, MAX_ASYNC_ETA); diff --git a/core/src/main/java/google/registry/batch/BatchModule.java b/core/src/main/java/google/registry/batch/BatchModule.java index b868b53bb..e4b9c6a48 100644 --- a/core/src/main/java/google/registry/batch/BatchModule.java +++ b/core/src/main/java/google/registry/batch/BatchModule.java @@ -24,9 +24,9 @@ import static google.registry.request.RequestParameters.extractOptionalBooleanPa import static google.registry.request.RequestParameters.extractOptionalInstantParameter; import static google.registry.request.RequestParameters.extractOptionalIntParameter; import static google.registry.request.RequestParameters.extractOptionalParameter; -import static google.registry.request.RequestParameters.extractRequiredDatetimeParameter; +import static google.registry.request.RequestParameters.extractRequiredInstantParameter; import static google.registry.request.RequestParameters.extractRequiredParameter; -import static google.registry.request.RequestParameters.extractSetOfDatetimeParameters; +import static google.registry.request.RequestParameters.extractSetOfInstantParameters; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -44,7 +44,6 @@ import jakarta.servlet.http.HttpServletRequest; import java.time.Instant; import java.util.List; import java.util.Optional; -import org.joda.time.DateTime; /** Dagger module for injecting common settings for batch actions. */ @Module @@ -98,14 +97,14 @@ public class BatchModule { @Provides @Parameter(PARAM_REQUESTED_TIME) - static DateTime provideRequestedTime(HttpServletRequest req) { - return extractRequiredDatetimeParameter(req, PARAM_REQUESTED_TIME); + static Instant provideRequestedTime(HttpServletRequest req) { + return extractRequiredInstantParameter(req, PARAM_REQUESTED_TIME); } @Provides @Parameter(PARAM_RESAVE_TIMES) - static ImmutableSet provideResaveTimes(HttpServletRequest req) { - return extractSetOfDatetimeParameters(req, PARAM_RESAVE_TIMES); + static ImmutableSet provideResaveTimes(HttpServletRequest req) { + return extractSetOfInstantParameters(req, PARAM_RESAVE_TIMES); } @Provides diff --git a/core/src/main/java/google/registry/batch/BulkDomainTransferAction.java b/core/src/main/java/google/registry/batch/BulkDomainTransferAction.java index b3bcc419d..f9f367568 100644 --- a/core/src/main/java/google/registry/batch/BulkDomainTransferAction.java +++ b/core/src/main/java/google/registry/batch/BulkDomainTransferAction.java @@ -42,10 +42,10 @@ import google.registry.request.auth.Auth; import google.registry.request.lock.LockHandler; import jakarta.inject.Inject; import jakarta.inject.Named; +import java.time.Duration; import java.util.Optional; import java.util.concurrent.Callable; import java.util.logging.Level; -import org.joda.time.Duration; /** * An action that transfers a set of domains from one registrar to another. @@ -158,7 +158,7 @@ public class BulkDomainTransferAction implements Runnable { return null; }; - if (!lockHandler.executeWithLocks(runner, null, Duration.standardHours(1), LOCK_NAME)) { + if (!lockHandler.executeWithLocks(runner, null, Duration.ofHours(1), LOCK_NAME)) { // Send a 200-series status code to prevent this conflicting action from retrying. response.setStatus(SC_NO_CONTENT); response.setPayload("Could not acquire lock; already running?"); diff --git a/core/src/main/java/google/registry/batch/CloudTasksUtils.java b/core/src/main/java/google/registry/batch/CloudTasksUtils.java index 06b7d5fb1..e8ac82d7c 100644 --- a/core/src/main/java/google/registry/batch/CloudTasksUtils.java +++ b/core/src/main/java/google/registry/batch/CloudTasksUtils.java @@ -52,11 +52,11 @@ import jakarta.inject.Inject; import java.io.Serial; import java.io.Serializable; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.Arrays; import java.util.Optional; import java.util.Random; import java.util.function.Supplier; -import org.joda.time.Duration; /** Utilities for dealing with Cloud Tasks. */ public class CloudTasksUtils implements Serializable { @@ -251,7 +251,7 @@ public class CloudTasksUtils implements Serializable { method, service, params, - Duration.millis(random.nextInt((int) SECONDS.toMillis(jitterSeconds.get())))); + Duration.ofMillis(random.nextInt((int) SECONDS.toMillis(jitterSeconds.get())))); } /** @@ -302,12 +302,12 @@ public class CloudTasksUtils implements Serializable { Action.Service service, Multimap params, Duration delay) { - if (delay.isEqual(Duration.ZERO)) { + if (delay.isZero()) { return createTask(path, method, service, params); } - checkArgument(delay.isLongerThan(Duration.ZERO), "Negative duration is not supported."); + checkArgument(!delay.isNegative(), "Negative duration is not supported."); return Task.newBuilder(createTask(path, method, service, params)) - .setScheduleTime(Timestamps.fromMillis(clock.nowUtc().plus(delay).getMillis())) + .setScheduleTime(Timestamps.fromMillis(clock.now().plus(delay).toEpochMilli())) .build(); } diff --git a/core/src/main/java/google/registry/batch/DeleteExpiredDomainsAction.java b/core/src/main/java/google/registry/batch/DeleteExpiredDomainsAction.java index e97e22e55..9893f4236 100644 --- a/core/src/main/java/google/registry/batch/DeleteExpiredDomainsAction.java +++ b/core/src/main/java/google/registry/batch/DeleteExpiredDomainsAction.java @@ -42,11 +42,11 @@ import google.registry.request.auth.Auth; import google.registry.request.lock.LockHandler; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.concurrent.Callable; import java.util.logging.Level; -import org.joda.time.Duration; /** * An action that deletes all non-renewing domains whose expiration dates have now passed. @@ -116,7 +116,7 @@ public class DeleteExpiredDomainsAction implements Runnable { return null; }; - if (!lockHandler.executeWithLocks(runner, null, Duration.standardHours(1), LOCK_NAME)) { + if (!lockHandler.executeWithLocks(runner, null, Duration.ofHours(1), LOCK_NAME)) { // Send a 200-series status code to prevent this conflicting action from retrying. response.setStatus(SC_NO_CONTENT); response.setPayload("Could not acquire lock; already running?"); diff --git a/core/src/main/java/google/registry/batch/DeleteLoadTestDataAction.java b/core/src/main/java/google/registry/batch/DeleteLoadTestDataAction.java index 7410f5208..93d40ac66 100644 --- a/core/src/main/java/google/registry/batch/DeleteLoadTestDataAction.java +++ b/core/src/main/java/google/registry/batch/DeleteLoadTestDataAction.java @@ -115,7 +115,7 @@ public class DeleteLoadTestDataAction implements Runnable { VKey hostVKey = host.createVKey(); // We can remove hosts from linked domains, so we should do so then delete the hosts ImmutableSet> linkedDomains = - EppResourceUtils.getLinkedDomainKeys(hostVKey, clock.nowUtc(), null); + EppResourceUtils.getLinkedDomainKeys(hostVKey, clock.now(), null); tm().loadByKeys(linkedDomains) .values() .forEach( diff --git a/core/src/main/java/google/registry/batch/DeleteProberDataAction.java b/core/src/main/java/google/registry/batch/DeleteProberDataAction.java index 030267201..8b946dfa9 100644 --- a/core/src/main/java/google/registry/batch/DeleteProberDataAction.java +++ b/core/src/main/java/google/registry/batch/DeleteProberDataAction.java @@ -218,7 +218,7 @@ public class DeleteProberDataAction implements Runnable { // successfully soft-delete the domain (thus leaving its DNS entry published). We soft-delete // it now so that the DNS entry can be handled. The domain will then be hard-deleted the next // time the job is run. - if (EppResourceUtils.isActive(domain, tm().getTransactionTime())) { + if (EppResourceUtils.isActive(domain, tm().getTxTime())) { if (isDryRun) { logger.atInfo().log( "Would soft-delete the active domain: %s (%s).", diff --git a/core/src/main/java/google/registry/batch/ExpandBillingRecurrencesAction.java b/core/src/main/java/google/registry/batch/ExpandBillingRecurrencesAction.java index 407da87dc..2f521e5a3 100644 --- a/core/src/main/java/google/registry/batch/ExpandBillingRecurrencesAction.java +++ b/core/src/main/java/google/registry/batch/ExpandBillingRecurrencesAction.java @@ -111,7 +111,7 @@ public class ExpandBillingRecurrencesAction implements Runnable { () -> tm().loadByKeyIfPresent(Cursor.createGlobalVKey(RECURRING_BILLING)) .orElse(Cursor.createGlobal(RECURRING_BILLING, START_INSTANT)) - .getCursorTimeInstant())); + .getCursorTime())); checkArgument( startTime.isBefore(endTime), "Start time (%s) must be before end time (%s)", diff --git a/core/src/main/java/google/registry/batch/RelockDomainAction.java b/core/src/main/java/google/registry/batch/RelockDomainAction.java index 30dba926c..278ba785a 100644 --- a/core/src/main/java/google/registry/batch/RelockDomainAction.java +++ b/core/src/main/java/google/registry/batch/RelockDomainAction.java @@ -18,6 +18,8 @@ import static com.google.common.base.Preconditions.checkArgument; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.request.Action.Method.POST; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; +import static google.registry.util.DateTimeUtils.isAtOrAfter; +import static google.registry.util.DateTimeUtils.toJodaDuration; import static jakarta.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static jakarta.servlet.http.HttpServletResponse.SC_OK; @@ -36,13 +38,12 @@ import google.registry.request.Parameter; import google.registry.request.Response; import google.registry.request.auth.Auth; import google.registry.tools.DomainLockUtils; -import google.registry.util.DateTimeUtils; import google.registry.util.EmailMessage; import jakarta.inject.Inject; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; import java.util.Optional; -import org.joda.time.Duration; /** Task that re-locks a previously-Registry-Locked domain after a predetermined period of time. */ @Action( @@ -59,8 +60,8 @@ public class RelockDomainAction implements Runnable { static final int ATTEMPTS_BEFORE_SLOWDOWN = 36; // every ten minutes for six hours then every hour static final int FAILURES_BEFORE_EMAIL = 2; // email after three failures, one half hour - private static final Duration TEN_MINUTES = Duration.standardMinutes(10); - private static final Duration ONE_HOUR = Duration.standardHours(1); + private static final Duration TEN_MINUTES = Duration.ofMinutes(10); + private static final Duration ONE_HOUR = Duration.ofHours(1); private static final String RELOCK_SUCCESS_EMAIL_TEMPLATE = """ @@ -188,7 +189,7 @@ public class RelockDomainAction implements Runnable { "Domain %s has a pending delete.", domainName); checkArgument( - !DateTimeUtils.isAtOrAfter(tm().getTxTime(), domain.getDeletionTime()), + !isAtOrAfter(tm().getTxTime(), domain.getDeletionTime()), "Domain %s has been deleted.", domainName); checkArgument( @@ -237,7 +238,8 @@ public class RelockDomainAction implements Runnable { } } Duration timeBeforeRetry = previousAttempts < ATTEMPTS_BEFORE_SLOWDOWN ? TEN_MINUTES : ONE_HOUR; - domainLockUtils.enqueueDomainRelock(timeBeforeRetry, oldUnlockRevisionId, previousAttempts + 1); + domainLockUtils.enqueueDomainRelock( + toJodaDuration(timeBeforeRetry), oldUnlockRevisionId, previousAttempts + 1); } private void sendSuccessEmail(RegistryLock oldLock) { diff --git a/core/src/main/java/google/registry/batch/ResaveEntityAction.java b/core/src/main/java/google/registry/batch/ResaveEntityAction.java index 0097c9bd6..0e4ea56ca 100644 --- a/core/src/main/java/google/registry/batch/ResaveEntityAction.java +++ b/core/src/main/java/google/registry/batch/ResaveEntityAction.java @@ -30,8 +30,8 @@ import google.registry.request.Parameter; import google.registry.request.Response; import google.registry.request.auth.Auth; import jakarta.inject.Inject; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** * An action that re-saves a given entity, typically after a certain amount of time has passed. @@ -50,16 +50,16 @@ public class ResaveEntityAction implements Runnable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String resourceKey; - private final DateTime requestedTime; - private final ImmutableSortedSet resaveTimes; + private final Instant requestedTime; + private final ImmutableSortedSet resaveTimes; private final AsyncTaskEnqueuer asyncTaskEnqueuer; private final Response response; @Inject ResaveEntityAction( @Parameter(PARAM_RESOURCE_KEY) String resourceKey, - @Parameter(PARAM_REQUESTED_TIME) DateTime requestedTime, - @Parameter(PARAM_RESAVE_TIMES) ImmutableSet resaveTimes, + @Parameter(PARAM_REQUESTED_TIME) Instant requestedTime, + @Parameter(PARAM_RESAVE_TIMES) ImmutableSet resaveTimes, AsyncTaskEnqueuer asyncTaskEnqueuer, Response response) { this.resourceKey = resourceKey; diff --git a/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java b/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java index 1e37272c0..f789aa802 100644 --- a/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java +++ b/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java @@ -17,8 +17,8 @@ package google.registry.batch; import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; +import static java.time.ZoneOffset.UTC; import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; import static org.apache.http.HttpStatus.SC_OK; @@ -43,11 +43,10 @@ import google.registry.util.EmailMessage; import jakarta.inject.Inject; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.Instant; +import java.time.format.DateTimeFormatter; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; /** An action that sends notification emails to registrars whose certificates are expiring soon. */ @Action( @@ -57,6 +56,7 @@ import org.joda.time.format.DateTimeFormatter; public class SendExpiringCertificateNotificationEmailAction implements Runnable { public static final String PATH = "/_dr/task/sendExpiringCertificateNotificationEmail"; + /** * Used as an offset when storing the last notification email sent date. * @@ -65,10 +65,11 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable * next day at 2am, the date difference will be less than a day, which will lead to the date * difference between two successive email sent date being the expected email interval days + 1; */ - protected static final Duration UPDATE_TIME_OFFSET = Duration.standardMinutes(10); + protected static final Duration UPDATE_TIME_OFFSET = Duration.ofMinutes(10); private static final FluentLogger logger = FluentLogger.forEnclosingClass(); - private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd"); + private static final DateTimeFormatter DATE_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(UTC); private final CertificateChecker certificateChecker; private final String expirationWarningEmailBodyText; @@ -149,19 +150,19 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable @VisibleForTesting boolean sendNotificationEmail( Registrar registrar, - DateTime lastExpiringCertNotificationSentDate, + Instant lastExpiringCertNotificationSentDate, CertificateType certificateType, Optional certificate) { if (certificate.isEmpty() || !certificateChecker.shouldReceiveExpiringNotification( - lastExpiringCertNotificationSentDate, certificate.get())) { + toDateTime(lastExpiringCertNotificationSentDate), certificate.get())) { return false; } try { ImmutableSet recipients = getEmailAddresses(registrar, Type.TECH); ImmutableSet ccs = getEmailAddresses(registrar, Type.ADMIN); - DateTime expirationDate = - new DateTime(certificateChecker.getCertificate(certificate.get()).getNotAfter()); + Instant expirationDate = + certificateChecker.getCertificate(certificate.get()).getNotAfter().toInstant(); logger.atInfo().log( " %s SSL certificate of registrar '%s' will expire on %s.", certificateType.getDisplayName(), registrar.getRegistrarName(), expirationDate); @@ -190,9 +191,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable * for applicable certificate. */ updateLastNotificationSentDate( - registrar, - clock.nowUtc().minusMinutes((int) UPDATE_TIME_OFFSET.getStandardMinutes()), - certificateType); + registrar, clock.now().minus(UPDATE_TIME_OFFSET), certificateType); return true; } catch (Exception e) { throw new RuntimeException( @@ -205,29 +204,29 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable /** Updates the last notification sent date in database. */ @VisibleForTesting void updateLastNotificationSentDate( - Registrar registrar, DateTime now, CertificateType certificateType) { + Registrar registrar, Instant now, CertificateType certificateType) { try { tm().transact( () -> { Registrar.Builder newRegistrar = tm().loadByEntity(registrar).asBuilder(); switch (certificateType) { case PRIMARY -> { - newRegistrar.setLastExpiringCertNotificationSentDate(toInstant(now)); + newRegistrar.setLastExpiringCertNotificationSentDate(now); tm().put(newRegistrar.build()); logger.atInfo().log( "Updated last notification email sent date to %s for %s certificate of " + "registrar %s.", - DATE_FORMATTER.print(now), + DATE_FORMATTER.format(now), certificateType.getDisplayName(), registrar.getRegistrarName()); } case FAILOVER -> { - newRegistrar.setLastExpiringFailoverCertNotificationSentDate(toInstant(now)); + newRegistrar.setLastExpiringFailoverCertNotificationSentDate(now); tm().put(newRegistrar.build()); logger.atInfo().log( "Updated last notification email sent date to %s for %s certificate of " + "registrar %s.", - DATE_FORMATTER.print(now), + DATE_FORMATTER.format(now), certificateType.getDisplayName(), registrar.getRegistrarName()); } @@ -257,7 +256,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable if (registrarInfo.isCertExpiring() && sendNotificationEmail( registrar, - toDateTime(registrar.getLastExpiringCertNotificationSentDate()), + registrar.getLastExpiringCertNotificationSentDate(), CertificateType.PRIMARY, registrar.getClientCertificate())) { numEmailsSent++; @@ -265,7 +264,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable if (registrarInfo.isFailOverCertExpiring() && sendNotificationEmail( registrar, - toDateTime(registrar.getLastExpiringFailoverCertNotificationSentDate()), + registrar.getLastExpiringFailoverCertNotificationSentDate(), CertificateType.FAILOVER, registrar.getFailoverClientCertificate())) { numEmailsSent++; @@ -300,7 +299,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable @VisibleForTesting @SuppressWarnings("lgtm[java/dereferenced-value-may-be-null]") String getEmailBody( - String registrarName, CertificateType type, DateTime expirationDate, String registrarId) { + String registrarName, CertificateType type, Instant expirationDate, String registrarId) { checkArgumentNotNull(expirationDate, "Expiration date cannot be null"); checkArgumentNotNull(type, "Certificate type cannot be null"); checkArgumentNotNull(registrarId, "Registrar Id cannot be null"); @@ -308,7 +307,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable expirationWarningEmailBodyText, registrarName, type.getDisplayName(), - DATE_FORMATTER.print(expirationDate), + DATE_FORMATTER.format(expirationDate), registrarId); } diff --git a/core/src/main/java/google/registry/batch/SyncRemoteCacheAction.java b/core/src/main/java/google/registry/batch/SyncRemoteCacheAction.java index a49491c0f..8877ac482 100644 --- a/core/src/main/java/google/registry/batch/SyncRemoteCacheAction.java +++ b/core/src/main/java/google/registry/batch/SyncRemoteCacheAction.java @@ -40,12 +40,12 @@ import google.registry.request.Response; import google.registry.request.auth.Auth; import google.registry.request.lock.LockHandler; import jakarta.inject.Inject; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; import java.util.function.Function; -import org.joda.time.Duration; @Action( service = Action.Service.BACKEND, @@ -99,7 +99,7 @@ public class SyncRemoteCacheAction implements Runnable { return null; }; - if (!lockHandler.executeWithLocks(runner, null, Duration.standardHours(1), LOCK_NAME)) { + if (!lockHandler.executeWithLocks(runner, null, Duration.ofHours(1), LOCK_NAME)) { // Send a 200-series status code to prevent this conflicting action from retrying. response.setStatus(SC_NO_CONTENT); response.setPayload("Could not acquire lock; already running?"); @@ -184,7 +184,7 @@ public class SyncRemoteCacheAction implements Runnable { private Instant getPreviousCursorTime(Cursor.CursorType cursorType) { return tm().loadByKeyIfPresent(Cursor.createGlobalVKey(cursorType)) - .map(Cursor::getCursorTimeInstant) + .map(Cursor::getCursorTime) .orElse(START_INSTANT); } diff --git a/core/src/main/java/google/registry/beam/BeamUtils.java b/core/src/main/java/google/registry/beam/BeamUtils.java index b913c6391..0219894f1 100644 --- a/core/src/main/java/google/registry/beam/BeamUtils.java +++ b/core/src/main/java/google/registry/beam/BeamUtils.java @@ -15,6 +15,7 @@ package google.registry.beam; import static com.google.common.base.Preconditions.checkArgument; +import static google.registry.util.DateTimeUtils.LOWERCASE_TIMESTAMP_FORMATTER; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; @@ -61,7 +62,7 @@ public class BeamUtils { // with a letter and ending with a letter or number. So we replace the "T" and "Z" in ISO 8601 // with lowercase letters. String jobName = - String.format("%s-%s", prefix, clock.nowUtc().toString("yyyy-MM-dd't'HH-mm-ss'z'")); + String.format("%s-%s", prefix, LOWERCASE_TIMESTAMP_FORMATTER.format(clock.now())); checkArgument( Pattern.compile("^[a-z][-a-z0-9]*[a-z0-9]*").matcher(jobName).matches(), "The job name %s is illegal, it consists of only characters [-a-z0-9], " diff --git a/core/src/main/java/google/registry/beam/billing/BillingEvent.java b/core/src/main/java/google/registry/beam/billing/BillingEvent.java index 8cde9d6f4..02b1dd724 100644 --- a/core/src/main/java/google/registry/beam/billing/BillingEvent.java +++ b/core/src/main/java/google/registry/beam/billing/BillingEvent.java @@ -14,6 +14,7 @@ package google.registry.beam.billing; +import static java.time.ZoneOffset.UTC; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; @@ -22,7 +23,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.time.Instant; -import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.regex.Pattern; @@ -70,7 +70,7 @@ public record BillingEvent( String flags) { private static final DateTimeFormatter DATE_TIME_FORMATTER = - DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC); + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(UTC); private static final Pattern SYNTHETIC_REGEX = Pattern.compile("SYNTHETIC", Pattern.LITERAL); @@ -164,13 +164,10 @@ public record BillingEvent( /** Returns the grouping key for this {@code BillingEvent}, to generate the overall invoice. */ InvoiceGroupingKey getInvoiceGroupingKey() { return new InvoiceGroupingKey( - ZonedDateTime.ofInstant(billingTime(), ZoneOffset.UTC) - .toLocalDate() - .withDayOfMonth(1) - .toString(), + ZonedDateTime.ofInstant(billingTime(), UTC).toLocalDate().withDayOfMonth(1).toString(), years() == 0 ? "" - : ZonedDateTime.ofInstant(billingTime(), ZoneOffset.UTC) + : ZonedDateTime.ofInstant(billingTime(), UTC) .toLocalDate() .withDayOfMonth(1) .plusYears(years()) diff --git a/core/src/main/java/google/registry/beam/billing/ExpandBillingRecurrencesPipeline.java b/core/src/main/java/google/registry/beam/billing/ExpandBillingRecurrencesPipeline.java index 3ec62f140..2698d1163 100644 --- a/core/src/main/java/google/registry/beam/billing/ExpandBillingRecurrencesPipeline.java +++ b/core/src/main/java/google/registry/beam/billing/ExpandBillingRecurrencesPipeline.java @@ -445,7 +445,7 @@ public class ExpandBillingRecurrencesPipeline implements Serializable { Cursor.createGlobalVKey(RECURRING_BILLING)) .orElse( Cursor.createGlobal(RECURRING_BILLING, START_INSTANT)) - .getCursorTimeInstant(); + .getCursorTime(); if (!currentCursorTime.equals(startTime)) { throw new IllegalStateException( String.format( diff --git a/core/src/main/java/google/registry/beam/rde/RdeIO.java b/core/src/main/java/google/registry/beam/rde/RdeIO.java index b1c374469..f772ee99d 100644 --- a/core/src/main/java/google/registry/beam/rde/RdeIO.java +++ b/core/src/main/java/google/registry/beam/rde/RdeIO.java @@ -56,6 +56,8 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.security.Security; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.transforms.DoFn; @@ -66,8 +68,6 @@ import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PDone; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; -import org.joda.time.Duration; public class RdeIO { @@ -163,7 +163,7 @@ public class RdeIO { // Determine some basic things about the deposit. final RdeMode mode = key.mode(); final String tld = key.tld(); - final DateTime watermark = key.watermark(); + final Instant watermark = key.watermark(); final int revision = Optional.ofNullable(key.revision()) .orElseGet(() -> RdeRevision.getNextRevision(tld, watermark, mode)); @@ -259,7 +259,7 @@ public class RdeIO { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final long serialVersionUID = 5822176227753327224L; - private static final Duration ENQUEUE_DELAY = Duration.standardMinutes(1); + private static final Duration ENQUEUE_DELAY = Duration.ofMinutes(1); private final CloudTasksUtils cloudTasksUtils; @@ -276,9 +276,9 @@ public class RdeIO { Tld tld = Tld.get(key.tld()); Optional cursor = tm().loadByKeyIfPresent(Cursor.createScopedVKey(key.cursor(), tld)); - DateTime position = getCursorTimeOrStartOfTime(cursor); + Instant position = getCursorTimeOrStartOfTime(cursor); checkState(key.interval() != null, "Interval must be present"); - DateTime newPosition = key.watermark().plus(key.interval()); + Instant newPosition = key.watermark().plus(key.interval()); if (!position.isBefore(newPosition)) { logger.atWarning().log("Cursor has already been rolled forward."); return; diff --git a/core/src/main/java/google/registry/beam/rde/RdePipeline.java b/core/src/main/java/google/registry/beam/rde/RdePipeline.java index 69125b746..4bc20aeb7 100644 --- a/core/src/main/java/google/registry/beam/rde/RdePipeline.java +++ b/core/src/main/java/google/registry/beam/rde/RdePipeline.java @@ -27,7 +27,6 @@ import static google.registry.beam.rde.RdePipeline.TupleTags.REVISION_ID; import static google.registry.beam.rde.RdePipeline.TupleTags.SUPERORDINATE_DOMAINS; import static google.registry.model.reporting.HistoryEntryDao.RESOURCE_TYPES_TO_HISTORY_TYPES; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toInstant; import static google.registry.util.SafeSerializationUtils.safeDeserializeCollection; import static google.registry.util.SafeSerializationUtils.serializeCollection; import static google.registry.util.SerializeUtils.decodeBase64; @@ -72,6 +71,7 @@ import jakarta.inject.Inject; import jakarta.inject.Singleton; import java.io.IOException; import java.io.Serializable; +import java.time.Instant; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.coders.KvCoder; @@ -97,7 +97,6 @@ import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; import org.apache.beam.sdk.values.TypeDescriptor; -import org.joda.time.DateTime; /** * Definition of a Dataflow Flex template, which generates RDE/BRDA deposits. @@ -171,7 +170,7 @@ public class RdePipeline implements Serializable { private final transient RdePipelineOptions options; private final ValidationMode mode; private final ImmutableSet pendingDeposits; - private final DateTime watermark; + private final Instant watermark; private final String rdeBucket; private final byte[] stagingKeyBytes; private final GcsUtils gcsUtils; @@ -190,7 +189,7 @@ public class RdePipeline implements Serializable { this.options = options; this.mode = ValidationMode.valueOf(options.getValidationMode()); this.pendingDeposits = decodePendingDeposits(options.getPendings()); - ImmutableSet potentialWatermarks = + ImmutableSet potentialWatermarks = pendingDeposits.stream() .map(PendingDeposit::watermark) .distinct() @@ -324,7 +323,7 @@ public class RdePipeline implements Serializable { ? "AND resource.tld IN " + "(SELECT id FROM Tld WHERE tldType = 'REAL')" : "")) .replace("%entity%", historyClass.getSimpleName()), - ImmutableMap.of("watermark", toInstant(watermark)), + ImmutableMap.of("watermark", watermark), Object[].class, row -> KV.of((String) row[0], (long) row[1])) .withCoder(KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of()))); @@ -365,7 +364,7 @@ public class RdePipeline implements Serializable { tm().loadByKey( VKey.create(historyEntryClazz, new HistoryEntryId(repoId, revisionId)))) .getResourceAtPointInTime() - .map(resource -> resource.cloneProjectedAtTime(toInstant(watermark))) + .map(resource -> resource.cloneProjectedAtTime(watermark)) .get(); } diff --git a/core/src/main/java/google/registry/beam/resave/ResaveAllEppResourcesPipeline.java b/core/src/main/java/google/registry/beam/resave/ResaveAllEppResourcesPipeline.java index 245eaac26..88995a229 100644 --- a/core/src/main/java/google/registry/beam/resave/ResaveAllEppResourcesPipeline.java +++ b/core/src/main/java/google/registry/beam/resave/ResaveAllEppResourcesPipeline.java @@ -103,7 +103,7 @@ public class ResaveAllEppResourcesPipeline implements Serializable { * transfers, grace periods). * *

The logic of what might have changed is paraphrased from {@link - * DomainBase#cloneProjectedAtTime(DateTime)}. + * DomainBase#cloneProjectedAtTime(Instant)}. */ private void fastResaveDomains(Pipeline pipeline) { Read repoIdRead = diff --git a/core/src/main/java/google/registry/beam/spec11/SafeBrowsingTransforms.java b/core/src/main/java/google/registry/beam/spec11/SafeBrowsingTransforms.java index b984af286..2a177679c 100644 --- a/core/src/main/java/google/registry/beam/spec11/SafeBrowsingTransforms.java +++ b/core/src/main/java/google/registry/beam/spec11/SafeBrowsingTransforms.java @@ -14,6 +14,7 @@ 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; @@ -22,7 +23,6 @@ import com.google.common.collect.ImmutableSet; import com.google.common.flogger.FluentLogger; import com.google.common.io.CharStreams; import google.registry.util.Clock; -import google.registry.util.DateTimeUtils; import google.registry.util.Retrier; import java.io.IOException; import java.io.InputStreamReader; @@ -132,9 +132,7 @@ public class SafeBrowsingTransforms { if (!domainNameInfoBuffer.isEmpty()) { ImmutableSet> results = evaluateAndFlush(); results.forEach( - (kv) -> - context.output( - kv, DateTimeUtils.toJodaInstant(clock.now()), GlobalWindow.INSTANCE)); + (kv) -> context.output(kv, toJodaInstant(clock.now()), GlobalWindow.INSTANCE)); } } diff --git a/core/src/main/java/google/registry/bigquery/BigqueryConnection.java b/core/src/main/java/google/registry/bigquery/BigqueryConnection.java index d001645f8..a401f147e 100644 --- a/core/src/main/java/google/registry/bigquery/BigqueryConnection.java +++ b/core/src/main/java/google/registry/bigquery/BigqueryConnection.java @@ -64,19 +64,19 @@ import google.registry.util.SqlTemplate; import google.registry.util.SystemSleeper; import jakarta.inject.Inject; import java.io.IOException; +import java.time.Duration; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import javax.annotation.Nullable; -import org.joda.time.Duration; /** Class encapsulating parameters and state for accessing the Bigquery API. */ public class BigqueryConnection implements AutoCloseable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); - private static final Duration MIN_POLL_INTERVAL = Duration.millis(500); + private static final Duration MIN_POLL_INTERVAL = Duration.ofMillis(500); @NonFinalForTesting private static Sleeper sleeper = new SystemSleeper(); @@ -88,7 +88,7 @@ public class BigqueryConnection implements AutoCloseable { private static final String TEMP_DATASET_NAME = "__temp__"; /** Default time to live for temporary tables. */ - private static final Duration TEMP_TABLE_TTL = Duration.standardHours(24); + private static final Duration TEMP_TABLE_TTL = Duration.ofHours(24); /** Bigquery client instance wrapped by this class. */ private final Bigquery bigquery; @@ -109,7 +109,7 @@ public class BigqueryConnection implements AutoCloseable { private boolean overwrite = false; /** Duration to wait between polls for job status. */ - private Duration pollInterval = Duration.millis(1000); + private Duration pollInterval = Duration.ofSeconds(1); BigqueryConnection(Bigquery bigquery, Clock clock) { this.bigquery = bigquery; @@ -146,9 +146,9 @@ public class BigqueryConnection implements AutoCloseable { public Builder setPollInterval(Duration pollInterval) { checkArgument( - !pollInterval.isShorterThan(MIN_POLL_INTERVAL), + pollInterval.compareTo(MIN_POLL_INTERVAL) >= 0, "poll interval must be at least %s ms", - MIN_POLL_INTERVAL.getMillis()); + MIN_POLL_INTERVAL.toMillis()); instance.pollInterval = pollInterval; return this; } @@ -225,7 +225,7 @@ public class BigqueryConnection implements AutoCloseable { } public Builder timeToLive(Duration duration) { - this.table.setExpirationTime(clock.nowUtc().plus(duration).getMillis()); + this.table.setExpirationTime(clock.now().plus(duration).toEpochMilli()); return this; } diff --git a/core/src/main/java/google/registry/bigquery/BigqueryUtils.java b/core/src/main/java/google/registry/bigquery/BigqueryUtils.java index ad88fcd8d..bbd1e2ada 100644 --- a/core/src/main/java/google/registry/bigquery/BigqueryUtils.java +++ b/core/src/main/java/google/registry/bigquery/BigqueryUtils.java @@ -14,13 +14,16 @@ package google.registry.bigquery; +import static java.time.ZoneOffset.UTC; +import static java.time.temporal.ChronoUnit.MICROS; + import com.google.api.services.bigquery.model.JobReference; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.SignStyle; +import java.time.temporal.ChronoField; import java.util.concurrent.TimeUnit; -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; /** Utilities related to Bigquery. */ public class BigqueryUtils { @@ -67,47 +70,56 @@ public class BigqueryUtils { * *

The general format definition is "YYYY-MM-DD HH:MM:SS.SSS[ ZZ]", where the fractional * seconds portion can have 0-6 decimal places (although we restrict it to 0-3 here since Joda - * DateTime only supports up to millisecond precision) and the zone if not specified defaults to + * Instant only supports up to millisecond precision) and the zone if not specified defaults to * UTC. * *

Although we expect a zone specification of "UTC" when parsing, we don't emit it when * printing because in some cases BigQuery does not allow any time zone specification (instead it * assumes UTC for whatever input you provide) for input timestamp strings (see b/16380363). * - * @see - * BigQuery Data Types - TIMESTAMP + * @see BigQuery Data Types + * - TIMESTAMP */ - public static final DateTimeFormatter BIGQUERY_TIMESTAMP_FORMAT = new DateTimeFormatterBuilder() - .append(ISODateTimeFormat.date()) - .appendLiteral(' ') - .append( - // For printing, always print out the milliseconds. - ISODateTimeFormat.hourMinuteSecondMillis().getPrinter(), - // For parsing, we need a series of parsers to correctly handle the milliseconds. - new DateTimeParser[] { - // Try to parse the time with milliseconds first, which requires at least one - // fractional second digit, and if that fails try to parse without milliseconds. - ISODateTimeFormat.hourMinuteSecondMillis().getParser(), - ISODateTimeFormat.hourMinuteSecond().getParser()}) - // Print UTC as the empty string since BigQuery's TIMESTAMP() function does not accept any - // time zone specification, but require "UTC" on parsing. Since we force this formatter to - // always use UTC below, the other arguments do not matter. If b/16380363 ever gets resolved - // this could be simplified to appendLiteral(" UTC"). - .appendTimeZoneOffset("", " UTC", false, 1, 1) - .toFormatter() - .withZoneUTC(); + private static final DateTimeFormatter BIGQUERY_TIMESTAMP_PARSER = + new DateTimeFormatterBuilder() + .appendValue(ChronoField.YEAR, 4, 10, SignStyle.NOT_NEGATIVE) + .appendLiteral('-') + .appendValue(ChronoField.MONTH_OF_YEAR, 2) + .appendLiteral('-') + .appendValue(ChronoField.DAY_OF_MONTH, 2) + .appendLiteral(' ') + .appendPattern("HH:mm:ss") + .optionalStart() + .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true) + .optionalEnd() + .appendLiteral(" UTC") + .toFormatter() + .withZone(UTC); + + private static final DateTimeFormatter BIGQUERY_TIMESTAMP_PRINTER = + new DateTimeFormatterBuilder() + .appendValue(ChronoField.YEAR, 4, 10, SignStyle.NOT_NEGATIVE) + .appendLiteral('-') + .appendValue(ChronoField.MONTH_OF_YEAR, 2) + .appendLiteral('-') + .appendValue(ChronoField.DAY_OF_MONTH, 2) + .appendLiteral(' ') + .appendPattern("HH:mm:ss") + .appendFraction(ChronoField.MILLI_OF_SECOND, 3, 3, true) + .toFormatter() + .withZone(UTC); /** - * Returns the human-readable string version of the given DateTime, suitable for conversion - * within BigQuery from a string literal into a BigQuery timestamp type. + * Returns the human-readable string version of the given Instant, suitable for conversion within + * BigQuery from a string literal into a BigQuery timestamp type. */ - public static String toBigqueryTimestampString(DateTime dateTime) { - return BIGQUERY_TIMESTAMP_FORMAT.print(dateTime); + public static String toBigqueryTimestampString(Instant dateTime) { + return BIGQUERY_TIMESTAMP_PRINTER.format(dateTime); } - /** Returns the DateTime for a given human-readable string-formatted BigQuery timestamp. */ - public static DateTime fromBigqueryTimestampString(String timestampString) { - return BIGQUERY_TIMESTAMP_FORMAT.parseDateTime(timestampString); + /** Returns the Instant for a given human-readable string-formatted BigQuery timestamp. */ + public static Instant fromBigqueryTimestampString(String timestampString) { + return BIGQUERY_TIMESTAMP_PARSER.parse(timestampString, Instant::from); } /** @@ -123,15 +135,16 @@ public class BigqueryUtils { } /** - * Converts a {@link DateTime} into a numeric string that BigQuery understands as a timestamp: - * the decimal number of seconds since the epoch, precise up to microseconds. + * Converts a time into a numeric string that BigQuery understands as a timestamp: the decimal + * number of seconds since the epoch, precise up to microseconds. * - *

Note that since {@code DateTime} only stores milliseconds, the last 3 digits will be zero. + *

Note that while {@code Instant} supports nanosecond precision, BigQuery only supports + * microsecond precision, so the sub-microsecond precision is truncated. * * @see Data Types */ - public static String toBigqueryTimestamp(DateTime dateTime) { - return toBigqueryTimestamp(dateTime.getMillis(), TimeUnit.MILLISECONDS); + public static String toBigqueryTimestamp(Instant dateTime) { + return toBigqueryTimestamp(MICROS.between(Instant.EPOCH, dateTime), TimeUnit.MICROSECONDS); } /** diff --git a/core/src/main/java/google/registry/bsa/BsaDownloadAction.java b/core/src/main/java/google/registry/bsa/BsaDownloadAction.java index e33268498..967974f26 100644 --- a/core/src/main/java/google/registry/bsa/BsaDownloadAction.java +++ b/core/src/main/java/google/registry/bsa/BsaDownloadAction.java @@ -116,7 +116,7 @@ public class BsaDownloadAction implements Runnable { Void runWithinLock() { // Cannot enroll new TLDs after download starts. This may change if b/309175410 is fixed. - if (!Tlds.hasActiveBsaEnrollment(clock.nowUtc())) { + if (!Tlds.hasActiveBsaEnrollment(clock.now())) { logger.atInfo().log("No TLDs enrolled with BSA. Quitting."); return null; } @@ -179,9 +179,7 @@ public class BsaDownloadAction implements Runnable { gcsClient.writeUnblockableDomains( schedule.jobName(), batches - .map( - batch -> - applyLabelDiff(batch, lazyIdnChecker.get(), schedule, clock.nowUtc())) + .map(batch -> applyLabelDiff(batch, lazyIdnChecker.get(), schedule, clock.now())) .flatMap(ImmutableList::stream)); } schedule.updateJobStage(DownloadStage.REPORT_START_OF_ORDER_PROCESSING); diff --git a/core/src/main/java/google/registry/bsa/BsaLock.java b/core/src/main/java/google/registry/bsa/BsaLock.java index aa5d498c0..d6b80756d 100644 --- a/core/src/main/java/google/registry/bsa/BsaLock.java +++ b/core/src/main/java/google/registry/bsa/BsaLock.java @@ -17,8 +17,8 @@ package google.registry.bsa; import google.registry.config.RegistryConfig.Config; import google.registry.request.lock.LockHandler; import jakarta.inject.Inject; +import java.time.Duration; import java.util.concurrent.Callable; -import org.joda.time.Duration; /** Helper for guarding all BSA related work with a common lock. */ public class BsaLock { diff --git a/core/src/main/java/google/registry/bsa/BsaRefreshAction.java b/core/src/main/java/google/registry/bsa/BsaRefreshAction.java index 3fd6df3af..57ff6f252 100644 --- a/core/src/main/java/google/registry/bsa/BsaRefreshAction.java +++ b/core/src/main/java/google/registry/bsa/BsaRefreshAction.java @@ -67,7 +67,7 @@ public class BsaRefreshAction implements Runnable { GcsClient gcsClient, BsaReportSender bsaReportSender, @Config("bsaTxnBatchSize") int transactionBatchSize, - @Config("domainCreateTxnCommitTimeLag") org.joda.time.Duration domainCreateTxnCommitTimeLag, + @Config("domainCreateTxnCommitTimeLag") Duration domainCreateTxnCommitTimeLag, BsaEmailSender emailSender, BsaLock bsaLock, Clock clock, @@ -76,7 +76,7 @@ public class BsaRefreshAction implements Runnable { this.gcsClient = gcsClient; this.bsaReportSender = bsaReportSender; this.transactionBatchSize = transactionBatchSize; - this.domainCreateTxnCommitTimeLag = Duration.ofMillis(domainCreateTxnCommitTimeLag.getMillis()); + this.domainCreateTxnCommitTimeLag = domainCreateTxnCommitTimeLag; this.emailSender = emailSender; this.bsaLock = bsaLock; this.clock = clock; diff --git a/core/src/main/java/google/registry/bsa/BsaValidateAction.java b/core/src/main/java/google/registry/bsa/BsaValidateAction.java index 87f5cbaee..1032b9d15 100644 --- a/core/src/main/java/google/registry/bsa/BsaValidateAction.java +++ b/core/src/main/java/google/registry/bsa/BsaValidateAction.java @@ -88,14 +88,14 @@ public class BsaValidateAction implements Runnable { IdnChecker idnChecker, BsaEmailSender emailSender, @Config("bsaTxnBatchSize") int transactionBatchSize, - @Config("bsaValidationMaxStaleness") org.joda.time.Duration maxStaleness, + @Config("bsaValidationMaxStaleness") Duration maxStaleness, Clock clock, Response response) { this.gcsClient = gcsClient; this.idnChecker = idnChecker; this.emailSender = emailSender; this.transactionBatchSize = transactionBatchSize; - this.maxStaleness = Duration.ofMillis(maxStaleness.getMillis()); + this.maxStaleness = maxStaleness; this.clock = clock; this.response = response; } diff --git a/core/src/main/java/google/registry/bsa/IdnChecker.java b/core/src/main/java/google/registry/bsa/IdnChecker.java index 4a478119d..10e4f9044 100644 --- a/core/src/main/java/google/registry/bsa/IdnChecker.java +++ b/core/src/main/java/google/registry/bsa/IdnChecker.java @@ -29,7 +29,7 @@ import google.registry.tldconfig.idn.IdnLabelValidator; import google.registry.tldconfig.idn.IdnTableEnum; import google.registry.util.Clock; import jakarta.inject.Inject; -import org.joda.time.DateTime; +import java.time.Instant; /** * Checks labels' validity wrt Idns in TLDs enrolled with BSA. @@ -45,7 +45,7 @@ public class IdnChecker { @Inject IdnChecker(Clock clock) { - this.idnToTlds = getIdnToTldMap(clock.nowUtc()); + this.idnToTlds = getIdnToTldMap(clock.now()); allTlds = idnToTlds.values().stream().flatMap(ImmutableSet::stream).collect(toImmutableSet()); } @@ -79,7 +79,7 @@ public class IdnChecker { return Sets.difference(allTlds, getSupportingTlds(idnTables)).immutableCopy(); } - private static ImmutableMap> getIdnToTldMap(DateTime now) { + private static ImmutableMap> getIdnToTldMap(Instant now) { var idnToTldMap = new ImmutableMultimap.Builder(); Tlds.getTldEntitiesOfType(TldType.REAL).stream() .filter(tld -> isEnrolledWithBsa(tld, now)) diff --git a/core/src/main/java/google/registry/bsa/ReservedDomainsUtils.java b/core/src/main/java/google/registry/bsa/ReservedDomainsUtils.java index 145f5d612..c754d24ad 100644 --- a/core/src/main/java/google/registry/bsa/ReservedDomainsUtils.java +++ b/core/src/main/java/google/registry/bsa/ReservedDomainsUtils.java @@ -20,7 +20,6 @@ import static google.registry.bsa.BsaStringUtils.DOMAIN_JOINER; import static google.registry.flows.domain.DomainFlowUtils.isReserved; import static google.registry.model.tld.Tlds.findTldForName; import static google.registry.model.tld.label.ReservedList.loadReservedLists; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableSet; import com.google.common.net.InternetDomainName; @@ -35,7 +34,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; -import org.joda.time.DateTime; /** * Utility for looking up reserved domain names. @@ -47,15 +45,6 @@ public final class ReservedDomainsUtils { private ReservedDomainsUtils() {} - /** - * @deprecated Use {@link #getAllReservedNames(Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Stream getAllReservedNames(DateTime now) { - return getAllReservedNames(toInstant(now)); - } - public static Stream getAllReservedNames(Instant now) { return Tlds.getTldEntitiesOfType(TldType.REAL).stream() .filter(tld -> Tld.isEnrolledWithBsa(tld, now)) @@ -74,15 +63,6 @@ public final class ReservedDomainsUtils { .collect(toImmutableSet()); } - /** - * @deprecated Use {@link #getAllReservedDomainsInTld(Tld, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - static ImmutableSet getAllReservedDomainsInTld(Tld tld, DateTime now) { - return getAllReservedDomainsInTld(tld, toInstant(now)); - } - /** * Returns true if {@code domain} is a reserved name that can be registered right now (e.g., * during sunrise or with allocation token), therefore unblockable. @@ -95,13 +75,4 @@ public final class ReservedDomainsUtils { InternetDomainName.from(domain), Objects.equals(tld.getTldState(now), TldState.START_DATE_SUNRISE)); } - - /** - * @deprecated Use {@link #isReservedDomain(String, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static boolean isReservedDomain(String domain, DateTime now) { - return isReservedDomain(domain, toInstant(now)); - } } diff --git a/core/src/main/java/google/registry/bsa/api/BsaCredential.java b/core/src/main/java/google/registry/bsa/api/BsaCredential.java index de20e81a6..f85e1fb29 100644 --- a/core/src/main/java/google/registry/bsa/api/BsaCredential.java +++ b/core/src/main/java/google/registry/bsa/api/BsaCredential.java @@ -31,12 +31,12 @@ import jakarta.inject.Inject; import java.io.IOException; import java.net.URL; import java.security.GeneralSecurityException; +import java.time.Duration; +import java.time.Instant; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import javax.net.ssl.HttpsURLConnection; -import org.joda.time.Duration; -import org.joda.time.Instant; /** * A credential for accessing the BSA API. @@ -104,7 +104,7 @@ public class BsaCredential { } private void ensureAuthTokenValid() throws IOException, GeneralSecurityException { - Instant now = Instant.ofEpochMilli(clock.nowUtc().getMillis()); + Instant now = clock.now(); if (authToken != null && lastRefreshTime.plus(authTokenExpiry).isAfter(now)) { logger.atInfo().log("AuthToken still valid, reusing."); return; diff --git a/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java b/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java index 519e412d2..88cf3918f 100644 --- a/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java +++ b/core/src/main/java/google/registry/bsa/persistence/DownloadScheduler.java @@ -20,7 +20,6 @@ import static google.registry.bsa.DownloadStage.DONE; import static google.registry.bsa.DownloadStage.NOP; import static google.registry.bsa.persistence.RefreshScheduler.fetchMostRecentRefresh; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static org.joda.time.Duration.standardSeconds; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; @@ -28,9 +27,9 @@ import google.registry.bsa.persistence.DownloadSchedule.CompletedJob; import google.registry.config.RegistryConfig.Config; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Duration; import java.util.Objects; import java.util.Optional; -import org.joda.time.Duration; /** * Assigns work for each cron invocation of the BSA Download job. @@ -57,7 +56,7 @@ import org.joda.time.Duration; public final class DownloadScheduler { /** Allows a new download to proceed if the cron job fires a little early due to NTP drift. */ - private static final Duration CRON_JITTER = standardSeconds(5); + private static final Duration CRON_JITTER = Duration.ofSeconds(5); private final Duration downloadInterval; private final Duration maxNopInterval; @@ -117,8 +116,8 @@ public final class DownloadScheduler { private boolean isTimeAgain(BsaDownload mostRecent, Duration interval) { return mostRecent .getCreationTime() - .plusMillis(interval.getMillis()) - .minusMillis(CRON_JITTER.getMillis()) + .plusMillis(interval.toMillis()) + .minusMillis(CRON_JITTER.toMillis()) .isBefore(clock.now()); } diff --git a/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java b/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java index 21b08fb59..5dbb197e2 100644 --- a/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java +++ b/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java @@ -37,9 +37,9 @@ import google.registry.bsa.api.UnblockableDomain.Reason; import google.registry.model.ForeignKeyUtils; import google.registry.model.domain.Domain; import google.registry.model.tld.Tld; +import java.time.Instant; import java.util.Map; import java.util.stream.Stream; -import org.joda.time.DateTime; /** Applies the BSA label diffs from the latest BSA download. */ public final class LabelDiffUpdates { @@ -60,7 +60,7 @@ public final class LabelDiffUpdates { ImmutableList labels, IdnChecker idnChecker, DownloadSchedule schedule, - DateTime now) { + Instant now) { ImmutableList.Builder nonBlockedDomains = new ImmutableList.Builder<>(); ImmutableMap> labelsByType = ImmutableMap.copyOf( @@ -134,7 +134,7 @@ public final class LabelDiffUpdates { } static ImmutableList tallyUnblockableDomainsForNewLabels( - ImmutableList labels, IdnChecker idnChecker, DateTime now) { + ImmutableList labels, IdnChecker idnChecker, Instant now) { ImmutableList.Builder nonBlockedDomains = new ImmutableList.Builder<>(); for (BlockLabel label : labels) { diff --git a/core/src/main/java/google/registry/config/RegistryConfig.java b/core/src/main/java/google/registry/config/RegistryConfig.java index 208267cbe..43c89e8cc 100644 --- a/core/src/main/java/google/registry/config/RegistryConfig.java +++ b/core/src/main/java/google/registry/config/RegistryConfig.java @@ -225,7 +225,7 @@ public final class RegistryConfig { */ @Provides @Config("databaseRetention") - public static Duration provideDatabaseRetention() { + public static java.time.Duration provideDatabaseRetention() { return getDatabaseRetention(); } @@ -281,8 +281,8 @@ public final class RegistryConfig { */ @Provides @Config("brdaInterval") - public static Duration provideBrdaInterval() { - return Duration.standardDays(7); + public static java.time.Duration provideBrdaInterval() { + return java.time.Duration.ofDays(7); } /** @@ -315,8 +315,8 @@ public final class RegistryConfig { */ @Provides @Config("publishDnsUpdatesLockDuration") - public static Duration providePublishDnsUpdatesLockDuration() { - return Duration.standardMinutes(3); + public static java.time.Duration providePublishDnsUpdatesLockDuration() { + return java.time.Duration.ofMinutes(3); } /** @@ -343,8 +343,8 @@ public final class RegistryConfig { */ @Provides @Config("readDnsRefreshRequestsActionRuntime") - public static Duration provideReadDnsRefreshRequestsRuntime() { - return Duration.standardSeconds(45); + public static java.time.Duration provideReadDnsRefreshRequestsRuntime() { + return java.time.Duration.ofSeconds(45); } /** @@ -354,8 +354,8 @@ public final class RegistryConfig { */ @Provides @Config("dnsDefaultATtl") - public static Duration provideDnsDefaultATtl() { - return Duration.standardHours(1); + public static java.time.Duration provideDnsDefaultATtl() { + return java.time.Duration.ofHours(1); } /** @@ -365,8 +365,8 @@ public final class RegistryConfig { */ @Provides @Config("dnsDefaultNsTtl") - public static Duration provideDnsDefaultNsTtl() { - return Duration.standardHours(3); + public static java.time.Duration provideDnsDefaultNsTtl() { + return java.time.Duration.ofHours(3); } /** @@ -376,8 +376,8 @@ public final class RegistryConfig { */ @Provides @Config("dnsDefaultDsTtl") - public static Duration provideDnsDefaultDsTtl() { - return Duration.standardHours(1); + public static java.time.Duration provideDnsDefaultDsTtl() { + return java.time.Duration.ofHours(1); } @Provides @@ -757,8 +757,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeInterval") - public static Duration provideRdeInterval() { - return Duration.standardDays(1); + public static java.time.Duration provideRdeInterval() { + return java.time.Duration.ofDays(1); } /** @@ -768,8 +768,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeReportLockTimeout") - public static Duration provideRdeReportLockTimeout() { - return Duration.standardMinutes(1); + public static java.time.Duration provideRdeReportLockTimeout() { + return java.time.Duration.ofMinutes(1); } /** @@ -792,8 +792,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeUploadLockTimeout") - public static Duration provideRdeUploadLockTimeout() { - return Duration.standardMinutes(30); + public static java.time.Duration provideRdeUploadLockTimeout() { + return java.time.Duration.ofMinutes(30); } /** @@ -805,8 +805,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeUploadSftpCooldown") - public static Duration provideRdeUploadSftpCooldown() { - return Duration.standardHours(2); + public static java.time.Duration provideRdeUploadSftpCooldown() { + return java.time.Duration.ofHours(2); } /** @@ -841,8 +841,8 @@ public final class RegistryConfig { */ @Provides @Config("sheetLockTimeout") - public static Duration provideSheetLockTimeout() { - return Duration.standardHours(1); + public static java.time.Duration provideSheetLockTimeout() { + return java.time.Duration.ofHours(1); } /** @@ -865,8 +865,8 @@ public final class RegistryConfig { */ @Provides @Config("emailThrottleDuration") - public static Duration provideEmailThrottleSeconds(RegistryConfigSettings config) { - return Duration.standardSeconds(config.misc.emailThrottleSeconds); + public static java.time.Duration provideEmailThrottleSeconds(RegistryConfigSettings config) { + return java.time.Duration.ofSeconds(config.misc.emailThrottleSeconds); } /** @@ -946,8 +946,8 @@ public final class RegistryConfig { */ @Provides @Config("sshTimeout") - public static Duration provideSshTimeout() { - return Duration.standardSeconds(30); + public static java.time.Duration provideSshTimeout() { + return java.time.Duration.ofSeconds(30); } /** @@ -957,8 +957,8 @@ public final class RegistryConfig { */ @Provides @Config("transactionCooldown") - public static Duration provideTransactionCooldown() { - return Duration.standardMinutes(5); + public static java.time.Duration provideTransactionCooldown() { + return java.time.Duration.ofMinutes(5); } /** @@ -1327,15 +1327,15 @@ public final class RegistryConfig { @Provides @Config("bsaLockLeaseExpiry") - public static Duration provideBsaLockLeaseExpiry(RegistryConfigSettings config) { - return Duration.standardMinutes(config.bsa.bsaLockLeaseExpiryMinutes); + public static java.time.Duration provideBsaLockLeaseExpiry(RegistryConfigSettings config) { + return java.time.Duration.ofMinutes(config.bsa.bsaLockLeaseExpiryMinutes); } /** Returns the desired interval between successive BSA downloads. */ @Provides @Config("bsaDownloadInterval") - public static Duration provideBsaDownloadInterval(RegistryConfigSettings config) { - return Duration.standardMinutes(config.bsa.bsaDownloadIntervalMinutes); + public static java.time.Duration provideBsaDownloadInterval(RegistryConfigSettings config) { + return java.time.Duration.ofMinutes(config.bsa.bsaDownloadIntervalMinutes); } /** @@ -1344,8 +1344,8 @@ public final class RegistryConfig { */ @Provides @Config("bsaMaxNopInterval") - public static Duration provideBsaMaxNopInterval(RegistryConfigSettings config) { - return Duration.standardHours(config.bsa.bsaMaxNopIntervalHours); + public static java.time.Duration provideBsaMaxNopInterval(RegistryConfigSettings config) { + return java.time.Duration.ofHours(config.bsa.bsaMaxNopIntervalHours); } @Provides @@ -1356,14 +1356,16 @@ public final class RegistryConfig { @Provides @Config("domainCreateTxnCommitTimeLag") - public static Duration provideDomainCreateTxnCommitTimeLag(RegistryConfigSettings config) { - return Duration.standardSeconds(config.bsa.domainCreateTxnCommitTimeLagSeconds); + public static java.time.Duration provideDomainCreateTxnCommitTimeLag( + RegistryConfigSettings config) { + return java.time.Duration.ofSeconds(config.bsa.domainCreateTxnCommitTimeLagSeconds); } @Provides @Config("bsaValidationMaxStaleness") - public static Duration provideBsaValidationMaxStaleness(RegistryConfigSettings config) { - return Duration.standardSeconds(config.bsa.bsaValidationMaxStalenessSeconds); + public static java.time.Duration provideBsaValidationMaxStaleness( + RegistryConfigSettings config) { + return java.time.Duration.ofSeconds(config.bsa.bsaValidationMaxStalenessSeconds); } @Provides @@ -1374,8 +1376,8 @@ public final class RegistryConfig { @Provides @Config("bsaAuthTokenExpiry") - public static Duration provideBsaAuthTokenExpiry(RegistryConfigSettings config) { - return Duration.standardSeconds(config.bsa.authTokenExpirySeconds); + public static java.time.Duration provideBsaAuthTokenExpiry(RegistryConfigSettings config) { + return java.time.Duration.ofSeconds(config.bsa.authTokenExpirySeconds); } @Provides @@ -1488,8 +1490,8 @@ public final class RegistryConfig { * * @see google.registry.tools.server.GenerateZoneFilesAction */ - public static Duration getDatabaseRetention() { - return Duration.standardDays(30); + public static java.time.Duration getDatabaseRetention() { + return java.time.Duration.ofDays(30); } public static boolean areServersLocal() { diff --git a/core/src/main/java/google/registry/dns/DnsMetrics.java b/core/src/main/java/google/registry/dns/DnsMetrics.java index 093ee88d9..aecdb359b 100644 --- a/core/src/main/java/google/registry/dns/DnsMetrics.java +++ b/core/src/main/java/google/registry/dns/DnsMetrics.java @@ -26,7 +26,7 @@ import com.google.monitoring.metrics.LabelDescriptor; import com.google.monitoring.metrics.MetricRegistryImpl; import google.registry.util.RegistryEnvironment; import jakarta.inject.Inject; -import org.joda.time.Duration; +import java.time.Duration; /** DNS instrumentation. */ // TODO(b/67947699):Once load testing is done, revisit these to rename them and delete the ones that @@ -239,15 +239,15 @@ public class DnsMetrics { int batchSize = numberOfDomains + numberOfHosts; processingTimePerCommitDist.record( - processingDuration.getMillis(), tld, status.name(), dnsWriter); + processingDuration.toMillis(), tld, status.name(), dnsWriter); processingTimePerItemDist.record( - processingDuration.getMillis(), batchSize, tld, status.name(), dnsWriter); + processingDuration.toMillis(), batchSize, tld, status.name(), dnsWriter); if (batchSize > 0) { normalizedProcessingTimePerCommitDist.record( - processingDuration.getMillis() / (double) batchSize, tld, status.name(), dnsWriter); + processingDuration.toMillis() / (double) batchSize, tld, status.name(), dnsWriter); normalizedProcessingTimePerItemDist.record( - processingDuration.getMillis() / (double) batchSize, + processingDuration.toMillis() / (double) batchSize, batchSize, tld, status.name(), @@ -267,7 +267,7 @@ public class DnsMetrics { Duration timeSinceUpdateRequest, Duration timeSinceActionEnqueued) { updateRequestLatency.record( - timeSinceUpdateRequest.getMillis(), numberOfItems, tld, status.name(), dnsWriter); - publishQueueDelay.record(timeSinceActionEnqueued.getMillis(), tld, status.name(), dnsWriter); + timeSinceUpdateRequest.toMillis(), numberOfItems, tld, status.name(), dnsWriter); + publishQueueDelay.record(timeSinceActionEnqueued.toMillis(), tld, status.name(), dnsWriter); } } diff --git a/core/src/main/java/google/registry/dns/DnsModule.java b/core/src/main/java/google/registry/dns/DnsModule.java index 7399e124c..ec0357aa6 100644 --- a/core/src/main/java/google/registry/dns/DnsModule.java +++ b/core/src/main/java/google/registry/dns/DnsModule.java @@ -32,9 +32,9 @@ import google.registry.dns.writer.DnsWriterZone; import google.registry.request.Parameter; import google.registry.request.RequestParameters; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; import java.util.Optional; import java.util.Set; -import org.joda.time.DateTime; /** Dagger module for the dns package. */ @Module @@ -68,15 +68,15 @@ public abstract class DnsModule { @Provides @Parameter(PARAM_PUBLISH_TASK_ENQUEUED) - static DateTime provideCreateTime(HttpServletRequest req) { - return DateTime.parse(extractRequiredParameter(req, PARAM_PUBLISH_TASK_ENQUEUED)); + static Instant provideCreateTime(HttpServletRequest req) { + return Instant.parse(extractRequiredParameter(req, PARAM_PUBLISH_TASK_ENQUEUED)); } // TODO: Retire the old header after DNS pull queue migration. @Provides @Parameter(PARAM_REFRESH_REQUEST_TIME) - static DateTime provideItemsCreateTime(HttpServletRequest req) { - return DateTime.parse( + static Instant provideItemsCreateTime(HttpServletRequest req) { + return Instant.parse( extractOptionalParameter(req, "itemsCreated") .orElse(extractRequiredParameter(req, PARAM_REFRESH_REQUEST_TIME))); } diff --git a/core/src/main/java/google/registry/dns/DnsUtils.java b/core/src/main/java/google/registry/dns/DnsUtils.java index ced833375..f90994dae 100644 --- a/core/src/main/java/google/registry/dns/DnsUtils.java +++ b/core/src/main/java/google/registry/dns/DnsUtils.java @@ -17,6 +17,7 @@ package google.registry.dns; import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.persistence.PersistenceModule.TransactionIsolationLevel.TRANSACTION_REPEATABLE_READ; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static google.registry.util.DateTimeUtils.toJavaDuration; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; @@ -24,10 +25,10 @@ import com.google.common.net.InternetDomainName; import google.registry.model.common.DnsRefreshRequest; import google.registry.model.tld.Tld; import google.registry.model.tld.Tlds; +import java.time.Duration; +import java.time.Instant; import java.util.Collection; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** Utility class to handle DNS refresh requests. */ public final class DnsUtils { @@ -42,13 +43,13 @@ public final class DnsUtils { // Throws an IllegalArgumentException if the name is not under a managed TLD -- we only update // DNS for names that are under our management. String tld = Tlds.findTldForNameOrThrow(InternetDomainName.from(name)).toString(); - tm().insert(new DnsRefreshRequest(type, name, tld, tm().getTransactionTime().plus(delay))); + tm().insert(new DnsRefreshRequest(type, name, tld, tm().getTxTime().plus(delay))); } private static void requestDnsRefresh( ImmutableCollection names, TargetType type, Duration delay) { tm().assertInTransaction(); - DateTime requestTime = tm().getTransactionTime().plus(delay); + Instant requestTime = tm().getTxTime().plus(delay); tm().insertAll( names.stream() .map( @@ -103,7 +104,7 @@ public final class DnsUtils { return tm().transact( TRANSACTION_REPEATABLE_READ, () -> { - DateTime transactionTime = tm().getTransactionTime(); + Instant transactionTime = tm().getTxTime(); ImmutableList requests = tm().query( "FROM DnsRefreshRequest WHERE tld = :tld " @@ -150,10 +151,10 @@ public final class DnsUtils { if (tldName.isPresent()) { Tld tld = Tld.get(tldName.get().toString()); if (tld.getDnsAPlusAaaaTtl().isPresent()) { - dnsAPlusAaaaTtl = tld.getDnsAPlusAaaaTtl().get(); + dnsAPlusAaaaTtl = toJavaDuration(tld.getDnsAPlusAaaaTtl().get()); } } - return dnsAPlusAaaaTtl.getStandardSeconds(); + return dnsAPlusAaaaTtl.toSeconds(); } /** The possible values of the {@code DNS_TARGET_TYPE_PARAM} parameter. */ diff --git a/core/src/main/java/google/registry/dns/PublishDnsUpdatesAction.java b/core/src/main/java/google/registry/dns/PublishDnsUpdatesAction.java index f26fd3077..13539819d 100644 --- a/core/src/main/java/google/registry/dns/PublishDnsUpdatesAction.java +++ b/core/src/main/java/google/registry/dns/PublishDnsUpdatesAction.java @@ -63,11 +63,11 @@ import google.registry.util.DomainNameUtils; import google.registry.util.EmailMessage; import jakarta.inject.Inject; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** Task that sends domain and host updates to the DNS server. */ @Action( @@ -100,8 +100,8 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { */ private final String dnsWriter; - private final DateTime enqueuedTime; - private final DateTime itemsCreateTime; + private final Instant enqueuedTime; + private final Instant itemsCreateTime; private final int lockIndex; private final int numPublishLocks; private final Set domains; @@ -121,8 +121,8 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { @Inject public PublishDnsUpdatesAction( @Parameter(PARAM_DNS_WRITER) String dnsWriter, - @Parameter(PARAM_PUBLISH_TASK_ENQUEUED) DateTime enqueuedTime, - @Parameter(PARAM_REFRESH_REQUEST_TIME) DateTime itemsCreateTime, + @Parameter(PARAM_PUBLISH_TASK_ENQUEUED) Instant enqueuedTime, + @Parameter(PARAM_REFRESH_REQUEST_TIME) Instant itemsCreateTime, @Parameter(PARAM_LOCK_INDEX) int lockIndex, @Parameter(PARAM_NUM_PUBLISH_LOCKS) int numPublishLocks, @Parameter(PARAM_DOMAINS) Set domains, @@ -167,15 +167,15 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { } private void recordActionResult(ActionStatus status) { - DateTime now = clock.nowUtc(); + Instant now = clock.now(); dnsMetrics.recordActionResult( tld, dnsWriter, status, nullToEmpty(domains).size() + nullToEmpty(hosts).size(), - new Duration(itemsCreateTime, now), - new Duration(enqueuedTime, now)); + Duration.between(itemsCreateTime, now), + Duration.between(enqueuedTime, now)); logger.atInfo().log( "publishDnsWriter latency statistics: TLD: %s, dnsWriter: %s, actionStatus: %s, " + "numItems: %d, timeSinceCreation: %s, timeInQueue: %s.", @@ -183,8 +183,8 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { dnsWriter, status, nullToEmpty(domains).size() + nullToEmpty(hosts).size(), - new Duration(itemsCreateTime, now), - new Duration(enqueuedTime, now)); + Duration.between(itemsCreateTime, now), + Duration.between(enqueuedTime, now)); } /** Runs the task. */ @@ -237,7 +237,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { .ifPresent( dn -> { Optional domain = - ForeignKeyUtils.loadResource(Domain.class, dn, clock.nowUtc()); + ForeignKeyUtils.loadResource(Domain.class, dn, clock.now()); if (domain.isPresent()) { notifyWithEmailAboutDnsUpdateFailure( domain.get().getCurrentSponsorRegistrarId(), dn, false); @@ -250,8 +250,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { .findFirst() .ifPresent( hn -> { - Optional host = - ForeignKeyUtils.loadResource(Host.class, hn, clock.nowUtc()); + Optional host = ForeignKeyUtils.loadResource(Host.class, hn, clock.now()); if (host.isPresent()) { notifyWithEmailAboutDnsUpdateFailure( host.get().getPersistedCurrentSponsorRegistrarId(), hn, true); @@ -336,7 +335,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { .put(PARAM_DNS_WRITER, dnsWriter) .put(PARAM_LOCK_INDEX, Integer.toString(lockIndex)) .put(PARAM_NUM_PUBLISH_LOCKS, Integer.toString(numPublishLocks)) - .put(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) + .put(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) .put(PARAM_REFRESH_REQUEST_TIME, itemsCreateTime.toString()) .put(PARAM_DOMAINS, Joiner.on(",").join(domains)) .put(PARAM_HOSTS, Joiner.on(",").join(hosts)) @@ -374,7 +373,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { /** Steps through the domain and host refreshes contained in the parameters and processes them. */ private void processBatch() { - DateTime timeAtStart = clock.nowUtc(); + Instant timeAtStart = clock.now(); DnsWriter writer = dnsWriterProxy.getByClassNameForTld(dnsWriter, tld); @@ -426,7 +425,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { actionStatus = ActionStatus.SUCCESS; } finally { recordActionResult(actionStatus); - Duration duration = new Duration(timeAtStart, clock.nowUtc()); + Duration duration = Duration.between(timeAtStart, clock.now()); dnsMetrics.recordCommit( tld, dnsWriter, commitStatus, duration, domainsPublished, hostsPublished); logger.atInfo().log( diff --git a/core/src/main/java/google/registry/dns/ReadDnsRefreshRequestsAction.java b/core/src/main/java/google/registry/dns/ReadDnsRefreshRequestsAction.java index f9ec789b4..7a3a488de 100644 --- a/core/src/main/java/google/registry/dns/ReadDnsRefreshRequestsAction.java +++ b/core/src/main/java/google/registry/dns/ReadDnsRefreshRequestsAction.java @@ -28,7 +28,7 @@ import static google.registry.dns.DnsUtils.deleteRequests; import static google.registry.dns.DnsUtils.readAndUpdateRequestsWithLatestProcessTime; import static google.registry.request.Action.Method.POST; import static google.registry.request.RequestParameters.PARAM_TLD; -import static google.registry.util.DateTimeUtils.END_OF_TIME; +import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DomainNameUtils.getSecondLevelDomain; import static java.nio.charset.StandardCharsets.UTF_8; @@ -49,10 +49,10 @@ import google.registry.request.Parameter; import google.registry.request.auth.Auth; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; import java.util.Collection; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Action for fanning out DNS refresh tasks by TLD, using data taken from {@link DnsRefreshRequest} @@ -104,11 +104,11 @@ public final class ReadDnsRefreshRequestsAction implements Runnable { logger.atInfo().log("The queue updated is paused for TLD: %s.", tld); return; } - DateTime requestedEndTime = clock.nowUtc().plus(requestedMaximumDuration); + Instant requestedEndTime = clock.now().plus(requestedMaximumDuration); // See getLockIndex(), requests are evenly distributed to [1, numDnsPublishLocks], so each // bucket would be roughly the size of tldUpdateBatchSize. int processBatchSize = tldUpdateBatchSize * Tld.get(tld).getNumDnsPublishLocks(); - while (requestedEndTime.isAfter(clock.nowUtc())) { + while (requestedEndTime.isAfter(clock.now())) { ImmutableList requests = readAndUpdateRequestsWithLatestProcessTime( tld, requestedMaximumDuration, processBatchSize); @@ -165,7 +165,7 @@ public final class ReadDnsRefreshRequestsAction implements Runnable { void enqueueUpdates(int lockIndex, int numPublishLocks, Collection requests) { ImmutableList.Builder domainsBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder hostsBuilder = new ImmutableList.Builder<>(); - DateTime earliestRequestTime = END_OF_TIME; + Instant earliestRequestTime = END_INSTANT; for (DnsRefreshRequest request : requests) { if (request.getRequestTime().isBefore(earliestRequestTime)) { earliestRequestTime = request.getRequestTime(); @@ -189,7 +189,7 @@ public final class ReadDnsRefreshRequestsAction implements Runnable { .put(PARAM_DNS_WRITER, dnsWriter) .put(PARAM_LOCK_INDEX, Integer.toString(lockIndex)) .put(PARAM_NUM_PUBLISH_LOCKS, Integer.toString(numPublishLocks)) - .put(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) + .put(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) .put(PARAM_REFRESH_REQUEST_TIME, earliestRequestTime.toString()) .put(PARAM_DOMAINS, Joiner.on(',').join(domains)) .put(PARAM_HOSTS, Joiner.on(',').join(hosts)) diff --git a/core/src/main/java/google/registry/dns/RefreshDnsAction.java b/core/src/main/java/google/registry/dns/RefreshDnsAction.java index 0e4c7508b..f7c62298c 100644 --- a/core/src/main/java/google/registry/dns/RefreshDnsAction.java +++ b/core/src/main/java/google/registry/dns/RefreshDnsAction.java @@ -78,7 +78,7 @@ public final class RefreshDnsAction implements Runnable { private T loadAndVerifyExistence(Class clazz, String foreignKey) { - return ForeignKeyUtils.loadResource(clazz, foreignKey, clock.nowUtc()) + return ForeignKeyUtils.loadResource(clazz, foreignKey, clock.now()) .orElseThrow( () -> new NotFoundException( diff --git a/core/src/main/java/google/registry/dns/RefreshDnsOnHostRenameAction.java b/core/src/main/java/google/registry/dns/RefreshDnsOnHostRenameAction.java index edaca7984..cdb0f21a2 100644 --- a/core/src/main/java/google/registry/dns/RefreshDnsOnHostRenameAction.java +++ b/core/src/main/java/google/registry/dns/RefreshDnsOnHostRenameAction.java @@ -30,7 +30,7 @@ import google.registry.request.Parameter; import google.registry.request.Response; import google.registry.request.auth.Auth; import jakarta.inject.Inject; -import org.joda.time.DateTime; +import java.time.Instant; @Action( service = Action.Service.BACKEND, @@ -56,7 +56,7 @@ public class RefreshDnsOnHostRenameAction implements Runnable { public void run() { tm().transact( () -> { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); Host host = tm().loadByKeyIfPresent(hostKey).orElse(null); boolean hostValid = true; String failureMessage = null; diff --git a/core/src/main/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java b/core/src/main/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java index 2562b004b..4d947c3cd 100644 --- a/core/src/main/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java +++ b/core/src/main/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java @@ -44,6 +44,7 @@ import google.registry.model.tld.Tld; import google.registry.model.tld.Tlds; import google.registry.util.Clock; import google.registry.util.Concurrent; +import google.registry.util.DateTimeUtils; import google.registry.util.Retrier; import jakarta.inject.Inject; import jakarta.inject.Named; @@ -51,6 +52,7 @@ import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; +import java.time.Duration; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.HashMap; import java.util.HashSet; @@ -59,7 +61,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; -import org.joda.time.Duration; /** * {@link DnsWriter} implementation that talks to Google Cloud DNS. @@ -123,8 +124,7 @@ public class CloudDnsWriter extends BaseDnsWriter { String absoluteDomainName = getAbsoluteHostName(domainName); // Load the target domain. Note that it can be absent if this domain was just deleted. - Optional domain = - ForeignKeyUtils.loadResource(Domain.class, domainName, clock.nowUtc()); + Optional domain = ForeignKeyUtils.loadResource(Domain.class, domainName, clock.now()); // Return early if no DNS records should be published. // desiredRecordsBuilder is populated with an empty set to indicate that all existing records @@ -148,7 +148,12 @@ public class CloudDnsWriter extends BaseDnsWriter { domainRecords.add( new ResourceRecordSet() .setName(absoluteDomainName) - .setTtl((int) tld.getDnsDsTtl().orElse(defaultDsTtl).getStandardSeconds()) + .setTtl( + (int) + tld.getDnsDsTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(defaultDsTtl) + .toSeconds()) .setType("DS") .setKind("dns#resourceRecordSet") .setRrdatas(ImmutableList.copyOf(dsRrData))); @@ -171,7 +176,12 @@ public class CloudDnsWriter extends BaseDnsWriter { domainRecords.add( new ResourceRecordSet() .setName(absoluteDomainName) - .setTtl((int) tld.getDnsNsTtl().orElse(defaultNsTtl).getStandardSeconds()) + .setTtl( + (int) + tld.getDnsNsTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(defaultNsTtl) + .toSeconds()) .setType("NS") .setKind("dns#resourceRecordSet") .setRrdatas(ImmutableList.copyOf(nsRrData))); @@ -190,7 +200,7 @@ public class CloudDnsWriter extends BaseDnsWriter { // Load the target host. Note that it can be absent if this host was just deleted. // desiredRecords is populated with an empty set to indicate that all existing records // should be deleted. - Optional host = ForeignKeyUtils.loadResource(Host.class, hostName, clock.nowUtc()); + Optional host = ForeignKeyUtils.loadResource(Host.class, hostName, clock.now()); // Return early if the host is deleted. if (host.isEmpty()) { diff --git a/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsMessageTransport.java b/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsMessageTransport.java index 412eb2529..99e4347d0 100644 --- a/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsMessageTransport.java +++ b/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsMessageTransport.java @@ -28,8 +28,8 @@ import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.nio.ByteBuffer; +import java.time.Duration; import javax.net.SocketFactory; -import org.joda.time.Duration; import org.xbill.DNS.Message; import org.xbill.DNS.Opcode; @@ -76,7 +76,7 @@ public class DnsMessageTransport { @Config("dnsUpdateTimeout") Duration updateTimeout) { this.factory = factory; this.updateHost = updateHost; - this.updateTimeout = Ints.checkedCast(updateTimeout.getMillis()); + this.updateTimeout = Ints.checkedCast(updateTimeout.toMillis()); } /** diff --git a/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateConfigModule.java b/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateConfigModule.java index c08d7da24..e5549dd5a 100644 --- a/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateConfigModule.java +++ b/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateConfigModule.java @@ -17,7 +17,7 @@ package google.registry.dns.writer.dnsupdate; import dagger.Module; import dagger.Provides; import google.registry.config.RegistryConfig.Config; -import org.joda.time.Duration; +import java.time.Duration; /** Dagger module that provides DNS configuration settings. */ @Module @@ -39,6 +39,6 @@ public class DnsUpdateConfigModule { @Provides @Config("dnsUpdateTimeout") public static Duration provideDnsUpdateTimeout() { - return Duration.standardSeconds(30); + return Duration.ofSeconds(30); } } diff --git a/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriter.java b/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriter.java index 08b965881..2c66a33b5 100644 --- a/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriter.java +++ b/core/src/main/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriter.java @@ -34,13 +34,14 @@ import google.registry.model.host.Host; import google.registry.model.tld.Tld; import google.registry.model.tld.Tlds; import google.registry.util.Clock; +import google.registry.util.DateTimeUtils; import jakarta.inject.Inject; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; +import java.time.Duration; import java.util.Optional; -import org.joda.time.Duration; import org.xbill.DNS.AAAARecord; import org.xbill.DNS.ARecord; import org.xbill.DNS.DClass; @@ -130,7 +131,7 @@ public class DnsUpdateWriter extends BaseDnsWriter { */ private void publishDomain(String domainName, String requestingHostName) { Optional domainOptional = - ForeignKeyUtils.loadResource(Domain.class, domainName, clock.nowUtc()); + ForeignKeyUtils.loadResource(Domain.class, domainName, clock.now()); update.delete(toAbsoluteName(domainName), Type.ANY); // If the domain is now deleted, then don't update DNS for it. if (domainOptional.isPresent()) { @@ -194,7 +195,10 @@ public class DnsUpdateWriter extends BaseDnsWriter { new DSRecord( toAbsoluteName(domain.getDomainName()), DClass.IN, - tld.getDnsDsTtl().orElse(dnsDefaultDsTtl).getStandardSeconds(), + tld.getDnsDsTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(dnsDefaultDsTtl) + .toSeconds(), signerData.getKeyTag(), signerData.getAlgorithm(), signerData.getDigestType(), @@ -219,7 +223,7 @@ public class DnsUpdateWriter extends BaseDnsWriter { private void addInBailiwickNameServerSet(Domain domain, Update update) { for (String hostName : intersection(domain.loadNameserverHostNames(), domain.getSubordinateHosts())) { - Optional host = ForeignKeyUtils.loadResource(Host.class, hostName, clock.nowUtc()); + Optional host = ForeignKeyUtils.loadResource(Host.class, hostName, clock.now()); checkState(host.isPresent(), "Host %s cannot be loaded", hostName); update.add(makeAddressSet(host.get())); update.add(makeV6AddressSet(host.get())); @@ -234,7 +238,10 @@ public class DnsUpdateWriter extends BaseDnsWriter { new NSRecord( toAbsoluteName(domain.getDomainName()), DClass.IN, - tld.getDnsNsTtl().orElse(dnsDefaultNsTtl).getStandardSeconds(), + tld.getDnsNsTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(dnsDefaultNsTtl) + .toSeconds(), toAbsoluteName(hostName)); nameServerSet.addRR(record); } diff --git a/core/src/main/java/google/registry/export/ExportDomainListsAction.java b/core/src/main/java/google/registry/export/ExportDomainListsAction.java index 69a742f7f..46250a5e0 100644 --- a/core/src/main/java/google/registry/export/ExportDomainListsAction.java +++ b/core/src/main/java/google/registry/export/ExportDomainListsAction.java @@ -47,8 +47,6 @@ import java.time.Instant; import java.util.List; import org.hibernate.query.NativeQuery; import org.hibernate.query.TupleTransformer; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; /** * An action that exports the list of active domains on all real TLDs to Google Drive and GCS. @@ -175,8 +173,7 @@ public class ExportDomainListsAction implements Runnable { @Override public String transformTuple(Object[] domainResult, String[] strings) { String domainName = (String) domainResult[0]; - Instant deletionInstant = (Instant) domainResult[1]; - DateTime deletionTime = new DateTime(deletionInstant.toEpochMilli(), DateTimeZone.UTC); + Instant deletionTime = (Instant) domainResult[1]; String[] domainStatuses = (String[]) domainResult[2]; String gracePeriodType = (String) domainResult[3]; boolean inPendingDelete = diff --git a/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheet.java b/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheet.java index c5de165a8..56ef05197 100644 --- a/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheet.java +++ b/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheet.java @@ -26,6 +26,7 @@ import static google.registry.model.registrar.RegistrarPoc.Type.TECH; import static google.registry.model.registrar.RegistrarPoc.Type.WHOIS; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.START_INSTANT; +import static google.registry.util.DateTimeUtils.isAtOrAfter; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; @@ -37,7 +38,6 @@ import google.registry.model.registrar.Registrar; import google.registry.model.registrar.RegistrarAddress; import google.registry.model.registrar.RegistrarPoc; import google.registry.util.Clock; -import google.registry.util.DateTimeUtils; import jakarta.inject.Inject; import java.io.IOException; import java.time.Instant; @@ -63,9 +63,9 @@ class SyncRegistrarsSheet { boolean wereRegistrarsModified() { Optional cursor = tm().transact(() -> tm().loadByKeyIfPresent(Cursor.createGlobalVKey(SYNC_REGISTRAR_SHEET))); - Instant lastUpdateTime = cursor.isEmpty() ? START_INSTANT : cursor.get().getCursorTimeInstant(); + Instant lastUpdateTime = cursor.isEmpty() ? START_INSTANT : cursor.get().getCursorTime(); for (Registrar registrar : Registrar.loadAllCached()) { - if (DateTimeUtils.isAtOrAfter(registrar.getLastUpdateTime(), lastUpdateTime)) { + if (isAtOrAfter(registrar.getLastUpdateTime(), lastUpdateTime)) { return true; } } diff --git a/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java b/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java index d876e3227..f0d2834f2 100644 --- a/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java +++ b/core/src/main/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java @@ -30,10 +30,10 @@ import google.registry.request.auth.Auth; import google.registry.request.lock.LockHandler; import jakarta.inject.Inject; import java.io.IOException; +import java.time.Duration; import java.util.Optional; import java.util.concurrent.Callable; import javax.annotation.Nullable; -import org.joda.time.Duration; /** * Action for synchronizing the registrars spreadsheet. diff --git a/core/src/main/java/google/registry/flows/domain/DomainDeleteFlow.java b/core/src/main/java/google/registry/flows/domain/DomainDeleteFlow.java index d14c4efba..1b1ac8f4e 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainDeleteFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainDeleteFlow.java @@ -42,6 +42,7 @@ import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.CollectionUtils.union; import static google.registry.util.DateTimeUtils.toDateTime; import static google.registry.util.DateTimeUtils.toInstant; +import static java.time.ZoneOffset.UTC; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -101,7 +102,6 @@ import google.registry.model.tld.Tld.TldType; import google.registry.model.transfer.TransferStatus; import jakarta.inject.Inject; import java.time.Instant; -import java.time.ZoneOffset; import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -194,9 +194,7 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging } else { Instant redemptionTime = now.plusMillis(redemptionGracePeriodLength.getMillis()); asyncTaskEnqueuer.enqueueAsyncResave( - existingDomain.createVKey(), - toDateTime(now), - ImmutableSortedSet.of(toDateTime(redemptionTime), toDateTime(deletionTime))); + existingDomain.createVKey(), now, ImmutableSortedSet.of(redemptionTime, deletionTime)); builder .setDeletionTime(deletionTime) .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE)) @@ -253,14 +251,11 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging // This can be either add grace periods or renew grace periods. BillingEvent billingEvent = tm().loadByKey(gracePeriod.getBillingEvent()); newExpirationTime = - newExpirationTime - .atZone(ZoneOffset.UTC) - .minusYears(billingEvent.getPeriodYears()) - .toInstant(); + newExpirationTime.atZone(UTC).minusYears(billingEvent.getPeriodYears()).toInstant(); } else if (gracePeriod.getBillingRecurrence() != null) { // Take 1 year off the registration if in the autorenew grace period (no need to load the // recurrence billing event; all autorenews are for 1 year). - newExpirationTime = newExpirationTime.atZone(ZoneOffset.UTC).minusYears(1).toInstant(); + newExpirationTime = newExpirationTime.atZone(UTC).minusYears(1).toInstant(); } } } diff --git a/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java b/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java index 9e94ee46b..b91314a71 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java +++ b/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java @@ -44,6 +44,7 @@ import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DomainNameUtils.ACE_PREFIX; +import static java.time.ZoneOffset.UTC; import static java.util.stream.Collectors.joining; import com.google.common.base.CharMatcher; @@ -124,7 +125,6 @@ import google.registry.tools.DigestType; import google.registry.util.Idn; import java.math.BigDecimal; import java.time.Instant; -import java.time.ZoneOffset; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; @@ -848,10 +848,7 @@ public class DomainFlowUtils { */ public static void validateRegistrationPeriod(Instant now, Instant newExpirationTime) throws EppException { - if (now.atZone(ZoneOffset.UTC) - .plusYears(MAX_REGISTRATION_YEARS) - .toInstant() - .isBefore(newExpirationTime)) { + if (now.atZone(UTC).plusYears(MAX_REGISTRATION_YEARS).toInstant().isBefore(newExpirationTime)) { throw new ExceedsMaxRegistrationYearsException(); } } diff --git a/core/src/main/java/google/registry/flows/domain/DomainRenewFlow.java b/core/src/main/java/google/registry/flows/domain/DomainRenewFlow.java index 824b0d25d..313985638 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainRenewFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainRenewFlow.java @@ -35,6 +35,7 @@ import static google.registry.flows.domain.token.AllocationTokenFlowUtils.verify import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_RENEW; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.toDateTime; +import static java.time.ZoneOffset.UTC; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -87,7 +88,6 @@ import google.registry.model.reporting.IcannReportingTypes.ActivityReportField; import google.registry.model.tld.Tld; import jakarta.inject.Inject; import java.time.Instant; -import java.time.ZoneOffset; import java.util.Optional; import org.joda.money.Money; import org.joda.time.Duration; @@ -194,7 +194,7 @@ public final class DomainRenewFlow implements MutatingFlow { Instant newExpirationTime = existingDomain .getRegistrationExpirationTime() - .atZone(ZoneOffset.UTC) + .atZone(UTC) .plusYears(years) .toInstant(); // Uncapped validateRegistrationPeriod(now, newExpirationTime); diff --git a/core/src/main/java/google/registry/flows/domain/DomainRestoreRequestFlow.java b/core/src/main/java/google/registry/flows/domain/DomainRestoreRequestFlow.java index ce1485b35..5b65832c4 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainRestoreRequestFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainRestoreRequestFlow.java @@ -31,6 +31,7 @@ import static google.registry.flows.domain.DomainFlowUtils.verifyRegistrarIsActi import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_RESTORE; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.END_INSTANT; +import static java.time.ZoneOffset.UTC; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -70,7 +71,6 @@ import google.registry.model.reporting.IcannReportingTypes.ActivityReportField; import google.registry.model.tld.Tld; import jakarta.inject.Inject; import java.time.Instant; -import java.time.ZoneOffset; import java.util.Optional; import org.joda.money.Money; @@ -152,7 +152,7 @@ public final class DomainRestoreRequestFlow implements MutatingFlow { Instant newExpirationTime = existingDomain .getRegistrationExpirationTime() - .atZone(ZoneOffset.UTC) + .atZone(UTC) .plusYears(isExpired ? 1 : 0) .toInstant(); // Restore the expiration time on the deleted domain, except if that's already passed, then add diff --git a/core/src/main/java/google/registry/flows/domain/DomainTransferRequestFlow.java b/core/src/main/java/google/registry/flows/domain/DomainTransferRequestFlow.java index a9d35ee92..77816c90a 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainTransferRequestFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainTransferRequestFlow.java @@ -35,7 +35,7 @@ import static google.registry.flows.domain.DomainTransferUtils.createTransferSer import static google.registry.model.eppoutput.Result.Code.SUCCESS_WITH_ACTION_PENDING; import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_TRANSFER_REQUEST; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toDateTime; +import static java.time.temporal.ChronoUnit.DAYS; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -82,7 +82,6 @@ import google.registry.model.transfer.TransferResponse.DomainTransferResponse; import google.registry.model.transfer.TransferStatus; import jakarta.inject.Inject; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.Optional; /** @@ -220,8 +219,7 @@ public final class DomainTransferRequestFlow implements MutatingFlow { .map( domainTransferRequestSuperuserExtension -> now.plus( - domainTransferRequestSuperuserExtension.getAutomaticTransferLength(), - ChronoUnit.DAYS)) + domainTransferRequestSuperuserExtension.getAutomaticTransferLength(), DAYS)) .orElseGet(() -> now.plusMillis(tld.getAutomaticTransferLength().getMillis())); // If the domain will be in the auto-renew grace period at the moment of transfer, the transfer // will subsume the autorenew, so we don't add the normal extra year from the transfer. @@ -284,9 +282,7 @@ public final class DomainTransferRequestFlow implements MutatingFlow { DomainHistory domainHistory = buildDomainHistory(newDomain, tld, now, period); asyncTaskEnqueuer.enqueueAsyncResave( - newDomain.createVKey(), - toDateTime(now), - ImmutableSortedSet.of(toDateTime(automaticTransferTime))); + newDomain.createVKey(), now, ImmutableSortedSet.of(automaticTransferTime)); tm().put(newDomain); tm().putAll(serverApproveEntities); tm().insertAll(domainHistory, requestPollMessage); diff --git a/core/src/main/java/google/registry/flows/poll/PollAckFlow.java b/core/src/main/java/google/registry/flows/poll/PollAckFlow.java index 6be8dec66..c10f13c2b 100644 --- a/core/src/main/java/google/registry/flows/poll/PollAckFlow.java +++ b/core/src/main/java/google/registry/flows/poll/PollAckFlow.java @@ -83,7 +83,7 @@ public final class PollAckFlow implements MutatingFlow { throw new InvalidMessageIdException(messageId); } - final Instant now = tm().getTxTime(); + Instant now = tm().getTxTime(); // Load the message to be acked. If a message is queued to be delivered in the future, we treat // it as if it doesn't exist yet. Same for if the message ID year isn't the same as the actual diff --git a/core/src/main/java/google/registry/model/common/Cursor.java b/core/src/main/java/google/registry/model/common/Cursor.java index c2bf3355b..de2765ad9 100644 --- a/core/src/main/java/google/registry/model/common/Cursor.java +++ b/core/src/main/java/google/registry/model/common/Cursor.java @@ -17,8 +17,6 @@ package google.registry.model.common; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static google.registry.util.DateTimeUtils.START_INSTANT; -import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; import google.registry.model.ImmutableObject; import google.registry.model.UnsafeSerializable; @@ -35,7 +33,6 @@ import jakarta.persistence.Id; import jakarta.persistence.IdClass; import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** * Shared entity for date cursors. @@ -156,15 +153,6 @@ public class Cursor extends UpdateAutoTimestampEntity { return getUpdateTimestamp().getTimestamp(); } - /** - * @deprecated Use {@link #getLastUpdateTime()} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public DateTime getLastUpdateDateTime() { - return toDateTime(getUpdateTimestamp().getTimestamp()); - } - public String getScope() { return scope; } @@ -189,30 +177,12 @@ public class Cursor extends UpdateAutoTimestampEntity { return create(cursorType, cursorTime, GLOBAL); } - /** - * @deprecated Use {@link #createGlobal(CursorType, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Cursor createGlobal(CursorType cursorType, DateTime cursorTime) { - return createGlobal(cursorType, toInstant(cursorTime)); - } - /** Creates a new cursor instance with a given {@link Tld} scope. */ public static Cursor createScoped(CursorType cursorType, Instant cursorTime, Tld scope) { checkNotNull(scope, "Cursor scope cannot be null"); return create(cursorType, cursorTime, scope.getTldStr()); } - /** - * @deprecated Use {@link #createScoped(CursorType, Instant, Tld)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Cursor createScoped(CursorType cursorType, DateTime cursorTime, Tld scope) { - return createScoped(cursorType, toInstant(cursorTime), scope); - } - /** * Creates a new cursor instance with a given TLD scope, or global if the scope is {@link * #GLOBAL}. @@ -230,29 +200,11 @@ public class Cursor extends UpdateAutoTimestampEntity { /** * Returns the current time for a given cursor, or {@code START_INSTANT} if the cursor is null. */ - public static Instant getCursorTimeOrStartOfTimeInstant(Optional cursor) { - return cursor.map(Cursor::getCursorTimeInstant).orElse(START_INSTANT); + public static Instant getCursorTimeOrStartOfTime(Optional cursor) { + return cursor.map(Cursor::getCursorTime).orElse(START_INSTANT); } - /** - * @deprecated Use {@link #getCursorTimeOrStartOfTimeInstant(Optional)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static DateTime getCursorTimeOrStartOfTime(Optional cursor) { - return toDateTime(getCursorTimeOrStartOfTimeInstant(cursor)); - } - - /** - * @deprecated Use {@link #getCursorTimeInstant()} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public DateTime getCursorTime() { - return toDateTime(cursorTime); - } - - public Instant getCursorTimeInstant() { + public Instant getCursorTime() { return cursorTime; } diff --git a/core/src/main/java/google/registry/model/common/DnsRefreshRequest.java b/core/src/main/java/google/registry/model/common/DnsRefreshRequest.java index b8fb36e37..3b269d366 100644 --- a/core/src/main/java/google/registry/model/common/DnsRefreshRequest.java +++ b/core/src/main/java/google/registry/model/common/DnsRefreshRequest.java @@ -16,7 +16,7 @@ package google.registry.model.common; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import google.registry.dns.DnsUtils.TargetType; import google.registry.dns.PublishDnsUpdatesAction; @@ -31,8 +31,8 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; +import java.time.Instant; import javax.annotation.Nullable; -import org.joda.time.DateTime; @Entity @Table(indexes = {@Index(columnList = "requestTime"), @Index(columnList = "lastProcessTime")}) @@ -54,10 +54,10 @@ public class DnsRefreshRequest extends ImmutableObject { private String tld; @Column(nullable = false) - private DateTime requestTime; + private Instant requestTime; @Column(nullable = false) - private DateTime lastProcessTime; + private Instant lastProcessTime; public TargetType getType() { return type; @@ -71,7 +71,7 @@ public class DnsRefreshRequest extends ImmutableObject { return tld; } - public DateTime getRequestTime() { + public Instant getRequestTime() { return requestTime; } @@ -86,7 +86,7 @@ public class DnsRefreshRequest extends ImmutableObject { * there are concurrent reads that all attempt to read the rows with oldest {@link #requestTime}, * or another read that comes too early after the previous read. */ - public DateTime getLastProcessTime() { + public Instant getLastProcessTime() { return lastProcessTime; } @@ -102,8 +102,8 @@ public class DnsRefreshRequest extends ImmutableObject { TargetType type, String name, String tld, - DateTime requestTime, - DateTime lastProcessTime) { + Instant requestTime, + Instant lastProcessTime) { checkNotNull(type, "Target type cannot be null"); checkNotNull(name, "Domain/host name cannot be null"); checkNotNull(tld, "TLD cannot be null"); @@ -119,11 +119,11 @@ public class DnsRefreshRequest extends ImmutableObject { this.lastProcessTime = lastProcessTime; } - public DnsRefreshRequest(TargetType type, String name, String tld, DateTime requestTime) { - this(null, type, name, tld, requestTime, START_OF_TIME); + public DnsRefreshRequest(TargetType type, String name, String tld, Instant requestTime) { + this(null, type, name, tld, requestTime, START_INSTANT); } - public DnsRefreshRequest updateProcessTime(DateTime processTime) { + public DnsRefreshRequest updateProcessTime(Instant processTime) { checkArgument( processTime.isAfter(getRequestTime()), "Process time %s must be later than request time %s", diff --git a/core/src/main/java/google/registry/model/common/TimeOfYear.java b/core/src/main/java/google/registry/model/common/TimeOfYear.java index a459b07a6..71fa4cb6b 100644 --- a/core/src/main/java/google/registry/model/common/TimeOfYear.java +++ b/core/src/main/java/google/registry/model/common/TimeOfYear.java @@ -22,6 +22,7 @@ import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static google.registry.util.DateTimeUtils.minusYears; import static google.registry.util.DateTimeUtils.plusYears; +import static java.time.ZoneOffset.UTC; import com.google.common.base.Splitter; import com.google.common.collect.ContiguousSet; @@ -32,7 +33,6 @@ import jakarta.persistence.Embeddable; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; -import java.time.ZoneOffset; import java.time.ZonedDateTime; 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, ZoneOffset.UTC); + ZonedDateTime zdt = ZonedDateTime.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 normalizedRange = range.intersection(Range.closed(START_INSTANT, END_INSTANT)); Range yearRange = Range.closed( - ZonedDateTime.ofInstant(normalizedRange.lowerEndpoint(), ZoneOffset.UTC).getYear(), - ZonedDateTime.ofInstant(normalizedRange.upperEndpoint(), ZoneOffset.UTC).getYear()); + ZonedDateTime.ofInstant(normalizedRange.lowerEndpoint(), UTC).getYear(), + ZonedDateTime.ofInstant(normalizedRange.upperEndpoint(), UTC).getYear()); return ContiguousSet.create(yearRange, integers()).stream() .map(this::toInstantWithYear) .filter(normalizedRange) @@ -107,20 +107,18 @@ public class TimeOfYear extends ImmutableObject implements UnsafeSerializable { int millis = Integer.parseInt(monthDayMillis.get(2)); return LocalDate.of(year, month, day) .atTime(LocalTime.ofNanoOfDay(millis * 1000000L)) - .toInstant(ZoneOffset.UTC); + .toInstant(UTC); } /** 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, ZoneOffset.UTC).getYear()); + Instant withSameYear = toInstantWithYear(ZonedDateTime.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, ZoneOffset.UTC).getYear()); + Instant withSameYear = toInstantWithYear(ZonedDateTime.ofInstant(end, UTC).getYear()); return isBeforeOrAt(withSameYear, end) ? withSameYear : minusYears(withSameYear, 1); } diff --git a/core/src/main/java/google/registry/model/poll/PollMessageExternalKeyConverter.java b/core/src/main/java/google/registry/model/poll/PollMessageExternalKeyConverter.java index 72af30278..f94cd9686 100644 --- a/core/src/main/java/google/registry/model/poll/PollMessageExternalKeyConverter.java +++ b/core/src/main/java/google/registry/model/poll/PollMessageExternalKeyConverter.java @@ -14,9 +14,10 @@ package google.registry.model.poll; +import static java.time.ZoneOffset.UTC; + import com.google.common.base.Splitter; import google.registry.persistence.VKey; -import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; @@ -45,8 +46,7 @@ public final class PollMessageExternalKeyConverter { public static String makePollMessageExternalId(PollMessage pollMessage) { return String.format( "%d-%d", - pollMessage.getId(), - ZonedDateTime.ofInstant(pollMessage.getEventTime(), ZoneOffset.UTC).getYear()); + pollMessage.getId(), ZonedDateTime.ofInstant(pollMessage.getEventTime(), UTC).getYear()); } /** diff --git a/core/src/main/java/google/registry/model/rde/RdeNamingUtils.java b/core/src/main/java/google/registry/model/rde/RdeNamingUtils.java index 4099d9939..16c58dfb7 100644 --- a/core/src/main/java/google/registry/model/rde/RdeNamingUtils.java +++ b/core/src/main/java/google/registry/model/rde/RdeNamingUtils.java @@ -16,38 +16,39 @@ package google.registry.model.rde; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static java.time.ZoneOffset.UTC; +import static java.time.temporal.ChronoUnit.DAYS; -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; +import java.time.Instant; +import java.time.format.DateTimeFormatter; /** Utility class for generating RDE filenames and string IDs. */ public final class RdeNamingUtils { - private static final DateTimeFormatter DATE_FORMATTER = ISODateTimeFormat.date(); + private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; /** * Returns extensionless RDE filename in format {@code ___S<#>_R}. * *

This naming scheme is defined in the {@code gTLD_Applicant_Guidebook_full.pdf}. */ - public static - String makeRydeFilename(String tld, DateTime date, RdeMode mode, int series, int revision) { + public static String makeRydeFilename( + String tld, Instant date, RdeMode mode, int series, int revision) { checkArgument(series >= 1, "series >= 1"); checkArgument(revision >= 0, "revision >= 0"); return String.format("%s_S%d_R%d", makePartialName(tld, date, mode), series, revision); } /** Returns same thing as {@link #makeRydeFilename} except without the series and revision. */ - public static String makePartialName(String tld, DateTime date, RdeMode mode) { + public static String makePartialName(String tld, Instant date, RdeMode mode) { return String.format("%s_%s_%s", checkNotNull(tld), formatDate(date), mode.getFilenameComponent()); } /** Returns date as a hyphened string with ISO-8601 ordering, e.g. {@code 1984-12-18}. */ - private static String formatDate(DateTime date) { - checkArgument(date.withTimeAtStartOfDay().equals(date), "Not midnight: %s", date); - return DATE_FORMATTER.print(date); + private static String formatDate(Instant date) { + checkArgument(date.truncatedTo(DAYS).equals(date), "Not midnight: %s", date); + return DATE_FORMATTER.withZone(UTC).format(date); } private RdeNamingUtils() {} diff --git a/core/src/main/java/google/registry/model/rde/RdeRevision.java b/core/src/main/java/google/registry/model/rde/RdeRevision.java index 2250c83e1..cb024d430 100644 --- a/core/src/main/java/google/registry/model/rde/RdeRevision.java +++ b/core/src/main/java/google/registry/model/rde/RdeRevision.java @@ -17,11 +17,11 @@ package google.registry.model.rde; import static com.google.common.base.Preconditions.checkArgument; import static google.registry.model.rde.RdeNamingUtils.makePartialName; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static google.registry.util.DateTimeUtils.toJodaLocalDate; import com.google.common.base.VerifyException; import google.registry.model.ImmutableObject; import google.registry.model.UpdateAutoTimestampEntity; -import google.registry.model.rde.RdeRevision.RdeRevisionId; import google.registry.persistence.VKey; import google.registry.persistence.converter.LocalDateConverter; import jakarta.persistence.Column; @@ -32,8 +32,8 @@ import jakarta.persistence.Enumerated; import jakarta.persistence.Id; import jakarta.persistence.IdClass; import java.io.Serializable; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; import org.joda.time.LocalDate; /** @@ -44,7 +44,7 @@ import org.joda.time.LocalDate; * flag is included in the generated XML. */ @Entity -@IdClass(RdeRevisionId.class) +@IdClass(RdeRevision.RdeRevisionId.class) public final class RdeRevision extends UpdateAutoTimestampEntity { @Id String tld; @@ -82,15 +82,15 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { * * @return {@code 0} for first deposit generation and {@code >0} for resends */ - public static int getNextRevision(String tld, DateTime date, RdeMode mode) { - RdeRevisionId sqlKey = RdeRevisionId.create(tld, date.toLocalDate(), mode); + public static int getNextRevision(String tld, Instant date, RdeMode mode) { + RdeRevisionId revisionId = RdeRevisionId.create(tld, toJodaLocalDate(date), mode); Optional revisionOptional = - tm().transact(() -> tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, sqlKey))); + tm().transact(() -> tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, revisionId))); return revisionOptional.map(rdeRevision -> rdeRevision.revision + 1).orElse(0); } /** Returns the latest revision of the report already generated for the given triplet. */ - public static Optional getCurrentRevision(String tld, DateTime date, RdeMode mode) { + public static Optional getCurrentRevision(String tld, Instant date, RdeMode mode) { int nextRevision = getNextRevision(tld, date, mode); if (nextRevision == 0) { return Optional.empty(); @@ -107,12 +107,12 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { * @throws IllegalStateException if not in a transaction * @throws VerifyException if the state doesn't meet the above criteria */ - public static void saveRevision(String tld, DateTime date, RdeMode mode, int revision) { + public static void saveRevision(String tld, Instant date, RdeMode mode, int revision) { checkArgument(revision >= 0, "Negative revision: %s", revision); tm().assertInTransaction(); - RdeRevisionId sqlKey = RdeRevisionId.create(tld, date.toLocalDate(), mode); + RdeRevisionId revisionId = RdeRevisionId.create(tld, toJodaLocalDate(date), mode); Optional revisionOptional = - tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, sqlKey)); + tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, revisionId)); if (revision == 0) { revisionOptional.ifPresent( rdeRevision -> { @@ -133,8 +133,7 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { revision - 1, revisionOptional.get()); } - RdeRevision object = create(tld, date.toLocalDate(), mode, revision); - tm().put(object); + tm().put(RdeRevision.create(tld, toJodaLocalDate(date), mode, revision)); } /** Class to represent the composite primary key of {@link RdeRevision} entity. */ diff --git a/core/src/main/java/google/registry/model/server/Lock.java b/core/src/main/java/google/registry/model/server/Lock.java index 0bf6320be..42c157097 100644 --- a/core/src/main/java/google/registry/model/server/Lock.java +++ b/core/src/main/java/google/registry/model/server/Lock.java @@ -34,11 +34,11 @@ import jakarta.persistence.IdClass; import jakarta.persistence.Table; import jakarta.persistence.Transient; import java.io.Serializable; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import java.util.concurrent.Callable; import javax.annotation.Nullable; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * A lock on some shared resource. @@ -79,11 +79,11 @@ public class Lock extends ImmutableObject implements Serializable { /** When the lock can be considered implicitly released. */ @Column(nullable = false) - DateTime expirationTime; + Instant expirationTime; /** When was the lock acquired. Used for logging. */ @Column(nullable = false) - DateTime acquiredTime; + Instant acquiredTime; /** The resource name used to create the lock. */ @Column(nullable = false) @@ -95,7 +95,7 @@ public class Lock extends ImmutableObject implements Serializable { @Id String scope; - public DateTime getExpirationTime() { + public Instant getExpirationTime() { return expirationTime; } @@ -109,10 +109,7 @@ public class Lock extends ImmutableObject implements Serializable { * namespace). */ private static Lock create( - String resourceName, - String scope, - DateTime acquiredTime, - Duration leaseLength) { + String resourceName, String scope, Instant acquiredTime, Duration leaseLength) { checkArgument(!Strings.isNullOrEmpty(resourceName), "resourceName cannot be null or empty"); Lock instance = new Lock(); // Add the scope to the Lock's id so that it is unique for locks acquiring the same resource @@ -130,7 +127,7 @@ public class Lock extends ImmutableObject implements Serializable { } record AcquireResult( - DateTime transactionTime, + Instant transactionTime, @Nullable Lock existingLock, @Nullable Lock newLock, LockState lockState) {} @@ -138,7 +135,7 @@ public class Lock extends ImmutableObject implements Serializable { private static void logAcquireResult(AcquireResult acquireResult) { try { Lock lock = acquireResult.existingLock(); - DateTime now = acquireResult.transactionTime(); + Instant now = acquireResult.transactionTime(); switch (acquireResult.lockState()) { case IN_USE -> logger.atInfo().log( @@ -170,7 +167,7 @@ public class Lock extends ImmutableObject implements Serializable { String scope = tld != null ? tld : GLOBAL; Callable lockAcquirer = () -> { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); // Checking if an unexpired lock still exists - if so, the lock can't be acquired. Lock lock = @@ -233,7 +230,7 @@ public class Lock extends ImmutableObject implements Serializable { tm().delete(key); lockMetrics.recordRelease( - resourceName, scope, new Duration(acquiredTime, tm().getTransactionTime())); + resourceName, scope, Duration.between(acquiredTime, tm().getTxTime())); } else { logger.atSevere().log( "The lock we acquired was transferred to someone else before we" diff --git a/core/src/main/java/google/registry/model/server/LockMetrics.java b/core/src/main/java/google/registry/model/server/LockMetrics.java index 2f26411e1..a1033203d 100644 --- a/core/src/main/java/google/registry/model/server/LockMetrics.java +++ b/core/src/main/java/google/registry/model/server/LockMetrics.java @@ -22,8 +22,8 @@ import com.google.monitoring.metrics.IncrementableMetric; import com.google.monitoring.metrics.LabelDescriptor; import com.google.monitoring.metrics.MetricRegistryImpl; import google.registry.model.server.Lock.LockState; +import java.time.Duration; import javax.annotation.Nullable; -import org.joda.time.Duration; /** Metrics for lock contention. */ class LockMetrics { @@ -67,6 +67,6 @@ class LockMetrics { } void recordRelease(String resourceName, @Nullable String tld, Duration duration) { - lockLifetimeMetric.record(duration.getMillis(), String.valueOf(tld), resourceName); + lockLifetimeMetric.record(duration.toMillis(), String.valueOf(tld), resourceName); } } diff --git a/core/src/main/java/google/registry/mosapi/MosApiMetrics.java b/core/src/main/java/google/registry/mosapi/MosApiMetrics.java index 7bf165268..efa18ae68 100644 --- a/core/src/main/java/google/registry/mosapi/MosApiMetrics.java +++ b/core/src/main/java/google/registry/mosapi/MosApiMetrics.java @@ -40,12 +40,12 @@ import google.registry.request.lock.LockHandler; import google.registry.util.Clock; import jakarta.inject.Inject; import java.io.IOException; +import java.time.Duration; import java.time.Instant; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; -import org.joda.time.Duration; /** Metrics Exporter for MoSAPI. */ public class MosApiMetrics { @@ -67,7 +67,7 @@ public class MosApiMetrics { // Lock Constants private static final String LOCK_NAME = "MosApiMetricCreation"; - private static final Duration LOCK_LEASE_TIME = Duration.standardHours(1); + private static final Duration LOCK_LEASE_TIME = Duration.ofHours(1); // Metric Names private static final String METRIC_TLD_STATUS = "tld_status"; private static final String METRIC_SERVICE_STATUS = "service_status"; diff --git a/core/src/main/java/google/registry/persistence/converter/DateTimeConverter.java b/core/src/main/java/google/registry/persistence/converter/DateTimeConverter.java index db16fb0a6..257aea563 100644 --- a/core/src/main/java/google/registry/persistence/converter/DateTimeConverter.java +++ b/core/src/main/java/google/registry/persistence/converter/DateTimeConverter.java @@ -13,7 +13,6 @@ // limitations under the License. package google.registry.persistence.converter; - import static org.joda.time.DateTimeZone.UTC; import jakarta.persistence.AttributeConverter; diff --git a/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java b/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java index 69e2f9532..4a00b6cb5 100644 --- a/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java +++ b/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java @@ -14,7 +14,9 @@ package google.registry.persistence.converter; -import google.registry.util.DateTimeUtils; +import static google.registry.util.DateTimeUtils.toLocalDate; +import static google.registry.util.DateTimeUtils.toSqlDate; + import jakarta.persistence.AttributeConverter; import jakarta.persistence.Converter; import java.sql.Date; @@ -26,11 +28,11 @@ public class LocalDateConverter implements AttributeConverter { @Override public Date convertToDatabaseColumn(LocalDate attribute) { - return attribute == null ? null : DateTimeUtils.toSqlDate(attribute); + return attribute == null ? null : toSqlDate(attribute); } @Override public LocalDate convertToEntityAttribute(Date dbData) { - return dbData == null ? null : DateTimeUtils.toLocalDate(dbData); + return dbData == null ? null : toLocalDate(dbData); } } diff --git a/core/src/main/java/google/registry/rde/BrdaCopyAction.java b/core/src/main/java/google/registry/rde/BrdaCopyAction.java index 9cd089bd1..6a8c4c248 100644 --- a/core/src/main/java/google/registry/rde/BrdaCopyAction.java +++ b/core/src/main/java/google/registry/rde/BrdaCopyAction.java @@ -14,6 +14,7 @@ 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; @@ -40,11 +41,11 @@ import jakarta.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; /** * Action that re-encrypts a BRDA escrow deposit and puts it into the upload bucket. @@ -77,7 +78,11 @@ public final class BrdaCopyAction implements Runnable { @Inject @Config("brdaBucket") String brdaBucket; @Inject @Config("rdeBucket") String stagingBucket; @Inject @Parameter(RequestParameters.PARAM_TLD) String tld; - @Inject @Parameter(RdeModule.PARAM_WATERMARK) DateTime watermark; + + @Inject + @Parameter(RdeModule.PARAM_WATERMARK) + Instant watermark; + @Inject @Parameter(RdeModule.PARAM_PREFIX) Optional prefix; @Inject @Key("brdaReceiverKey") PGPPublicKey receiverKey; @Inject @Key("brdaSigningKey") PGPKeyPair signingKey; @@ -98,7 +103,7 @@ public final class BrdaCopyAction implements Runnable { // Not urgent since file writes on GCS are atomic. Optional cursor = tm().transact(() -> tm().loadByKeyIfPresent(Cursor.createScopedVKey(BRDA, Tld.get(tld)))); - DateTime brdaCursorTime = getCursorTimeOrStartOfTime(cursor); + Instant brdaCursorTime = getCursorTimeOrStartOfTime(cursor); if (isBeforeOrAt(brdaCursorTime, watermark)) { throw new NoContentException( String.format( diff --git a/core/src/main/java/google/registry/rde/EscrowTaskRunner.java b/core/src/main/java/google/registry/rde/EscrowTaskRunner.java index 76c20ea46..79f9e4f85 100644 --- a/core/src/main/java/google/registry/rde/EscrowTaskRunner.java +++ b/core/src/main/java/google/registry/rde/EscrowTaskRunner.java @@ -15,6 +15,7 @@ package google.registry.rde; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static java.time.temporal.ChronoUnit.DAYS; import com.google.common.flogger.FluentLogger; import google.registry.model.common.Cursor; @@ -25,9 +26,9 @@ import google.registry.request.HttpException.ServiceUnavailableException; import google.registry.request.lock.LockHandler; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; import java.util.concurrent.Callable; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Runner applying guaranteed reliability to an {@link EscrowTask}. @@ -61,7 +62,7 @@ class EscrowTaskRunner { * * @param watermark the logical time for a point-in-time view of the database. */ - void runWithLock(DateTime watermark) throws Exception; + void runWithLock(Instant watermark) throws Exception; } private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @@ -88,8 +89,8 @@ class EscrowTaskRunner { Callable lockRunner = () -> { logger.atInfo().log("Performing escrow for TLD '%s'.", tld.getTld()); - DateTime startOfToday = clock.nowUtc().withTimeAtStartOfDay(); - DateTime nextRequiredRun = + Instant startOfToday = clock.now().truncatedTo(DAYS); + Instant nextRequiredRun = tm().transact(() -> tm().loadByKeyIfPresent(Cursor.createScopedVKey(cursorType, tld))) .map(Cursor::getCursorTime) .orElse(startOfToday); @@ -98,7 +99,7 @@ class EscrowTaskRunner { } logger.atInfo().log("Current cursor is: %s.", nextRequiredRun); task.runWithLock(nextRequiredRun); - DateTime nextRun = nextRequiredRun.plus(interval); + Instant nextRun = nextRequiredRun.plus(interval); logger.atInfo().log("Rolling cursor forward to %s.", nextRun); tm().transact(() -> tm().put(Cursor.createScoped(cursorType, nextRun, tld))); return null; diff --git a/core/src/main/java/google/registry/rde/Ghostryde.java b/core/src/main/java/google/registry/rde/Ghostryde.java index a39e8ae44..cd1a1a4f0 100644 --- a/core/src/main/java/google/registry/rde/Ghostryde.java +++ b/core/src/main/java/google/registry/rde/Ghostryde.java @@ -36,10 +36,10 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.time.Instant; import javax.annotation.Nullable; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; /** * Utility class for reading and writing data in the ghostryde container format. @@ -116,7 +116,8 @@ public final class Ghostryde { * set them to a constant value. */ static final String INNER_FILENAME = "file.xml"; - static final DateTime INNER_MODIFICATION_TIME = DateTime.parse("2000-01-01TZ"); + + static final Instant INNER_MODIFICATION_TIME = Instant.parse("2000-01-01T00:00:00Z"); /** Creates a ghostryde file from an in-memory byte array. */ public static byte[] encode(byte[] data, PGPPublicKey key) throws IOException { diff --git a/core/src/main/java/google/registry/rde/HostToXjcConverter.java b/core/src/main/java/google/registry/rde/HostToXjcConverter.java index d5b7ced49..cfedb5a15 100644 --- a/core/src/main/java/google/registry/rde/HostToXjcConverter.java +++ b/core/src/main/java/google/registry/rde/HostToXjcConverter.java @@ -29,7 +29,7 @@ import google.registry.xjc.rdehost.XjcRdeHost; import google.registry.xjc.rdehost.XjcRdeHostElement; import java.net.Inet6Address; import java.net.InetAddress; -import org.joda.time.DateTime; +import java.time.Instant; /** Utility class that turns a {@link Host} resource into {@link XjcRdeHostElement}. */ final class HostToXjcConverter { @@ -52,7 +52,7 @@ final class HostToXjcConverter { convertHostCommon( model, superordinateDomain.getCurrentSponsorRegistrarId(), - toDateTime(model.computeLastTransferTime(superordinateDomain))); + model.computeLastTransferTime(superordinateDomain)); if (superordinateDomain.getStatusValues().contains(StatusValue.PENDING_TRANSFER)) { bean.getStatuses().add(convertStatusValue(StatusValue.PENDING_TRANSFER)); } @@ -62,13 +62,11 @@ final class HostToXjcConverter { /** Converts {@link Host} to {@link XjcRdeHost}. */ static XjcRdeHost convertExternalHost(Host model) { return convertHostCommon( - model, - model.getPersistedCurrentSponsorRegistrarId(), - toDateTime(model.getLastTransferTime())); + model, model.getPersistedCurrentSponsorRegistrarId(), model.getLastTransferTime()); } private static XjcRdeHost convertHostCommon( - Host model, String registrarId, DateTime lastTransferTime) { + Host model, String registrarId, Instant lastTransferTime) { XjcRdeHost bean = new XjcRdeHost(); bean.setName(model.getHostName()); bean.setRoid(model.getRepoId()); @@ -78,7 +76,7 @@ final class HostToXjcConverter { bean.setUpRr(RdeAdapter.convertRr(model.getLastEppUpdateRegistrarId(), null)); bean.setCrRr(RdeAdapter.convertRr(model.getCreationRegistrarId(), null)); bean.setClID(registrarId); - bean.setTrDate(lastTransferTime); + bean.setTrDate(toDateTime(lastTransferTime)); for (StatusValue status : model.getStatusValues()) { // TODO(b/34844887): Remove when PENDING_TRANSFER is not persisted on host resources. if (status.equals(StatusValue.PENDING_TRANSFER)) { diff --git a/core/src/main/java/google/registry/rde/JSchSshSession.java b/core/src/main/java/google/registry/rde/JSchSshSession.java index d05b6f86e..c29882422 100644 --- a/core/src/main/java/google/registry/rde/JSchSshSession.java +++ b/core/src/main/java/google/registry/rde/JSchSshSession.java @@ -25,7 +25,7 @@ import google.registry.config.RegistryConfig.Config; import jakarta.inject.Inject; import java.io.Closeable; import java.net.URI; -import org.joda.time.Duration; +import java.time.Duration; /** * SFTP connection {@link Session} delegate that implements {@link Closeable}. @@ -67,9 +67,9 @@ final class JSchSshSession implements Closeable { if (url.getPass().isPresent()) { session.setPassword(url.getPass().get()); } - session.setTimeout((int) sshTimeout.getMillis()); - session.connect((int) sshTimeout.getMillis()); - return new JSchSshSession(session, url, (int) sshTimeout.getMillis()); + session.setTimeout((int) sshTimeout.toMillis()); + session.connect((int) sshTimeout.toMillis()); + return new JSchSshSession(session, url, (int) sshTimeout.toMillis()); } } diff --git a/core/src/main/java/google/registry/rde/LoggingSftpProgressMonitor.java b/core/src/main/java/google/registry/rde/LoggingSftpProgressMonitor.java index baba9476b..dda05b269 100644 --- a/core/src/main/java/google/registry/rde/LoggingSftpProgressMonitor.java +++ b/core/src/main/java/google/registry/rde/LoggingSftpProgressMonitor.java @@ -20,8 +20,8 @@ import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.SftpProgressMonitor; import google.registry.util.Clock; import jakarta.inject.Inject; -import org.joda.time.DateTime; -import org.joda.time.Duration; +import java.time.Duration; +import java.time.Instant; /** A progress monitor for SFTP operations that writes status to logs periodically. */ public class LoggingSftpProgressMonitor implements SftpProgressMonitor { @@ -32,7 +32,7 @@ public class LoggingSftpProgressMonitor implements SftpProgressMonitor { private final Clock clock; private long bytesOfLastLog = 0; private int callsSinceLastLog = 0; - private DateTime timeOfLastLog; + private Instant timeOfLastLog; @Inject LoggingSftpProgressMonitor(Clock clock) { @@ -49,7 +49,7 @@ public class LoggingSftpProgressMonitor implements SftpProgressMonitor { @Override public void init(int op, String src, String dest, long max) { - timeOfLastLog = clock.nowUtc(); + timeOfLastLog = clock.now(); logger.atInfo().log( "Initiating SFTP transfer from '%s' to '%s' using mode %s, max size %,d bytes.", src, dest, OPERATION_MODES.getOrDefault(op, "(unknown)"), max); @@ -60,11 +60,11 @@ public class LoggingSftpProgressMonitor implements SftpProgressMonitor { callsSinceLastLog++; long bytesSinceLastLog = count - bytesOfLastLog; if (bytesSinceLastLog > LOGGING_CHUNK_SIZE_BYTES) { - DateTime now = clock.nowUtc(); + Instant now = clock.now(); logger.atInfo().log( "%,d more bytes transmitted in %,d ms; %,d bytes in total. [%,d calls to count()]", bytesSinceLastLog, - new Duration(timeOfLastLog, now).getMillis(), + Duration.between(timeOfLastLog, now).toMillis(), count, callsSinceLastLog); bytesOfLastLog = count; diff --git a/core/src/main/java/google/registry/rde/PendingDeposit.java b/core/src/main/java/google/registry/rde/PendingDeposit.java index c9e28a1ad..4b41e8e93 100644 --- a/core/src/main/java/google/registry/rde/PendingDeposit.java +++ b/core/src/main/java/google/registry/rde/PendingDeposit.java @@ -22,6 +22,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Serial; import java.io.Serializable; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; import org.apache.beam.sdk.coders.AtomicCoder; @@ -29,8 +31,6 @@ import org.apache.beam.sdk.coders.BooleanCoder; import org.apache.beam.sdk.coders.NullableCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.coders.VarIntCoder; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Container representing a single RDE or BRDA XML escrow deposit that needs to be created. @@ -68,8 +68,8 @@ public record PendingDeposit( @Nullable Integer revision) implements Serializable { - public DateTime watermark() { - return DateTime.parse(watermarkStr); + public Instant watermark() { + return Instant.parse(watermarkStr); } public Duration interval() { @@ -79,14 +79,14 @@ public record PendingDeposit( @Serial private static final long serialVersionUID = 3141095605225904433L; public static PendingDeposit create( - String tld, DateTime watermark, RdeMode mode, CursorType cursor, Duration interval) { + String tld, Instant watermark, RdeMode mode, CursorType cursor, Duration interval) { return new PendingDeposit( false, tld, watermark.toString(), mode, cursor, interval.toString(), null, null); } public static PendingDeposit createInManualOperation( String tld, - DateTime watermark, + Instant watermark, RdeMode mode, String directoryWithTrailingSlash, @Nullable Integer revision) { diff --git a/core/src/main/java/google/registry/rde/PendingDepositChecker.java b/core/src/main/java/google/registry/rde/PendingDepositChecker.java index 7e4a762c0..267ae7cf9 100644 --- a/core/src/main/java/google/registry/rde/PendingDepositChecker.java +++ b/core/src/main/java/google/registry/rde/PendingDepositChecker.java @@ -17,6 +17,9 @@ package google.registry.rde; import static com.google.common.base.Preconditions.checkArgument; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.isBeforeOrAt; +import static google.registry.util.DateTimeUtils.plusDays; +import static java.time.ZoneOffset.UTC; +import static java.time.temporal.ChronoUnit.DAYS; import com.google.common.collect.ImmutableSetMultimap; import google.registry.config.RegistryConfig.Config; @@ -28,9 +31,9 @@ import google.registry.model.tld.Tld.TldType; import google.registry.model.tld.Tlds; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Utility class that determines which RDE or BRDA deposits need to be created. @@ -64,25 +67,22 @@ public final class PendingDepositChecker { return new ImmutableSetMultimap.Builder() .putAll( getTldsAndWatermarksPendingDeposit( - RdeMode.FULL, - CursorType.RDE_STAGING, - rdeInterval, - clock.nowUtc().withTimeAtStartOfDay())) + RdeMode.FULL, CursorType.RDE_STAGING, rdeInterval, clock.now().truncatedTo(DAYS))) .putAll( getTldsAndWatermarksPendingDeposit( RdeMode.THIN, CursorType.BRDA, brdaInterval, - advanceToDayOfWeek(clock.nowUtc().withTimeAtStartOfDay(), brdaDayOfWeek))) + advanceToDayOfWeek(clock.now().truncatedTo(DAYS), brdaDayOfWeek))) .build(); } private ImmutableSetMultimap getTldsAndWatermarksPendingDeposit( - RdeMode mode, CursorType cursorType, Duration interval, DateTime startingPoint) { - checkArgument(interval.isLongerThan(Duration.ZERO)); + RdeMode mode, CursorType cursorType, Duration interval, Instant startingPoint) { + checkArgument(interval.compareTo(Duration.ZERO) > 0); ImmutableSetMultimap.Builder builder = new ImmutableSetMultimap.Builder<>(); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); for (String tldStr : Tlds.getTldsOfType(TldType.REAL)) { Tld tld = Tld.get(tldStr); if (!tld.getEscrowEnabled()) { @@ -91,9 +91,9 @@ public final class PendingDepositChecker { // Avoid creating a transaction unless absolutely necessary. Optional maybeCursor = tm().transact(() -> tm().loadByKeyIfPresent(Cursor.createScopedVKey(cursorType, tld))); - DateTime cursorValue = maybeCursor.map(Cursor::getCursorTime).orElse(startingPoint); + Instant cursorValue = maybeCursor.map(Cursor::getCursorTime).orElse(startingPoint); if (isBeforeOrAt(cursorValue, now)) { - DateTime watermark = + Instant watermark = maybeCursor .map(Cursor::getCursorTime) .orElse(transactionallyInitializeCursor(tld, cursorType, startingPoint)); @@ -105,8 +105,8 @@ public final class PendingDepositChecker { return builder.build(); } - private DateTime transactionallyInitializeCursor( - final Tld tld, final CursorType cursorType, final DateTime initialValue) { + private Instant transactionallyInitializeCursor( + Tld tld, CursorType cursorType, Instant initialValue) { return tm().transact( () -> { Optional maybeCursor = @@ -119,9 +119,9 @@ public final class PendingDepositChecker { }); } - private static DateTime advanceToDayOfWeek(DateTime date, int dayOfWeek) { - while (date.getDayOfWeek() != dayOfWeek) { - date = date.plusDays(1); + private static Instant advanceToDayOfWeek(Instant date, int dayOfWeek) { + while (date.atZone(UTC).getDayOfWeek().getValue() != dayOfWeek) { + date = plusDays(date, 1); } return date; } diff --git a/core/src/main/java/google/registry/rde/RdeCounter.java b/core/src/main/java/google/registry/rde/RdeCounter.java index 0a2a54cee..25aaddc6e 100644 --- a/core/src/main/java/google/registry/rde/RdeCounter.java +++ b/core/src/main/java/google/registry/rde/RdeCounter.java @@ -14,6 +14,8 @@ package google.registry.rde; +import static google.registry.util.DateTimeUtils.toDateTime; + import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import google.registry.model.rde.RdeMode; @@ -23,11 +25,11 @@ import google.registry.xjc.rdeheader.XjcRdeHeaderCount; import google.registry.xjc.rdeheader.XjcRdeHeaderElement; import google.registry.xjc.rdereport.XjcRdeReport; import jakarta.inject.Inject; +import java.time.Instant; import java.util.EnumMap; import java.util.EnumSet; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.concurrent.NotThreadSafe; -import org.joda.time.DateTime; /** Utility class for generating a single {@link XjcRdeHeader} while marshalling a deposit. */ @NotThreadSafe @@ -61,13 +63,12 @@ public final class RdeCounter { } /** Returns an ICANN notification report as a JAXB object. */ - public XjcRdeReport - makeReport(String id, DateTime watermark, XjcRdeHeader header, int revision) { + public XjcRdeReport makeReport(String id, Instant watermark, XjcRdeHeader header, int revision) { XjcRdeReport report = new XjcRdeReport(); report.setId(id); report.setKind(XjcRdeDepositTypeType.FULL); - report.setCrDate(watermark); - report.setWatermark(watermark); + report.setCrDate(toDateTime(watermark)); + report.setWatermark(toDateTime(watermark)); report.setVersion(ICANN_REPORT_SPEC_VERSION); report.setRydeSpecEscrow(URI_ESCROW); report.setRydeSpecMapping(URI_MAPPING); diff --git a/core/src/main/java/google/registry/rde/RdeMarshaller.java b/core/src/main/java/google/registry/rde/RdeMarshaller.java index 27acbc6d1..d9b5adc6f 100644 --- a/core/src/main/java/google/registry/rde/RdeMarshaller.java +++ b/core/src/main/java/google/registry/rde/RdeMarshaller.java @@ -15,6 +15,7 @@ package google.registry.rde; import static com.google.common.base.Verify.verify; +import static google.registry.util.DateTimeUtils.toDateTime; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.flogger.FluentLogger; @@ -41,9 +42,9 @@ import jakarta.xml.bind.MarshalException; import java.io.ByteArrayOutputStream; import java.io.Serial; import java.io.Serializable; +import java.time.Instant; import java.util.Collection; import javax.annotation.concurrent.NotThreadSafe; -import org.joda.time.DateTime; /** XML document fragment marshaller for RDE. */ @NotThreadSafe @@ -61,7 +62,7 @@ public final class RdeMarshaller implements Serializable { /** Returns top-portion of XML document. */ public String makeHeader( - String depositId, DateTime watermark, Collection uris, int revision) { + String depositId, Instant watermark, Collection uris, int revision) { // We can't make JAXB marshal half an element. So we're going to use a kludge where we provide // it with the minimum data necessary to marshal a deposit, and then cut it up by manually. XjcRdeMenuType menu = new XjcRdeMenuType(); @@ -74,7 +75,7 @@ public final class RdeMarshaller implements Serializable { contents.getContents().add(new XjcRdePolicyElement(policy)); XjcRdeDeposit deposit = new XjcRdeDeposit(); deposit.setId(depositId); - deposit.setWatermark(watermark); + deposit.setWatermark(toDateTime(watermark)); deposit.setType(XjcRdeDepositTypeType.FULL); if (revision > 0) { deposit.setResend(revision); diff --git a/core/src/main/java/google/registry/rde/RdeModule.java b/core/src/main/java/google/registry/rde/RdeModule.java index 67faa174d..1f06e0db9 100644 --- a/core/src/main/java/google/registry/rde/RdeModule.java +++ b/core/src/main/java/google/registry/rde/RdeModule.java @@ -17,8 +17,8 @@ package google.registry.rde; import static google.registry.request.RequestParameters.extractBooleanParameter; import static google.registry.request.RequestParameters.extractOptionalIntParameter; import static google.registry.request.RequestParameters.extractOptionalParameter; -import static google.registry.request.RequestParameters.extractRequiredDatetimeParameter; -import static google.registry.request.RequestParameters.extractSetOfDatetimeParameters; +import static google.registry.request.RequestParameters.extractRequiredInstantParameter; +import static google.registry.request.RequestParameters.extractSetOfInstantParameters; import static google.registry.request.RequestParameters.extractSetOfParameters; import com.google.common.collect.ImmutableSet; @@ -28,8 +28,8 @@ import dagger.Module; import dagger.Provides; import google.registry.request.Parameter; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** Dagger module for RDE package. */ @Module @@ -49,14 +49,14 @@ public abstract class RdeModule { @Provides @Parameter(PARAM_WATERMARK) - static DateTime provideWatermark(HttpServletRequest req) { - return extractRequiredDatetimeParameter(req, PARAM_WATERMARK); + static Instant provideWatermark(HttpServletRequest req) { + return extractRequiredInstantParameter(req, PARAM_WATERMARK); } @Provides @Parameter(PARAM_WATERMARKS) - static ImmutableSet provideWatermarks(HttpServletRequest req) { - return extractSetOfDatetimeParameters(req, PARAM_WATERMARKS); + static ImmutableSet provideWatermarks(HttpServletRequest req) { + return extractSetOfInstantParameters(req, PARAM_WATERMARKS); } @Provides diff --git a/core/src/main/java/google/registry/rde/RdeReportAction.java b/core/src/main/java/google/registry/rde/RdeReportAction.java index 154702c70..506fce860 100644 --- a/core/src/main/java/google/registry/rde/RdeReportAction.java +++ b/core/src/main/java/google/registry/rde/RdeReportAction.java @@ -14,6 +14,7 @@ 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; @@ -44,10 +45,10 @@ import google.registry.request.auth.Auth; import jakarta.inject.Inject; import java.io.IOException; import java.io.InputStream; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openpgp.PGPPrivateKey; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Action that uploads a small XML RDE report to ICANN after {@link RdeUploadAction} has finished. @@ -81,13 +82,13 @@ public final class RdeReportAction implements Runnable, EscrowTask { } @Override - public void runWithLock(DateTime watermark) throws Exception { + public void runWithLock(Instant watermark) throws Exception { Optional cursor = tm().transact( () -> tm().loadByKeyIfPresent( Cursor.createScopedVKey(CursorType.RDE_UPLOAD, Tld.get(tld)))); - DateTime cursorTime = getCursorTimeOrStartOfTime(cursor); + Instant cursorTime = getCursorTimeOrStartOfTime(cursor); if (isBeforeOrAt(cursorTime, watermark)) { throw new NoContentException( String.format( diff --git a/core/src/main/java/google/registry/rde/RdeStagingAction.java b/core/src/main/java/google/registry/rde/RdeStagingAction.java index 890e892a3..bcd2fe2aa 100644 --- a/core/src/main/java/google/registry/rde/RdeStagingAction.java +++ b/core/src/main/java/google/registry/rde/RdeStagingAction.java @@ -18,11 +18,13 @@ import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMulti import static google.registry.beam.BeamUtils.createJobName; import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.POST; +import static google.registry.util.DateTimeUtils.LOWERCASE_TIMESTAMP_FORMATTER; import static google.registry.xml.ValidationMode.LENIENT; import static google.registry.xml.ValidationMode.STRICT; import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static jakarta.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static java.time.temporal.ChronoUnit.DAYS; import static java.util.function.Function.identity; import com.google.api.services.dataflow.Dataflow; @@ -59,9 +61,9 @@ import google.registry.util.RegistryEnvironment; import google.registry.xml.ValidationMode; import jakarta.inject.Inject; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Action that kicks off a Dataflow job to stage escrow deposit XML files on GCS for RDE/BRDA for @@ -237,7 +239,11 @@ public final class RdeStagingAction implements Runnable { @Inject @Parameter(RdeModule.PARAM_DIRECTORY) Optional directory; @Inject @Parameter(RdeModule.PARAM_MODE) ImmutableSet modeStrings; @Inject @Parameter(RequestParameters.PARAM_TLDS) ImmutableSet tlds; - @Inject @Parameter(RdeModule.PARAM_WATERMARKS) ImmutableSet watermarks; + + @Inject + @Parameter(RdeModule.PARAM_WATERMARKS) + ImmutableSet watermarks; + @Inject @Parameter(RdeModule.PARAM_REVISION) Optional revision; @Inject @Parameter(RdeModule.PARAM_LENIENT) boolean lenient; @Inject @Key("rdeStagingEncryptionKey") byte[] stagingKeyBytes; @@ -271,7 +277,7 @@ public final class RdeStagingAction implements Runnable { .setJobName( createJobName( String.format( - "rde-%s", watermark.toString("yyyy-MM-dd't'HH-mm-ss'z'")), + "rde-%s", LOWERCASE_TIMESTAMP_FORMATTER.format(watermark)), clock)) .setContainerSpecGcsPath( String.format("%s/%s_metadata.json", stagingBucketUrl, PIPELINE_NAME)) @@ -340,7 +346,7 @@ public final class RdeStagingAction implements Runnable { Multimaps.filterValues( pendingDepositChecker.getTldsAndWatermarksPendingDepositForRdeAndBrda(), pending -> { - if (clock.nowUtc().isBefore(pending.watermark().plus(transactionCooldown))) { + if (clock.now().isBefore(pending.watermark().plus(transactionCooldown))) { logger.atInfo().log( "Ignoring within %s cooldown: %s", transactionCooldown, pending); return false; @@ -384,8 +390,8 @@ public final class RdeStagingAction implements Runnable { // In theory, BRDA deposits should be on a specific day of the week, but in manual mode, let the // user create deposits on other days. But dates should definitely be at the start of the day; // otherwise, confusion is likely. - for (DateTime watermark : watermarks) { - if (!watermark.equals(watermark.withTimeAtStartOfDay())) { + for (Instant watermark : watermarks) { + if (!watermark.equals(watermark.truncatedTo(DAYS))) { throw new BadRequestException("Watermarks must be at the start of a day."); } } @@ -398,7 +404,7 @@ public final class RdeStagingAction implements Runnable { new ImmutableSetMultimap.Builder<>(); for (String tld : tlds) { - for (DateTime watermark : watermarks) { + for (Instant watermark : watermarks) { for (RdeMode mode : modes) { pendingsBuilder.put( tld, diff --git a/core/src/main/java/google/registry/rde/RdeUploadAction.java b/core/src/main/java/google/registry/rde/RdeUploadAction.java index d1a92b53b..942de8247 100644 --- a/core/src/main/java/google/registry/rde/RdeUploadAction.java +++ b/core/src/main/java/google/registry/rde/RdeUploadAction.java @@ -14,6 +14,7 @@ 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; @@ -25,7 +26,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.rde.RdeModule.RDE_REPORT_QUEUE; import static google.registry.rde.RdeUtils.findMostRecentPrefixForWatermark; import static google.registry.request.Action.Method.POST; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static java.util.Arrays.asList; @@ -65,12 +66,12 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Action that securely uploads an RDE XML file from Cloud Storage to a trusted third party (such as @@ -133,7 +134,7 @@ public final class RdeUploadAction implements Runnable, EscrowTask { } @Override - public void runWithLock(final DateTime watermark) throws Exception { + public void runWithLock(Instant watermark) throws Exception { // If a prefix is not provided,try to determine the prefix. This should only happen when the RDE // upload cron job runs to catch up any un-retried (i. e. expected) RDE failures. String actualPrefix = @@ -142,7 +143,7 @@ public final class RdeUploadAction implements Runnable, EscrowTask { Optional cursor = tm().transact( () -> tm().loadByKeyIfPresent(Cursor.createScopedVKey(RDE_STAGING, Tld.get(tld)))); - DateTime stagingCursorTime = getCursorTimeOrStartOfTime(cursor); + Instant stagingCursorTime = getCursorTimeOrStartOfTime(cursor); if (isBeforeOrAt(stagingCursorTime, watermark)) { throw new NoContentException( String.format( @@ -150,23 +151,23 @@ public final class RdeUploadAction implements Runnable, EscrowTask { + "last RDE staging completion was before %s", tld, watermark, stagingCursorTime)); } - DateTime sftpCursorTime = + Instant sftpCursorTime = tm().transact( () -> tm().loadByKeyIfPresent(Cursor.createScopedVKey(RDE_UPLOAD_SFTP, Tld.get(tld)))) .map(Cursor::getCursorTime) - .orElse(START_OF_TIME); - Duration timeSinceLastSftp = new Duration(sftpCursorTime, clock.nowUtc()); - if (timeSinceLastSftp.isShorterThan(sftpCooldown)) { + .orElse(START_INSTANT); + Duration timeSinceLastSftp = Duration.between(sftpCursorTime, clock.now()); + if (timeSinceLastSftp.compareTo(sftpCooldown) < 0) { throw new NoContentException( String.format( "Waiting on %d minute SFTP cooldown for TLD %s to send %s upload; " + "last upload attempt was at %s (%d minutes ago)", - sftpCooldown.getStandardMinutes(), + sftpCooldown.toMinutes(), tld, watermark, sftpCursorTime, - timeSinceLastSftp.getStandardMinutes())); + timeSinceLastSftp.toMinutes())); } int revision = RdeRevision.getCurrentRevision(tld, watermark, FULL) @@ -189,10 +190,7 @@ public final class RdeUploadAction implements Runnable, EscrowTask { logger.atInfo().log( "Updating RDE cursor '%s' for TLD '%s' following successful upload.", RDE_UPLOAD_SFTP, tld); tm().transact( - () -> - tm().put( - Cursor.createScoped( - RDE_UPLOAD_SFTP, tm().getTransactionTime(), Tld.get(tld)))); + () -> tm().put(Cursor.createScoped(RDE_UPLOAD_SFTP, tm().getTxTime(), Tld.get(tld)))); response.setContentType(PLAIN_TEXT_UTF_8); response.setPayload(String.format("OK %s %s\n", tld, watermark)); } @@ -222,7 +220,7 @@ public final class RdeUploadAction implements Runnable, EscrowTask { */ @VisibleForTesting private void upload( - BlobId xmlFile, long xmlLength, DateTime watermark, String name, String nameWithoutPrefix) + BlobId xmlFile, long xmlLength, Instant watermark, String name, String nameWithoutPrefix) throws Exception { logger.atInfo().log("Uploading XML file '%s' to remote path '%s'.", xmlFile, uploadUrl); try (InputStream gcsInput = gcsUtils.openInputStream(xmlFile); diff --git a/core/src/main/java/google/registry/rde/RdeUtils.java b/core/src/main/java/google/registry/rde/RdeUtils.java index 0760400ab..557ecab61 100644 --- a/core/src/main/java/google/registry/rde/RdeUtils.java +++ b/core/src/main/java/google/registry/rde/RdeUtils.java @@ -14,6 +14,7 @@ package google.registry.rde; +import static google.registry.util.DateTimeUtils.LOWERCASE_TIMESTAMP_FORMATTER; import static google.registry.util.HexDumper.dumpHex; import static java.nio.charset.StandardCharsets.UTF_8; @@ -28,10 +29,7 @@ import google.registry.xml.XmlException; import java.io.BufferedInputStream; import java.io.IOException; import java.nio.ByteBuffer; -import org.joda.time.DateTime; -import org.joda.time.ReadableInstant; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; +import java.time.Instant; /** Helper methods for RDE. */ public final class RdeUtils { @@ -42,15 +40,11 @@ public final class RdeUtils { /** Regular expression for extracting creation timestamp from a raw XML deposit. */ private static final Pattern WATERMARK_PATTERN = Pattern.compile("[<:]watermark>\\s*([^<\\s]+)"); - /** Standard ISO date/time formatter without milliseconds. Used for watermarks. */ - private static final DateTimeFormatter DATETIME_FORMATTER = - ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(); - /** - * Look at some bytes from {@code xmlInput} to ensure it appears to be a FULL XML deposit and - * then use a regular expression to extract the watermark timestamp which is returned. + * Look at some bytes from {@code xmlInput} to ensure it appears to be a FULL XML deposit and then + * use a regular expression to extract the watermark timestamp which is returned. */ - public static DateTime peekWatermark(BufferedInputStream xmlInput) + public static Instant peekWatermark(BufferedInputStream xmlInput) throws IOException, XmlException { xmlInput.mark(PEEK_SIZE); byte[] peek = new byte[PEEK_SIZE]; @@ -70,16 +64,16 @@ public final class RdeUtils { if (!watermarkMatcher.find()) { throw new XmlException("Could not find RDE watermark in XML"); } - return DATETIME_FORMATTER.parseDateTime(watermarkMatcher.group(1)); + return Instant.parse(watermarkMatcher.group(1)); } /** Find the most recent folder in the given GCS bucket for the given watermark. */ public static String findMostRecentPrefixForWatermark( - DateTime watermark, String bucket, String tld, GcsUtils gcsUtils) throws NoContentException { + Instant watermark, String bucket, String tld, GcsUtils gcsUtils) throws NoContentException { // The prefix is always in the format of: rde-2022-02-21t00-00-00z-2022-02-21t00-07-33z, where // the first datetime is the watermark and the second one is the time when the RDE beam job // launched. We search for the latest folder that starts with "rde-[watermark]". - String partialPrefix = String.format("rde-%s", watermark.toString("yyyy-MM-dd't'HH-mm-ss'z'")); + String partialPrefix = String.format("rde-%s", LOWERCASE_TIMESTAMP_FORMATTER.format(watermark)); String latestFilenameSuffix = null; try { latestFilenameSuffix = @@ -106,8 +100,8 @@ public final class RdeUtils { * big-endian byte-array which is then converted to a base32 string without padding that's no * longer than 13 chars because {@code 13 = Ceiling[Log[32, 2^64]]}. How lucky! */ - public static String timestampToId(ReadableInstant timestamp) { - byte[] bytes = ByteBuffer.allocate(8).putLong(timestamp.getMillis()).array(); + public static String timestampToId(Instant timestamp) { + byte[] bytes = ByteBuffer.allocate(8).putLong(timestamp.toEpochMilli()).array(); return BaseEncoding.base32().omitPadding().encode(bytes); } diff --git a/core/src/main/java/google/registry/rde/RydeEncoder.java b/core/src/main/java/google/registry/rde/RydeEncoder.java index da3dfd1c5..748d1bf59 100644 --- a/core/src/main/java/google/registry/rde/RydeEncoder.java +++ b/core/src/main/java/google/registry/rde/RydeEncoder.java @@ -26,12 +26,12 @@ import com.google.common.io.Closer; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.time.Instant; import java.util.Collection; import javax.annotation.concurrent.NotThreadSafe; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; /** * Stream that performs the full RyDE encryption. @@ -63,7 +63,7 @@ public final class RydeEncoder extends FilterOutputStream { OutputStream sigOutput, long dataLength, String filenamePrefix, - DateTime modified, + Instant modified, PGPKeyPair signingKey, Collection receiverKeys) { super(null); @@ -110,7 +110,7 @@ public final class RydeEncoder extends FilterOutputStream { OutputStream sigOutput; Long dataLength; String filenamePrefix; - DateTime modified; + Instant modified; PGPKeyPair signingKey; ImmutableList receiverKeys; @@ -131,7 +131,7 @@ public final class RydeEncoder extends FilterOutputStream { } /** Sets the information about the unencoded data that will follow. */ - public Builder setFileMetadata(String filenamePrefix, long dataLength, DateTime modified) { + public Builder setFileMetadata(String filenamePrefix, long dataLength, Instant modified) { this.filenamePrefix = filenamePrefix; this.dataLength = dataLength; this.modified = modified; diff --git a/core/src/main/java/google/registry/rde/RydeFileEncoding.java b/core/src/main/java/google/registry/rde/RydeFileEncoding.java index ecb11e953..d4415782c 100644 --- a/core/src/main/java/google/registry/rde/RydeFileEncoding.java +++ b/core/src/main/java/google/registry/rde/RydeFileEncoding.java @@ -15,18 +15,18 @@ package google.registry.rde; import static org.bouncycastle.openpgp.PGPLiteralData.BINARY; -import static org.joda.time.DateTimeZone.UTC; import google.registry.util.ImprovedInputStream; import google.registry.util.ImprovedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.sql.Timestamp; +import java.time.Instant; import javax.annotation.CheckReturnValue; import javax.annotation.WillNotClose; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralDataGenerator; -import org.joda.time.DateTime; /** * Input/Output stream for reading/writing PGP literal data layer. @@ -54,12 +54,12 @@ final class RydeFileEncoding { */ @CheckReturnValue static ImprovedOutputStream openPgpFileWriter( - @WillNotClose OutputStream os, String filename, DateTime modified) { + @WillNotClose OutputStream os, String filename, Instant modified) { try { return new ImprovedOutputStream( "PgpFileWriter", new PGPLiteralDataGenerator() - .open(os, BINARY, filename, modified.toDate(), new byte[BUFFER_SIZE])); + .open(os, BINARY, filename, Timestamp.from(modified), new byte[BUFFER_SIZE])); } catch (IOException e) { throw new RuntimeException(e); } @@ -68,12 +68,12 @@ final class RydeFileEncoding { /** Input stream to a PGP file's data that also holds the file's metadata. */ static class PgpFileInputStream extends ImprovedInputStream { private final String filename; - private final DateTime modified; + private final Instant modified; private PgpFileInputStream(PGPLiteralData literal) { super("PgpFileReader", literal.getDataStream()); filename = literal.getFileName(); - modified = new DateTime(literal.getModificationTime(), UTC); + modified = literal.getModificationTime().toInstant(); } /** Returns the name of the original file. */ @@ -82,7 +82,7 @@ final class RydeFileEncoding { } /** Returns the time this file was created or modified. */ - DateTime getModified() { + Instant getModified() { return modified; } } diff --git a/core/src/main/java/google/registry/rde/RydeTar.java b/core/src/main/java/google/registry/rde/RydeTar.java index e2e85c1f3..c2e8ee5c8 100644 --- a/core/src/main/java/google/registry/rde/RydeTar.java +++ b/core/src/main/java/google/registry/rde/RydeTar.java @@ -16,6 +16,8 @@ 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; @@ -24,9 +26,9 @@ import google.registry.util.PosixTarHeader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.time.Instant; import javax.annotation.CheckReturnValue; import javax.annotation.WillNotClose; -import org.joda.time.DateTime; /** Single-file POSIX tar archive creator that wraps an {@link OutputStream}. */ final class RydeTar { @@ -41,18 +43,19 @@ final class RydeTar { */ @CheckReturnValue static ImprovedOutputStream openTarWriter( - @WillNotClose OutputStream os, long expectedSize, String filename, DateTime modified) { + @WillNotClose OutputStream os, long expectedSize, String filename, Instant modified) { checkArgument(expectedSize >= 0); checkArgument(filename.endsWith(".xml"), "Ryde expects tar archive to contain a filename with an '.xml' extension."); try { - os.write(new PosixTarHeader.Builder() - .setName(filename) - .setSize(expectedSize) - .setMtime(modified) - .build() - .getBytes()); + os.write( + new PosixTarHeader.Builder() + .setName(filename) + .setSize(expectedSize) + .setMtime(toDateTime(modified)) + .build() + .getBytes()); return new ImprovedOutputStream("RydeTarWriter", os) { /** Writes the end of archive marker. */ @Override @@ -92,8 +95,8 @@ final class RydeTar { } /** Returns the creation/modification time of the file archived in this TAR. */ - DateTime getModified() { - return header.getMtime(); + Instant getModified() { + return toInstant(header.getMtime()); } } diff --git a/core/src/main/java/google/registry/reporting/ReportingModule.java b/core/src/main/java/google/registry/reporting/ReportingModule.java index e25b46b65..d93b263fd 100644 --- a/core/src/main/java/google/registry/reporting/ReportingModule.java +++ b/core/src/main/java/google/registry/reporting/ReportingModule.java @@ -17,6 +17,7 @@ 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; @@ -28,11 +29,11 @@ import google.registry.request.Parameter; import google.registry.util.Clock; import google.registry.util.GoogleCredentialsBundle; import jakarta.servlet.http.HttpServletRequest; +import java.time.LocalDate; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Optional; -import org.joda.time.DateTimeZone; -import org.joda.time.LocalDate; -import org.joda.time.YearMonth; -import org.joda.time.format.ISODateTimeFormat; /** Dagger module for injecting common settings for all reporting tasks. */ @Module @@ -84,8 +85,9 @@ public class ReportingModule { static Optional provideYearMonthOptional(HttpServletRequest req) { Optional optionalYearMonthStr = extractOptionalParameter(req, PARAM_YEAR_MONTH); try { - return optionalYearMonthStr.map(s -> YearMonth.parse(s, ISODateTimeFormat.yearMonth())); - } catch (IllegalArgumentException e) { + return optionalYearMonthStr.map( + s -> YearMonth.parse(s, DateTimeFormatter.ofPattern("yyyy-MM"))); + } catch (IllegalArgumentException | DateTimeParseException e) { throw new BadRequestException( String.format( "yearMonth must be in yyyy-MM format, got %s instead", @@ -101,7 +103,7 @@ public class ReportingModule { static YearMonth provideYearMonth( @Parameter(PARAM_YEAR_MONTH) Optional yearMonthOptional, @Parameter(PARAM_DATE) LocalDate date) { - return yearMonthOptional.orElseGet(() -> new YearMonth(date.minusMonths(1))); + return yearMonthOptional.orElseGet(() -> YearMonth.from(date.minusMonths(1))); } /** Extracts an optional date in yyyy-MM-dd format from the request. */ @@ -110,8 +112,8 @@ public class ReportingModule { static Optional provideDateOptional(HttpServletRequest req) { Optional optionalDateString = extractOptionalParameter(req, PARAM_DATE); try { - return optionalDateString.map(s -> LocalDate.parse(s, ISODateTimeFormat.yearMonthDay())); - } catch (IllegalArgumentException e) { + return optionalDateString.map(s -> LocalDate.parse(s, DateTimeFormatter.ISO_LOCAL_DATE)); + } catch (IllegalArgumentException | DateTimeParseException e) { throw new BadRequestException( String.format( "date must be in yyyy-MM-dd format, got %s instead", @@ -127,8 +129,7 @@ public class ReportingModule { @Provides @Parameter(PARAM_DATE) static LocalDate provideDate(HttpServletRequest req, Clock clock) { - return provideDateOptional(req) - .orElseGet(() -> new LocalDate(clock.nowUtc(), DateTimeZone.UTC)); + return provideDateOptional(req).orElseGet(() -> LocalDate.ofInstant(clock.now(), UTC)); } /** Constructs a {@link Dataflow} API client with default settings. */ diff --git a/core/src/main/java/google/registry/reporting/billing/BillingEmailUtils.java b/core/src/main/java/google/registry/reporting/billing/BillingEmailUtils.java index 5ac37e06c..0f0fb059e 100644 --- a/core/src/main/java/google/registry/reporting/billing/BillingEmailUtils.java +++ b/core/src/main/java/google/registry/reporting/billing/BillingEmailUtils.java @@ -28,8 +28,8 @@ import google.registry.reporting.billing.BillingModule.InvoiceDirectoryPrefix; import google.registry.util.EmailMessage; import jakarta.inject.Inject; import jakarta.mail.internet.InternetAddress; +import java.time.YearMonth; import java.util.Optional; -import org.joda.time.YearMonth; /** Utility functions for sending emails involving monthly invoices. */ public class BillingEmailUtils { diff --git a/core/src/main/java/google/registry/reporting/billing/BillingModule.java b/core/src/main/java/google/registry/reporting/billing/BillingModule.java index b8ed8d15a..01f0c90af 100644 --- a/core/src/main/java/google/registry/reporting/billing/BillingModule.java +++ b/core/src/main/java/google/registry/reporting/billing/BillingModule.java @@ -25,7 +25,7 @@ import jakarta.inject.Qualifier; import jakarta.servlet.http.HttpServletRequest; import java.lang.annotation.Documented; import java.lang.annotation.Retention; -import org.joda.time.YearMonth; +import java.time.YearMonth; /** Module for dependencies required by monthly billing actions. */ @Module diff --git a/core/src/main/java/google/registry/reporting/billing/GenerateInvoicesAction.java b/core/src/main/java/google/registry/reporting/billing/GenerateInvoicesAction.java index c8e7a272f..bb5f44de5 100644 --- a/core/src/main/java/google/registry/reporting/billing/GenerateInvoicesAction.java +++ b/core/src/main/java/google/registry/reporting/billing/GenerateInvoicesAction.java @@ -39,8 +39,8 @@ import google.registry.util.Clock; import google.registry.util.RegistryEnvironment; import jakarta.inject.Inject; import java.io.IOException; -import org.joda.time.Duration; -import org.joda.time.YearMonth; +import java.time.Duration; +import java.time.YearMonth; /** * Invokes the {@code InvoicingPipeline} beam template via the REST api, and enqueues the {@link @@ -114,7 +114,7 @@ public class GenerateInvoicesAction implements Runnable { String.format("%s/%s_metadata.json", stagingBucketUrl, PIPELINE_NAME)) .setParameters( new ImmutableMap.Builder() - .put("yearMonth", yearMonth.toString("yyyy-MM")) + .put("yearMonth", yearMonth.toString()) .put("invoiceFilePrefix", invoiceFilePrefix) .put("billingBucketUrl", billingBucketUrl) .put("registryEnvironment", RegistryEnvironment.get().name()) @@ -145,7 +145,7 @@ public class GenerateInvoicesAction implements Runnable { jobId, ReportingModule.PARAM_YEAR_MONTH, yearMonth.toString()), - Duration.standardMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES))); + Duration.ofMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES))); } response.setStatus(SC_OK); response.setPayload(String.format("Launched invoicing pipeline: %s", jobId)); diff --git a/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java b/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java index 4c57c6855..43e776971 100644 --- a/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java +++ b/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java @@ -35,7 +35,7 @@ import google.registry.request.Response; import google.registry.request.auth.Auth; import jakarta.inject.Inject; import java.io.IOException; -import org.joda.time.YearMonth; +import java.time.YearMonth; /** * Uploads the results of the {@link google.registry.beam.billing.InvoicingPipeline}. diff --git a/core/src/main/java/google/registry/reporting/icann/ActivityReportingQueryBuilder.java b/core/src/main/java/google/registry/reporting/icann/ActivityReportingQueryBuilder.java index 45f2fce43..7aa4f1986 100644 --- a/core/src/main/java/google/registry/reporting/icann/ActivityReportingQueryBuilder.java +++ b/core/src/main/java/google/registry/reporting/icann/ActivityReportingQueryBuilder.java @@ -23,10 +23,9 @@ import google.registry.config.RegistryConfig.Config; import google.registry.util.SqlTemplate; import jakarta.inject.Inject; import jakarta.inject.Named; -import org.joda.time.LocalDate; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; +import java.time.LocalDate; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; /** Utility class that produces SQL queries used to generate activity reports from Bigquery. */ public final class ActivityReportingQueryBuilder implements QueryBuilder { @@ -64,9 +63,9 @@ public final class ActivityReportingQueryBuilder implements QueryBuilder { /** Sets the month we're doing activity reporting for, and returns the view query map. */ @Override public ImmutableMap getViewQueryMap(YearMonth yearMonth) { - LocalDate firstDayOfMonth = yearMonth.toLocalDate(1); + LocalDate firstDayOfMonth = yearMonth.atDay(1); // The pattern-matching is inclusive, so we subtract 1 day to only report that month's data. - LocalDate lastDayOfMonth = yearMonth.toLocalDate(1).plusMonths(1).minusDays(1); + LocalDate lastDayOfMonth = yearMonth.atDay(1).plusMonths(1).minusDays(1); ImmutableMap.Builder queriesBuilder = ImmutableMap.builder(); String operationalRegistrarsQuery; @@ -81,20 +80,20 @@ public final class ActivityReportingQueryBuilder implements QueryBuilder { queriesBuilder.put(getTableName(DNS_COUNTS, yearMonth), dnsCountsQuery); // Convert reportingMonth into YYYYMMDD format for Bigquery table partition pattern-matching. - DateTimeFormatter logTableFormatter = DateTimeFormat.forPattern("yyyyMMdd"); + DateTimeFormatter logTableFormatter = DateTimeFormatter.ofPattern("yyyyMMdd"); String monthlyLogsQuery = SqlTemplate.create(getQueryFromFile(MONTHLY_LOGS + ".sql")) .put("PROJECT_ID", projectId) - .put("FIRST_DAY_OF_MONTH", logTableFormatter.print(firstDayOfMonth)) - .put("LAST_DAY_OF_MONTH", logTableFormatter.print(lastDayOfMonth)) + .put("FIRST_DAY_OF_MONTH", logTableFormatter.format(firstDayOfMonth)) + .put("LAST_DAY_OF_MONTH", logTableFormatter.format(lastDayOfMonth)) .build(); queriesBuilder.put(getTableName(MONTHLY_LOGS, yearMonth), monthlyLogsQuery); String eppQuery = SqlTemplate.create(getQueryFromFile(EPP_METRICS + ".sql")) .put("PROJECT_ID", projectId) - .put("FIRST_DAY_OF_MONTH", logTableFormatter.print(firstDayOfMonth)) - .put("LAST_DAY_OF_MONTH", logTableFormatter.print(lastDayOfMonth)) + .put("FIRST_DAY_OF_MONTH", logTableFormatter.format(firstDayOfMonth)) + .put("LAST_DAY_OF_MONTH", logTableFormatter.format(lastDayOfMonth)) .build(); queriesBuilder.put(getTableName(EPP_METRICS, yearMonth), eppQuery); diff --git a/core/src/main/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinator.java b/core/src/main/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinator.java index 6d2eba9e0..c7f2bf302 100644 --- a/core/src/main/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinator.java +++ b/core/src/main/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinator.java @@ -18,9 +18,9 @@ import com.google.common.io.Resources; import google.registry.bigquery.BigqueryUtils.TableType; import google.registry.util.ResourceUtils; import google.registry.util.SqlTemplate; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; import java.util.concurrent.ExecutionException; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; /** * DNS Count query that relies on a table Cloud DNS publishes internally to Google. @@ -76,7 +76,7 @@ public class CloudDnsCountQueryCoordinator extends DnsCountQueryCoordinator { .put("PROJECT_ID", projectId) .put("DATASET_ID", icannReportingDataSet) .put("TABLE_ID", TABLE_ID) - .put("YEAR_MONTH", DateTimeFormat.forPattern("yyyyMM").print(yearMonth)); + .put("YEAR_MONTH", DateTimeFormatter.ofPattern("yyyyMM").format(yearMonth)); return queryTemplate.build(); } } diff --git a/core/src/main/java/google/registry/reporting/icann/DnsCountQueryCoordinator.java b/core/src/main/java/google/registry/reporting/icann/DnsCountQueryCoordinator.java index 3255d58de..eb8f560f8 100644 --- a/core/src/main/java/google/registry/reporting/icann/DnsCountQueryCoordinator.java +++ b/core/src/main/java/google/registry/reporting/icann/DnsCountQueryCoordinator.java @@ -25,7 +25,7 @@ import google.registry.bigquery.BigqueryConnection; import google.registry.config.RegistryConfig.Config; import jakarta.inject.Inject; import jakarta.inject.Named; -import org.joda.time.YearMonth; +import java.time.YearMonth; /** * Methods for preparing and querying DNS statistics. diff --git a/core/src/main/java/google/registry/reporting/icann/DummyDnsCountQueryCoordinator.java b/core/src/main/java/google/registry/reporting/icann/DummyDnsCountQueryCoordinator.java index 4e1658ab0..391293894 100644 --- a/core/src/main/java/google/registry/reporting/icann/DummyDnsCountQueryCoordinator.java +++ b/core/src/main/java/google/registry/reporting/icann/DummyDnsCountQueryCoordinator.java @@ -16,7 +16,7 @@ package google.registry.reporting.icann; import google.registry.util.ResourceUtils; import google.registry.util.SqlTemplate; -import org.joda.time.YearMonth; +import java.time.YearMonth; /** DNS Count query where returned values are all -1. */ public class DummyDnsCountQueryCoordinator extends DnsCountQueryCoordinator { diff --git a/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java b/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java index f0aca098a..f7fcaf38e 100644 --- a/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java +++ b/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java @@ -40,9 +40,9 @@ import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; import java.util.List; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; /** * Class that uploads a CSV file to ICANN's endpoint via an HTTP PUT call. @@ -148,7 +148,7 @@ public class IcannHttpReporter { ReportType reportType = ReportType.valueOf(Ascii.toUpperCase(elements.get(0))); // Re-add hyphen between year and month, because ICANN is inconsistent between filename and URL String yearMonth = - YearMonth.parse(elements.get(1), DateTimeFormat.forPattern("yyyyMM")).toString("yyyy-MM"); + YearMonth.parse(elements.get(1), DateTimeFormatter.ofPattern("yyyyMM")).toString(); return new URL(String.format("%s/%s/%s", getUrlPrefix(reportType), tld, yearMonth)); } diff --git a/core/src/main/java/google/registry/reporting/icann/IcannReportingModule.java b/core/src/main/java/google/registry/reporting/icann/IcannReportingModule.java index c02844234..3d25e84c7 100644 --- a/core/src/main/java/google/registry/reporting/icann/IcannReportingModule.java +++ b/core/src/main/java/google/registry/reporting/icann/IcannReportingModule.java @@ -28,8 +28,8 @@ import google.registry.request.HttpException.BadRequestException; import google.registry.request.Parameter; import jakarta.inject.Named; import jakarta.servlet.http.HttpServletRequest; +import java.time.Duration; import java.util.Optional; -import org.joda.time.Duration; /** Module for dependencies required by ICANN monthly transactions/activity reporting. */ @Module @@ -101,7 +101,7 @@ public final class IcannReportingModule { .setExecutorService(MoreExecutors.newDirectExecutorService()) .setDatasetId(icannReportingDataSet) .setOverwrite(true) - .setPollInterval(Duration.standardSeconds(1)) + .setPollInterval(Duration.ofSeconds(1)) .build(); } catch (Throwable e) { throw new RuntimeException("Could not initialize BigqueryConnection!", e); diff --git a/core/src/main/java/google/registry/reporting/icann/IcannReportingStager.java b/core/src/main/java/google/registry/reporting/icann/IcannReportingStager.java index de69ecfc1..51fa054df 100644 --- a/core/src/main/java/google/registry/reporting/icann/IcannReportingStager.java +++ b/core/src/main/java/google/registry/reporting/icann/IcannReportingStager.java @@ -38,6 +38,8 @@ import google.registry.gcs.GcsUtils; import google.registry.reporting.icann.IcannReportingModule.ReportType; import jakarta.inject.Inject; import java.io.IOException; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -47,8 +49,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; /** * Class containing methods for staging ICANN monthly reports on GCS. @@ -258,7 +258,7 @@ public class IcannReportingStager { "%s-%s-%s.csv", tld, Ascii.toLowerCase(reportType.toString()), - DateTimeFormat.forPattern("yyyyMM").print(yearMonth)); + DateTimeFormatter.ofPattern("yyyyMM").format(yearMonth)); final BlobId gcsFilename = BlobId.of(reportingBucket, String.format("%s/%s", subdir, reportFilename)); gcsUtils.createFromBytes(gcsFilename, reportBytes); diff --git a/core/src/main/java/google/registry/reporting/icann/IcannReportingStagingAction.java b/core/src/main/java/google/registry/reporting/icann/IcannReportingStagingAction.java index b8fe488f2..67c50dccb 100644 --- a/core/src/main/java/google/registry/reporting/icann/IcannReportingStagingAction.java +++ b/core/src/main/java/google/registry/reporting/icann/IcannReportingStagingAction.java @@ -41,10 +41,10 @@ import google.registry.util.EmailMessage; import google.registry.util.Retrier; import jakarta.inject.Inject; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; import java.util.Optional; -import org.joda.time.Duration; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; /** * Action that generates monthly ICANN activity and transactions reports. @@ -138,7 +138,7 @@ public final class IcannReportingStagingAction implements Runnable { cloudTasksUtils.enqueue( CRON_QUEUE, cloudTasksUtils.createTaskWithDelay( - IcannReportingUploadAction.class, POST, null, Duration.standardMinutes(2))); + IcannReportingUploadAction.class, POST, null, Duration.ofMinutes(2))); } else { logger.atInfo().log("Would have enqueued report upload"); } @@ -166,6 +166,7 @@ public final class IcannReportingStagingAction implements Runnable { return IcannReportingModule.checkSubdirValid( overrideSubdir.orElse( String.format( - "%s/%s", DEFAULT_SUBDIR, DateTimeFormat.forPattern("yyyy-MM").print(yearMonth)))); + "%s/%s", + DEFAULT_SUBDIR, DateTimeFormatter.ofPattern("yyyy-MM").format(yearMonth)))); } } diff --git a/core/src/main/java/google/registry/reporting/icann/IcannReportingUploadAction.java b/core/src/main/java/google/registry/reporting/icann/IcannReportingUploadAction.java index 703d8b8df..8882449ea 100644 --- a/core/src/main/java/google/registry/reporting/icann/IcannReportingUploadAction.java +++ b/core/src/main/java/google/registry/reporting/icann/IcannReportingUploadAction.java @@ -18,6 +18,7 @@ import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.request.Action.Method.POST; import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static java.time.ZoneOffset.UTC; import com.google.cloud.storage.BlobId; import com.google.common.collect.ImmutableMap; @@ -46,11 +47,11 @@ import jakarta.inject.Inject; import jakarta.mail.internet.InternetAddress; import java.io.IOException; import java.io.InputStream; +import java.time.Duration; +import java.time.Instant; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Action that uploads the monthly activity/transactions reports from GCS to ICANN via an HTTP PUT. @@ -105,14 +106,13 @@ public final class IcannReportingUploadAction implements Runnable { * staging action is scheduled to run at 9AM UTC on that day, and there is no reason to run the * upload job before that. See {@code icannReportingStaging} in {@code cloud-scheduler.xml}. */ - private static DateTime getScheduledTimeForCurrentMonth(DateTime time) { - return time.withDayOfMonth(2).withHourOfDay(10).withMinuteOfHour(0).plusMonths(1); + private static Instant getScheduledTimeForCurrentMonth(Instant time) { + return time.atZone(UTC).withDayOfMonth(2).withHour(10).withMinute(0).plusMonths(1).toInstant(); } @Override public void run() { - if (!lockHandler.executeWithLocks( - this::runWithLock, null, Duration.standardHours(2), LOCK_NAME)) { + if (!lockHandler.executeWithLocks(this::runWithLock, null, Duration.ofHours(2), LOCK_NAME)) { throw new ServiceUnavailableException(String.format("Lock for %s already in use", LOCK_NAME)); } } @@ -124,7 +124,7 @@ public final class IcannReportingUploadAction implements Runnable { // If cursor time is before now, upload the corresponding report cursors.entrySet().stream() - .filter(entry -> entry.getKey().getCursorTime().isBefore(clock.nowUtc())) + .filter(entry -> entry.getKey().getCursorTime().isBefore(clock.now())) .forEach(entry -> uploadReport(entry.getKey(), entry.getValue(), reportSummaryBuilder)); // Send email of which reports were uploaded emailUploadResults(reportSummaryBuilder.build()); @@ -136,13 +136,15 @@ public final class IcannReportingUploadAction implements Runnable { /** Uploads the report and rolls forward the cursor for that report. */ private void uploadReport( Cursor cursor, String tldStr, ImmutableMap.Builder reportSummaryBuilder) { - DateTime cursorTime = cursor.getCursorTime(); + Instant cursorTime = cursor.getCursorTime(); CursorType cursorType = cursor.getType(); - DateTime cursorTimeMinusMonth = cursorTime.withDayOfMonth(1).minusMonths(1); + Instant cursorTimeMinusMonth = + cursorTime.atZone(UTC).withDayOfMonth(1).minusMonths(1).toInstant(); String reportSubdir = String.format( "icann/monthly/%d-%02d", - cursorTimeMinusMonth.getYear(), cursorTimeMinusMonth.getMonthOfYear()); + cursorTimeMinusMonth.atZone(UTC).getYear(), + cursorTimeMinusMonth.atZone(UTC).getMonthValue()); String filename = getFileName(cursorType, cursorTime, tldStr); final BlobId gcsFilename = BlobId.of(reportingBucket, String.format("%s/%s", reportSubdir, filename)); @@ -154,7 +156,7 @@ public final class IcannReportingUploadAction implements Runnable { "Could not upload %s report for %s because file %s (object %s in bucket %s) did not" + " exist.", cursorType, tldStr, filename, gcsFilename.getName(), gcsFilename.getBucket()); - if (clock.nowUtc().dayOfMonth().get() == 1) { + if (clock.now().atZone(UTC).getDayOfMonth() == 1) { logger.atInfo().log("%s This report may not have been staged yet.", logMessage); } else { logger.atSevere().log(logMessage); @@ -202,14 +204,15 @@ public final class IcannReportingUploadAction implements Runnable { reportSummaryBuilder.put(filename, success); } - private String getFileName(CursorType cursorType, DateTime cursorTime, String tld) { - DateTime cursorTimeMinusMonth = cursorTime.withDayOfMonth(1).minusMonths(1); + private String getFileName(CursorType cursorType, Instant cursorTime, String tld) { + Instant cursorTimeMinusMonth = + cursorTime.atZone(UTC).withDayOfMonth(1).minusMonths(1).toInstant(); return String.format( "%s%s%d%02d.csv", tld, (cursorType.equals(CursorType.ICANN_UPLOAD_ACTIVITY) ? "-activity-" : "-transactions-"), - cursorTimeMinusMonth.year().get(), - cursorTimeMinusMonth.monthOfYear().get()); + cursorTimeMinusMonth.atZone(UTC).getYear(), + cursorTimeMinusMonth.atZone(UTC).getMonthValue()); } /** Returns a map of each cursor to the tld. */ @@ -260,7 +263,7 @@ public final class IcannReportingUploadAction implements Runnable { cursorMap.getOrDefault( key, Cursor.createScoped( - type, getScheduledTimeForCurrentMonth(clock.nowUtc()), registry)); + type, getScheduledTimeForCurrentMonth(clock.now()), registry)); if (!cursorMap.containsValue(cursor)) { tm().put(cursor); } diff --git a/core/src/main/java/google/registry/reporting/icann/QueryBuilder.java b/core/src/main/java/google/registry/reporting/icann/QueryBuilder.java index 6c3ad00da..eb07d24f2 100644 --- a/core/src/main/java/google/registry/reporting/icann/QueryBuilder.java +++ b/core/src/main/java/google/registry/reporting/icann/QueryBuilder.java @@ -15,7 +15,7 @@ package google.registry.reporting.icann; import com.google.common.collect.ImmutableMap; -import org.joda.time.YearMonth; +import java.time.YearMonth; /** Interface defining the necessary methods to construct ICANN reporting SQL queries. */ public interface QueryBuilder { diff --git a/core/src/main/java/google/registry/reporting/icann/QueryBuilderUtils.java b/core/src/main/java/google/registry/reporting/icann/QueryBuilderUtils.java index 6a25de06c..f49675a72 100644 --- a/core/src/main/java/google/registry/reporting/icann/QueryBuilderUtils.java +++ b/core/src/main/java/google/registry/reporting/icann/QueryBuilderUtils.java @@ -17,8 +17,8 @@ package google.registry.reporting.icann; import com.google.common.io.Resources; import google.registry.util.ResourceUtils; import java.net.URL; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; final class QueryBuilderUtils { @@ -26,7 +26,8 @@ final class QueryBuilderUtils { /** Returns the table name of the query, suffixed with the yearMonth in _yyyyMM format. */ static String getTableName(String queryName, YearMonth yearMonth) { - return String.format("%s_%s", queryName, DateTimeFormat.forPattern("yyyyMM").print(yearMonth)); + return String.format( + "%s_%s", queryName, DateTimeFormatter.ofPattern("yyyyMM").format(yearMonth)); } /** Returns {@link String} for file in {@code reporting/sql/} directory. */ diff --git a/core/src/main/java/google/registry/reporting/icann/TransactionsReportingQueryBuilder.java b/core/src/main/java/google/registry/reporting/icann/TransactionsReportingQueryBuilder.java index 8e7e2afb4..e3a416f21 100644 --- a/core/src/main/java/google/registry/reporting/icann/TransactionsReportingQueryBuilder.java +++ b/core/src/main/java/google/registry/reporting/icann/TransactionsReportingQueryBuilder.java @@ -17,17 +17,17 @@ package google.registry.reporting.icann; import static google.registry.reporting.icann.IcannReportingModule.ICANN_REPORTING_DATA_SET; import static google.registry.reporting.icann.QueryBuilderUtils.getQueryFromFile; import static google.registry.reporting.icann.QueryBuilderUtils.getTableName; +import static java.time.ZoneOffset.UTC; import com.google.common.collect.ImmutableMap; import google.registry.config.RegistryConfig.Config; import google.registry.util.SqlTemplate; import jakarta.inject.Inject; import jakarta.inject.Named; -import org.joda.time.DateTime; -import org.joda.time.LocalTime; -import org.joda.time.YearMonth; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; +import java.time.Duration; +import java.time.Instant; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; /** * Utility class that produces SQL queries used to generate activity reports from Bigquery. @@ -65,9 +65,10 @@ public final class TransactionsReportingQueryBuilder implements QueryBuilder { @Override public ImmutableMap getViewQueryMap(YearMonth yearMonth) { // Set the earliest date to to yearMonth on day 1 at 00:00:00 - DateTime earliestReportTime = yearMonth.toLocalDate(1).toDateTime(new LocalTime(0, 0, 0)); + Instant earliestReportTime = yearMonth.atDay(1).atTime(0, 0, 0).toInstant(UTC); // Set the latest date to yearMonth on the last day at 23:59:59.999 - DateTime latestReportTime = earliestReportTime.plusMonths(1).minusMillis(1); + Instant latestReportTime = + earliestReportTime.atZone(UTC).plusMonths(1).minus(Duration.ofMillis(1)).toInstant(); ImmutableMap.Builder queriesBuilder = ImmutableMap.builder(); String registrarIanaIdQuery = @@ -82,38 +83,39 @@ public final class TransactionsReportingQueryBuilder implements QueryBuilder { .build(); queriesBuilder.put(getTableName(TOTAL_DOMAINS, yearMonth), totalDomainsQuery); - DateTimeFormatter timestampFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"); + DateTimeFormatter timestampFormatter = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(UTC); String totalNameserversQuery = SqlTemplate.create(getQueryFromFile(TOTAL_NAMESERVERS + ".sql")) .put("PROJECT_ID", projectId) - .put("LATEST_REPORT_TIME", timestampFormatter.print(latestReportTime)) + .put("LATEST_REPORT_TIME", timestampFormatter.format(latestReportTime)) .build(); queriesBuilder.put(getTableName(TOTAL_NAMESERVERS, yearMonth), totalNameserversQuery); String transactionCountsQuery = SqlTemplate.create(getQueryFromFile(TRANSACTION_COUNTS + ".sql")) .put("PROJECT_ID", projectId) - .put("EARLIEST_REPORT_TIME", timestampFormatter.print(earliestReportTime)) - .put("LATEST_REPORT_TIME", timestampFormatter.print(latestReportTime)) + .put("EARLIEST_REPORT_TIME", timestampFormatter.format(earliestReportTime)) + .put("LATEST_REPORT_TIME", timestampFormatter.format(latestReportTime)) .build(); queriesBuilder.put(getTableName(TRANSACTION_COUNTS, yearMonth), transactionCountsQuery); String transactionTransferLosingQuery = SqlTemplate.create(getQueryFromFile(TRANSACTION_TRANSFER_LOSING + ".sql")) .put("PROJECT_ID", projectId) - .put("EARLIEST_REPORT_TIME", timestampFormatter.print(earliestReportTime)) - .put("LATEST_REPORT_TIME", timestampFormatter.print(latestReportTime)) + .put("EARLIEST_REPORT_TIME", timestampFormatter.format(earliestReportTime)) + .put("LATEST_REPORT_TIME", timestampFormatter.format(latestReportTime)) .build(); queriesBuilder.put( getTableName(TRANSACTION_TRANSFER_LOSING, yearMonth), transactionTransferLosingQuery); // Log table suffixes use YYYYMMDD format - DateTimeFormatter logTableFormatter = DateTimeFormat.forPattern("yyyyMMdd"); + DateTimeFormatter logTableFormatter = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(UTC); String attemptedAddsQuery = SqlTemplate.create(getQueryFromFile(ATTEMPTED_ADDS + ".sql")) .put("PROJECT_ID", projectId) - .put("FIRST_DAY_OF_MONTH", logTableFormatter.print(earliestReportTime)) - .put("LAST_DAY_OF_MONTH", logTableFormatter.print(latestReportTime)) + .put("FIRST_DAY_OF_MONTH", logTableFormatter.format(earliestReportTime)) + .put("LAST_DAY_OF_MONTH", logTableFormatter.format(latestReportTime)) .build(); queriesBuilder.put(getTableName(ATTEMPTED_ADDS, yearMonth), attemptedAddsQuery); diff --git a/core/src/main/java/google/registry/reporting/spec11/GenerateSpec11ReportAction.java b/core/src/main/java/google/registry/reporting/spec11/GenerateSpec11ReportAction.java index e921a4d59..9ca44fc91 100644 --- a/core/src/main/java/google/registry/reporting/spec11/GenerateSpec11ReportAction.java +++ b/core/src/main/java/google/registry/reporting/spec11/GenerateSpec11ReportAction.java @@ -39,8 +39,8 @@ import google.registry.util.Clock; import google.registry.util.RegistryEnvironment; import jakarta.inject.Inject; import java.io.IOException; -import org.joda.time.Duration; -import org.joda.time.LocalDate; +import java.time.Duration; +import java.time.LocalDate; /** * Invokes the {@code Spec11Pipeline} Beam template via the REST api. @@ -140,7 +140,7 @@ public class GenerateSpec11ReportAction implements Runnable { jobId, ReportingModule.PARAM_DATE, date.toString()), - Duration.standardMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES))); + Duration.ofMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES))); } response.setStatus(SC_OK); response.setPayload(String.format("Launched Spec11 pipeline: %s", jobId)); diff --git a/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java b/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java index 22160d57e..fe38f03f9 100644 --- a/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java +++ b/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java @@ -43,9 +43,9 @@ import google.registry.request.Response; import google.registry.request.auth.Auth; import jakarta.inject.Inject; import java.io.IOException; +import java.time.LocalDate; import java.util.Optional; import java.util.Set; -import org.joda.time.LocalDate; import org.json.JSONException; /** diff --git a/core/src/main/java/google/registry/reporting/spec11/Spec11EmailUtils.java b/core/src/main/java/google/registry/reporting/spec11/Spec11EmailUtils.java index 353e77fc3..2d105a730 100644 --- a/core/src/main/java/google/registry/reporting/spec11/Spec11EmailUtils.java +++ b/core/src/main/java/google/registry/reporting/spec11/Spec11EmailUtils.java @@ -41,10 +41,10 @@ import google.registry.util.Sleeper; import jakarta.inject.Inject; import jakarta.mail.MessagingException; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.LocalDate; import java.util.List; import java.util.Map; -import org.joda.time.Duration; -import org.joda.time.LocalDate; /** Provides e-mail functionality for Spec11 tasks, such as sending Spec11 reports to registrars. */ public class Spec11EmailUtils { @@ -103,11 +103,7 @@ public class Spec11EmailUtils { RegistrarThreatMatches filteredMatches = filterOutNonPublishedMatches(registrarThreatMatches); if (!filteredMatches.threatMatches().isEmpty()) { if (numRegistrarsEmailed > 0) { - try { - sleeper.sleep(emailThrottleDuration); - } catch (InterruptedException ie) { - throw new RuntimeException(ie); - } + sleeper.sleepInterruptibly(emailThrottleDuration); } try { // Handle exceptions individually per registrar so that one failed email doesn't prevent diff --git a/core/src/main/java/google/registry/reporting/spec11/Spec11Module.java b/core/src/main/java/google/registry/reporting/spec11/Spec11Module.java index f1ca3f7c5..3ddc8d804 100644 --- a/core/src/main/java/google/registry/reporting/spec11/Spec11Module.java +++ b/core/src/main/java/google/registry/reporting/spec11/Spec11Module.java @@ -14,6 +14,7 @@ package google.registry.reporting.spec11; +import static google.registry.util.DateTimeUtils.toJodaLocalDate; import static java.lang.annotation.RetentionPolicy.RUNTIME; import dagger.Module; @@ -22,7 +23,7 @@ import google.registry.beam.spec11.Spec11Pipeline; import jakarta.inject.Qualifier; import java.lang.annotation.Documented; import java.lang.annotation.Retention; -import org.joda.time.LocalDate; +import java.time.LocalDate; /** Module for dependencies required by Spec11 reporting. */ @Module @@ -31,7 +32,7 @@ public class Spec11Module { @Provides @Spec11ReportFilePath static String provideSpec11ReportFilePath(LocalDate localDate) { - return Spec11Pipeline.getSpec11ReportFilePath(localDate); + return Spec11Pipeline.getSpec11ReportFilePath(toJodaLocalDate(localDate)); } /** Dagger qualifier for the subdirectory we stage to/upload from for Spec11 reports. */ diff --git a/core/src/main/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParser.java b/core/src/main/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParser.java index 2947c08d9..2495ba6fe 100644 --- a/core/src/main/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParser.java +++ b/core/src/main/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParser.java @@ -15,6 +15,7 @@ package google.registry.reporting.spec11; import static com.google.common.collect.ImmutableSet.toImmutableSet; +import static google.registry.util.DateTimeUtils.toJodaLocalDate; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.cloud.storage.BlobId; @@ -31,8 +32,8 @@ import jakarta.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.time.LocalDate; import java.util.Optional; -import org.joda.time.LocalDate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -99,7 +100,8 @@ public class Spec11RegistrarThreatMatchesParser { } private BlobId getGcsFilename(LocalDate localDate) { - return BlobId.of(reportingBucket, Spec11Pipeline.getSpec11ReportFilePath(localDate)); + return BlobId.of( + reportingBucket, Spec11Pipeline.getSpec11ReportFilePath(toJodaLocalDate(localDate))); } private RegistrarThreatMatches parseRegistrarThreatMatch(String line) throws JSONException { diff --git a/core/src/main/java/google/registry/request/RequestParameters.java b/core/src/main/java/google/registry/request/RequestParameters.java index 6cd6a034b..bf6fd0c01 100644 --- a/core/src/main/java/google/registry/request/RequestParameters.java +++ b/core/src/main/java/google/registry/request/RequestParameters.java @@ -326,6 +326,18 @@ public final class RequestParameters { } } + public static ImmutableSet extractSetOfInstantParameters( + HttpServletRequest req, String name) { + try { + return extractSetOfParameters(req, name).stream() + .filter(not(String::isEmpty)) + .map(Instant::parse) + .collect(toImmutableSet()); + } catch (DateTimeParseException e) { + throw new BadRequestException("Bad ISO 8601 timestamp: " + name); + } + } + /** * Returns all GET or POST date parameters associated with {@code name}, or an empty set if none. * diff --git a/core/src/main/java/google/registry/request/lock/LockHandler.java b/core/src/main/java/google/registry/request/lock/LockHandler.java index 31ed7fec0..c3ba3f6b0 100644 --- a/core/src/main/java/google/registry/request/lock/LockHandler.java +++ b/core/src/main/java/google/registry/request/lock/LockHandler.java @@ -15,9 +15,9 @@ package google.registry.request.lock; import java.io.Serializable; +import java.time.Duration; import java.util.concurrent.Callable; import javax.annotation.Nullable; -import org.joda.time.Duration; /** * Code execution locked on some shared resource. diff --git a/core/src/main/java/google/registry/request/lock/LockHandlerImpl.java b/core/src/main/java/google/registry/request/lock/LockHandlerImpl.java index 18c92aa3f..02579955c 100644 --- a/core/src/main/java/google/registry/request/lock/LockHandlerImpl.java +++ b/core/src/main/java/google/registry/request/lock/LockHandlerImpl.java @@ -27,6 +27,8 @@ import google.registry.model.server.Lock; import google.registry.util.Clock; import google.registry.util.TimeLimiter; import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; import java.util.HashSet; import java.util.Optional; import java.util.Set; @@ -35,8 +37,6 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** Implementation of {@link LockHandler} that uses the database lock. */ public class LockHandlerImpl implements LockHandler { @@ -45,7 +45,7 @@ public class LockHandlerImpl implements LockHandler { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Fudge factor to make sure we kill threads before a lock actually expires. */ - private static final Duration LOCK_TIMEOUT_FUDGE = Duration.standardSeconds(5); + private static final Duration LOCK_TIMEOUT_FUDGE = Duration.ofSeconds(5); private final Clock clock; @@ -79,13 +79,13 @@ public class LockHandlerImpl implements LockHandler { Duration leaseLength, LockAcquirer lockAcquirer, String... lockNames) { - DateTime startTime = clock.nowUtc(); + Instant startTime = clock.now(); String sanitizedTld = Strings.emptyToNull(tld); try { return TimeLimiter.create() .callWithTimeout( new LockingCallable(callable, lockAcquirer, sanitizedTld, leaseLength, lockNames), - leaseLength.minus(LOCK_TIMEOUT_FUDGE).getMillis(), + leaseLength.minus(LOCK_TIMEOUT_FUDGE).toMillis(), TimeUnit.MILLISECONDS); } catch (ExecutionException | UncheckedExecutionException e) { // Unwrap the execution exception and throw its root cause. @@ -96,7 +96,7 @@ public class LockHandlerImpl implements LockHandler { "Execution on locks '%s' for TLD '%s' timed out after %s; started at %s", Joiner.on(", ").join(lockNames), Optional.ofNullable(sanitizedTld).orElse("(null)"), - new Duration(startTime, clock.nowUtc()), + Duration.between(startTime, clock.now()), startTime), cause); } @@ -132,7 +132,7 @@ public class LockHandlerImpl implements LockHandler { String tld, Duration leaseLength, String... lockNames) { - checkArgument(leaseLength.isLongerThan(LOCK_TIMEOUT_FUDGE)); + checkArgument(leaseLength.compareTo(LOCK_TIMEOUT_FUDGE) > 0); this.delegate = delegate; this.lockAcquirer = lockAcquirer; this.tld = tld; diff --git a/core/src/main/java/google/registry/tmch/LordnLog.java b/core/src/main/java/google/registry/tmch/LordnLog.java index 5061e5550..0f9a634a6 100644 --- a/core/src/main/java/google/registry/tmch/LordnLog.java +++ b/core/src/main/java/google/registry/tmch/LordnLog.java @@ -22,12 +22,12 @@ import com.google.common.base.Ascii; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableMap; import com.google.re2j.Pattern; +import java.time.Instant; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; -import org.joda.time.DateTime; /** * Parser of LORDN log responses from the MarksDB server during the NORDN process. @@ -127,16 +127,16 @@ public final class LordnLog implements Iterable> private final String logId; private final Status status; - private final DateTime logCreation; - private final DateTime lordnCreation; + private final Instant logCreation; + private final Instant lordnCreation; private final boolean hasWarnings; private final ImmutableMap results; private LordnLog( String logId, Status status, - DateTime logCreation, - DateTime lordnCreation, + Instant logCreation, + Instant lordnCreation, boolean hasWarnings, ImmutableMap results) { this.logId = logId; @@ -155,11 +155,11 @@ public final class LordnLog implements Iterable> return status; } - public DateTime getLogCreation() { + public Instant getLogCreation() { return logCreation; } - public DateTime getLordnCreation() { + public Instant getLordnCreation() { return lordnCreation; } @@ -204,12 +204,12 @@ public final class LordnLog implements Iterable> // + , date and time in UTC that the // LORDN Log was created. - DateTime logCreation = DateTime.parse(firstLine.get(1)); + Instant logCreation = Instant.parse(firstLine.get(1)); // + , date and time in UTC of // creation for the LORDN file that this log file is referring // to. - DateTime lordnCreation = DateTime.parse(firstLine.get(2)); + Instant lordnCreation = Instant.parse(firstLine.get(2)); // + , unique identifier of the LORDN Log // provided by the TMDB. This identifier could be used by the diff --git a/core/src/main/java/google/registry/tmch/NordnUploadAction.java b/core/src/main/java/google/registry/tmch/NordnUploadAction.java index 47a59efa5..28922a567 100644 --- a/core/src/main/java/google/registry/tmch/NordnUploadAction.java +++ b/core/src/main/java/google/registry/tmch/NordnUploadAction.java @@ -53,10 +53,10 @@ import java.net.HttpURLConnection; import java.net.URL; import java.security.GeneralSecurityException; import java.security.SecureRandom; +import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.Random; -import org.joda.time.Duration; /** * Action that reads the NORDN pull queues, uploads claims and sunrise marks data to TMCH, and @@ -119,7 +119,7 @@ public final class NordnUploadAction implements Runnable { Ascii.toLowerCase(LordnPhase.CLAIMS.toString()); /** How long to wait before attempting to verify an upload by fetching the log. */ - private static final Duration VERIFY_DELAY = Duration.standardMinutes(30); + private static final Duration VERIFY_DELAY = Duration.ofMinutes(30); @Override public void run() { @@ -249,6 +249,6 @@ public final class NordnUploadAction implements Runnable { .put(NordnVerifyAction.NORDN_LOG_ID_PARAM, actionLogId) .put(RequestParameters.PARAM_TLD, tld) .build(), - Duration.millis(VERIFY_DELAY.getMillis())); + VERIFY_DELAY); } } diff --git a/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java b/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java index 67000e52b..ab7ba443b 100644 --- a/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java +++ b/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java @@ -34,6 +34,7 @@ import java.security.GeneralSecurityException; import java.security.cert.CertificateParsingException; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; +import java.sql.Timestamp; import java.util.Optional; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; @@ -161,7 +162,7 @@ public final class TmchCertificateAuthority { // The current production certificate expires on 2023-07-23. Future code monkey be reminded, // if you are looking at this code because the next line throws an exception, ask ICANN for a // new root certificate! (preferably before the current one expires...) - root.checkValidity(clock.nowUtc().toDate()); + root.checkValidity(Timestamp.from(clock.now())); return root; } catch (Exception e) { if (e instanceof GeneralSecurityException generalSecurityException) { diff --git a/core/src/main/java/google/registry/tools/BigqueryParameters.java b/core/src/main/java/google/registry/tools/BigqueryParameters.java index 1b4995a2e..f29fb5bb3 100644 --- a/core/src/main/java/google/registry/tools/BigqueryParameters.java +++ b/core/src/main/java/google/registry/tools/BigqueryParameters.java @@ -17,8 +17,8 @@ package google.registry.tools; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import google.registry.bigquery.BigqueryConnection; +import java.time.Duration; import java.util.concurrent.Executors; -import org.joda.time.Duration; /** Parameter delegate class to handle flag settings for a command's BigqueryConnection object. */ @Parameters(separators = " =") @@ -44,7 +44,7 @@ public final class BigqueryParameters { @Parameter( names = "--bigquery_poll_interval", description = "Interval in milliseconds to wait between polls for job status.") - private Duration bigqueryPollInterval = Duration.standardSeconds(1); + private Duration bigqueryPollInterval = Duration.ofSeconds(1); @Parameter( names = "--bigquery_num_threads", diff --git a/core/src/main/java/google/registry/tools/DomainLockUtils.java b/core/src/main/java/google/registry/tools/DomainLockUtils.java index 01d513d04..e40394410 100644 --- a/core/src/main/java/google/registry/tools/DomainLockUtils.java +++ b/core/src/main/java/google/registry/tools/DomainLockUtils.java @@ -19,6 +19,7 @@ import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.toJavaDuration; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; @@ -201,7 +202,7 @@ public final class DomainLockUtils { String.valueOf(lockRevisionId), RelockDomainAction.PREVIOUS_ATTEMPTS_PARAM, String.valueOf(previousAttempts)), - countdown)); + toJavaDuration(countdown))); } private RegistryLock verifyAndApplyLock(RegistryLock lock, boolean isAdmin) { diff --git a/core/src/main/java/google/registry/tools/EscrowDepositEncryptor.java b/core/src/main/java/google/registry/tools/EscrowDepositEncryptor.java index 332fec2f1..582bfa26f 100644 --- a/core/src/main/java/google/registry/tools/EscrowDepositEncryptor.java +++ b/core/src/main/java/google/registry/tools/EscrowDepositEncryptor.java @@ -31,10 +31,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; /** Utility for encrypting an RDE RyDE deposit on the Java 7 NIO file system. */ final class EscrowDepositEncryptor { @@ -59,7 +59,7 @@ final class EscrowDepositEncryptor { throws IOException, XmlException { try (InputStream xmlFileInput = Files.newInputStream(xmlFile); BufferedInputStream xmlInput = new BufferedInputStream(xmlFileInput, PEEK_BUFFER_SIZE)) { - DateTime watermark = RdeUtils.peekWatermark(xmlInput); + Instant watermark = RdeUtils.peekWatermark(xmlInput); String name = RdeNamingUtils.makeRydeFilename(tld, watermark, mode, 1, revision); Path rydePath = outdir.resolve(name + ".ryde"); Path sigPath = outdir.resolve(name + ".sig"); diff --git a/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java b/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java index d2ca07c73..f5243d1c4 100644 --- a/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java +++ b/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java @@ -19,6 +19,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Sets.difference; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.toInstant; +import static java.time.ZoneOffset.UTC; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; @@ -39,7 +40,6 @@ import google.registry.tools.params.NameserversParameter; import google.registry.tools.soy.DomainRenewSoyInfo; import google.registry.tools.soy.UniformRapidSuspensionSoyInfo; import jakarta.xml.bind.annotation.adapters.HexBinaryAdapter; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashSet; @@ -162,7 +162,7 @@ final class UniformRapidSuspensionCommand extends MutatingEppToolCommand { domain.getDomainName(), "expirationDate", DateTimeFormatter.ofPattern("yyyy-MM-dd") - .withZone(ZoneOffset.UTC) + .withZone(UTC) .format(domain.getRegistrationExpirationTime()), // period is the number of years to renew the registration for "period", diff --git a/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java b/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java index 4a724e8c2..54bf06261 100644 --- a/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java +++ b/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java @@ -23,9 +23,9 @@ import com.google.common.collect.ImmutableList; import google.registry.model.common.Cursor; import google.registry.model.common.Cursor.CursorType; import google.registry.model.tld.Tld; -import google.registry.tools.params.DateTimeParameter; +import google.registry.tools.params.InstantParameter; +import java.time.Instant; import java.util.List; -import org.joda.time.DateTime; /** Modifies {@link Cursor} timestamps used by locking rolling cursor tasks, like in RDE. */ @Parameters(separators = " =", commandDescription = "Modifies cursor timestamps used by LRC tasks") @@ -40,9 +40,10 @@ final class UpdateCursorsCommand extends ConfirmingCommand implements Command { @Parameter( names = "--timestamp", description = "The new timestamp to set.", - validateWith = DateTimeParameter.class, + converter = InstantParameter.class, + validateWith = InstantParameter.class, required = true) - private DateTime newTimestamp; + private Instant newTimestamp; ImmutableList cursorsToUpdate; diff --git a/core/src/main/java/google/registry/tools/params/DateParameter.java b/core/src/main/java/google/registry/tools/params/DateParameter.java index 1ccea8d6a..6fee29e3e 100644 --- a/core/src/main/java/google/registry/tools/params/DateParameter.java +++ b/core/src/main/java/google/registry/tools/params/DateParameter.java @@ -13,7 +13,6 @@ // limitations under the License. package google.registry.tools.params; - import static org.joda.time.DateTimeZone.UTC; import org.joda.time.DateTime; diff --git a/core/src/main/java/google/registry/tools/params/DateTimeParameter.java b/core/src/main/java/google/registry/tools/params/DateTimeParameter.java index 6f8e9dda8..a20d1b984 100644 --- a/core/src/main/java/google/registry/tools/params/DateTimeParameter.java +++ b/core/src/main/java/google/registry/tools/params/DateTimeParameter.java @@ -13,7 +13,6 @@ // limitations under the License. package google.registry.tools.params; - import static org.joda.time.DateTimeZone.UTC; import com.google.common.primitives.Longs; diff --git a/core/src/main/java/google/registry/tools/server/GenerateZoneFilesAction.java b/core/src/main/java/google/registry/tools/server/GenerateZoneFilesAction.java index 1d3c95ed6..0ddfe54c6 100644 --- a/core/src/main/java/google/registry/tools/server/GenerateZoneFilesAction.java +++ b/core/src/main/java/google/registry/tools/server/GenerateZoneFilesAction.java @@ -38,6 +38,7 @@ import google.registry.request.HttpException.BadRequestException; import google.registry.request.JsonActionRunner; import google.registry.request.auth.Auth; import google.registry.util.Clock; +import google.registry.util.DateTimeUtils; import jakarta.inject.Inject; import java.io.IOException; import java.io.OutputStream; @@ -46,6 +47,7 @@ import java.io.PrintWriter; import java.io.Writer; import java.net.Inet4Address; import java.net.InetAddress; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -53,7 +55,6 @@ import org.hibernate.CacheMode; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.query.SelectionQuery; -import org.joda.time.Duration; /** * Action that requests generation of BIND zone files for a set of TLDs at a given time. @@ -119,7 +120,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA public Map handleJsonRequest(Map json) { @SuppressWarnings("unchecked") ImmutableSet tlds = ImmutableSet.copyOf((List) json.get("tlds")); - final Instant exportTime = Instant.parse(json.get("exportTime").toString()); + Instant exportTime = Instant.parse(json.get("exportTime").toString()); // We disallow exporting within the past 2 minutes because there might be outstanding writes. // We can only reliably call loadAtPointInTime at times that are UTC midnight and > // databaseRetention ago in the past. @@ -127,10 +128,9 @@ 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.getMillis()))) { + if (exportTime.isBefore(now.minusMillis(databaseRetention.toMillis()))) { throw new BadRequestException( - String.format( - "Invalid export time: must be < %d days ago", databaseRetention.getStandardDays())); + String.format("Invalid export time: must be < %d days ago", databaseRetention.toDays())); } tlds.forEach(tld -> generateForTld(tld, exportTime)); ImmutableList filenames = @@ -238,7 +238,10 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA String.format( NS_FORMAT, domainLabel, - tld.getDnsNsTtl().orElse(dnsDefaultNsTtl).getStandardSeconds(), + tld.getDnsNsTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(dnsDefaultNsTtl) + .toSeconds(), // Load the nameservers at the export time in case they've been renamed or deleted. loadAtPointInTime(nameserver, exportTime).getHostName())); } @@ -247,7 +250,10 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA String.format( DS_FORMAT, domainLabel, - tld.getDnsDsTtl().orElse(dnsDefaultDsTtl).getStandardSeconds(), + tld.getDnsDsTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(dnsDefaultDsTtl) + .toSeconds(), dsData.getKeyTag(), dsData.getAlgorithm(), dsData.getDigestType(), @@ -278,7 +284,10 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA String.format( A_FORMAT, stripTld(host.getHostName(), tldStr), - tld.getDnsAPlusAaaaTtl().orElse(dnsDefaultATtl).getStandardSeconds(), + tld.getDnsAPlusAaaaTtl() + .map(DateTimeUtils::toJavaDuration) + .orElse(dnsDefaultATtl) + .toSeconds(), rrSetClass, addr.getHostAddress())); } diff --git a/core/src/main/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java b/core/src/main/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java index 1534c7d42..20965695b 100644 --- a/core/src/main/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java +++ b/core/src/main/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java @@ -35,13 +35,13 @@ import google.registry.request.Response; import google.registry.request.auth.Auth; import jakarta.inject.Inject; import jakarta.persistence.TypedQuery; +import java.time.Duration; import java.util.Optional; import java.util.Random; import javax.annotation.Nullable; import org.apache.arrow.util.VisibleForTesting; import org.apache.http.HttpStatus; import org.joda.time.DateTime; -import org.joda.time.Duration; /** * A task that enqueues DNS publish tasks on all active domains on the specified TLD(s). @@ -136,7 +136,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable { .setParameter("tlds", tlds) .setParameter("activeOrDeletedSince", toInstant(activeOrDeletedSince)) .getSingleResult(); - Duration smear = Duration.standardSeconds(Math.max(activeDomains / refreshQps, 1)); + Duration smear = Duration.ofSeconds(Math.max(activeDomains / refreshQps, 1)); logger.atInfo().log("Smearing %d domain DNS refresh tasks across %s.", activeDomains, smear); return smear; } @@ -161,7 +161,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable { try { // Smear the task execution time over the next N seconds. requestDomainDnsRefresh( - domainBatch, Duration.standardSeconds(random.nextInt((int) smear.getStandardSeconds()))); + domainBatch, Duration.ofSeconds(random.nextInt((int) smear.toSeconds()))); } catch (Throwable t) { logger.atSevere().withCause(t).log("Error while enqueuing DNS refresh batch"); response.setStatus(HttpStatus.SC_OK); diff --git a/core/src/main/java/google/registry/xml/UtcInstantAdapter.java b/core/src/main/java/google/registry/xml/UtcInstantAdapter.java index 8a7b57675..1613ce797 100644 --- a/core/src/main/java/google/registry/xml/UtcInstantAdapter.java +++ b/core/src/main/java/google/registry/xml/UtcInstantAdapter.java @@ -16,10 +16,10 @@ package google.registry.xml; import static com.google.common.base.Strings.isNullOrEmpty; 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.ZoneOffset; import java.time.format.DateTimeFormatter; import javax.annotation.CheckForNull; import javax.annotation.Nullable; @@ -33,7 +33,7 @@ import javax.annotation.Nullable; public class UtcInstantAdapter extends XmlAdapter { private static final DateTimeFormatter MARSHAL_FORMAT = - DateTimeFormatter.ofPattern("u-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC); + 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) { diff --git a/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java b/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java index 82d06c316..c90d06b0a 100644 --- a/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java +++ b/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java @@ -20,6 +20,8 @@ import static google.registry.batch.AsyncTaskEnqueuer.PARAM_RESOURCE_KEY; import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS; import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.TestLogHandlerUtils.assertLogMessage; +import static google.registry.util.DateTimeUtils.plusDays; +import static google.registry.util.DateTimeUtils.plusHours; import com.google.cloud.tasks.v2.HttpMethod; import com.google.common.collect.ImmutableSortedSet; @@ -31,9 +33,8 @@ import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; import google.registry.util.CapturingLogHandler; import google.registry.util.JdkLoggerConfig; +import java.time.Instant; import java.util.logging.Level; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -52,7 +53,7 @@ public class AsyncTaskEnqueuerTest { private AsyncTaskEnqueuer asyncTaskEnqueuer; private final CapturingLogHandler logHandler = new CapturingLogHandler(); - private final FakeClock clock = new FakeClock(DateTime.parse("2015-05-18T12:34:56Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2015-05-18T12:34:56Z")); private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); @BeforeEach @@ -69,7 +70,7 @@ public class AsyncTaskEnqueuerTest { void test_enqueueAsyncResave_success() { Host host = persistActiveHost("ns1.example.tld"); asyncTaskEnqueuer.enqueueAsyncResave( - host.createVKey(), clock.nowUtc(), ImmutableSortedSet.of(clock.nowUtc().plusDays(5))); + host.createVKey(), clock.now(), ImmutableSortedSet.of(plusDays(clock.now(), 5))); cloudTasksHelper.assertTasksEnqueued( QUEUE_ASYNC_ACTIONS, new CloudTasksHelper.TaskMatcher() @@ -78,18 +79,18 @@ public class AsyncTaskEnqueuerTest { .service("backend") .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, host.createVKey().stringify()) - .param(PARAM_REQUESTED_TIME, clock.nowUtc().toString()) - .scheduleTime(clock.nowUtc().plus(Duration.standardDays(5)))); + .param(PARAM_REQUESTED_TIME, clock.now().toString()) + .scheduleTime(plusDays(clock.now(), 5))); } @Test void test_enqueueAsyncResave_multipleResaves() { Host host = persistActiveHost("ns1.example.tld"); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); asyncTaskEnqueuer.enqueueAsyncResave( host.createVKey(), now, - ImmutableSortedSet.of(now.plusHours(24), now.plusHours(50), now.plusHours(75))); + ImmutableSortedSet.of(plusHours(now, 24), plusHours(now, 50), plusHours(now, 75))); cloudTasksHelper.assertTasksEnqueued( QUEUE_ASYNC_ACTIONS, new TaskMatcher() @@ -99,8 +100,8 @@ public class AsyncTaskEnqueuerTest { .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, host.createVKey().stringify()) .param(PARAM_REQUESTED_TIME, now.toString()) - .param(PARAM_RESAVE_TIMES, "2015-05-20T14:34:56.000Z,2015-05-21T15:34:56.000Z") - .scheduleTime(clock.nowUtc().plus(Duration.standardHours(24)))); + .param(PARAM_RESAVE_TIMES, "2015-05-20T14:34:56Z,2015-05-21T15:34:56Z") + .scheduleTime(clock.nowUtc().plusHours(24))); } @MockitoSettings(strictness = Strictness.LENIENT) @@ -108,7 +109,7 @@ public class AsyncTaskEnqueuerTest { void test_enqueueAsyncResave_ignoresTasksTooFarIntoFuture() { Host host = persistActiveHost("ns1.example.tld"); asyncTaskEnqueuer.enqueueAsyncResave( - host.createVKey(), clock.nowUtc(), ImmutableSortedSet.of(clock.nowUtc().plusDays(31))); + host.createVKey(), clock.now(), ImmutableSortedSet.of(plusDays(clock.now(), 31))); cloudTasksHelper.assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS); assertLogMessage(logHandler, Level.INFO, "Ignoring async re-save"); } diff --git a/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java b/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java index cd560faef..abf07993c 100644 --- a/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java +++ b/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java @@ -20,6 +20,10 @@ import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.persistDeletedDomain; import static google.registry.testing.DatabaseHelper.persistDomainWithDependentResources; import static google.registry.testing.DatabaseHelper.persistResource; +import static google.registry.util.DateTimeUtils.minusDays; +import static google.registry.util.DateTimeUtils.minusMonths; +import static google.registry.util.DateTimeUtils.plusMonths; +import static google.registry.util.DateTimeUtils.toDateTime; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableList; @@ -37,7 +41,6 @@ import google.registry.testing.FakeLockHandler; import google.registry.testing.FakeResponse; import google.registry.util.DateTimeUtils; import java.time.Instant; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -45,7 +48,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link BulkDomainTransferAction}. */ public class BulkDomainTransferActionTest { - private final FakeClock fakeClock = new FakeClock(DateTime.parse("2024-01-01T00:00:00.000Z")); + private final FakeClock fakeClock = new FakeClock(Instant.parse("2024-01-01T00:00:00.000Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -62,26 +65,26 @@ public class BulkDomainTransferActionTest { @BeforeEach void beforeEach() throws Exception { createTld("tld"); - DateTime now = fakeClock.nowUtc(); + Instant now = fakeClock.now(); // The default registrar is TheRegistrar, which will be the losing registrar activeDomain = persistDomainWithDependentResources( - "active", "tld", now, now.minusDays(1), DateTimeUtils.END_OF_TIME); + "active", "tld", now, minusDays(now, 1), DateTimeUtils.END_INSTANT); alreadyTransferredDomain = persistResource( persistDomainWithDependentResources( - "alreadytransferred", "tld", now, now.minusDays(1), DateTimeUtils.END_OF_TIME) + "alreadytransferred", "tld", now, minusDays(now, 1), DateTimeUtils.END_INSTANT) .asBuilder() .setPersistedCurrentSponsorRegistrarId("NewRegistrar") .build()); pendingDeleteDomain = persistResource( persistDomainWithDependentResources( - "pendingdelete", "tld", now, now.minusDays(1), now.plusMonths(1)) + "pendingdelete", "tld", now, minusDays(now, 1), plusMonths(now, 1)) .asBuilder() .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE)) .build()); - deletedDomain = persistDeletedDomain("deleted.tld", now.minusMonths(1)); + deletedDomain = persistDeletedDomain("deleted.tld", toDateTime(minusMonths(now, 1))); } @Test diff --git a/core/src/test/java/google/registry/batch/CheckBulkComplianceActionTest.java b/core/src/test/java/google/registry/batch/CheckBulkComplianceActionTest.java index f0c15a75c..5a1ddf736 100644 --- a/core/src/test/java/google/registry/batch/CheckBulkComplianceActionTest.java +++ b/core/src/test/java/google/registry/batch/CheckBulkComplianceActionTest.java @@ -47,7 +47,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.joda.money.CurrencyUnit; import org.joda.money.Money; -import org.joda.time.DateTime; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -57,7 +56,7 @@ import org.mockito.ArgumentCaptor; /** Unit tests for {@link CheckBulkComplianceAction}. */ public class CheckBulkComplianceActionTest { // This is the default creation time for test data. - private final FakeClock clock = new FakeClock(DateTime.parse("2012-03-25TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("2012-03-25T00:00:00Z")); private static final String CREATE_LIMIT_EMAIL_SUBJECT = "create limit subject"; private static final String DOMAIN_LIMIT_WARNING_EMAIL_SUBJECT = "domain limit warning subject"; private static final String DOMAIN_LIMIT_UPGRADE_EMAIL_SUBJECT = "domain limit upgrade subject"; diff --git a/core/src/test/java/google/registry/batch/CloudTasksUtilsTest.java b/core/src/test/java/google/registry/batch/CloudTasksUtilsTest.java index 370f69121..a58a0bcde 100644 --- a/core/src/test/java/google/registry/batch/CloudTasksUtilsTest.java +++ b/core/src/test/java/google/registry/batch/CloudTasksUtilsTest.java @@ -39,10 +39,9 @@ import google.registry.testing.FakeClock; import google.registry.testing.FakeSleeper; import google.registry.util.Retrier; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,7 +50,7 @@ public class CloudTasksUtilsTest { // Use a LinkedListMultimap to preserve order of the inserted entries for assertion. private final LinkedListMultimap params = LinkedListMultimap.create(); private final SerializableCloudTasksClient mockClient = mock(SerializableCloudTasksClient.class); - private final FakeClock clock = new FakeClock(DateTime.parse("2021-11-08")); + private final FakeClock clock = new FakeClock(Instant.parse("2021-11-08T00:00:00Z")); private final CloudTasksUtils cloudTasksUtils = new CloudTasksUtils( new Retrier(new FakeSleeper(clock), 1), @@ -78,7 +77,7 @@ public class CloudTasksUtilsTest { IllegalArgumentException.class, () -> cloudTasksUtils.createTaskWithDelay( - TheAction.class, GET, params, Duration.standardMinutes(-10))); + TheAction.class, GET, params, Duration.ofMinutes(-10))); assertThat(thrown).hasMessageThat().isEqualTo("Negative duration is not supported."); } @@ -217,8 +216,8 @@ public class CloudTasksUtilsTest { assertThat(task.getScheduleTime().getSeconds()).isNotEqualTo(0); Instant scheduleTime = Instant.ofEpochSecond(task.getScheduleTime().getSeconds()); - Instant lowerBoundTime = Instant.ofEpochMilli(clock.nowUtc().getMillis()); - Instant upperBound = Instant.ofEpochMilli(clock.nowUtc().plusSeconds(100).getMillis()); + Instant lowerBoundTime = Instant.ofEpochMilli(clock.now().toEpochMilli()); + Instant upperBound = Instant.ofEpochMilli(clock.now().plusSeconds(100).toEpochMilli()); assertThat(scheduleTime.isBefore(lowerBoundTime)).isFalse(); assertThat(upperBound.isBefore(scheduleTime)).isFalse(); @@ -248,14 +247,13 @@ public class CloudTasksUtilsTest { @Test void testSuccess_createTasks_withDelay() { Task task = - cloudTasksUtils.createTaskWithDelay( - TheAction.class, GET, params, Duration.standardMinutes(10)); + cloudTasksUtils.createTaskWithDelay(TheAction.class, GET, params, Duration.ofMinutes(10)); assertThat(task.getHttpRequest().getHttpMethod()).isEqualTo(HttpMethod.GET); assertThat(task.getHttpRequest().getUrl()) .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.nowUtc().plusMinutes(10).getMillis())); + .isEqualTo(Instant.ofEpochMilli(clock.now().plus(Duration.ofMinutes(10)).toEpochMilli())); } @Test diff --git a/core/src/test/java/google/registry/batch/DeleteExpiredDomainsActionTest.java b/core/src/test/java/google/registry/batch/DeleteExpiredDomainsActionTest.java index 2a20a7d08..e23867157 100644 --- a/core/src/test/java/google/registry/batch/DeleteExpiredDomainsActionTest.java +++ b/core/src/test/java/google/registry/batch/DeleteExpiredDomainsActionTest.java @@ -24,7 +24,6 @@ import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.util.DateTimeUtils.END_INSTANT; -import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.minusMonths; import static google.registry.util.DateTimeUtils.plusDays; @@ -48,8 +47,8 @@ import google.registry.testing.DatabaseHelper; import google.registry.testing.FakeClock; import google.registry.testing.FakeLockHandler; import google.registry.testing.FakeResponse; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -57,7 +56,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link DeleteExpiredDomainsAction}. */ class DeleteExpiredDomainsActionTest { - private final FakeClock clock = new FakeClock(DateTime.parse("2016-06-13T20:21:22Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2016-06-13T20:21:22Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -208,7 +207,7 @@ class DeleteExpiredDomainsActionTest { .setTargetId("fizz.tld") .setRegistrarId("TheRegistrar") .setEventTime(plusYears(clock.now(), 1)) - .setAutorenewEndTime(END_OF_TIME) + .setAutorenewEndTime(END_INSTANT) .setHistoryEntry(createHistoryEntry); } } diff --git a/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java b/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java index 2dc44c00a..1aa63cfce 100644 --- a/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java +++ b/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java @@ -28,7 +28,8 @@ import static google.registry.testing.DatabaseHelper.persistDomainAsDeleted; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.minusYears; -import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.plusYears; +import static google.registry.util.DateTimeUtils.toDateTime; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableSet; @@ -49,11 +50,11 @@ import google.registry.testing.DatabaseHelper; import google.registry.testing.FakeClock; import google.registry.testing.SystemPropertyExtension; import google.registry.util.RegistryEnvironment; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.Set; import org.joda.money.Money; -import org.joda.time.DateTime; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -62,7 +63,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link DeleteProberDataAction}. */ class DeleteProberDataActionTest { - private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z"); + private static final Instant DELETION_TIME = Instant.parse("2010-01-01T00:00:00.000Z"); private final FakeClock clock = new FakeClock(Instant.parse("2021-01-01T00:00:00Z")); @@ -270,7 +271,7 @@ class DeleteProberDataActionTest { .asBuilder() .setSubordinateHosts(ImmutableSet.of("ns1.blah.ib-any.test")) .build(), - clock.nowUtc().minusYears(1)); + minusYears(clock.now(), 1)); action.run(); assertAllExist(ImmutableSet.of(domainWithSubord)); @@ -293,32 +294,32 @@ class DeleteProberDataActionTest { * Persists and returns a domain and a descendant history entry, billing event, and poll message. */ private static Set persistDomainAndDescendants(String fqdn) { - Domain domain = persistDeletedDomain(fqdn, DELETION_TIME); + Domain domain = persistDeletedDomain(fqdn, toDateTime(DELETION_TIME)); DomainHistory historyEntry = persistResource( new DomainHistory.Builder() .setDomain(domain) .setType(HistoryEntry.Type.DOMAIN_CREATE) .setRegistrarId("TheRegistrar") - .setModificationTime(toInstant(DELETION_TIME.minusYears(3))) + .setModificationTime(minusYears(DELETION_TIME, 3)) .build()); BillingEvent billingEvent = persistResource( new BillingEvent.Builder() .setDomainHistory(historyEntry) - .setBillingTime(toInstant(DELETION_TIME.plusYears(1))) + .setBillingTime(plusYears(DELETION_TIME, 1)) .setCost(Money.parse("USD 10")) .setPeriodYears(1) .setReason(Reason.CREATE) .setRegistrarId("TheRegistrar") - .setEventTime(toInstant(DELETION_TIME)) + .setEventTime(DELETION_TIME) .setTargetId(fqdn) .build()); PollMessage.OneTime pollMessage = persistResource( new PollMessage.OneTime.Builder() .setHistoryEntry(historyEntry) - .setEventTime(toInstant(DELETION_TIME)) + .setEventTime(DELETION_TIME) .setRegistrarId("TheRegistrar") .setMsg("Domain registered") .build()); @@ -327,7 +328,7 @@ class DeleteProberDataActionTest { GracePeriod.create( ADD, domain.getRepoId(), - toInstant(DELETION_TIME.plusDays(5)), + DELETION_TIME.plus(Duration.ofDays(5)), "TheRegistrar", billingEvent.createVKey())); domain = persistResource(domain.asBuilder().addGracePeriod(gracePeriod).build()); diff --git a/core/src/test/java/google/registry/batch/ExpandBillingRecurrencesActionTest.java b/core/src/test/java/google/registry/batch/ExpandBillingRecurrencesActionTest.java index 2bda1be8f..a65c2319e 100644 --- a/core/src/test/java/google/registry/batch/ExpandBillingRecurrencesActionTest.java +++ b/core/src/test/java/google/registry/batch/ExpandBillingRecurrencesActionTest.java @@ -16,7 +16,6 @@ package google.registry.batch; import static com.google.common.truth.Truth.assertThat; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toDateTime; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; @@ -74,10 +73,7 @@ public class ExpandBillingRecurrencesActionTest extends BeamActionTestBase { expectedParameters.put("endTime", "2020-02-02T00:00:00Z"); expectedParameters.put("isDryRun", "false"); expectedParameters.put("advanceCursor", "true"); - tm().transact( - () -> - tm().put( - Cursor.createGlobal(CursorType.RECURRING_BILLING, toDateTime(cursorTime)))); + tm().transact(() -> tm().put(Cursor.createGlobal(CursorType.RECURRING_BILLING, cursorTime))); } @Test diff --git a/core/src/test/java/google/registry/batch/RelockDomainActionTest.java b/core/src/test/java/google/registry/batch/RelockDomainActionTest.java index d728e6f9b..d937c80bb 100644 --- a/core/src/test/java/google/registry/batch/RelockDomainActionTest.java +++ b/core/src/test/java/google/registry/batch/RelockDomainActionTest.java @@ -51,9 +51,9 @@ import google.registry.tools.DomainLockUtils; import google.registry.util.EmailMessage; import google.registry.util.StringGenerator.Alphabets; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -71,7 +71,7 @@ public class RelockDomainActionTest { private static final String LOCK_EMAIL_ADDRESS = "Marla.Singer.RegistryLock@crr.com"; private final FakeResponse response = new FakeResponse(); - private final FakeClock clock = new FakeClock(DateTime.parse("2015-05-18T12:34:56Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2015-05-18T12:34:56Z")); private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); private final DomainLockUtils domainLockUtils = new DomainLockUtils( @@ -130,7 +130,7 @@ public class RelockDomainActionTest { action.run(); assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT); assertThat(response.getPayload()).isEqualTo("Re-lock failed: Unknown revision ID 12128675309"); - assertTaskEnqueued(1, 12128675309L, Duration.standardMinutes(10)); // should retry, transient + assertTaskEnqueued(1, 12128675309L, Duration.ofMinutes(10)); // should retry, transient } @Test @@ -169,7 +169,7 @@ public class RelockDomainActionTest { @Test void testFailure_domainDeleted() throws Exception { - persistDomainAsDeleted(domain, clock.nowUtc()); + persistDomainAsDeleted(domain, clock.now()); action.run(); String expectedFailureMessage = "Domain example.tld has been deleted."; assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT); @@ -248,7 +248,7 @@ public class RelockDomainActionTest { assertTaskEnqueued( RelockDomainAction.ATTEMPTS_BEFORE_SLOWDOWN + 1, oldLock.getRevisionId(), - Duration.standardHours(1)); + Duration.ofHours(1)); } private void assertSuccessEmailSent() throws Exception { @@ -304,7 +304,7 @@ public class RelockDomainActionTest { } private void assertTaskEnqueued(int numAttempts) { - assertTaskEnqueued(numAttempts, oldLock.getRevisionId(), Duration.standardMinutes(10)); + assertTaskEnqueued(numAttempts, oldLock.getRevisionId(), Duration.ofMinutes(10)); } private void assertTaskEnqueued(int numAttempts, long oldUnlockRevisionId, Duration duration) { @@ -317,7 +317,7 @@ public class RelockDomainActionTest { RelockDomainAction.OLD_UNLOCK_REVISION_ID_PARAM, String.valueOf(oldUnlockRevisionId)) .param(RelockDomainAction.PREVIOUS_ATTEMPTS_PARAM, String.valueOf(numAttempts)) - .scheduleTime(clock.nowUtc().plus(duration))); + .scheduleTime(clock.nowUtc().plusMillis((int) duration.toMillis()))); } private RelockDomainAction createAction(Long oldUnlockRevisionId) throws Exception { diff --git a/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java b/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java index 09d5532dd..ce1daa516 100644 --- a/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java +++ b/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java @@ -41,7 +41,7 @@ import google.registry.request.Response; import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -60,7 +60,7 @@ public class ResaveEntityActionTest { new JpaTestExtensions.Builder().buildIntegrationTestExtension(); @Mock private Response response; - private final FakeClock clock = new FakeClock(DateTime.parse("2016-02-11T10:00:00Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2016-02-11T10:00:00Z")); private AsyncTaskEnqueuer asyncTaskEnqueuer; private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); @@ -72,7 +72,7 @@ public class ResaveEntityActionTest { } private void runAction( - String resourceKey, DateTime requestedTime, ImmutableSortedSet resaveTimes) { + String resourceKey, Instant requestedTime, ImmutableSortedSet resaveTimes) { ResaveEntityAction action = new ResaveEntityAction( resourceKey, requestedTime, resaveTimes, asyncTaskEnqueuer, response); @@ -87,17 +87,17 @@ public class ResaveEntityActionTest { persistDomainWithDependentResources( "domain", "tld", - DateTime.parse("2016-02-06T10:00:00Z"), - DateTime.parse("2016-02-06T10:00:00Z"), - DateTime.parse("2017-01-02T10:11:00Z")), - DateTime.parse("2016-02-06T10:00:00Z"), - DateTime.parse("2016-02-11T10:00:00Z"), - DateTime.parse("2017-01-02T10:11:00Z")); + Instant.parse("2016-02-06T10:00:00Z"), + Instant.parse("2016-02-06T10:00:00Z"), + Instant.parse("2017-01-02T10:11:00Z")), + Instant.parse("2016-02-06T10:00:00Z"), + Instant.parse("2016-02-11T10:00:00Z"), + Instant.parse("2017-01-02T10:11:00Z")); clock.advanceOneMilli(); assertThat(domain.getCurrentSponsorRegistrarId()).isEqualTo("TheRegistrar"); runAction( domain.createVKey().stringify(), - DateTime.parse("2016-02-06T10:00:01Z"), + Instant.parse("2016-02-06T10:00:01Z"), ImmutableSortedSet.of()); Domain resavedDomain = loadByEntity(domain); assertThat(resavedDomain.getCurrentSponsorRegistrarId()).isEqualTo("NewRegistrar"); @@ -122,13 +122,13 @@ public class ResaveEntityActionTest { "TheRegistrar"))) .build()); clock.advanceBy(standardDays(30)); - DateTime requestedTime = clock.nowUtc(); + Instant requestedTime = clock.now(); assertThat(domain.getGracePeriods()).isNotEmpty(); runAction( domain.createVKey().stringify(), requestedTime, - ImmutableSortedSet.of(requestedTime.plusDays(5))); + ImmutableSortedSet.of(plusDays(requestedTime, 5))); Domain resavedDomain = loadByEntity(domain); assertThat(resavedDomain.getGracePeriods()).isEmpty(); @@ -141,17 +141,17 @@ public class ResaveEntityActionTest { .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, resavedDomain.createVKey().stringify()) .param(PARAM_REQUESTED_TIME, requestedTime.toString()) - .scheduleTime(clock.nowUtc().plus(standardDays(5)))); + .scheduleTime(clock.nowUtc().plusDays(5))); } @Test void test_queuedTaskForNonExistentDomain_failsPermanently() { - DateTime requestedTime = clock.nowUtc(); + Instant requestedTime = clock.now(); // It should complete its run without throwing an exception (that would cause a retry) ... runAction( newDomain("nonexistent.tld").createVKey().stringify(), requestedTime, - ImmutableSortedSet.of(requestedTime.plusDays(5))); + ImmutableSortedSet.of(plusDays(requestedTime, 5))); // ... and it shouldn't enqueue the subsequent re-save 5 days later. cloudTasksHelper.assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS); } diff --git a/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java b/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java index bec2a6d98..55d283ef4 100644 --- a/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java +++ b/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java @@ -19,6 +19,7 @@ import static google.registry.persistence.transaction.JpaTransactionManagerExten import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResources; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.apache.http.HttpStatus.SC_OK; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -44,6 +45,7 @@ import google.registry.testing.FakeResponse; import google.registry.util.SelfSignedCaCertificate; import jakarta.mail.internet.InternetAddress; import java.security.cert.X509Certificate; +import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; import org.joda.time.DateTime; @@ -122,7 +124,7 @@ class SendExpiringCertificateNotificationEmailActionTest { .build()); persistSampleContacts(registrar, Type.TECH); assertThat( - action.sendNotificationEmail(registrar, START_OF_TIME, CertificateType.FAILOVER, cert)) + action.sendNotificationEmail(registrar, START_INSTANT, CertificateType.FAILOVER, cert)) .isEqualTo(true); } @@ -144,7 +146,7 @@ class SendExpiringCertificateNotificationEmailActionTest { .build()); persistSampleContacts(registrar, Type.ADMIN); assertThat( - action.sendNotificationEmail(registrar, START_OF_TIME, CertificateType.FAILOVER, cert)) + action.sendNotificationEmail(registrar, START_INSTANT, CertificateType.FAILOVER, cert)) .isEqualTo(true); } @@ -166,7 +168,7 @@ class SendExpiringCertificateNotificationEmailActionTest { assertThat( action.sendNotificationEmail( registrar, - START_OF_TIME, + START_INSTANT, CertificateType.FAILOVER, Optional.of( certificateChecker.serializeCertificate( @@ -190,7 +192,7 @@ class SendExpiringCertificateNotificationEmailActionTest { Optional.of(certificateChecker.serializeCertificate(expiringCertificate)); assertThat( action.sendNotificationEmail( - sampleRegistrar, START_OF_TIME, CertificateType.FAILOVER, cert)) + sampleRegistrar, START_INSTANT, CertificateType.FAILOVER, cert)) .isEqualTo(false); } @@ -231,7 +233,7 @@ class SendExpiringCertificateNotificationEmailActionTest { RuntimeException.class, () -> action.sendNotificationEmail( - registrar, START_OF_TIME, CertificateType.FAILOVER, cert)); + registrar, START_INSTANT, CertificateType.FAILOVER, cert)); assertThat(thrown) .hasMessageThat() .contains( @@ -244,7 +246,7 @@ class SendExpiringCertificateNotificationEmailActionTest { void sendNotificationEmail_returnsFalse_noCertificate() { assertThat( action.sendNotificationEmail( - sampleRegistrar, START_OF_TIME, CertificateType.FAILOVER, Optional.empty())) + sampleRegistrar, START_INSTANT, CertificateType.FAILOVER, Optional.empty())) .isEqualTo(false); } @@ -338,7 +340,7 @@ class SendExpiringCertificateNotificationEmailActionTest { Registrar registrar = createRegistrar("testClientId", "registrar", expiringCertificate, null).build(); persistResource(registrar); - action.updateLastNotificationSentDate(registrar, clock.nowUtc(), CertificateType.PRIMARY); + action.updateLastNotificationSentDate(registrar, clock.now(), CertificateType.PRIMARY); assertThat(loadByEntity(registrar).getLastExpiringCertNotificationSentDate()) .isEqualTo(clock.now()); } @@ -354,7 +356,7 @@ class SendExpiringCertificateNotificationEmailActionTest { Registrar registrar = createRegistrar("testClientId", "registrar", null, expiringCertificate).build(); persistResource(registrar); - action.updateLastNotificationSentDate(registrar, clock.nowUtc(), CertificateType.FAILOVER); + action.updateLastNotificationSentDate(registrar, clock.now(), CertificateType.FAILOVER); assertThat(loadByEntity(registrar).getLastExpiringFailoverCertNotificationSentDate()) .isEqualTo(clock.now()); } @@ -395,7 +397,7 @@ class SendExpiringCertificateNotificationEmailActionTest { IllegalArgumentException.class, () -> action.updateLastNotificationSentDate( - registrar, clock.nowUtc(), CertificateType.valueOf("randomType"))); + registrar, clock.now(), CertificateType.valueOf("randomType"))); assertThat(thrown).hasMessageThat().contains("No enum constant"); } @@ -574,15 +576,15 @@ class SendExpiringCertificateNotificationEmailActionTest { @Test void getEmailBody_returnsEmailBodyText() { String registrarName = "good registrar"; - String certExpirationDateStr = "2021-06-15"; + String certExpirationDateStr = "2021-06-15T00:00:00Z"; CertificateType certificateType = CertificateType.PRIMARY; String registrarId = "registrarid"; String emailBody = action.getEmailBody( - registrarName, certificateType, DateTime.parse(certExpirationDateStr), registrarId); + registrarName, certificateType, Instant.parse(certExpirationDateStr), registrarId); assertThat(emailBody).contains(registrarName); assertThat(emailBody).contains(certificateType.getDisplayName()); - assertThat(emailBody).contains(certExpirationDateStr); + assertThat(emailBody).contains("2021-06-15"); assertThat(emailBody).contains(registrarId + "@registry.example"); assertThat(emailBody).doesNotContain("%1$s"); assertThat(emailBody).doesNotContain("%2$s"); @@ -608,7 +610,7 @@ class SendExpiringCertificateNotificationEmailActionTest { IllegalArgumentException.class, () -> action.getEmailBody( - "good registrar", null, DateTime.parse("2021-06-15"), "registrarId")); + "good registrar", null, Instant.parse("2021-06-15T00:00:00Z"), "registrarId")); assertThat(thrown).hasMessageThat().contains("Certificate type cannot be null"); } @@ -621,7 +623,7 @@ class SendExpiringCertificateNotificationEmailActionTest { action.getEmailBody( "good registrar", CertificateType.FAILOVER, - DateTime.parse("2021-06-15"), + Instant.parse("2021-06-15T00:00:00Z"), null)); assertThat(thrown).hasMessageThat().contains("Registrar Id cannot be null"); } diff --git a/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java b/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java index 655d6fc5c..cd08a4663 100644 --- a/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java +++ b/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java @@ -135,7 +135,7 @@ class SyncRemoteCacheActionTest { assertThat( DatabaseHelper.loadByKey(Cursor.createGlobalVKey(REMOTE_CACHE_DOMAIN_SYNC)) - .getCursorTimeInstant() + .getCursorTime() .toString()) .isEqualTo("2025-01-01T00:00:00.001Z"); } @@ -205,7 +205,7 @@ class SyncRemoteCacheActionTest { assertThat( DatabaseHelper.loadByKey(Cursor.createGlobalVKey(REMOTE_CACHE_HOST_SYNC)) - .getCursorTimeInstant() + .getCursorTime() .toString()) .isEqualTo("2025-01-01T00:00:00.001Z"); } diff --git a/core/src/test/java/google/registry/beam/billing/ExpandBillingRecurrencesPipelineTest.java b/core/src/test/java/google/registry/beam/billing/ExpandBillingRecurrencesPipelineTest.java index 3b01b8820..7e47d1c1f 100644 --- a/core/src/test/java/google/registry/beam/billing/ExpandBillingRecurrencesPipelineTest.java +++ b/core/src/test/java/google/registry/beam/billing/ExpandBillingRecurrencesPipelineTest.java @@ -36,6 +36,9 @@ import static google.registry.util.DateTimeUtils.plusDays; import static google.registry.util.DateTimeUtils.plusYears; import static google.registry.util.DateTimeUtils.toDateTime; import static google.registry.util.DateTimeUtils.toInstant; +import static java.time.temporal.ChronoUnit.DAYS; +import static java.time.temporal.ChronoUnit.HOURS; +import static java.time.temporal.ChronoUnit.MILLIS; import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -59,7 +62,6 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Comparator; import java.util.List; @@ -82,10 +84,9 @@ public class ExpandBillingRecurrencesPipelineTest { private final FakeClock clock = new FakeClock(Instant.parse("2021-02-02T00:00:05.000Z")); private final Instant startTime = Instant.parse("2021-02-01T00:00:00.000Z"); - private Instant endTime = Instant.parse("2021-02-02T00:00:00.000Z"); - private final Cursor cursor = Cursor.createGlobal(RECURRING_BILLING, toDateTime(startTime)); + private final Cursor cursor = Cursor.createGlobal(RECURRING_BILLING, startTime); private Domain domain; @@ -117,14 +118,13 @@ public class ExpandBillingRecurrencesPipelineTest { // Set up the database. createTld("tld"); - billingRecurrence = - createDomainAtTime("example.tld", minusYears(startTime, 1).plus(12, ChronoUnit.HOURS)); + billingRecurrence = createDomainAtTime("example.tld", minusYears(startTime, 1).plus(12, HOURS)); domain = ForeignKeyUtils.loadResource(Domain.class, "example.tld", clock.now()).get(); } @Test void testFailure_endTimeAfterNow() { - options.setEndTime(clock.now().plus(1, ChronoUnit.MILLIS).toString()); + options.setEndTime(clock.now().plus(1, MILLIS).toString()); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, this::runPipeline); assertThat(thrown) @@ -134,7 +134,7 @@ public class ExpandBillingRecurrencesPipelineTest { @Test void testFailure_endTimeBeforeStartTime() { - options.setEndTime(startTime.minus(1, ChronoUnit.MILLIS).toString()); + options.setEndTime(startTime.minus(1, MILLIS).toString()); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, this::runPipeline); assertThat(thrown) @@ -189,11 +189,7 @@ public class ExpandBillingRecurrencesPipelineTest { @Test void testFailure_expandSingleEvent_cursorNotAtStartTime() { - tm().transact( - () -> - tm().put( - Cursor.createGlobal( - RECURRING_BILLING, toDateTime(startTime.plusMillis(1))))); + tm().transact(() -> tm().put(Cursor.createGlobal(RECURRING_BILLING, startTime.plusMillis(1)))); PipelineExecutionException thrown = assertThrows(PipelineExecutionException.class, this::runPipeline); @@ -222,7 +218,7 @@ public class ExpandBillingRecurrencesPipelineTest { persistResource( billingRecurrence .asBuilder() - .setRecurrenceEndTime(billingRecurrence.getEventTime().minus(1, ChronoUnit.DAYS)) + .setRecurrenceEndTime(billingRecurrence.getEventTime().minus(1, DAYS)) .build()); runPipeline(); assertNoExpansionsHappened(); @@ -232,10 +228,7 @@ public class ExpandBillingRecurrencesPipelineTest { void testSuccess_noExpansion_recurrenceClosedBeforeStartTime() { billingRecurrence = persistResource( - billingRecurrence - .asBuilder() - .setRecurrenceEndTime(startTime.minus(1, ChronoUnit.DAYS)) - .build()); + billingRecurrence.asBuilder().setRecurrenceEndTime(startTime.minus(1, DAYS)).build()); runPipeline(); assertNoExpansionsHappened(); } @@ -247,7 +240,7 @@ public class ExpandBillingRecurrencesPipelineTest { billingRecurrence .asBuilder() .setEventTime(minusYears(billingRecurrence.getEventTime(), 1)) - .setRecurrenceEndTime(startTime.plus(6, ChronoUnit.HOURS)) + .setRecurrenceEndTime(startTime.plus(6, HOURS)) .build()); runPipeline(); assertNoExpansionsHappened(); @@ -330,7 +323,7 @@ public class ExpandBillingRecurrencesPipelineTest { .asBuilder() .setPremiumList(persistPremiumList("premium", USD, "other,USD 100")) .build()); - Instant otherCreateTime = minusYears(startTime, 1).plus(5, ChronoUnit.HOURS); + Instant otherCreateTime = minusYears(startTime, 1).plus(5, HOURS); BillingRecurrence otherBillingRecurrence = createDomainAtTime("other.test", otherCreateTime); Domain otherDomain = ForeignKeyUtils.loadResource(Domain.class, "other.test", clock.now()).get(); @@ -530,7 +523,7 @@ public class ExpandBillingRecurrencesPipelineTest { private static void assertCursorAt(Instant expectedCursorTime) { Cursor cursor = tm().transact(() -> tm().loadByKey(Cursor.createGlobalVKey(RECURRING_BILLING))); assertThat(cursor).isNotNull(); - assertThat(cursor.getCursorTimeInstant()).isEqualTo(expectedCursorTime); + assertThat(cursor.getCursorTime()).isEqualTo(expectedCursorTime); } private static void assertCursorAt(DateTime expectedCursorTime) { diff --git a/core/src/test/java/google/registry/beam/rde/RdePipelineTest.java b/core/src/test/java/google/registry/beam/rde/RdePipelineTest.java index af8413bea..fac89c919 100644 --- a/core/src/test/java/google/registry/beam/rde/RdePipelineTest.java +++ b/core/src/test/java/google/registry/beam/rde/RdePipelineTest.java @@ -83,6 +83,7 @@ import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; import google.registry.testing.FakeKeyringModule; import java.io.IOException; +import java.time.Duration; import java.time.Instant; import java.util.function.Function; import java.util.regex.Matcher; @@ -96,7 +97,6 @@ import org.apache.beam.sdk.values.PCollection; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -120,12 +120,9 @@ public class RdePipelineTest { private final ImmutableSet pendings = ImmutableSet.of( - PendingDeposit.create( - "soy", toDateTime(now), FULL, RDE_STAGING, Duration.standardDays(1)), - PendingDeposit.create( - "soy", toDateTime(now), THIN, RDE_STAGING, Duration.standardDays(1)), - PendingDeposit.create( - "fun", toDateTime(now), FULL, RDE_STAGING, Duration.standardDays(1))); + PendingDeposit.create("soy", now, FULL, RDE_STAGING, Duration.ofDays(1)), + PendingDeposit.create("soy", now, THIN, RDE_STAGING, Duration.ofDays(1)), + PendingDeposit.create("fun", now, FULL, RDE_STAGING, Duration.ofDays(1))); private final ImmutableList brdaFragments = ImmutableList.of( @@ -229,10 +226,10 @@ public class RdePipelineTest { tm().transact( () -> { - tm().put(Cursor.createScoped(CursorType.BRDA, toDateTime(now), Tld.get("soy"))); - tm().put(Cursor.createScoped(RDE_STAGING, toDateTime(now), Tld.get("soy"))); - RdeRevision.saveRevision("soy", toDateTime(now), THIN, 0); - RdeRevision.saveRevision("soy", toDateTime(now), FULL, 0); + tm().put(Cursor.createScoped(CursorType.BRDA, now, Tld.get("soy"))); + tm().put(Cursor.createScoped(RDE_STAGING, now, Tld.get("soy"))); + RdeRevision.saveRevision("soy", now, THIN, 0); + RdeRevision.saveRevision("soy", now, FULL, 0); }); // This host is never referenced. @@ -281,7 +278,7 @@ public class RdePipelineTest { // Set the clock to 2000-01-02, any change after hereafter should not show up in the // resulting deposit fragments. - clock.advanceBy(Duration.standardDays(2)); + clock.advanceBy(Duration.ofDays(2)); persistDomainHistory(kittyDomain.asBuilder().setDeletionTime(clock.now()).build()); Host futureHost = persistActiveHost("ns1.future.tld"); persistHostHistory(futureHost); @@ -313,14 +310,9 @@ public class RdePipelineTest { options.setPendings( encodePendingDeposits( ImmutableSet.of( + PendingDeposit.create("soy", now, FULL, RDE_STAGING, Duration.ofDays(1)), PendingDeposit.create( - "soy", toDateTime(now), FULL, RDE_STAGING, Duration.standardDays(1)), - PendingDeposit.create( - "soy", - toDateTime(now.plusSeconds(1)), - THIN, - RDE_STAGING, - Duration.standardDays(1))))); + "soy", now.plusSeconds(1), THIN, RDE_STAGING, Duration.ofDays(1))))); assertThrows( IllegalArgumentException.class, () -> new RdePipeline(options, gcsUtils, cloudTasksHelper.getTestCloudTasksUtils())); @@ -438,10 +430,9 @@ public class RdePipelineTest { @RetryingTest(4) void testSuccess_persistData() throws Exception { PendingDeposit brdaKey = - PendingDeposit.create( - "soy", toDateTime(now), THIN, CursorType.BRDA, Duration.standardDays(1)); + PendingDeposit.create("soy", now, THIN, CursorType.BRDA, Duration.ofDays(1)); PendingDeposit rdeKey = - PendingDeposit.create("soy", toDateTime(now), FULL, RDE_STAGING, Duration.standardDays(1)); + PendingDeposit.create("soy", now, FULL, RDE_STAGING, Duration.ofDays(1)); verifyFiles(ImmutableMap.of(brdaKey, brdaFragments, rdeKey, rdeFragments), false); @@ -464,7 +455,7 @@ public class RdePipelineTest { .path("/_dr/task/brdaCopy") .service("backend") .param("tld", "soy") - .param("watermark", toDateTime(now).toString()) + .param("watermark", now.toString()) .param("prefix", "rde-job/")); cloudTasksHelper.assertTasksEnqueued( "rde-upload", @@ -478,10 +469,8 @@ public class RdePipelineTest { // The GCS folder listing can be a bit flaky, so retry if necessary @RetryingTest(4) void testSuccess_persistData_manual() throws Exception { - PendingDeposit brdaKey = - PendingDeposit.createInManualOperation("soy", toDateTime(now), THIN, "test/", 0); - PendingDeposit rdeKey = - PendingDeposit.createInManualOperation("soy", toDateTime(now), FULL, "test/", 0); + PendingDeposit brdaKey = PendingDeposit.createInManualOperation("soy", now, THIN, "test/", 0); + PendingDeposit rdeKey = PendingDeposit.createInManualOperation("soy", now, FULL, "test/", 0); verifyFiles(ImmutableMap.of(brdaKey, brdaFragments, rdeKey, rdeFragments), true); @@ -561,9 +550,7 @@ public class RdePipelineTest { private static Instant loadCursorTime(CursorType type) { return tm().transact( - () -> - tm().loadByKey(Cursor.createScopedVKey(type, Tld.get("soy"))) - .getCursorTimeInstant()); + () -> tm().loadByKey(Cursor.createScopedVKey(type, Tld.get("soy"))).getCursorTime()); } private static Function getXmlElement(String pattern) { diff --git a/core/src/test/java/google/registry/beam/resave/ResaveAllEppResourcesPipelineTest.java b/core/src/test/java/google/registry/beam/resave/ResaveAllEppResourcesPipelineTest.java index 776bc3979..30caf574c 100644 --- a/core/src/test/java/google/registry/beam/resave/ResaveAllEppResourcesPipelineTest.java +++ b/core/src/test/java/google/registry/beam/resave/ResaveAllEppResourcesPipelineTest.java @@ -27,6 +27,7 @@ import static google.registry.testing.DatabaseHelper.persistDomainWithPendingTra import static google.registry.testing.DatabaseHelper.persistNewRegistrars; import static google.registry.util.DateTimeUtils.plusYears; import static google.registry.util.DateTimeUtils.toDateTime; +import static java.time.temporal.ChronoUnit.DAYS; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -44,7 +45,6 @@ import google.registry.persistence.transaction.JpaTransactionManager; import google.registry.persistence.transaction.TransactionManagerFactory; import google.registry.testing.FakeClock; import java.time.Instant; -import java.time.temporal.ChronoUnit; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.hibernate.cfg.Environment; import org.joda.time.DateTime; @@ -101,11 +101,11 @@ public class ResaveAllEppResourcesPipelineTest { persistDomainWithDependentResources( "domain", "tld", - toDateTime(now.minus(5, ChronoUnit.DAYS)), - toDateTime(now.minus(5, ChronoUnit.DAYS)), + toDateTime(now.minus(5, DAYS)), + toDateTime(now.minus(5, DAYS)), toDateTime(plusYears(now, 2))), - toDateTime(now.minus(4, ChronoUnit.DAYS)), - toDateTime(now.minus(1, ChronoUnit.DAYS)), + toDateTime(now.minus(4, DAYS)), + toDateTime(now.minus(1, DAYS)), toDateTime(plusYears(now, 2))); assertThat(domain.getStatusValues()).contains(StatusValue.PENDING_TRANSFER); assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(now); diff --git a/core/src/test/java/google/registry/bigquery/BigqueryUtilsTest.java b/core/src/test/java/google/registry/bigquery/BigqueryUtilsTest.java index 434f6d8da..2f9b2d1ed 100644 --- a/core/src/test/java/google/registry/bigquery/BigqueryUtilsTest.java +++ b/core/src/test/java/google/registry/bigquery/BigqueryUtilsTest.java @@ -19,46 +19,45 @@ import static google.registry.bigquery.BigqueryUtils.fromBigqueryTimestampString import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestamp; import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestampString; import static google.registry.bigquery.BigqueryUtils.toJobReferenceString; -import static google.registry.util.DateTimeUtils.END_OF_TIME; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.END_INSTANT; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.services.bigquery.model.JobReference; +import java.time.Instant; +import java.time.format.DateTimeParseException; import java.util.concurrent.TimeUnit; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.jupiter.api.Test; /** Unit tests for {@link BigqueryUtils}. */ class BigqueryUtilsTest { - private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z"); - private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z"); - private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z"); - private static final DateTime DATE_3 = DateTime.parse("2014-07-17T20:35:42.123Z"); + private static final Instant DATE_0 = Instant.parse("2014-07-17T20:35:42Z"); + private static final Instant DATE_1 = Instant.parse("2014-07-17T20:35:42.1Z"); + private static final Instant DATE_2 = Instant.parse("2014-07-17T20:35:42.12Z"); + private static final Instant DATE_3 = Instant.parse("2014-07-17T20:35:42.123Z"); @Test void test_toBigqueryTimestampString() { - assertThat(toBigqueryTimestampString(START_OF_TIME)).isEqualTo("1970-01-01 00:00:00.000"); + assertThat(toBigqueryTimestampString(START_INSTANT)).isEqualTo("1970-01-01 00:00:00.000"); assertThat(toBigqueryTimestampString(DATE_0)).isEqualTo("2014-07-17 20:35:42.000"); assertThat(toBigqueryTimestampString(DATE_1)).isEqualTo("2014-07-17 20:35:42.100"); assertThat(toBigqueryTimestampString(DATE_2)).isEqualTo("2014-07-17 20:35:42.120"); assertThat(toBigqueryTimestampString(DATE_3)).isEqualTo("2014-07-17 20:35:42.123"); - assertThat(toBigqueryTimestampString(END_OF_TIME)).isEqualTo("294247-01-10 04:00:54.775"); + assertThat(toBigqueryTimestampString(END_INSTANT)).isEqualTo("294247-01-10 04:00:54.775"); } @Test void test_toBigqueryTimestampString_convertsToUtc() { - assertThat(toBigqueryTimestampString(START_OF_TIME.withZone(DateTimeZone.forOffsetHours(5)))) - .isEqualTo("1970-01-01 00:00:00.000"); - assertThat(toBigqueryTimestampString(DateTime.parse("1970-01-01T00:00:00-0500"))) + + assertThat(toBigqueryTimestampString(Instant.parse("1970-01-01T05:00:00Z"))) .isEqualTo("1970-01-01 05:00:00.000"); } @Test void test_fromBigqueryTimestampString_startAndEndOfTime() { - assertThat(fromBigqueryTimestampString("1970-01-01 00:00:00 UTC")).isEqualTo(START_OF_TIME); - assertThat(fromBigqueryTimestampString("294247-01-10 04:00:54.775 UTC")).isEqualTo(END_OF_TIME); + assertThat(fromBigqueryTimestampString("1970-01-01 00:00:00 UTC")).isEqualTo(START_INSTANT); + assertThat(fromBigqueryTimestampString("294247-01-10 04:00:54.775 UTC")).isEqualTo(END_INSTANT); } @Test @@ -78,20 +77,20 @@ class BigqueryUtilsTest { @Test void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() { assertThrows( - IllegalArgumentException.class, + DateTimeParseException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00")); } @Test void testFailure_fromBigqueryTimestampString_noTimeZone() { assertThrows( - IllegalArgumentException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01")); + DateTimeParseException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01")); } @Test void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() { assertThrows( - IllegalArgumentException.class, + DateTimeParseException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC")); } @@ -116,12 +115,12 @@ class BigqueryUtilsTest { @Test void test_toBigqueryTimestamp_datetimeConversion() { - assertThat(toBigqueryTimestamp(START_OF_TIME)).isEqualTo("0.000000"); + assertThat(toBigqueryTimestamp(START_INSTANT)).isEqualTo("0.000000"); assertThat(toBigqueryTimestamp(DATE_0)).isEqualTo("1405629342.000000"); assertThat(toBigqueryTimestamp(DATE_1)).isEqualTo("1405629342.100000"); assertThat(toBigqueryTimestamp(DATE_2)).isEqualTo("1405629342.120000"); assertThat(toBigqueryTimestamp(DATE_3)).isEqualTo("1405629342.123000"); - assertThat(toBigqueryTimestamp(END_OF_TIME)).isEqualTo("9223372036854.775000"); + assertThat(toBigqueryTimestamp(END_INSTANT)).isEqualTo("9223372036854.775000"); } @Test diff --git a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java index 35d69059f..0121fd979 100644 --- a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java @@ -20,9 +20,8 @@ import static google.registry.bsa.persistence.BsaTestingUtils.createDownloadSche import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.createTlds; import static google.registry.testing.DatabaseHelper.persistResource; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.joda.time.Duration.standardDays; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -43,11 +42,11 @@ import google.registry.testing.FakeClock; import google.registry.testing.FakeLockHandler; import google.registry.testing.FakeResponse; import java.security.MessageDigest; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import java.util.function.BiConsumer; import java.util.stream.Stream; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -59,7 +58,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class BsaDownloadFunctionalTest { - static final DateTime TEST_START_TIME = DateTime.parse("2024-01-01T00:00:00Z"); + static final Instant TEST_START_TIME = Instant.parse("2024-01-01T00:00:00Z"); static final String BSA_CSV_HEADER = "domainLabel,orderIDs"; @Mock BlockListFetcher blockListFetcher; @Mock BsaReportSender bsaReportSender; @@ -83,7 +82,9 @@ class BsaDownloadFunctionalTest { .forEach( tld -> persistResource( - tld.asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build())); + tld.asBuilder() + .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) + .build())); gcsClient = new GcsClient(new GcsUtils(LocalStorageHelper.getOptions()), "my-bucket", "SHA-256"); response = new FakeResponse(); @@ -96,8 +97,7 @@ class BsaDownloadFunctionalTest { gcsClient, () -> new IdnChecker(fakeClock), bsaEmailSender, - new BsaLock( - new FakeLockHandler(/* lockSucceeds= */ true), Duration.standardSeconds(30)), + new BsaLock(new FakeLockHandler(/* lockSucceeds= */ true), Duration.ofSeconds(30)), fakeClock, /* transactionBatchSize= */ 5, response); @@ -133,7 +133,7 @@ class BsaDownloadFunctionalTest { mockBlockListFetcher(blockList, blockPlusList, blockList2, blockPlusList2); action.run(); assertThat(getPersistedLabels()).containsExactly("abc", "def"); - fakeClock.advanceBy(standardDays(1)); + fakeClock.advanceBy(Duration.ofDays(1)); action.run(); assertThat(getPersistedLabels()).containsExactly("abc"); } diff --git a/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java b/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java index c26d36063..072427356 100644 --- a/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java +++ b/core/src/test/java/google/registry/bsa/BsaRefreshActionTest.java @@ -28,8 +28,8 @@ import google.registry.request.Response; import google.registry.testing.FakeClock; import google.registry.util.EmailMessage; import jakarta.mail.internet.InternetAddress; -import org.joda.time.DateTime; -import org.joda.time.Duration; +import java.time.Duration; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -40,7 +40,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class BsaRefreshActionTest { - FakeClock fakeClock = new FakeClock(DateTime.parse("2023-11-09T02:08:57.880Z")); + FakeClock fakeClock = new FakeClock(Instant.parse("2023-11-09T02:08:57.880Z")); @Mock RefreshScheduler scheduler; @@ -66,7 +66,7 @@ public class BsaRefreshActionTest { gcsClient, bsaReportSender, /* transactionBatchSize= */ 5, - /* domainCreateTxnCommitTimeLag= */ Duration.millis(1), + /* domainCreateTxnCommitTimeLag= */ Duration.ofMillis(1), new BsaEmailSender(gmailClient, emailRecipient), bsaLock, fakeClock, diff --git a/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java index 368fc87c5..d4d01fa12 100644 --- a/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java @@ -28,7 +28,7 @@ import static google.registry.testing.DatabaseHelper.createTlds; import static google.registry.testing.DatabaseHelper.deleteTestDomain; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistResource; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; @@ -55,9 +55,9 @@ import google.registry.testing.FakeClock; import google.registry.testing.FakeLockHandler; import google.registry.testing.FakeResponse; import java.io.UncheckedIOException; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -74,7 +74,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class BsaRefreshFunctionalTest { - static final DateTime TEST_START_TIME = DateTime.parse("2024-01-01T00:00:00Z"); + static final Instant TEST_START_TIME = Instant.parse("2024-01-01T00:00:00Z"); static final String RESERVED_LIST_NAME = "reserved"; @@ -103,17 +103,16 @@ class BsaRefreshFunctionalTest { gcsClient, bsaReportSender, /* transactionBatchSize= */ 5, - /* domainCreateTxnCommitTimeLag= */ Duration.millis(1), + /* domainCreateTxnCommitTimeLag= */ Duration.ofMillis(1), emailSender, - new BsaLock( - new FakeLockHandler(/* lockSucceeds= */ true), Duration.standardSeconds(30)), + new BsaLock(new FakeLockHandler(/* lockSucceeds= */ true), Duration.ofSeconds(30)), fakeClock, response); initDb(); } - private String getRefreshJobName(DateTime jobStartTime) { + private String getRefreshJobName(Instant jobStartTime) { return jobStartTime.toString() + "-refresh"; } @@ -123,7 +122,9 @@ class BsaRefreshFunctionalTest { .forEach( tld -> persistResource( - tld.asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build())); + tld.asBuilder() + .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) + .build())); createReservedList(RESERVED_LIST_NAME, "dummy", RESERVED_FOR_SPECIFIC_USE); addReservedListsToTld("app", ImmutableList.of(RESERVED_LIST_NAME)); @@ -139,7 +140,7 @@ class BsaRefreshFunctionalTest { void newReservedDomain_addedAsUnblockable() throws Exception { addReservedDomainToList( RESERVED_LIST_NAME, ImmutableMap.of("blocked1", RESERVED_FOR_SPECIFIC_USE)); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); action.run(); UnblockableDomain newUnblockable = new UnblockableDomain("blocked1.app", Reason.RESERVED); assertThat(queryUnblockableDomains()).containsExactly(newUnblockable); @@ -156,7 +157,7 @@ class BsaRefreshFunctionalTest { void newRegisteredDomain_addedAsUnblockable() throws Exception { persistActiveDomain("blocked1.dev", fakeClock.nowUtc()); persistActiveDomain("dummy.dev", fakeClock.nowUtc()); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); action.run(); UnblockableDomain newUnblockable = new UnblockableDomain("blocked1.dev", Reason.REGISTERED); assertThat(queryUnblockableDomains()).containsExactly(newUnblockable); @@ -178,7 +179,7 @@ class BsaRefreshFunctionalTest { deleteTestDomain(domain, fakeClock.nowUtc()); fakeClock.advanceOneMilli(); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); Mockito.reset(bsaReportSender); action.run(); assertThat(queryUnblockableDomains()).isEmpty(); @@ -201,7 +202,7 @@ class BsaRefreshFunctionalTest { fakeClock.advanceOneMilli(); removeReservedDomainFromList(RESERVED_LIST_NAME, ImmutableSet.of("blocked1")); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); Mockito.reset(bsaReportSender); action.run(); assertThat(queryUnblockableDomains()).isEmpty(); @@ -226,7 +227,7 @@ class BsaRefreshFunctionalTest { deleteTestDomain(domain, fakeClock.nowUtc()); fakeClock.advanceOneMilli(); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); Mockito.reset(bsaReportSender); action.run(); assertThat(queryUnblockableDomains()) @@ -254,7 +255,7 @@ class BsaRefreshFunctionalTest { fakeClock.advanceOneMilli(); Mockito.reset(bsaReportSender); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); action.run(); UnblockableDomain changed = new UnblockableDomain("blocked1.app", Reason.REGISTERED); assertThat(queryUnblockableDomains()).containsExactly(changed); @@ -274,7 +275,7 @@ class BsaRefreshFunctionalTest { addReservedDomainToList( RESERVED_LIST_NAME, ImmutableMap.of("blocked1", RESERVED_FOR_SPECIFIC_USE)); persistActiveDomain("blocked1.app", fakeClock.nowUtc()); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); action.run(); UnblockableDomain newUnblockable = new UnblockableDomain("blocked1.app", Reason.REGISTERED); assertThat(queryUnblockableDomains()).containsExactly(newUnblockable); @@ -295,7 +296,7 @@ class BsaRefreshFunctionalTest { fakeClock.advanceOneMilli(); Mockito.reset(bsaReportSender); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); action.run(); assertThat(queryUnblockableDomains()) .containsExactly(new UnblockableDomain("blocked1.app", Reason.REGISTERED)); @@ -320,7 +321,7 @@ class BsaRefreshFunctionalTest { fakeClock.advanceOneMilli(); Mockito.reset(bsaReportSender); - String jobName = getRefreshJobName(fakeClock.nowUtc()); + String jobName = getRefreshJobName(fakeClock.now()); action.run(); assertThat(queryUnblockableDomains()) .containsExactly(new UnblockableDomain("blocked1.app", Reason.REGISTERED)); diff --git a/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java b/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java index 7577145e4..a5047e620 100644 --- a/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java +++ b/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java @@ -26,7 +26,6 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.util.DateTimeUtils.START_OF_TIME; -import static org.joda.time.Duration.millis; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.startsWith; @@ -108,7 +107,7 @@ public class BsaValidateActionTest { idnChecker, new BsaEmailSender(gmailClient, emailRecipient), /* transactionBatchSize= */ 500, - millis(MAX_STALENESS.toMillis()), + MAX_STALENESS, fakeClock, response); createTld("app"); @@ -239,7 +238,7 @@ public class BsaValidateActionTest { void isStalenessAllowed_newDomain_allowed() { persistBsaLabel("label"); Domain domain = persistActiveDomain("label.app", fakeClock.nowUtc()); - fakeClock.advanceBy(millis(MAX_STALENESS.minusSeconds(1).toMillis())); + fakeClock.advanceBy(MAX_STALENESS.minusSeconds(1)); assertThat(action.isStalenessAllowed(domain)).isTrue(); } @@ -247,7 +246,7 @@ public class BsaValidateActionTest { void isStalenessAllowed_newDomain_notAllowed() { persistBsaLabel("label"); Domain domain = persistActiveDomain("label.app", fakeClock.nowUtc()); - fakeClock.advanceBy(millis(MAX_STALENESS.toMillis())); + fakeClock.advanceBy(MAX_STALENESS); assertThat(action.isStalenessAllowed(domain)).isFalse(); } diff --git a/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java b/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java index 4e72f4f3b..5f816e413 100644 --- a/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java +++ b/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java @@ -21,7 +21,7 @@ import static google.registry.testing.DatabaseHelper.persistDeletedDomain; import static google.registry.testing.DatabaseHelper.persistReservedList; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.LogsSubject.assertAboutLogs; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.NetworkUtils.pickUnusedPort; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.Executors.newSingleThreadExecutor; @@ -60,12 +60,12 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.InetAddress; +import java.time.Instant; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -81,7 +81,7 @@ public class UploadBsaUnavailableDomainsActionTest { private static final String API_URL = "https://upload.test/bsa"; - private final FakeClock clock = new FakeClock(DateTime.parse("2024-02-02T02:02:02Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2024-02-02T02:02:02Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -112,7 +112,7 @@ public class UploadBsaUnavailableDomainsActionTest { Tld.get("tld") .asBuilder() .setReservedLists(reservedList) - .setBsaEnrollStartTime(Optional.of(START_OF_TIME)) + .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) .setTldType(TldType.REAL) .build()); action = diff --git a/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java b/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java index c2ae04a5c..63510e7d0 100644 --- a/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java +++ b/core/src/test/java/google/registry/bsa/api/BsaCredentialTest.java @@ -36,8 +36,8 @@ import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.security.GeneralSecurityException; +import java.time.Duration; import javax.net.ssl.HttpsURLConnection; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -48,7 +48,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class BsaCredentialTest { - private static final Duration AUTH_TOKEN_EXPIRY = Duration.standardMinutes(30); + private static final Duration AUTH_TOKEN_EXPIRY = Duration.ofMinutes(30); @Mock OutputStream connectionOutputStream; @Mock HttpsURLConnection connection; @@ -82,7 +82,7 @@ class BsaCredentialTest { credential = spy(credential); doReturn("a", "b", "c").when(credential).fetchNewAuthToken(); assertThat(credential.getAuthToken()).isEqualTo("a"); - clock.advanceBy(AUTH_TOKEN_EXPIRY.minus(Duration.millis(1))); + clock.advanceBy(AUTH_TOKEN_EXPIRY.minus(Duration.ofMillis(1))); assertThat(credential.getAuthToken()).isEqualTo("a"); verify(credential, times(1)).fetchNewAuthToken(); } diff --git a/core/src/test/java/google/registry/bsa/persistence/BsaDomainRefreshTest.java b/core/src/test/java/google/registry/bsa/persistence/BsaDomainRefreshTest.java index e9acb4368..989f03b65 100644 --- a/core/src/test/java/google/registry/bsa/persistence/BsaDomainRefreshTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/BsaDomainRefreshTest.java @@ -17,19 +17,18 @@ package google.registry.bsa.persistence; import static com.google.common.truth.Truth.assertThat; import static google.registry.bsa.RefreshStage.CHECK_FOR_CHANGES; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static org.joda.time.DateTimeZone.UTC; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; import google.registry.testing.FakeClock; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit test for {@link BsaDomainRefresh}. */ public class BsaDomainRefreshTest { - protected FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); + protected FakeClock fakeClock = new FakeClock(Instant.parse("2024-01-01T00:00:00Z")); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = diff --git a/core/src/test/java/google/registry/bsa/persistence/BsaDownloadTest.java b/core/src/test/java/google/registry/bsa/persistence/BsaDownloadTest.java index 81606299e..13b2cb70e 100644 --- a/core/src/test/java/google/registry/bsa/persistence/BsaDownloadTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/BsaDownloadTest.java @@ -19,21 +19,20 @@ import static google.registry.bsa.BlockListType.BLOCK; import static google.registry.bsa.BlockListType.BLOCK_PLUS; import static google.registry.bsa.DownloadStage.DOWNLOAD_BLOCK_LISTS; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static org.joda.time.DateTimeZone.UTC; import com.google.common.collect.ImmutableMap; import google.registry.bsa.BlockListType; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; import google.registry.testing.FakeClock; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit test for {@link BsaDownload}. */ public class BsaDownloadTest { - FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); + FakeClock fakeClock = new FakeClock(Instant.parse("2024-01-01T00:00:00Z")); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = diff --git a/core/src/test/java/google/registry/bsa/persistence/BsaLabelUtilsTest.java b/core/src/test/java/google/registry/bsa/persistence/BsaLabelUtilsTest.java index bfc387249..bb85a088a 100644 --- a/core/src/test/java/google/registry/bsa/persistence/BsaLabelUtilsTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/BsaLabelUtilsTest.java @@ -21,9 +21,6 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.persistence.transaction.TransactionManagerFactory.setJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.setReplicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static org.joda.time.DateTimeZone.UTC; -import static org.joda.time.Duration.millis; -import static org.joda.time.Duration.standardMinutes; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -35,14 +32,15 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; import google.registry.persistence.transaction.JpaTransactionManager; import google.registry.testing.FakeClock; -import org.joda.time.DateTime; +import java.time.Duration; +import java.time.Instant; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link BsaLabelUtils}. */ public class BsaLabelUtilsTest { - protected FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); + protected FakeClock fakeClock = new FakeClock(Instant.parse("2024-01-01T00:00:00Z")); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = @@ -90,7 +88,7 @@ public class BsaLabelUtilsTest { assertThat(isLabelBlocked("abc")).isTrue(); // If test fails, check and fix cache expiry in the config file. Do not increase the duration // on the line below without proper discussion. - fakeClock.advanceBy(standardMinutes(1).plus(millis(1))); + fakeClock.advanceBy(Duration.ofMinutes(1).plus(Duration.ofMillis(1))); assertThat(isLabelBlocked("abc")).isTrue(); verify(replicaTm, times(2)).loadByKey(any()); } catch (Throwable e) { diff --git a/core/src/test/java/google/registry/bsa/persistence/BsaTestingUtils.java b/core/src/test/java/google/registry/bsa/persistence/BsaTestingUtils.java index 5acd3613d..0cabd8624 100644 --- a/core/src/test/java/google/registry/bsa/persistence/BsaTestingUtils.java +++ b/core/src/test/java/google/registry/bsa/persistence/BsaTestingUtils.java @@ -21,14 +21,14 @@ import com.google.common.collect.ImmutableList; import google.registry.bsa.DownloadStage; import google.registry.bsa.api.UnblockableDomain; import google.registry.util.Clock; +import java.time.Duration; import java.time.Instant; -import org.joda.time.Duration; /** Exposes BSA persistence entities and tools to test classes. */ public final class BsaTestingUtils { - public static final Duration DEFAULT_DOWNLOAD_INTERVAL = Duration.standardHours(1); - public static final Duration DEFAULT_NOP_INTERVAL = Duration.standardDays(1); + public static final Duration DEFAULT_DOWNLOAD_INTERVAL = Duration.ofHours(1); + public static final Duration DEFAULT_NOP_INTERVAL = Duration.ofDays(1); /** An arbitrary point of time used as BsaLabels' creation time. */ public static final Instant BSA_LABEL_CREATION_TIME = Instant.parse("2023-12-31T00:00:00Z"); diff --git a/core/src/test/java/google/registry/bsa/persistence/BsaUnblockableDomainTest.java b/core/src/test/java/google/registry/bsa/persistence/BsaUnblockableDomainTest.java index d28f05ea8..6aea68e39 100644 --- a/core/src/test/java/google/registry/bsa/persistence/BsaUnblockableDomainTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/BsaUnblockableDomainTest.java @@ -16,7 +16,6 @@ package google.registry.bsa.persistence; import static com.google.common.truth.Truth.assertThat; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static org.joda.time.DateTimeZone.UTC; import static org.junit.jupiter.api.Assertions.assertThrows; import google.registry.bsa.api.UnblockableDomain; @@ -25,14 +24,14 @@ import google.registry.persistence.transaction.DatabaseException; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; import google.registry.testing.FakeClock; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link BsaUnblockableDomain}. */ public class BsaUnblockableDomainTest { - FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); + FakeClock fakeClock = new FakeClock(Instant.parse("2024-01-01T00:00:00Z")); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = diff --git a/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java b/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java index f29331bc6..d3add84a6 100644 --- a/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java @@ -22,7 +22,6 @@ import static google.registry.bsa.DownloadStage.MAKE_ORDER_AND_LABEL_DIFF; import static google.registry.bsa.DownloadStage.NOP; import static google.registry.bsa.persistence.DownloadScheduler.fetchTwoMostRecentDownloads; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static org.joda.time.Duration.standardSeconds; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -33,9 +32,9 @@ import google.registry.bsa.persistence.DownloadSchedule.CompletedJob; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; import google.registry.testing.FakeClock; +import java.time.Duration; import java.time.Instant; import java.util.Optional; -import org.joda.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -44,8 +43,8 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link DownloadScheduler} */ class DownloadSchedulerTest { - static final Duration DOWNLOAD_INTERVAL = Duration.standardMinutes(30); - static final Duration MAX_NOP_INTERVAL = Duration.standardDays(1); + static final Duration DOWNLOAD_INTERVAL = Duration.ofMinutes(30); + static final Duration MAX_NOP_INTERVAL = Duration.ofDays(1); FakeClock fakeClock = new FakeClock(Instant.parse("2023-11-09T02:08:57.880Z")); @@ -151,14 +150,14 @@ class DownloadSchedulerTest { @Test void doneJob_cronEarlyWithJitter_newSchedule() { insertOneJobAndAdvanceClock(DONE); - fakeClock.advanceBy(DOWNLOAD_INTERVAL.minus(standardSeconds(5))); + fakeClock.advanceBy(DOWNLOAD_INTERVAL.minus(Duration.ofSeconds(5))); assertThat(scheduler.schedule()).isPresent(); } @Test void doneJob_cronEarlyMoreThanJitter_newSchedule() { insertOneJobAndAdvanceClock(DONE); - fakeClock.advanceBy(DOWNLOAD_INTERVAL.minus(standardSeconds(6))); + fakeClock.advanceBy(DOWNLOAD_INTERVAL.minus(Duration.ofSeconds(6))); assertThat(scheduler.schedule()).isEmpty(); } diff --git a/core/src/test/java/google/registry/bsa/persistence/LabelDiffUpdatesTest.java b/core/src/test/java/google/registry/bsa/persistence/LabelDiffUpdatesTest.java index 570f9a89f..43308c9e2 100644 --- a/core/src/test/java/google/registry/bsa/persistence/LabelDiffUpdatesTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/LabelDiffUpdatesTest.java @@ -22,7 +22,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.tldconfig.idn.IdnTableEnum.UNCONFUSABLE_LATIN; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -39,8 +39,8 @@ import google.registry.model.tld.label.ReservationType; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationWithCoverageExtension; import google.registry.testing.FakeClock; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -52,7 +52,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class LabelDiffUpdatesTest { - FakeClock fakeClock = new FakeClock(DateTime.parse("2023-11-09T02:08:57.880Z")); + FakeClock fakeClock = new FakeClock(Instant.parse("2023-11-09T02:08:57.880Z")); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = @@ -74,7 +74,7 @@ class LabelDiffUpdatesTest { () -> tm().put( tld.asBuilder() - .setBsaEnrollStartTime(Optional.of(START_OF_TIME)) + .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) .setIdnTables(ImmutableSet.of(UNCONFUSABLE_LATIN)) .build())); app = tm().transact(() -> tm().loadByEntity(tld)); @@ -96,7 +96,7 @@ class LabelDiffUpdatesTest { ImmutableList.of(BlockLabel.create("label", LabelType.DELETE, ImmutableSet.of())), idnChecker, schedule, - fakeClock.nowUtc()); + fakeClock.now()); assertThat(unblockableDomains).isEmpty(); assertThat(tm().transact(() -> tm().loadByKeyIfPresent(BsaLabel.vKey("label")))).isEmpty(); assertThat( @@ -121,7 +121,7 @@ class LabelDiffUpdatesTest { BlockLabel.create("label", LabelType.NEW_ORDER_ASSOCIATION, ImmutableSet.of())), idnChecker, schedule, - fakeClock.nowUtc()); + fakeClock.now()); assertThat(unblockableDomains) .containsExactly( new UnblockableDomain("label.app", UnblockableDomain.Reason.REGISTERED), @@ -148,7 +148,7 @@ class LabelDiffUpdatesTest { ImmutableList.of(BlockLabel.create("label", LabelType.CREATE, ImmutableSet.of())), idnChecker, schedule, - fakeClock.nowUtc()); + fakeClock.now()); assertThat(unblockableDomains) .containsExactly( new UnblockableDomain("label.app", UnblockableDomain.Reason.REGISTERED), diff --git a/core/src/test/java/google/registry/dns/DnsInjectionTest.java b/core/src/test/java/google/registry/dns/DnsInjectionTest.java index 05dfa01fe..7a2a7d218 100644 --- a/core/src/test/java/google/registry/dns/DnsInjectionTest.java +++ b/core/src/test/java/google/registry/dns/DnsInjectionTest.java @@ -36,7 +36,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.StringWriter; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -47,7 +47,7 @@ public final class DnsInjectionTest { private final HttpServletRequest req = mock(HttpServletRequest.class); private final HttpServletResponse rsp = mock(HttpServletResponse.class); private final StringWriter httpOutput = new StringWriter(); - private final FakeClock clock = new FakeClock(DateTime.parse("2014-01-01TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("2014-01-01T00:00:00Z")); private DnsTestComponent component; @RegisterExtension diff --git a/core/src/test/java/google/registry/dns/DnsUtilsTest.java b/core/src/test/java/google/registry/dns/DnsUtilsTest.java index 69e54d368..7fc274e98 100644 --- a/core/src/test/java/google/registry/dns/DnsUtilsTest.java +++ b/core/src/test/java/google/registry/dns/DnsUtilsTest.java @@ -23,7 +23,8 @@ import static google.registry.dns.DnsUtils.requestHostDnsRefresh; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.loadAllOf; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; +import static google.registry.util.DateTimeUtils.minusMinutes; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; @@ -32,9 +33,9 @@ import google.registry.model.common.DnsRefreshRequest; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; +import java.time.Duration; +import java.time.Instant; import java.util.Comparator; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -47,7 +48,7 @@ public class DnsUtilsTest { private static final String domainName = "test.tld"; private static final String hostName = "ns1.test.tld"; - private final FakeClock clock = new FakeClock(DateTime.parse("2020-02-02T01:23:45Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2020-02-02T01:23:45Z")); @RegisterExtension JpaIntegrationTestExtension jpa = @@ -80,7 +81,7 @@ public class DnsUtilsTest { void testSuccess_hostRefresh() { tm().transact(() -> requestHostDnsRefresh(hostName)); DnsRefreshRequest request = Iterables.getOnlyElement(loadAllOf(DnsRefreshRequest.class)); - assertRequest(request, TargetType.HOST, hostName, tld, clock.nowUtc()); + assertRequest(request, TargetType.HOST, hostName, tld, clock.now()); } @Test @@ -89,57 +90,58 @@ public class DnsUtilsTest { () -> requestDomainDnsRefresh(ImmutableList.of(domainName, "test2.tld", "test3.tld"))); ImmutableList requests = loadAllOf(DnsRefreshRequest.class); assertThat(requests.size()).isEqualTo(3); - assertRequest(requests.get(0), TargetType.DOMAIN, domainName, tld, clock.nowUtc()); - assertRequest(requests.get(1), TargetType.DOMAIN, "test2.tld", tld, clock.nowUtc()); - assertRequest(requests.get(2), TargetType.DOMAIN, "test3.tld", tld, clock.nowUtc()); + assertRequest(requests.get(0), TargetType.DOMAIN, domainName, tld, clock.now()); + assertRequest(requests.get(1), TargetType.DOMAIN, "test2.tld", tld, clock.now()); + assertRequest(requests.get(2), TargetType.DOMAIN, "test3.tld", tld, clock.now()); } @Test void testSuccess_domainRefreshMultipleDomains() { tm().transact(() -> requestDomainDnsRefresh(domainName)); DnsRefreshRequest request = Iterables.getOnlyElement(loadAllOf(DnsRefreshRequest.class)); - assertRequest(request, TargetType.DOMAIN, domainName, tld, clock.nowUtc()); + assertRequest(request, TargetType.DOMAIN, domainName, tld, clock.now()); } @Test void testSuccess_domainRefreshWithDelay() { - tm().transact(() -> requestDomainDnsRefresh(domainName, Duration.standardMinutes(3))); + tm().transact(() -> requestDomainDnsRefresh(domainName, Duration.ofMinutes(3))); DnsRefreshRequest request = Iterables.getOnlyElement(loadAllOf(DnsRefreshRequest.class)); - assertRequest(request, TargetType.DOMAIN, domainName, tld, clock.nowUtc().plusMinutes(3)); + assertRequest( + request, TargetType.DOMAIN, domainName, tld, clock.now().plus(Duration.ofMinutes(3))); } @Test void testSuccess_ProcessRequests() { ImmutableList requests = processRequests(); - DateTime processtime = clock.nowUtc(); + Instant processtime = clock.now(); assertThat(requests.size()).isEqualTo(4); assertRequest( requests.get(0), TargetType.DOMAIN, "test2.tld", "tld", - clock.nowUtc().minusMinutes(4), + minusMinutes(clock.now(), 4), processtime); assertRequest( requests.get(1), TargetType.DOMAIN, "test1.tld", "tld", - clock.nowUtc().minusMinutes(3), + minusMinutes(clock.now(), 3), processtime); assertRequest( requests.get(2), TargetType.HOST, "ns1.test2.tld", "tld", - clock.nowUtc().minusMinutes(1), + minusMinutes(clock.now(), 1), processtime); assertRequest( requests.get(3), TargetType.DOMAIN, "test5.tld", "tld", - clock.nowUtc().minusMinutes(1), + minusMinutes(clock.now(), 1), processtime); requests = loadAllOf(DnsRefreshRequest.class); assertThat(requests.size()).isEqualTo(7); @@ -149,15 +151,15 @@ public class DnsUtilsTest { clock.advanceOneMilli(); // Requests within cooldown period not included. - requests = readAndUpdateRequestsWithLatestProcessTime("tld", Duration.standardMinutes(1), 4); + requests = readAndUpdateRequestsWithLatestProcessTime("tld", Duration.ofMinutes(1), 4); assertThat(requests.size()).isEqualTo(1); assertRequest( requests.get(0), TargetType.DOMAIN, "test6.tld", "tld", - clock.nowUtc().minusMinutes(1).minusMillis(1), - clock.nowUtc()); + minusMinutes(clock.now(), 1).minusMillis(1), + clock.now()); } @Test @@ -173,19 +175,19 @@ public class DnsUtilsTest { TargetType.DOMAIN, "something.example", "example", - clock.nowUtc().minusMinutes(2)); + minusMinutes(clock.now(), 2)); assertRequest( remainingRequests.get(1), TargetType.DOMAIN, "test6.tld", "tld", - clock.nowUtc().minusMinutes(1)); + minusMinutes(clock.now(), 1)); assertRequest( remainingRequests.get(2), TargetType.DOMAIN, "test4.tld", "tld", - clock.nowUtc().plusMinutes(1)); + clock.now().plus(Duration.ofMinutes(1))); tm().transact(() -> tm().delete(remainingRequests.get(2))); assertThat(loadAllOf(DnsRefreshRequest.class).size()).isEqualTo(2); // Should not throw even though one of the request is already deleted. @@ -196,28 +198,28 @@ public class DnsUtilsTest { private ImmutableList processRequests() { createTld("example"); // Domain Included. - tm().transact(() -> requestDomainDnsRefresh("test1.tld", Duration.standardMinutes(1))); + tm().transact(() -> requestDomainDnsRefresh("test1.tld", Duration.ofMinutes(1))); // This one should be returned before test1.tld, even though it's added later, because of // the delay specified in test1.tld. tm().transact(() -> requestDomainDnsRefresh("test2.tld")); // Not included because the TLD is not under management. - tm().transact(() -> requestDomainDnsRefresh("something.example", Duration.standardMinutes(2))); - clock.advanceBy(Duration.standardMinutes(3)); + tm().transact(() -> requestDomainDnsRefresh("something.example", Duration.ofMinutes(2))); + clock.advanceBy(Duration.ofMinutes(3)); // Host included. tm().transact(() -> requestHostDnsRefresh("ns1.test2.tld")); // Not included because the request time is in the future - tm().transact(() -> requestDomainDnsRefresh("test4.tld", Duration.standardMinutes(2))); + tm().transact(() -> requestDomainDnsRefresh("test4.tld", Duration.ofMinutes(2))); // Included after the previous one. Same request time, order by insertion order (i.e. ID); tm().transact(() -> requestDomainDnsRefresh("test5.tld")); // Not included because batch size is exceeded; tm().transact(() -> requestDomainDnsRefresh("test6.tld")); - clock.advanceBy(Duration.standardMinutes(1)); - return readAndUpdateRequestsWithLatestProcessTime("tld", Duration.standardMinutes(1), 4); + clock.advanceBy(Duration.ofMinutes(1)); + return readAndUpdateRequestsWithLatestProcessTime("tld", Duration.ofMinutes(1), 4); } private static void assertRequest( - DnsRefreshRequest request, TargetType type, String name, String tld, DateTime requestTime) { - assertRequest(request, type, name, tld, requestTime, START_OF_TIME); + DnsRefreshRequest request, TargetType type, String name, String tld, Instant requestTime) { + assertRequest(request, type, name, tld, requestTime, START_INSTANT); } private static void assertRequest( @@ -225,8 +227,8 @@ public class DnsUtilsTest { TargetType type, String name, String tld, - DateTime requestTime, - DateTime processTime) { + Instant requestTime, + Instant processTime) { assertThat(request.getType()).isEqualTo(type); assertThat(request.getName()).isEqualTo(name); assertThat(request.getTld()).isEqualTo(tld); diff --git a/core/src/test/java/google/registry/dns/PublishDnsUpdatesActionTest.java b/core/src/test/java/google/registry/dns/PublishDnsUpdatesActionTest.java index b4501172c..430411ad8 100644 --- a/core/src/test/java/google/registry/dns/PublishDnsUpdatesActionTest.java +++ b/core/src/test/java/google/registry/dns/PublishDnsUpdatesActionTest.java @@ -65,9 +65,9 @@ import google.registry.testing.FakeResponse; import google.registry.testing.Lazies; import google.registry.util.EmailMessage; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.Instant; import java.util.Set; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -80,7 +80,7 @@ public class PublishDnsUpdatesActionTest { final JpaIntegrationTestExtension jpa = new JpaTestExtensions.Builder().buildIntegrationTestExtension(); - private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("1971-01-01T00:00:00Z")); private final FakeResponse response = new FakeResponse(); private final FakeLockHandler lockHandler = new FakeLockHandler(true); private final DnsWriter dnsWriter = mock(DnsWriter.class); @@ -144,14 +144,14 @@ public class PublishDnsUpdatesActionTest { return new PublishDnsUpdatesAction( dnsWriterString, - clock.nowUtc().minusHours(1), - clock.nowUtc().minusHours(2), + clock.now().minus(Duration.ofHours(1)), + clock.now().minus(Duration.ofHours(2)), lockIndex, numPublishLocks, domains, hosts, tld, - Duration.standardSeconds(10), + Duration.ofSeconds(10), "Subj", "Body %1$s %2$s %3$s %4$s %5$s", "awesomeRegistry", @@ -188,8 +188,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.SUCCESS, 1, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertNoDnsRequests(); assertThat(response.getStatus()).isEqualTo(SC_OK); @@ -215,8 +215,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.SUCCESS, 1, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertNoDnsRequests(); assertThat(response.getStatus()).isEqualTo(SC_OK); @@ -239,8 +239,7 @@ public class PublishDnsUpdatesActionTest { action.run(); verify(mockLockHandler) - .executeWithLocks( - action, "xn--q9jyb4c", Duration.standardSeconds(10), "DNS updates-lock 2 of 4"); + .executeWithLocks(action, "xn--q9jyb4c", Duration.ofSeconds(10), "DNS updates-lock 2 of 4"); } @Test @@ -268,8 +267,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.COMMIT_FAILURE, 5, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertNoDnsRequests(); } @@ -294,8 +293,8 @@ public class PublishDnsUpdatesActionTest { .param(PARAM_DNS_WRITER, "correctWriter") .param(PARAM_LOCK_INDEX, "1") .param(PARAM_NUM_PUBLISH_LOCKS, "1") - .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) - .param(PARAM_REFRESH_REQUEST_TIME, clock.nowUtc().minusHours(2).toString()) + .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) + .param(PARAM_REFRESH_REQUEST_TIME, clock.now().minus(Duration.ofHours(2)).toString()) .param(PARAM_DOMAINS, "example1.xn--q9jyb4c,example2.xn--q9jyb4c") .param(PARAM_HOSTS, "") .header("content-type", "application/x-www-form-urlencoded"), @@ -305,8 +304,8 @@ public class PublishDnsUpdatesActionTest { .param(PARAM_DNS_WRITER, "correctWriter") .param(PARAM_LOCK_INDEX, "1") .param(PARAM_NUM_PUBLISH_LOCKS, "1") - .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) - .param(PARAM_REFRESH_REQUEST_TIME, clock.nowUtc().minusHours(2).toString()) + .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) + .param(PARAM_REFRESH_REQUEST_TIME, clock.now().minus(Duration.ofHours(2)).toString()) .param(PARAM_DOMAINS, "example3.xn--q9jyb4c,example4.xn--q9jyb4c") .param(PARAM_HOSTS, "ns1.example.xn--q9jyb4c") .header("content-type", "application/x-www-form-urlencoded")); @@ -333,8 +332,8 @@ public class PublishDnsUpdatesActionTest { .param(PARAM_DNS_WRITER, "correctWriter") .param(PARAM_LOCK_INDEX, "1") .param(PARAM_NUM_PUBLISH_LOCKS, "1") - .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) - .param(PARAM_REFRESH_REQUEST_TIME, clock.nowUtc().minusHours(2).toString()) + .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) + .param(PARAM_REFRESH_REQUEST_TIME, clock.now().minus(Duration.ofHours(2)).toString()) .param(PARAM_DOMAINS, "example1.xn--q9jyb4c,example2.xn--q9jyb4c") .param(PARAM_HOSTS, "") .header("content-type", "application/x-www-form-urlencoded"), @@ -344,8 +343,8 @@ public class PublishDnsUpdatesActionTest { .param(PARAM_DNS_WRITER, "correctWriter") .param(PARAM_LOCK_INDEX, "1") .param(PARAM_NUM_PUBLISH_LOCKS, "1") - .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) - .param(PARAM_REFRESH_REQUEST_TIME, clock.nowUtc().minusHours(2).toString()) + .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) + .param(PARAM_REFRESH_REQUEST_TIME, clock.now().minus(Duration.ofHours(2)).toString()) .param(PARAM_DOMAINS, "example3.xn--q9jyb4c,example4.xn--q9jyb4c,example5.xn--q9jyb4c") .param(PARAM_HOSTS, "ns1.example.xn--q9jyb4c") .header("content-type", "application/x-www-form-urlencoded")); @@ -370,8 +369,8 @@ public class PublishDnsUpdatesActionTest { .param(PARAM_DNS_WRITER, "correctWriter") .param(PARAM_LOCK_INDEX, "1") .param(PARAM_NUM_PUBLISH_LOCKS, "1") - .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) - .param(PARAM_REFRESH_REQUEST_TIME, clock.nowUtc().minusHours(2).toString()) + .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) + .param(PARAM_REFRESH_REQUEST_TIME, clock.now().minus(Duration.ofHours(2)).toString()) .param(PARAM_DOMAINS, "example1.xn--q9jyb4c") .param(PARAM_HOSTS, "") .header("content-type", "application/x-www-form-urlencoded"), @@ -381,8 +380,8 @@ public class PublishDnsUpdatesActionTest { .param(PARAM_DNS_WRITER, "correctWriter") .param(PARAM_LOCK_INDEX, "1") .param(PARAM_NUM_PUBLISH_LOCKS, "1") - .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.nowUtc().toString()) - .param(PARAM_REFRESH_REQUEST_TIME, clock.nowUtc().minusHours(2).toString()) + .param(PARAM_PUBLISH_TASK_ENQUEUED, clock.now().toString()) + .param(PARAM_REFRESH_REQUEST_TIME, clock.now().minus(Duration.ofHours(2)).toString()) .param(PARAM_DOMAINS, "") .param(PARAM_HOSTS, "ns1.example.xn--q9jyb4c") .header("content-type", "application/x-www-form-urlencoded")); @@ -474,8 +473,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.SUCCESS, 5, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertNoDnsRequests(); } @@ -504,8 +503,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.SUCCESS, 5, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertNoDnsRequests(); } @@ -532,8 +531,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.LOCK_FAILURE, 5, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertNoDnsRequests(); } @@ -558,8 +557,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.BAD_LOCK_INDEX, 2, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertDomainDnsRequests("example.com"); assertHostDnsRequests("ns1.example.com"); @@ -586,8 +585,8 @@ public class PublishDnsUpdatesActionTest { "correctWriter", ActionStatus.BAD_LOCK_INDEX, 2, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertDomainDnsRequests("example.com"); assertHostDnsRequests("ns1.example.com"); @@ -610,8 +609,8 @@ public class PublishDnsUpdatesActionTest { "wrongWriter", ActionStatus.BAD_WRITER, 5, - Duration.standardHours(2), - Duration.standardHours(1)); + Duration.ofHours(2), + Duration.ofHours(1)); verifyNoMoreInteractions(dnsMetrics); assertDomainDnsRequests("example.com"); assertDomainDnsRequests("example2.com"); diff --git a/core/src/test/java/google/registry/dns/ReadDnsRefreshRequestsActionTest.java b/core/src/test/java/google/registry/dns/ReadDnsRefreshRequestsActionTest.java index 0f06a78eb..7c4ddad4a 100644 --- a/core/src/test/java/google/registry/dns/ReadDnsRefreshRequestsActionTest.java +++ b/core/src/test/java/google/registry/dns/ReadDnsRefreshRequestsActionTest.java @@ -19,7 +19,7 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.loadAllOf; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResources; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyCollection; @@ -43,11 +43,10 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; +import java.time.Duration; +import java.time.Instant; import java.util.Collection; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -56,7 +55,7 @@ import org.mockito.ArgumentCaptor; /** Unit tests for {@link DnsRefreshRequestTest}. */ public class ReadDnsRefreshRequestsActionTest { - private final FakeClock clock = new FakeClock(DateTime.parse("2020-02-02T01:23:45Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2020-02-02T01:23:45Z")); private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); private final Optional jitterSeconds = Optional.of(5); @@ -68,7 +67,7 @@ public class ReadDnsRefreshRequestsActionTest { spy( new ReadDnsRefreshRequestsAction( 2, - Duration.standardSeconds(10), + Duration.ofSeconds(10), jitterSeconds, "tld", clock, @@ -87,15 +86,21 @@ public class ReadDnsRefreshRequestsActionTest { .build()); requests = new ImmutableList.Builder() - .add(new DnsRefreshRequest(TargetType.DOMAIN, "domain.tld", "tld", clock.nowUtc())) + .add(new DnsRefreshRequest(TargetType.DOMAIN, "domain.tld", "tld", clock.now())) .add( new DnsRefreshRequest( - TargetType.HOST, "ns1.domain.tld", "tld", clock.nowUtc().minusMinutes(1))) + TargetType.HOST, + "ns1.domain.tld", + "tld", + clock.now().minus(Duration.ofMinutes(1)))) .add( new DnsRefreshRequest( - TargetType.DOMAIN, "future.tld", "tld", clock.nowUtc().plusMinutes(1))) + TargetType.DOMAIN, + "future.tld", + "tld", + clock.now().plus(Duration.ofMinutes(1)))) .build(); - clock.advanceBy(Duration.standardMinutes(5)); + clock.advanceBy(Duration.ofMinutes(5)); persistResources(requests); requests = loadAllOf(DnsRefreshRequest.class); } @@ -110,7 +115,7 @@ public class ReadDnsRefreshRequestsActionTest { @Test void testSuccess_runAction_requestTimeInTheFuture() { - clock.setTo(DateTime.parse("2000-01-01T00:00:00Z")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.run(); verify(action, never()).enqueueUpdates(anyInt(), anyInt(), anyCollection()); verify(action, never()).processRequests(anyCollection()); @@ -176,7 +181,7 @@ public class ReadDnsRefreshRequestsActionTest { (ImmutableList) invocation.callRealMethod(); // After this function is called once, the loop in run() should top when it checks // if the current time is before the request end time. - clock.advanceBy(Duration.standardHours(1)); + clock.advanceBy(Duration.ofHours(1)); return ans; }) .when(action) @@ -187,7 +192,7 @@ public class ReadDnsRefreshRequestsActionTest { // The third request is left untouched because it is not read; ImmutableList remainingRequests = loadAllOf(DnsRefreshRequest.class); assertThat(remainingRequests.size()).isEqualTo(1); - assertThat(remainingRequests.get(0).getLastProcessTime()).isEqualTo(START_OF_TIME); + assertThat(remainingRequests.get(0).getLastProcessTime()).isEqualTo(START_INSTANT); } @Test @@ -231,8 +236,8 @@ public class ReadDnsRefreshRequestsActionTest { .param("dnsWriter", "FooWriter") .param("lockIndex", "2") .param("numPublishLocks", "3") - .param("enqueued", clock.nowUtc().toString()) - .param("requestTime", clock.nowUtc().minusMinutes(6).toString()) + .param("enqueued", clock.now().toString()) + .param("requestTime", clock.now().minus(Duration.ofMinutes(6)).toString()) .param("domains", "domain.tld,future.tld") .param("hosts", "ns1.domain.tld"), new TaskMatcher() @@ -242,18 +247,17 @@ public class ReadDnsRefreshRequestsActionTest { .param("dnsWriter", "BarWriter") .param("lockIndex", "2") .param("numPublishLocks", "3") - .param("enqueued", clock.nowUtc().toString()) - .param("requestTime", clock.nowUtc().minusMinutes(6).toString()) + .param("enqueued", clock.now().toString()) + .param("requestTime", clock.now().minus(Duration.ofMinutes(6)).toString()) .param("domains", "domain.tld,future.tld") .param("hosts", "ns1.domain.tld")); cloudTasksHelper .getTestTasksFor("dns-publish") .forEach( task -> { - DateTime scheduledTime = - new DateTime(task.getScheduleTime().getSeconds() * 1000, DateTimeZone.UTC); - assertThat(new Duration(clock.nowUtc(), scheduledTime)) - .isAtMost(Duration.standardSeconds(jitterSeconds.get())); + Instant scheduledTime = Instant.ofEpochSecond(task.getScheduleTime().getSeconds()); + assertThat(Duration.between(clock.now(), scheduledTime)) + .isAtMost(Duration.ofSeconds(jitterSeconds.get())); }); } } diff --git a/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java b/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java index eb1b9e4e5..509e1cf40 100644 --- a/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java +++ b/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java @@ -33,7 +33,7 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; import google.registry.testing.FakeResponse; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -41,7 +41,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link RefreshDnsOnHostRenameAction}. */ public class RefreshDnsOnHostRenameActionTest { - private final FakeClock clock = new FakeClock(DateTime.parse("2015-01-15T11:22:33Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2015-01-15T11:22:33Z")); private final FakeResponse response = new FakeResponse(); @RegisterExtension diff --git a/core/src/test/java/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java b/core/src/test/java/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java index dbcf4b59a..b633b007d 100644 --- a/core/src/test/java/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java +++ b/core/src/test/java/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java @@ -54,7 +54,6 @@ import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -120,18 +119,18 @@ public class CloudDnsWriterTest { persistResource( Tld.get("tld") .asBuilder() - .setDnsAPlusAaaaTtl(Duration.standardSeconds(11)) - .setDnsNsTtl(Duration.standardSeconds(222)) - .setDnsDsTtl(Duration.standardSeconds(3333)) + .setDnsAPlusAaaaTtl(org.joda.time.Duration.standardSeconds(11)) + .setDnsNsTtl(org.joda.time.Duration.standardSeconds(222)) + .setDnsDsTtl(org.joda.time.Duration.standardSeconds(3333)) .build()); writer = new CloudDnsWriter( dnsConnection, "projectId", "triple.secret.tld", // used by testInvalidZoneNames() - Duration.ZERO, - Duration.ZERO, - Duration.ZERO, + java.time.Duration.ZERO, + java.time.Duration.ZERO, + java.time.Duration.ZERO, RateLimiter.create(20), 10, // max num threads new SystemClock(), @@ -402,9 +401,9 @@ public class CloudDnsWriterTest { dnsConnection, "projectId", "triple.secret.tld", - Duration.standardSeconds(11), - Duration.standardSeconds(222), - Duration.standardSeconds(3333), + java.time.Duration.ofSeconds(11), + java.time.Duration.ofSeconds(222), + java.time.Duration.ofSeconds(3333), RateLimiter.create(20), 10, new SystemClock(), diff --git a/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java b/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java index a5c1b377d..78bf6f440 100644 --- a/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java +++ b/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java @@ -30,9 +30,9 @@ import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; +import java.time.Duration; import java.util.Arrays; import javax.net.SocketFactory; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -121,11 +121,11 @@ class DnsMessageTransportTest { when(mockSocket.getInputStream()).thenReturn(mockInputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); - Duration testTimeout = Duration.standardSeconds(1); + Duration testTimeout = Duration.ofSeconds(1); DnsMessageTransport resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, testTimeout); Message expectedQuery = new Message(); assertThrows(SocketTimeoutException.class, () -> resolver.send(expectedQuery)); - verify(mockSocket).setSoTimeout((int) testTimeout.getMillis()); + verify(mockSocket).setSoTimeout((int) testTimeout.toMillis()); } @Test diff --git a/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java b/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java index 087f7f0bd..b5164872c 100644 --- a/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java +++ b/core/src/test/java/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java @@ -44,10 +44,10 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.DatabaseHelper; import google.registry.testing.FakeClock; +import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.joda.time.DateTime; import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -83,7 +83,7 @@ public class DnsUpdateWriterTest { @Mock private DnsMessageTransport mockResolver; @Captor private ArgumentCaptor updateCaptor; - private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("1971-01-01T00:00:00Z")); private DnsUpdateWriter writer; @@ -92,8 +92,14 @@ public class DnsUpdateWriterTest { createTld("tld"); when(mockResolver.send(any(Update.class))).thenReturn(messageWithResponseCode(Rcode.NOERROR)); - writer = new DnsUpdateWriter( - "tld", Duration.ZERO, Duration.ZERO, Duration.ZERO, mockResolver, clock); + writer = + new DnsUpdateWriter( + "tld", + java.time.Duration.ZERO, + java.time.Duration.ZERO, + java.time.Duration.ZERO, + mockResolver, + clock); } @Test diff --git a/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java b/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java index 2a905ca4e..8aa746d09 100644 --- a/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java +++ b/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java @@ -22,7 +22,6 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistDeletedDomain; import static google.registry.testing.DatabaseHelper.persistResource; -import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.plusDays; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -49,6 +48,8 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.storage.drive.DriveConnection; import google.registry.testing.FakeClock; +import google.registry.util.DateTimeUtils; +import java.time.Instant; import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -62,7 +63,7 @@ class ExportDomainListsActionTest { private final DriveConnection driveConnection = mock(DriveConnection.class); private final ArgumentCaptor bytesExportedToDrive = ArgumentCaptor.forClass(byte[].class); private ExportDomainListsAction action; - private final FakeClock clock = new FakeClock(DateTime.parse("2020-02-02T02:02:02Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2020-02-02T02:02:02Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -192,7 +193,7 @@ class ExportDomainListsActionTest { verifyExportedToDrive( "brouhaha", "registered_domains_tld.txt", - "active.tld,\npendingdelete.tld,2020-02-05T02:02:02.000Z\nredemption.tld,"); + "active.tld,\npendingdelete.tld,2020-02-05T02:02:02Z\nredemption.tld,"); } @Test @@ -261,7 +262,7 @@ class ExportDomainListsActionTest { new FeatureFlag() .asBuilder() .setFeatureName(INCLUDE_PENDING_DELETE_DATE_FOR_DOMAINS) - .setStatusMap(ImmutableSortedMap.of(START_OF_TIME, status)) + .setStatusMap(ImmutableSortedMap.of(DateTimeUtils.START_OF_TIME, status)) .build()); } } diff --git a/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetActionTest.java b/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetActionTest.java index e97c426ad..501a9ebb2 100644 --- a/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetActionTest.java +++ b/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetActionTest.java @@ -25,9 +25,9 @@ import static org.mockito.Mockito.when; import google.registry.testing.FakeLockHandler; import google.registry.testing.FakeResponse; +import java.time.Duration; import java.util.Optional; import javax.annotation.Nullable; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -50,7 +50,7 @@ public class SyncRegistrarsSheetActionTest { action = new SyncRegistrarsSheetAction(); action.response = response; action.syncRegistrarsSheet = syncRegistrarsSheet; - action.timeout = Duration.standardHours(1); + action.timeout = Duration.ofHours(1); action.lockHandler = new FakeLockHandler(true); } diff --git a/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java b/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java index faf517761..b9de16b6c 100644 --- a/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java +++ b/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java @@ -28,7 +28,6 @@ import static google.registry.util.DateTimeUtils.minusHours; import static google.registry.util.DateTimeUtils.plusHours; import static org.joda.money.CurrencyUnit.JPY; import static org.joda.money.CurrencyUnit.USD; -import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.Duration.standardMinutes; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; @@ -45,7 +44,6 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.DatabaseHelper; import google.registry.testing.FakeClock; import java.time.Instant; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -59,15 +57,15 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class SyncRegistrarsSheetTest { + private final FakeClock clock = new FakeClock(Instant.parse("2024-01-01T00:00:00Z")); + @RegisterExtension final JpaIntegrationTestExtension jpa = - new JpaTestExtensions.Builder().buildIntegrationTestExtension(); + new JpaTestExtensions.Builder().withClock(clock).buildIntegrationTestExtension(); @Captor private ArgumentCaptor>> rowsCaptor; @Mock private SheetSynchronizer sheetSynchronizer; - private final FakeClock clock = new FakeClock(DateTime.now(UTC)); - private SyncRegistrarsSheet newSyncRegistrarsSheet() { SyncRegistrarsSheet result = new SyncRegistrarsSheet(); result.clock = clock; @@ -318,7 +316,7 @@ public class SyncRegistrarsSheetTest { Cursor cursor = loadByKey(Cursor.createGlobalVKey(SYNC_REGISTRAR_SHEET)); assertThat(cursor).isNotNull(); - assertThat(cursor.getCursorTimeInstant()).isGreaterThan(registrarCreationTime); + assertThat(cursor.getCursorTime()).isGreaterThan(registrarCreationTime); } @Test diff --git a/core/src/test/java/google/registry/model/CreateAutoTimestampTest.java b/core/src/test/java/google/registry/model/CreateAutoTimestampTest.java index d6fda01b4..39538a75b 100644 --- a/core/src/test/java/google/registry/model/CreateAutoTimestampTest.java +++ b/core/src/test/java/google/registry/model/CreateAutoTimestampTest.java @@ -67,7 +67,7 @@ public class CreateAutoTimestampTest { @Test void testResavingRespectsOriginalTime() { - final Instant oldCreateTime = minusDays(clock.now(), 1); + Instant oldCreateTime = minusDays(clock.now(), 1); tm().transact( () -> { CreateAutoTimestampTestObject object = new CreateAutoTimestampTestObject(); diff --git a/core/src/test/java/google/registry/model/EntityTestCase.java b/core/src/test/java/google/registry/model/EntityTestCase.java index 2f2852766..8ea9acf61 100644 --- a/core/src/test/java/google/registry/model/EntityTestCase.java +++ b/core/src/test/java/google/registry/model/EntityTestCase.java @@ -13,7 +13,6 @@ // limitations under the License. package google.registry.model; - import static org.joda.time.DateTimeZone.UTC; import google.registry.persistence.transaction.JpaEntityCoverageExtension; diff --git a/core/src/test/java/google/registry/model/common/CursorTest.java b/core/src/test/java/google/registry/model/common/CursorTest.java index b1f20747e..c2306aff1 100644 --- a/core/src/test/java/google/registry/model/common/CursorTest.java +++ b/core/src/test/java/google/registry/model/common/CursorTest.java @@ -20,14 +20,13 @@ import static google.registry.model.common.Cursor.CursorType.RDE_UPLOAD; import static google.registry.model.common.Cursor.CursorType.RECURRING_BILLING; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.createTld; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.junit.jupiter.api.Assertions.assertThrows; import google.registry.model.EntityTestCase; import google.registry.model.tld.Tld; import google.registry.util.SerializeUtils; import java.time.Instant; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,12 +39,13 @@ public class CursorTest extends EntityTestCase { @BeforeEach void setUp() { - fakeClock.setTo(DateTime.parse("2010-10-17TZ")); + createTld("tld"); + fakeClock.setTo(Instant.parse("2010-10-17T00:00:00Z")); } @Test void testSerializable() { - final DateTime time = DateTime.parse("2012-07-12T03:30:00.000Z"); + Instant time = Instant.parse("2012-07-12T03:30:00.000Z"); tm().transact(() -> tm().put(Cursor.createGlobal(RECURRING_BILLING, time))); Cursor persisted = tm().transact(() -> tm().loadByKey(Cursor.createGlobalVKey(RECURRING_BILLING))); @@ -54,9 +54,9 @@ public class CursorTest extends EntityTestCase { @Test void testSuccess_persistScopedCursor() { - Tld tld = createTld("tld"); + Tld tld = Tld.get("tld"); this.fakeClock.advanceOneMilli(); - final DateTime time = DateTime.parse("2012-07-12T03:30:00.000Z"); + Instant time = Instant.parse("2012-07-12T03:30:00.000Z"); Cursor cursor = Cursor.createScoped(RDE_UPLOAD, time, tld); tm().transact(() -> tm().put(cursor)); tm().transact( @@ -70,7 +70,7 @@ public class CursorTest extends EntityTestCase { @Test void testSuccess_persistGlobalCursor() { - final DateTime time = DateTime.parse("2012-07-12T03:30:00.000Z"); + Instant time = Instant.parse("2012-07-12T03:30:00.000Z"); Cursor cursor = Cursor.createGlobal(RECURRING_BILLING, time); tm().transact(() -> tm().put(cursor)); assertThat(tm().transact(() -> tm().loadByKey(cursor.createVKey())).getCursorTime()) @@ -79,7 +79,7 @@ public class CursorTest extends EntityTestCase { @Test void testFailure_VKeyWrongScope() { - Tld tld = createTld("tld"); + Tld tld = Tld.get("tld"); assertThrows( IllegalArgumentException.class, () -> Cursor.createGlobalVKey(RDE_UPLOAD), @@ -97,23 +97,21 @@ public class CursorTest extends EntityTestCase { NullPointerException thrown = assertThrows( NullPointerException.class, - () -> Cursor.createScoped(RECURRING_BILLING, START_OF_TIME, null)); + () -> Cursor.createScoped(RECURRING_BILLING, START_INSTANT, null)); assertThat(thrown).hasMessageThat().contains("Cursor scope cannot be null"); } @Test void testFailure_nullCursorType() { - createTld("tld"); NullPointerException thrown = assertThrows( NullPointerException.class, - () -> Cursor.createScoped(null, START_OF_TIME, Tld.get("tld"))); + () -> Cursor.createScoped(null, START_INSTANT, Tld.get("tld"))); assertThat(thrown).hasMessageThat().contains("Cursor type cannot be null"); } @Test void testFailure_nullTime() { - createTld("tld"); NullPointerException thrown = assertThrows( NullPointerException.class, diff --git a/core/src/test/java/google/registry/model/common/DnsRefreshRequestTest.java b/core/src/test/java/google/registry/model/common/DnsRefreshRequestTest.java index b6b1eafb1..8a7791aa7 100644 --- a/core/src/test/java/google/registry/model/common/DnsRefreshRequestTest.java +++ b/core/src/test/java/google/registry/model/common/DnsRefreshRequestTest.java @@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.loadAllOf; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableList; @@ -34,12 +34,11 @@ public class DnsRefreshRequestTest extends EntityTestCase { } private final DnsRefreshRequest request = - new DnsRefreshRequest( - DnsUtils.TargetType.DOMAIN, "test.example", "example", fakeClock.nowUtc()); + new DnsRefreshRequest(DnsUtils.TargetType.DOMAIN, "test.example", "example", fakeClock.now()); @Test void testPersistence() { - assertThat(request.getLastProcessTime()).isEqualTo(START_OF_TIME); + assertThat(request.getLastProcessTime()).isEqualTo(START_INSTANT); fakeClock.advanceOneMilli(); tm().transact(() -> tm().insert(request)); fakeClock.advanceOneMilli(); @@ -53,18 +52,17 @@ public class DnsRefreshRequestTest extends EntityTestCase { // type assertThrows( NullPointerException.class, - () -> new DnsRefreshRequest(null, "test.example", "example", fakeClock.nowUtc())); + () -> new DnsRefreshRequest(null, "test.example", "example", fakeClock.now())); // name assertThrows( NullPointerException.class, - () -> - new DnsRefreshRequest(DnsUtils.TargetType.DOMAIN, null, "example", fakeClock.nowUtc())); + () -> new DnsRefreshRequest(DnsUtils.TargetType.DOMAIN, null, "example", fakeClock.now())); // tld assertThrows( NullPointerException.class, () -> new DnsRefreshRequest( - DnsUtils.TargetType.DOMAIN, "test.example", null, fakeClock.nowUtc())); + DnsUtils.TargetType.DOMAIN, "test.example", null, fakeClock.now())); // request time assertThrows( NullPointerException.class, @@ -75,22 +73,21 @@ public class DnsRefreshRequestTest extends EntityTestCase { void testUpdateProcessTime() { assertThat( assertThrows( - IllegalArgumentException.class, - () -> request.updateProcessTime(fakeClock.nowUtc()))) + IllegalArgumentException.class, () -> request.updateProcessTime(fakeClock.now()))) .hasMessageThat() .contains("must be later than request time"); fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli(); - DnsRefreshRequest newRequest = request.updateProcessTime(fakeClock.nowUtc()); + DnsRefreshRequest newRequest = request.updateProcessTime(fakeClock.now()); assertAboutImmutableObjects().that(newRequest).isEqualExceptFields(request, "lastProcessTime"); - assertThat(newRequest.getLastProcessTime()).isEqualTo(fakeClock.nowUtc()); + assertThat(newRequest.getLastProcessTime()).isEqualTo(fakeClock.now()); assertThat( assertThrows( IllegalArgumentException.class, - () -> newRequest.updateProcessTime(fakeClock.nowUtc().minusMillis(1)))) + () -> newRequest.updateProcessTime(fakeClock.now().minusMillis(1)))) .hasMessageThat() .contains("must be later than the old one"); } diff --git a/core/src/test/java/google/registry/model/domain/DomainTest.java b/core/src/test/java/google/registry/model/domain/DomainTest.java index 2f4a3d5ea..089915796 100644 --- a/core/src/test/java/google/registry/model/domain/DomainTest.java +++ b/core/src/test/java/google/registry/model/domain/DomainTest.java @@ -35,8 +35,8 @@ import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusDays; import static google.registry.util.DateTimeUtils.plusYears; import static google.registry.util.DateTimeUtils.toInstant; +import static java.time.ZoneOffset.UTC; import static org.joda.money.CurrencyUnit.USD; -import static org.joda.time.DateTimeZone.UTC; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableList; @@ -73,10 +73,10 @@ import google.registry.testing.DatabaseHelper; import google.registry.testing.FakeClock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneOffset; import java.util.Optional; import org.joda.money.Money; import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -85,7 +85,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; @SuppressWarnings("WeakerAccess") // Referred to by EppInputTest. public class DomainTest { - protected FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); + protected FakeClock fakeClock = new FakeClock(DateTime.now(DateTimeZone.UTC)); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = @@ -673,8 +673,7 @@ public class DomainTest { .build(); Domain renewed = domain.cloneProjectedAtTime(plusYears(domain.getRegistrationExpirationTime(), 4)); - assertThat(renewed.getRegistrationExpirationTime().atZone(ZoneOffset.UTC).getDayOfMonth()) - .isEqualTo(28); + assertThat(renewed.getRegistrationExpirationTime().atZone(UTC).getDayOfMonth()).isEqualTo(28); } @Test @@ -739,7 +738,7 @@ public class DomainTest { @Test void testClone_doNotExtendExpirationOnDeletedDomain() { - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); domain = persistResource( domain @@ -755,7 +754,7 @@ public class DomainTest { @Test void testClone_doNotExtendExpirationOnFutureDeletedDomain() { // if a domain is in pending deletion (StatusValue.PENDING_DELETE), don't extend expiration - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); domain = persistResource( domain @@ -771,7 +770,7 @@ public class DomainTest { @Test void testClone_extendsExpirationForExpiredTransferredDomain() { // If the transfer implicitly succeeded, the expiration time should be extended - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); DateTime transferExpirationTime = now.minusDays(1); DateTime previousExpiration = now.minusDays(2); @@ -799,7 +798,7 @@ public class DomainTest { void testClone_extendsExpirationForNonExpiredTransferredDomain() { // If the transfer implicitly succeeded, the expiration time should be extended even if it // hadn't already expired - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); DateTime transferExpirationTime = now.minusDays(1); DateTime previousExpiration = now.plusWeeks(2); @@ -827,7 +826,7 @@ public class DomainTest { void testClone_removesBulkTokenFromTransferredDomain() { // If the transfer implicitly succeeded, the expiration time should be extended even if it // hadn't already expired - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); DateTime transferExpirationTime = now.minusDays(1); DateTime previousExpiration = now.plusWeeks(2); @@ -868,7 +867,7 @@ public class DomainTest { @Test void testClone_doesNotExtendExpirationForPendingTransfer() { // Pending transfers shouldn't affect the expiration time - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); DateTime transferExpirationTime = now.plusDays(1); DateTime previousExpiration = now.plusWeeks(2); @@ -893,7 +892,7 @@ public class DomainTest { @Test void testClone_doesNotRemoveBulkTokenForPendingTransfer() { // Pending transfers shouldn't affect the expiration time - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); DateTime transferExpirationTime = now.plusDays(1); DateTime previousExpiration = now.plusWeeks(2); @@ -933,7 +932,7 @@ public class DomainTest { void testClone_transferDuringAutorenew() { // When the domain is an autorenew grace period, we should not extend the registration // expiration by a further year--it should just be whatever the autorenew was - DateTime now = DateTime.now(UTC); + DateTime now = DateTime.now(DateTimeZone.UTC); DateTime transferExpirationTime = now.minusDays(1); DateTime previousExpiration = now.minusDays(2); diff --git a/core/src/test/java/google/registry/model/domain/GracePeriodTest.java b/core/src/test/java/google/registry/model/domain/GracePeriodTest.java index 1b3a17a5f..d64a90785 100644 --- a/core/src/test/java/google/registry/model/domain/GracePeriodTest.java +++ b/core/src/test/java/google/registry/model/domain/GracePeriodTest.java @@ -15,6 +15,7 @@ package google.registry.model.domain; import static com.google.common.truth.Truth.assertThat; +import static java.time.temporal.ChronoUnit.DAYS; import static org.junit.jupiter.api.Assertions.assertThrows; import google.registry.model.billing.BillingBase.Reason; @@ -27,7 +28,6 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; import java.time.Instant; -import java.time.temporal.ChronoUnit; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.junit.jupiter.api.BeforeEach; @@ -52,7 +52,7 @@ public class GracePeriodTest { onetime = new BillingEvent.Builder() .setEventTime(now) - .setBillingTime(now.plus(1, ChronoUnit.DAYS)) + .setBillingTime(now.plus(1, DAYS)) .setRegistrarId("TheRegistrar") .setCost(Money.of(CurrencyUnit.USD, 42)) .setDomainHistoryId(new HistoryEntryId("domain", 12345)) @@ -71,7 +71,7 @@ public class GracePeriodTest { assertThat(gracePeriod.getBillingEvent()).isEqualTo(onetime.createVKey()); assertThat(gracePeriod.getBillingRecurrence()).isNull(); assertThat(gracePeriod.getRegistrarId()).isEqualTo("TheRegistrar"); - assertThat(gracePeriod.getExpirationTime()).isEqualTo(now.plus(1, ChronoUnit.DAYS)); + assertThat(gracePeriod.getExpirationTime()).isEqualTo(now.plus(1, DAYS)); assertThat(gracePeriod.hasBillingEvent()).isTrue(); } @@ -81,7 +81,7 @@ public class GracePeriodTest { GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, "1-TEST", - now.plus(1, ChronoUnit.DAYS), + now.plus(1, DAYS), "TheRegistrar", recurrenceKey); assertThat(gracePeriod.getType()).isEqualTo(GracePeriodStatus.AUTO_RENEW); @@ -89,7 +89,7 @@ public class GracePeriodTest { assertThat(gracePeriod.getBillingEvent()).isNull(); assertThat(gracePeriod.getBillingRecurrence()).isEqualTo(recurrenceKey); assertThat(gracePeriod.getRegistrarId()).isEqualTo("TheRegistrar"); - assertThat(gracePeriod.getExpirationTime()).isEqualTo(now.plus(1, ChronoUnit.DAYS)); + assertThat(gracePeriod.getExpirationTime()).isEqualTo(now.plus(1, DAYS)); assertThat(gracePeriod.hasBillingEvent()).isTrue(); } @@ -125,7 +125,7 @@ public class GracePeriodTest { GracePeriod.createForRecurrence( GracePeriodStatus.RENEW, "1-TEST", - now.plus(1, ChronoUnit.DAYS), + now.plus(1, DAYS), "TheRegistrar", recurrenceKey)); assertThat(thrown).hasMessageThat().contains("autorenew"); diff --git a/core/src/test/java/google/registry/model/rde/RdeNamingUtilsTest.java b/core/src/test/java/google/registry/model/rde/RdeNamingUtilsTest.java index cc2f2f2a9..a0bd0fdde 100644 --- a/core/src/test/java/google/registry/model/rde/RdeNamingUtilsTest.java +++ b/core/src/test/java/google/registry/model/rde/RdeNamingUtilsTest.java @@ -21,7 +21,7 @@ import static google.registry.model.rde.RdeNamingUtils.makePartialName; import static google.registry.model.rde.RdeNamingUtils.makeRydeFilename; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; /** Unit tests for {@link RdeNamingUtils}. */ @@ -29,19 +29,19 @@ class RdeNamingUtilsTest { @Test void testMakeRydeFilename_rdeDeposit() { - assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0)) + assertThat(makeRydeFilename("numbness", Instant.parse("1984-12-18T00:00:00Z"), FULL, 1, 0)) .isEqualTo("numbness_1984-12-18_full_S1_R0"); } @Test void testMakeRydeFilename_brdaDeposit() { - assertThat(makeRydeFilename("dreary", DateTime.parse("2000-12-18TZ"), THIN, 1, 0)) + assertThat(makeRydeFilename("dreary", Instant.parse("2000-12-18T00:00:00Z"), THIN, 1, 0)) .isEqualTo("dreary_2000-12-18_thin_S1_R0"); } @Test void testMakeRydeFilename_revisionNumber() { - assertThat(makeRydeFilename("wretched", DateTime.parse("2000-12-18TZ"), THIN, 1, 123)) + assertThat(makeRydeFilename("wretched", Instant.parse("2000-12-18T00:00:00Z"), THIN, 1, 123)) .isEqualTo("wretched_2000-12-18_thin_S1_R123"); } @@ -49,12 +49,12 @@ class RdeNamingUtilsTest { void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() { assertThrows( IllegalArgumentException.class, - () -> makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0)); + () -> makeRydeFilename("wretched", Instant.parse("2000-12-18T04:20:00Z"), THIN, 1, 0)); } @Test void testMakePartialName() { - assertThat(makePartialName("unholy", DateTime.parse("2000-12-18TZ"), THIN)) + assertThat(makePartialName("unholy", Instant.parse("2000-12-18T00:00:00Z"), THIN)) .isEqualTo("unholy_2000-12-18_thin"); } } diff --git a/core/src/test/java/google/registry/model/rde/RdeRevisionTest.java b/core/src/test/java/google/registry/model/rde/RdeRevisionTest.java index 0e6d674fa..70d70c895 100644 --- a/core/src/test/java/google/registry/model/rde/RdeRevisionTest.java +++ b/core/src/test/java/google/registry/model/rde/RdeRevisionTest.java @@ -19,10 +19,12 @@ import static google.registry.model.rde.RdeMode.FULL; import static google.registry.model.rde.RdeRevision.getNextRevision; import static google.registry.model.rde.RdeRevision.saveRevision; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static google.registry.util.DateTimeUtils.toJodaLocalDate; +import static java.time.temporal.ChronoUnit.DAYS; import static org.junit.jupiter.api.Assertions.assertThrows; import google.registry.model.EntityTestCase; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,28 +37,25 @@ public class RdeRevisionTest extends EntityTestCase { @BeforeEach void beforeEach() { - fakeClock.setTo(DateTime.parse("1984-12-18TZ")); + fakeClock.setTo(Instant.parse("1984-12-18T00:00:00Z")); } @Test void testGetNextRevision_objectDoesntExist_returnsZero() { - tm().transact( - () -> assertThat(getNextRevision("torment", fakeClock.nowUtc(), FULL)).isEqualTo(0)); + tm().transact(() -> assertThat(getNextRevision("torment", fakeClock.now(), FULL)).isEqualTo(0)); } @Test void testGetNextRevision_objectExistsAtZero_returnsOne() { - save("sorrow", fakeClock.nowUtc(), FULL, 0); - tm().transact( - () -> assertThat(getNextRevision("sorrow", fakeClock.nowUtc(), FULL)).isEqualTo(1)); + save("sorrow", fakeClock.now(), FULL, 0); + tm().transact(() -> assertThat(getNextRevision("sorrow", fakeClock.now(), FULL)).isEqualTo(1)); } @Test void testSaveRevision_objectDoesntExist_newRevisionIsZero_nextRevIsOne() { - tm().transact(() -> saveRevision("despondency", fakeClock.nowUtc(), FULL, 0)); + tm().transact(() -> saveRevision("despondency", fakeClock.now(), FULL, 0)); tm().transact( - () -> - assertThat(getNextRevision("despondency", fakeClock.nowUtc(), FULL)).isEqualTo(1)); + () -> assertThat(getNextRevision("despondency", fakeClock.now(), FULL)).isEqualTo(1)); } @Test @@ -64,7 +63,7 @@ public class RdeRevisionTest extends EntityTestCase { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, - () -> tm().transact(() -> saveRevision("despondency", fakeClock.nowUtc(), FULL, 1))); + () -> tm().transact(() -> saveRevision("despondency", fakeClock.now(), FULL, 1))); assertThat(thrown) .hasMessageThat() .isEqualTo( @@ -74,17 +73,17 @@ public class RdeRevisionTest extends EntityTestCase { @Test void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() { - save("melancholy", fakeClock.nowUtc(), FULL, 0); + save("melancholy", fakeClock.now(), FULL, 0); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, - () -> tm().transact(() -> saveRevision("melancholy", fakeClock.nowUtc(), FULL, 0))); + () -> tm().transact(() -> saveRevision("melancholy", fakeClock.now(), FULL, 0))); assertThat(thrown).hasMessageThat().contains("object already created"); } @Test void testSaveRevision_objectExistsAtZero_newRevisionIsOne_nextRevIsTwo() { - DateTime startOfDay = fakeClock.nowUtc().withTimeAtStartOfDay(); + Instant startOfDay = fakeClock.now().truncatedTo(DAYS); save("melancholy", startOfDay, FULL, 0); fakeClock.advanceOneMilli(); tm().transact(() -> saveRevision("melancholy", startOfDay, FULL, 1)); @@ -93,11 +92,11 @@ public class RdeRevisionTest extends EntityTestCase { @Test void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() { - save("melancholy", fakeClock.nowUtc(), FULL, 0); + save("melancholy", fakeClock.now(), FULL, 0); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, - () -> tm().transact(() -> saveRevision("melancholy", fakeClock.nowUtc(), FULL, 2))); + () -> tm().transact(() -> saveRevision("melancholy", fakeClock.now(), FULL, 2))); assertThat(thrown) .hasMessageThat() .contains("RDE revision object should be at revision 1 but was"); @@ -108,7 +107,7 @@ public class RdeRevisionTest extends EntityTestCase { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, - () -> tm().transact(() -> saveRevision("melancholy", fakeClock.nowUtc(), FULL, -1))); + () -> tm().transact(() -> saveRevision("melancholy", fakeClock.now(), FULL, -1))); assertThat(thrown).hasMessageThat().contains("Negative revision"); } @@ -116,12 +115,12 @@ public class RdeRevisionTest extends EntityTestCase { void testSaveRevision_callerNotInTransaction_throwsIse() { IllegalStateException thrown = assertThrows( - IllegalStateException.class, () -> saveRevision("frenzy", fakeClock.nowUtc(), FULL, 1)); + IllegalStateException.class, () -> saveRevision("frenzy", fakeClock.now(), FULL, 1)); assertThat(thrown).hasMessageThat().contains("transaction"); } - public static void save(String tld, DateTime date, RdeMode mode, int revision) { - RdeRevision object = RdeRevision.create(tld, date.toLocalDate(), mode, revision); + public static void save(String tld, Instant date, RdeMode mode, int revision) { + RdeRevision object = RdeRevision.create(tld, toJodaLocalDate(date), mode, revision); tm().transact(() -> tm().put(object)); } } diff --git a/core/src/test/java/google/registry/model/server/LockTest.java b/core/src/test/java/google/registry/model/server/LockTest.java index 2bc40f0f8..9332bef52 100644 --- a/core/src/test/java/google/registry/model/server/LockTest.java +++ b/core/src/test/java/google/registry/model/server/LockTest.java @@ -25,8 +25,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import google.registry.model.EntityTestCase; import google.registry.model.server.Lock.LockState; +import java.time.Duration; import java.util.Optional; -import org.joda.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,8 +35,8 @@ import org.junit.jupiter.api.Test; public class LockTest extends EntityTestCase { private static final String RESOURCE_NAME = "foo"; - private static final Duration ONE_DAY = Duration.standardDays(1); - private static final Duration TWO_MILLIS = Duration.millis(2); + private static final Duration ONE_DAY = Duration.ofDays(1); + private static final Duration TWO_MILLIS = Duration.ofMillis(2); private LockMetrics origLockMetrics; @@ -58,7 +58,7 @@ public class LockTest extends EntityTestCase { Lock.lockMetrics = mock(LockMetrics.class); lock.release(); verify(Lock.lockMetrics) - .recordRelease(RESOURCE_NAME, expectedTld, Duration.millis(expectedMillis)); + .recordRelease(RESOURCE_NAME, expectedTld, Duration.ofMillis(expectedMillis)); verifyNoMoreInteractions(Lock.lockMetrics); Lock.lockMetrics = null; } @@ -81,7 +81,7 @@ public class LockTest extends EntityTestCase { // We can't get it again at the same time. assertThat(acquire("", ONE_DAY, IN_USE)).isEmpty(); // But if we release it, it's available. - fakeClock.advanceBy(Duration.millis(123)); + fakeClock.advanceBy(Duration.ofMillis(123)); release(lock.get(), "", 123); assertThat(acquire("", ONE_DAY, FREE)).isPresent(); } diff --git a/core/src/test/java/google/registry/mosapi/module/MosApiModuleTest.java b/core/src/test/java/google/registry/mosapi/module/MosApiModuleTest.java index 995495eab..5804dcdbe 100644 --- a/core/src/test/java/google/registry/mosapi/module/MosApiModuleTest.java +++ b/core/src/test/java/google/registry/mosapi/module/MosApiModuleTest.java @@ -16,6 +16,7 @@ package google.registry.mosapi.module; import static com.google.common.truth.Truth.assertThat; import static google.registry.util.DateTimeUtils.plusYears; +import static java.time.ZoneOffset.UTC; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -34,7 +35,6 @@ import java.security.Security; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.time.Instant; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Optional; import javax.net.ssl.SSLContext; @@ -154,8 +154,7 @@ public class MosApiModuleTest { keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); this.generatedPrivateKey = keyPair.getPrivate(); - DateTimeFormatter formatter = - DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'").withZone(ZoneOffset.UTC); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'").withZone(UTC); Instant now = Instant.parse("2021-01-01T00:00:00Z"); Instant end = plusYears(now, 1); // Convert string to Bouncy Castle Time objects diff --git a/core/src/test/java/google/registry/rde/BrdaCopyActionTest.java b/core/src/test/java/google/registry/rde/BrdaCopyActionTest.java index a933fee25..5e167238d 100644 --- a/core/src/test/java/google/registry/rde/BrdaCopyActionTest.java +++ b/core/src/test/java/google/registry/rde/BrdaCopyActionTest.java @@ -22,6 +22,7 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.GpgSystemCommandExtension.GPG_BINARY; import static google.registry.testing.SystemInfo.hasCommand; +import static google.registry.util.DateTimeUtils.plusDays; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -47,11 +48,11 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.RegisterExtension; @@ -116,7 +117,7 @@ public class BrdaCopyActionTest { createTld("lol"); action.gcsUtils = gcsUtils; action.tld = "lol"; - action.watermark = DateTime.parse("2010-10-17TZ"); + action.watermark = Instant.parse("2010-10-17T00:00:00Z"); action.brdaBucket = "tub"; action.stagingBucket = "keg"; action.receiverKey = receiverKey; @@ -124,9 +125,10 @@ public class BrdaCopyActionTest { action.stagingDecryptionKey = decryptKey; tm().transact( () -> { - RdeRevision.saveRevision("lol", DateTime.parse("2010-10-17TZ"), RdeMode.THIN, 0); + RdeRevision.saveRevision( + "lol", Instant.parse("2010-10-17T00:00:00Z"), RdeMode.THIN, 0); }); - persistResource(Cursor.createScoped(BRDA, action.watermark.plusDays(1), Tld.get("lol"))); + persistResource(Cursor.createScoped(BRDA, plusDays(action.watermark, 1), Tld.get("lol"))); } @ParameterizedTest @@ -138,8 +140,8 @@ public class BrdaCopyActionTest { .hasMessageThat() .isEqualTo( "Waiting on RdeStagingAction for TLD lol to copy BRDA deposit for" - + " 2010-10-17T00:00:00.000Z to GCS; last BRDA staging completion was before" - + " 2010-10-17T00:00:00.000Z"); + + " 2010-10-17T00:00:00Z to GCS; last BRDA staging completion was before" + + " 2010-10-17T00:00:00Z"); } @ParameterizedTest diff --git a/core/src/test/java/google/registry/rde/DomainToXjcConverterTest.java b/core/src/test/java/google/registry/rde/DomainToXjcConverterTest.java index a7ee9967d..c00179437 100644 --- a/core/src/test/java/google/registry/rde/DomainToXjcConverterTest.java +++ b/core/src/test/java/google/registry/rde/DomainToXjcConverterTest.java @@ -85,7 +85,7 @@ public class DomainToXjcConverterTest { final JpaIntegrationTestExtension jpa = new JpaTestExtensions.Builder().buildIntegrationTestExtension(); - private final DateTime now = DateTime.parse("2014-01-01T00:00:00Z"); + private final Instant now = Instant.parse("2014-01-01T00:00:00Z"); private final FakeClock clock = new FakeClock(now); @BeforeEach @@ -207,7 +207,7 @@ public class DomainToXjcConverterTest { XjcRdeDeposit deposit = new XjcRdeDeposit(); deposit.setId("984302"); deposit.setType(XjcRdeDepositTypeType.FULL); - deposit.setWatermark(new DateTime("2012-01-01T04:20:00Z")); + deposit.setWatermark(DateTime.parse("2012-01-01T04:20:00Z")); XjcRdeMenuType menu = new XjcRdeMenuType(); menu.setVersion("1.0"); menu.getObjURIs().add("lol"); diff --git a/core/src/test/java/google/registry/rde/EscrowTaskRunnerTest.java b/core/src/test/java/google/registry/rde/EscrowTaskRunnerTest.java index 8fd7b34df..7dd353d84 100644 --- a/core/src/test/java/google/registry/rde/EscrowTaskRunnerTest.java +++ b/core/src/test/java/google/registry/rde/EscrowTaskRunnerTest.java @@ -18,8 +18,6 @@ import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.loadByKey; import static google.registry.testing.DatabaseHelper.persistResource; -import static org.joda.time.Duration.standardDays; -import static org.joda.time.Duration.standardSeconds; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -34,8 +32,9 @@ import google.registry.request.HttpException.NoContentException; import google.registry.request.HttpException.ServiceUnavailableException; import google.registry.testing.FakeClock; import google.registry.testing.FakeLockHandler; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,9 +48,9 @@ public class EscrowTaskRunnerTest { new JpaTestExtensions.Builder().buildIntegrationTestExtension(); private final EscrowTask task = mock(EscrowTask.class); - private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("2000-01-01T00:00:00Z")); - private DateTimeZone previousDateTimeZone; + private ZoneId previousDateTimeZone; private EscrowTaskRunner runner; private Tld registry; @@ -62,64 +61,77 @@ public class EscrowTaskRunnerTest { runner = new EscrowTaskRunner(); runner.clock = clock; runner.lockHandler = new FakeLockHandler(true); - previousDateTimeZone = DateTimeZone.getDefault(); - DateTimeZone.setDefault(DateTimeZone.forID("America/New_York")); // Make sure UTC stuff works. + previousDateTimeZone = ZoneId.systemDefault(); + // java.time.ZoneId does not have a global setDefault + System.setProperty("user.timezone", "America/New_York"); // Make sure UTC stuff works. } @AfterEach void afterEach() { - DateTimeZone.setDefault(previousDateTimeZone); + // Restore timezone + System.setProperty("user.timezone", previousDateTimeZone.getId()); } @Test void testRun_cursorIsToday_advancesCursorToTomorrow() throws Exception { - clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); + clock.setTo(Instant.parse("2006-06-06T00:30:00Z")); persistResource( - Cursor.createScoped(CursorType.RDE_STAGING, DateTime.parse("2006-06-06TZ"), registry)); + Cursor.createScoped( + CursorType.RDE_STAGING, Instant.parse("2006-06-06T00:00:00Z"), registry)); runner.lockRunAndRollForward( - task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); - verify(task).runWithLock(DateTime.parse("2006-06-06TZ")); + task, registry, Duration.ofSeconds(30), CursorType.RDE_STAGING, Duration.ofDays(1)); + verify(task).runWithLock(Instant.parse("2006-06-06T00:00:00Z")); Cursor cursor = loadByKey(Cursor.createScopedVKey(CursorType.RDE_STAGING, registry)); - assertThat(cursor.getCursorTime()).isEqualTo(DateTime.parse("2006-06-07TZ")); + assertThat(cursor.getCursorTime()).isEqualTo(Instant.parse("2006-06-07T00:00:00Z")); } @Test void testRun_cursorMissing_assumesTodayAndAdvancesCursorToTomorrow() throws Exception { - clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); + clock.setTo(Instant.parse("2006-06-06T00:30:00Z")); runner.lockRunAndRollForward( - task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); - verify(task).runWithLock(DateTime.parse("2006-06-06TZ")); + task, registry, Duration.ofSeconds(30), CursorType.RDE_STAGING, Duration.ofDays(1)); + verify(task).runWithLock(Instant.parse("2006-06-06T00:00:00Z")); Cursor cursor = loadByKey(Cursor.createScopedVKey(CursorType.RDE_STAGING, registry)); - assertThat(cursor.getCursorTime()).isEqualTo(DateTime.parse("2006-06-07TZ")); + assertThat(cursor.getCursorTime()).isEqualTo(Instant.parse("2006-06-07T00:00:00Z")); } @Test void testRun_cursorInTheFuture_doesNothing() { - clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); + clock.setTo(Instant.parse("2006-06-06T00:30:00Z")); persistResource( - Cursor.createScoped(CursorType.RDE_STAGING, DateTime.parse("2006-06-07TZ"), registry)); + Cursor.createScoped( + CursorType.RDE_STAGING, Instant.parse("2006-06-07T00:00:00Z"), registry)); NoContentException thrown = assertThrows( NoContentException.class, () -> runner.lockRunAndRollForward( - task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1))); + task, + registry, + Duration.ofSeconds(30), + CursorType.RDE_STAGING, + Duration.ofDays(1))); assertThat(thrown).hasMessageThat().contains("Already completed"); } @Test void testRun_lockIsntAvailable_throws503() { String lockName = "EscrowTaskRunner " + task.getClass().getSimpleName(); - clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); + clock.setTo(Instant.parse("2006-06-06T00:30:00Z")); persistResource( - Cursor.createScoped(CursorType.RDE_STAGING, DateTime.parse("2006-06-06TZ"), registry)); + Cursor.createScoped( + CursorType.RDE_STAGING, Instant.parse("2006-06-06T00:00:00Z"), registry)); runner.lockHandler = new FakeLockHandler(false); ServiceUnavailableException thrown = assertThrows( ServiceUnavailableException.class, () -> runner.lockRunAndRollForward( - task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1))); + task, + registry, + Duration.ofSeconds(30), + CursorType.RDE_STAGING, + Duration.ofDays(1))); assertThat(thrown).hasMessageThat().contains("Lock in use: " + lockName + " for TLD: lol"); } } diff --git a/core/src/test/java/google/registry/rde/PendingDepositCheckerTest.java b/core/src/test/java/google/registry/rde/PendingDepositCheckerTest.java index 702c0fa0c..30dd36849 100644 --- a/core/src/test/java/google/registry/rde/PendingDepositCheckerTest.java +++ b/core/src/test/java/google/registry/rde/PendingDepositCheckerTest.java @@ -25,7 +25,6 @@ import static google.registry.testing.DatabaseHelper.loadByKey; import static google.registry.testing.DatabaseHelper.loadByKeyIfPresent; import static google.registry.testing.DatabaseHelper.persistResource; import static org.joda.time.DateTimeConstants.TUESDAY; -import static org.joda.time.Duration.standardDays; import com.google.common.collect.ImmutableSetMultimap; import google.registry.model.common.Cursor; @@ -34,7 +33,8 @@ import google.registry.model.tld.Tld; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; -import org.joda.time.DateTime; +import java.time.Duration; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -52,9 +52,9 @@ public class PendingDepositCheckerTest { @BeforeEach void beforeEach() { checker.brdaDayOfWeek = TUESDAY; - checker.brdaInterval = standardDays(7); + checker.brdaInterval = Duration.ofDays(7); checker.clock = clock; - checker.rdeInterval = standardDays(1); + checker.rdeInterval = Duration.ofDays(1); } @Test @@ -66,46 +66,63 @@ public class PendingDepositCheckerTest { @Test void testMethod_firstDeposit_depositsRdeTodayAtMidnight() { - clock.setTo(DateTime.parse("2000-01-01T08:00Z")); // Saturday + clock.setTo(Instant.parse("2000-01-01T08:00:00Z")); // Saturday createTldWithEscrowEnabled("lol"); clock.advanceOneMilli(); - assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()).isEqualTo( - ImmutableSetMultimap.of( - "lol", PendingDeposit.create( - "lol", DateTime.parse("2000-01-01TZ"), FULL, RDE_STAGING, standardDays(1)))); + assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()) + .isEqualTo( + ImmutableSetMultimap.of( + "lol", + PendingDeposit.create( + "lol", + Instant.parse("2000-01-01T00:00:00Z"), + FULL, + RDE_STAGING, + Duration.ofDays(1)))); } @Test void testMethod_firstDepositOnBrdaDay_depositsBothRdeAndBrda() { - clock.setTo(DateTime.parse("2000-01-04T08:00Z")); // Tuesday + clock.setTo(Instant.parse("2000-01-04T08:00:00Z")); // Tuesday createTldWithEscrowEnabled("lol"); clock.setAutoIncrementByOneMilli(); - assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()).isEqualTo( - ImmutableSetMultimap.of( - "lol", PendingDeposit.create( - "lol", DateTime.parse("2000-01-04TZ"), FULL, RDE_STAGING, standardDays(1)), - "lol", PendingDeposit.create( - "lol", DateTime.parse("2000-01-04TZ"), THIN, BRDA, standardDays(7)))); + assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()) + .isEqualTo( + ImmutableSetMultimap.of( + "lol", + PendingDeposit.create( + "lol", + Instant.parse("2000-01-04T00:00:00Z"), + FULL, + RDE_STAGING, + Duration.ofDays(1)), + "lol", + PendingDeposit.create( + "lol", + Instant.parse("2000-01-04T00:00:00Z"), + THIN, + BRDA, + Duration.ofDays(7)))); } @Test void testMethod_firstRdeDeposit_initializesCursorToMidnightToday() { - clock.setTo(DateTime.parse("2000-01-01TZ")); // Saturday + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); // Saturday createTldWithEscrowEnabled("lol"); clock.advanceOneMilli(); Tld registry = Tld.get("lol"); assertThat(loadByKeyIfPresent(Cursor.createScopedVKey(RDE_STAGING, registry))).isEmpty(); checker.getTldsAndWatermarksPendingDepositForRdeAndBrda(); assertThat(loadByKey(Cursor.createScopedVKey(RDE_STAGING, registry)).getCursorTime()) - .isEqualTo(DateTime.parse("2000-01-01TZ")); + .isEqualTo(Instant.parse("2000-01-01T00:00:00Z")); } @Test void testMethod_subsequentRdeDeposit_doesntMutateCursor() { - clock.setTo(DateTime.parse("2000-01-01TZ")); // Saturday + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); // Saturday createTldWithEscrowEnabled("lol"); clock.advanceOneMilli(); - DateTime yesterday = DateTime.parse("1999-12-31TZ"); + Instant yesterday = Instant.parse("1999-12-31T00:00:00Z"); setCursor(Tld.get("lol"), RDE_STAGING, yesterday); clock.advanceOneMilli(); checker.getTldsAndWatermarksPendingDepositForRdeAndBrda(); @@ -115,11 +132,12 @@ public class PendingDepositCheckerTest { @Test void testMethod_firstBrdaDepositButNotOnBrdaDay_doesntInitializeCursor() { - clock.setTo(DateTime.parse("2000-01-01TZ")); // Saturday + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); // Saturday createTldWithEscrowEnabled("lol"); Tld registry = Tld.get("lol"); clock.advanceOneMilli(); - setCursor(registry, RDE_STAGING, DateTime.parse("2000-01-02TZ")); // assume rde is already done + setCursor( + registry, RDE_STAGING, Instant.parse("2000-01-02T00:00:00Z")); // assume rde is already done clock.advanceOneMilli(); assertThat(loadByKeyIfPresent(Cursor.createScopedVKey(BRDA, registry))).isEmpty(); assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()).isEmpty(); @@ -128,20 +146,26 @@ public class PendingDepositCheckerTest { @Test void testMethod_backloggedTwoDays_onlyWantsLeastRecentDay() { - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); createTldWithEscrowEnabled("lol"); clock.advanceOneMilli(); - setCursor(Tld.get("lol"), RDE_STAGING, DateTime.parse("1999-12-30TZ")); + setCursor(Tld.get("lol"), RDE_STAGING, Instant.parse("1999-12-30T00:00:00Z")); clock.advanceOneMilli(); - assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()).isEqualTo( - ImmutableSetMultimap.of( - "lol", PendingDeposit.create( - "lol", DateTime.parse("1999-12-30TZ"), FULL, RDE_STAGING, standardDays(1)))); + assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()) + .isEqualTo( + ImmutableSetMultimap.of( + "lol", + PendingDeposit.create( + "lol", + Instant.parse("1999-12-30T00:00:00Z"), + FULL, + RDE_STAGING, + Duration.ofDays(1)))); } @Test void testMethod_multipleTldsWithEscrowEnabled_depositsBoth() { - clock.setTo(DateTime.parse("2000-01-01TZ")); // Saturday + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); // Saturday createTldWithEscrowEnabled("pal"); clock.advanceOneMilli(); createTldWithEscrowEnabled("fun"); @@ -151,18 +175,21 @@ public class PendingDepositCheckerTest { ImmutableSetMultimap.of( "pal", PendingDeposit.create( - "pal", DateTime.parse("2000-01-01TZ"), FULL, RDE_STAGING, standardDays(1)), + "pal", + Instant.parse("2000-01-01T00:00:00Z"), + FULL, + RDE_STAGING, + Duration.ofDays(1)), "fun", PendingDeposit.create( "fun", - DateTime.parse("2000-01-01TZ"), + Instant.parse("2000-01-01T00:00:00Z"), FULL, RDE_STAGING, - standardDays(1)))); + Duration.ofDays(1)))); } - private static void setCursor( - final Tld registry, final CursorType cursorType, final DateTime value) { + private static void setCursor(final Tld registry, final CursorType cursorType, Instant value) { tm().transact(() -> tm().put(Cursor.createScoped(cursorType, value, registry))); } diff --git a/core/src/test/java/google/registry/rde/PendingDepositTest.java b/core/src/test/java/google/registry/rde/PendingDepositTest.java index 2f31d942b..a0ff31338 100644 --- a/core/src/test/java/google/registry/rde/PendingDepositTest.java +++ b/core/src/test/java/google/registry/rde/PendingDepositTest.java @@ -21,16 +21,16 @@ import static google.registry.util.SafeSerializationUtils.safeDeserialize; import static google.registry.util.SerializeUtils.deserialize; import static google.registry.util.SerializeUtils.serialize; -import org.joda.time.DateTime; -import org.joda.time.Duration; +import java.time.Duration; +import java.time.Instant; import org.junit.jupiter.api.Test; /** Unit tests for {@link PendingDeposit}. */ public class PendingDepositTest { - private final DateTime now = DateTime.parse("2000-01-01TZ"); + private final Instant now = Instant.parse("2000-01-01T00:00:00Z"); PendingDeposit pendingDeposit = - PendingDeposit.create("soy", now, FULL, RDE_STAGING, Duration.standardDays(1)); + PendingDeposit.create("soy", now, FULL, RDE_STAGING, Duration.ofDays(1)); PendingDeposit manualPendingDeposit = PendingDeposit.createInManualOperation("soy", now, FULL, "/", null); diff --git a/core/src/test/java/google/registry/rde/RdeReportActionTest.java b/core/src/test/java/google/registry/rde/RdeReportActionTest.java index 016879756..dd9248dc2 100644 --- a/core/src/test/java/google/registry/rde/RdeReportActionTest.java +++ b/core/src/test/java/google/registry/rde/RdeReportActionTest.java @@ -26,8 +26,6 @@ import static google.registry.testing.DatabaseHelper.persistResource; import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; -import static org.joda.time.Duration.standardDays; -import static org.joda.time.Duration.standardSeconds; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -58,6 +56,8 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openpgp.PGPPublicKey; import org.joda.time.DateTime; @@ -104,9 +104,9 @@ public class RdeReportActionTest { action.response = response; action.bucket = "tub"; action.tld = "test"; - action.interval = standardDays(1); + action.interval = Duration.ofDays(1); action.reporter = reporter; - action.timeout = standardSeconds(30); + action.timeout = Duration.ofSeconds(30); action.stagingDecryptionKey = new FakeKeyringModule().get().getRdeStagingDecryptionKey(); action.runner = runner; action.prefix = Optional.of("job-name/"); @@ -116,10 +116,13 @@ public class RdeReportActionTest { @BeforeEach void beforeEach() throws Exception { registry = createTld("test"); - persistResource(Cursor.createScoped(RDE_REPORT, DateTime.parse("2006-06-06TZ"), registry)); - persistResource(Cursor.createScoped(RDE_UPLOAD, DateTime.parse("2006-06-07TZ"), registry)); + persistResource( + Cursor.createScoped(RDE_REPORT, Instant.parse("2006-06-06T00:00:00Z"), registry)); + persistResource( + Cursor.createScoped(RDE_UPLOAD, Instant.parse("2006-06-07T00:00:00Z"), registry)); gcsUtils.createFromBytes(reportFile, Ghostryde.encode(REPORT_XML.read(), encryptKey)); - tm().transact(() -> RdeRevision.saveRevision("test", DateTime.parse("2006-06-06TZ"), FULL, 0)); + tm().transact( + () -> RdeRevision.saveRevision("test", Instant.parse("2006-06-06T00:00:00Z"), FULL, 0)); when(httpUrlConnection.getOutputStream()).thenReturn(connectionOutputStream); when(httpUrlConnection.getResponseCode()).thenReturn(SC_OK); when(httpUrlConnection.getInputStream()).thenReturn(IIRDEA_GOOD_XML.openBufferedStream()); @@ -133,7 +136,7 @@ public class RdeReportActionTest { action.run(); verify(runner) .lockRunAndRollForward( - action, Tld.get("lol"), standardSeconds(30), RDE_REPORT, standardDays(1)); + action, Tld.get("lol"), Duration.ofSeconds(30), RDE_REPORT, Duration.ofDays(1)); verifyNoMoreInteractions(runner); } @@ -142,7 +145,7 @@ public class RdeReportActionTest { createAction().runWithLock(loadRdeReportCursor()); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00Z\n"); // Verify the HTTP request was correct. verify(httpUrlConnection).setRequestMethod("PUT"); @@ -164,7 +167,7 @@ public class RdeReportActionTest { action.runWithLock(loadRdeReportCursor()); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00Z\n"); // Verify the HTTP request was correct. verify(httpUrlConnection).setRequestMethod("PUT"); @@ -204,11 +207,12 @@ public class RdeReportActionTest { Ghostryde.encode( ByteSource.wrap("BAD DATA".getBytes(StandardCharsets.UTF_8)).read(), encryptKey)); gcsUtils.createFromBytes(otherReportFile2, Ghostryde.encode(REPORT_XML.read(), encryptKey)); - tm().transact(() -> RdeRevision.saveRevision("test", DateTime.parse("2006-06-06TZ"), FULL, 1)); + tm().transact( + () -> RdeRevision.saveRevision("test", Instant.parse("2006-06-06T00:00:00Z"), FULL, 1)); action.runWithLock(loadRdeReportCursor()); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK test 2006-06-06T00:00:00Z\n"); // Verify the HTTP request was correct. verify(httpUrlConnection).setRequestMethod("PUT"); @@ -230,7 +234,8 @@ public class RdeReportActionTest { BlobId newReport = BlobId.of("tub", "job-name/test_2006-06-06_full_S1_R1-report.xml.ghostryde"); PGPPublicKey encryptKey = new FakeKeyringModule().get().getRdeStagingEncryptionKey(); gcsUtils.createFromBytes(newReport, Ghostryde.encode(REPORT_XML.read(), encryptKey)); - tm().transact(() -> RdeRevision.saveRevision("test", DateTime.parse("2006-06-06TZ"), FULL, 1)); + tm().transact( + () -> RdeRevision.saveRevision("test", Instant.parse("2006-06-06T00:00:00Z"), FULL, 1)); createAction().runWithLock(loadRdeReportCursor()); assertThat(response.getStatus()).isEqualTo(200); } @@ -243,22 +248,22 @@ public class RdeReportActionTest { assertThat(thrown) .hasMessageThat() .isEqualTo( - "Waiting on RdeUploadAction for TLD test to send 2006-06-06T00:00:00.000Z report; last" - + " upload completion was at 1970-01-01T00:00:00.000Z"); + "Waiting on RdeUploadAction for TLD test to send 2006-06-06T00:00:00Z report; last" + + " upload completion was at 1970-01-01T00:00:00Z"); } @Test void testRunWithLock_uploadNotFinished_throws204() { persistResource( - Cursor.createScoped(RDE_UPLOAD, DateTime.parse("2006-06-06TZ"), Tld.get("test"))); + Cursor.createScoped(RDE_UPLOAD, Instant.parse("2006-06-06T00:00:00Z"), Tld.get("test"))); NoContentException thrown = assertThrows( NoContentException.class, () -> createAction().runWithLock(loadRdeReportCursor())); assertThat(thrown) .hasMessageThat() .isEqualTo( - "Waiting on RdeUploadAction for TLD test to send 2006-06-06T00:00:00.000Z report; " - + "last upload completion was at 2006-06-06T00:00:00.000Z"); + "Waiting on RdeUploadAction for TLD test to send 2006-06-06T00:00:00Z report; " + + "last upload completion was at 2006-06-06T00:00:00Z"); } @Test @@ -282,7 +287,7 @@ public class RdeReportActionTest { assertThat(thrown).hasMessageThat().contains("PUT failed"); } - private DateTime loadRdeReportCursor() { + private Instant loadRdeReportCursor() { return loadByKey(Cursor.createScopedVKey(RDE_REPORT, registry)).getCursorTime(); } diff --git a/core/src/test/java/google/registry/rde/RdeStagingActionTest.java b/core/src/test/java/google/registry/rde/RdeStagingActionTest.java index f99f89d9c..537568544 100644 --- a/core/src/test/java/google/registry/rde/RdeStagingActionTest.java +++ b/core/src/test/java/google/registry/rde/RdeStagingActionTest.java @@ -35,10 +35,10 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.request.HttpException.BadRequestException; import google.registry.testing.FakeClock; import java.nio.charset.StandardCharsets; +import java.time.DayOfWeek; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.DateTimeConstants; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -64,10 +64,10 @@ public class RdeStagingActionTest extends BeamActionTestBase { action.jobRegion = "jobRegion"; action.rdeBucket = "rde-bucket"; action.pendingDepositChecker = new PendingDepositChecker(); - action.pendingDepositChecker.brdaDayOfWeek = DateTimeConstants.TUESDAY; - action.pendingDepositChecker.brdaInterval = Duration.standardDays(7); + action.pendingDepositChecker.brdaDayOfWeek = DayOfWeek.TUESDAY.getValue(); + action.pendingDepositChecker.brdaInterval = Duration.ofDays(7); action.pendingDepositChecker.clock = clock; - action.pendingDepositChecker.rdeInterval = Duration.standardDays(1); + action.pendingDepositChecker.rdeInterval = Duration.ofDays(1); action.gcsUtils = gcsUtils; action.response = response; action.transactionCooldown = Duration.ZERO; @@ -84,7 +84,7 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_modeInNonManualMode_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.modeStrings = ImmutableSet.of("full"); assertThrows(BadRequestException.class, action::run); verifyNoMoreInteractions(dataflow); @@ -93,7 +93,7 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_tldInNonManualMode_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.tlds = ImmutableSet.of("tld"); assertThrows(BadRequestException.class, action::run); verifyNoMoreInteractions(dataflow); @@ -102,8 +102,8 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_watermarkInNonManualMode_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); - action.watermarks = ImmutableSet.of(clock.nowUtc()); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); + action.watermarks = ImmutableSet.of(clock.now()); assertThrows(BadRequestException.class, action::run); verifyNoMoreInteractions(dataflow); } @@ -111,7 +111,7 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_revisionInNonManualMode_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.revision = Optional.of(42); assertThrows(BadRequestException.class, action::run); verifyNoMoreInteractions(dataflow); @@ -128,7 +128,7 @@ public class RdeStagingActionTest extends BeamActionTestBase { void testRun_tldWithoutEscrowEnabled_returns204() { createTld("lol"); persistResource(Tld.get("lol").asBuilder().setEscrowEnabled(false).build()); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.run(); assertThat(response.getStatus()).isEqualTo(204); verifyNoMoreInteractions(dataflow); @@ -137,7 +137,7 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_tldWithEscrowEnabled_launchesPipeline() throws Exception { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.run(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getPayload()).contains("Launched RDE pipeline: jobid"); @@ -148,8 +148,8 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_withinTransactionCooldown_getsExcludedAndReturns204() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01T00:04:59Z")); - action.transactionCooldown = Duration.standardMinutes(5); + clock.setTo(Instant.parse("2000-01-01T00:04:59Z")); + action.transactionCooldown = Duration.ofMinutes(5); action.run(); assertThat(response.getStatus()).isEqualTo(204); verifyNoMoreInteractions(dataflow); @@ -158,8 +158,8 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testRun_afterTransactionCooldown_runsPipeline() throws Exception { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01T00:05:00Z")); - action.transactionCooldown = Duration.standardMinutes(5); + clock.setTo(Instant.parse("2000-01-01T00:05:00Z")); + action.transactionCooldown = Duration.ofMinutes(5); action.run(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getPayload()).contains("Launched RDE pipeline: jobid"); @@ -170,43 +170,43 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testManualRun_emptyMode_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of(); action.tlds = ImmutableSet.of("lol"); - action.watermarks = ImmutableSet.of(clock.nowUtc()); + action.watermarks = ImmutableSet.of(clock.now()); assertThrows(BadRequestException.class, action::run); } @Test void testManualRun_invalidMode_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of("full", "thing"); action.tlds = ImmutableSet.of("lol"); - action.watermarks = ImmutableSet.of(clock.nowUtc()); + action.watermarks = ImmutableSet.of(clock.now()); assertThrows(BadRequestException.class, action::run); } @Test void testManualRun_emptyTld_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of(); - action.watermarks = ImmutableSet.of(clock.nowUtc()); + action.watermarks = ImmutableSet.of(clock.now()); assertThrows(BadRequestException.class, action::run); } @Test void testManualRun_emptyWatermark_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of("full"); @@ -218,24 +218,24 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testManualRun_nonDayStartWatermark_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of("lol"); - action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T01:36:45Z")); + action.watermarks = ImmutableSet.of(Instant.parse("2001-01-01T01:36:45Z")); assertThrows(BadRequestException.class, action::run); } @Test void testManualRun_invalidRevision_throwsException() { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of("lol"); - action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T00:00:00Z")); + action.watermarks = ImmutableSet.of(Instant.parse("2001-01-01T00:00:00Z")); action.revision = Optional.of(-1); assertThrows(BadRequestException.class, action::run); } @@ -243,13 +243,14 @@ public class RdeStagingActionTest extends BeamActionTestBase { @Test void testManualRun_validParameters_runsPipeline() throws Exception { createTldWithEscrowEnabled("lol"); - clock.setTo(DateTime.parse("2000-01-01TZ")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); action.manual = true; action.directory = Optional.of("test/"); action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of("lol"); action.watermarks = - ImmutableSet.of(DateTime.parse("1999-12-31TZ"), DateTime.parse("2001-01-01TZ")); + ImmutableSet.of( + Instant.parse("1999-12-31T00:00:00Z"), Instant.parse("2001-01-01T00:00:00Z")); action.run(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getPayload()).contains("Launched RDE pipeline: jobid, jobid1"); diff --git a/core/src/test/java/google/registry/rde/RdeUploadActionTest.java b/core/src/test/java/google/registry/rde/RdeUploadActionTest.java index ac55052ad..942a61c84 100644 --- a/core/src/test/java/google/registry/rde/RdeUploadActionTest.java +++ b/core/src/test/java/google/registry/rde/RdeUploadActionTest.java @@ -26,9 +26,6 @@ import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.GpgSystemCommandExtension.GPG_BINARY; import static google.registry.testing.SystemInfo.hasCommand; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.joda.time.Duration.standardDays; -import static org.joda.time.Duration.standardHours; -import static org.joda.time.Duration.standardSeconds; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.ArgumentMatchers.anyInt; @@ -75,9 +72,10 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.net.URI; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -137,7 +135,7 @@ public class RdeUploadActionTest { new FakeKeyringModule().get().getRdeStagingEncryptionKey(); private final FakeResponse response = new FakeResponse(); private final EscrowTaskRunner runner = mock(EscrowTaskRunner.class); - private final FakeClock clock = new FakeClock(DateTime.parse("2010-10-17TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("2010-10-17T00:00:00Z")); private RdeUploadAction createAction(URI uploadUrl) { try (Keyring keyring = new FakeKeyringModule().get()) { @@ -150,13 +148,13 @@ public class RdeUploadActionTest { "user@ignored", keyring.getRdeSshClientPrivateKey(), keyring.getRdeSshClientPublicKey()); - action.jschSshSessionFactory = new JSchSshSessionFactory(standardSeconds(3)); + action.jschSshSessionFactory = new JSchSshSessionFactory(Duration.ofSeconds(3)); action.response = response; action.bucket = "bucket"; - action.interval = standardDays(1); - action.timeout = standardSeconds(23); + action.interval = Duration.ofDays(1); + action.timeout = Duration.ofSeconds(23); action.tld = "tld"; - action.sftpCooldown = standardSeconds(7); + action.sftpCooldown = Duration.ofSeconds(7); action.uploadUrl = uploadUrl; action.receiverKey = keyring.getRdeReceiverKey(); action.signingKey = keyring.getRdeSigningKey(); @@ -198,8 +196,8 @@ public class RdeUploadActionTest { tm().transact( () -> { - RdeRevision.saveRevision("lol", DateTime.parse("2010-10-17TZ"), FULL, 0); - RdeRevision.saveRevision("tld", DateTime.parse("2010-10-17TZ"), FULL, 0); + RdeRevision.saveRevision("lol", Instant.parse("2010-10-17T00:00:00Z"), FULL, 0); + RdeRevision.saveRevision("tld", Instant.parse("2010-10-17T00:00:00Z"), FULL, 0); }); } @@ -219,7 +217,11 @@ public class RdeUploadActionTest { action.run(); verify(runner) .lockRunAndRollForward( - action, Tld.get("lol"), standardSeconds(23), CursorType.RDE_UPLOAD, standardDays(1)); + action, + Tld.get("lol"), + Duration.ofSeconds(23), + CursorType.RDE_UPLOAD, + Duration.ofDays(1)); cloudTasksHelper.assertTasksEnqueued( "rde-report", new TaskMatcher().path(RdeReportAction.PATH).param(RequestParameters.PARAM_TLD, "lol")); @@ -235,7 +237,11 @@ public class RdeUploadActionTest { action.run(); verify(runner) .lockRunAndRollForward( - action, Tld.get("lol"), standardSeconds(23), CursorType.RDE_UPLOAD, standardDays(1)); + action, + Tld.get("lol"), + Duration.ofSeconds(23), + CursorType.RDE_UPLOAD, + Duration.ofDays(1)); cloudTasksHelper.assertTasksEnqueued( "rde-report", new TaskMatcher() @@ -249,15 +255,15 @@ public class RdeUploadActionTest { void testRunWithLock_succeedsOnThirdTry() throws Exception { int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); RdeUploadAction action = createAction(uploadUrl); action.lazyJsch = Lazies.of(createThrowingJSchSpy(action.lazyJsch.get(), 2)); action.runWithLock(uploadCursor); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00Z\n"); cloudTasksHelper.assertNoTasksEnqueued("rde-upload"); assertThat(folder.list()) .asList() @@ -268,8 +274,8 @@ public class RdeUploadActionTest { void testRunWithLock_failsAfterThreeAttempts() throws Exception { int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); RdeUploadAction action = createAction(uploadUrl); action.lazyJsch = Lazies.of(createThrowingJSchSpy(action.lazyJsch.get(), 3)); @@ -282,8 +288,8 @@ public class RdeUploadActionTest { void testRunWithLock_cannotGuessPrefix() throws Exception { int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); gcsUtils.delete(GHOSTRYDE_FILE_WITH_PREFIX); gcsUtils.delete(LENGTH_FILE_WITH_PREFIX); @@ -293,7 +299,7 @@ public class RdeUploadActionTest { assertThrows(NoContentException.class, () -> action.runWithLock(uploadCursor)); assertThat(thrown) .hasMessageThat() - .isEqualTo("RDE deposit for TLD tld on 2010-10-17T00:00:00.000Z does not exist"); + .isEqualTo("RDE deposit for TLD tld on 2010-10-17T00:00:00Z does not exist"); cloudTasksHelper.assertNoTasksEnqueued("rde-upload"); assertThat(folder.list()).isEmpty(); } @@ -302,8 +308,8 @@ public class RdeUploadActionTest { void testRunWithLock_copiesOnGcs_withPrefix() throws Exception { int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); RdeUploadAction action = createAction(uploadUrl); action.prefix = Optional.of(JOB_PREFIX + "-job-name/"); @@ -313,7 +319,7 @@ public class RdeUploadActionTest { action.runWithLock(uploadCursor); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00Z\n"); cloudTasksHelper.assertNoTasksEnqueued("rde-upload"); // Assert that both files are written to SFTP and GCS, and that the contents are identical. String rydeFilename = "tld_2010-10-17_full_S1_R0.ryde"; @@ -331,8 +337,8 @@ public class RdeUploadActionTest { void testRunWithLock_copiesOnGcs_withoutPrefix() throws Exception { int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); RdeUploadAction action = createAction(uploadUrl); gcsUtils.delete(GHOSTRYDE_FILE); @@ -353,7 +359,7 @@ public class RdeUploadActionTest { action.runWithLock(uploadCursor); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00Z\n"); cloudTasksHelper.assertNoTasksEnqueued("rde-upload"); // Assert that both files are written to SFTP and GCS, and that the contents are identical. String rydeFilename = "tld_2010-10-17_full_S1_R0.ryde"; @@ -369,11 +375,12 @@ public class RdeUploadActionTest { @Test void testRunWithLock_resend() throws Exception { - tm().transact(() -> RdeRevision.saveRevision("tld", DateTime.parse("2010-10-17TZ"), FULL, 1)); + tm().transact( + () -> RdeRevision.saveRevision("tld", Instant.parse("2010-10-17T00:00:00Z"), FULL, 1)); int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); BlobId ghostrydeR1FileWithPrefix = BlobId.of("bucket", JOB_PREFIX + "-job-name/tld_2010-10-17_full_S1_R1.xml.ghostryde"); @@ -391,7 +398,7 @@ public class RdeUploadActionTest { createAction(uploadUrl).runWithLock(uploadCursor); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); - assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00.000Z\n"); + assertThat(response.getPayload()).isEqualTo("OK tld 2010-10-17T00:00:00Z\n"); cloudTasksHelper.assertNoTasksEnqueued("rde-upload"); assertThat(folder.list()) .asList() @@ -403,8 +410,8 @@ public class RdeUploadActionTest { assumeTrue(hasCommand(GPG_BINARY + " --version")); int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); createAction(uploadUrl).runWithLock(uploadCursor); // Only verify signature for SFTP versions, since we check elsewhere that the GCS files are @@ -425,15 +432,15 @@ public class RdeUploadActionTest { void testRunWithLock_nonexistentCursor_throws204() throws Exception { int port = sftpd.serve("user", "password", folder); URI uploadUrl = URI.create(String.format("sftp://user:password@localhost:%d/", port)); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); RdeUploadAction action = createAction(uploadUrl); NoContentException thrown = assertThrows(NoContentException.class, () -> action.runWithLock(uploadCursor)); assertThat(thrown) .hasMessageThat() .isEqualTo( - "Waiting on RdeStagingAction for TLD tld to send 2010-10-17T00:00:00.000Z upload; last" - + " RDE staging completion was before 1970-01-01T00:00:00.000Z"); + "Waiting on RdeStagingAction for TLD tld to send 2010-10-17T00:00:00Z upload; last" + + " RDE staging completion was before 1970-01-01T00:00:00Z"); cloudTasksHelper.assertNoTasksEnqueued("rde-upload"); assertThat(folder.list()).isEmpty(); } @@ -441,25 +448,26 @@ public class RdeUploadActionTest { @Test void testRunWithLock_stagingNotFinished_throws204() { URI url = URI.create("sftp://user:password@localhost:32323/"); - DateTime stagingCursor = DateTime.parse("2010-10-17TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); + Instant stagingCursor = Instant.parse("2010-10-17T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); NoContentException thrown = assertThrows(NoContentException.class, () -> createAction(url).runWithLock(uploadCursor)); assertThat(thrown) .hasMessageThat() .isEqualTo( - "Waiting on RdeStagingAction for TLD tld to send 2010-10-17T00:00:00.000Z upload; " - + "last RDE staging completion was before 2010-10-17T00:00:00.000Z"); + "Waiting on RdeStagingAction for TLD tld to send 2010-10-17T00:00:00Z upload; " + + "last RDE staging completion was before 2010-10-17T00:00:00Z"); } @Test void testRunWithLock_sftpCooldownNotPassed_throws204() { RdeUploadAction action = createAction(URI.create("sftp://user:password@localhost:32323/")); - action.sftpCooldown = standardHours(2); - DateTime stagingCursor = DateTime.parse("2010-10-18TZ"); - DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); - DateTime sftpCursor = uploadCursor.minusMinutes(97); // Within the 2-hour cooldown period. + action.sftpCooldown = Duration.ofHours(2); + Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); + Instant uploadCursor = Instant.parse("2010-10-17T00:00:00Z"); + Instant sftpCursor = + uploadCursor.minus(Duration.ofMinutes(97)); // Within the 2-hour cooldown period. persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); persistResource(Cursor.createScoped(RDE_UPLOAD_SFTP, sftpCursor, Tld.get("tld"))); NoContentException thrown = @@ -467,8 +475,8 @@ public class RdeUploadActionTest { assertThat(thrown) .hasMessageThat() .isEqualTo( - "Waiting on 120 minute SFTP cooldown for TLD tld to send 2010-10-17T00:00:00.000Z" - + " upload; last upload attempt was at 2010-10-16T22:23:00.000Z (97 minutes" + "Waiting on 120 minute SFTP cooldown for TLD tld to send 2010-10-17T00:00:00Z" + + " upload; last upload attempt was at 2010-10-16T22:23:00Z (97 minutes" + " ago)"); } diff --git a/core/src/test/java/google/registry/rde/RegistrarToXjcConverterTest.java b/core/src/test/java/google/registry/rde/RegistrarToXjcConverterTest.java index df51c4e7c..e1abdbe0f 100644 --- a/core/src/test/java/google/registry/rde/RegistrarToXjcConverterTest.java +++ b/core/src/test/java/google/registry/rde/RegistrarToXjcConverterTest.java @@ -47,7 +47,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; */ public class RegistrarToXjcConverterTest { - private final FakeClock clock = new FakeClock(DateTime.parse("2013-01-01T00:00:00Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2013-01-01T00:00:00Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -88,7 +88,7 @@ public class RegistrarToXjcConverterTest { .build(); registrar = cloneAndSetAutoTimestamps(registrar); // Set the creation time in 2013. registrar = registrar.asBuilder().setLastUpdateTime((Instant) null).build(); - clock.setTo(DateTime.parse("2014-01-01T00:00:00Z")); + clock.setTo(Instant.parse("2014-01-01T00:00:00Z")); registrar = cloneAndSetAutoTimestamps(registrar); // Set the update time in 2014. } diff --git a/core/src/test/java/google/registry/rde/RydeFileEncodingTest.java b/core/src/test/java/google/registry/rde/RydeFileEncodingTest.java index 2b0fcac4d..c71f4c664 100644 --- a/core/src/test/java/google/registry/rde/RydeFileEncodingTest.java +++ b/core/src/test/java/google/registry/rde/RydeFileEncodingTest.java @@ -21,7 +21,7 @@ import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; /** Unit tests for {@link RydeFileEncoding}. */ @@ -31,7 +31,7 @@ final class RydeFileEncodingTest { void testEncodeDecode() throws Exception { byte[] expectedContent = "Testing 1, 2, 3".getBytes(UTF_8); String expectedFilename = "myFile.txt"; - DateTime expectedModified = DateTime.parse("2015-12-25T06:30:00.000Z"); + Instant expectedModified = Instant.parse("2015-12-25T06:30:00.000Z"); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (OutputStream encoder = diff --git a/core/src/test/java/google/registry/rde/RydeGpgIntegrationTest.java b/core/src/test/java/google/registry/rde/RydeGpgIntegrationTest.java index 7a8df740f..bc22ff90c 100644 --- a/core/src/test/java/google/registry/rde/RydeGpgIntegrationTest.java +++ b/core/src/test/java/google/registry/rde/RydeGpgIntegrationTest.java @@ -35,10 +35,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; +import java.time.Instant; import java.util.stream.Stream; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPublicKey; -import org.joda.time.DateTime; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -82,7 +82,7 @@ public class RydeGpgIntegrationTest { Keyring keyring = keyringFactory.get(); PGPKeyPair signingKey = keyring.getRdeSigningKey(); PGPPublicKey receiverKey = keyring.getRdeReceiverKey(); - DateTime modified = DateTime.parse("1984-01-01T00:00:00Z"); + Instant modified = Instant.parse("1984-01-01T00:00:00Z"); File home = gpg.getCwd(); File rydeFile = new File(home, filename + ".ryde"); File sigFile = new File(home, filename + ".sig"); diff --git a/core/src/test/java/google/registry/rde/RydeTarTest.java b/core/src/test/java/google/registry/rde/RydeTarTest.java index 96c9a1b4e..f675cc30e 100644 --- a/core/src/test/java/google/registry/rde/RydeTarTest.java +++ b/core/src/test/java/google/registry/rde/RydeTarTest.java @@ -21,7 +21,7 @@ import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; /** Unit tests for {@link RydeTar}. */ @@ -31,7 +31,7 @@ final class RydeTarTest { void testWriteRead() throws Exception { byte[] expectedContent = "Testing 1, 2, 3".getBytes(UTF_8); String expectedFilename = "myFile.xml"; - DateTime expectedModified = DateTime.parse("2015-12-25T06:30:00.000Z"); + Instant expectedModified = Instant.parse("2015-12-25T06:30:00.000Z"); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (OutputStream writer = diff --git a/core/src/test/java/google/registry/reporting/ReportingModuleTest.java b/core/src/test/java/google/registry/reporting/ReportingModuleTest.java index 363dfe333..56d5f7155 100644 --- a/core/src/test/java/google/registry/reporting/ReportingModuleTest.java +++ b/core/src/test/java/google/registry/reporting/ReportingModuleTest.java @@ -23,10 +23,10 @@ import google.registry.request.HttpException.BadRequestException; import google.registry.testing.FakeClock; import google.registry.util.Clock; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; +import java.time.LocalDate; +import java.time.YearMonth; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -38,7 +38,7 @@ class ReportingModuleTest { @BeforeEach void beforeEach() { - clock = new FakeClock(DateTime.parse("2017-07-01TZ")); + clock = new FakeClock(Instant.parse("2017-07-01T00:00:00Z")); } @Test @@ -50,7 +50,7 @@ class ReportingModuleTest { @Test void testValidYearMonthParameter_returnsThatMonth() { when(req.getParameter("yearMonth")).thenReturn("2017-05"); - assertThat(ReportingModule.provideYearMonthOptional(req)).hasValue(new YearMonth(2017, 5)); + assertThat(ReportingModule.provideYearMonthOptional(req)).hasValue(YearMonth.of(2017, 5)); } @Test @@ -66,16 +66,16 @@ class ReportingModuleTest { @Test void testEmptyYearMonth_returnsLastMonth() { - assertThat(ReportingModule.provideYearMonth(Optional.empty(), new LocalDate(2017, 1, 6))) - .isEqualTo(new YearMonth(2016, 12)); + assertThat(ReportingModule.provideYearMonth(Optional.empty(), LocalDate.of(2017, 1, 6))) + .isEqualTo(YearMonth.of(2016, 12)); } @Test void testGivenYearMonth_returnsThatMonth() { assertThat( ReportingModule.provideYearMonth( - Optional.of(new YearMonth(2017, 5)), new LocalDate(2017, 7, 6))) - .isEqualTo(new YearMonth(2017, 5)); + Optional.of(YearMonth.of(2017, 5)), LocalDate.of(2017, 7, 6))) + .isEqualTo(YearMonth.of(2017, 5)); } @Test @@ -87,7 +87,7 @@ class ReportingModuleTest { @Test void testValidDateParameter_returnsThatDate() { when(req.getParameter("date")).thenReturn("2017-05-13"); - assertThat(ReportingModule.provideDateOptional(req)).hasValue(new LocalDate(2017, 5, 13)); + assertThat(ReportingModule.provideDateOptional(req)).hasValue(LocalDate.of(2017, 5, 13)); } @Test @@ -103,13 +103,13 @@ class ReportingModuleTest { @Test void testEmptyDate_returnsToday() { when(req.getParameter("date")).thenReturn(null); - assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 1)); + assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(LocalDate.of(2017, 7, 1)); } @Test void testGivenDate_returnsThatDate() { when(req.getParameter("date")).thenReturn("2017-07-02"); - assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(new LocalDate(2017, 7, 2)); + assertThat(ReportingModule.provideDate(req, clock)).isEqualTo(LocalDate.of(2017, 7, 2)); } @Test diff --git a/core/src/test/java/google/registry/reporting/billing/BillingEmailUtilsTest.java b/core/src/test/java/google/registry/reporting/billing/BillingEmailUtilsTest.java index 0560da278..7af4f2a50 100644 --- a/core/src/test/java/google/registry/reporting/billing/BillingEmailUtilsTest.java +++ b/core/src/test/java/google/registry/reporting/billing/BillingEmailUtilsTest.java @@ -28,8 +28,8 @@ import google.registry.groups.GmailClient; import google.registry.util.EmailMessage; import jakarta.mail.MessagingException; import jakarta.mail.internet.InternetAddress; +import java.time.YearMonth; import java.util.Optional; -import org.joda.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -54,7 +54,7 @@ class BillingEmailUtilsTest { throws Exception { return new BillingEmailUtils( gmailClient, - new YearMonth(2017, 10), + YearMonth.of(2017, 10), new InternetAddress("my-receiver@test.com"), ImmutableList.of( new InternetAddress("hello@world.com"), new InternetAddress("hola@mundo.com")), diff --git a/core/src/test/java/google/registry/reporting/billing/GenerateInvoicesActionTest.java b/core/src/test/java/google/registry/reporting/billing/GenerateInvoicesActionTest.java index d9fa8fb60..81ca83ed1 100644 --- a/core/src/test/java/google/registry/reporting/billing/GenerateInvoicesActionTest.java +++ b/core/src/test/java/google/registry/reporting/billing/GenerateInvoicesActionTest.java @@ -32,8 +32,7 @@ import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; import java.io.IOException; -import org.joda.time.Duration; -import org.joda.time.YearMonth; +import java.time.YearMonth; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -60,7 +59,7 @@ class GenerateInvoicesActionTest extends BeamActionTestBase { "billing_bucket", "REG-INV", true, - new YearMonth(2017, 10), + YearMonth.of(2017, 10), emailUtils, cloudTasksUtils, clock, @@ -78,10 +77,7 @@ class GenerateInvoicesActionTest extends BeamActionTestBase { .method(HttpMethod.POST) .param("jobId", "jobid") .param("yearMonth", "2017-10") - .scheduleTime( - clock - .nowUtc() - .plus(Duration.standardMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES)))); + .scheduleTime(clock.nowUtc().plusMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES))); } @Test @@ -94,7 +90,7 @@ class GenerateInvoicesActionTest extends BeamActionTestBase { "billing_bucket", "REG-INV", false, - new YearMonth(2017, 10), + YearMonth.of(2017, 10), emailUtils, cloudTasksUtils, clock, @@ -118,7 +114,7 @@ class GenerateInvoicesActionTest extends BeamActionTestBase { "billing_bucket", "REG-INV", false, - new YearMonth(2017, 10), + YearMonth.of(2017, 10), emailUtils, cloudTasksUtils, clock, diff --git a/core/src/test/java/google/registry/reporting/billing/PublishInvoicesActionTest.java b/core/src/test/java/google/registry/reporting/billing/PublishInvoicesActionTest.java index 8fe86a582..45cf96427 100644 --- a/core/src/test/java/google/registry/reporting/billing/PublishInvoicesActionTest.java +++ b/core/src/test/java/google/registry/reporting/billing/PublishInvoicesActionTest.java @@ -36,7 +36,7 @@ import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeResponse; import java.io.IOException; -import org.joda.time.YearMonth; +import java.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -71,7 +71,7 @@ class PublishInvoicesActionTest { emailUtils, dataflow, response, - new YearMonth(2017, 10), + YearMonth.of(2017, 10), cloudTasksUtils); } diff --git a/core/src/test/java/google/registry/reporting/icann/ActivityReportingQueryBuilderTest.java b/core/src/test/java/google/registry/reporting/icann/ActivityReportingQueryBuilderTest.java index b116d0e5d..82eb9a189 100644 --- a/core/src/test/java/google/registry/reporting/icann/ActivityReportingQueryBuilderTest.java +++ b/core/src/test/java/google/registry/reporting/icann/ActivityReportingQueryBuilderTest.java @@ -18,13 +18,13 @@ import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import org.joda.time.YearMonth; +import java.time.YearMonth; import org.junit.jupiter.api.Test; /** Unit tests for {@link ActivityReportingQueryBuilder}. */ class ActivityReportingQueryBuilderTest { - private final YearMonth yearMonth = new YearMonth(2017, 9); + private final YearMonth yearMonth = YearMonth.of(2017, 9); @SuppressWarnings("NonCanonicalType") private ActivityReportingQueryBuilder createQueryBuilder(String datasetName) { diff --git a/core/src/test/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinatorTest.java b/core/src/test/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinatorTest.java index 137738666..0ea2bc527 100644 --- a/core/src/test/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinatorTest.java +++ b/core/src/test/java/google/registry/reporting/icann/CloudDnsCountQueryCoordinatorTest.java @@ -15,7 +15,7 @@ package google.registry.reporting.icann; import static com.google.common.truth.Truth.assertThat; -import org.joda.time.YearMonth; +import java.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test; public class CloudDnsCountQueryCoordinatorTest { public CloudDnsCountQueryCoordinatorTest() {} - private final YearMonth yearMonth = new YearMonth(2017, 9); + private final YearMonth yearMonth = YearMonth.of(2017, 9); CloudDnsCountQueryCoordinator coordinator = new CloudDnsCountQueryCoordinator(); @BeforeEach diff --git a/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java b/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java index c7c875c97..26e9d307a 100644 --- a/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java +++ b/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java @@ -33,19 +33,19 @@ import google.registry.gcs.GcsUtils; import google.registry.reporting.icann.IcannReportingModule.ReportType; import google.registry.testing.FakeClock; import google.registry.testing.FakeResponse; +import java.time.Instant; +import java.time.YearMonth; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; -import org.joda.time.DateTime; -import org.joda.time.YearMonth; import org.junit.jupiter.api.Test; /** Unit tests for {@link google.registry.reporting.icann.IcannReportingStager}. */ class IcannReportingStagerTest { - private final FakeClock clock = new FakeClock(DateTime.parse("2026-01-26T21:06:12.284Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2026-01-26T21:06:12.284Z")); private BigqueryConnection bigquery = mock(BigqueryConnection.class); FakeResponse response = new FakeResponse(); - private YearMonth yearMonth = new YearMonth(2017, 6); + private YearMonth yearMonth = YearMonth.of(2017, 6); private String subdir = "icann/monthly/2017-06"; private GcsUtils gcsUtils = new GcsUtils(LocalStorageHelper.getOptions()); diff --git a/core/src/test/java/google/registry/reporting/icann/IcannReportingStagingActionTest.java b/core/src/test/java/google/registry/reporting/icann/IcannReportingStagingActionTest.java index b78c844d8..3eadf725c 100644 --- a/core/src/test/java/google/registry/reporting/icann/IcannReportingStagingActionTest.java +++ b/core/src/test/java/google/registry/reporting/icann/IcannReportingStagingActionTest.java @@ -37,10 +37,9 @@ import google.registry.testing.FakeSleeper; import google.registry.util.EmailMessage; import google.registry.util.Retrier; import jakarta.mail.internet.InternetAddress; +import java.time.Instant; +import java.time.YearMonth; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,10 +48,10 @@ class IcannReportingStagingActionTest { private FakeResponse response = new FakeResponse(); private IcannReportingStager stager = mock(IcannReportingStager.class); - private YearMonth yearMonth = new YearMonth(2017, 6); + private YearMonth yearMonth = YearMonth.of(2017, 6); private String subdir = "default/dir"; private IcannReportingStagingAction action; - private FakeClock clock = new FakeClock(DateTime.parse("2021-01-02T11:00:00Z")); + private FakeClock clock = new FakeClock(Instant.parse("2021-01-02T11:00:00Z")); private CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); @BeforeEach @@ -82,7 +81,7 @@ class IcannReportingStagingActionTest { new TaskMatcher() .path("/_dr/task/icannReportingUpload") .method(HttpMethod.POST) - .scheduleTime(clock.nowUtc().plus(Duration.standardMinutes(2)))); + .scheduleTime(clock.nowUtc().plusMinutes(2))); } @Test @@ -187,20 +186,20 @@ class IcannReportingStagingActionTest { @Test void testEmptySubDir_returnsDefaultSubdir() { action.overrideSubdir = Optional.empty(); - assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("icann/monthly/2017-06"); + assertThat(action.getSubdir(YearMonth.of(2017, 6))).isEqualTo("icann/monthly/2017-06"); } @Test void testGivenSubdir_returnsManualSubdir() { action.overrideSubdir = Optional.of("manual/dir"); - assertThat(action.getSubdir(new YearMonth(2017, 6))).isEqualTo("manual/dir"); + assertThat(action.getSubdir(YearMonth.of(2017, 6))).isEqualTo("manual/dir"); } @Test void testInvalidSubdir_throwsException() { action.overrideSubdir = Optional.of("/whoops"); BadRequestException thrown = - assertThrows(BadRequestException.class, () -> action.getSubdir(new YearMonth(2017, 6))); + assertThrows(BadRequestException.class, () -> action.getSubdir(YearMonth.of(2017, 6))); assertThat(thrown) .hasMessageThat() .contains("subdir must not start or end with a \"/\", got /whoops instead."); diff --git a/core/src/test/java/google/registry/reporting/icann/IcannReportingUploadActionTest.java b/core/src/test/java/google/registry/reporting/icann/IcannReportingUploadActionTest.java index e0b52b5c1..d787584ca 100644 --- a/core/src/test/java/google/registry/reporting/icann/IcannReportingUploadActionTest.java +++ b/core/src/test/java/google/registry/reporting/icann/IcannReportingUploadActionTest.java @@ -46,9 +46,9 @@ import google.registry.util.EmailMessage; import google.registry.util.Retrier; import jakarta.mail.internet.InternetAddress; import java.io.IOException; +import java.time.Instant; import java.util.logging.Level; import java.util.logging.Logger; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -69,7 +69,7 @@ class IcannReportingUploadActionTest { private final TestLogHandler logHandler = new TestLogHandler(); private final Logger loggerToIntercept = Logger.getLogger(IcannReportingUploadAction.class.getCanonicalName()); - private final FakeClock clock = new FakeClock(DateTime.parse("2000-01-01TZ")); + private final FakeClock clock = new FakeClock(Instant.parse("2000-01-01T00:00:00Z")); private IcannReportingUploadAction createAction() throws Exception { IcannReportingUploadAction action = new IcannReportingUploadAction(); @@ -100,19 +100,23 @@ class IcannReportingUploadActionTest { when(mockReporter.send(PAYLOAD_SUCCESS, "foo-transactions-200606.csv")).thenReturn(true); when(mockReporter.send(PAYLOAD_FAIL, "tld-activity-200606.csv")).thenReturn(false); when(mockReporter.send(PAYLOAD_SUCCESS, "foo-activity-200606.csv")).thenReturn(true); - clock.setTo(DateTime.parse("2006-07-05T00:30:00Z")); + clock.setTo(Instant.parse("2006-07-05T00:30:00Z")); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-07-01TZ"), Tld.get("tld"))); + CursorType.ICANN_UPLOAD_ACTIVITY, + Instant.parse("2006-07-01T00:00:00Z"), + Tld.get("tld"))); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_TX, DateTime.parse("2006-07-01TZ"), Tld.get("tld"))); + CursorType.ICANN_UPLOAD_TX, Instant.parse("2006-07-01T00:00:00Z"), Tld.get("tld"))); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-07-01TZ"), Tld.get("foo"))); + CursorType.ICANN_UPLOAD_ACTIVITY, + Instant.parse("2006-07-01T00:00:00Z"), + Tld.get("foo"))); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_TX, DateTime.parse("2006-07-01TZ"), Tld.get("foo"))); + CursorType.ICANN_UPLOAD_TX, Instant.parse("2006-07-01T00:00:00Z"), Tld.get("foo"))); loggerToIntercept.addHandler(logHandler); } @@ -131,23 +135,26 @@ class IcannReportingUploadActionTest { EmailMessage.create( "ICANN Monthly report upload summary: 3/4 succeeded", """ - Report Filename - Upload status: - foo-activity-200606.csv - SUCCESS - foo-transactions-200606.csv - SUCCESS - tld-activity-200606.csv - FAILURE - tld-transactions-200606.csv - SUCCESS""", + Report Filename - Upload status: + foo-activity-200606.csv - SUCCESS + foo-transactions-200606.csv - SUCCESS + tld-activity-200606.csv - FAILURE + tld-transactions-200606.csv - SUCCESS\ + """, new InternetAddress("recipient@example.com"))); } @Test void testSuccess_january() throws Exception { - clock.setTo(DateTime.parse("2006-01-22T00:30:00Z")); + clock.setTo(Instant.parse("2006-01-22T00:30:00Z")); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-01-01TZ"), Tld.get("tld"))); + CursorType.ICANN_UPLOAD_ACTIVITY, + Instant.parse("2006-01-01T00:00:00Z"), + Tld.get("tld"))); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_TX, DateTime.parse("2006-01-01TZ"), Tld.get("tld"))); + CursorType.ICANN_UPLOAD_TX, Instant.parse("2006-01-01T00:00:00Z"), Tld.get("tld"))); gcsUtils.createFromBytes( BlobId.of("basin", "icann/monthly/2005-12/tld-transactions-200512.csv"), PAYLOAD_SUCCESS); gcsUtils.createFromBytes( @@ -166,9 +173,10 @@ class IcannReportingUploadActionTest { EmailMessage.create( "ICANN Monthly report upload summary: 2/2 succeeded", """ - Report Filename - Upload status: - tld-activity-200512.csv - SUCCESS - tld-transactions-200512.csv - SUCCESS""", + Report Filename - Upload status: + tld-activity-200512.csv - SUCCESS + tld-transactions-200512.csv - SUCCESS\ + """, new InternetAddress("recipient@example.com"))); } @@ -181,12 +189,12 @@ class IcannReportingUploadActionTest { action.run(); Cursor cursor = loadByKey(Cursor.createScopedVKey(CursorType.ICANN_UPLOAD_ACTIVITY, Tld.get("tld"))); - assertThat(cursor.getCursorTime()).isEqualTo(DateTime.parse("2006-08-02T10:00:00Z")); + assertThat(cursor.getCursorTime()).isEqualTo(Instant.parse("2006-08-02T10:00:00Z")); } @Test void testSuccess_noUploadsNeeded() throws Exception { - clock.setTo(DateTime.parse("2006-5-01T00:30:00Z")); + clock.setTo(Instant.parse("2006-05-01T00:30:00Z")); IcannReportingUploadAction action = createAction(); action.run(); verifyNoMoreInteractions(mockReporter); @@ -210,11 +218,12 @@ class IcannReportingUploadActionTest { EmailMessage.create( "ICANN Monthly report upload summary: 3/4 succeeded", """ - Report Filename - Upload status: - foo-activity-200606.csv - SUCCESS - foo-transactions-200606.csv - SUCCESS - tld-activity-200606.csv - FAILURE - tld-transactions-200606.csv - SUCCESS""", + Report Filename - Upload status: + foo-activity-200606.csv - SUCCESS + foo-transactions-200606.csv - SUCCESS + tld-activity-200606.csv - FAILURE + tld-transactions-200606.csv - SUCCESS\ + """, new InternetAddress("recipient@example.com"))); } @@ -238,17 +247,17 @@ class IcannReportingUploadActionTest { new IOException("Your IP address 25.147.130.158 is not allowed to connect")); Cursor cursor = loadByKey(Cursor.createScopedVKey(CursorType.ICANN_UPLOAD_ACTIVITY, Tld.get("tld"))); - assertThat(cursor.getCursorTime()).isEqualTo(DateTime.parse("2006-07-01TZ")); + assertThat(cursor.getCursorTime()).isEqualTo(Instant.parse("2006-07-01T00:00:00Z")); } @Test void testNotRunIfCursorDateIsAfterToday() throws Exception { - clock.setTo(DateTime.parse("2006-05-01T00:30:00Z")); + clock.setTo(Instant.parse("2006-05-01T00:30:00Z")); IcannReportingUploadAction action = createAction(); action.run(); Cursor cursor = loadByKey(Cursor.createScopedVKey(CursorType.ICANN_UPLOAD_ACTIVITY, Tld.get("foo"))); - assertThat(cursor.getCursorTime()).isEqualTo(DateTime.parse("2006-07-01TZ")); + assertThat(cursor.getCursorTime()).isEqualTo(Instant.parse("2006-07-01T00:00:00Z")); verifyNoMoreInteractions(mockReporter); } @@ -270,20 +279,23 @@ class IcannReportingUploadActionTest { EmailMessage.create( "ICANN Monthly report upload summary: 3/4 succeeded", """ - Report Filename - Upload status: - foo-activity-200606.csv - SUCCESS - foo-transactions-200606.csv - SUCCESS - tld-activity-200606.csv - FAILURE - tld-transactions-200606.csv - SUCCESS""", + Report Filename - Upload status: + foo-activity-200606.csv - SUCCESS + foo-transactions-200606.csv - SUCCESS + tld-activity-200606.csv - FAILURE + tld-transactions-200606.csv - SUCCESS\ + """, new InternetAddress("recipient@example.com"))); } @Test void testFail_fileNotFound() throws Exception { - clock.setTo(DateTime.parse("2006-01-22T00:30:00Z")); + clock.setTo(Instant.parse("2006-01-22T00:30:00Z")); persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-01-01TZ"), Tld.get("tld"))); + CursorType.ICANN_UPLOAD_ACTIVITY, + Instant.parse("2006-01-01T00:00:00Z"), + Tld.get("tld"))); IcannReportingUploadAction action = createAction(); action.run(); assertAboutLogs() @@ -299,8 +311,10 @@ class IcannReportingUploadActionTest { void testWarning_fileNotStagedYet() throws Exception { persistResource( Cursor.createScoped( - CursorType.ICANN_UPLOAD_ACTIVITY, DateTime.parse("2006-08-01TZ"), Tld.get("foo"))); - clock.setTo(DateTime.parse("2006-08-01T00:30:00Z")); + CursorType.ICANN_UPLOAD_ACTIVITY, + Instant.parse("2006-08-01T00:00:00Z"), + Tld.get("foo"))); + clock.setTo(Instant.parse("2006-08-01T00:30:00Z")); IcannReportingUploadAction action = createAction(); action.run(); assertAboutLogs() @@ -340,19 +354,20 @@ class IcannReportingUploadActionTest { EmailMessage.create( "ICANN Monthly report upload summary: 3/4 succeeded", """ - Report Filename - Upload status: - foo-activity-200606.csv - SUCCESS - foo-transactions-200606.csv - SUCCESS - tld-activity-200606.csv - FAILURE - tld-transactions-200606.csv - SUCCESS""", + Report Filename - Upload status: + foo-activity-200606.csv - SUCCESS + foo-transactions-200606.csv - SUCCESS + tld-activity-200606.csv - FAILURE + tld-transactions-200606.csv - SUCCESS\ + """, new InternetAddress("recipient@example.com"))); Cursor newActivityCursor = loadByKey(Cursor.createScopedVKey(CursorType.ICANN_UPLOAD_ACTIVITY, Tld.get("new"))); - assertThat(newActivityCursor.getCursorTime()).isEqualTo(DateTime.parse("2006-08-02T10:00:00Z")); + assertThat(newActivityCursor.getCursorTime()).isEqualTo(Instant.parse("2006-08-02T10:00:00Z")); Cursor newTransactionCursor = loadByKey(Cursor.createScopedVKey(CursorType.ICANN_UPLOAD_TX, Tld.get("new"))); assertThat(newTransactionCursor.getCursorTime()) - .isEqualTo(DateTime.parse("2006-08-02T10:00:00Z")); + .isEqualTo(Instant.parse("2006-08-02T10:00:00Z")); } } diff --git a/core/src/test/java/google/registry/reporting/icann/TransactionsReportingQueryBuilderTest.java b/core/src/test/java/google/registry/reporting/icann/TransactionsReportingQueryBuilderTest.java index b7afdfa01..f99257023 100644 --- a/core/src/test/java/google/registry/reporting/icann/TransactionsReportingQueryBuilderTest.java +++ b/core/src/test/java/google/registry/reporting/icann/TransactionsReportingQueryBuilderTest.java @@ -19,13 +19,13 @@ import static com.google.common.truth.Truth.assertWithMessage; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import org.joda.time.YearMonth; +import java.time.YearMonth; import org.junit.jupiter.api.Test; /** Unit tests for {@link ActivityReportingQueryBuilder}. */ class TransactionsReportingQueryBuilderTest { - private final YearMonth yearMonth = new YearMonth(2017, 9); + private final YearMonth yearMonth = YearMonth.of(2017, 9); private TransactionsReportingQueryBuilder createQueryBuilder(String datasetName) { return new TransactionsReportingQueryBuilder("domain-registry-alpha", datasetName); diff --git a/core/src/test/java/google/registry/reporting/spec11/GenerateSpec11ReportActionTest.java b/core/src/test/java/google/registry/reporting/spec11/GenerateSpec11ReportActionTest.java index 2288ca288..1f66b09dc 100644 --- a/core/src/test/java/google/registry/reporting/spec11/GenerateSpec11ReportActionTest.java +++ b/core/src/test/java/google/registry/reporting/spec11/GenerateSpec11ReportActionTest.java @@ -16,6 +16,7 @@ package google.registry.reporting.spec11; import static com.google.common.truth.Truth.assertThat; import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; +import static java.time.ZoneOffset.UTC; import static org.apache.http.HttpStatus.SC_OK; import static org.mockito.Mockito.when; @@ -28,14 +29,13 @@ import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; import java.io.IOException; -import org.joda.time.DateTime; -import org.joda.time.Duration; +import java.time.Instant; import org.junit.jupiter.api.Test; /** Unit tests for {@link GenerateSpec11ReportAction}. */ class GenerateSpec11ReportActionTest extends BeamActionTestBase { - private final FakeClock clock = new FakeClock(DateTime.parse("2018-06-11T12:23:56Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2018-06-11T12:23:56Z")); private CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); private CloudTasksUtils cloudTasksUtils = cloudTasksHelper.getTestCloudTasksUtils(); private GenerateSpec11ReportAction action; @@ -49,7 +49,7 @@ class GenerateSpec11ReportActionTest extends BeamActionTestBase { "gs://staging-project/staging-bucket/", "gs://reporting-project/reporting-bucket/", "api_key/a", - clock.nowUtc().toLocalDate(), + clock.now().atZone(UTC).toLocalDate(), true, clock, response, @@ -72,7 +72,7 @@ class GenerateSpec11ReportActionTest extends BeamActionTestBase { "gs://staging-project/staging-bucket/", "gs://reporting-project/reporting-bucket/", "api_key/a", - clock.nowUtc().toLocalDate(), + clock.now().atZone(UTC).toLocalDate(), true, clock, response, @@ -90,10 +90,7 @@ class GenerateSpec11ReportActionTest extends BeamActionTestBase { .method(HttpMethod.POST) .param("jobId", "jobid") .param("date", "2018-06-11") - .scheduleTime( - clock - .nowUtc() - .plus(Duration.standardMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES)))); + .scheduleTime(clock.nowUtc().plusMinutes(ReportingModule.ENQUEUE_DELAY_MINUTES))); } @Test @@ -105,7 +102,7 @@ class GenerateSpec11ReportActionTest extends BeamActionTestBase { "gs://staging-project/staging-bucket/", "gs://reporting-project/reporting-bucket/", "api_key/a", - clock.nowUtc().toLocalDate(), + clock.now().atZone(UTC).toLocalDate(), false, clock, response, diff --git a/core/src/test/java/google/registry/reporting/spec11/PublishSpec11ReportActionTest.java b/core/src/test/java/google/registry/reporting/spec11/PublishSpec11ReportActionTest.java index 671c7fe8d..25079f2d3 100644 --- a/core/src/test/java/google/registry/reporting/spec11/PublishSpec11ReportActionTest.java +++ b/core/src/test/java/google/registry/reporting/spec11/PublishSpec11ReportActionTest.java @@ -40,15 +40,15 @@ import google.registry.beam.spec11.ThreatMatch; import google.registry.reporting.spec11.soy.Spec11EmailSoyInfo; import google.registry.testing.FakeResponse; import java.io.IOException; +import java.time.LocalDate; import java.util.Optional; -import org.joda.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Unit tests for {@link PublishSpec11ReportAction}. */ class PublishSpec11ReportActionTest { - private final LocalDate date = new LocalDate(2018, 6, 5); + private final LocalDate date = LocalDate.of(2018, 6, 5); private Dataflow dataflow; private Projects projects; diff --git a/core/src/test/java/google/registry/reporting/spec11/Spec11EmailUtilsTest.java b/core/src/test/java/google/registry/reporting/spec11/Spec11EmailUtilsTest.java index 3363fb4ef..2085bdfb3 100644 --- a/core/src/test/java/google/registry/reporting/spec11/Spec11EmailUtilsTest.java +++ b/core/src/test/java/google/registry/reporting/spec11/Spec11EmailUtilsTest.java @@ -27,7 +27,6 @@ import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.DatabaseHelper.persistResource; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -46,11 +45,11 @@ import google.registry.util.EmailMessage; import google.registry.util.Sleeper; import jakarta.mail.MessagingException; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; +import java.time.LocalDate; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; -import org.joda.time.Duration; -import org.joda.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -106,10 +105,10 @@ class Spec11EmailUtilsTest { @Mock private GmailClient gmailClient; @Mock private Sleeper sleeper; - private Duration emailThrottleDuration = Duration.millis(1); + private Duration emailThrottleDuration = Duration.ofMillis(1); private Spec11EmailUtils emailUtils; private ArgumentCaptor contentCaptor; - private final LocalDate date = new LocalDate(2018, 7, 15); + private final LocalDate date = LocalDate.of(2018, 7, 15); private Domain aDomain; private Domain bDomain; @@ -146,7 +145,7 @@ class Spec11EmailUtilsTest { // We inspect individual parameters because Message doesn't implement equals(). verify(gmailClient, times(3)).sendEmail(any(EmailMessage.class)); // Sleep once between two reports sent in a tight loop. No sleep before the final alert message. - verify(sleeper, times(1)).sleep(same(emailThrottleDuration)); + verify(sleeper, times(1)).sleepInterruptibly(emailThrottleDuration); } @Test diff --git a/core/src/test/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParserTest.java b/core/src/test/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParserTest.java index afa36531a..97fc7b21d 100644 --- a/core/src/test/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParserTest.java +++ b/core/src/test/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParserTest.java @@ -27,7 +27,7 @@ import google.registry.gcs.GcsUtils; import google.registry.testing.TestDataHelper; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import org.joda.time.LocalDate; +import java.time.LocalDate; import org.json.JSONObject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/core/src/test/java/google/registry/request/lock/LockHandlerImplTest.java b/core/src/test/java/google/registry/request/lock/LockHandlerImplTest.java index ee4f58012..1c0d1172d 100644 --- a/core/src/test/java/google/registry/request/lock/LockHandlerImplTest.java +++ b/core/src/test/java/google/registry/request/lock/LockHandlerImplTest.java @@ -22,20 +22,20 @@ import static org.mockito.Mockito.verify; import google.registry.model.server.Lock; import google.registry.testing.FakeClock; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.Test; /** Unit tests for {@link LockHandler}. */ final class LockHandlerImplTest { - private static final Duration ONE_DAY = Duration.standardDays(1); + private static final Duration ONE_DAY = Duration.ofDays(1); - private final FakeClock clock = new FakeClock(DateTime.parse("2001-08-29T12:20:00Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2001-08-29T12:20:00Z")); private static class CountingCallable implements Callable { int numCalled; @@ -58,7 +58,7 @@ final class LockHandlerImplTest { @Override public Void call() throws Exception { - clock.advanceBy(Duration.standardSeconds(77)); + clock.advanceBy(Duration.ofSeconds(77)); throw exception; } } @@ -102,7 +102,7 @@ final class LockHandlerImplTest { .hasMessageThat() .isEqualTo( "Execution on locks 'resourceName' for TLD 'tld'" - + " timed out after PT77S; started at 2001-08-29T12:20:00.000Z"); + + " timed out after PT1M17S; started at 2001-08-29T12:20:00Z"); verify(lock, times(1)).release(); } diff --git a/core/src/test/java/google/registry/testing/CloudTasksHelper.java b/core/src/test/java/google/registry/testing/CloudTasksHelper.java index 4f5f18382..e4604ea95 100644 --- a/core/src/test/java/google/registry/testing/CloudTasksHelper.java +++ b/core/src/test/java/google/registry/testing/CloudTasksHelper.java @@ -53,6 +53,7 @@ import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -356,6 +357,10 @@ public class CloudTasksHelper implements Serializable { return this; } + public TaskMatcher scheduleTime(Instant scheduleTime) { + return scheduleTime(Timestamps.fromMillis(scheduleTime.toEpochMilli())); + } + public TaskMatcher scheduleTime(DateTime scheduleTime) { return scheduleTime(Timestamps.fromMillis(scheduleTime.getMillis())); } diff --git a/core/src/test/java/google/registry/testing/DatabaseHelper.java b/core/src/test/java/google/registry/testing/DatabaseHelper.java index 062c399e5..630e7a7c7 100644 --- a/core/src/test/java/google/registry/testing/DatabaseHelper.java +++ b/core/src/test/java/google/registry/testing/DatabaseHelper.java @@ -47,6 +47,7 @@ import static google.registry.util.PreconditionsUtils.checkArgumentPresent; import static google.registry.util.ResourceUtils.readResourceUtf8; import static java.util.Arrays.asList; import static org.joda.money.CurrencyUnit.USD; +import static org.joda.time.DateTimeZone.UTC; import com.google.common.base.Ascii; import com.google.common.base.Splitter; @@ -117,7 +118,6 @@ import javax.annotation.Nullable; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.joda.time.Duration; /** Static utils for setting up test resources. */ @@ -321,7 +321,7 @@ public final class DatabaseHelper { new ReservedList.Builder() .setName(listName) .setReservedListMapFromLines(ImmutableList.copyOf(lines)) - .setCreationTimestamp(DateTime.now(DateTimeZone.UTC)) + .setCreationTimestamp(DateTime.now(UTC)) .build(); return persistReservedList(reservedList); } @@ -342,7 +342,7 @@ public final class DatabaseHelper { PremiumList premiumList = partialPremiumList .asBuilder() - .setCreationTimestamp(DateTime.now(DateTimeZone.UTC)) + .setCreationTimestamp(DateTime.now(UTC)) .setCurrency(currencyUnit) .setLabelsToPrices( entries.entrySet().stream() @@ -1299,8 +1299,7 @@ public final class DatabaseHelper { assertNoDnsRequestsExcept(); } - public static void assertDomainDnsRequestWithRequestTime( - String domainName, DateTime requestTime) { + public static void assertDomainDnsRequestWithRequestTime(String domainName, Instant requestTime) { assertThat( tm().transact( () -> @@ -1312,7 +1311,7 @@ public final class DatabaseHelper { .isEqualTo(1); } - public static void assertDnsRequestsWithRequestTime(DateTime requestTime, int numOfDomains) { + public static void assertDnsRequestsWithRequestTime(Instant requestTime, int numOfDomains) { assertThat( tm().transact( () -> diff --git a/core/src/test/java/google/registry/testing/FakeLockHandler.java b/core/src/test/java/google/registry/testing/FakeLockHandler.java index c2382befb..9e736a05b 100644 --- a/core/src/test/java/google/registry/testing/FakeLockHandler.java +++ b/core/src/test/java/google/registry/testing/FakeLockHandler.java @@ -17,9 +17,9 @@ package google.registry.testing; import static com.google.common.base.Throwables.throwIfUnchecked; import google.registry.request.lock.LockHandler; +import java.time.Duration; import java.util.concurrent.Callable; import javax.annotation.Nullable; -import org.joda.time.Duration; /** A fake {@link LockHandler} where user can control if lock acquisition succeeds. */ public class FakeLockHandler implements LockHandler { diff --git a/core/src/test/java/google/registry/tmch/LordnLogTest.java b/core/src/test/java/google/registry/tmch/LordnLogTest.java index dc8a304c4..c976f85e0 100644 --- a/core/src/test/java/google/registry/tmch/LordnLogTest.java +++ b/core/src/test/java/google/registry/tmch/LordnLogTest.java @@ -19,8 +19,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableList; import google.registry.tmch.LordnLog.Result; +import java.time.Instant; import java.util.Map.Entry; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; /** Unit tests for {@link LordnLog}. */ @@ -28,16 +28,20 @@ class LordnLogTest { private static final ImmutableList EXAMPLE_FROM_RFC = ImmutableList.of( - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," - + "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=," - + "accepted,no-warnings,1", + """ + 1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,\ + 0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,\ + accepted,no-warnings,1\ + """, "roid,result-code", "SH8013-REP,2000"); private static final ImmutableList EXAMPLE_WITH_WARNINGS = ImmutableList.of( - "1,2014-03-21T15:40:08.4Z,2014-03-21T15:35:28.0Z," - + "0000000000000004799,accepted,warnings-present,2", + """ + 1,2014-03-21T15:40:08.4Z,2014-03-21T15:35:28.0Z,\ + 0000000000000004799,accepted,warnings-present,2\ + """, "roid,result-code", "19dc9b4-roid,3610", "1580e26-roid,3610"); @@ -46,8 +50,8 @@ class LordnLogTest { void testSuccess_parseFirstLine() { LordnLog log = LordnLog.parse(EXAMPLE_FROM_RFC); assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED); - assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2012-08-16T02:15:00.0Z")); - assertThat(log.getLordnCreation()).isEqualTo(DateTime.parse("2012-08-16T00:00:00.0Z")); + assertThat(log.getLogCreation()).isEqualTo(Instant.parse("2012-08-16T02:15:00.0Z")); + assertThat(log.getLordnCreation()).isEqualTo(Instant.parse("2012-08-16T00:00:00.0Z")); assertThat(log.getLogId()) .isEqualTo("0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4="); assertThat(log.hasWarnings()).isFalse(); @@ -113,19 +117,16 @@ class LordnLogTest { @Test void testSuccess_toString() { - assertThat(LordnLog.parse(EXAMPLE_WITH_WARNINGS).toString()).isEqualTo( - "LordnLog{" - + "logId=0000000000000004799, " - + "status=ACCEPTED, " - + "logCreation=2014-03-21T15:40:08.400Z, " - + "lordnCreation=2014-03-21T15:35:28.000Z, " - + "hasWarnings=true, " - + "results={" - + "19dc9b4-roid=Result{code=3610, outcome=WARNING, " - + "description=DN reported outside of the time window}, " - + "1580e26-roid=Result{code=3610, outcome=WARNING, " - + "description=DN reported outside of the time window}" - + "}}"); + assertThat(LordnLog.parse(EXAMPLE_WITH_WARNINGS).toString()) + .isEqualTo( + """ + LordnLog{logId=0000000000000004799, status=ACCEPTED, \ + logCreation=2014-03-21T15:40:08.400Z, lordnCreation=2014-03-21T15:35:28Z, \ + hasWarnings=true, results={19dc9b4-roid=Result{code=3610, outcome=WARNING, \ + description=DN reported outside of the time window}, \ + 1580e26-roid=Result{code=3610, outcome=WARNING, \ + description=DN reported outside of the time window}}}\ + """); } @Test @@ -139,8 +140,8 @@ class LordnLogTest { void testSuccess_withWarnings() { LordnLog log = LordnLog.parse(EXAMPLE_WITH_WARNINGS); assertThat(log.getStatus()).isEqualTo(LordnLog.Status.ACCEPTED); - assertThat(log.getLogCreation()).isEqualTo(DateTime.parse("2014-03-21T15:40:08.4Z")); - assertThat(log.getLordnCreation()).isEqualTo(DateTime.parse("2014-03-21T15:35:28.0Z")); + assertThat(log.getLogCreation()).isEqualTo(Instant.parse("2014-03-21T15:40:08.4Z")); + assertThat(log.getLordnCreation()).isEqualTo(Instant.parse("2014-03-21T15:35:28.0Z")); assertThat(log.getLogId()).isEqualTo("0000000000000004799"); assertThat(log.hasWarnings()).isTrue(); diff --git a/core/src/test/java/google/registry/tmch/NordnUploadActionTest.java b/core/src/test/java/google/registry/tmch/NordnUploadActionTest.java index 71eed2020..9f387db39 100644 --- a/core/src/test/java/google/registry/tmch/NordnUploadActionTest.java +++ b/core/src/test/java/google/registry/tmch/NordnUploadActionTest.java @@ -59,9 +59,9 @@ import java.io.ByteArrayOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -87,7 +87,7 @@ class NordnUploadActionTest { private static final String LOCATION_URL = "http://trololol"; - private final FakeClock clock = new FakeClock(DateTime.parse("2010-05-01T10:11:12.000Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2010-05-01T10:11:12.000Z")); private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); private final CloudTasksUtils cloudTasksUtils = cloudTasksHelper.getTestCloudTasksUtils(); @@ -118,7 +118,7 @@ class NordnUploadActionTest { createTld("tld"); persistResource(Tld.get("tld").asBuilder().setLordnUsername("lolcat").build()); persistSunriseModeDomain(); - clock.advanceBy(Duration.standardDays(1)); + clock.advanceBy(Duration.ofDays(1)); persistClaimsModeDomain(); action.clock = clock; action.cloudTasksUtils = cloudTasksUtils; @@ -141,13 +141,13 @@ class NordnUploadActionTest { @Test void testSuccess_nothingScheduled() { persistResource( - ForeignKeyUtils.loadResource(Domain.class, "claims-landrush1.tld", clock.nowUtc()) + ForeignKeyUtils.loadResource(Domain.class, "claims-landrush1.tld", clock.now()) .get() .asBuilder() .setLordnPhase(LordnPhase.NONE) .build()); persistResource( - ForeignKeyUtils.loadResource(Domain.class, "claims-landrush2.tld", clock.nowUtc()) + ForeignKeyUtils.loadResource(Domain.class, "claims-landrush2.tld", clock.now()) .get() .asBuilder() .setLordnPhase(LordnPhase.NONE) @@ -203,7 +203,7 @@ class NordnUploadActionTest { LaunchNotice.create("landrush2tcn", null, null, minusHours(clock.now(), 2))) .setLordnPhase(LordnPhase.CLAIMS) .build()); - clock.advanceBy(Duration.standardDays(1)); + clock.advanceBy(Duration.ofDays(1)); persistResource( newDomain("claims-landrush1.tld") .asBuilder() @@ -223,7 +223,7 @@ class NordnUploadActionTest { .setSmdId("new-smdid") .setLordnPhase(LordnPhase.SUNRISE) .build()); - clock.advanceBy(Duration.standardDays(1)); + clock.advanceBy(Duration.ofDays(1)); persistResource( newDomain("sunrise1.tld") .asBuilder() @@ -234,7 +234,7 @@ class NordnUploadActionTest { } private void verifyColumnCleared(String domainName) { - Domain domain = ForeignKeyUtils.loadResource(Domain.class, domainName, clock.nowUtc()).get(); + Domain domain = ForeignKeyUtils.loadResource(Domain.class, domainName, clock.now()).get(); assertThat(domain.getLordnPhase()).isEqualTo(LordnPhase.NONE); } diff --git a/core/src/test/java/google/registry/tmch/TmchCertificateAuthorityTest.java b/core/src/test/java/google/registry/tmch/TmchCertificateAuthorityTest.java index 6bf4f0b9a..b0798b3e8 100644 --- a/core/src/test/java/google/registry/tmch/TmchCertificateAuthorityTest.java +++ b/core/src/test/java/google/registry/tmch/TmchCertificateAuthorityTest.java @@ -30,7 +30,7 @@ import java.security.SignatureException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateRevokedException; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -51,13 +51,13 @@ class TmchCertificateAuthorityTest { public final JpaIntegrationTestExtension jpa = new JpaTestExtensions.Builder().buildIntegrationTestExtension(); - private final FakeClock clock = new FakeClock(DateTime.parse("2022-11-20T00:00:00Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2022-11-20T00:00:00Z")); @Test void testFailure_prodRootExpired() { TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PRODUCTION, clock); - clock.setTo(DateTime.parse("2500-01-01T00:00:00Z")); + clock.setTo(Instant.parse("2500-01-01T00:00:00Z")); CertificateExpiredException e = assertThrows( CertificateExpiredException.class, tmchCertificateAuthority::getAndValidateRoot); @@ -68,7 +68,7 @@ class TmchCertificateAuthorityTest { void testFailure_prodRootNotYetValid() { TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PRODUCTION, clock); - clock.setTo(DateTime.parse("2000-01-01T00:00:00Z")); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); CertificateNotYetValidException e = assertThrows( CertificateNotYetValidException.class, tmchCertificateAuthority::getAndValidateRoot); diff --git a/core/src/test/java/google/registry/tmch/TmchCrlActionTest.java b/core/src/test/java/google/registry/tmch/TmchCrlActionTest.java index 9b67085d3..6966f0acd 100644 --- a/core/src/test/java/google/registry/tmch/TmchCrlActionTest.java +++ b/core/src/test/java/google/registry/tmch/TmchCrlActionTest.java @@ -28,7 +28,7 @@ import java.net.URL; import java.security.SignatureException; import java.security.cert.CRLException; import java.security.cert.CertificateNotYetValidException; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,7 +45,7 @@ class TmchCrlActionTest extends TmchActionTestCase { @BeforeEach void before() { - clock.setTo(DateTime.parse("2023-03-24TZ")); + clock.setTo(Instant.parse("2023-03-24T00:00:00Z")); } @Test @@ -86,7 +86,7 @@ class TmchCrlActionTest extends TmchActionTestCase { @Test void testFailure_crlNotYetValid() throws Exception { - clock.setTo(DateTime.parse("1984-01-01TZ")); + clock.setTo(Instant.parse("1984-01-01T00:00:00Z")); when(httpUrlConnection.getInputStream()) .thenReturn( new ByteArrayInputStream( diff --git a/core/src/test/java/google/registry/tmch/TmchXmlSignatureTest.java b/core/src/test/java/google/registry/tmch/TmchXmlSignatureTest.java index 14d3dc1be..417ad6ecd 100644 --- a/core/src/test/java/google/registry/tmch/TmchXmlSignatureTest.java +++ b/core/src/test/java/google/registry/tmch/TmchXmlSignatureTest.java @@ -26,8 +26,8 @@ import google.registry.tmch.TmchXmlSignature.CertificateSignatureException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateRevokedException; +import java.time.Instant; import javax.xml.crypto.dsig.XMLSignatureException; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; @@ -59,7 +59,7 @@ class TmchXmlSignatureTest { // // When updating this date, also update the "time travel" dates in two tests below, which test to // make sure that dates before and after the validity window result in rejection. - private final FakeClock clock = new FakeClock(DateTime.parse("2023-01-15T23:15:37.4Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2023-01-15T23:15:37.4Z")); private byte[] smdData; private TmchXmlSignature tmchXmlSignature = @@ -104,14 +104,14 @@ class TmchXmlSignatureTest { @Test void testTimeTravelBeforeCertificateWasCreated() { smdData = loadSmd("smd/active.smd"); - clock.setTo(DateTime.parse("2021-05-01T00:00:00Z")); + clock.setTo(Instant.parse("2021-05-01T00:00:00Z")); assertThrows(CertificateNotYetValidException.class, () -> tmchXmlSignature.verify(smdData)); } @Test void testTimeTravelAfterCertificateHasExpired() { smdData = loadSmd("smd/active.smd"); - clock.setTo(DateTime.parse("2028-06-01T00:00:00Z")); + clock.setTo(Instant.parse("2028-06-01T00:00:00Z")); assertThrows(CertificateExpiredException.class, () -> tmchXmlSignature.verify(smdData)); } diff --git a/core/src/test/java/google/registry/tools/ListCursorsCommandTest.java b/core/src/test/java/google/registry/tools/ListCursorsCommandTest.java index df4b5b017..7bcf35b4c 100644 --- a/core/src/test/java/google/registry/tools/ListCursorsCommandTest.java +++ b/core/src/test/java/google/registry/tools/ListCursorsCommandTest.java @@ -24,7 +24,7 @@ import com.beust.jcommander.ParameterException; import google.registry.model.common.Cursor; import google.registry.model.common.Cursor.CursorType; import google.registry.model.tld.Tld; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,7 +39,7 @@ public class ListCursorsCommandTest extends CommandTestCase @BeforeEach void beforeEach() { - fakeClock.setTo(DateTime.parse("1984-12-21T06:07:08.789Z")); + fakeClock.setTo(Instant.parse("1984-12-21T06:07:08.789Z")); } @Test @@ -58,13 +58,14 @@ public class ListCursorsCommandTest extends CommandTestCase void testListCursors_twoTldsOneAbsent_printsAbsentAndTimestampSorted() throws Exception { createTlds("foo", "bar"); persistResource( - Cursor.createScoped(CursorType.BRDA, DateTime.parse("1984-12-18TZ"), Tld.get("bar"))); + Cursor.createScoped( + CursorType.BRDA, Instant.parse("1984-12-18T00:00:00Z"), Tld.get("bar"))); runCommand("--type=BRDA"); assertThat(getStdoutAsLines()) .containsExactly( HEADER_ONE, HEADER_TWO, - "bar 1984-12-18T00:00:00.000Z 1984-12-21T06:07:08.789Z", + "bar 1984-12-18T00:00:00Z 1984-12-21T06:07:08.789Z", "foo (absent) (absent)") .inOrder(); } @@ -73,7 +74,7 @@ public class ListCursorsCommandTest extends CommandTestCase void testListCursors_badCursor_throwsIae() { ParameterException thrown = assertThrows(ParameterException.class, () -> runCommand("--type=love")); - assertThat(thrown).hasMessageThat().contains("Invalid value for --type parameter."); + assertThat(thrown).hasMessageThat().contains("Invalid value for --type parameter"); } @Test diff --git a/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java b/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java index 8de35b4f9..b0720a8a6 100644 --- a/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java +++ b/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java @@ -26,7 +26,7 @@ import google.registry.model.common.Cursor; import google.registry.model.common.Cursor.CursorType; import google.registry.model.tld.Tld; import google.registry.model.tld.Tld.TldNotFoundException; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -43,21 +43,21 @@ class UpdateCursorsCommandTest extends CommandTestCase { void doUpdateTest() throws Exception { runCommandForced("--type=brda", "--timestamp=1984-12-18T00:00:00Z", "foo"); assertThat(loadByKey(Cursor.createScopedVKey(CursorType.BRDA, registry)).getCursorTime()) - .isEqualTo(DateTime.parse("1984-12-18TZ")); + .isEqualTo(Instant.parse("1984-12-18T00:00:00Z")); String changes = command.prompt(); assertThat(changes) - .isEqualTo("Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z\n"); + .isEqualTo("Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00Z\n"); } void doGlobalUpdateTest() throws Exception { runCommandForced("--type=recurring_billing", "--timestamp=1984-12-18T00:00:00Z"); assertThat(loadByKey(Cursor.createGlobalVKey(CursorType.RECURRING_BILLING)).getCursorTime()) - .isEqualTo(DateTime.parse("1984-12-18TZ")); + .isEqualTo(Instant.parse("1984-12-18T00:00:00Z")); String changes = command.prompt(); assertThat(changes) .isEqualTo( "Change cursorTime of RECURRING_BILLING for Scope:GLOBAL to" - + " 1984-12-18T00:00:00.000Z\n"); + + " 1984-12-18T00:00:00Z\n"); } @Test @@ -68,14 +68,15 @@ class UpdateCursorsCommandTest extends CommandTestCase { @Test void testSuccess_hasOldValue() throws Exception { - persistResource(Cursor.createScoped(CursorType.BRDA, DateTime.parse("1950-12-18TZ"), registry)); + persistResource( + Cursor.createScoped(CursorType.BRDA, Instant.parse("1950-12-18T00:00:00Z"), registry)); doUpdateTest(); } @Test void testSuccess_global_hasOldValue() throws Exception { persistResource( - Cursor.createGlobal(CursorType.RECURRING_BILLING, DateTime.parse("1950-12-18TZ"))); + Cursor.createGlobal(CursorType.RECURRING_BILLING, Instant.parse("1950-12-18T00:00:00Z"))); doGlobalUpdateTest(); } @@ -89,21 +90,22 @@ class UpdateCursorsCommandTest extends CommandTestCase { void testSuccess_multipleTlds_hasOldValue() throws Exception { Tld barRegistry = createTld("bar"); Tld registry2 = Tld.get("bar"); - persistResource(Cursor.createScoped(CursorType.BRDA, DateTime.parse("1950-12-18TZ"), registry)); persistResource( - Cursor.createScoped(CursorType.BRDA, DateTime.parse("1950-12-18TZ"), registry2)); + Cursor.createScoped(CursorType.BRDA, Instant.parse("1950-12-18T00:00:00Z"), registry)); + persistResource( + Cursor.createScoped(CursorType.BRDA, Instant.parse("1950-12-18T00:00:00Z"), registry2)); runCommandForced("--type=brda", "--timestamp=1984-12-18T00:00:00Z", "foo", "bar"); assertThat(loadByKey(Cursor.createScopedVKey(CursorType.BRDA, registry)).getCursorTime()) - .isEqualTo(DateTime.parse("1984-12-18TZ")); + .isEqualTo(Instant.parse("1984-12-18T00:00:00Z")); assertThat(loadByKey(Cursor.createScopedVKey(CursorType.BRDA, barRegistry)).getCursorTime()) - .isEqualTo(DateTime.parse("1984-12-18TZ")); + .isEqualTo(Instant.parse("1984-12-18T00:00:00Z")); String changes = command.prompt(); assertThat(changes) .isEqualTo( """ - Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z - Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00.000Z - """); + Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00Z + Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00Z + """); } @Test @@ -113,16 +115,16 @@ class UpdateCursorsCommandTest extends CommandTestCase { assertThat(loadByKeyIfPresent(Cursor.createScopedVKey(CursorType.BRDA, barRegistry))).isEmpty(); runCommandForced("--type=brda", "--timestamp=1984-12-18T00:00:00Z", "foo", "bar"); assertThat(loadByKey(Cursor.createScopedVKey(CursorType.BRDA, registry)).getCursorTime()) - .isEqualTo(DateTime.parse("1984-12-18TZ")); + .isEqualTo(Instant.parse("1984-12-18T00:00:00Z")); assertThat(loadByKey(Cursor.createScopedVKey(CursorType.BRDA, barRegistry)).getCursorTime()) - .isEqualTo(DateTime.parse("1984-12-18TZ")); + .isEqualTo(Instant.parse("1984-12-18T00:00:00Z")); String changes = command.prompt(); assertThat(changes) .isEqualTo( """ - Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z - Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00.000Z - """); + Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00Z + Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00Z + """); } @Test diff --git a/core/src/test/java/google/registry/tools/server/GenerateZoneFilesActionTest.java b/core/src/test/java/google/registry/tools/server/GenerateZoneFilesActionTest.java index e702db758..b751745d5 100644 --- a/core/src/test/java/google/registry/tools/server/GenerateZoneFilesActionTest.java +++ b/core/src/test/java/google/registry/tools/server/GenerateZoneFilesActionTest.java @@ -23,7 +23,7 @@ import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.TestDataHelper.loadFile; import static google.registry.util.DateTimeUtils.toInstant; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.joda.time.Duration.standardDays; +import static org.joda.time.DateTimeZone.UTC; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; @@ -42,10 +42,9 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.DatabaseHelper; import google.registry.testing.FakeClock; import java.net.InetAddress; +import java.time.Duration; import java.util.Map; import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -70,16 +69,16 @@ class GenerateZoneFilesActionTest { persistResource( Tld.get("tld") .asBuilder() - .setDnsAPlusAaaaTtl(Duration.standardSeconds(300)) - .setDnsNsTtl(Duration.standardSeconds(400)) - .setDnsDsTtl(Duration.standardSeconds(500)) + .setDnsAPlusAaaaTtl(org.joda.time.Duration.standardSeconds(300)) + .setDnsNsTtl(org.joda.time.Duration.standardSeconds(400)) + .setDnsDsTtl(org.joda.time.Duration.standardSeconds(500)) .build()); testGenerate("tldCustomTtl.zone"); } @SuppressWarnings("AddressSelection") void testGenerate(String goldenFileName) throws Exception { - DateTime now = DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay(); + DateTime now = DateTime.now(UTC).withTimeAtStartOfDay(); ImmutableSet ips = ImmutableSet.of(InetAddress.getByName("127.0.0.1"), InetAddress.getByName("::1")); @@ -145,10 +144,10 @@ class GenerateZoneFilesActionTest { GenerateZoneFilesAction action = new GenerateZoneFilesAction(); action.bucket = "zonefiles-bucket"; action.gcsUtils = gcsUtils; - action.databaseRetention = standardDays(29); - action.dnsDefaultATtl = Duration.standardSeconds(11); - action.dnsDefaultNsTtl = Duration.standardSeconds(222); - action.dnsDefaultDsTtl = Duration.standardSeconds(3333); + action.databaseRetention = Duration.ofDays(29); + action.dnsDefaultATtl = Duration.ofSeconds(11); + action.dnsDefaultNsTtl = Duration.ofSeconds(222); + action.dnsDefaultDsTtl = Duration.ofSeconds(3333); action.clock = new FakeClock(now.plusMinutes(2)); // Move past the actions' 2 minute check. Map response = diff --git a/core/src/test/java/google/registry/tools/server/RefreshDnsForAllDomainsActionTest.java b/core/src/test/java/google/registry/tools/server/RefreshDnsForAllDomainsActionTest.java index 07a580030..a11ecff57 100644 --- a/core/src/test/java/google/registry/tools/server/RefreshDnsForAllDomainsActionTest.java +++ b/core/src/test/java/google/registry/tools/server/RefreshDnsForAllDomainsActionTest.java @@ -32,10 +32,10 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; import google.registry.testing.FakeResponse; +import java.time.Duration; import java.util.Optional; import java.util.Random; import org.joda.time.DateTime; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -69,8 +69,8 @@ public class RefreshDnsForAllDomainsActionTest { persistActiveDomain("foo.bar"); persistActiveDomain("low.bar"); action.run(); - assertDomainDnsRequestWithRequestTime("foo.bar", clock.nowUtc()); - assertDomainDnsRequestWithRequestTime("low.bar", clock.nowUtc()); + assertDomainDnsRequestWithRequestTime("foo.bar", clock.now()); + assertDomainDnsRequestWithRequestTime("low.bar", clock.now()); } @Test @@ -86,8 +86,8 @@ public class RefreshDnsForAllDomainsActionTest { Optional.of(7), Optional.empty(), new Random()); - tm().transact(() -> action.refreshBatch(Optional.empty(), Duration.standardMinutes(1000))); - tm().transact(() -> action.refreshBatch(Optional.empty(), Duration.standardMinutes(1000))); + tm().transact(() -> action.refreshBatch(Optional.empty(), Duration.ofMinutes(1000))); + tm().transact(() -> action.refreshBatch(Optional.empty(), Duration.ofMinutes(1000))); ImmutableList refreshRequests = tm().transact( () -> @@ -104,7 +104,7 @@ public class RefreshDnsForAllDomainsActionTest { persistActiveDomain("foo.bar"); persistDeletedDomain("deleted.bar", clock.nowUtc().minusYears(1)); action.run(); - assertDomainDnsRequestWithRequestTime("foo.bar", clock.nowUtc()); + assertDomainDnsRequestWithRequestTime("foo.bar", clock.now()); assertNoDnsRequestsExcept("foo.bar"); } @@ -123,9 +123,9 @@ public class RefreshDnsForAllDomainsActionTest { persistDeletedDomain("deleted3.bar", clock.nowUtc().minusYears(3)); persistDeletedDomain("deleted5.bar", clock.nowUtc().minusYears(5)); action.run(); - assertDomainDnsRequestWithRequestTime("foo.bar", clock.nowUtc()); - assertDomainDnsRequestWithRequestTime("deleted1.bar", clock.nowUtc()); - assertDomainDnsRequestWithRequestTime("deleted3.bar", clock.nowUtc()); + assertDomainDnsRequestWithRequestTime("foo.bar", clock.now()); + assertDomainDnsRequestWithRequestTime("deleted1.bar", clock.now()); + assertDomainDnsRequestWithRequestTime("deleted3.bar", clock.now()); assertNoDnsRequestsExcept("foo.bar", "deleted1.bar", "deleted3.bar"); } @@ -137,8 +137,8 @@ public class RefreshDnsForAllDomainsActionTest { persistActiveDomain("low.bar"); persistActiveDomain("ignore.baz"); action.run(); - assertDomainDnsRequestWithRequestTime("foo.bar", clock.nowUtc()); - assertDomainDnsRequestWithRequestTime("low.bar", clock.nowUtc()); + assertDomainDnsRequestWithRequestTime("foo.bar", clock.now()); + assertDomainDnsRequestWithRequestTime("low.bar", clock.now()); assertNoDnsRequestsExcept("foo.bar", "low.bar"); } @@ -148,6 +148,6 @@ public class RefreshDnsForAllDomainsActionTest { persistActiveDomain(String.format("test%s.bar", i)); } action.run(); - assertDnsRequestsWithRequestTime(clock.nowUtc(), 11); + assertDnsRequestsWithRequestTime(clock.now(), 11); } } diff --git a/core/src/test/java/google/registry/webdriver/ConsoleScreenshotTest.java b/core/src/test/java/google/registry/webdriver/ConsoleScreenshotTest.java index bda22b305..cd7719cde 100644 --- a/core/src/test/java/google/registry/webdriver/ConsoleScreenshotTest.java +++ b/core/src/test/java/google/registry/webdriver/ConsoleScreenshotTest.java @@ -17,6 +17,7 @@ package google.registry.webdriver; import static com.google.common.truth.Truth.assertThat; import static google.registry.server.Fixture.BASIC; import static google.registry.testing.DatabaseHelper.persistResource; +import static java.time.temporal.ChronoUnit.MILLIS; import com.google.common.collect.ImmutableMap; import google.registry.model.console.GlobalRole; @@ -24,7 +25,6 @@ import google.registry.model.console.RegistrarRole; import google.registry.model.registrar.Registrar; import google.registry.server.RegistryTestServer; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Timeout; @@ -80,10 +80,7 @@ public class ConsoleScreenshotTest { server.setRegistrarRoles(ImmutableMap.of("TheRegistrar", RegistrarRole.ACCOUNT_MANAGER)); Registrar registrar = Registrar.loadByRegistrarId("TheRegistrar").get(); registrar = - registrar - .asBuilder() - .setLastPocVerificationDate(Instant.now().truncatedTo(ChronoUnit.MILLIS)) - .build(); + registrar.asBuilder().setLastPocVerificationDate(Instant.now().truncatedTo(MILLIS)).build(); persistResource(registrar); loadHomePage(); } diff --git a/load-testing/src/main/java/google/registry/client/EppClient.java b/load-testing/src/main/java/google/registry/client/EppClient.java index c5a5efc76..6f6d514cc 100644 --- a/load-testing/src/main/java/google/registry/client/EppClient.java +++ b/load-testing/src/main/java/google/registry/client/EppClient.java @@ -15,7 +15,7 @@ package google.registry.client; import static com.google.common.io.Resources.getResource; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.joda.time.DateTimeZone.UTC; +import static java.time.ZoneOffset.UTC; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.JCommander; @@ -54,7 +54,6 @@ import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.time.Duration; -import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Iterator; @@ -71,6 +70,7 @@ import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; /** A simple EPP client that can be used for load testing. */ @Parameters(separators = " =") @@ -261,8 +261,7 @@ public class EppClient implements Runnable { String outputFolder, ImmutableList loggingExecutors) throws IOException { return new ChannelInitializer<>() { - private final ImmutableList inputList = - makeInputList(ZonedDateTime.now(ZoneOffset.UTC)); + private final ImmutableList inputList = makeInputList(ZonedDateTime.now(UTC)); private final KeyPair key = getKeyPair(keyFileName); private final X509Certificate cert = getCertificate(certFileName); private final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO); @@ -317,7 +316,8 @@ public class EppClient implements Runnable { @Override public void run() { - String outputFolder = createOutputFolder(String.format("load-tests/%s", DateTime.now(UTC))); + String outputFolder = + createOutputFolder(String.format("load-tests/%s", DateTime.now(DateTimeZone.UTC))); ImmutableList.Builder builder = ImmutableList.builderWithExpectedSize(5); for (int i = 0; i < 5; ++i) { builder.add(Executors.newSingleThreadExecutor()); @@ -373,8 +373,7 @@ public class EppClient implements Runnable { .awaitUninterruptibly( TIMEOUT_SECONDS * 1000 - Duration.between( - channel.attr(REQUEST_SENT).get().getFirst(), - ZonedDateTime.now(ZoneOffset.UTC)) + channel.attr(REQUEST_SENT).get().getFirst(), ZonedDateTime.now(UTC)) .toMillis())) { channel.close().syncUninterruptibly(); killedConnections.add(channelNumber); diff --git a/load-testing/src/main/java/google/registry/client/EppClientHandler.java b/load-testing/src/main/java/google/registry/client/EppClientHandler.java index e2c9204e8..f18293b66 100644 --- a/load-testing/src/main/java/google/registry/client/EppClientHandler.java +++ b/load-testing/src/main/java/google/registry/client/EppClientHandler.java @@ -23,6 +23,7 @@ import static google.registry.client.EppClient.LOGGING_REQUEST_COMPLETE; import static google.registry.client.EppClient.REQUEST_SENT; import static google.registry.client.EppClient.RESPONSE_RECEIVED; import static java.nio.file.StandardOpenOption.APPEND; +import static java.time.ZoneOffset.UTC; import com.google.common.flogger.FluentLogger; import io.netty.buffer.ByteBuf; @@ -37,7 +38,6 @@ import io.netty.util.concurrent.Promise; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.time.ZoneOffset; import java.time.ZonedDateTime; /** Handler that sends EPP requests and receives EPP responses. */ @@ -75,7 +75,7 @@ public class EppClientHandler extends ChannelDuplexHandler { @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { - ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(UTC); ctx.channel().attr(REQUEST_SENT).get().add(now); ctx.channel().attr(LOGGING_REQUEST_COMPLETE).set(ctx.executor().newPromise()); super.channelRegistered(ctx); @@ -93,7 +93,7 @@ public class EppClientHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { - ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(UTC); Channel ch = ctx.channel(); ctx.channel().attr(RESPONSE_RECEIVED).get().add(now); if (msg instanceof ByteBuf buffer) { @@ -118,7 +118,7 @@ public class EppClientHandler extends ChannelDuplexHandler { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { - ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(UTC); Channel ch = ctx.channel(); ctx.channel().attr(REQUEST_SENT).get().add(now); if (msg instanceof byte[] outputBytes) { diff --git a/proxy/src/main/java/google/registry/proxy/ProxyModule.java b/proxy/src/main/java/google/registry/proxy/ProxyModule.java index 10fdd6166..b11730138 100644 --- a/proxy/src/main/java/google/registry/proxy/ProxyModule.java +++ b/proxy/src/main/java/google/registry/proxy/ProxyModule.java @@ -14,6 +14,7 @@ package google.registry.proxy; + import static com.google.common.base.Preconditions.checkArgument; import static google.registry.proxy.ProxyConfig.getProxyConfig; diff --git a/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java b/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java index c2ee30c0c..320ce09b0 100644 --- a/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java +++ b/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java @@ -17,6 +17,7 @@ package google.registry.proxy.handler; import static com.google.common.truth.Truth.assertThat; import static google.registry.proxy.Protocol.PROTOCOL_KEY; import static google.registry.proxy.handler.EppServiceHandler.CLIENT_CERTIFICATE_HASH_KEY; +import static org.joda.time.DateTimeZone.UTC; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -36,7 +37,6 @@ import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.embedded.EmbeddedChannel; import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,7 +49,7 @@ class EppQuotaHandlerTest { private final EppQuotaHandler handler = new EppQuotaHandler(quotaManager, metrics); private final EmbeddedChannel channel = new EmbeddedChannel(handler); private final String clientCertHash = "blah/123!"; - private final DateTime now = DateTime.now(DateTimeZone.UTC); + private final DateTime now = DateTime.now(UTC); private final Object message = new Object(); private void setProtocol(Channel channel) { diff --git a/util/src/main/java/google/registry/util/InstantTypeAdapter.java b/util/src/main/java/google/registry/util/InstantTypeAdapter.java index f036fd6fe..fec2e8bef 100644 --- a/util/src/main/java/google/registry/util/InstantTypeAdapter.java +++ b/util/src/main/java/google/registry/util/InstantTypeAdapter.java @@ -15,6 +15,7 @@ package google.registry.util; import static google.registry.util.DateTimeUtils.formatInstant; +import static google.registry.util.DateTimeUtils.parseInstant; import com.google.gson.stream.JsonWriter; import java.io.IOException; @@ -27,7 +28,7 @@ public class InstantTypeAdapter extends StringBaseTypeAdapter { @Override protected Instant fromString(String stringValue) throws IOException { try { - return DateTimeUtils.parseInstant(stringValue); + return parseInstant(stringValue); } catch (Exception e) { throw new IOException(e); } diff --git a/util/src/test/java/google/registry/util/DateTimeUtilsTest.java b/util/src/test/java/google/registry/util/DateTimeUtilsTest.java index f62f6221b..c5b574973 100644 --- a/util/src/test/java/google/registry/util/DateTimeUtilsTest.java +++ b/util/src/test/java/google/registry/util/DateTimeUtilsTest.java @@ -19,16 +19,20 @@ import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.earliestDateTimeOf; import static google.registry.util.DateTimeUtils.earliestOf; import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.isBeforeOrAt; +import static google.registry.util.DateTimeUtils.latestDateTimeOf; import static google.registry.util.DateTimeUtils.latestOf; import static google.registry.util.DateTimeUtils.minusMonths; import static google.registry.util.DateTimeUtils.minusYears; +import static google.registry.util.DateTimeUtils.parseInstant; import static google.registry.util.DateTimeUtils.plusMonths; import static google.registry.util.DateTimeUtils.plusYears; import static google.registry.util.DateTimeUtils.toDateTime; import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.toJodaInstant; import static google.registry.util.DateTimeUtils.toLocalDate; import static google.registry.util.DateTimeUtils.toSqlDate; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -49,7 +53,7 @@ class DateTimeUtilsTest { @Test void testSuccess_earliestOf() { assertThat(earliestOf(START_OF_TIME, END_OF_TIME)).isEqualTo(START_OF_TIME); - assertThat(DateTimeUtils.earliestDateTimeOf(sampleDates)).isEqualTo(START_OF_TIME); + assertThat(earliestDateTimeOf(sampleDates)).isEqualTo(START_OF_TIME); } @Test @@ -61,7 +65,7 @@ class DateTimeUtilsTest { @Test void testSuccess_latestOf() { assertThat(latestOf(START_OF_TIME, END_OF_TIME)).isEqualTo(END_OF_TIME); - assertThat(DateTimeUtils.latestDateTimeOf(sampleDates)).isEqualTo(END_OF_TIME); + assertThat(latestDateTimeOf(sampleDates)).isEqualTo(END_OF_TIME); } @Test @@ -136,14 +140,12 @@ class DateTimeUtilsTest { @Test void testFailure_earliestOfEmpty() { - assertThrows( - IllegalArgumentException.class, () -> DateTimeUtils.earliestDateTimeOf(ImmutableList.of())); + assertThrows(IllegalArgumentException.class, () -> earliestDateTimeOf(ImmutableList.of())); } @Test void testFailure_latestOfEmpty() { - assertThrows( - IllegalArgumentException.class, () -> DateTimeUtils.latestDateTimeOf(ImmutableList.of())); + assertThrows(IllegalArgumentException.class, () -> latestDateTimeOf(ImmutableList.of())); } @Test @@ -180,11 +182,11 @@ class DateTimeUtilsTest { .isEqualTo(DateTime.parse("2024-03-27T10:15:30.105Z")); assertThat(toInstant(DateTime.parse("2024-03-27T10:15:30.105Z"))) .isEqualTo(Instant.parse("2024-03-27T10:15:30.105Z")); - assertThat(DateTimeUtils.toJodaInstant(Instant.parse("2024-03-27T10:15:30.105Z"))) + assertThat(toJodaInstant(Instant.parse("2024-03-27T10:15:30.105Z"))) .isEqualTo(org.joda.time.Instant.parse("2024-03-27T10:15:30.105Z")); - assertThat(DateTimeUtils.parseInstant("2024-03-27T10:15:30.105Z")) + assertThat(parseInstant("2024-03-27T10:15:30.105Z")) .isEqualTo(Instant.parse("2024-03-27T10:15:30.105Z")); - assertThat(DateTimeUtils.parseInstant("2024-03-27T10:15:30Z")) + assertThat(parseInstant("2024-03-27T10:15:30Z")) .isEqualTo(Instant.parse("2024-03-27T10:15:30Z")); } } diff --git a/util/src/test/java/google/registry/util/PosixTarHeaderTest.java b/util/src/test/java/google/registry/util/PosixTarHeaderTest.java index 1b0d41bc9..f9e10ec6c 100644 --- a/util/src/test/java/google/registry/util/PosixTarHeaderTest.java +++ b/util/src/test/java/google/registry/util/PosixTarHeaderTest.java @@ -18,6 +18,7 @@ import static com.google.common.io.BaseEncoding.base64; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.joda.time.DateTimeZone.UTC; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.EqualsTester; @@ -27,7 +28,6 @@ import java.io.InputStream; import java.util.Arrays; import java.util.zip.GZIPInputStream; import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; import org.junit.jupiter.api.Test; @@ -203,7 +203,7 @@ class PosixTarHeaderTest { new PosixTarHeader.Builder() .setName("(◕‿◕).txt") .setSize(31337) - .setMtime(DateTime.now(DateTimeZone.UTC)) + .setMtime(DateTime.now(UTC)) .build(); byte[] bytes = header.getBytes(); bytes[150] = '0'; @@ -239,7 +239,7 @@ class PosixTarHeaderTest { new PosixTarHeader.Builder() .setName("(•︵•).txt") // Awwwww! It looks so sad... .setSize(123) - .setMtime(DateTime.now(DateTimeZone.UTC)) + .setMtime(DateTime.now(UTC)) .build()) .testEquals(); }