From b69d51add1737e7f70ddc872e6c730d94194b558 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Fri, 8 May 2026 17:04:00 -0400 Subject: [PATCH] Refactor foundational temporal types to java.time (#3036) * Migrates core classes (Clock, Sleeper, TransactionManager) and extensive domain models from Joda-Time to java.time. * Restores original public API method names while substituting parameters/return values with `java.time.Instant`. * Updates JAXB XJC `bindings.xjb` to natively generate `java.time.Instant` and `java.time.LocalDate`, eliminating `toDateTime` wrapper methods. * Fixes XML serializers (`DateAdapter`) to robustly convert OffsetDateTime timezone strings to UTC. * Cleans up redundant imports and Checkstyle failures across the codebase. Remaining Joda-Time surface area to migrate in future tasks: * Command-line parameters (e.g. `DateTimeParameter`, `DateParameter`, `IntervalParameter`) in `google.registry.tools.params`. * EPP/RDAP flow testing infrastructure (`EppTestCase`, `RdapActionBaseTestCase`, `FlowTestCase`). * Beam pipelines and Load Testing modules (`Spec11PipelineTest`, `RdePipelineTest`, `RegistryJpaReadTest`, `EppClient`). * Utility bridges and converters (`DateTimeUtils.toDateTime/toInstant`, `DateTimeConverter`, `UtcDateTimeAdapter`). * Remaining UI Console tests and Actions. --- GEMINI.md | 8 +- .../main/java/google/registry/util/Clock.java | 5 - .../google/registry/util/DateTimeUtils.java | 117 ++-------- .../java/google/registry/util/Sleeper.java | 42 +--- .../google/registry/util/SystemClock.java | 8 - .../google/registry/util/SystemSleeper.java | 15 +- .../google/registry/testing/FakeClock.java | 41 ++-- .../google/registry/testing/FakeSleeper.java | 10 +- config/presubmits.py | 50 ++--- .../batch/DeleteProberDataAction.java | 22 +- .../registry/batch/RelockDomainAction.java | 4 +- ...ingCertificateNotificationEmailAction.java | 7 +- .../registry/beam/billing/BillingEvent.java | 7 +- .../ExpandBillingRecurrencesPipeline.java | 2 +- .../resave/ResaveAllEppResourcesPipeline.java | 9 +- .../registry/beam/spec11/Spec11Pipeline.java | 9 +- .../registry/config/DelegatedCredentials.java | 5 +- .../registry/config/RegistryConfig.java | 132 ++++++----- .../config/RegistryConfigSettings.java | 4 +- .../registry/config/files/default-config.yaml | 2 +- .../java/google/registry/dns/DnsUtils.java | 3 +- .../dns/writer/clouddns/CloudDnsWriter.java | 3 - .../dns/writer/dnsupdate/DnsUpdateWriter.java | 3 - .../registry/flows/CheckApiMetrics.java | 3 +- .../google/registry/flows/EppMetrics.java | 2 +- .../flows/certs/CertificateChecker.java | 73 +++--- .../flows/domain/DomainCreateFlow.java | 20 +- .../flows/domain/DomainDeleteFlow.java | 33 ++- .../flows/domain/DomainDeletionTimeCache.java | 35 +-- .../flows/domain/DomainFlowUtils.java | 4 +- .../flows/domain/DomainRenewFlow.java | 10 +- .../domain/DomainTransferApproveFlow.java | 5 +- .../domain/DomainTransferRejectFlow.java | 4 +- .../domain/DomainTransferRequestFlow.java | 6 +- .../flows/domain/DomainTransferUtils.java | 3 +- .../registry/loadtest/LoadTestAction.java | 13 +- .../registry/model/EntityYamlUtils.java | 8 +- .../google/registry/model/EppResource.java | 2 +- .../registry/model/EppResourceUtils.java | 68 +----- .../registry/model/ForeignKeyUtils.java | 149 +------------ .../registry/model/OteAccountBuilder.java | 14 +- .../registry/model/ResourceTransferUtils.java | 52 ----- .../model/billing/BillingRecurrence.java | 6 +- .../registry/model/common/FeatureFlag.java | 29 +-- .../model/common/TimedTransitionProperty.java | 112 +--------- .../model/console/ConsoleUpdateHistory.java | 8 +- .../model/console/PasswordResetRequest.java | 17 +- .../registry/model/contact/package-info.java | 1 - .../registry/model/domain/DomainBase.java | 9 +- .../registry/model/domain/DomainCommand.java | 2 +- .../registry/model/domain/RegistryLock.java | 6 +- .../registry/model/domain/package-info.java | 5 +- .../model/domain/token/AllocationToken.java | 6 +- .../registry/model/eppinput/package-info.java | 1 - .../model/eppoutput/package-info.java | 1 - .../registry/model/host/package-info.java | 1 - .../PendingActionNotificationResponse.java | 33 --- .../registry/model/poll/PollMessage.java | 30 --- .../registry/model/poll/package-info.java | 1 - .../registry/model/rde/RdeRevision.java | 25 +-- .../model/reporting/HistoryEntryDao.java | 38 ---- .../model/reporting/Spec11ThreatMatch.java | 2 +- .../model/reporting/Spec11ThreatMatchDao.java | 2 +- .../java/google/registry/model/tld/Tld.java | 82 +++---- .../java/google/registry/model/tld/Tlds.java | 11 - .../model/tld/label/BaseDomainLabelList.java | 8 +- .../model/tld/label/PremiumListDao.java | 3 +- .../model/tld/label/PremiumListUtils.java | 4 +- .../registry/model/transfer/package-info.java | 1 - .../google/registry/module/ServletBase.java | 6 +- .../monitoring/whitebox/CheckApiMetric.java | 14 +- .../monitoring/whitebox/EppMetric.java | 20 +- .../whitebox/StackdriverModule.java | 6 +- .../google/registry/mosapi/MosApiMetrics.java | 2 +- .../converter/DurationUserType.java | 51 ++--- .../converter/LocalDateConverter.java | 38 ---- .../TimedTransitionBaseUserType.java | 4 +- ...elegatingReplicaJpaTransactionManager.java | 6 - .../JpaTransactionManagerImpl.java | 7 - .../transaction/TransactionManager.java | 5 - .../registry/rdap/RdapSearchActionBase.java | 2 +- .../registry/rde/DomainToXjcConverter.java | 16 +- .../registry/rde/HostToXjcConverter.java | 7 +- .../java/google/registry/rde/RdeCounter.java | 6 +- .../google/registry/rde/RdeMarshaller.java | 3 +- .../registry/rde/RegistrarToXjcConverter.java | 5 +- .../reporting/spec11/Spec11Module.java | 3 +- .../Spec11RegistrarThreatMatchesParser.java | 4 +- .../google/registry/request/JsonResponse.java | 4 +- .../registry/request/RequestHandler.java | 8 +- .../registry/request/RequestMetrics.java | 6 +- .../google/registry/request/Response.java | 4 +- .../google/registry/request/ResponseImpl.java | 6 +- .../registry/security/XsrfTokenManager.java | 11 +- .../tmch/TmchCertificateAuthority.java | 8 +- .../registry/tools/CommandUtilities.java | 4 +- .../tools/ConfigureFeatureFlagCommand.java | 5 +- .../registry/tools/ConfigureTldCommand.java | 4 +- .../tools/CreateOrUpdateRegistrarCommand.java | 12 +- .../tools/CreateReservedListCommand.java | 4 +- .../registry/tools/DomainLockUtils.java | 56 +++-- .../tools/GenerateDnsReportCommand.java | 10 +- .../registry/tools/GenerateLordnCommand.java | 7 +- .../tools/GenerateZoneFilesCommand.java | 11 +- .../registry/tools/GetEppResourceCommand.java | 10 +- .../tools/GetHistoryEntriesCommand.java | 2 +- .../java/google/registry/tools/GsonUtils.java | 3 + .../registry/tools/RenewDomainCommand.java | 19 +- .../registry/tools/SetupOteCommand.java | 7 +- .../google/registry/tools/ShellCommand.java | 33 +-- .../tools/UniformRapidSuspensionCommand.java | 8 +- .../registry/tools/UnrenewDomainCommand.java | 38 ++-- .../registry/tools/UpdateCursorsCommand.java | 1 - .../tools/UpdatePremiumListCommand.java | 2 +- .../tools/server/GenerateZoneFilesAction.java | 4 - .../tools/server/ListDomainsAction.java | 2 +- .../server/RefreshDnsForAllDomainsAction.java | 19 +- .../tools/server/ToolsServerModule.java | 8 +- .../ui/server/console/ConsoleApiAction.java | 5 +- .../console/ConsoleDomainGetAction.java | 2 +- .../console/ConsoleDomainListAction.java | 19 +- .../console/ConsoleDumDownloadAction.java | 7 +- .../ui/server/console/ConsoleModule.java | 6 +- .../console/ConsoleRegistryLockAction.java | 4 +- .../console/PasswordResetVerifyAction.java | 2 +- .../java/google/registry/xjc/bindings.xjb | 6 +- .../java/google/registry/xml/DateAdapter.java | 38 ++-- .../main/resources/META-INF/persistence.xml | 1 - .../registry/batch/AsyncTaskEnqueuerTest.java | 2 +- .../batch/BulkDomainTransferActionTest.java | 11 +- .../batch/DeleteProberDataActionTest.java | 5 +- .../batch/RelockDomainActionTest.java | 8 +- .../batch/ResaveEntityActionTest.java | 2 +- ...ertificateNotificationEmailActionTest.java | 86 ++++--- .../batch/SyncRemoteCacheActionTest.java | 8 +- .../ExpandBillingRecurrencesPipelineTest.java | 23 +- .../registry/beam/rde/RdePipelineTest.java | 15 +- .../ResaveAllEppResourcesPipelineTest.java | 42 ++-- .../beam/spec11/Spec11PipelineTest.java | 14 +- .../bsa/BsaDownloadFunctionalTest.java | 4 +- .../bsa/BsaRefreshFunctionalTest.java | 24 +- .../registry/bsa/BsaValidateActionTest.java | 18 +- .../google/registry/bsa/IdnCheckerTest.java | 8 +- .../bsa/ReservedDomainsTestingUtils.java | 8 +- ...UploadBsaUnavailableDomainsActionTest.java | 7 +- .../bsa/persistence/DomainsRefresherTest.java | 2 +- .../bsa/persistence/LabelDiffUpdatesTest.java | 2 +- .../registry/bsa/persistence/QueriesTest.java | 22 +- .../cache/SimplifiedJedisClientTest.java | 7 +- .../dns/RefreshDnsOnHostRenameActionTest.java | 5 +- .../writer/clouddns/CloudDnsWriterTest.java | 19 +- .../writer/dnsupdate/DnsUpdateWriterTest.java | 91 +++----- .../export/ExportDomainListsActionTest.java | 9 +- .../registry/flows/CheckApiActionTest.java | 12 +- .../flows/EppLifecycleDomainTest.java | 3 +- .../registry/flows/EppLifecycleHostTest.java | 4 +- .../registry/flows/EppLoggedOutTest.java | 10 +- .../registry/flows/EppLoginTlsTest.java | 42 ++-- .../registry/flows/EppPointInTimeTest.java | 27 ++- .../google/registry/flows/EppTestCase.java | 57 +++-- .../google/registry/flows/FlowRunnerTest.java | 6 +- .../google/registry/flows/FlowTestCase.java | 6 +- .../registry/flows/ResourceFlowTestCase.java | 11 +- .../registry/flows/TlsCredentialsTest.java | 6 +- .../flows/certs/CertificateCheckerTest.java | 160 +++++++------- .../TestDomainCreateFlowCustomLogic.java | 2 +- .../flows/domain/DomainCheckFlowTest.java | 32 +-- .../flows/domain/DomainCreateFlowTest.java | 16 +- .../flows/domain/DomainDeleteFlowTest.java | 76 +++---- .../domain/DomainDeletionTimeCacheTest.java | 35 ++- .../flows/domain/DomainRenewFlowTest.java | 13 +- .../domain/DomainRestoreRequestFlowTest.java | 11 +- .../domain/DomainTransferApproveFlowTest.java | 39 ++-- .../domain/DomainTransferCancelFlowTest.java | 16 +- .../domain/DomainTransferFlowTestCase.java | 10 +- .../domain/DomainTransferQueryFlowTest.java | 7 +- .../domain/DomainTransferRejectFlowTest.java | 14 +- .../domain/DomainTransferRequestFlowTest.java | 75 +++---- .../flows/domain/DomainUpdateFlowTest.java | 3 +- ...ProductionSimulatingFeeExtensionsTest.java | 6 +- .../flows/host/HostCheckFlowTest.java | 3 +- .../flows/host/HostCreateFlowTest.java | 9 +- .../flows/host/HostDeleteFlowTest.java | 10 +- .../flows/host/HostUpdateFlowTest.java | 20 +- .../registry/flows/poll/PollAckFlowTest.java | 27 ++- .../flows/poll/PollRequestFlowTest.java | 30 ++- .../registry/flows/session/HelloFlowTest.java | 7 +- .../flows/session/LoginFlowTestCase.java | 8 +- .../flows/session/LoginFlowViaTlsTest.java | 14 +- .../registry/model/EppResourceTest.java | 2 +- .../registry/model/EppResourceUtilsTest.java | 9 +- .../registry/model/ForeignKeyUtilsTest.java | 28 +-- .../registry/model/ImmutableObjectTest.java | 13 +- .../registry/model/OteAccountBuilderTest.java | 16 +- .../registry/model/OteStatsTestHelper.java | 39 ++-- .../model/common/FeatureFlagTest.java | 74 +++---- .../common/TimedTransitionPropertyTest.java | 38 ++-- .../console/ConsoleUpdateHistoryTest.java | 10 +- .../registry/model/domain/DomainTest.java | 209 +++++++++--------- .../domain/token/AllocationTokenTest.java | 2 +- .../PollMessageExternalKeyConverterTest.java | 8 +- .../registry/model/poll/PollMessageTest.java | 9 +- .../registry/model/rde/RdeRevisionTest.java | 4 +- .../model/reporting/HistoryEntryDaoTest.java | 15 +- .../reporting/Spec11ThreatMatchDaoTest.java | 6 +- .../reporting/Spec11ThreatMatchTest.java | 5 +- .../model/tld/RegistryLockDaoTest.java | 6 +- .../google/registry/model/tld/TldTest.java | 23 +- .../google/registry/model/tld/TldsTest.java | 14 +- .../model/tld/label/PremiumListDaoTest.java | 22 +- .../model/tld/label/PremiumListUtilsTest.java | 4 +- .../model/tld/label/ReservedListDaoTest.java | 12 +- .../whitebox/CheckApiMetricTest.java | 6 +- ...tionTokenStatusTransitionUserTypeTest.java | 12 +- .../BillingCostTransitionUserTypeTest.java | 10 +- .../converter/DurationUserTypeTest.java | 20 +- .../TimedTransitionBaseUserTypeTest.java | 21 +- .../TldStateTransitionUserTypeTest.java | 14 +- .../DummyJpaTransactionManagerTest.java | 2 +- .../transaction/TransactionManagerTest.java | 8 +- .../registry/rdap/RdapDomainActionTest.java | 32 +-- .../rdap/RdapDomainSearchActionTest.java | 32 +-- .../registry/rdap/RdapJsonFormatterTest.java | 28 +-- .../rdap/RdapNameserverActionTest.java | 11 +- .../rdap/RdapNameserverSearchActionTest.java | 15 +- .../rde/DomainToXjcConverterTest.java | 22 +- .../registry/rde/HostToXjcConverterTest.java | 13 +- .../registry/rde/RdeReportActionTest.java | 13 +- .../rde/RegistrarToXjcConverterTest.java | 5 +- .../billing/GenerateInvoicesActionTest.java | 4 +- .../IcannReportingStagingActionTest.java | 3 +- .../GenerateSpec11ReportActionTest.java | 12 +- .../registry/request/JsonResponseTest.java | 8 + .../registry/request/ResponseImplTest.java | 9 + .../security/XsrfTokenManagerTest.java | 10 +- .../testing/AbstractEppResourceSubject.java | 35 +-- .../registry/testing/DatabaseHelper.java | 159 ++++--------- .../google/registry/testing/FakeResponse.java | 4 +- .../testing/FullFieldsTestEntityHelper.java | 12 +- .../tools/AckPollMessagesCommandTest.java | 46 ++-- .../ConfigureFeatureFlagCommandTest.java | 64 +++--- .../tools/ConfigureTldCommandTest.java | 4 +- .../tools/CountDomainsCommandTest.java | 3 +- ...teOrUpdateReservedListCommandTestCase.java | 6 +- .../tools/CreateRegistrarCommandTest.java | 18 +- .../tools/DeleteFeatureFlagCommandTest.java | 4 +- .../registry/tools/DeleteTldCommandTest.java | 4 +- .../registry/tools/DomainLockUtilsTest.java | 28 +-- .../registry/tools/EppLifecycleToolsTest.java | 13 +- .../GenerateAllocationTokensCommandTest.java | 12 +- .../tools/GenerateLordnCommandTest.java | 12 +- .../tools/GetAllocationTokenCommandTest.java | 7 +- .../registry/tools/GetDomainCommandTest.java | 10 +- .../tools/GetEppResourceCommandTest.java | 11 +- .../tools/GetFeatureFlagCommandTest.java | 33 +-- .../tools/GetHistoryEntriesCommandTest.java | 24 +- .../registry/tools/GetHostCommandTest.java | 6 +- .../registry/tools/GetTldCommandTest.java | 4 +- .../tools/ListFeatureFlagsCommandTest.java | 33 +-- .../tools/RenewDomainCommandTest.java | 33 +-- .../registry/tools/SetupOteCommandTest.java | 11 +- .../tools/UnrenewDomainCommandTest.java | 40 ++-- .../UpdateAllocationTokensCommandTest.java | 38 ++-- .../tools/UpdateRecurrenceCommandTest.java | 14 +- .../tools/UpdateRegistrarCommandTest.java | 4 +- .../tools/UpdateReservedListCommandTest.java | 4 +- .../ValidateEscrowDepositCommandTest.java | 4 +- .../ValidateLoginCredentialsCommandTest.java | 5 +- ...cellationsForBillingEventsCommandTest.java | 7 +- ...RecreateBillingRecurrencesCommandTest.java | 17 +- .../server/GenerateZoneFilesActionTest.java | 21 +- .../tools/server/ListDomainsActionTest.java | 58 ++--- .../RefreshDnsForAllDomainsActionTest.java | 15 +- .../tools/server/ToolsServerModuleTest.java | 6 +- .../console/ConsoleDomainGetActionTest.java | 4 +- .../console/ConsoleDomainListActionTest.java | 20 +- .../console/ConsoleDumDownloadActionTest.java | 7 +- .../console/ConsoleHistoryDataActionTest.java | 50 ++--- .../ConsoleRegistryLockActionTest.java | 26 +-- .../domains/ConsoleBulkDomainActionTest.java | 8 +- .../console/settings/SecurityActionTest.java | 13 +- .../google/registry/xml/DateAdapterTest.java | 11 +- .../google/registry/model/tld/tld.yaml | 18 +- .../resources/google/registry/tools/1tld.yaml | 18 +- .../google/registry/tools/badidn.yaml | 18 +- .../google/registry/tools/badunicode.yaml | 18 +- .../google/registry/tools/diffcostmap.yaml | 18 +- .../google/registry/tools/extrafield.yaml | 18 +- .../resources/google/registry/tools/idns.yaml | 16 +- .../resources/google/registry/tools/jpy.yaml | 18 +- .../registry/tools/missingnullablefields.yaml | 16 +- .../registry/tools/nullablefieldsallnull.yaml | 16 +- .../registry/tools/outoforderfields.yaml | 18 +- .../resources/google/registry/tools/tld.yaml | 18 +- .../google/registry/tools/wildcard.yaml | 18 +- .../handler/SslServerInitializerTest.java | 15 +- .../monitoring/blackbox/ProbingSequence.java | 12 +- .../monitoring/blackbox/token/EppToken.java | 2 +- .../proxy/handler/BackendMetricsHandler.java | 10 +- .../proxy/handler/FrontendMetricsHandler.java | 10 +- .../registry/proxy/metric/BackendMetrics.java | 4 +- .../proxy/metric/FrontendMetrics.java | 4 +- .../registry/proxy/quota/QuotaConfig.java | 6 +- .../registry/proxy/quota/QuotaManager.java | 6 +- .../registry/proxy/quota/TokenStore.java | 43 ++-- .../handler/BackendMetricsHandlerTest.java | 36 +-- .../proxy/handler/EppQuotaHandlerTest.java | 11 +- .../handler/FrontendMetricsHandlerTest.java | 34 +-- .../proxy/metric/BackendMetricsTest.java | 14 +- .../proxy/metric/FrontendMetricsTest.java | 8 +- .../registry/proxy/quota/QuotaConfigTest.java | 9 +- .../proxy/quota/QuotaManagerTest.java | 12 +- .../registry/proxy/quota/TokenStoreTest.java | 106 ++++----- .../registry/util/DurationTypeAdapter.java | 27 +++ .../registry/util/InstantTypeAdapter.java | 2 +- .../java/google/registry/util/Retrier.java | 4 +- .../util/SelfSignedCaCertificate.java | 21 +- .../registry/util/StringBaseTypeAdapter.java | 12 +- .../java/google/registry/util/X509Utils.java | 15 +- .../registry/util/DateTimeUtilsTest.java | 105 ++++----- 320 files changed, 2450 insertions(+), 3488 deletions(-) delete mode 100644 core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java create mode 100644 util/src/main/java/google/registry/util/DurationTypeAdapter.java diff --git a/GEMINI.md b/GEMINI.md index cc88195ce..0c983023c 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -49,7 +49,9 @@ This document outlines foundational mandates, architectural patterns, and projec - **Utility/Cache Methods:** Use `tm().reTransact(...)` for utility methods or Caffeine cache loaders that might be invoked from both transactional and non-transactional paths. - `reTransact` will join an existing transaction if one is present (acting as a no-op) or start a new one if not. - This is particularly useful for in-memory caches where the loader must be able to fetch data regardless of whether the caller is currently in a transaction. - - **Transactional Time:** Ensure code that relies on `tm().getTransactionTime()` is executed within a transaction context. + - **Test Helpers & Timestamps:** If a static test helper method (like in `DatabaseHelper`) needs the database transaction time but might be called from outside a transaction, using `tm().reTransact(tm()::getTxTime)` is acceptable. However, NEVER wrap it redundantly like `tm().transact(() -> tm().reTransact(tm()::getTxTime))`. If you are just setting an arbitrary timestamp in a test where the exact DB transaction time isn't strictly required, prefer `Instant.now()` or `clock.now()` to avoid creating unnecessary database transactions. + - **Production Code:** In production code, if a flow fails because it is calling `getTxTime()` outside of a transaction, you must wrap the *caller* in a transaction instead of adding an unnecessary `reTransact()` around `getTxTime()`. + - **Transactional Time:** Ensure code that relies on `tm().getTransactionTime()` (or `tm().getTxTime()`) is executed within a transaction context. ### 5. Testing Best Practices - **FakeClock and Sleeper:** Use `FakeClock` and `Sleeper` for any logic involving timeouts, delays, or expiration. @@ -94,7 +96,7 @@ This document captures high-level architectural patterns, lessons learned from l - **Dependency Injection:** Dagger 2 is used extensively. If you see "cannot find symbol" errors for classes starting with `Dagger...`, the project is in a state where annotation processing failed. Fix compilation in core models first to restore generated code. - **Value Types:** AutoValue and "ImmutableObject" patterns are dominant. Most models follow a `Buildable` pattern with a nested `Builder`. - **Temporal Logic:** The project is migrating from Joda-Time to `java.time`. - - Core boundaries: `DateTimeUtils.START_OF_TIME_INSTANT` (Unix Epoch) and `END_OF_TIME_INSTANT` (Long.MAX_VALUE / 1000). + - Core boundaries: `DateTimeUtils.START_INSTANT` (Unix Epoch) and `DateTimeUtils.END_INSTANT` (Long.MAX_VALUE / 1000). - Year Arithmetic: Use `DateTimeUtils.plusYears()` and `DateTimeUtils.minusYears()` to handle February 29th logic correctly. ## Source Control @@ -150,7 +152,7 @@ This project treats Error Prone warnings as errors. - **Static Imports:** Methods like `toDateTime`, `toInstant`, `plusYears`, `plusMonths`, and `minusDays` from `DateTimeUtils` MUST be statically imported. Do NOT use them fully qualified (e.g., `DateTimeUtils.plusMonths(...)`). - **Redundant Parses:** Never write `toDateTime(Instant.parse(...))` or `toInstant(DateTime.parse(...))`. If you need a `DateTime`, use `DateTime.parse(...)` directly. If you need an `Instant`, use `Instant.parse(...)` directly. -- **cloneProjectedAtTime vs cloneProjectedAtInstant:** When converting tests and logic that use `clock.now()` to project resource state into the future or past, do not wrap the Java `Instant` in `toDateTime()` just to call `cloneProjectedAtTime()`. Instead, switch the method call to use the native `cloneProjectedAtInstant()` method which is available on all `EppResource` models. +- **cloneProjectedAtTime vs cloneProjectedAtTime:** When converting tests and logic that use `clock.now()` to project resource state into the future or past, do not wrap the Java `Instant` in `toDateTime()` just to call `cloneProjectedAtTime()`. Instead, switch the method call to use the native `cloneProjectedAtTime()` method which is available on all `EppResource` models. - **Do not go in circles with the build:** If you see an `InlineMeSuggester` error, apply the suppression to **ALL** similar methods in that file and related files in one turn. Do not fix them one by one. Furthermore, do not run a global `./gradlew build` when a scoped `./gradlew :core:build` or `./gradlew :core:test` is faster and more appropriate. Run global builds only when doing final verification. - **Exception Conversion in Tests:** When migrating time types (e.g., from Joda `DateTime` to Java `Instant`), be extremely careful with tests that verify parsing failures (e.g., `assertThrows(IllegalArgumentException.class, ...)`). Joda's `DateTime.parse()` throws an `IllegalArgumentException` on failure, but `Instant.parse()` throws a `java.time.format.DateTimeParseException`. You must update the expected exception type in these tests to ensure they actually test the correct behavior, and verify the tests are not failing prematurely on the first line if it contains invalid data meant to be ignored. - Dagger/AutoValue corruption: If you modify a builder or a component incorrectly, Dagger will fail to generate code, leading to hundreds of "cannot find symbol" errors. If this happens, `git checkout` the last working state of the specific file and re-apply changes more surgically. diff --git a/common/src/main/java/google/registry/util/Clock.java b/common/src/main/java/google/registry/util/Clock.java index ba6e8c4b3..8deec023c 100644 --- a/common/src/main/java/google/registry/util/Clock.java +++ b/common/src/main/java/google/registry/util/Clock.java @@ -19,7 +19,6 @@ import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import javax.annotation.concurrent.ThreadSafe; -import org.joda.time.DateTime; /** * A clock that tells the current time in milliseconds or nanoseconds. @@ -32,10 +31,6 @@ import org.joda.time.DateTime; @ThreadSafe public interface Clock extends Serializable { - /** Returns current time in UTC timezone. */ - @Deprecated - DateTime nowUtc(); - /** Returns current Instant (which is always in UTC). */ Instant now(); diff --git a/common/src/main/java/google/registry/util/DateTimeUtils.java b/common/src/main/java/google/registry/util/DateTimeUtils.java index b73c3dbbc..95e8cf3aa 100644 --- a/common/src/main/java/google/registry/util/DateTimeUtils.java +++ b/common/src/main/java/google/registry/util/DateTimeUtils.java @@ -20,8 +20,8 @@ import static org.joda.time.DateTimeZone.UTC; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; -import java.sql.Date; import java.time.Instant; +import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; @@ -31,27 +31,13 @@ import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import javax.annotation.Nullable; import org.joda.time.DateTime; -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, 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); - /** - * A date in the far future that we can treat as infinity. - * - *

This value is (2^63-1)/1000 rounded down. Postgres can store dates as 64 bit microseconds, - * 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, UTC); - /** * An instant in the far future that we can treat as infinity. * @@ -71,7 +57,7 @@ public abstract class DateTimeUtils { */ private static final DateTimeFormatter ISO_8601_FORMATTER = new DateTimeFormatterBuilder() - .appendValue(ChronoField.YEAR, 4, 10, SignStyle.NORMAL) + .appendValue(ChronoField.YEAR, 4, 10, SignStyle.NOT_NEGATIVE) .appendPattern("-MM-dd'T'HH:mm:ss.SSS'Z'") .toFormatter() .withZone(ZoneOffset.UTC); @@ -102,55 +88,28 @@ public abstract class DateTimeUtils { } } - /** Returns the earliest of a number of given {@link DateTime} instances. */ - public static DateTime earliestOf(DateTime first, DateTime... rest) { - return earliestDateTimeOf(Lists.asList(first, rest)); - } - /** Returns the earliest of a number of given {@link Instant} instances. */ public static Instant earliestOf(Instant first, Instant... rest) { return earliestOf(Lists.asList(first, rest)); } - /** Returns the earliest element in a {@link DateTime} iterable. */ - public static DateTime earliestDateTimeOf(Iterable dates) { - checkArgument(!Iterables.isEmpty(dates)); - return Ordering.natural().min(dates); - } - /** Returns the earliest element in a {@link Instant} iterable. */ public static Instant earliestOf(Iterable instants) { checkArgument(!Iterables.isEmpty(instants)); return Ordering.natural().min(instants); } - /** Returns the latest of a number of given {@link DateTime} instances. */ - public static DateTime latestOf(DateTime first, DateTime... rest) { - return latestDateTimeOf(Lists.asList(first, rest)); - } - /** Returns the latest of a number of given {@link Instant} instances. */ public static Instant latestOf(Instant first, Instant... rest) { return latestOf(Lists.asList(first, rest)); } - /** Returns the latest element in a {@link DateTime} iterable. */ - public static DateTime latestDateTimeOf(Iterable dates) { - checkArgument(!Iterables.isEmpty(dates)); - return Ordering.natural().max(dates); - } - /** Returns the latest element in a {@link Instant} iterable. */ public static Instant latestOf(Iterable instants) { checkArgument(!Iterables.isEmpty(instants)); return Ordering.natural().max(instants); } - /** Returns whether the first {@link DateTime} is equal to or earlier than the second. */ - public static boolean isBeforeOrAt(DateTime timeToCheck, DateTime timeToCompareTo) { - return !timeToCheck.isAfter(timeToCompareTo); - } - /** Converts a Joda-Time Duration to a java.time.Duration. */ @Nullable public static java.time.Duration toJavaDuration(@Nullable ReadableDuration duration) { @@ -168,25 +127,11 @@ public abstract class DateTimeUtils { return !timeToCheck.isAfter(timeToCompareTo); } - /** Returns whether the first {@link DateTime} is equal to or later than the second. */ - public static boolean isAtOrAfter(DateTime timeToCheck, DateTime timeToCompareTo) { - return !timeToCheck.isBefore(timeToCompareTo); - } - /** Returns whether the first {@link Instant} is equal to or later than the second. */ public static boolean isAtOrAfter(Instant timeToCheck, Instant timeToCompareTo) { return !timeToCheck.isBefore(timeToCompareTo); } - /** - * Adds years to a date, in the {@code Duration} sense of semantic years. Use this instead of - * {@link DateTime#plusYears} to ensure that we never end up on February 29. - */ - public static DateTime plusYears(DateTime now, int years) { - checkArgument(years >= 0); - return years == 0 ? now : now.plusYears(1).plusYears(years - 1); - } - /** * Adds years to a date, in the {@code Duration} sense of semantic years. Use this instead of * {@link java.time.ZonedDateTime#plusYears} to ensure that we never end up on February 29. @@ -210,15 +155,6 @@ public abstract class DateTimeUtils { return now.atZone(ZoneOffset.UTC).minusMonths(months).toInstant(); } - /** - * Subtracts years from a date, in the {@code Duration} sense of semantic years. Use this instead - * of {@link DateTime#minusYears} to ensure that we never end up on February 29. - */ - public static DateTime minusYears(DateTime now, int years) { - checkArgument(years >= 0); - return years == 0 ? now : now.minusYears(1).minusYears(years - 1); - } - /** * Subtracts years from a date, in the {@code Duration} sense of semantic years. Use this instead * of {@link java.time.ZonedDateTime#minusYears} to ensure that we never end up on February 29. @@ -230,40 +166,9 @@ public abstract class DateTimeUtils { : now.atZone(ZoneOffset.UTC).minusYears(1).minusYears(years - 1).toInstant(); } - /** - * @deprecated Use {@link #plusYears(DateTime, int)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static DateTime leapSafeAddYears(DateTime now, int years) { - return plusYears(now, years); - } - - /** - * @deprecated Use {@link #minusYears(DateTime, int)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static DateTime leapSafeSubtractYears(DateTime now, int years) { - return minusYears(now, years); - } - - public static Date toSqlDate(LocalDate localDate) { - return new Date(localDate.toDateTimeAtStartOfDay().getMillis()); - } - - public static LocalDate toLocalDate(Date date) { - 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); + /** Converts an Instant to a java.time.LocalDate in UTC. */ + public static LocalDate toLocalDate(Instant instant) { + return instant.atZone(ZoneOffset.UTC).toLocalDate(); } /** Convert a joda {@link DateTime} to a java.time {@link Instant}, null-safe. */ @@ -300,11 +205,19 @@ public abstract class DateTimeUtils { return instant.minus(minutes, ChronoUnit.MINUTES); } - public static Instant plusDays(Instant instant, int days) { + public static Instant plusWeeks(Instant instant, int weeks) { + return instant.atZone(ZoneOffset.UTC).plusWeeks(weeks).toInstant(); + } + + public static Instant minusWeeks(Instant instant, int weeks) { + return instant.atZone(ZoneOffset.UTC).minusWeeks(weeks).toInstant(); + } + + public static Instant plusDays(Instant instant, long days) { return instant.atZone(ZoneOffset.UTC).plusDays(days).toInstant(); } - public static Instant minusDays(Instant instant, int days) { + public static Instant minusDays(Instant instant, long days) { return instant.atZone(ZoneOffset.UTC).minusDays(days).toInstant(); } } diff --git a/common/src/main/java/google/registry/util/Sleeper.java b/common/src/main/java/google/registry/util/Sleeper.java index a55c2f5a3..cd8840f4c 100644 --- a/common/src/main/java/google/registry/util/Sleeper.java +++ b/common/src/main/java/google/registry/util/Sleeper.java @@ -16,7 +16,6 @@ package google.registry.util; import java.time.Duration; import javax.annotation.concurrent.ThreadSafe; -import org.joda.time.ReadableDuration; /** * An object which accepts requests to put the current thread to sleep. @@ -31,16 +30,7 @@ public interface Sleeper { * * @throws InterruptedException if this thread was interrupted */ - 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)); - } + void sleep(Duration duration) throws InterruptedException; /** * Puts the current thread to sleep, ignoring interrupts. @@ -50,35 +40,7 @@ public interface Sleeper { * * @see com.google.common.util.concurrent.Uninterruptibles#sleepUninterruptibly */ - 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. - * - *

This is a convenience method for {@link #sleep} that properly converts an {@link - * InterruptedException} to a {@link RuntimeException}. - */ - default void sleepInterruptibly(ReadableDuration duration) { - try { - sleep(duration); - } catch (InterruptedException e) { - // Restore current thread's interrupted state. - Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted.", e); - } - } + void sleepUninterruptibly(Duration duration); /** * Puts the current thread to interruptible sleep. diff --git a/common/src/main/java/google/registry/util/SystemClock.java b/common/src/main/java/google/registry/util/SystemClock.java index 632cdf9be..ac699d754 100644 --- a/common/src/main/java/google/registry/util/SystemClock.java +++ b/common/src/main/java/google/registry/util/SystemClock.java @@ -15,12 +15,10 @@ 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 javax.annotation.concurrent.ThreadSafe; -import org.joda.time.DateTime; /** Clock implementation that proxies to the real system clock. */ @ThreadSafe @@ -31,12 +29,6 @@ public class SystemClock implements Clock { @Inject public SystemClock() {} - /** Returns the current time. */ - @Override - public DateTime nowUtc() { - return DateTime.now(UTC); - } - @Override public Instant now() { // Truncate to milliseconds to match the precision of Joda DateTime and our database schema diff --git a/common/src/main/java/google/registry/util/SystemSleeper.java b/common/src/main/java/google/registry/util/SystemSleeper.java index 0cafc74ab..4459fbeb0 100644 --- a/common/src/main/java/google/registry/util/SystemSleeper.java +++ b/common/src/main/java/google/registry/util/SystemSleeper.java @@ -15,13 +15,12 @@ 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; /** Implementation of {@link Sleeper} for production use. */ @ThreadSafe @@ -33,14 +32,14 @@ public final class SystemSleeper implements Sleeper, Serializable { public SystemSleeper() {} @Override - public void sleep(ReadableDuration duration) throws InterruptedException { - checkArgument(duration.getMillis() >= 0); - Thread.sleep(duration.getMillis()); + public void sleep(Duration duration) throws InterruptedException { + checkArgument(!duration.isNegative(), "Duration must be non-negative"); + Thread.sleep(duration.toMillis()); } @Override - public void sleepUninterruptibly(ReadableDuration duration) { - checkArgument(duration.getMillis() >= 0); - Uninterruptibles.sleepUninterruptibly(toJavaDuration(duration)); + public void sleepUninterruptibly(Duration duration) { + checkArgument(!duration.isNegative(), "Duration must be non-negative"); + Uninterruptibles.sleepUninterruptibly(duration); } } diff --git a/common/src/testing/java/google/registry/testing/FakeClock.java b/common/src/testing/java/google/registry/testing/FakeClock.java index f455fc2ee..bbd43fc2a 100644 --- a/common/src/testing/java/google/registry/testing/FakeClock.java +++ b/common/src/testing/java/google/registry/testing/FakeClock.java @@ -14,16 +14,13 @@ package google.registry.testing; -import static google.registry.util.DateTimeUtils.START_OF_TIME; -import static org.joda.time.DateTimeZone.UTC; -import static org.joda.time.Duration.millis; +import static google.registry.util.DateTimeUtils.START_INSTANT; import google.registry.util.Clock; +import java.time.Duration; import java.time.Instant; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.concurrent.ThreadSafe; -import org.joda.time.DateTime; -import org.joda.time.Duration; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; @@ -39,12 +36,13 @@ public final class FakeClock implements Clock { private volatile long autoIncrementStepMs; - /** Creates a FakeClock that starts at START_OF_TIME. */ + /** Creates a FakeClock that starts at START_INSTANT. */ public FakeClock() { - this(START_OF_TIME); + this(START_INSTANT); } /** Creates a FakeClock initialized to a specific time. */ + @Deprecated public FakeClock(ReadableInstant startTime) { setTo(startTime); } @@ -54,12 +52,6 @@ public final class FakeClock implements Clock { setTo(startTime); } - /** Returns the current time. */ - @Override - public DateTime nowUtc() { - return new DateTime(currentTimeMillis.addAndGet(autoIncrementStepMs), UTC); - } - @Override public Instant now() { return Instant.ofEpochMilli(currentTimeMillis.addAndGet(autoIncrementStepMs)); @@ -74,27 +66,44 @@ public final class FakeClock implements Clock { * @param autoIncrementStep the new auto increment duration * @return this */ + @Deprecated public FakeClock setAutoIncrementStep(ReadableDuration autoIncrementStep) { this.autoIncrementStepMs = autoIncrementStep.getMillis(); return this; } + /** + * Sets the increment applied to the clock whenever it is queried. The increment is zero by + * default: the clock is left unchanged when queried. + * + *

Passing a duration of zero to this method effectively unsets the auto increment mode. + * + * @param autoIncrementStep the new auto increment duration + * @return this + */ + public FakeClock setAutoIncrementStep(Duration autoIncrementStep) { + this.autoIncrementStepMs = autoIncrementStep.toMillis(); + return this; + } + /** Advances clock by one millisecond. */ public void advanceOneMilli() { - advanceBy(millis(1)); + advanceBy(Duration.ofMillis(1)); } /** Advances clock by some duration. */ + @Deprecated public void advanceBy(ReadableDuration duration) { currentTimeMillis.addAndGet(duration.getMillis()); } /** Advances clock by some duration. */ - public void advanceBy(java.time.Duration duration) { + public void advanceBy(Duration duration) { currentTimeMillis.addAndGet(duration.toMillis()); } /** Sets the time to the specified instant. */ + @Deprecated public void setTo(ReadableInstant time) { currentTimeMillis.set(time.getMillis()); } @@ -106,7 +115,7 @@ public final class FakeClock implements Clock { /** Invokes {@link #setAutoIncrementStep} with one millisecond-step. */ public FakeClock setAutoIncrementByOneMilli() { - return setAutoIncrementStep(Duration.millis(1)); + return setAutoIncrementStep(Duration.ofMillis(1)); } /** Disables the auto-increment mode. */ diff --git a/common/src/testing/java/google/registry/testing/FakeSleeper.java b/common/src/testing/java/google/registry/testing/FakeSleeper.java index 2ce63513f..17537e5cd 100644 --- a/common/src/testing/java/google/registry/testing/FakeSleeper.java +++ b/common/src/testing/java/google/registry/testing/FakeSleeper.java @@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull; import google.registry.util.Sleeper; import java.io.Serializable; +import java.time.Duration; import javax.annotation.concurrent.ThreadSafe; -import org.joda.time.ReadableDuration; /** Sleeper implementation for unit tests that advances {@link FakeClock} rather than sleep. */ @ThreadSafe @@ -35,8 +35,8 @@ public final class FakeSleeper implements Sleeper, Serializable { } @Override - public void sleep(ReadableDuration duration) throws InterruptedException { - checkArgument(duration.getMillis() >= 0); + public void sleep(Duration duration) throws InterruptedException { + checkArgument(!duration.isNegative(), "Duration must be non-negative"); if (Thread.interrupted()) { throw new InterruptedException(); } @@ -44,8 +44,8 @@ public final class FakeSleeper implements Sleeper, Serializable { } @Override - public void sleepUninterruptibly(ReadableDuration duration) { - checkArgument(duration.getMillis() >= 0); + public void sleepUninterruptibly(Duration duration) { + checkArgument(!duration.isNegative(), "Duration must be non-negative"); clock.advanceBy(duration); } } diff --git a/config/presubmits.py b/config/presubmits.py index 3defad0e8..3cd715992 100644 --- a/config/presubmits.py +++ b/config/presubmits.py @@ -153,7 +153,15 @@ PRESUBMITS = { PresubmitCheck( r".*java\.util\.Date.*", "java", - {"/node_modules/", "JpaTransactionManagerImpl.java", "DateTimeUtils.java"}, + { + "/node_modules/", + "JpaTransactionManagerImpl.java", + "DateTimeUtils.java", + "SelfSignedCaCertificate.java", + "X509Utils.java", + "TmchCertificateAuthority.java", + "DelegatedCredentials.java" + }, ): "Do not use java.util.Date. Use classes in java.time package instead.", PresubmitCheck( @@ -208,29 +216,29 @@ PRESUBMITS = { ): "Do not double-wrap toInstant(toDateTime(...)).", PresubmitCheck( - r".*toInstant\([^;]*[cC]lock\.nowUtc\(\).*", + r".*toInstant\([^;]*[cC]lock\.now\(\).*", "java", {}, ): - "Do not use toInstant(clock.nowUtc()). Use clock.now() instead.", + "Do not use toInstant(clock.now()). Use clock.now() instead.", PresubmitCheck( r".*toDateTime\([^;]*[cC]lock\.now\(\).*", "java", {}, ): - "Do not use toDateTime(clock.now()). Use clock.nowUtc() instead.", + "Do not use toDateTime(clock.now()). Use clock.now() and Instant overloads instead.", PresubmitCheck( - r".*toInstant\([^;]*tm\(\)\.getTransactionTime\(\).*", + r".*toInstant\([^;]*tm\(\)\.getTxTime\(\).*", "java", {}, ): - "Do not use toInstant(tm().getTransactionTime()). Use tm().getTxTime() instead.", + "Do not use toInstant(tm().getTxTime()). Use tm().getTxTime() instead.", PresubmitCheck( r".*toDateTime\([^;]*tm\(\)\.getTxTime\(\).*", "java", {}, ): - "Do not use toDateTime(tm().getTxTime()). Use tm().getTransactionTime() instead.", + "Do not use toDateTime(tm().getTxTime()). Use tm().getTxTime() and Instant overloads instead.", PresubmitCheck( r".*\(\s*Instant\s*\)\s*(?:this\.)?(?:fakeClock|clock)\.now\(\s*\).*", "java", @@ -266,37 +274,13 @@ PRESUBMITS = { "java", {}, ): - "Do not use cloneProjectedAtTime(toDateTime(...)). Use cloneProjectedAtInstant(...) instead.", + "Do not use cloneProjectedAtTime(toDateTime(...)). Use cloneProjectedAtTime(...) instead.", PresubmitCheck( r".*ZoneId\.of\(\s*\"UTC\"\s*\).*", "java", {}, ): - "Do not use ZoneId.of(\"UTC\"). Use java.time.ZoneOffset.UTC.", - PresubmitCheck( - r".*toDateTime\(\s*END_INSTANT\s*\).*", - "java", - {"DateTimeUtilsTest.java"}, - ): - "Do not wrap END_INSTANT in toDateTime. Use END_OF_TIME.", - PresubmitCheck( - r".*toInstant\(\s*END_OF_TIME\s*\).*", - "java", - {"DateTimeUtilsTest.java"}, - ): - "Do not wrap END_OF_TIME in toInstant. Use END_INSTANT.", - PresubmitCheck( - r".*toDateTime\(\s*START_INSTANT\s*\).*", - "java", - {"DateTimeUtilsTest.java"}, - ): - "Do not wrap START_INSTANT in toDateTime. Use START_OF_TIME.", - PresubmitCheck( - r".*toInstant\(\s*START_OF_TIME\s*\).*", - "java", - {"DateTimeUtilsTest.java"}, - ): - "Do not wrap START_OF_TIME in toInstant. Use START_INSTANT." + "Do not use ZoneId.of(\"UTC\"). Use java.time.ZoneOffset.UTC." } # Note that this regex only works for one kind of Flyway file. If we want to diff --git a/core/src/main/java/google/registry/batch/DeleteProberDataAction.java b/core/src/main/java/google/registry/batch/DeleteProberDataAction.java index 8b946dfa9..71ec09223 100644 --- a/core/src/main/java/google/registry/batch/DeleteProberDataAction.java +++ b/core/src/main/java/google/registry/batch/DeleteProberDataAction.java @@ -27,7 +27,6 @@ import static google.registry.request.Action.Method.POST; import static google.registry.request.RequestParameters.PARAM_BATCH_SIZE; import static google.registry.request.RequestParameters.PARAM_DRY_RUN; import static google.registry.request.RequestParameters.PARAM_TLDS; -import static google.registry.util.DateTimeUtils.toInstant; import static google.registry.util.RegistryEnvironment.PRODUCTION; import com.google.common.base.Strings; @@ -48,11 +47,11 @@ import google.registry.util.Clock; import google.registry.util.RegistryEnvironment; import jakarta.inject.Inject; import jakarta.persistence.TypedQuery; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Deletes all prober {@link Domain}s and their subordinate history entries, poll messages, and @@ -74,7 +73,7 @@ public class DeleteProberDataAction implements Runnable { *

In practice, the prober's connection will time out well before this duration. This includes * a decent buffer. */ - private static final Duration DOMAIN_USED_DURATION = Duration.standardHours(1); + private static final Duration DOMAIN_USED_DURATION = Duration.ofHours(1); /** * The minimum amount of time we want a domain to be "soft deleted". @@ -82,7 +81,7 @@ public class DeleteProberDataAction implements Runnable { *

The domain has to remain soft deleted for at least enough time for the DNS task to run and * remove it from DNS itself. This is probably on the order of minutes. */ - private static final Duration SOFT_DELETE_DELAY = Duration.standardHours(1); + private static final Duration SOFT_DELETE_DELAY = Duration.ofHours(1); // Domains to delete must: // 1. Be in one of the prober TLDs @@ -150,7 +149,7 @@ public class DeleteProberDataAction implements Runnable { AtomicInteger softDeletedDomains = new AtomicInteger(); AtomicInteger hardDeletedDomains = new AtomicInteger(); AtomicReference> domainsBatch = new AtomicReference<>(); - DateTime startTime = clock.nowUtc(); + Instant startTime = clock.now(); do { tm().transact( TRANSACTION_REPEATABLE_READ, @@ -169,7 +168,7 @@ public class DeleteProberDataAction implements Runnable { hardDeletedDomains.get(), batchSize); // Automatically kill the job if it is running for over 20 hours - } while (clock.nowUtc().isBefore(startTime.plusHours(20)) + } while (clock.now().isBefore(startTime.plus(Duration.ofHours(20))) && domainsBatch.get().size() == batchSize); logger.atInfo().log( "%s %d domains.", @@ -183,15 +182,14 @@ public class DeleteProberDataAction implements Runnable { ImmutableSet deletableTlds, AtomicInteger softDeletedDomains, AtomicInteger hardDeletedDomains, - DateTime now) { + Instant now) { TypedQuery query = tm().query(DOMAIN_QUERY_STRING, Domain.class) .setParameter("tlds", deletableTlds) .setParameter( - "creationTimeCutoff", - CreateAutoTimestamp.create(toInstant(now.minus(DOMAIN_USED_DURATION)))) - .setParameter("nowMinusSoftDeleteDelay", toInstant(now.minus(SOFT_DELETE_DELAY))) - .setParameter("now", toInstant(now)); + "creationTimeCutoff", CreateAutoTimestamp.create(now.minus(DOMAIN_USED_DURATION))) + .setParameter("nowMinusSoftDeleteDelay", now.minus(SOFT_DELETE_DELAY)) + .setParameter("now", now); ImmutableList domainList = query.setMaxResults(batchSize).getResultStream().collect(toImmutableList()); ImmutableList.Builder domainRepoIdsToHardDelete = new ImmutableList.Builder<>(); diff --git a/core/src/main/java/google/registry/batch/RelockDomainAction.java b/core/src/main/java/google/registry/batch/RelockDomainAction.java index 278ba785a..616fa9a2f 100644 --- a/core/src/main/java/google/registry/batch/RelockDomainAction.java +++ b/core/src/main/java/google/registry/batch/RelockDomainAction.java @@ -19,7 +19,6 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. 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; @@ -238,8 +237,7 @@ public class RelockDomainAction implements Runnable { } } Duration timeBeforeRetry = previousAttempts < ATTEMPTS_BEFORE_SLOWDOWN ? TEN_MINUTES : ONE_HOUR; - domainLockUtils.enqueueDomainRelock( - toJodaDuration(timeBeforeRetry), oldUnlockRevisionId, previousAttempts + 1); + domainLockUtils.enqueueDomainRelock(timeBeforeRetry, oldUnlockRevisionId, previousAttempts + 1); } private void sendSuccessEmail(RegistryLock oldLock) { diff --git a/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java b/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java index f789aa802..921228a0c 100644 --- a/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java +++ b/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java @@ -16,7 +16,6 @@ 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.PreconditionsUtils.checkArgumentNotNull; import static java.time.ZoneOffset.UTC; import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; @@ -131,11 +130,11 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable registrar, registrar.getClientCertificate().isPresent() && certificateChecker.shouldReceiveExpiringNotification( - toDateTime(registrar.getLastExpiringCertNotificationSentDate()), + registrar.getLastExpiringCertNotificationSentDate(), registrar.getClientCertificate().get()), registrar.getFailoverClientCertificate().isPresent() && certificateChecker.shouldReceiveExpiringNotification( - toDateTime(registrar.getLastExpiringFailoverCertNotificationSentDate()), + registrar.getLastExpiringFailoverCertNotificationSentDate(), registrar.getFailoverClientCertificate().get()))) .filter( registrarInfo -> @@ -155,7 +154,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable Optional certificate) { if (certificate.isEmpty() || !certificateChecker.shouldReceiveExpiringNotification( - toDateTime(lastExpiringCertNotificationSentDate), certificate.get())) { + lastExpiringCertNotificationSentDate, certificate.get())) { return false; } try { 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 02b1dd724..47b52bc71 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 google.registry.util.DateTimeUtils.toLocalDate; import static java.time.ZoneOffset.UTC; import com.google.common.base.Joiner; @@ -23,7 +24,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.time.Instant; -import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.regex.Pattern; import org.apache.beam.sdk.coders.AtomicCoder; @@ -164,11 +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(), UTC).toLocalDate().withDayOfMonth(1).toString(), + toLocalDate(billingTime()).withDayOfMonth(1).toString(), years() == 0 ? "" - : ZonedDateTime.ofInstant(billingTime(), UTC) - .toLocalDate() + : toLocalDate(billingTime()) .withDayOfMonth(1) .plusYears(years()) .minusDays(1) 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 2698d1163..44dd31559 100644 --- a/core/src/main/java/google/registry/beam/billing/ExpandBillingRecurrencesPipeline.java +++ b/core/src/main/java/google/registry/beam/billing/ExpandBillingRecurrencesPipeline.java @@ -311,7 +311,7 @@ public class ExpandBillingRecurrencesPipeline implements Serializable { for (Instant eventTime : eventTimesToExpand) { recurrenceLastExpansionTime = latestOf(recurrenceLastExpansionTime, eventTime); oneTimesToExpandCounter.inc(); - Instant billingTime = eventTime.plusMillis(tld.getAutoRenewGracePeriodLength().getMillis()); + Instant billingTime = eventTime.plus(tld.getAutoRenewGracePeriodLength()); // Note that the DomainHistory is created as of transaction time, as opposed to event time. // This might be counterintuitive because other DomainHistories are created at the time // mutation events occur, such as in DomainDeleteFlow or DomainRenewFlow. Therefore, it is 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 88995a229..77a439e4f 100644 --- a/core/src/main/java/google/registry/beam/resave/ResaveAllEppResourcesPipeline.java +++ b/core/src/main/java/google/registry/beam/resave/ResaveAllEppResourcesPipeline.java @@ -17,7 +17,6 @@ package google.registry.beam.resave; import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.END_INSTANT; -import static google.registry.util.DateTimeUtils.toInstant; import static org.apache.beam.sdk.values.TypeDescriptors.integers; import com.google.common.collect.ImmutableList; @@ -33,6 +32,7 @@ import google.registry.model.host.Host; import google.registry.persistence.PersistenceModule.TransactionIsolationLevel; import google.registry.persistence.VKey; 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.StringUtf8Coder; @@ -43,13 +43,12 @@ import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.util.ShardedKey; import org.apache.beam.sdk.values.KV; -import org.joda.time.DateTime; /** * A Dataflow Flex pipeline that resaves changed EPP resources in SQL. * *

Due to the way that Hibernate works, if an entity is unchanged by {@link - * EppResource#cloneProjectedAtTime(DateTime)} it will not actually be re-persisted to the database. + * EppResource#cloneProjectedAtTime(Instant)} it will not actually be re-persisted to the database. * Thus, the only actual changes occur when objects are changed by projecting them to now, such as * when a pending transfer is resolved. */ @@ -158,14 +157,14 @@ public class ResaveAllEppResourcesPipeline implements Serializable { public void processElement(@Element KV, Iterable> element) { tm().transact( () -> { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); ImmutableList> keys = Streams.stream(element.getValue()) .map(repoId -> VKey.create(clazz, repoId)) .collect(toImmutableList()); ImmutableList mappedResources = tm().loadByKeys(keys).values().stream() - .map(r -> r.cloneProjectedAtTime(toInstant(now))) + .map(r -> r.cloneProjectedAtTime(now)) .collect(toImmutableList()); tm().putAll(mappedResources); }); diff --git a/core/src/main/java/google/registry/beam/spec11/Spec11Pipeline.java b/core/src/main/java/google/registry/beam/spec11/Spec11Pipeline.java index 3e376d9e5..b2a2ee925 100644 --- a/core/src/main/java/google/registry/beam/spec11/Spec11Pipeline.java +++ b/core/src/main/java/google/registry/beam/spec11/Spec11Pipeline.java @@ -35,6 +35,8 @@ import google.registry.util.Retrier; import google.registry.util.UtilsModule; import jakarta.inject.Singleton; import java.io.Serializable; +import java.time.LocalDate; +import java.time.YearMonth; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.coders.KvCoder; @@ -50,9 +52,6 @@ import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.sdk.values.TypeDescriptors; -import org.joda.time.LocalDate; -import org.joda.time.YearMonth; -import org.joda.time.format.ISODateTimeFormat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -76,7 +75,7 @@ public class Spec11Pipeline implements Serializable { * @see google.registry.reporting.spec11.Spec11EmailUtils */ public static String getSpec11ReportFilePath(LocalDate localDate) { - YearMonth yearMonth = new YearMonth(localDate); + YearMonth yearMonth = YearMonth.from(localDate); return String.format("icann/spec11/%s/SPEC11_MONTHLY_REPORT_%s", yearMonth, localDate); } @@ -155,7 +154,7 @@ public class Spec11Pipeline implements Serializable { static void saveToSql( PCollection> threatMatches, Spec11PipelineOptions options) { - LocalDate date = LocalDate.parse(options.getDate(), ISODateTimeFormat.date()); + LocalDate date = LocalDate.parse(options.getDate()); String transformId = "Spec11 Threat Matches"; threatMatches .apply( diff --git a/core/src/main/java/google/registry/config/DelegatedCredentials.java b/core/src/main/java/google/registry/config/DelegatedCredentials.java index 09af7a473..cf3882e4a 100644 --- a/core/src/main/java/google/registry/config/DelegatedCredentials.java +++ b/core/src/main/java/google/registry/config/DelegatedCredentials.java @@ -45,6 +45,7 @@ import java.io.IOException; import java.math.BigDecimal; import java.time.Duration; import java.util.Collection; +import java.util.Date; import java.util.Map; import java.util.ServiceLoader; import org.apache.commons.codec.binary.Base64; @@ -154,7 +155,7 @@ public class DelegatedCredentials extends GoogleCredentials { @Override public AccessToken refreshAccessToken() throws IOException { JsonFactory jsonFactory = JSON_FACTORY; - long currentTime = clock.nowUtc().getMillis(); + long currentTime = clock.now().toEpochMilli(); String assertion = createAssertion(jsonFactory, currentTime); GenericData tokenRequest = new GenericData(); @@ -195,7 +196,7 @@ public class DelegatedCredentials extends GoogleCredentials { GenericData responseData = response.parseAs(GenericData.class); String accessToken = validateString(responseData, "access_token", PARSE_ERROR_PREFIX); int expiresInSeconds = validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX); - return new AccessToken(accessToken, clock.nowUtc().plusSeconds(expiresInSeconds).toDate()); + return new AccessToken(accessToken, Date.from(clock.now().plusSeconds(expiresInSeconds))); } String createAssertion(JsonFactory jsonFactory, long currentTime) throws IOException { diff --git a/core/src/main/java/google/registry/config/RegistryConfig.java b/core/src/main/java/google/registry/config/RegistryConfig.java index 43c89e8cc..aecef3ea3 100644 --- a/core/src/main/java/google/registry/config/RegistryConfig.java +++ b/core/src/main/java/google/registry/config/RegistryConfig.java @@ -18,7 +18,7 @@ import static com.google.common.base.Suppliers.memoize; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSortedMap.toImmutableSortedMap; import static google.registry.config.ConfigUtils.makeUrl; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.ResourceUtils.readResourceUtf8; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.Comparator.naturalOrder; @@ -50,14 +50,14 @@ import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.net.URI; import java.net.URL; +import java.time.Duration; +import java.time.Instant; import java.util.Map.Entry; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.Nullable; -import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; -import org.joda.time.Duration; /** * Central clearing-house for all configuration. @@ -225,7 +225,7 @@ public final class RegistryConfig { */ @Provides @Config("databaseRetention") - public static java.time.Duration provideDatabaseRetention() { + public static Duration provideDatabaseRetention() { return getDatabaseRetention(); } @@ -281,8 +281,8 @@ public final class RegistryConfig { */ @Provides @Config("brdaInterval") - public static java.time.Duration provideBrdaInterval() { - return java.time.Duration.ofDays(7); + public static Duration provideBrdaInterval() { + return Duration.ofDays(7); } /** @@ -315,8 +315,8 @@ public final class RegistryConfig { */ @Provides @Config("publishDnsUpdatesLockDuration") - public static java.time.Duration providePublishDnsUpdatesLockDuration() { - return java.time.Duration.ofMinutes(3); + public static Duration providePublishDnsUpdatesLockDuration() { + return Duration.ofMinutes(3); } /** @@ -343,8 +343,8 @@ public final class RegistryConfig { */ @Provides @Config("readDnsRefreshRequestsActionRuntime") - public static java.time.Duration provideReadDnsRefreshRequestsRuntime() { - return java.time.Duration.ofSeconds(45); + public static Duration provideReadDnsRefreshRequestsRuntime() { + return Duration.ofSeconds(45); } /** @@ -354,8 +354,8 @@ public final class RegistryConfig { */ @Provides @Config("dnsDefaultATtl") - public static java.time.Duration provideDnsDefaultATtl() { - return java.time.Duration.ofHours(1); + public static Duration provideDnsDefaultATtl() { + return Duration.ofHours(1); } /** @@ -365,8 +365,8 @@ public final class RegistryConfig { */ @Provides @Config("dnsDefaultNsTtl") - public static java.time.Duration provideDnsDefaultNsTtl() { - return java.time.Duration.ofHours(3); + public static Duration provideDnsDefaultNsTtl() { + return Duration.ofHours(3); } /** @@ -376,8 +376,8 @@ public final class RegistryConfig { */ @Provides @Config("dnsDefaultDsTtl") - public static java.time.Duration provideDnsDefaultDsTtl() { - return java.time.Duration.ofHours(1); + public static Duration provideDnsDefaultDsTtl() { + return Duration.ofHours(1); } @Provides @@ -757,8 +757,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeInterval") - public static java.time.Duration provideRdeInterval() { - return java.time.Duration.ofDays(1); + public static Duration provideRdeInterval() { + return Duration.ofDays(1); } /** @@ -768,8 +768,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeReportLockTimeout") - public static java.time.Duration provideRdeReportLockTimeout() { - return java.time.Duration.ofMinutes(1); + public static Duration provideRdeReportLockTimeout() { + return Duration.ofMinutes(1); } /** @@ -792,8 +792,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeUploadLockTimeout") - public static java.time.Duration provideRdeUploadLockTimeout() { - return java.time.Duration.ofMinutes(30); + public static Duration provideRdeUploadLockTimeout() { + return Duration.ofMinutes(30); } /** @@ -805,8 +805,8 @@ public final class RegistryConfig { */ @Provides @Config("rdeUploadSftpCooldown") - public static java.time.Duration provideRdeUploadSftpCooldown() { - return java.time.Duration.ofHours(2); + public static Duration provideRdeUploadSftpCooldown() { + return Duration.ofHours(2); } /** @@ -841,8 +841,8 @@ public final class RegistryConfig { */ @Provides @Config("sheetLockTimeout") - public static java.time.Duration provideSheetLockTimeout() { - return java.time.Duration.ofHours(1); + public static Duration provideSheetLockTimeout() { + return Duration.ofHours(1); } /** @@ -865,8 +865,8 @@ public final class RegistryConfig { */ @Provides @Config("emailThrottleDuration") - public static java.time.Duration provideEmailThrottleSeconds(RegistryConfigSettings config) { - return java.time.Duration.ofSeconds(config.misc.emailThrottleSeconds); + public static Duration provideEmailThrottleSeconds(RegistryConfigSettings config) { + return Duration.ofSeconds(config.misc.emailThrottleSeconds); } /** @@ -946,8 +946,8 @@ public final class RegistryConfig { */ @Provides @Config("sshTimeout") - public static java.time.Duration provideSshTimeout() { - return java.time.Duration.ofSeconds(30); + public static Duration provideSshTimeout() { + return Duration.ofSeconds(30); } /** @@ -957,8 +957,8 @@ public final class RegistryConfig { */ @Provides @Config("transactionCooldown") - public static java.time.Duration provideTransactionCooldown() { - return java.time.Duration.ofMinutes(5); + public static Duration provideTransactionCooldown() { + return Duration.ofMinutes(5); } /** @@ -1034,7 +1034,7 @@ public final class RegistryConfig { @Provides @Config("metricsWriteInterval") public static Duration provideMetricsWriteInterval(RegistryConfigSettings config) { - return Duration.standardSeconds(config.monitoring.writeIntervalSeconds); + return Duration.ofSeconds(config.monitoring.writeIntervalSeconds); } /** @@ -1148,8 +1148,8 @@ public final class RegistryConfig { @Provides @Config("tokenRefreshDelay") - public static java.time.Duration provideTokenRefreshDelay(RegistryConfigSettings config) { - return java.time.Duration.ofSeconds(config.credentialOAuth.tokenRefreshDelaySeconds); + public static Duration provideTokenRefreshDelay(RegistryConfigSettings config) { + return Duration.ofSeconds(config.credentialOAuth.tokenRefreshDelaySeconds); } /** OAuth client ID used by the nomulus tool. */ @@ -1186,28 +1186,28 @@ public final class RegistryConfig { @Provides @Config("maxValidityDaysSchedule") - public static ImmutableSortedMap provideValidityDaysMap( + public static ImmutableSortedMap provideValidityDaysMap( RegistryConfigSettings config) { return config.sslCertificateValidation.maxValidityDaysSchedule.entrySet().stream() .collect( toImmutableSortedMap( naturalOrder(), e -> - "START_OF_TIME".equals(e.getKey()) - ? START_OF_TIME - : DateTime.parse(e.getKey()), + "START_INSTANT".equals(e.getKey()) + ? START_INSTANT + : Instant.parse(e.getKey()), Entry::getValue)); } @Provides @Config("expirationWarningDays") - public static int provideExpirationWarningDays(RegistryConfigSettings config) { + public static long provideExpirationWarningDays(RegistryConfigSettings config) { return config.sslCertificateValidation.expirationWarningDays; } @Provides @Config("expirationWarningIntervalDays") - public static int provideExpirationWarningIntervalDays(RegistryConfigSettings config) { + public static long provideExpirationWarningIntervalDays(RegistryConfigSettings config) { return config.sslCertificateValidation.expirationWarningIntervalDays; } @@ -1327,15 +1327,15 @@ public final class RegistryConfig { @Provides @Config("bsaLockLeaseExpiry") - public static java.time.Duration provideBsaLockLeaseExpiry(RegistryConfigSettings config) { - return java.time.Duration.ofMinutes(config.bsa.bsaLockLeaseExpiryMinutes); + public static Duration provideBsaLockLeaseExpiry(RegistryConfigSettings config) { + return Duration.ofMinutes(config.bsa.bsaLockLeaseExpiryMinutes); } /** Returns the desired interval between successive BSA downloads. */ @Provides @Config("bsaDownloadInterval") - public static java.time.Duration provideBsaDownloadInterval(RegistryConfigSettings config) { - return java.time.Duration.ofMinutes(config.bsa.bsaDownloadIntervalMinutes); + public static Duration provideBsaDownloadInterval(RegistryConfigSettings config) { + return Duration.ofMinutes(config.bsa.bsaDownloadIntervalMinutes); } /** @@ -1344,8 +1344,8 @@ public final class RegistryConfig { */ @Provides @Config("bsaMaxNopInterval") - public static java.time.Duration provideBsaMaxNopInterval(RegistryConfigSettings config) { - return java.time.Duration.ofHours(config.bsa.bsaMaxNopIntervalHours); + public static Duration provideBsaMaxNopInterval(RegistryConfigSettings config) { + return Duration.ofHours(config.bsa.bsaMaxNopIntervalHours); } @Provides @@ -1356,16 +1356,14 @@ public final class RegistryConfig { @Provides @Config("domainCreateTxnCommitTimeLag") - public static java.time.Duration provideDomainCreateTxnCommitTimeLag( - RegistryConfigSettings config) { - return java.time.Duration.ofSeconds(config.bsa.domainCreateTxnCommitTimeLagSeconds); + public static Duration provideDomainCreateTxnCommitTimeLag(RegistryConfigSettings config) { + return Duration.ofSeconds(config.bsa.domainCreateTxnCommitTimeLagSeconds); } @Provides @Config("bsaValidationMaxStaleness") - public static java.time.Duration provideBsaValidationMaxStaleness( - RegistryConfigSettings config) { - return java.time.Duration.ofSeconds(config.bsa.bsaValidationMaxStalenessSeconds); + public static Duration provideBsaValidationMaxStaleness(RegistryConfigSettings config) { + return Duration.ofSeconds(config.bsa.bsaValidationMaxStalenessSeconds); } @Provides @@ -1376,8 +1374,8 @@ public final class RegistryConfig { @Provides @Config("bsaAuthTokenExpiry") - public static java.time.Duration provideBsaAuthTokenExpiry(RegistryConfigSettings config) { - return java.time.Duration.ofSeconds(config.bsa.authTokenExpirySeconds); + public static Duration provideBsaAuthTokenExpiry(RegistryConfigSettings config) { + return Duration.ofSeconds(config.bsa.authTokenExpirySeconds); } @Provides @@ -1490,8 +1488,8 @@ public final class RegistryConfig { * * @see google.registry.tools.server.GenerateZoneFilesAction */ - public static java.time.Duration getDatabaseRetention() { - return java.time.Duration.ofDays(30); + public static Duration getDatabaseRetention() { + return Duration.ofDays(30); } public static boolean areServersLocal() { @@ -1507,8 +1505,8 @@ public final class RegistryConfig { } /** Returns the amount of time a singleton should be cached, before expiring. */ - public static java.time.Duration getSingletonCacheRefreshDuration() { - return java.time.Duration.ofSeconds(CONFIG_SETTINGS.get().caching.singletonCacheRefreshSeconds); + public static Duration getSingletonCacheRefreshDuration() { + return Duration.ofSeconds(CONFIG_SETTINGS.get().caching.singletonCacheRefreshSeconds); } /** @@ -1517,13 +1515,13 @@ public final class RegistryConfig { * @see google.registry.model.tld.label.ReservedList * @see google.registry.model.tld.label.PremiumList */ - public static java.time.Duration getDomainLabelListCacheDuration() { - return java.time.Duration.ofSeconds(CONFIG_SETTINGS.get().caching.domainLabelCachingSeconds); + public static Duration getDomainLabelListCacheDuration() { + return Duration.ofSeconds(CONFIG_SETTINGS.get().caching.domainLabelCachingSeconds); } /** Returns the amount of time a singleton should be cached in persist mode, before expiring. */ - public static java.time.Duration getSingletonCachePersistDuration() { - return java.time.Duration.ofSeconds(CONFIG_SETTINGS.get().caching.singletonCachePersistSeconds); + public static Duration getSingletonCachePersistDuration() { + return Duration.ofSeconds(CONFIG_SETTINGS.get().caching.singletonCachePersistSeconds); } /** @@ -1545,8 +1543,8 @@ public final class RegistryConfig { /** * Returns the amount of time an EPP resource or key should be cached in memory before expiring. */ - public static java.time.Duration getEppResourceCachingDuration() { - return java.time.Duration.ofSeconds(CONFIG_SETTINGS.get().caching.eppResourceCachingSeconds); + public static Duration getEppResourceCachingDuration() { + return Duration.ofSeconds(CONFIG_SETTINGS.get().caching.eppResourceCachingSeconds); } /** Returns the maximum number of EPP resources and keys to keep in in-memory cache. */ @@ -1555,8 +1553,8 @@ public final class RegistryConfig { } /** Returns the amount of time that a particular claims list should be cached. */ - public static java.time.Duration getClaimsListCacheDuration() { - return java.time.Duration.ofSeconds(CONFIG_SETTINGS.get().caching.claimsListCachingSeconds); + public static Duration getClaimsListCacheDuration() { + return Duration.ofSeconds(CONFIG_SETTINGS.get().caching.claimsListCachingSeconds); } /** Returns the email address that outgoing emails from the app are sent from. */ diff --git a/core/src/main/java/google/registry/config/RegistryConfigSettings.java b/core/src/main/java/google/registry/config/RegistryConfigSettings.java index c8a84e5ac..1f2331b37 100644 --- a/core/src/main/java/google/registry/config/RegistryConfigSettings.java +++ b/core/src/main/java/google/registry/config/RegistryConfigSettings.java @@ -214,8 +214,8 @@ public class RegistryConfigSettings { /** Configuration for the certificate checker. */ public static class SslCertificateValidation { public Map maxValidityDaysSchedule; - public int expirationWarningDays; - public int expirationWarningIntervalDays; + public long expirationWarningDays; + public long expirationWarningIntervalDays; public int minimumRsaKeyLength; public Set allowedEcdsaCurves; public String expirationWarningEmailBodyText; diff --git a/core/src/main/java/google/registry/config/files/default-config.yaml b/core/src/main/java/google/registry/config/files/default-config.yaml index 0ba35d283..22f751de1 100644 --- a/core/src/main/java/google/registry/config/files/default-config.yaml +++ b/core/src/main/java/google/registry/config/files/default-config.yaml @@ -476,7 +476,7 @@ sslCertificateValidation: # The entry key is the date closest before the date the certificate was issued # and the entry value is the applicable maximum validity days for that certificate. maxValidityDaysSchedule: - "START_OF_TIME": 825 + "START_INSTANT": 825 "2020-09-01T00:00:00Z": 398 # The number of days before a certificate expires that indicates the # certificate is nearing expiration and warnings should be sent. diff --git a/core/src/main/java/google/registry/dns/DnsUtils.java b/core/src/main/java/google/registry/dns/DnsUtils.java index f90994dae..d4db7cb3d 100644 --- a/core/src/main/java/google/registry/dns/DnsUtils.java +++ b/core/src/main/java/google/registry/dns/DnsUtils.java @@ -17,7 +17,6 @@ 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; @@ -151,7 +150,7 @@ public final class DnsUtils { if (tldName.isPresent()) { Tld tld = Tld.get(tldName.get().toString()); if (tld.getDnsAPlusAaaaTtl().isPresent()) { - dnsAPlusAaaaTtl = toJavaDuration(tld.getDnsAPlusAaaaTtl().get()); + dnsAPlusAaaaTtl = tld.getDnsAPlusAaaaTtl().get(); } } return dnsAPlusAaaaTtl.toSeconds(); 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 4d947c3cd..baa93fd20 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,7 +44,6 @@ 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; @@ -151,7 +150,6 @@ public class CloudDnsWriter extends BaseDnsWriter { .setTtl( (int) tld.getDnsDsTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(defaultDsTtl) .toSeconds()) .setType("DS") @@ -179,7 +177,6 @@ public class CloudDnsWriter extends BaseDnsWriter { .setTtl( (int) tld.getDnsNsTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(defaultNsTtl) .toSeconds()) .setType("NS") 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 2c66a33b5..0c1b14147 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,7 +34,6 @@ 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; @@ -196,7 +195,6 @@ public class DnsUpdateWriter extends BaseDnsWriter { toAbsoluteName(domain.getDomainName()), DClass.IN, tld.getDnsDsTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(dnsDefaultDsTtl) .toSeconds(), signerData.getKeyTag(), @@ -239,7 +237,6 @@ public class DnsUpdateWriter extends BaseDnsWriter { toAbsoluteName(domain.getDomainName()), DClass.IN, tld.getDnsNsTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(dnsDefaultNsTtl) .toSeconds(), toAbsoluteName(hostName)); diff --git a/core/src/main/java/google/registry/flows/CheckApiMetrics.java b/core/src/main/java/google/registry/flows/CheckApiMetrics.java index 6508e8a8d..365979f4a 100644 --- a/core/src/main/java/google/registry/flows/CheckApiMetrics.java +++ b/core/src/main/java/google/registry/flows/CheckApiMetrics.java @@ -60,7 +60,8 @@ public class CheckApiMetrics { } public void recordProcessingTime(CheckApiMetric metric) { - long elapsedTime = metric.endTimestamp().getMillis() - metric.startTimestamp().getMillis(); + long elapsedTime = + metric.endTimestamp().toEpochMilli() - metric.startTimestamp().toEpochMilli(); processingTime.record( elapsedTime, metric.tier().map(Tier::getDisplayLabel).orElse(""), diff --git a/core/src/main/java/google/registry/flows/EppMetrics.java b/core/src/main/java/google/registry/flows/EppMetrics.java index 76968f5ee..66af33a2f 100644 --- a/core/src/main/java/google/registry/flows/EppMetrics.java +++ b/core/src/main/java/google/registry/flows/EppMetrics.java @@ -98,7 +98,7 @@ public class EppMetrics { String eppStatusCode = metric.getStatus().isPresent() ? String.valueOf(metric.getStatus().get().code) : ""; long processingTime = - metric.getEndTimestamp().getMillis() - metric.getStartTimestamp().getMillis(); + metric.getEndTimestamp().toEpochMilli() - metric.getStartTimestamp().toEpochMilli(); String commandName = metric.getCommandName().orElse(""); String tld = metric.getTld().orElse(""); requestTime.record(processingTime, commandName, getTrafficType(tld).toString(), eppStatusCode); diff --git a/core/src/main/java/google/registry/flows/certs/CertificateChecker.java b/core/src/main/java/google/registry/flows/certs/CertificateChecker.java index c9ad04001..02e4e5109 100644 --- a/core/src/main/java/google/registry/flows/certs/CertificateChecker.java +++ b/core/src/main/java/google/registry/flows/certs/CertificateChecker.java @@ -15,15 +15,15 @@ package google.registry.flows.certs; import static com.google.common.base.Preconditions.checkArgument; -import static google.registry.util.DateTimeUtils.START_OF_TIME; -import static google.registry.util.DateTimeUtils.toDateTime; +import static google.registry.util.DateTimeUtils.START_INSTANT; +import static google.registry.util.DateTimeUtils.plusDays; +import static google.registry.util.DateTimeUtils.toLocalDate; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import google.registry.config.RegistryConfig.Config; import google.registry.util.Clock; -import google.registry.util.DateTimeUtils; import jakarta.inject.Inject; import java.io.ByteArrayInputStream; import java.io.StringWriter; @@ -33,6 +33,8 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPublicKey; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.stream.Collectors; import org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util; import org.bouncycastle.jce.ECNamedCurveTable; @@ -41,51 +43,49 @@ import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator; import org.bouncycastle.util.io.pem.PemObjectGenerator; import org.bouncycastle.util.io.pem.PemWriter; -import org.joda.time.DateTime; -import org.joda.time.DateTimeComparator; -import org.joda.time.Days; /** A utility to check that a given certificate meets our requirements */ public class CertificateChecker { - private final ImmutableSortedMap maxValidityLengthSchedule; - private final int expirationWarningDays; + private final ImmutableSortedMap maxValidityLengthSchedule; + private final long expirationWarningDays; private final int minimumRsaKeyLength; private final Clock clock; private final ImmutableSet allowedEcdsaCurves; - private final int expirationWarningIntervalDays; + private final long expirationWarningIntervalDays; /** * Constructs a CertificateChecker instance with the specified configuration parameters. * - *

The max validity length schedule is a sorted map of {@link DateTime} to {@link Integer} + *

The max validity length schedule is a sorted map of {@link Instant} to {@link Integer} * entries representing a maximum validity period for certificates issued on or after that date. - * The first entry must have a key of {@link DateTimeUtils#START_OF_TIME}, such that every - * possible date has an applicable max validity period. Since security requirements tighten over - * time, the max validity periods will be decreasing as the date increases. + * The first entry must have a key of {@link google.registry.util.DateTimeUtils#START_INSTANT}, + * such that every possible date has an applicable max validity period. Since security + * requirements tighten over time, the max validity periods will be decreasing as the date + * increases. * *

The validity length schedule used by all major Web browsers as of 2020Q4 would be * represented as: * *

    *   ImmutableSortedMap.of(
-   *     START_OF_TIME, 825,
-   *     DateTime.parse("2020-09-01T00:00:00Z"), 398
+   *     START_INSTANT, 825,
+   *     Instant.parse("2020-09-01T00:00:00Z"), 398
    *   );
    * 
*/ @Inject public CertificateChecker( @Config("maxValidityDaysSchedule") - ImmutableSortedMap maxValidityDaysSchedule, - @Config("expirationWarningDays") int expirationWarningDays, - @Config("expirationWarningIntervalDays") int expirationWarningIntervalDays, + ImmutableSortedMap maxValidityDaysSchedule, + @Config("expirationWarningDays") long expirationWarningDays, + @Config("expirationWarningIntervalDays") long expirationWarningIntervalDays, @Config("minimumRsaKeyLength") int minimumRsaKeyLength, @Config("allowedEcdsaCurves") ImmutableSet allowedEcdsaCurves, Clock clock) { checkArgument( - maxValidityDaysSchedule.containsKey(START_OF_TIME), - "Max validity length schedule must contain an entry for START_OF_TIME"); + maxValidityDaysSchedule.containsKey(START_INSTANT), + "Max validity length schedule must contain an entry for START_INSTANT"); this.maxValidityLengthSchedule = maxValidityDaysSchedule; this.expirationWarningDays = expirationWarningDays; this.minimumRsaKeyLength = minimumRsaKeyLength; @@ -94,10 +94,10 @@ public class CertificateChecker { this.clock = clock; } - private static int getValidityLengthInDays(X509Certificate certificate) { - DateTime start = toDateTime(certificate.getNotBefore().toInstant()); - DateTime end = toDateTime(certificate.getNotAfter().toInstant()); - return Days.daysBetween(start.withTimeAtStartOfDay(), end.withTimeAtStartOfDay()).getDays(); + private static long getValidityLengthInDays(X509Certificate certificate) { + return ChronoUnit.DAYS.between( + toLocalDate(certificate.getNotBefore().toInstant()), + toLocalDate(certificate.getNotAfter().toInstant())); } /** Checks if the curve used for a public key is in the list of acceptable curves. */ @@ -159,16 +159,16 @@ public class CertificateChecker { ImmutableSet.Builder violations = new ImmutableSet.Builder<>(); // Check if currently in validity period - DateTime now = clock.nowUtc(); - if (DateTimeComparator.getInstance().compare(certificate.getNotAfter(), now) < 0) { + Instant now = clock.now(); + if (certificate.getNotAfter().toInstant().isBefore(now)) { violations.add(CertificateViolation.EXPIRED); - } else if (DateTimeComparator.getInstance().compare(certificate.getNotBefore(), now) > 0) { + } else if (certificate.getNotBefore().toInstant().isAfter(now)) { violations.add(CertificateViolation.NOT_YET_VALID); } // Check validity period length - int maxValidityDays = - maxValidityLengthSchedule.floorEntry(new DateTime(certificate.getNotBefore())).getValue(); + long maxValidityDays = + maxValidityLengthSchedule.floorEntry(certificate.getNotBefore().toInstant()).getValue(); if (getValidityLengthInDays(certificate) > maxValidityDays) { violations.add(CertificateViolation.VALIDITY_LENGTH_TOO_LONG); } @@ -225,25 +225,24 @@ public class CertificateChecker { /** Returns whether the client should receive a notification email. */ public boolean shouldReceiveExpiringNotification( - DateTime lastExpiringNotificationSentDate, String certificateStr) { + Instant lastExpiringNotificationSentDate, String certificateStr) { X509Certificate certificate = getCertificate(certificateStr); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); // the expiration date is one day after lastValidDate - DateTime lastValidDate = new DateTime(certificate.getNotAfter()); + Instant lastValidDate = certificate.getNotAfter().toInstant(); if (lastValidDate.isBefore(now)) { return false; } /* * Client should receive a notification if: * 1) client has never received notification (lastExpiringNotificationSentDate is initially - * set to START_OF_TIME) and the certificate has entered the expiring period, OR + * set to START_INSTANT) and the certificate has entered the expiring period, OR * 2) client has received notification but the interval between now and * lastExpiringNotificationSentDate is greater than expirationWarningIntervalDays. */ - return !lastValidDate.isAfter(now.plusDays(expirationWarningDays)) - && (lastExpiringNotificationSentDate.equals(START_OF_TIME) - || !lastExpiringNotificationSentDate - .plusDays(expirationWarningIntervalDays) + return !lastValidDate.isAfter(plusDays(now, expirationWarningDays)) + && (lastExpiringNotificationSentDate.equals(START_INSTANT) + || !plusDays(lastExpiringNotificationSentDate, expirationWarningIntervalDays) .isAfter(now)); } diff --git a/core/src/main/java/google/registry/flows/domain/DomainCreateFlow.java b/core/src/main/java/google/registry/flows/domain/DomainCreateFlow.java index ec564e971..a36690edf 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainCreateFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainCreateFlow.java @@ -53,7 +53,6 @@ import static google.registry.model.tld.label.ReservationType.NAME_COLLISION; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.plusYears; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -121,10 +120,9 @@ import google.registry.model.tmch.ClaimsList; import google.registry.model.tmch.ClaimsListDao; import google.registry.tmch.LordnTaskUtils.LordnPhase; 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; /** * An EPP flow that creates a new domain resource. @@ -565,7 +563,7 @@ public final class DomainCreateFlow implements MutatingFlow { ImmutableSet.of( DomainTransactionRecord.create( tld.getTldStr(), - now.plusMillis(addGracePeriod.getMillis()), + now.plus(addGracePeriod), TransactionReportField.netAddsFieldFromYears(period.getValue()), 1))); } @@ -603,11 +601,10 @@ public final class DomainCreateFlow implements MutatingFlow { .setEventTime(now) .setAllocationToken(allocationToken.map(AllocationToken::createVKey).orElse(null)) .setBillingTime( - now.plusMillis( - (isAnchorTenant - ? tld.getAnchorTenantAddGracePeriodLength() - : tld.getAddGracePeriodLength()) - .getMillis())) + now.plus( + isAnchorTenant + ? tld.getAnchorTenantAddGracePeriodLength() + : tld.getAddGracePeriodLength())) .setFlags(flagsBuilder.build()) .setDomainHistoryId(domainHistoryId) .build(); @@ -652,10 +649,9 @@ public final class DomainCreateFlow implements MutatingFlow { } private void verifyDomainDoesNotExist() throws ResourceCreateContentionException { - Optional previousDeletionTime = + Optional previousDeletionTime = domainDeletionTimeCache.getDeletionTimeForDomain(targetId); - if (previousDeletionTime.isPresent() - && !tm().getTxTime().isAfter(toInstant(previousDeletionTime.get()))) { + if (previousDeletionTime.isPresent() && !tm().getTxTime().isAfter(previousDeletionTime.get())) { throw new ResourceCreateContentionException(targetId); } } 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 1b1ac8f4e..8a1347190 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainDeleteFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainDeleteFlow.java @@ -40,9 +40,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.pricing.PricingEngineProxy.getDomainRenewCost; 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 static google.registry.util.DateTimeUtils.minusYears; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -101,14 +99,13 @@ import google.registry.model.tld.Tld; import google.registry.model.tld.Tld.TldType; import google.registry.model.transfer.TransferStatus; import jakarta.inject.Inject; +import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.joda.money.Money; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * An EPP flow that deletes a domain. @@ -172,10 +169,9 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging eppInput.getSingleExtension(DomainDeleteSuperuserExtension.class); if (domainDeleteSuperuserExtension.isPresent()) { redemptionGracePeriodLength = - Duration.standardDays( - domainDeleteSuperuserExtension.get().getRedemptionGracePeriodDays()); + Duration.ofDays(domainDeleteSuperuserExtension.get().getRedemptionGracePeriodDays()); pendingDeleteLength = - Duration.standardDays(domainDeleteSuperuserExtension.get().getPendingDeleteDays()); + Duration.ofDays(domainDeleteSuperuserExtension.get().getPendingDeleteDays()); } boolean inAddGracePeriod = existingDomain.getGracePeriodStatuses().contains(GracePeriodStatus.ADD); @@ -188,11 +184,11 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging : redemptionGracePeriodLength.plus(pendingDeleteLength); HistoryEntryId domainHistoryId = createHistoryEntryId(existingDomain); historyBuilder.setRevisionId(domainHistoryId.getRevisionId()); - Instant deletionTime = now.plusMillis(durationUntilDelete.getMillis()); + Instant deletionTime = now.plus(durationUntilDelete); if (durationUntilDelete.equals(Duration.ZERO)) { builder.setDeletionTime(now).setStatusValues(null); } else { - Instant redemptionTime = now.plusMillis(redemptionGracePeriodLength.getMillis()); + Instant redemptionTime = now.plus(redemptionGracePeriodLength); asyncTaskEnqueuer.enqueueAsyncResave( existingDomain.createVKey(), now, ImmutableSortedSet.of(redemptionTime, deletionTime)); builder @@ -217,7 +213,7 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging // Enqueue the deletion poll message if the delete is asynchronous or if requested by a // superuser (i.e. the registrar didn't request this delete and thus should be notified even if // it is synchronous). - if (durationUntilDelete.isLongerThan(Duration.ZERO) || isSuperuser) { + if (durationUntilDelete.compareTo(Duration.ZERO) > 0 || isSuperuser) { if (RegistryConfig.getNoPollMessageOnDeletionRegistrarIds() .contains(existingDomain.getCurrentSponsorRegistrarId())) { logger.atInfo().log( @@ -233,7 +229,7 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging // Send a second poll message immediately if the domain is being deleted asynchronously by a // registrar other than the sponsoring registrar (which will necessarily be a superuser). - if (durationUntilDelete.isLongerThan(Duration.ZERO) + if (durationUntilDelete.compareTo(Duration.ZERO) > 0 && !registrarId.equals(existingDomain.getPersistedCurrentSponsorRegistrarId())) { entitiesToInsert.add( createImmediateDeletePollMessage(existingDomain, domainHistoryId, now, deletionTime)); @@ -250,12 +246,11 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging // Take the amount of registration time being refunded off the expiration time. // This can be either add grace periods or renew grace periods. BillingEvent billingEvent = tm().loadByKey(gracePeriod.getBillingEvent()); - newExpirationTime = - newExpirationTime.atZone(UTC).minusYears(billingEvent.getPeriodYears()).toInstant(); + newExpirationTime = minusYears(newExpirationTime, billingEvent.getPeriodYears()); } 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(UTC).minusYears(1).toInstant(); + newExpirationTime = minusYears(newExpirationTime, 1); } } } @@ -343,7 +338,7 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging cancelledRecords, DomainTransactionRecord.create( domain.getTld(), - now.plusMillis(durationUntilDelete.getMillis()), + now.plus(durationUntilDelete), inAddGracePeriod ? TransactionReportField.DELETED_DOMAINS_GRACE : TransactionReportField.DELETED_DOMAINS_NOGRACE, @@ -420,9 +415,9 @@ public final class DomainDeleteFlow implements MutatingFlow, SqlStatementLogging BillingRecurrence billingRecurrence, GracePeriod gracePeriod, Instant now) { if (gracePeriod.getType() == GracePeriodStatus.AUTO_RENEW) { // If we updated the autorenew billing event, reuse it. - DateTime autoRenewTime = - toDateTime(billingRecurrence.getRecurrenceTimeOfYear().getLastInstanceBeforeOrAt(now)); - return getDomainRenewCost(targetId, toInstant(autoRenewTime), 1); + Instant autoRenewTime = + billingRecurrence.getRecurrenceTimeOfYear().getLastInstanceBeforeOrAt(now); + return getDomainRenewCost(targetId, autoRenewTime, 1); } return tm().loadByKey(checkNotNull(gracePeriod.getBillingEvent())).getCost(); } diff --git a/core/src/main/java/google/registry/flows/domain/DomainDeletionTimeCache.java b/core/src/main/java/google/registry/flows/domain/DomainDeletionTimeCache.java index 361e2dc7f..44831b7b9 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainDeletionTimeCache.java +++ b/core/src/main/java/google/registry/flows/domain/DomainDeletionTimeCache.java @@ -15,6 +15,7 @@ package google.registry.flows.domain; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; +import static google.registry.util.DateTimeUtils.END_INSTANT; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.Caffeine; @@ -24,9 +25,10 @@ import com.github.benmanes.caffeine.cache.Ticker; import com.google.common.collect.ImmutableSet; import google.registry.model.ForeignKeyUtils; import google.registry.model.domain.Domain; -import google.registry.util.DateTimeUtils; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Optional; -import org.joda.time.DateTime; /** * Functionally-static loading cache that keeps track of deletion (AKA drop) times for domains. @@ -39,7 +41,7 @@ import org.joda.time.DateTime; * *

The cache is fairly short-lived (as we're concerned about many requests at basically the same * time), and entries also expire when the drop actually happens. If the domain is re-created after - * a drop, the next load attempt will populate the cache with a deletion time of END_OF_TIME, which + * a drop, the next load attempt will populate the cache with a deletion time of END_INSTANT, which * will be read from the cache by subsequent attempts. * *

We take advantage of the fact that Caffeine caches don't store nulls returned from the @@ -57,8 +59,7 @@ import org.joda.time.DateTime; public class DomainDeletionTimeCache { // Max expiry time is ten minutes - private static final long NANOS_IN_ONE_MILLISECOND = 100000L; - private static final long MAX_EXPIRY_NANOS = 10L * 60L * 1000L * NANOS_IN_ONE_MILLISECOND; + private static final long MAX_EXPIRY_NANOS = Duration.ofMinutes(10).toNanos(); private static final int MAX_ENTRIES = 500; /** @@ -69,15 +70,15 @@ public class DomainDeletionTimeCache { * *

NB: the Expiry class requires the return value in nanoseconds, not milliseconds */ - private static final Expiry EXPIRY_POLICY = + private static final Expiry EXPIRY_POLICY = new Expiry<>() { @Override - public long expireAfterCreate(String key, DateTime value, long currentTime) { + public long expireAfterCreate(String key, Instant value, long currentTime) { // Watch out for Long overflow long deletionTimeNanos = - value.equals(DateTimeUtils.END_OF_TIME) + value.equals(END_INSTANT) ? Long.MAX_VALUE - : value.getMillis() * NANOS_IN_ONE_MILLISECOND; + : ChronoUnit.NANOS.between(Instant.EPOCH, value); long nanosUntilDeletion = deletionTimeNanos - currentTime; return Math.max(0L, Math.min(MAX_EXPIRY_NANOS, nanosUntilDeletion)); } @@ -85,31 +86,31 @@ public class DomainDeletionTimeCache { /** Reset the time entirely on update, as if we were creating the entry anew. */ @Override public long expireAfterUpdate( - String key, DateTime value, long currentTime, long currentDuration) { + String key, Instant value, long currentTime, long currentDuration) { return expireAfterCreate(key, value, currentTime); } /** Reads do not change the expiry duration. */ @Override public long expireAfterRead( - String key, DateTime value, long currentTime, long currentDuration) { + String key, Instant value, long currentTime, long currentDuration) { return currentDuration; } }; /** Attempt to load the domain's deletion time if the domain exists. */ - private static final CacheLoader CACHE_LOADER = + private static final CacheLoader CACHE_LOADER = (domainName) -> { ForeignKeyUtils.MostRecentResource mostRecentResource = ForeignKeyUtils.loadMostRecentResources( Domain.class, ImmutableSet.of(domainName), false) .get(domainName); - return mostRecentResource == null ? null : mostRecentResource.getDeletionTime(); + return mostRecentResource == null ? null : mostRecentResource.deletionTime(); }; // Unfortunately, maintenance tasks aren't necessarily already in a transaction private static final Ticker TRANSACTION_TIME_TICKER = - () -> tm().reTransact(() -> tm().getTransactionTime().getMillis() * NANOS_IN_ONE_MILLISECOND); + () -> tm().reTransact(() -> ChronoUnit.NANOS.between(Instant.EPOCH, tm().getTxTime())); public static DomainDeletionTimeCache create() { return new DomainDeletionTimeCache( @@ -120,14 +121,14 @@ public class DomainDeletionTimeCache { .build(CACHE_LOADER)); } - private final LoadingCache cache; + private final LoadingCache cache; - private DomainDeletionTimeCache(LoadingCache cache) { + private DomainDeletionTimeCache(LoadingCache cache) { this.cache = cache; } /** Returns the domain's deletion time, or null if it doesn't currently exist. */ - public Optional getDeletionTimeForDomain(String domainName) { + public Optional getDeletionTimeForDomain(String domainName) { return Optional.ofNullable(cache.get(domainName)); } } 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 b91314a71..3a1d010c8 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java +++ b/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java @@ -124,6 +124,7 @@ import google.registry.tldconfig.idn.IdnLabelValidator; import google.registry.tools.DigestType; import google.registry.util.Idn; import java.math.BigDecimal; +import java.time.Duration; import java.time.Instant; import java.util.Comparator; import java.util.List; @@ -133,7 +134,6 @@ import java.util.Set; import javax.annotation.Nullable; import org.joda.money.CurrencyUnit; import org.joda.money.Money; -import org.joda.time.Duration; import org.xbill.DNS.DNSSEC.Algorithm; /** Static utility functions for domain flows. */ @@ -1114,7 +1114,7 @@ public class DomainFlowUtils { "FROM DomainHistory WHERE modificationTime >= :beginning AND repoId = " + ":repoId ORDER BY modificationTime ASC", DomainHistory.class) - .setParameter("beginning", now.minusMillis(maxSearchPeriod.getMillis())) + .setParameter("beginning", now.minus(maxSearchPeriod)) .setParameter("repoId", domain.getRepoId()) .getResultList(); } 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 313985638..f561d2e6a 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainRenewFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainRenewFlow.java @@ -34,7 +34,7 @@ import static google.registry.flows.domain.token.AllocationTokenFlowUtils.maybeA import static google.registry.flows.domain.token.AllocationTokenFlowUtils.verifyBulkTokenAllowedOnDomain; 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 google.registry.util.DateTimeUtils.toLocalDate; import static java.time.ZoneOffset.UTC; import com.google.common.collect.ImmutableList; @@ -87,10 +87,10 @@ import google.registry.model.reporting.HistoryEntry.HistoryEntryId; import google.registry.model.reporting.IcannReportingTypes.ActivityReportField; import google.registry.model.tld.Tld; import jakarta.inject.Inject; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import org.joda.money.Money; -import org.joda.time.Duration; /** * An EPP flow that renews a domain. @@ -310,7 +310,7 @@ public final class DomainRenewFlow implements MutatingFlow { ImmutableSet.of( DomainTransactionRecord.create( newDomain.getTld(), - now.plusMillis(renewGracePeriod.getMillis()), + now.plus(renewGracePeriod), TransactionReportField.netRenewsFieldFromYears(period.getValue()), 1))) .build(); @@ -335,7 +335,7 @@ public final class DomainRenewFlow implements MutatingFlow { // If the date they specify doesn't match the expiration, fail. (This is an idempotence check). if (!command .getCurrentExpirationDate() - .equals(toDateTime(existingDomain.getRegistrationExpirationTime()).toLocalDate())) { + .equals(toLocalDate(existingDomain.getRegistrationExpirationTime()))) { throw new IncorrectCurrentExpirationDateException(); } } @@ -359,7 +359,7 @@ public final class DomainRenewFlow implements MutatingFlow { .filter(t -> AllocationToken.TokenBehavior.DEFAULT.equals(t.getTokenBehavior())) .map(AllocationToken::createVKey) .orElse(null)) - .setBillingTime(now.plusMillis(Tld.get(tld).getRenewGracePeriodLength().getMillis())) + .setBillingTime(now.plus(Tld.get(tld).getRenewGracePeriodLength())) .setDomainHistoryId(domainHistoryId) .build(); } diff --git a/core/src/main/java/google/registry/flows/domain/DomainTransferApproveFlow.java b/core/src/main/java/google/registry/flows/domain/DomainTransferApproveFlow.java index bb5b282c9..b0afa8b4b 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainTransferApproveFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainTransferApproveFlow.java @@ -168,8 +168,7 @@ public final class DomainTransferApproveFlow implements MutatingFlow { hasBulkToken ? null : existingBillingRecurrence) .getRenewCost()) .setEventTime(now) - .setBillingTime( - now.plusMillis(Tld.get(tldStr).getTransferGracePeriodLength().getMillis())) + .setBillingTime(now.plus(Tld.get(tldStr).getTransferGracePeriodLength())) .setDomainHistoryId(domainHistoryId) .build()); @@ -292,7 +291,7 @@ public final class DomainTransferApproveFlow implements MutatingFlow { cancelingRecords, DomainTransactionRecord.create( newDomain.getTld(), - now.plusMillis(tld.getTransferGracePeriodLength().getMillis()), + now.plus(tld.getTransferGracePeriodLength()), TRANSFER_SUCCESSFUL, 1))) .build(); diff --git a/core/src/main/java/google/registry/flows/domain/DomainTransferRejectFlow.java b/core/src/main/java/google/registry/flows/domain/DomainTransferRejectFlow.java index 0d8aef0ef..95d67dd9c 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainTransferRejectFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainTransferRejectFlow.java @@ -32,7 +32,6 @@ import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_TRANSFER_ import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.CollectionUtils.union; import static google.registry.util.DateTimeUtils.END_INSTANT; -import static google.registry.util.DateTimeUtils.toDateTime; import com.google.common.collect.ImmutableSet; import google.registry.flows.EppException; @@ -108,8 +107,7 @@ public final class DomainTransferRejectFlow implements MutatingFlow { checkAllowedAccessToTld(registrarId, existingDomain.getTld()); } Domain newDomain = - denyPendingTransfer( - existingDomain, TransferStatus.CLIENT_REJECTED, toDateTime(now), registrarId); + denyPendingTransfer(existingDomain, TransferStatus.CLIENT_REJECTED, now, registrarId); DomainHistory domainHistory = buildDomainHistory(newDomain, tld, now); tm().update(newDomain); tm().insertAll( 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 77816c90a..8caa7b07c 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainTransferRequestFlow.java +++ b/core/src/main/java/google/registry/flows/domain/DomainTransferRequestFlow.java @@ -220,7 +220,7 @@ public final class DomainTransferRequestFlow implements MutatingFlow { domainTransferRequestSuperuserExtension -> now.plus( domainTransferRequestSuperuserExtension.getAutomaticTransferLength(), DAYS)) - .orElseGet(() -> now.plusMillis(tld.getAutomaticTransferLength().getMillis())); + .orElseGet(() -> now.plus(tld.getAutomaticTransferLength())); // 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. // The gaining registrar is still billed for the extra year; the losing registrar will get a @@ -368,8 +368,8 @@ public final class DomainTransferRequestFlow implements MutatingFlow { ImmutableSet.of( DomainTransactionRecord.create( tld.getTldStr(), - now.plusMillis(tld.getAutomaticTransferLength().getMillis()) - .plusMillis(tld.getTransferGracePeriodLength().getMillis()), + now.plus(tld.getAutomaticTransferLength()) + .plus(tld.getTransferGracePeriodLength()), TransactionReportField.TRANSFER_SUCCESSFUL, 1))) .build(); diff --git a/core/src/main/java/google/registry/flows/domain/DomainTransferUtils.java b/core/src/main/java/google/registry/flows/domain/DomainTransferUtils.java index 8c6e75d5c..bbe1b9ddc 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainTransferUtils.java +++ b/core/src/main/java/google/registry/flows/domain/DomainTransferUtils.java @@ -316,8 +316,7 @@ public final class DomainTransferUtils { .setCost(transferCost) .setPeriodYears(1) .setEventTime(automaticTransferTime) - .setBillingTime( - automaticTransferTime.plusMillis(registry.getTransferGracePeriodLength().getMillis())) + .setBillingTime(automaticTransferTime.plus(registry.getTransferGracePeriodLength())) .setDomainHistoryId(domainHistoryId) .build(); } diff --git a/core/src/main/java/google/registry/loadtest/LoadTestAction.java b/core/src/main/java/google/registry/loadtest/LoadTestAction.java index 319da0b3f..109aadf02 100644 --- a/core/src/main/java/google/registry/loadtest/LoadTestAction.java +++ b/core/src/main/java/google/registry/loadtest/LoadTestAction.java @@ -33,13 +33,13 @@ import google.registry.request.auth.Auth; import google.registry.util.Clock; import google.registry.util.RegistryEnvironment; import jakarta.inject.Inject; +import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.function.Function; -import org.joda.time.DateTime; /** * Simple load test action that can generate configurable QPSes of various EPP actions. @@ -160,7 +160,7 @@ public class LoadTestAction implements Runnable { @Override public void run() { validateAndLogRequest(); - DateTime initialStartSecond = clock.nowUtc().plusSeconds(delaySeconds); + Instant initialStartSecond = clock.now().plus(Duration.ofSeconds(delaySeconds)); ImmutableList.Builder preTaskXmls = new ImmutableList.Builder<>(); ImmutableList.Builder hostPrefixesBuilder = new ImmutableList.Builder<>(); for (int i = 0; i < successfulDomainCreatesPerSecond; i++) { @@ -169,12 +169,12 @@ public class LoadTestAction implements Runnable { preTaskXmls.add( xmlHostCreateTmpl.replace("%host%", hostPrefix)); } - enqueue(createTasks(preTaskXmls.build(), clock.nowUtc())); + enqueue(createTasks(preTaskXmls.build(), clock.now())); ImmutableList hostPrefixes = hostPrefixesBuilder.build(); ImmutableList.Builder tasks = new ImmutableList.Builder<>(); for (int offsetSeconds = 0; offsetSeconds < runSeconds; offsetSeconds++) { - DateTime startSecond = initialStartSecond.plusSeconds(offsetSeconds); + Instant startSecond = initialStartSecond.plus(Duration.ofSeconds(offsetSeconds)); // The first "failed" creates might actually succeed if the object doesn't already exist, but // that shouldn't affect the load numbers. tasks.addAll( @@ -265,12 +265,11 @@ public class LoadTestAction implements Runnable { return name.toString(); } - private ImmutableList createTasks(ImmutableList xmls, DateTime start) { + private ImmutableList createTasks(ImmutableList xmls, Instant start) { ImmutableList.Builder tasks = new ImmutableList.Builder<>(); for (int i = 0; i < xmls.size(); i++) { // Space tasks evenly within across a second. - Instant scheduleTime = - Instant.ofEpochMilli(start.plusMillis((int) (1000.0 / xmls.size() * i)).getMillis()); + Instant scheduleTime = start.plus(Duration.ofMillis((long) (1000.0 / xmls.size() * i))); tasks.add( cloudTasksUtils .createTask( diff --git a/core/src/main/java/google/registry/model/EntityYamlUtils.java b/core/src/main/java/google/registry/model/EntityYamlUtils.java index 8b89e9835..611c4ef97 100644 --- a/core/src/main/java/google/registry/model/EntityYamlUtils.java +++ b/core/src/main/java/google/registry/model/EntityYamlUtils.java @@ -42,6 +42,7 @@ import google.registry.model.tld.Tld.TldState; import google.registry.persistence.VKey; import java.io.IOException; import java.math.BigDecimal; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -51,7 +52,6 @@ import java.util.Set; import java.util.SortedMap; import org.joda.money.CurrencyUnit; import org.joda.money.Money; -import org.joda.time.Duration; /** A collection of static utility classes/functions to convert entities to/from YAML files. */ public class EntityYamlUtils { @@ -337,7 +337,7 @@ public class EntityYamlUtils { public TimedTransitionProperty deserialize( JsonParser jp, DeserializationContext context) throws IOException { SortedMap valueMap = jp.readValueAs(SortedMap.class); - return TimedTransitionProperty.fromValueMapInstant( + return TimedTransitionProperty.fromValueMap( valueMap.keySet().stream() .collect( toImmutableSortedMap( @@ -363,7 +363,7 @@ public class EntityYamlUtils { public TimedTransitionProperty deserialize(JsonParser jp, DeserializationContext context) throws IOException { SortedMap> valueMap = jp.readValueAs(SortedMap.class); - return TimedTransitionProperty.fromValueMapInstant( + return TimedTransitionProperty.fromValueMap( valueMap.keySet().stream() .collect( toImmutableSortedMap( @@ -393,7 +393,7 @@ public class EntityYamlUtils { public TimedTransitionProperty deserialize( JsonParser jp, DeserializationContext context) throws IOException { SortedMap valueMap = jp.readValueAs(SortedMap.class); - return TimedTransitionProperty.fromValueMapInstant( + return TimedTransitionProperty.fromValueMap( valueMap.keySet().stream() .collect( toImmutableSortedMap( diff --git a/core/src/main/java/google/registry/model/EppResource.java b/core/src/main/java/google/registry/model/EppResource.java index a331a234e..228bf4dbe 100644 --- a/core/src/main/java/google/registry/model/EppResource.java +++ b/core/src/main/java/google/registry/model/EppResource.java @@ -115,7 +115,7 @@ public abstract class EppResource extends UpdateAutoTimestampEntity implements B *

    *
  • For deleted resources, this is in the past. *
  • For pending-delete resources, this is in the near future. - *
  • For active resources, this is {@code END_OF_TIME}. + *
  • For active resources, this is {@code END_INSTANT}. *
* *

This scheme allows for setting pending deletes in the future and having them magically drop diff --git a/core/src/main/java/google/registry/model/EppResourceUtils.java b/core/src/main/java/google/registry/model/EppResourceUtils.java index 1791078f0..cc541baa8 100644 --- a/core/src/main/java/google/registry/model/EppResourceUtils.java +++ b/core/src/main/java/google/registry/model/EppResourceUtils.java @@ -20,7 +20,6 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.isBeforeOrAt; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableSet; import com.google.common.flogger.FluentLogger; @@ -39,7 +38,6 @@ import java.time.Instant; import java.util.Comparator; import java.util.function.Function; import javax.annotation.Nullable; -import org.joda.time.DateTime; /** Utilities for working with {@link EppResource}. */ public final class EppResourceUtils { @@ -65,18 +63,12 @@ public final class EppResourceUtils { return String.format("%X-%s", repoId, roidSuffix); } - /** Helper to call {@link EppResource#cloneProjectedAtTime} without warnings. */ - @SuppressWarnings("unchecked") - private static T cloneProjectedAtTime(T resource, DateTime now) { - return (T) resource.cloneProjectedAtTime(toInstant(now)); - } - /** - * Returns a Function that transforms an EppResource to the given DateTime, suitable for use with + * Returns a Function that transforms an EppResource to the given Instant, suitable for use with * Iterables.transform() over a collection of EppResources. */ - public static Function transformAtTime(final DateTime now) { - return (T resource) -> cloneProjectedAtTime(resource, now); + public static Function transformAtTime(final Instant now) { + return (T resource) -> (T) resource.cloneProjectedAtTime(now); } public static boolean isActive(EppResource resource, Instant time) { @@ -84,28 +76,10 @@ public final class EppResourceUtils { && time.isBefore(resource.getDeletionTime()); } - /** - * @deprecated Use {@link #isActive(EppResource, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static boolean isActive(EppResource resource, DateTime time) { - return isActive(resource, toInstant(time)); - } - public static boolean isDeleted(EppResource resource, Instant time) { return !isActive(resource, time); } - /** - * @deprecated Use {@link #isDeleted(EppResource, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static boolean isDeleted(EppResource resource, DateTime time) { - return isDeleted(resource, toInstant(time)); - } - /** Process an automatic transfer on a domain. */ public static void setAutomaticTransferSuccessProperties( DomainBase.Builder builder, DomainTransferData transferData) { @@ -173,16 +147,6 @@ public final class EppResourceUtils { : null); } - /** - * @deprecated Use {@link #loadAtPointInTime(EppResource, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static T loadAtPointInTime( - final T resource, final DateTime timestamp) { - return loadAtPointInTime(resource, toInstant(timestamp)); - } - /** * Returns the most recent revision of a given EppResource before or at the provided timestamp, * falling back to using the resource as-is if there are no revisions. @@ -207,21 +171,6 @@ public final class EppResourceUtils { return resourceAtPointInTime; } - /** - * Returns a set of {@link VKey} for domains that reference a specified host. - * - * @param key the referent key - * @param now the logical time of the check /** Returns the domains that are linked to this host - * at the given time. - * @deprecated Use {@link #getLinkedDomainKeys(VKey, Instant, Integer)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ImmutableSet> getLinkedDomainKeys( - VKey key, DateTime now, @Nullable Integer limit) { - return getLinkedDomainKeys(key, toInstant(now), limit); - } - /** Returns the domains that are linked to this host at the given time. */ public static ImmutableSet> getLinkedDomainKeys( VKey key, Instant now, @Nullable Integer limit) { @@ -246,17 +195,6 @@ public final class EppResourceUtils { }); } - /** - * Returns whether this host is linked to any domains at the given time. - * - * @deprecated Use {@link #isLinked(VKey, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static boolean isLinked(VKey key, DateTime now) { - return isLinked(key, toInstant(now)); - } - /** Returns whether this resource is linked to any domains at the given time. */ public static boolean isLinked(VKey key, Instant now) { return !getLinkedDomainKeys(key, now, 1).isEmpty(); diff --git a/core/src/main/java/google/registry/model/ForeignKeyUtils.java b/core/src/main/java/google/registry/model/ForeignKeyUtils.java index e68275503..9b7169912 100644 --- a/core/src/main/java/google/registry/model/ForeignKeyUtils.java +++ b/core/src/main/java/google/registry/model/ForeignKeyUtils.java @@ -20,8 +20,6 @@ import static google.registry.config.RegistryConfig.getEppResourceCachingDuratio import static google.registry.config.RegistryConfig.getEppResourceMaxCachedEntries; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.LoadingCache; @@ -43,7 +41,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; -import org.joda.time.DateTime; /** * Util class for mapping a foreign key to a {@link VKey} or {@link EppResource}. @@ -65,30 +62,7 @@ public final class ForeignKeyUtils { Domain.class, "domainName", Host.class, "hostName"); - public record MostRecentResource(String repoId, Instant deletionTime) { - /** - * @deprecated Use {@link #deletionTime()} - */ - @Deprecated - public DateTime getDeletionTime() { - return toDateTime(deletionTime); - } - } - - /** - * Loads an optional {@link VKey} to an {@link EppResource} from the database by foreign key. - * - *

Returns empty if no resource with this foreign key was ever created, or if the most recently - * created resource was deleted before time "now". - * - * @deprecated Use {@link #loadKey(Class, String, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Optional> loadKey( - Class clazz, String foreignKey, DateTime now) { - return loadKey(clazz, foreignKey, toInstant(now)); - } + public record MostRecentResource(String repoId, Instant deletionTime) {} /** * Loads an optional {@link VKey} to an {@link EppResource} from the database by foreign key. @@ -101,21 +75,6 @@ public final class ForeignKeyUtils { return Optional.ofNullable(loadKeys(clazz, ImmutableList.of(foreignKey), now).get(foreignKey)); } - /** - * Loads an {@link EppResource} from the database by foreign key. - * - *

Returns null if no resource with this foreign key was ever created or if the most recently - * created resource was deleted before time "now". - * - * @deprecated Use {@link #loadResource(Class, String, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Optional loadResource( - Class clazz, String foreignKey, DateTime now) { - return loadResource(clazz, foreignKey, toInstant(now)); - } - /** * Loads an {@link EppResource} from the database by foreign key. * @@ -129,22 +88,6 @@ public final class ForeignKeyUtils { loadResources(clazz, ImmutableList.of(foreignKey), now).get(foreignKey)); } - /** - * Load a map of {@link String} foreign keys to {@link VKey}s to {@link EppResource} that are - * active at or after the specified moment in time. - * - *

The returned map will omit any foreign keys for which the {@link EppResource} doesn't exist - * or has been soft-deleted. - * - * @deprecated Use {@link #loadKeys(Class, Collection, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ImmutableMap> loadKeys( - Class clazz, Collection foreignKeys, DateTime now) { - return loadKeys(clazz, foreignKeys, toInstant(now)); - } - /** * Load a map of {@link String} foreign keys to {@link VKey}s to {@link EppResource} that are * active at or after the specified moment in time. @@ -159,20 +102,6 @@ public final class ForeignKeyUtils { .collect(toImmutableMap(Entry::getKey, e -> VKey.create(clazz, e.getValue().repoId()))); } - /** - * Load a map of {@link String} foreign keys to the {@link EppResource} that are active at or - * after the specified moment in time. - * - *

The returned map will omit any foreign keys for which the {@link EppResource} doesn't exist - * or has been soft-deleted. - */ - @SuppressWarnings({"unchecked", "InlineMeSuggester"}) - @Deprecated - public static ImmutableMap loadResources( - Class clazz, Collection foreignKeys, DateTime now) { - return loadResources(clazz, foreignKeys, toInstant(now)); - } - /** * Load a map of {@link String} foreign keys to the {@link EppResource} that are active at or * after the specified moment in time. @@ -198,7 +127,7 @@ public final class ForeignKeyUtils { * should monotonically increase as one cannot create a domain/host/contact with the same foreign * key without soft deleting the existing resource first. However, in test, there's no such * guarantee and one must make sure that no two resources with the same foreign key exist with the - * same max {@code deleteTime}, usually {@code END_OF_TIME}, lest this method throws an error due + * same max {@code deleteTime}, usually {@code END_INSTANT}, lest this method throws an error due * to duplicate keys. */ public static @@ -322,25 +251,6 @@ public final class ForeignKeyUtils { foreignKeyToRepoIdCache = createForeignKeyToRepoIdCache(effectiveExpiry); } - /** - * Load a list of {@link VKey} to {@link EppResource} instances by class and foreign key strings - * that are active at or after the specified moment in time, using the cache if enabled. - * - *

The returned map will omit any keys for which the {@link EppResource} doesn't exist or has - * been soft-deleted. - * - *

Don't use the cached version of this method unless you really need it for performance - * reasons, and are OK with the trade-offs in loss of transactional consistency. - * - * @deprecated Use {@link #loadKeysByCacheIfEnabled(Class, Collection, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ImmutableMap> loadKeysByCacheIfEnabled( - Class clazz, Collection foreignKeys, DateTime now) { - return loadKeysByCacheIfEnabled(clazz, foreignKeys, toInstant(now)); - } - /** * Load a list of {@link VKey} to {@link EppResource} instances by class and foreign key strings * that are active at or after the specified moment in time, using the cache if enabled. @@ -367,18 +277,6 @@ public final class ForeignKeyUtils { e -> VKey.create(clazz, e.getValue().get().repoId()))); } - /** - * Loads an optional {@link VKey} to an {@link EppResource} using the cache. - * - * @deprecated Use {@link #loadKeyByCache(Class, String, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Optional> loadKeyByCache( - Class clazz, String foreignKey, DateTime now) { - return loadKeyByCache(clazz, foreignKey, toInstant(now)); - } - /** Loads an optional {@link VKey} to an {@link EppResource} using the cache. */ public static Optional> loadKeyByCache( Class clazz, String foreignKey, Instant now) { @@ -461,33 +359,6 @@ public final class ForeignKeyUtils { foreignKeyToResourceCache = createForeignKeyToResourceCache(effectiveExpiry); } - /** - * Loads the last created version of an {@link EppResource} from the database by foreign key, - * using a cache, if caching is enabled in config settings. - * - *

Returns null if no resource with this foreign key was ever created, or if the most recently - * created resource was deleted before time "now". - * - *

Loading an {@link EppResource} by itself is not sufficient to know its current state since - * it may have various expirable conditions and status values that might implicitly change its - * state as time progresses even if it has not been updated in the database. Rather, the resource - * must be combined with a timestamp to view its current state. We use a global last updated - * timestamp to guarantee monotonically increasing write times, and forward our projected time to - * the greater of this timestamp or "now". This guarantees that we're not projecting into the - * past. - * - *

Do not call this cached version for anything that needs transactional consistency. It should - * only be used when it's OK if the data is potentially being out of date, e.g. RDAP. - * - * @deprecated Use {@link #loadResourceByCacheIfEnabled(Class, String, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Optional loadResourceByCacheIfEnabled( - Class clazz, String foreignKey, DateTime now) { - return loadResourceByCacheIfEnabled(clazz, foreignKey, toInstant(now)); - } - /** * Loads the last created version of an {@link EppResource} from the database by foreign key, * using a cache, if caching is enabled in config settings. @@ -513,22 +384,6 @@ public final class ForeignKeyUtils { : loadResource(clazz, foreignKey, now); } - /** - * Loads the last created version of an {@link EppResource} from the replica database by foreign - * key, using a cache. - * - *

This method ignores the config setting for caching, and is reserved for use cases that can - * tolerate slightly stale data. - * - * @deprecated Use {@link #loadResourceByCache(Class, String, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Optional loadResourceByCache( - Class clazz, String foreignKey, DateTime now) { - return loadResourceByCache(clazz, foreignKey, toInstant(now)); - } - /** * Loads the last created version of an {@link EppResource} from the replica database by foreign * key, using a cache. diff --git a/core/src/main/java/google/registry/model/OteAccountBuilder.java b/core/src/main/java/google/registry/model/OteAccountBuilder.java index ca8511e0c..69b943231 100644 --- a/core/src/main/java/google/registry/model/OteAccountBuilder.java +++ b/core/src/main/java/google/registry/model/OteAccountBuilder.java @@ -22,7 +22,6 @@ import static google.registry.model.tld.Tld.TldState.GENERAL_AVAILABILITY; import static google.registry.model.tld.Tld.TldState.START_DATE_SUNRISE; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.START_INSTANT; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -46,6 +45,7 @@ import google.registry.persistence.VKey; import google.registry.tools.IamClient; import google.registry.util.CidrAddressBlock; import google.registry.util.RegistryEnvironment; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; @@ -55,8 +55,6 @@ import java.util.function.Function; import java.util.regex.Pattern; import org.joda.money.CurrencyUnit; import org.joda.money.Money; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Class to help build and persist all the OT&E entities in the database. @@ -94,9 +92,9 @@ public final class OteAccountBuilder { private static final Pattern REGISTRAR_PATTERN = Pattern.compile("^[a-z\\d]{3,14}$"); // Durations are short so that registrars can test with quick transfer (etc.) turnaround. - private static final Duration SHORT_ADD_GRACE_PERIOD = Duration.standardMinutes(60); - private static final Duration SHORT_REDEMPTION_GRACE_PERIOD = Duration.standardMinutes(10); - private static final Duration SHORT_PENDING_DELETE_LENGTH = Duration.standardMinutes(5); + private static final Duration SHORT_ADD_GRACE_PERIOD = Duration.ofMinutes(60); + private static final Duration SHORT_REDEMPTION_GRACE_PERIOD = Duration.ofMinutes(10); + private static final Duration SHORT_PENDING_DELETE_LENGTH = Duration.ofMinutes(5); private static final String DEFAULT_PREMIUM_LIST = "default_sandbox_list"; @@ -234,8 +232,8 @@ public final class OteAccountBuilder { } /** Sets the client certificate to all the OT&E Registrars. */ - public OteAccountBuilder setCertificate(String asciiCert, DateTime now) { - return transformRegistrars(builder -> builder.setClientCertificate(asciiCert, toInstant(now))); + public OteAccountBuilder setCertificate(String asciiCert, Instant now) { + return transformRegistrars(builder -> builder.setClientCertificate(asciiCert, now)); } /** Sets the IP allowlist to all the OT&E Registrars. */ diff --git a/core/src/main/java/google/registry/model/ResourceTransferUtils.java b/core/src/main/java/google/registry/model/ResourceTransferUtils.java index f1f50c637..3004a8fa9 100644 --- a/core/src/main/java/google/registry/model/ResourceTransferUtils.java +++ b/core/src/main/java/google/registry/model/ResourceTransferUtils.java @@ -16,7 +16,6 @@ package google.registry.model; import static com.google.common.base.Preconditions.checkArgument; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -33,7 +32,6 @@ import google.registry.model.transfer.TransferResponse; import google.registry.model.transfer.TransferResponse.DomainTransferResponse; import google.registry.model.transfer.TransferStatus; import java.time.Instant; -import org.joda.time.DateTime; /** Static utility functions for domain transfers. */ public final class ResourceTransferUtils { @@ -73,20 +71,6 @@ public final class ResourceTransferUtils { domain.getDomainName(), actionResult, transferRequestTrid, processedDate); } - /** - * Create a pending action notification response indicating the resolution of a transfer. - * - * @deprecated Use {@link #createPendingTransferNotificationResponse(Domain, Trid, boolean, - * Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static PendingActionNotificationResponse createPendingTransferNotificationResponse( - Domain domain, Trid transferRequestTrid, boolean actionResult, DateTime processedDate) { - return createPendingTransferNotificationResponse( - domain, transferRequestTrid, actionResult, toInstant(processedDate)); - } - /** If there is a transfer out, delete the server-approve entities and enqueue a poll message. */ public static void handlePendingTransferOnDelete( Domain domain, Domain newDomain, Instant now, HistoryEntry historyEntry) { @@ -109,18 +93,6 @@ public final class ResourceTransferUtils { .build()); } - /** - * If there is a transfer out, delete the server-approve entities and enqueue a poll message. - * - * @deprecated Use {@link #handlePendingTransferOnDelete(Domain, Domain, Instant, HistoryEntry)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static void handlePendingTransferOnDelete( - Domain domain, Domain newDomain, DateTime now, HistoryEntry historyEntry) { - handlePendingTransferOnDelete(domain, newDomain, toInstant(now), historyEntry); - } - /** * Turn a domain into a builder with its pending transfer resolved. * @@ -165,18 +137,6 @@ public final class ResourceTransferUtils { .build(); } - /** - * Resolve a pending transfer by awarding it to the gaining client. - * - * @deprecated Use {@link #approvePendingTransfer(Domain, TransferStatus, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Domain approvePendingTransfer( - Domain domain, TransferStatus transferStatus, DateTime now) { - return approvePendingTransfer(domain, transferStatus, toInstant(now)); - } - /** * Resolve a pending transfer by denying it. * @@ -193,16 +153,4 @@ public final class ResourceTransferUtils { .setLastEppUpdateRegistrarId(lastEppUpdateRegistrarId) .build(); } - - /** - * Resolve a pending transfer by denying it. - * - * @deprecated Use {@link #denyPendingTransfer(Domain, TransferStatus, Instant, String)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static Domain denyPendingTransfer( - Domain domain, TransferStatus transferStatus, DateTime now, String lastEppUpdateRegistrarId) { - return denyPendingTransfer(domain, transferStatus, toInstant(now), lastEppUpdateRegistrarId); - } } diff --git a/core/src/main/java/google/registry/model/billing/BillingRecurrence.java b/core/src/main/java/google/registry/model/billing/BillingRecurrence.java index 813b72762..c83c11b59 100644 --- a/core/src/main/java/google/registry/model/billing/BillingRecurrence.java +++ b/core/src/main/java/google/registry/model/billing/BillingRecurrence.java @@ -83,9 +83,9 @@ public class BillingRecurrence extends BillingBase { * *

Note that this is a recurrence of the event time, not the billing time. The billing time can * be calculated by adding the relevant grace period length to this date. The reason for this - * requirement is that the event time recurs on a {@link org.joda.time.Period} schedule (same day - * of year, which can be 365 or 366 days later) which is what {@link TimeOfYear} can model, - * whereas the billing time is a fixed {@link org.joda.time.Duration} later. + * requirement is that the event time recurs on a year-based schedule (same day of year, which can + * be 365 or 366 days later) which is what {@link TimeOfYear} can model, whereas the billing time + * is a fixed {@link java.time.Duration} later. */ @Embedded @AttributeOverrides( diff --git a/core/src/main/java/google/registry/model/common/FeatureFlag.java b/core/src/main/java/google/registry/model/common/FeatureFlag.java index 4af8eb66d..49ef44a1a 100644 --- a/core/src/main/java/google/registry/model/common/FeatureFlag.java +++ b/core/src/main/java/google/registry/model/common/FeatureFlag.java @@ -20,7 +20,6 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration; import static google.registry.model.common.FeatureFlag.FeatureStatus.ACTIVE; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toInstant; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @@ -32,7 +31,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; -import com.google.common.collect.Ordering; import google.registry.model.Buildable; import google.registry.model.CacheUtils; import google.registry.model.EntityYamlUtils.TimedTransitionPropertyFeatureStatusDeserializer; @@ -49,7 +47,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import org.hibernate.annotations.Type; -import org.joda.time.DateTime; @Entity public class FeatureFlag extends ImmutableObject implements Buildable { @@ -182,10 +179,6 @@ public class FeatureFlag extends ImmutableObject implements Buildable { return status; } - public FeatureStatus getStatus(DateTime time) { - return getStatus(toInstant(time)); - } - public FeatureStatus getStatus(Instant time) { return status.getValueAtTime(time); } @@ -194,24 +187,14 @@ public class FeatureFlag extends ImmutableObject implements Buildable { * Returns whether the flag is active now, or else the flag's default value if it doesn't exist. */ public static boolean isActiveNow(FeatureName featureName) { - tm().assertInTransaction(); return isActiveAt(featureName, tm().getTxTime()); } - /** - * Returns whether the flag is active at the given time, or else the flag's default value if it - * doesn't exist. - */ - public static boolean isActiveAt(FeatureName featureName, DateTime dateTime) { - return isActiveAt(featureName, toInstant(dateTime)); - } - /** * Returns whether the flag is active at the given time, or else the flag's default value if it * doesn't exist. */ public static boolean isActiveAt(FeatureName featureName, Instant instant) { - tm().assertInTransaction(); return CACHE .get(featureName) .map(flag -> flag.getStatus(instant).equals(ACTIVE)) @@ -244,16 +227,8 @@ public class FeatureFlag extends ImmutableObject implements Buildable { return this; } - public Builder setStatusMap(ImmutableSortedMap statusMap) { - return setStatusMapInstant( - statusMap.entrySet().stream() - .collect( - ImmutableSortedMap.toImmutableSortedMap( - Ordering.natural(), e -> toInstant(e.getKey()), Map.Entry::getValue))); - } - - public Builder setStatusMapInstant(ImmutableSortedMap statusMap) { - getInstance().status = TimedTransitionProperty.fromValueMapInstant(statusMap); + public Builder setStatusMap(ImmutableSortedMap statusMap) { + getInstance().status = TimedTransitionProperty.fromValueMap(statusMap); return this; } } diff --git a/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java b/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java index 97bee6bbc..21a3e7ceb 100644 --- a/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java +++ b/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java @@ -20,8 +20,6 @@ import static com.google.common.collect.ImmutableSortedMap.toImmutableSortedMap; import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.formatInstant; import static google.registry.util.DateTimeUtils.latestOf; -import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.collect.ImmutableMultimap; @@ -34,7 +32,6 @@ import java.util.Map; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import org.joda.time.DateTime; /** * An entity property whose value transitions over time. Each value it takes on becomes active at a @@ -70,6 +67,9 @@ public class TimedTransitionProperty implements UnsafeSe checkArgument( backingMap.containsKey(START_INSTANT), "Must provide transition entry for the start of time (Unix Epoch)"); + checkArgument( + Ordering.natural().equals(backingMap.comparator()), + "Timed transition value map must have transition time keys in chronological order"); this.backingMap = ImmutableSortedMap.copyOfSorted(backingMap); } @@ -83,7 +83,7 @@ public class TimedTransitionProperty implements UnsafeSe * START_INSTANT}. */ public static TimedTransitionProperty withInitialValue(V value) { - return fromValueMapInstant(ImmutableSortedMap.of(START_INSTANT, value)); + return fromValueMap(ImmutableSortedMap.of(START_INSTANT, value)); } /** @@ -91,53 +91,12 @@ public class TimedTransitionProperty implements UnsafeSe * in the given map. * *

The map must contain a value for {@code START_INSTANT}. - * - * @deprecated Use {@link #fromValueMapInstant(ImmutableSortedMap)} */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") public static TimedTransitionProperty fromValueMap( - ImmutableSortedMap valueMap) { - return fromValueMapInstant(toInstantMap(valueMap)); - } - - /** - * Returns a {@link TimedTransitionProperty} that contains the transition values and times defined - * in the given map. - * - *

The map must contain a value for {@code START_INSTANT}. - */ - public static TimedTransitionProperty fromValueMapInstant( ImmutableSortedMap valueMap) { return new TimedTransitionProperty<>(valueMap); } - /** - * Returns a {@link TimedTransitionProperty} that contains the transition values and times defined - * in the given map. - * - *

The map must contain a value for {@code START_OF_TIME}. The map is also validated against a - * set of allowed transitions. - * - * @deprecated Use {@link #makeInstant(ImmutableSortedMap, ImmutableMultimap, String, - * Serializable, String)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static TimedTransitionProperty make( - ImmutableSortedMap valueMap, - ImmutableMultimap allowedTransitions, - String mapName, - V initialValue, - String initialValueErrorMessage) { - return makeInstant( - toInstantMap(valueMap), - allowedTransitions, - mapName, - initialValue, - initialValueErrorMessage); - } - /** * Returns a {@link TimedTransitionProperty} that contains the transition values and times defined * in the given map. @@ -145,44 +104,27 @@ public class TimedTransitionProperty implements UnsafeSe *

The map must contain a value for {@code START_INSTANT}. The map is also validated against a * set of allowed transitions. */ - public static TimedTransitionProperty makeInstant( + public static TimedTransitionProperty make( ImmutableSortedMap valueMap, ImmutableMultimap allowedTransitions, String mapName, V initialValue, String initialValueErrorMessage) { - validateTimedTransitionMapInstant(valueMap, allowedTransitions, mapName); + validateTimedTransitionMap(valueMap, allowedTransitions, mapName); checkArgument(valueMap.firstEntry().getValue().equals(initialValue), initialValueErrorMessage); - return fromValueMapInstant(valueMap); - } - - /** - * Validates a timed transition map. - * - * @deprecated Use {@link #validateTimedTransitionMapInstant(ImmutableSortedMap, - * ImmutableMultimap, String)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static void validateTimedTransitionMap( - ImmutableSortedMap valueMap, - ImmutableMultimap allowedTransitions, - String mapName) { - validateTimedTransitionMapInstant(toInstantMap(valueMap), allowedTransitions, mapName); + return fromValueMap(valueMap); } /** Validates a timed transition map. */ - public static void validateTimedTransitionMapInstant( + public static void validateTimedTransitionMap( ImmutableSortedMap valueMap, ImmutableMultimap allowedTransitions, String mapName) { checkArgument( Ordering.natural().equals(valueMap.comparator()), "Timed transition value map must have transition time keys in chronological order"); - checkArgument(!valueMap.isEmpty(), "%s map cannot be null or empty.", mapName); - checkArgument( - valueMap.firstKey().equals(START_INSTANT), "%s map must start at START_OF_TIME.", mapName); + valueMap.firstKey().equals(START_INSTANT), "%s map must start at START_INSTANT.", mapName); V lastValue = null; for (V value : valueMap.values()) { @@ -199,17 +141,6 @@ public class TimedTransitionProperty implements UnsafeSe } } - private static ImmutableSortedMap toInstantMap( - ImmutableSortedMap valueMap) { - checkArgument( - Ordering.natural().equals(valueMap.comparator()), - "Timed transition value map must have transition time keys in chronological order"); - return valueMap.entrySet().stream() - .collect( - toImmutableSortedMap( - Ordering.natural(), e -> toInstant(e.getKey()), Map.Entry::getValue)); - } - /** Checks whether the property is valid. */ public void checkValidity() { checkState( @@ -217,39 +148,16 @@ public class TimedTransitionProperty implements UnsafeSe "Timed transition values missing required entry for the start of time (Unix Epoch)"); } - /** Returns the value of the property that is active at the given time. */ - public V getValueAtTime(DateTime time) { - return getValueAtTime(toInstant(time)); - } - /** Returns the value of the property that is active at the given time. */ public V getValueAtTime(Instant time) { return backingMap.floorEntry(latestOf(START_INSTANT, time)).getValue(); } /** Returns the map of all the transitions that have been defined for this property. */ - public ImmutableSortedMap toValueMap() { - return backingMap.entrySet().stream() - .collect( - toImmutableSortedMap( - Ordering.natural(), e -> toDateTime(e.getKey()), Map.Entry::getValue)); - } - - /** Returns the map of all the transitions that have been defined for this property. */ - public ImmutableSortedMap toValueMapInstant() { + public ImmutableSortedMap toValueMap() { return backingMap; } - /** - * Returns the time of the next transition after the given time. Returns null if there is no - * subsequent transition. - */ - @Nullable - public DateTime getNextTransitionAfter(DateTime time) { - Instant nextTransition = getNextTransitionAfter(toInstant(time)); - return nextTransition == null ? null : toDateTime(nextTransition); - } - /** Returns the time of the next transition. Returns null if there is no subsequent transition. */ @Nullable public Instant getNextTransitionAfter(Instant time) { diff --git a/core/src/main/java/google/registry/model/console/ConsoleUpdateHistory.java b/core/src/main/java/google/registry/model/console/ConsoleUpdateHistory.java index 6a60d40c6..6579b52da 100644 --- a/core/src/main/java/google/registry/model/console/ConsoleUpdateHistory.java +++ b/core/src/main/java/google/registry/model/console/ConsoleUpdateHistory.java @@ -30,8 +30,8 @@ import jakarta.persistence.Index; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; @Entity @WithVKey(Long.class) @@ -47,7 +47,7 @@ public class ConsoleUpdateHistory extends ImmutableObject implements Buildable { @Column(nullable = false) @Expose - DateTime modificationTime; + Instant modificationTime; /** The HTTP method (e.g. POST, PUT) used to make this modification. */ @Column(nullable = false) @@ -76,7 +76,7 @@ public class ConsoleUpdateHistory extends ImmutableObject implements Buildable { return revisionId; } - public DateTime getModificationTime() { + public Instant getModificationTime() { return modificationTime; } @@ -141,7 +141,7 @@ public class ConsoleUpdateHistory extends ImmutableObject implements Buildable { return super.build(); } - public Builder setModificationTime(DateTime modificationTime) { + public Builder setModificationTime(Instant modificationTime) { getInstance().modificationTime = modificationTime; return this; } diff --git a/core/src/main/java/google/registry/model/console/PasswordResetRequest.java b/core/src/main/java/google/registry/model/console/PasswordResetRequest.java index a2d1acae7..11662e95e 100644 --- a/core/src/main/java/google/registry/model/console/PasswordResetRequest.java +++ b/core/src/main/java/google/registry/model/console/PasswordResetRequest.java @@ -14,7 +14,6 @@ package google.registry.model.console; -import static google.registry.util.DateTimeUtils.toDateTime; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import google.registry.model.Buildable; @@ -31,7 +30,6 @@ import jakarta.persistence.Id; import java.time.Instant; import java.util.Optional; import java.util.UUID; -import org.joda.time.DateTime; /** * Represents a password reset request of some type. @@ -64,7 +62,7 @@ public class PasswordResetRequest extends ImmutableObject implements Buildable { @Column(nullable = false) String requester; - @Column DateTime fulfillmentTime; + @Column Instant fulfillmentTime; @Column(nullable = false) String destinationEmail; @@ -84,20 +82,11 @@ public class PasswordResetRequest extends ImmutableObject implements Buildable { return requestTime.getTimestamp(); } - /** - * @deprecated Use {@link #getRequestTime()} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public DateTime getRequestDateTime() { - return toDateTime(requestTime.getTimestamp()); - } - public String getRequester() { return requester; } - public Optional getFulfillmentTime() { + public Optional getFulfillmentTime() { return Optional.ofNullable(fulfillmentTime); } @@ -153,7 +142,7 @@ public class PasswordResetRequest extends ImmutableObject implements Buildable { return this; } - public Builder setFulfillmentTime(DateTime fulfillmentTime) { + public Builder setFulfillmentTime(Instant fulfillmentTime) { getInstance().fulfillmentTime = fulfillmentTime; return this; } diff --git a/core/src/main/java/google/registry/model/contact/package-info.java b/core/src/main/java/google/registry/model/contact/package-info.java index 12bb579e1..ba85e2d36 100644 --- a/core/src/main/java/google/registry/model/contact/package-info.java +++ b/core/src/main/java/google/registry/model/contact/package-info.java @@ -18,7 +18,6 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(UtcInstantAdapter.class) }) package google.registry.model.contact; diff --git a/core/src/main/java/google/registry/model/domain/DomainBase.java b/core/src/main/java/google/registry/model/domain/DomainBase.java index 46c0b8997..0045242fa 100644 --- a/core/src/main/java/google/registry/model/domain/DomainBase.java +++ b/core/src/main/java/google/registry/model/domain/DomainBase.java @@ -80,7 +80,6 @@ import jakarta.persistence.Enumerated; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.Transient; -import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashSet; @@ -495,8 +494,7 @@ public class DomainBase extends EppResource { GracePeriodStatus.TRANSFER, domain.getRepoId(), transferExpirationTime.plus( - Duration.ofMillis( - Tld.get(domain.getTld()).getTransferGracePeriodLength().getMillis())), + Tld.get(domain.getTld()).getTransferGracePeriodLength()), transferData.getGainingRegistrarId(), transferData.getServerApproveBillingEvent()))); } else { @@ -533,8 +531,7 @@ public class DomainBase extends EppResource { GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), - lastAutorenewTime.plusMillis( - Tld.get(domain.getTld()).getAutoRenewGracePeriodLength().getMillis()), + lastAutorenewTime.plus(Tld.get(domain.getTld()).getAutoRenewGracePeriodLength()), domain.getCurrentSponsorRegistrarId(), domain.getAutorenewBillingEvent())); newLastEppUpdateTime = Optional.of(lastAutorenewTime); @@ -782,7 +779,7 @@ public class DomainBase extends EppResource { /** * Sets the autorenew end time, or clears it if empty is passed. * - *

Note that {@link DateTimeUtils#END_OF_TIME} is used as a sentinel value in the database + *

Note that {@link DateTimeUtils#END_INSTANT} is used as a sentinel value in the database * representation to signify that autorenew doesn't end, and is mapped to empty here for the * purposes of more legible business logic. */ diff --git a/core/src/main/java/google/registry/model/domain/DomainCommand.java b/core/src/main/java/google/registry/model/domain/DomainCommand.java index 87410a11f..d85235b62 100644 --- a/core/src/main/java/google/registry/model/domain/DomainCommand.java +++ b/core/src/main/java/google/registry/model/domain/DomainCommand.java @@ -46,10 +46,10 @@ import jakarta.xml.bind.annotation.XmlTransient; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlValue; import java.time.Instant; +import java.time.LocalDate; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; -import org.joda.time.LocalDate; /** A collection of {@link Domain} commands. */ public class DomainCommand { diff --git a/core/src/main/java/google/registry/model/domain/RegistryLock.java b/core/src/main/java/google/registry/model/domain/RegistryLock.java index 0bd4c722d..6fc4b6ca5 100644 --- a/core/src/main/java/google/registry/model/domain/RegistryLock.java +++ b/core/src/main/java/google/registry/model/domain/RegistryLock.java @@ -23,6 +23,7 @@ import com.google.gson.annotations.Expose; import google.registry.model.Buildable; import google.registry.model.CreateAutoTimestamp; import google.registry.model.UpdateAutoTimestampEntity; +import google.registry.persistence.converter.DurationUserType; import jakarta.persistence.Access; import jakarta.persistence.AccessType; import jakarta.persistence.AttributeOverride; @@ -37,10 +38,11 @@ import jakarta.persistence.Index; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; -import org.joda.time.Duration; +import org.hibernate.annotations.Type; /** * Represents a registry lock/unlock object, meaning that the domain is locked on the registry @@ -156,6 +158,8 @@ public final class RegistryLock extends UpdateAutoTimestampEntity implements Bui /** The duration after which we will re-lock this domain after it is unlocked. */ @Column(columnDefinition = "interval") + @Type(DurationUserType.class) + @Expose private Duration relockDuration; public String getRepoId() { diff --git a/core/src/main/java/google/registry/model/domain/package-info.java b/core/src/main/java/google/registry/model/domain/package-info.java index de8c3b623..7e0778e16 100644 --- a/core/src/main/java/google/registry/model/domain/package-info.java +++ b/core/src/main/java/google/registry/model/domain/package-info.java @@ -18,9 +18,8 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), - @XmlJavaTypeAdapter(UtcInstantAdapter.class), - @XmlJavaTypeAdapter(DateAdapter.class) + @XmlJavaTypeAdapter(value = UtcInstantAdapter.class, type = java.time.Instant.class), + @XmlJavaTypeAdapter(value = DateAdapter.class, type = java.time.LocalDate.class) }) package google.registry.model.domain; diff --git a/core/src/main/java/google/registry/model/domain/token/AllocationToken.java b/core/src/main/java/google/registry/model/domain/token/AllocationToken.java index 2c7c22f72..afba77c08 100644 --- a/core/src/main/java/google/registry/model/domain/token/AllocationToken.java +++ b/core/src/main/java/google/registry/model/domain/token/AllocationToken.java @@ -343,8 +343,8 @@ public class AllocationToken extends UpdateAutoTimestampEntity implements Builda } @JsonIgnore - public ImmutableSortedMap getTokenStatusTransitionsMapInstant() { - return tokenStatusTransitions.toValueMapInstant(); + public ImmutableSortedMap getTokenStatusTransitionsMap() { + return tokenStatusTransitions.toValueMap(); } public ImmutableSet getAllowedEppActions() { @@ -568,7 +568,7 @@ public class AllocationToken extends UpdateAutoTimestampEntity implements Builda public Builder setTokenStatusTransitions(ImmutableSortedMap transitions) { getInstance().tokenStatusTransitions = - TimedTransitionProperty.makeInstant( + TimedTransitionProperty.make( transitions, VALID_TOKEN_STATUS_TRANSITIONS, "tokenStatusTransitions", diff --git a/core/src/main/java/google/registry/model/eppinput/package-info.java b/core/src/main/java/google/registry/model/eppinput/package-info.java index 8516473f9..52d6b0937 100644 --- a/core/src/main/java/google/registry/model/eppinput/package-info.java +++ b/core/src/main/java/google/registry/model/eppinput/package-info.java @@ -18,7 +18,6 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(UtcInstantAdapter.class) }) package google.registry.model.eppinput; diff --git a/core/src/main/java/google/registry/model/eppoutput/package-info.java b/core/src/main/java/google/registry/model/eppoutput/package-info.java index a28017aeb..d10997047 100644 --- a/core/src/main/java/google/registry/model/eppoutput/package-info.java +++ b/core/src/main/java/google/registry/model/eppoutput/package-info.java @@ -18,7 +18,6 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(UtcInstantAdapter.class) }) package google.registry.model.eppoutput; diff --git a/core/src/main/java/google/registry/model/host/package-info.java b/core/src/main/java/google/registry/model/host/package-info.java index 7ba8a5b86..f75370d96 100644 --- a/core/src/main/java/google/registry/model/host/package-info.java +++ b/core/src/main/java/google/registry/model/host/package-info.java @@ -18,7 +18,6 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(InetAddressAdapter.class) }) diff --git a/core/src/main/java/google/registry/model/poll/PendingActionNotificationResponse.java b/core/src/main/java/google/registry/model/poll/PendingActionNotificationResponse.java index e77b070bd..d5d409678 100644 --- a/core/src/main/java/google/registry/model/poll/PendingActionNotificationResponse.java +++ b/core/src/main/java/google/registry/model/poll/PendingActionNotificationResponse.java @@ -14,8 +14,6 @@ package google.registry.model.poll; -import static google.registry.util.DateTimeUtils.toInstant; - import com.google.common.annotations.VisibleForTesting; import google.registry.model.ImmutableObject; import google.registry.model.UnsafeSerializable; @@ -31,7 +29,6 @@ import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlValue; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.Instant; -import org.joda.time.DateTime; /** The {@link ResponseData} returned when completing a pending action on a domain. */ @XmlTransient @@ -105,16 +102,6 @@ public class PendingActionNotificationResponse extends ImmutableObject trid, processedDate); } - - /** - * @deprecated Use {@link #create(String, boolean, Trid, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static DomainPendingActionNotificationResponse create( - String domainName, boolean actionResult, Trid trid, DateTime processedDate) { - return create(domainName, actionResult, trid, toInstant(processedDate)); - } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @@ -139,16 +126,6 @@ public class PendingActionNotificationResponse extends ImmutableObject trid, processedDate); } - - /** - * @deprecated Use {@link #create(String, boolean, Trid, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ContactPendingActionNotificationResponse create( - String contactId, boolean actionResult, Trid trid, DateTime processedDate) { - return create(contactId, actionResult, trid, toInstant(processedDate)); - } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @@ -170,15 +147,5 @@ public class PendingActionNotificationResponse extends ImmutableObject return init( new HostPendingActionNotificationResponse(), hostName, actionResult, trid, processedDate); } - - /** - * @deprecated Use {@link #create(String, boolean, Trid, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static HostPendingActionNotificationResponse create( - String hostName, boolean actionResult, Trid trid, DateTime processedDate) { - return create(hostName, actionResult, trid, toInstant(processedDate)); - } } } diff --git a/core/src/main/java/google/registry/model/poll/PollMessage.java b/core/src/main/java/google/registry/model/poll/PollMessage.java index 8857e17fc..c8581f514 100644 --- a/core/src/main/java/google/registry/model/poll/PollMessage.java +++ b/core/src/main/java/google/registry/model/poll/PollMessage.java @@ -18,8 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static google.registry.util.DateTimeUtils.END_INSTANT; 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.PreconditionsUtils.checkArgumentNotNull; import com.google.common.collect.ImmutableList; @@ -60,7 +58,6 @@ import jakarta.persistence.InheritanceType; import jakarta.persistence.Table; import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** * A poll message that is pending for a registrar. @@ -246,15 +243,6 @@ public abstract class PollMessage extends ImmutableObject return thisCastToDerived(); } - /** - * @deprecated Use {@link #setEventTime(Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public B setEventTime(DateTime eventTime) { - return setEventTime(toInstant(eventTime)); - } - public B setEventTime(Instant eventTime) { getInstance().eventTime = eventTime; return thisCastToDerived(); @@ -403,15 +391,6 @@ public abstract class PollMessage extends ImmutableObject return new Builder(clone(this)); } - /** - * @deprecated Use {@link #getExtendedRegistrationExpirationTime()} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public DateTime getExtendedRegistrationExpirationDateTime() { - return toDateTime(extendedRegistrationExpirationTime); - } - public Instant getExtendedRegistrationExpirationTime() { return extendedRegistrationExpirationTime; } @@ -584,15 +563,6 @@ public abstract class PollMessage extends ImmutableObject return this; } - /** - * @deprecated Use {@link #setAutorenewEndTime(Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public Builder setAutorenewEndTime(DateTime autorenewEndTime) { - return setAutorenewEndTime(toInstant(autorenewEndTime)); - } - public Builder setAutorenewEndTime(Instant autorenewEndTime) { getInstance().autorenewEndTime = autorenewEndTime; return this; diff --git a/core/src/main/java/google/registry/model/poll/package-info.java b/core/src/main/java/google/registry/model/poll/package-info.java index c59d7162c..30d132a13 100644 --- a/core/src/main/java/google/registry/model/poll/package-info.java +++ b/core/src/main/java/google/registry/model/poll/package-info.java @@ -18,7 +18,6 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(UtcInstantAdapter.class) }) package google.registry.model.poll; 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 cb024d430..016763b1b 100644 --- a/core/src/main/java/google/registry/model/rde/RdeRevision.java +++ b/core/src/main/java/google/registry/model/rde/RdeRevision.java @@ -17,15 +17,13 @@ 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 static google.registry.util.DateTimeUtils.toLocalDate; import com.google.common.base.VerifyException; import google.registry.model.ImmutableObject; import google.registry.model.UpdateAutoTimestampEntity; import google.registry.persistence.VKey; -import google.registry.persistence.converter.LocalDateConverter; import jakarta.persistence.Column; -import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; @@ -33,8 +31,8 @@ import jakarta.persistence.Id; import jakarta.persistence.IdClass; import java.io.Serializable; import java.time.Instant; +import java.time.LocalDate; import java.util.Optional; -import org.joda.time.LocalDate; /** * Entity for tracking RDE revisions. @@ -82,16 +80,16 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { * * @return {@code 0} for first deposit generation and {@code >0} for resends */ - public static int getNextRevision(String tld, Instant date, RdeMode mode) { - RdeRevisionId revisionId = RdeRevisionId.create(tld, toJodaLocalDate(date), mode); + public static int getNextRevision(String tld, Instant watermark, RdeMode mode) { + RdeRevisionId revisionId = RdeRevisionId.create(tld, toLocalDate(watermark), mode); Optional revisionOptional = 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, Instant date, RdeMode mode) { - int nextRevision = getNextRevision(tld, date, mode); + public static Optional getCurrentRevision(String tld, Instant watermark, RdeMode mode) { + int nextRevision = getNextRevision(tld, watermark, mode); if (nextRevision == 0) { return Optional.empty(); } @@ -107,10 +105,10 @@ 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, Instant date, RdeMode mode, int revision) { + public static void saveRevision(String tld, Instant watermark, RdeMode mode, int revision) { checkArgument(revision >= 0, "Negative revision: %s", revision); tm().assertInTransaction(); - RdeRevisionId revisionId = RdeRevisionId.create(tld, toJodaLocalDate(date), mode); + RdeRevisionId revisionId = RdeRevisionId.create(tld, toLocalDate(watermark), mode); Optional revisionOptional = tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, revisionId)); if (revision == 0) { @@ -125,7 +123,7 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { checkArgument( revisionOptional.isPresent(), "Couldn't find existing RDE revision %s when trying to save new revision %s", - makePartialName(tld, date, mode), + makePartialName(tld, watermark, mode), revision); checkArgument( revisionOptional.get().revision == revision - 1, @@ -133,7 +131,7 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { revision - 1, revisionOptional.get()); } - tm().put(RdeRevision.create(tld, toJodaLocalDate(date), mode, revision)); + tm().put(RdeRevision.create(tld, toLocalDate(watermark), mode, revision)); } /** Class to represent the composite primary key of {@link RdeRevision} entity. */ @@ -141,9 +139,8 @@ public final class RdeRevision extends UpdateAutoTimestampEntity { String tld; - // Auto-conversion doesn't work for ID classes, we must specify @Column and @Convert + // Auto-conversion doesn't work for ID classes, we must specify @Column @Column(columnDefinition = "date") - @Convert(converter = LocalDateConverter.class) LocalDate date; @Enumerated(EnumType.STRING) diff --git a/core/src/main/java/google/registry/model/reporting/HistoryEntryDao.java b/core/src/main/java/google/registry/model/reporting/HistoryEntryDao.java index e3834086a..a91e53324 100644 --- a/core/src/main/java/google/registry/model/reporting/HistoryEntryDao.java +++ b/core/src/main/java/google/registry/model/reporting/HistoryEntryDao.java @@ -19,7 +19,6 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.START_INSTANT; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; @@ -37,7 +36,6 @@ import java.time.Instant; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; -import org.joda.time.DateTime; /** Retrieves {@link HistoryEntry} descendants (e.g. {@link DomainHistory}). */ public class HistoryEntryDao { @@ -50,18 +48,6 @@ public class HistoryEntryDao { Host.class, HostHistory.class); - /** - * Loads all history objects in the times specified, including all types. - * - * @deprecated Use {@link #loadAllHistoryObjects(Instant, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ImmutableList loadAllHistoryObjects( - DateTime afterTime, DateTime beforeTime) { - return loadAllHistoryObjects(toInstant(afterTime), toInstant(beforeTime)); - } - /** Loads all history objects in the times specified, including all types. */ public static ImmutableList loadAllHistoryObjects( Instant afterTime, Instant beforeTime) { @@ -88,16 +74,6 @@ public class HistoryEntryDao { return loadHistoryObjectsForResource(resourceKey, START_INSTANT, END_INSTANT, subclazz); } - /** - * @deprecated Use {@link #loadHistoryObjectsForResource(VKey, Instant, Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ImmutableList loadHistoryObjectsForResource( - VKey resourceKey, DateTime afterTime, DateTime beforeTime) { - return loadHistoryObjectsForResource(resourceKey, toInstant(afterTime), toInstant(beforeTime)); - } - /** Loads all history objects in the time period specified for the given {@link EppResource}. */ public static ImmutableList loadHistoryObjectsForResource( VKey resourceKey, Instant afterTime, Instant beforeTime) { @@ -105,20 +81,6 @@ public class HistoryEntryDao { () -> loadHistoryObjectsForResourceInternal(resourceKey, afterTime, beforeTime)); } - /** - * @deprecated Use {@link #loadHistoryObjectsForResource(VKey, Instant, Instant, Class)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static ImmutableList loadHistoryObjectsForResource( - VKey resourceKey, - DateTime afterTime, - DateTime beforeTime, - Class subclazz) { - return loadHistoryObjectsForResource( - resourceKey, toInstant(afterTime), toInstant(beforeTime), subclazz); - } - /** * Loads all history objects in the time period specified for the given {@link EppResource} and * cast to the appropriate subclass. diff --git a/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatch.java b/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatch.java index 42b84d149..e27fbf0d3 100644 --- a/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatch.java +++ b/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatch.java @@ -32,8 +32,8 @@ import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; import java.io.Serializable; +import java.time.LocalDate; import java.util.Set; -import org.joda.time.LocalDate; @Entity @Table( diff --git a/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatchDao.java b/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatchDao.java index 35217e7ae..fa0372b51 100644 --- a/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatchDao.java +++ b/core/src/main/java/google/registry/model/reporting/Spec11ThreatMatchDao.java @@ -16,7 +16,7 @@ package google.registry.model.reporting; import com.google.common.collect.ImmutableList; import google.registry.persistence.transaction.JpaTransactionManager; -import org.joda.time.LocalDate; +import java.time.LocalDate; /** * Data access object for {@link Spec11ThreatMatch}. diff --git a/core/src/main/java/google/registry/model/tld/Tld.java b/core/src/main/java/google/registry/model/tld/Tld.java index 7745d792b..4d3f8addd 100644 --- a/core/src/main/java/google/registry/model/tld/Tld.java +++ b/core/src/main/java/google/registry/model/tld/Tld.java @@ -24,8 +24,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.START_INSTANT; -import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.formatInstant; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static org.joda.money.CurrencyUnit.USD; @@ -77,7 +76,6 @@ import google.registry.persistence.converter.AllocationTokenVkeyListUserType; import google.registry.persistence.converter.BillingCostTransitionUserType; import google.registry.persistence.converter.TldStateTransitionUserType; import google.registry.tldconfig.idn.IdnTableEnum; -import google.registry.util.DateTimeUtils; import google.registry.util.Idn; import jakarta.persistence.AttributeOverride; import jakarta.persistence.Column; @@ -86,6 +84,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.Id; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -98,8 +97,6 @@ import javax.annotation.Nullable; import org.hibernate.annotations.Type; import org.joda.money.CurrencyUnit; import org.joda.money.Money; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** Persisted per-TLD configuration data. */ @Entity @@ -121,14 +118,14 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public static final boolean DEFAULT_ESCROW_ENABLED = false; public static final boolean DEFAULT_DNS_PAUSED = false; - public static final Duration DEFAULT_ADD_GRACE_PERIOD = Duration.standardDays(5); - public static final Duration DEFAULT_AUTO_RENEW_GRACE_PERIOD = Duration.standardDays(45); - public static final Duration DEFAULT_REDEMPTION_GRACE_PERIOD = Duration.standardDays(30); - public static final Duration DEFAULT_RENEW_GRACE_PERIOD = Duration.standardDays(5); - public static final Duration DEFAULT_TRANSFER_GRACE_PERIOD = Duration.standardDays(5); - public static final Duration DEFAULT_AUTOMATIC_TRANSFER_LENGTH = Duration.standardDays(5); - public static final Duration DEFAULT_PENDING_DELETE_LENGTH = Duration.standardDays(5); - public static final Duration DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD = Duration.standardDays(30); + public static final Duration DEFAULT_ADD_GRACE_PERIOD = Duration.ofDays(5); + public static final Duration DEFAULT_AUTO_RENEW_GRACE_PERIOD = Duration.ofDays(45); + public static final Duration DEFAULT_REDEMPTION_GRACE_PERIOD = Duration.ofDays(30); + public static final Duration DEFAULT_RENEW_GRACE_PERIOD = Duration.ofDays(5); + public static final Duration DEFAULT_TRANSFER_GRACE_PERIOD = Duration.ofDays(5); + public static final Duration DEFAULT_AUTOMATIC_TRANSFER_LENGTH = Duration.ofDays(5); + public static final Duration DEFAULT_PENDING_DELETE_LENGTH = Duration.ofDays(5); + public static final Duration DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD = Duration.ofDays(30); public static final CurrencyUnit DEFAULT_CURRENCY = USD; public static final Money DEFAULT_CREATE_BILLING_COST = Money.of(USD, 8); public static final Money DEFAULT_EAP_BILLING_COST = Money.of(USD, 0); @@ -260,14 +257,9 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl return VKey.create(Tld.class, tldStr); } - /** Checks if {@code tld} is enrolled with BSA. */ - public static boolean isEnrolledWithBsa(Tld tld, DateTime now) { - return isEnrolledWithBsa(tld, toInstant(now)); - } - /** Checks if {@code tld} is enrolled with BSA. */ public static boolean isEnrolledWithBsa(Tld tld, Instant now) { - return tld.getBsaEnrollStartTimeInstant().orElse(END_INSTANT).isBefore(now); + return tld.getBsaEnrollStartTime().orElse(END_INSTANT).isBefore(now); } /** @@ -601,13 +593,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl /** Returns the time when this TLD was enrolled in the Brand Safety Alliance (BSA) program. */ @JsonIgnore - public Optional getBsaEnrollStartTime() { - return Optional.ofNullable(toDateTime(this.bsaEnrollStartTime)); - } - - /** Returns the time when this TLD was enrolled in the Brand Safety Alliance (BSA) program. */ - @JsonIgnore - public Optional getBsaEnrollStartTimeInstant() { + public Optional getBsaEnrollStartTime() { return Optional.ofNullable(this.bsaEnrollStartTime); } @@ -697,7 +683,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl } public ImmutableSortedMap getCreateBillingCostTransitions() { - return createBillingCostTransitions.toValueMapInstant(); + return createBillingCostTransitions.toValueMap(); } /** @@ -728,11 +714,11 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl } public ImmutableSortedMap getTldStateTransitions() { - return tldStateTransitions.toValueMapInstant(); + return tldStateTransitions.toValueMap(); } public ImmutableSortedMap getRenewBillingCostTransitions() { - return renewBillingCostTransitions.toValueMapInstant(); + return renewBillingCostTransitions.toValueMap(); } /** Returns the EAP fee for the tld at the given time. */ @@ -752,13 +738,13 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl // which the domain is separately considered standard vs premium depending on renewal price. false, validPeriod, - toDateTime(validPeriod.upperEndpoint())); + formatInstant(validPeriod.upperEndpoint())); } @VisibleForTesting @JsonProperty("eapFeeSchedule") public ImmutableSortedMap getEapFeeScheduleAsMap() { - return eapFeeSchedule.toValueMapInstant(); + return eapFeeSchedule.toValueMap(); } public String getLordnUsername() { @@ -853,7 +839,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl .filter(state -> !TldState.QUIET_PERIOD.equals(state)) .collect(Collectors.toList())), "The TLD states are chronologically out of order"); - getInstance().tldStateTransitions = TimedTransitionProperty.fromValueMapInstant(tldStatesMap); + getInstance().tldStateTransitions = TimedTransitionProperty.fromValueMap(tldStatesMap); return this; } @@ -913,7 +899,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public Builder setAddGracePeriodLength(Duration addGracePeriodLength) { checkArgument( - addGracePeriodLength.isLongerThan(Duration.ZERO), + addGracePeriodLength.compareTo(Duration.ZERO) > 0, "addGracePeriodLength must be non-zero"); getInstance().addGracePeriodLength = addGracePeriodLength; return this; @@ -922,7 +908,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl /** Warning! Changing this will affect the billing time of autorenew events in the past. */ public Builder setAutoRenewGracePeriodLength(Duration autoRenewGracePeriodLength) { checkArgument( - autoRenewGracePeriodLength.isLongerThan(Duration.ZERO), + autoRenewGracePeriodLength.compareTo(Duration.ZERO) > 0, "autoRenewGracePeriodLength must be non-zero"); getInstance().autoRenewGracePeriodLength = autoRenewGracePeriodLength; return this; @@ -930,7 +916,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public Builder setRedemptionGracePeriodLength(Duration redemptionGracePeriodLength) { checkArgument( - redemptionGracePeriodLength.isLongerThan(Duration.ZERO), + redemptionGracePeriodLength.compareTo(Duration.ZERO) > 0, "redemptionGracePeriodLength must be non-zero"); getInstance().redemptionGracePeriodLength = redemptionGracePeriodLength; return this; @@ -938,7 +924,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public Builder setRenewGracePeriodLength(Duration renewGracePeriodLength) { checkArgument( - renewGracePeriodLength.isLongerThan(Duration.ZERO), + renewGracePeriodLength.compareTo(Duration.ZERO) > 0, "renewGracePeriodLength must be non-zero"); getInstance().renewGracePeriodLength = renewGracePeriodLength; return this; @@ -946,7 +932,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public Builder setTransferGracePeriodLength(Duration transferGracePeriodLength) { checkArgument( - transferGracePeriodLength.isLongerThan(Duration.ZERO), + transferGracePeriodLength.compareTo(Duration.ZERO) > 0, "transferGracePeriodLength must be non-zero"); getInstance().transferGracePeriodLength = transferGracePeriodLength; return this; @@ -954,7 +940,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public Builder setAutomaticTransferLength(Duration automaticTransferLength) { checkArgument( - automaticTransferLength.isLongerThan(Duration.ZERO), + automaticTransferLength.compareTo(Duration.ZERO) > 0, "automaticTransferLength must be non-zero"); getInstance().automaticTransferLength = automaticTransferLength; return this; @@ -962,7 +948,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl public Builder setPendingDeleteLength(Duration pendingDeleteLength) { checkArgument( - pendingDeleteLength.isLongerThan(Duration.ZERO), "pendingDeleteLength must be non-zero"); + pendingDeleteLength.compareTo(Duration.ZERO) > 0, "pendingDeleteLength must be non-zero"); getInstance().pendingDeleteLength = pendingDeleteLength; return this; } @@ -980,7 +966,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl createCostsMap.values().stream().allMatch(Money::isPositiveOrZero), "Create billing cost cannot be negative"); getInstance().createBillingCostTransitions = - TimedTransitionProperty.fromValueMapInstant(createCostsMap); + TimedTransitionProperty.fromValueMap(createCostsMap); return this; } @@ -1033,7 +1019,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl renewCostsMap.values().stream().allMatch(Money::isPositiveOrZero), "Renew billing cost cannot be negative"); getInstance().renewBillingCostTransitions = - TimedTransitionProperty.fromValueMapInstant(renewCostsMap); + TimedTransitionProperty.fromValueMap(renewCostsMap); return this; } @@ -1043,7 +1029,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl checkArgument( eapFeeSchedule.values().stream().allMatch(Money::isPositiveOrZero), "EAP fee cannot be negative"); - getInstance().eapFeeSchedule = TimedTransitionProperty.fromValueMapInstant(eapFeeSchedule); + getInstance().eapFeeSchedule = TimedTransitionProperty.fromValueMap(eapFeeSchedule); return this; } @@ -1121,13 +1107,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl return this; } - public Builder setBsaEnrollStartTime(Optional enrollTime) { - // TODO(b/309175133): forbid if enrolled with BSA - getInstance().bsaEnrollStartTime = enrollTime.map(DateTimeUtils::toInstant).orElse(null); - return this; - } - - public Builder setBsaEnrollStartTimeInstant(Optional enrollTime) { + public Builder setBsaEnrollStartTime(Optional enrollTime) { // TODO(b/309175133): forbid if enrolled with BSA getInstance().bsaEnrollStartTime = enrollTime.orElse(null); return this; @@ -1145,7 +1125,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl && tldName.equals(InternetDomainName.from(tldName).toString()), "Cannot create registry for TLD that is not a valid, canonical domain name"); // Check the validity of all TimedTransitionProperties to ensure that they have values for - // START_OF_TIME. The setters above have already checked this for new values, but also check + // START_INSTANT. The setters above have already checked this for new values, but also check // here to catch cases where we loaded an invalid TimedTransitionProperty from the database // and cloned it into a new builder, to block re-building a Tld in an invalid state. instance.tldStateTransitions.checkValidity(); @@ -1172,7 +1152,7 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl instance.getCreateBillingCostTransitions().values().stream().allMatch(currencyCheck), "Create cost must be in the TLD's currency"); checkArgument( - instance.eapFeeSchedule.toValueMapInstant().values().stream().allMatch(currencyCheck), + instance.eapFeeSchedule.toValueMap().values().stream().allMatch(currencyCheck), "All EAP fees must be in the TLD's currency"); checkArgumentNotNull( instance.pricingEngineClassName, "All registries must have a configured pricing engine"); diff --git a/core/src/main/java/google/registry/model/tld/Tlds.java b/core/src/main/java/google/registry/model/tld/Tlds.java index ad6a2940c..d80fab7a0 100644 --- a/core/src/main/java/google/registry/model/tld/Tlds.java +++ b/core/src/main/java/google/registry/model/tld/Tlds.java @@ -25,7 +25,6 @@ import static google.registry.model.CacheUtils.memoizeWithShortExpiration; import static google.registry.model.tld.Tld.isEnrolledWithBsa; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.CollectionUtils.entriesToImmutableMap; -import static google.registry.util.DateTimeUtils.toInstant; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import com.google.common.base.Joiner; @@ -41,7 +40,6 @@ import java.time.Instant; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Stream; -import org.joda.time.DateTime; /** Utilities for finding and listing {@link Tld} entities. */ public final class Tlds { @@ -159,13 +157,4 @@ public final class Tlds { public static boolean hasActiveBsaEnrollment(Instant now) { return getTldEntitiesOfType(TldType.REAL).stream().anyMatch(tld -> isEnrolledWithBsa(tld, now)); } - - /** - * @deprecated Use {@link #hasActiveBsaEnrollment(Instant)} - */ - @Deprecated - @SuppressWarnings("InlineMeSuggester") - public static boolean hasActiveBsaEnrollment(DateTime now) { - return hasActiveBsaEnrollment(toInstant(now)); - } } diff --git a/core/src/main/java/google/registry/model/tld/label/BaseDomainLabelList.java b/core/src/main/java/google/registry/model/tld/label/BaseDomainLabelList.java index 41e53ecf4..348d95ac6 100644 --- a/core/src/main/java/google/registry/model/tld/label/BaseDomainLabelList.java +++ b/core/src/main/java/google/registry/model/tld/label/BaseDomainLabelList.java @@ -33,11 +33,11 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; +import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import org.joda.time.DateTime; /** * Base class for {@link ReservedList} and {@link PremiumList} objects. @@ -58,7 +58,7 @@ public abstract class BaseDomainLabelList, R extends Dom String name; @Column(name = "creation_timestamp") - DateTime creationTimestamp; + Instant creationTimestamp; /** Returns the ID of this revision, or throws if null. */ public long getRevisionId() { @@ -74,7 +74,7 @@ public abstract class BaseDomainLabelList, R extends Dom } /** Returns the creation time of this revision of the reserved list. */ - public DateTime getCreationTimestamp() { + public Instant getCreationTimestamp() { return creationTimestamp; } @@ -159,7 +159,7 @@ public abstract class BaseDomainLabelList, R extends Dom return thisCastToDerived(); } - public B setCreationTimestamp(DateTime creationTime) { + public B setCreationTimestamp(Instant creationTime) { getInstance().creationTimestamp = creationTime; return thisCastToDerived(); } diff --git a/core/src/main/java/google/registry/model/tld/label/PremiumListDao.java b/core/src/main/java/google/registry/model/tld/label/PremiumListDao.java index 7a5fc608f..6630d2202 100644 --- a/core/src/main/java/google/registry/model/tld/label/PremiumListDao.java +++ b/core/src/main/java/google/registry/model/tld/label/PremiumListDao.java @@ -131,8 +131,7 @@ public final class PremiumListDao { checkArgument(!inputData.isEmpty(), "New premium list data cannot be empty"); tm().assertInTransaction(); return save( - PremiumListUtils.parseToPremiumList( - name, currencyUnit, inputData, tm().getTransactionTime())); + PremiumListUtils.parseToPremiumList(name, currencyUnit, inputData, tm().getTxTime())); } /** Saves the given premium list (and its premium list entries) to Cloud SQL. */ diff --git a/core/src/main/java/google/registry/model/tld/label/PremiumListUtils.java b/core/src/main/java/google/registry/model/tld/label/PremiumListUtils.java index 463be206d..d57807722 100644 --- a/core/src/main/java/google/registry/model/tld/label/PremiumListUtils.java +++ b/core/src/main/java/google/registry/model/tld/label/PremiumListUtils.java @@ -18,16 +18,16 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import google.registry.model.tld.label.PremiumList.PremiumEntry; import java.math.BigDecimal; +import java.time.Instant; import java.util.List; import java.util.Map; import org.joda.money.CurrencyUnit; -import org.joda.time.DateTime; /** Static utility methods for {@link PremiumList}. */ public class PremiumListUtils { public static PremiumList parseToPremiumList( - String name, CurrencyUnit currencyUnit, List inputData, DateTime creationTime) { + String name, CurrencyUnit currencyUnit, List inputData, Instant creationTime) { PremiumList partialPremiumList = new PremiumList.Builder() .setName(name) diff --git a/core/src/main/java/google/registry/model/transfer/package-info.java b/core/src/main/java/google/registry/model/transfer/package-info.java index 9e26d4232..0353ffa0b 100644 --- a/core/src/main/java/google/registry/model/transfer/package-info.java +++ b/core/src/main/java/google/registry/model/transfer/package-info.java @@ -18,7 +18,6 @@ elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ - @XmlJavaTypeAdapter(UtcInstantAdapter.class), @XmlJavaTypeAdapter(UtcInstantAdapter.class) }) package google.registry.model.transfer; diff --git a/core/src/main/java/google/registry/module/ServletBase.java b/core/src/main/java/google/registry/module/ServletBase.java index 2b8ba9539..9f5d9b4b3 100644 --- a/core/src/main/java/google/registry/module/ServletBase.java +++ b/core/src/main/java/google/registry/module/ServletBase.java @@ -25,9 +25,9 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.Security; import java.time.Duration; +import java.time.Instant; import java.util.concurrent.TimeoutException; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.joda.time.DateTime; /** Base for Servlets that handle all requests to our modules. */ public class ServletBase extends HttpServlet { @@ -71,13 +71,13 @@ public class ServletBase extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException { logger.atInfo().log("Received %s request.", getClass().getSimpleName()); - DateTime startTime = clock.nowUtc(); + Instant startTime = clock.now(); try { requestHandler.handleRequest(req, rsp); } finally { logger.atInfo().log( "Finished %s request. Latency: %.3fs.", - getClass().getSimpleName(), (clock.nowUtc().getMillis() - startTime.getMillis()) / 1000d); + getClass().getSimpleName(), Duration.between(startTime, clock.now()).toMillis() / 1000d); } } } diff --git a/core/src/main/java/google/registry/monitoring/whitebox/CheckApiMetric.java b/core/src/main/java/google/registry/monitoring/whitebox/CheckApiMetric.java index 00bb9675d..644a018e0 100644 --- a/core/src/main/java/google/registry/monitoring/whitebox/CheckApiMetric.java +++ b/core/src/main/java/google/registry/monitoring/whitebox/CheckApiMetric.java @@ -18,13 +18,13 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.auto.value.AutoBuilder; import google.registry.util.Clock; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** A record for recording attributes of a domain check metric. */ public record CheckApiMetric( - DateTime startTimestamp, - DateTime endTimestamp, + Instant startTimestamp, + Instant endTimestamp, Status status, Optional tier, Optional availability) { @@ -83,7 +83,7 @@ public record CheckApiMetric( public static Builder builder(Clock clock) { - return new AutoBuilder_CheckApiMetric_Builder().startTimestamp(clock.nowUtc()).setClock(clock); + return new AutoBuilder_CheckApiMetric_Builder().startTimestamp(clock.now()).setClock(clock); } /** Builder for {@link CheckApiMetric}. */ @@ -100,12 +100,12 @@ public record CheckApiMetric( } public CheckApiMetric build() { - return this.endTimestamp(clock.nowUtc()).autoBuild(); + return this.endTimestamp(clock.now()).autoBuild(); } - abstract Builder startTimestamp(DateTime startTimestamp); + abstract Builder startTimestamp(Instant startTimestamp); - abstract Builder endTimestamp(DateTime endTimestamp); + abstract Builder endTimestamp(Instant endTimestamp); public abstract Builder status(Status status); diff --git a/core/src/main/java/google/registry/monitoring/whitebox/EppMetric.java b/core/src/main/java/google/registry/monitoring/whitebox/EppMetric.java index 7abc3fa80..4aa878b82 100644 --- a/core/src/main/java/google/registry/monitoring/whitebox/EppMetric.java +++ b/core/src/main/java/google/registry/monitoring/whitebox/EppMetric.java @@ -22,13 +22,13 @@ import com.google.common.collect.Iterables; import google.registry.model.eppoutput.Result.Code; import google.registry.model.tld.Tlds; import google.registry.util.Clock; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** A record for recording attributes of an EPP metric. */ public record EppMetric( - DateTime startTimestamp, - DateTime endTimestamp, + Instant startTimestamp, + Instant endTimestamp, Optional commandName, Optional registrarId, Optional tld, @@ -46,16 +46,14 @@ public record EppMetric( *

The start timestamp is recorded now, and the end timestamp at {@code build()}. */ public static Builder builderForRequest(Clock clock) { - return builder() - .setStartTimestamp(clock.nowUtc()) - .setClock(clock); + return builder().setStartTimestamp(clock.now()).setClock(clock); } - public DateTime getStartTimestamp() { + public Instant getStartTimestamp() { return startTimestamp; } - public DateTime getEndTimestamp() { + public Instant getEndTimestamp() { return endTimestamp; } @@ -82,9 +80,9 @@ public record EppMetric( /** Builder-only clock to support automatic recording of endTimestamp on {@link #build()}. */ private Clock clock = null; - abstract Builder setStartTimestamp(DateTime startTimestamp); + abstract Builder setStartTimestamp(Instant startTimestamp); - abstract Builder setEndTimestamp(DateTime endTimestamp); + abstract Builder setEndTimestamp(Instant endTimestamp); abstract Builder setCommandName(String commandName); @@ -141,7 +139,7 @@ public record EppMetric( */ public EppMetric build() { if (clock != null) { - setEndTimestamp(clock.nowUtc()); + setEndTimestamp(clock.now()); } return autoBuild(); } diff --git a/core/src/main/java/google/registry/monitoring/whitebox/StackdriverModule.java b/core/src/main/java/google/registry/monitoring/whitebox/StackdriverModule.java index 0396e013e..8c3808a1b 100644 --- a/core/src/main/java/google/registry/monitoring/whitebox/StackdriverModule.java +++ b/core/src/main/java/google/registry/monitoring/whitebox/StackdriverModule.java @@ -30,7 +30,7 @@ import google.registry.util.GoogleCredentialsBundle; import google.registry.util.MetricParameters; import jakarta.inject.Named; import jakarta.inject.Singleton; -import org.joda.time.Duration; +import java.time.Duration; /** Dagger module for monitoring and Google Stackdriver service connection objects. */ @Module @@ -45,7 +45,7 @@ public final class StackdriverModule { @Provides @Named("spoofedGceInstanceId") static String providesSpoofedGceInstanceId(Clock clock) { - return clock.nowUtc().toString(); + return clock.now().toString(); } @Provides @@ -84,7 +84,7 @@ public final class StackdriverModule { return new MetricReporter( metricWriter, - writeInterval.getStandardSeconds(), + writeInterval.toSeconds(), new ThreadFactoryBuilder().setDaemon(true).build()); } } diff --git a/core/src/main/java/google/registry/mosapi/MosApiMetrics.java b/core/src/main/java/google/registry/mosapi/MosApiMetrics.java index efa18ae68..d6a1257d3 100644 --- a/core/src/main/java/google/registry/mosapi/MosApiMetrics.java +++ b/core/src/main/java/google/registry/mosapi/MosApiMetrics.java @@ -227,7 +227,7 @@ public class MosApiMetrics { } private void pushBatchMetrics(ImmutableList states) { - Instant now = Instant.ofEpochMilli(clock.nowUtc().getMillis()); + Instant now = clock.now(); TimeInterval interval = new TimeInterval().setEndTime(now.toString()); Stream allTimeSeriesStream = states.stream().flatMap(state -> createMetricsForState(state, interval)); diff --git a/core/src/main/java/google/registry/persistence/converter/DurationUserType.java b/core/src/main/java/google/registry/persistence/converter/DurationUserType.java index bb5ba3448..aede1fcb7 100644 --- a/core/src/main/java/google/registry/persistence/converter/DurationUserType.java +++ b/core/src/main/java/google/registry/persistence/converter/DurationUserType.java @@ -21,12 +21,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; +import java.time.Duration; import java.util.Objects; import javax.annotation.Nullable; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; -import org.joda.time.Duration; -import org.joda.time.Period; import org.postgresql.util.PGInterval; /** @@ -108,43 +107,31 @@ public class DurationUserType implements UserType { } public static PGInterval convertToPGInterval(Duration duration) { - // When the period is created from duration by calling duration.toPeriod(), only precise fields - // in the period type will be used. Thus, only the hour, minute, second and millisecond fields - // on the period will be used. The year, month, week and day fields will not be populated: - // 1. If the duration is small, less than one day, then this method will just set - // hours/minutes/seconds correctly. - // 2. If the duration is larger than one day then all the remaining duration will - // be stored in the largest available field, hours in this case. - // So, when we convert the period to a PGInterval instance, we set the days field by extracting - // it from period's hours field. - Period period = duration.toPeriod(); PGInterval interval = new PGInterval(); - interval.setDays(period.getHours() / 24); - interval.setHours(period.getHours() % 24); - interval.setMinutes(period.getMinutes()); - double millis = (double) period.getMillis() / 1000; - interval.setSeconds(period.getSeconds() + millis); + long seconds = duration.getSeconds(); + int nanos = duration.getNano(); + interval.setDays((int) (seconds / 86400)); + seconds %= 86400; + interval.setHours((int) (seconds / 3600)); + seconds %= 3600; + interval.setMinutes((int) (seconds / 60)); + seconds %= 60; + interval.setSeconds(seconds + (double) nanos / 1_000_000_000); return interval; } @Nullable public static Duration convertToDuration(PGInterval dbData) { - PGInterval interval = null; - try { - interval = new PGInterval(dbData.toString()); - } catch (SQLException e) { - throw new RuntimeException(e); - } - - if (interval.equals(new PGInterval())) { + if (dbData == null) { return null; } - - final int days = interval.getDays(); - final int hours = interval.getHours(); - final int mins = interval.getMinutes(); - final int secs = (int) interval.getSeconds(); - final int millis = interval.getMicroSeconds() / 1000; - return new Period(0, 0, 0, days, hours, mins, secs, millis).toStandardDuration(); + double seconds = dbData.getSeconds(); + long fullSeconds = (long) seconds; + int nanos = (int) Math.round((seconds - fullSeconds) * 1_000_000_000); + return Duration.ofDays(dbData.getDays()) + .plusHours(dbData.getHours()) + .plusMinutes(dbData.getMinutes()) + .plusSeconds(fullSeconds) + .plusNanos(nanos); } } diff --git a/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java b/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java deleted file mode 100644 index 4a00b6cb5..000000000 --- a/core/src/main/java/google/registry/persistence/converter/LocalDateConverter.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 The Nomulus Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package google.registry.persistence.converter; - -import static google.registry.util.DateTimeUtils.toLocalDate; -import static google.registry.util.DateTimeUtils.toSqlDate; - -import jakarta.persistence.AttributeConverter; -import jakarta.persistence.Converter; -import java.sql.Date; -import org.joda.time.LocalDate; - -/** JPA converter for {@link LocalDate}, to/from {@link Date}. */ -@Converter(autoApply = true) -public class LocalDateConverter implements AttributeConverter { - - @Override - public Date convertToDatabaseColumn(LocalDate attribute) { - return attribute == null ? null : toSqlDate(attribute); - } - - @Override - public LocalDate convertToEntityAttribute(Date dbData) { - return dbData == null ? null : toLocalDate(dbData); - } -} diff --git a/core/src/main/java/google/registry/persistence/converter/TimedTransitionBaseUserType.java b/core/src/main/java/google/registry/persistence/converter/TimedTransitionBaseUserType.java index 6c4e2eb9f..b76fae2db 100644 --- a/core/src/main/java/google/registry/persistence/converter/TimedTransitionBaseUserType.java +++ b/core/src/main/java/google/registry/persistence/converter/TimedTransitionBaseUserType.java @@ -46,7 +46,7 @@ public abstract class TimedTransitionBaseUserType @Override Map toStringMap(TimedTransitionProperty map) { - return map.toValueMapInstant().entrySet().stream() + return map.toValueMap().entrySet().stream() .collect(toImmutableMap(e -> formatInstant(e.getKey()), e -> valueToString(e.getValue()))); } @@ -59,6 +59,6 @@ public abstract class TimedTransitionBaseUserType Ordering.natural(), e -> parseInstant(e.getKey()), e -> stringToValue(e.getValue()))); - return TimedTransitionProperty.fromValueMapInstant(valueMap); + return TimedTransitionProperty.fromValueMap(valueMap); } } diff --git a/core/src/main/java/google/registry/persistence/transaction/DelegatingReplicaJpaTransactionManager.java b/core/src/main/java/google/registry/persistence/transaction/DelegatingReplicaJpaTransactionManager.java index 8d7b647d4..6d6141a97 100644 --- a/core/src/main/java/google/registry/persistence/transaction/DelegatingReplicaJpaTransactionManager.java +++ b/core/src/main/java/google/registry/persistence/transaction/DelegatingReplicaJpaTransactionManager.java @@ -34,7 +34,6 @@ import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.stream.Stream; -import org.joda.time.DateTime; /** * A {@link JpaTransactionManager} that load-balances across multiple read-only replicas. @@ -156,11 +155,6 @@ public class DelegatingReplicaJpaTransactionManager implements JpaTransactionMan }); } - @Override - public DateTime getTransactionTime() { - return getReplica().getTransactionTime(); - } - @Override public Instant getTxTime() { return getReplica().getTxTime(); diff --git a/core/src/main/java/google/registry/persistence/transaction/JpaTransactionManagerImpl.java b/core/src/main/java/google/registry/persistence/transaction/JpaTransactionManagerImpl.java index 4502a7d39..289933170 100644 --- a/core/src/main/java/google/registry/persistence/transaction/JpaTransactionManagerImpl.java +++ b/core/src/main/java/google/registry/persistence/transaction/JpaTransactionManagerImpl.java @@ -21,7 +21,6 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.config.RegistryConfig.getHibernateAllowNestedTransactions; import static google.registry.persistence.transaction.DatabaseException.throwIfSqlException; -import static google.registry.util.DateTimeUtils.toDateTime; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static java.util.AbstractMap.SimpleEntry; import static java.util.stream.Collectors.joining; @@ -83,7 +82,6 @@ import javax.annotation.Nullable; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Environment; -import org.joda.time.DateTime; /** Implementation of {@link JpaTransactionManager} for JPA compatible database. */ public class JpaTransactionManagerImpl implements JpaTransactionManager { @@ -340,11 +338,6 @@ public class JpaTransactionManagerImpl implements JpaTransactionManager { return TransactionIsolationLevel.fromMode(mode); } - @Override - public DateTime getTransactionTime() { - return toDateTime(getTxTime()); - } - @Override public Instant getTxTime() { assertInTransaction(); diff --git a/core/src/main/java/google/registry/persistence/transaction/TransactionManager.java b/core/src/main/java/google/registry/persistence/transaction/TransactionManager.java index e49f608f3..72a396f45 100644 --- a/core/src/main/java/google/registry/persistence/transaction/TransactionManager.java +++ b/core/src/main/java/google/registry/persistence/transaction/TransactionManager.java @@ -25,7 +25,6 @@ import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.Callable; import java.util.stream.Stream; -import org.joda.time.DateTime; /** * This interface defines the methods to execute database operations with or without a transaction. @@ -129,10 +128,6 @@ public interface TransactionManager { */ void reTransact(ThrowingRunnable work); - /** Returns the time associated with the start of this particular transaction attempt. */ - @Deprecated - DateTime getTransactionTime(); - /** Returns the Instant associated with the start of this particular transaction attempt. */ Instant getTxTime(); diff --git a/core/src/main/java/google/registry/rdap/RdapSearchActionBase.java b/core/src/main/java/google/registry/rdap/RdapSearchActionBase.java index 48fbe428f..aa4c83b30 100644 --- a/core/src/main/java/google/registry/rdap/RdapSearchActionBase.java +++ b/core/src/main/java/google/registry/rdap/RdapSearchActionBase.java @@ -282,7 +282,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase { * there are no pending deletes. * *

In such cases, it is sufficient to check whether {@code deletionTime} is equal to {@code - * END_OF_TIME}, because any other value means it has already been deleted. This allows us to use + * END_INSTANT}, because any other value means it has already been deleted. This allows us to use * an equality query for the deletion time. * * @param clazz the type of resource to be queried diff --git a/core/src/main/java/google/registry/rde/DomainToXjcConverter.java b/core/src/main/java/google/registry/rde/DomainToXjcConverter.java index 5e14a5537..b7f2da5c1 100644 --- a/core/src/main/java/google/registry/rde/DomainToXjcConverter.java +++ b/core/src/main/java/google/registry/rde/DomainToXjcConverter.java @@ -14,8 +14,6 @@ package google.registry.rde; -import static google.registry.util.DateTimeUtils.toDateTime; - import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import google.registry.model.domain.Domain; @@ -89,19 +87,19 @@ final class DomainToXjcConverter { // o An OPTIONAL element that contains the date and time of // the domain name object creation. This element MUST be present if // the domain name has been allocated. - bean.setCrDate(toDateTime(model.getCreationTime())); + bean.setCrDate(model.getCreationTime()); // o An OPTIONAL element that contains the date and time // identifying the end (expiration) of the domain name object's // registration period. This element MUST be present if the domain // name has been allocated. - bean.setExDate(toDateTime(model.getRegistrationExpirationTime())); + bean.setExDate(model.getRegistrationExpirationTime()); // o An OPTIONAL element that contains the date and time of // the most recent domain-name-object modification. This element // MUST NOT be present if the domain name object has never been // modified. - bean.setUpDate(toDateTime(model.getLastEppUpdateTime())); + bean.setUpDate(model.getLastEppUpdateTime()); // o An OPTIONAL element that contains the identifier of the // registrar that last updated the domain name object. This element @@ -114,7 +112,7 @@ final class DomainToXjcConverter { // the most recent domain object successful transfer. This element // MUST NOT be present if the domain name object has never been // transferred. - bean.setTrDate(toDateTime(model.getLastTransferTime())); + bean.setTrDate(model.getLastTransferTime()); // o One or more elements that contain the current status // descriptors associated with the domain name. @@ -226,9 +224,9 @@ final class DomainToXjcConverter { XjcEppcomTrStatusType.fromValue(model.getTransferStatus().getXmlName())); bean.setReRr(RdeUtils.makeXjcRdeRrType(model.getGainingRegistrarId())); bean.setAcRr(RdeUtils.makeXjcRdeRrType(model.getLosingRegistrarId())); - bean.setReDate(toDateTime(model.getTransferRequestTime())); - bean.setAcDate(toDateTime(model.getPendingTransferExpirationTime())); - bean.setExDate(toDateTime(model.getTransferredRegistrationExpirationTime())); + bean.setReDate(model.getTransferRequestTime()); + bean.setAcDate(model.getPendingTransferExpirationTime()); + bean.setExDate(model.getTransferredRegistrationExpirationTime()); return bean; } diff --git a/core/src/main/java/google/registry/rde/HostToXjcConverter.java b/core/src/main/java/google/registry/rde/HostToXjcConverter.java index cfedb5a15..ce3579933 100644 --- a/core/src/main/java/google/registry/rde/HostToXjcConverter.java +++ b/core/src/main/java/google/registry/rde/HostToXjcConverter.java @@ -15,7 +15,6 @@ package google.registry.rde; import static com.google.common.base.Preconditions.checkArgument; -import static google.registry.util.DateTimeUtils.toDateTime; import com.google.common.net.InetAddresses; import google.registry.model.domain.Domain; @@ -70,13 +69,13 @@ final class HostToXjcConverter { XjcRdeHost bean = new XjcRdeHost(); bean.setName(model.getHostName()); bean.setRoid(model.getRepoId()); - bean.setCrDate(toDateTime(model.getCreationTime())); - bean.setUpDate(toDateTime(model.getLastEppUpdateTime())); + bean.setCrDate(model.getCreationTime()); + bean.setUpDate(model.getLastEppUpdateTime()); bean.setCrRr(RdeAdapter.convertRr(model.getCreationRegistrarId(), null)); bean.setUpRr(RdeAdapter.convertRr(model.getLastEppUpdateRegistrarId(), null)); bean.setCrRr(RdeAdapter.convertRr(model.getCreationRegistrarId(), null)); bean.setClID(registrarId); - bean.setTrDate(toDateTime(lastTransferTime)); + bean.setTrDate(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/RdeCounter.java b/core/src/main/java/google/registry/rde/RdeCounter.java index 25aaddc6e..b3fcb27fd 100644 --- a/core/src/main/java/google/registry/rde/RdeCounter.java +++ b/core/src/main/java/google/registry/rde/RdeCounter.java @@ -14,8 +14,6 @@ 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; @@ -67,8 +65,8 @@ public final class RdeCounter { XjcRdeReport report = new XjcRdeReport(); report.setId(id); report.setKind(XjcRdeDepositTypeType.FULL); - report.setCrDate(toDateTime(watermark)); - report.setWatermark(toDateTime(watermark)); + report.setCrDate(watermark); + report.setWatermark(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 d9b5adc6f..4d79b075b 100644 --- a/core/src/main/java/google/registry/rde/RdeMarshaller.java +++ b/core/src/main/java/google/registry/rde/RdeMarshaller.java @@ -15,7 +15,6 @@ 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; @@ -75,7 +74,7 @@ public final class RdeMarshaller implements Serializable { contents.getContents().add(new XjcRdePolicyElement(policy)); XjcRdeDeposit deposit = new XjcRdeDeposit(); deposit.setId(depositId); - deposit.setWatermark(toDateTime(watermark)); + deposit.setWatermark(watermark); deposit.setType(XjcRdeDepositTypeType.FULL); if (revision > 0) { deposit.setResend(revision); diff --git a/core/src/main/java/google/registry/rde/RegistrarToXjcConverter.java b/core/src/main/java/google/registry/rde/RegistrarToXjcConverter.java index 543e654db..f19104e10 100644 --- a/core/src/main/java/google/registry/rde/RegistrarToXjcConverter.java +++ b/core/src/main/java/google/registry/rde/RegistrarToXjcConverter.java @@ -16,7 +16,6 @@ package google.registry.rde; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkState; -import static google.registry.util.DateTimeUtils.toDateTime; import com.google.common.collect.ImmutableMap; import google.registry.model.registrar.Registrar; @@ -140,13 +139,13 @@ final class RegistrarToXjcConverter { // o A element that contains the date and time of registrar- // object creation. - bean.setCrDate(toDateTime(model.getCreationTime())); + bean.setCrDate(model.getCreationTime()); // o An OPTIONAL element that contains the date and time of // the most recent RDE registrar-object modification. This element // MUST NOT be present if the rdeRegistrar object has never been // modified. - bean.setUpDate(toDateTime(model.getLastUpdateTime())); + bean.setUpDate(model.getLastUpdateTime()); return bean; } 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 3ddc8d804..950041c75 100644 --- a/core/src/main/java/google/registry/reporting/spec11/Spec11Module.java +++ b/core/src/main/java/google/registry/reporting/spec11/Spec11Module.java @@ -14,7 +14,6 @@ package google.registry.reporting.spec11; -import static google.registry.util.DateTimeUtils.toJodaLocalDate; import static java.lang.annotation.RetentionPolicy.RUNTIME; import dagger.Module; @@ -32,7 +31,7 @@ public class Spec11Module { @Provides @Spec11ReportFilePath static String provideSpec11ReportFilePath(LocalDate localDate) { - return Spec11Pipeline.getSpec11ReportFilePath(toJodaLocalDate(localDate)); + return Spec11Pipeline.getSpec11ReportFilePath(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 2495ba6fe..44e930516 100644 --- a/core/src/main/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParser.java +++ b/core/src/main/java/google/registry/reporting/spec11/Spec11RegistrarThreatMatchesParser.java @@ -15,7 +15,6 @@ 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; @@ -100,8 +99,7 @@ public class Spec11RegistrarThreatMatchesParser { } private BlobId getGcsFilename(LocalDate localDate) { - return BlobId.of( - reportingBucket, Spec11Pipeline.getSpec11ReportFilePath(toJodaLocalDate(localDate))); + return BlobId.of(reportingBucket, Spec11Pipeline.getSpec11ReportFilePath(localDate)); } private RegistrarThreatMatches parseRegistrarThreatMatch(String line) throws JSONException { diff --git a/core/src/main/java/google/registry/request/JsonResponse.java b/core/src/main/java/google/registry/request/JsonResponse.java index 78809a359..6f7cf06e1 100644 --- a/core/src/main/java/google/registry/request/JsonResponse.java +++ b/core/src/main/java/google/registry/request/JsonResponse.java @@ -21,8 +21,8 @@ import static com.google.common.net.MediaType.JSON_UTF_8; import static org.json.simple.JSONValue.toJSONString; import jakarta.inject.Inject; +import java.time.Instant; import java.util.Map; -import org.joda.time.DateTime; /** JSON response object. */ public class JsonResponse { @@ -72,7 +72,7 @@ public class JsonResponse { * *

see Response#setDateHeader */ - public void setDateHeader(String header, DateTime timestamp) { + public void setDateHeader(String header, Instant timestamp) { response.setDateHeader(header, timestamp); } } diff --git a/core/src/main/java/google/registry/request/RequestHandler.java b/core/src/main/java/google/registry/request/RequestHandler.java index d1f81151b..f6ae5166c 100644 --- a/core/src/main/java/google/registry/request/RequestHandler.java +++ b/core/src/main/java/google/registry/request/RequestHandler.java @@ -34,11 +34,11 @@ import jakarta.inject.Provider; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Dagger-based request processor. @@ -172,7 +172,7 @@ public class RequestHandler { .build(); // Apply the selected Route to the component to produce an Action instance, and run it. boolean success = true; - DateTime startTime = clock.nowUtc(); + Instant startTime = clock.now(); try { route.get().instantiator().apply(component).run(); if (route.get().action().automaticallyPrintOk()) { @@ -188,7 +188,7 @@ public class RequestHandler { logger.atSevere().withCause(e).log("Encountered internal server error"); } finally { requestMetrics.record( - new Duration(startTime, clock.nowUtc()), + Duration.between(startTime, clock.now()), path, method, authResult.get().authLevel(), diff --git a/core/src/main/java/google/registry/request/RequestMetrics.java b/core/src/main/java/google/registry/request/RequestMetrics.java index ef805a28c..e0d69ba74 100644 --- a/core/src/main/java/google/registry/request/RequestMetrics.java +++ b/core/src/main/java/google/registry/request/RequestMetrics.java @@ -25,9 +25,9 @@ import com.google.monitoring.metrics.EventMetric; import com.google.monitoring.metrics.LabelDescriptor; import com.google.monitoring.metrics.MetricRegistryImpl; import google.registry.request.auth.AuthSettings.AuthLevel; +import java.time.Duration; import java.util.List; import java.util.stream.Collectors; -import org.joda.time.Duration; class RequestMetrics { @@ -54,14 +54,14 @@ class RequestMetrics { public void record( Duration duration, String path, Action.Method method, AuthLevel authLevel, boolean success) { requestDurationMetric.record( - duration.getMillis(), + duration.toMillis(), truncatePath(path), String.valueOf(method), String.valueOf(authLevel), String.valueOf(success)); logger.atInfo().log( "Action called for path=%s, method=%s, authLevel=%s, success=%s. Took: %.3fs.", - path, method, authLevel, success, duration.getMillis() / 1000d); + path, method, authLevel, success, duration.toMillis() / 1000d); } private static String truncatePath(String path) { diff --git a/core/src/main/java/google/registry/request/Response.java b/core/src/main/java/google/registry/request/Response.java index 88bd6c5d5..0bb13eb76 100644 --- a/core/src/main/java/google/registry/request/Response.java +++ b/core/src/main/java/google/registry/request/Response.java @@ -19,7 +19,7 @@ import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; -import org.joda.time.DateTime; +import java.time.Instant; /** * HTTP request response object. @@ -55,7 +55,7 @@ public interface Response { * * @see HttpServletResponse#setDateHeader(String, long) */ - void setDateHeader(String header, DateTime timestamp); + void setDateHeader(String header, Instant timestamp); /** * Adds a cookie to the response diff --git a/core/src/main/java/google/registry/request/ResponseImpl.java b/core/src/main/java/google/registry/request/ResponseImpl.java index 97807f050..059975cc8 100644 --- a/core/src/main/java/google/registry/request/ResponseImpl.java +++ b/core/src/main/java/google/registry/request/ResponseImpl.java @@ -20,7 +20,7 @@ import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; -import org.joda.time.DateTime; +import java.time.Instant; /** HTTP response object. */ public final class ResponseImpl implements Response { @@ -62,8 +62,8 @@ public final class ResponseImpl implements Response { } @Override - public void setDateHeader(String header, DateTime timestamp) { - rsp.setDateHeader(header, timestamp.getMillis()); + public void setDateHeader(String header, Instant timestamp) { + rsp.setDateHeader(header, timestamp.toEpochMilli()); } @Override diff --git a/core/src/main/java/google/registry/security/XsrfTokenManager.java b/core/src/main/java/google/registry/security/XsrfTokenManager.java index 2538d583e..936d82072 100644 --- a/core/src/main/java/google/registry/security/XsrfTokenManager.java +++ b/core/src/main/java/google/registry/security/XsrfTokenManager.java @@ -17,7 +17,6 @@ package google.registry.security; import static com.google.common.io.BaseEncoding.base64Url; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.joda.time.DateTimeZone.UTC; import com.google.common.base.Joiner; import com.google.common.base.Splitter; @@ -26,9 +25,9 @@ import com.google.common.hash.Hashing; import google.registry.model.server.ServerSecret; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; import java.util.List; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** Helper class for generating and validate XSRF tokens. */ public final class XsrfTokenManager { @@ -40,7 +39,7 @@ public final class XsrfTokenManager { public static final String P_CSRF_TOKEN = "xsrfToken"; /** Maximum age of an acceptable XSRF token. */ - private static final Duration XSRF_VALIDITY = Duration.standardDays(1); + private static final Duration XSRF_VALIDITY = Duration.ofDays(1); /** Token version identifier for version 1. */ private static final String VERSION_1 = "1"; @@ -57,7 +56,7 @@ public final class XsrfTokenManager { /** Generates an XSRF token for a given user based on email address. */ public String generateToken(String email) { checkArgumentNotNull(email); - long timestampMillis = clock.nowUtc().getMillis(); + long timestampMillis = clock.now().toEpochMilli(); return encodeToken(ServerSecret.get().asBytes(), email, timestampMillis); } @@ -97,7 +96,7 @@ public final class XsrfTokenManager { logger.atWarning().log("Bad timestamp in XSRF token: %s", token); return false; } - if (new DateTime(timestampMillis, UTC).plus(XSRF_VALIDITY).isBefore(clock.nowUtc())) { + if (Instant.ofEpochMilli(timestampMillis).plus(XSRF_VALIDITY).isBefore(clock.now())) { logger.atInfo().log("Expired timestamp in XSRF token: %s", token); return false; } diff --git a/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java b/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java index ab7ba443b..555f552c0 100644 --- a/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java +++ b/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java @@ -34,7 +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.Date; import java.util.Optional; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; @@ -128,7 +128,7 @@ public final class TmchCertificateAuthority { */ public void verify(X509Certificate cert) throws GeneralSecurityException { synchronized (TmchCertificateAuthority.class) { - X509Utils.verifyCertificate(getAndValidateRoot(), getCrl(), cert, clock.nowUtc()); + X509Utils.verifyCertificate(getAndValidateRoot(), getCrl(), cert, clock.now()); } } @@ -152,7 +152,7 @@ public final class TmchCertificateAuthority { } catch (Exception e) { logger.atWarning().withCause(e).log("Old CRL is invalid, ignored during CRL update."); } - X509Utils.verifyCrl(getAndValidateRoot(), oldCrl, newCrl, clock.nowUtc()); + X509Utils.verifyCrl(getAndValidateRoot(), oldCrl, newCrl, clock.now()); TmchCrl.set(asciiCrl, url); } @@ -162,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(Timestamp.from(clock.now())); + root.checkValidity(Date.from(clock.now())); return root; } catch (Exception e) { if (e instanceof GeneralSecurityException generalSecurityException) { diff --git a/core/src/main/java/google/registry/tools/CommandUtilities.java b/core/src/main/java/google/registry/tools/CommandUtilities.java index 215b199d6..4a2a31c8e 100644 --- a/core/src/main/java/google/registry/tools/CommandUtilities.java +++ b/core/src/main/java/google/registry/tools/CommandUtilities.java @@ -20,7 +20,7 @@ import google.registry.model.ForeignKeyUtils; import google.registry.model.domain.Domain; import google.registry.model.host.Host; import google.registry.persistence.VKey; -import org.joda.time.DateTime; +import java.time.Instant; /** Container class for static utility methods. */ class CommandUtilities { @@ -36,7 +36,7 @@ class CommandUtilities { this.clazz = clazz; } - public VKey getKey(String uniqueId, DateTime now) { + public VKey getKey(String uniqueId, Instant now) { return ForeignKeyUtils.loadKey(clazz, uniqueId, now) .orElseThrow( () -> diff --git a/core/src/main/java/google/registry/tools/ConfigureFeatureFlagCommand.java b/core/src/main/java/google/registry/tools/ConfigureFeatureFlagCommand.java index 9c04d5c36..255654d93 100644 --- a/core/src/main/java/google/registry/tools/ConfigureFeatureFlagCommand.java +++ b/core/src/main/java/google/registry/tools/ConfigureFeatureFlagCommand.java @@ -48,10 +48,7 @@ public class ConfigureFeatureFlagCommand extends MutatingCommand { for (FeatureName name : mainParameters) { Optional oldFlag = FeatureFlag.getUncached(name); FeatureFlag.Builder newFlagBuilder = - new FeatureFlag() - .asBuilder() - .setFeatureName(name) - .setStatusMapInstant(featureStatusTransitions); + new FeatureFlag().asBuilder().setFeatureName(name).setStatusMap(featureStatusTransitions); stageEntityChange(oldFlag.orElse(null), newFlagBuilder.build()); } } diff --git a/core/src/main/java/google/registry/tools/ConfigureTldCommand.java b/core/src/main/java/google/registry/tools/ConfigureTldCommand.java index 27a66202d..59d141788 100644 --- a/core/src/main/java/google/registry/tools/ConfigureTldCommand.java +++ b/core/src/main/java/google/registry/tools/ConfigureTldCommand.java @@ -40,6 +40,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; import java.util.Arrays; import java.util.HashSet; import java.util.Map; @@ -48,7 +49,6 @@ import java.util.Set; import java.util.stream.Collectors; import org.joda.money.CurrencyUnit; import org.joda.money.Money; -import org.joda.time.DateTime; import org.yaml.snakeyaml.Yaml; /** Command to create or update a {@link Tld} using a YAML file. */ @@ -152,7 +152,7 @@ public class ConfigureTldCommand extends MutatingCommand { checkCurrency(newTld); // bsaEnrollStartTime only exists in DB. Need to carry it over to the updated copy. See Tld.java // for more information. - Optional bsaEnrollTime = + Optional bsaEnrollTime = Optional.ofNullable(oldTld).flatMap(Tld::getBsaEnrollStartTime); if (bsaEnrollTime.isPresent()) { newTld = newTld.asBuilder().setBsaEnrollStartTime(bsaEnrollTime).build(); diff --git a/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java b/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java index 17173f8ae..046403a3a 100644 --- a/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java +++ b/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java @@ -19,7 +19,6 @@ import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; -import static google.registry.util.DateTimeUtils.toInstant; import static google.registry.util.RegistrarUtils.normalizeRegistrarName; import static java.nio.charset.StandardCharsets.US_ASCII; @@ -41,6 +40,7 @@ import google.registry.util.Clock; import jakarta.inject.Inject; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; @@ -50,7 +50,6 @@ import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.joda.money.CurrencyUnit; -import org.joda.time.DateTime; /** Shared base class for commands to create or update a {@link Registrar}. */ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { @@ -275,7 +274,7 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { @Override protected final void init() throws Exception { initRegistrarCommand(); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); for (String clientId : mainParameters) { Registrar oldRegistrar = getOldRegistrar(clientId); Registrar.Builder builder = @@ -339,10 +338,9 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { verify( oldRegistrar.getClientCertificate().isPresent(), "Primary cert is absent. Rotation may remove a failover certificate still in use."); - builder.setFailoverClientCertificate( - oldRegistrar.getClientCertificate().get(), toInstant(now)); + builder.setFailoverClientCertificate(oldRegistrar.getClientCertificate().get(), now); } - builder.setClientCertificate(asciiCert, toInstant(now)); + builder.setClientCertificate(asciiCert, now); } if (rotatePrimaryCert && clientCertificateFilename == null) { throw new IllegalArgumentException("--rotate_primary_cert must be used with --cert_file."); @@ -353,7 +351,7 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { if (!asciiCert.equals("")) { certificateChecker.validateCertificate(asciiCert); } - builder.setFailoverClientCertificate(asciiCert, toInstant(now)); + builder.setFailoverClientCertificate(asciiCert, now); } Optional.ofNullable(ianaId).ifPresent(i -> builder.setIanaIdentifier(i.orElse(null))); Optional.ofNullable(poNumber).ifPresent(builder::setPoNumber); diff --git a/core/src/main/java/google/registry/tools/CreateReservedListCommand.java b/core/src/main/java/google/registry/tools/CreateReservedListCommand.java index 968a01409..c6c08feff 100644 --- a/core/src/main/java/google/registry/tools/CreateReservedListCommand.java +++ b/core/src/main/java/google/registry/tools/CreateReservedListCommand.java @@ -26,8 +26,8 @@ import com.google.common.base.Splitter; import com.google.common.base.Strings; import google.registry.model.tld.label.ReservedList; import java.nio.file.Files; +import java.time.Instant; import java.util.List; -import org.joda.time.DateTime; /** Command to create a {@link ReservedList}. */ @Parameters(separators = " =", commandDescription = "Create a ReservedList.") @@ -50,7 +50,7 @@ final class CreateReservedListCommand extends CreateOrUpdateReservedListCommand if (!override) { validateListName(name); } - DateTime now = clock.nowUtc(); + Instant now = clock.now(); List allLines = Files.readAllLines(input, UTF_8); reservedList = new ReservedList.Builder() diff --git a/core/src/main/java/google/registry/tools/DomainLockUtils.java b/core/src/main/java/google/registry/tools/DomainLockUtils.java index e40394410..690e7becd 100644 --- a/core/src/main/java/google/registry/tools/DomainLockUtils.java +++ b/core/src/main/java/google/registry/tools/DomainLockUtils.java @@ -18,8 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument; 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; @@ -40,10 +38,10 @@ import google.registry.request.Action; import google.registry.util.StringGenerator; import jakarta.inject.Inject; import jakarta.inject.Named; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Utility functions for validating and applying {@link RegistryLock}s. @@ -135,11 +133,11 @@ public final class DomainLockUtils { String domainName, String registrarId, @Nullable String registryLockEmail, boolean isAdmin) { return tm().transact( () -> { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); RegistryLock newLock = RegistryLockDao.save( createLockBuilder(domainName, registrarId, registryLockEmail, isAdmin) - .setLockCompletionTime(toInstant(now)) + .setLockCompletionTime(now) .build()); applyLockStatuses(newLock, now, isAdmin); setAsRelock(newLock); @@ -157,11 +155,11 @@ public final class DomainLockUtils { RegistryLock lock = tm().transact( () -> { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); RegistryLock result = RegistryLockDao.save( createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration) - .setUnlockCompletionTime(toInstant(now)) + .setUnlockCompletionTime(now) .build()); removeLockStatuses(result, isAdmin, now); return result; @@ -202,34 +200,32 @@ public final class DomainLockUtils { String.valueOf(lockRevisionId), RelockDomainAction.PREVIOUS_ATTEMPTS_PARAM, String.valueOf(previousAttempts)), - toJavaDuration(countdown))); + countdown)); } private RegistryLock verifyAndApplyLock(RegistryLock lock, boolean isAdmin) { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); checkArgument( - !lock.isLockRequestExpired(toInstant(now)), - "The pending lock has expired; please try again"); + !lock.isLockRequestExpired(now), "The pending lock has expired; please try again"); checkArgument(!lock.isSuperuser() || isAdmin, "Non-admin user cannot complete admin lock"); RegistryLock newLock = - RegistryLockDao.save(lock.asBuilder().setLockCompletionTime(toInstant(now)).build()); + RegistryLockDao.save(lock.asBuilder().setLockCompletionTime(now).build()); setAsRelock(newLock); applyLockStatuses(newLock, now, isAdmin); return newLock; } private RegistryLock verifyAndApplyUnlock(RegistryLock lock, boolean isAdmin) { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); checkArgument( - !lock.isUnlockRequestExpired(toInstant(now)), - "The pending unlock has expired; please try again"); + !lock.isUnlockRequestExpired(now), "The pending unlock has expired; please try again"); checkArgument(isAdmin || !lock.isSuperuser(), "Non-admin user cannot complete admin unlock"); RegistryLock newLock = - RegistryLockDao.save(lock.asBuilder().setUnlockCompletionTime(toInstant(now)).build()); + RegistryLockDao.save(lock.asBuilder().setUnlockCompletionTime(now).build()); removeLockStatuses(newLock, isAdmin, now); return newLock; } @@ -241,7 +237,7 @@ public final class DomainLockUtils { private RegistryLock.Builder createLockBuilder( String domainName, String registrarId, @Nullable String registryLockEmail, boolean isAdmin) { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); Domain domain = getDomain(domainName, registrarId, now); verifyDomainNotLocked(domain, isAdmin); @@ -250,7 +246,7 @@ public final class DomainLockUtils { .ifPresent( previousLock -> checkArgument( - previousLock.isLockRequestExpired(toInstant(now)) + previousLock.isLockRequestExpired(now) || previousLock.getUnlockCompletionTime().isPresent() || isAdmin, "A pending or completed lock action already exists for %s", @@ -266,7 +262,7 @@ public final class DomainLockUtils { private RegistryLock.Builder createUnlockBuilder( String domainName, String registrarId, boolean isAdmin, Optional relockDuration) { - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); Domain domain = getDomain(domainName, registrarId, now); Optional lockOptional = RegistryLockDao.getMostRecentVerifiedLockByRepoId(domain.getRepoId()); @@ -285,7 +281,7 @@ public final class DomainLockUtils { new RegistryLock.Builder() .setRepoId(domain.getRepoId()) .setDomainName(domainName) - .setLockCompletionTime(toInstant(now)) + .setLockCompletionTime(now) .setRegistrarId(registrarId)); } else { RegistryLock lock = @@ -296,7 +292,7 @@ public final class DomainLockUtils { checkArgument( lock.isLocked(), "Lock object for domain %s is not currently locked", domainName); checkArgument( - lock.getUnlockRequestTime().isEmpty() || lock.isUnlockRequestExpired(toInstant(now)), + lock.getUnlockRequestTime().isEmpty() || lock.isUnlockRequestExpired(now), "A pending unlock action already exists for %s", domainName); checkArgument( @@ -311,7 +307,7 @@ public final class DomainLockUtils { return newLockBuilder .setVerificationCode(stringGenerator.createString(VERIFICATION_CODE_LENGTH)) .isSuperuser(isAdmin) - .setUnlockRequestTime(toInstant(now)) + .setUnlockRequestTime(now) .setRegistrarId(registrarId); } @@ -329,7 +325,7 @@ public final class DomainLockUtils { domain.getDomainName()); } - private Domain getDomain(String domainName, String registrarId, DateTime now) { + private Domain getDomain(String domainName, String registrarId, Instant now) { Domain domain = ForeignKeyUtils.loadResource(Domain.class, domainName, now) .orElseThrow(() -> new IllegalArgumentException("Domain doesn't exist")); @@ -351,7 +347,7 @@ public final class DomainLockUtils { String.format("Invalid verification code \"%s\"", verificationCode))); } - private void applyLockStatuses(RegistryLock lock, DateTime lockTime, boolean isAdmin) { + private void applyLockStatuses(RegistryLock lock, Instant lockTime, boolean isAdmin) { Domain domain = getDomain(lock.getDomainName(), lock.getRegistrarId(), lockTime); verifyDomainNotLocked(domain, isAdmin); @@ -364,7 +360,7 @@ public final class DomainLockUtils { saveEntities(newDomain, lock, lockTime, true); } - private void removeLockStatuses(RegistryLock lock, boolean isAdmin, DateTime unlockTime) { + private void removeLockStatuses(RegistryLock lock, boolean isAdmin, Instant unlockTime) { Domain domain = getDomain(lock.getDomainName(), lock.getRegistrarId(), unlockTime); verifyDomainLocked(domain, isAdmin); @@ -378,7 +374,7 @@ public final class DomainLockUtils { saveEntities(newDomain, lock, unlockTime, false); } - private static void saveEntities(Domain domain, RegistryLock lock, DateTime now, boolean isLock) { + private static void saveEntities(Domain domain, RegistryLock lock, Instant now, boolean isLock) { String reason = String.format( "%s of a domain through a RegistryLock operation", isLock ? "Lock" : "Unlock"); @@ -388,7 +384,7 @@ public final class DomainLockUtils { .setBySuperuser(lock.isSuperuser()) .setRequestedByRegistrar(!lock.isSuperuser()) .setType(HistoryEntry.Type.DOMAIN_UPDATE) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .setDomain(domain) .setReason(reason) .build(); @@ -401,8 +397,8 @@ public final class DomainLockUtils { .setTargetId(domain.getForeignKey()) .setRegistrarId(domain.getCurrentSponsorRegistrarId()) .setCost(Tld.get(domain.getTld()).getRegistryLockOrUnlockBillingCost()) - .setEventTime(toInstant(now)) - .setBillingTime(toInstant(now)) + .setEventTime(now) + .setBillingTime(now) .setDomainHistory(domainHistory) .build(); tm().insert(billingEvent); diff --git a/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java b/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java index 07d81b3e3..fc416a389 100644 --- a/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java +++ b/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java @@ -19,7 +19,6 @@ import static com.google.common.io.BaseEncoding.base16; import static google.registry.model.tld.Tlds.assertTldExists; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.util.DateTimeUtils.isBeforeOrAt; -import static google.registry.util.DateTimeUtils.toInstant; import static java.nio.charset.StandardCharsets.US_ASCII; import com.beust.jcommander.Parameter; @@ -36,9 +35,9 @@ import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.time.Instant; import java.util.List; import java.util.Map; -import org.joda.time.DateTime; import org.json.simple.JSONValue; /** Command to generate a report of all DNS data. */ @@ -66,7 +65,7 @@ final class GenerateDnsReportCommand implements Command { } private class Generator { - private final DateTime now = clock.nowUtc(); + private final Instant now = clock.now(); private final StringBuilder result = new StringBuilder(); private boolean first = true; @@ -81,8 +80,7 @@ final class GenerateDnsReportCommand implements Command { .list()); for (Domain domain : domains) { // Skip deleted domains and domains that don't get published to DNS. - if (isBeforeOrAt(domain.getDeletionTime(), toInstant(now)) - || !domain.shouldPublishToDns()) { + if (isBeforeOrAt(domain.getDeletionTime(), now) || !domain.shouldPublishToDns()) { continue; } write(domain); @@ -91,7 +89,7 @@ final class GenerateDnsReportCommand implements Command { Iterable nameservers = tm().transact(() -> tm().loadAllOf(Host.class)); for (Host nameserver : nameservers) { // Skip deleted hosts and external hosts. - if (isBeforeOrAt(nameserver.getDeletionTime(), toInstant(now)) + if (isBeforeOrAt(nameserver.getDeletionTime(), now) || nameserver.getInetAddresses().isEmpty()) { continue; } diff --git a/core/src/main/java/google/registry/tools/GenerateLordnCommand.java b/core/src/main/java/google/registry/tools/GenerateLordnCommand.java index 712d864b8..0aecc3f8c 100644 --- a/core/src/main/java/google/registry/tools/GenerateLordnCommand.java +++ b/core/src/main/java/google/registry/tools/GenerateLordnCommand.java @@ -29,7 +29,8 @@ import jakarta.inject.Inject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import org.joda.time.DateTime; +import java.time.Duration; +import java.time.Instant; /** Command to generate a LORDN CSV file for an entire TLD. */ @Parameters(separators = " =", commandDescription = "Generate LORDN CSV file") @@ -59,7 +60,7 @@ final class GenerateLordnCommand implements Command { @Override public void run() throws IOException { - DateTime now = clock.nowUtc(); + Instant now = clock.now(); ImmutableList.Builder claimsCsv = new ImmutableList.Builder<>(); ImmutableList.Builder sunriseCsv = new ImmutableList.Builder<>(); tm().transact( @@ -80,7 +81,7 @@ final class GenerateLordnCommand implements Command { ImmutableList sunriseRows = sunriseCsv.build(); ImmutableList sunriseAll = new ImmutableList.Builder() - .add(String.format("1,%s,%d", now.plusMillis(1), sunriseRows.size())) + .add(String.format("1,%s,%d", now.plus(Duration.ofMillis(1)), sunriseRows.size())) .add(LordnTaskUtils.COLUMNS_SUNRISE) .addAll(sunriseRows) .build(); diff --git a/core/src/main/java/google/registry/tools/GenerateZoneFilesCommand.java b/core/src/main/java/google/registry/tools/GenerateZoneFilesCommand.java index c82fd402d..6219f6463 100644 --- a/core/src/main/java/google/registry/tools/GenerateZoneFilesCommand.java +++ b/core/src/main/java/google/registry/tools/GenerateZoneFilesCommand.java @@ -15,7 +15,8 @@ package google.registry.tools; import static google.registry.model.tld.Tlds.assertTldsExist; -import static org.joda.time.Duration.standardMinutes; +import static google.registry.util.DateTimeUtils.toLocalDate; +import static java.time.ZoneOffset.UTC; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; @@ -25,9 +26,10 @@ import google.registry.tools.server.GenerateZoneFilesAction; import google.registry.util.Clock; import jakarta.inject.Inject; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.Map; -import org.joda.time.DateTime; /** Command to generate zone files. */ @Parameters(separators = " =", commandDescription = "Generate zone files") @@ -45,7 +47,7 @@ final class GenerateZoneFilesCommand implements CommandWithConnection { "The date to generate the file for (defaults to today, or yesterday if run " + "before 00:02).", validateWith = DateParameter.class) - private DateTime exportDate; + private Instant exportDate; @Inject Clock clock; @@ -59,7 +61,8 @@ final class GenerateZoneFilesCommand implements CommandWithConnection { @Override public void run() throws IOException { if (exportDate == null) { - exportDate = clock.nowUtc().minus(standardMinutes(2)).withTimeAtStartOfDay(); + exportDate = + toLocalDate(clock.now().minus(Duration.ofMinutes(2))).atStartOfDay(UTC).toInstant(); } assertTldsExist(mainParameters); ImmutableMap params = ImmutableMap.of( diff --git a/core/src/main/java/google/registry/tools/GetEppResourceCommand.java b/core/src/main/java/google/registry/tools/GetEppResourceCommand.java index 69b546cc1..4a61640d4 100644 --- a/core/src/main/java/google/registry/tools/GetEppResourceCommand.java +++ b/core/src/main/java/google/registry/tools/GetEppResourceCommand.java @@ -19,10 +19,11 @@ import static com.google.common.base.Preconditions.checkArgument; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import google.registry.model.EppResource; +import google.registry.tools.params.InstantParameter; import google.registry.util.Clock; import jakarta.inject.Inject; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** Abstract command to print one or more resources to stdout. */ @Parameters(separators = " =") @@ -30,8 +31,9 @@ abstract class GetEppResourceCommand implements Command { @Parameter( names = "--read_timestamp", - description = "Timestamp to use when reading. May not be in the past.") - protected DateTime readTimestamp; + description = "Timestamp to use when reading. May not be in the past.", + converter = InstantParameter.class) + protected Instant readTimestamp; @Parameter( names = "--expand", @@ -60,7 +62,7 @@ abstract class GetEppResourceCommand implements Command { @Override public void run() { - DateTime now = clock.nowUtc(); + Instant now = clock.now(); if (readTimestamp == null) { readTimestamp = now; } diff --git a/core/src/main/java/google/registry/tools/GetHistoryEntriesCommand.java b/core/src/main/java/google/registry/tools/GetHistoryEntriesCommand.java index c28d7f683..f1a98fbd1 100644 --- a/core/src/main/java/google/registry/tools/GetHistoryEntriesCommand.java +++ b/core/src/main/java/google/registry/tools/GetHistoryEntriesCommand.java @@ -64,7 +64,7 @@ final class GetHistoryEntriesCommand implements Command { checkArgument( type != null && uniqueId != null, "If either of 'type' or 'id' are set then both must be"); - VKey parentKey = type.getKey(uniqueId, clock.nowUtc()); + VKey parentKey = type.getKey(uniqueId, clock.now()); historyEntries = HistoryEntryDao.loadHistoryObjectsForResource(parentKey, after, before); } else { historyEntries = HistoryEntryDao.loadAllHistoryObjects(after, before); diff --git a/core/src/main/java/google/registry/tools/GsonUtils.java b/core/src/main/java/google/registry/tools/GsonUtils.java index 53331629d..a5525898b 100644 --- a/core/src/main/java/google/registry/tools/GsonUtils.java +++ b/core/src/main/java/google/registry/tools/GsonUtils.java @@ -27,9 +27,11 @@ import google.registry.model.adapters.SerializableJsonTypeAdapter; import google.registry.util.CidrAddressBlock; import google.registry.util.CidrAddressBlock.CidrAddressBlockAdapter; import google.registry.util.DateTimeTypeAdapter; +import google.registry.util.DurationTypeAdapter; import google.registry.util.InstantTypeAdapter; import java.io.IOException; import java.io.Serializable; +import java.time.Duration; import java.time.Instant; import org.joda.money.CurrencyUnit; import org.joda.time.DateTime; @@ -77,6 +79,7 @@ public class GsonUtils { .registerTypeAdapter(CidrAddressBlock.class, new CidrAddressBlockAdapter()) .registerTypeAdapter(CurrencyUnit.class, new CurrencyJsonAdapter()) .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(Duration.class, new DurationTypeAdapter()) .registerTypeAdapter(Instant.class, new InstantTypeAdapter()) .registerTypeAdapter(Serializable.class, new SerializableJsonTypeAdapter()) .registerTypeAdapterFactory(new ClassProcessingTypeAdapterFactory()) diff --git a/core/src/main/java/google/registry/tools/RenewDomainCommand.java b/core/src/main/java/google/registry/tools/RenewDomainCommand.java index 05650bd2c..da7b8b707 100644 --- a/core/src/main/java/google/registry/tools/RenewDomainCommand.java +++ b/core/src/main/java/google/registry/tools/RenewDomainCommand.java @@ -17,8 +17,6 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; import static google.registry.util.CollectionUtils.findDuplicates; -import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import com.beust.jcommander.Parameter; @@ -28,10 +26,10 @@ import com.google.template.soy.data.SoyMapData; import google.registry.flows.ResourceFlowUtils; import google.registry.model.domain.Domain; import google.registry.tools.soy.DomainRenewSoyInfo; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import java.util.List; -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; /** A command to renew domain(s) via EPP. */ @Parameters(separators = " =", commandDescription = "Renew domain(s) via EPP.") @@ -63,7 +61,8 @@ final class RenewDomainCommand extends MutatingEppToolCommand { arity = 1) Boolean requestedByRegistrar; - private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("YYYY-MM-dd"); + private static final DateTimeFormatter DATE_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC); @Override protected void initMutatingEppToolCommand() @@ -71,16 +70,14 @@ final class RenewDomainCommand extends MutatingEppToolCommand { String duplicates = Joiner.on(", ").join(findDuplicates(mainParameters)); checkArgument(duplicates.isEmpty(), "Duplicate domain arguments found: '%s'", duplicates); checkArgument(period < 10, "Cannot renew domains for 10 or more years"); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); for (String domainName : mainParameters) { - Domain domain = - ResourceFlowUtils.loadAndVerifyExistence(Domain.class, domainName, toInstant(now)); + Domain domain = ResourceFlowUtils.loadAndVerifyExistence(Domain.class, domainName, now); setSoyTemplate(DomainRenewSoyInfo.getInstance(), DomainRenewSoyInfo.RENEWDOMAIN); SoyMapData soyMapData = new SoyMapData( "domainName", domain.getDomainName(), - "expirationDate", - DATE_FORMATTER.print(toDateTime(domain.getRegistrationExpirationTime())), + "expirationDate", DATE_FORMATTER.format(domain.getRegistrationExpirationTime()), "period", String.valueOf(period)); if (requestedByRegistrar != null) { diff --git a/core/src/main/java/google/registry/tools/SetupOteCommand.java b/core/src/main/java/google/registry/tools/SetupOteCommand.java index e4bbf9c70..1cfc38be3 100644 --- a/core/src/main/java/google/registry/tools/SetupOteCommand.java +++ b/core/src/main/java/google/registry/tools/SetupOteCommand.java @@ -105,7 +105,7 @@ final class SetupOteCommand extends ConfirmingCommand { String asciiCert = MoreFiles.asCharSource(certFile, US_ASCII).read(); // Don't wait for create_registrar to fail if it's a bad certificate file. loadCertificate(asciiCert); - oteAccountBuilder.setCertificate(asciiCert, clock.nowUtc()); + oteAccountBuilder.setCertificate(asciiCert, clock.now()); } @Override @@ -124,11 +124,12 @@ final class SetupOteCommand extends ConfirmingCommand { && RegistryEnvironment.get() != RegistryEnvironment.UNITTEST) { builder.append( String.format( - """ +""" WARNING: Running against %s environment. Are \ -you sure you didn't mean to run this against sandbox (e.g. "-e SANDBOX")?""", +you sure you didn't mean to run this against sandbox (e.g. "-e SANDBOX")?\ +""", RegistryEnvironment.get())); } diff --git a/core/src/main/java/google/registry/tools/ShellCommand.java b/core/src/main/java/google/registry/tools/ShellCommand.java index 88bd0fbd4..156abdad8 100644 --- a/core/src/main/java/google/registry/tools/ShellCommand.java +++ b/core/src/main/java/google/registry/tools/ShellCommand.java @@ -38,6 +38,8 @@ import java.io.PrintStream; import java.io.StreamTokenizer; import java.io.StringReader; import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; @@ -55,8 +57,6 @@ import org.jline.reader.impl.LineReaderImpl; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import org.jline.terminal.impl.DumbTerminal; -import org.joda.time.DateTime; -import org.joda.time.Duration; /** * Implements a tiny shell interpreter for the nomulus tool. @@ -71,7 +71,7 @@ public class ShellCommand implements Command { private static final String RESET = "\u001b[0m"; private static final String NON_ALERT_COLOR = "\u001b[32m"; // green foreground private static final String ALERT_COLOR = "\u001b[1;41;97m"; // red background - private static final Duration IDLE_THRESHOLD = Duration.standardHours(1); + private static final Duration IDLE_THRESHOLD = Duration.ofHours(1); private static final String SUCCESS = "SUCCESS"; private static final String FAILURE = "FAILURE"; private static final String RUNNING = "RUNNING"; @@ -101,19 +101,21 @@ public class ShellCommand implements Command { names = {"--dont_exit_on_idle"}, description = """ - Prevents the shell from exiting on PROD after the 1 hour idle delay. - Will instead warn you and require re-running the command.""") + Prevents the shell from exiting on PROD after the 1 hour idle delay. + Will instead warn you and require re-running the command.\ + """) boolean dontExitOnIdle = false; @Parameter( names = {"--encapsulate_output"}, description = """ - Encapsulate command standard output and error by combining the two streams to - standard output and inserting a prefix ('out:' or 'err:') at the beginning of every - line of normal output and adding a line consisting of either 'SUCCESS' or - 'FAILURE ' at the end of the output for a - command, allowing the output to be easily parsed by wrapper scripts.""") + Encapsulate command standard output and error by combining the two streams to + standard output and inserting a prefix ('out:' or 'err:') at the beginning of every + line of normal output and adding a line consisting of either 'SUCCESS' or + 'FAILURE ' at the end of the output for a + command, allowing the output to be easily parsed by wrapper scripts.\ + """) boolean encapsulateOutput = false; ShellCommand(CommandRunner runner) throws IOException { @@ -215,7 +217,7 @@ public class ShellCommand implements Command { boolean beExtraCareful = (RegistryToolEnvironment.get() == RegistryToolEnvironment.PRODUCTION); setPrompt(RegistryToolEnvironment.get(), beExtraCareful); String line; - DateTime lastTime = clock.nowUtc(); + Instant lastTime = clock.now(); while (true) { try { line = lineReader.readLine(prompt); @@ -225,13 +227,14 @@ public class ShellCommand implements Command { // Make sure we're not idle for too long. Only relevant when we're "extra careful" if (!dontExitOnIdle && beExtraCareful - && lastTime.plus(IDLE_THRESHOLD).isBefore(clock.nowUtc())) { + && lastTime.plus(IDLE_THRESHOLD).isBefore(clock.now())) { throw new RuntimeException( """ - Been idle for too long, while in 'extra careful' mode. - The last command was saved in history. Please rerun the shell and try again."""); + Been idle for too long, while in 'extra careful' mode. + The last command was saved in history. Please rerun the shell and try again.\ + """); } - lastTime = clock.nowUtc(); + lastTime = clock.now(); String[] lineArgs = parseCommand(line); if (lineArgs.length == 0) { continue; diff --git a/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java b/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java index f5243d1c4..df176a7e2 100644 --- a/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java +++ b/core/src/main/java/google/registry/tools/UniformRapidSuspensionCommand.java @@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument; 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; @@ -40,12 +39,12 @@ 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.Instant; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.joda.time.DateTime; /** A command to suspend a domain for the Uniform Rapid Suspension process. */ @Parameters(separators = " =", @@ -126,9 +125,8 @@ final class UniformRapidSuspensionCommand extends MutatingEppToolCommand { protected void initMutatingEppToolCommand() throws ResourceFlowUtils.ResourceDoesNotExistException { superuser = true; - DateTime now = clock.nowUtc(); - Domain domain = - ResourceFlowUtils.loadAndVerifyExistence(Domain.class, domainName, toInstant(now)); + Instant now = clock.now(); + Domain domain = ResourceFlowUtils.loadAndVerifyExistence(Domain.class, domainName, now); Set missingHosts = difference(newHosts, ForeignKeyUtils.loadKeys(Host.class, newHosts, now).keySet()); checkArgument(missingHosts.isEmpty(), "Hosts do not exist: %s", missingHosts); diff --git a/core/src/main/java/google/registry/tools/UnrenewDomainCommand.java b/core/src/main/java/google/registry/tools/UnrenewDomainCommand.java index 9042afe4d..a567b6c81 100644 --- a/core/src/main/java/google/registry/tools/UnrenewDomainCommand.java +++ b/core/src/main/java/google/registry/tools/UnrenewDomainCommand.java @@ -16,16 +16,15 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableMap.toImmutableMap; import static google.registry.flows.domain.DomainFlowUtils.newAutorenewBillingEvent; import static google.registry.flows.domain.DomainFlowUtils.newAutorenewPollMessage; import static google.registry.flows.domain.DomainFlowUtils.updateAutorenewRecurrenceEndTime; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.formatInstant; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static google.registry.util.DateTimeUtils.minusYears; -import static google.registry.util.DateTimeUtils.toDateTime; -import static google.registry.util.DateTimeUtils.toInstant; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; @@ -48,8 +47,8 @@ import jakarta.inject.Inject; import java.io.UnsupportedEncodingException; import java.time.Instant; import java.util.List; +import java.util.Map.Entry; import java.util.Optional; -import org.joda.time.DateTime; /** * Command to unrenew a domain. @@ -82,16 +81,16 @@ class UnrenewDomainCommand extends ConfirmingCommand { @Override protected void init() throws UnsupportedEncodingException { checkArgument(period >= 1 && period <= 9, "Period must be in the range 1-9"); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); ImmutableSet.Builder domainsNonexistentBuilder = new ImmutableSet.Builder<>(); ImmutableSet.Builder domainsDeletingBuilder = new ImmutableSet.Builder<>(); ImmutableMultimap.Builder domainsWithDisallowedStatusesBuilder = new ImmutableMultimap.Builder<>(); - ImmutableMap.Builder domainsExpiringTooSoonBuilder = + ImmutableMap.Builder domainsExpiringTooSoonBuilder = new ImmutableMap.Builder<>(); for (String domainName : mainParameters) { - if (ForeignKeyUtils.loadKey(Domain.class, domainName, START_OF_TIME).isEmpty()) { + if (ForeignKeyUtils.loadKey(Domain.class, domainName, START_INSTANT).isEmpty()) { domainsNonexistentBuilder.add(domainName); continue; } @@ -102,10 +101,8 @@ class UnrenewDomainCommand extends ConfirmingCommand { } domainsWithDisallowedStatusesBuilder.putAll( domainName, Sets.intersection(domain.get().getStatusValues(), DISALLOWED_STATUSES)); - if (isBeforeOrAt( - toDateTime(minusYears(domain.get().getRegistrationExpirationTime(), period)), now)) { - domainsExpiringTooSoonBuilder.put( - domainName, toDateTime(domain.get().getRegistrationExpirationTime())); + if (isBeforeOrAt(minusYears(domain.get().getRegistrationExpirationTime(), period), now)) { + domainsExpiringTooSoonBuilder.put(domainName, domain.get().getRegistrationExpirationTime()); } } @@ -113,7 +110,7 @@ class UnrenewDomainCommand extends ConfirmingCommand { ImmutableSet domainsDeleting = domainsDeletingBuilder.build(); ImmutableMultimap domainsWithDisallowedStatuses = domainsWithDisallowedStatusesBuilder.build(); - ImmutableMap domainsExpiringTooSoon = domainsExpiringTooSoonBuilder.build(); + ImmutableMap domainsExpiringTooSoon = domainsExpiringTooSoonBuilder.build(); boolean foundInvalidDomains = !(domainsNonexistent.isEmpty() @@ -137,7 +134,10 @@ class UnrenewDomainCommand extends ConfirmingCommand { "Domains with disallowed statuses: %s\n\n", domainsWithDisallowedStatuses); } if (!domainsExpiringTooSoon.isEmpty()) { - errorPrintStream.printf("Domains expiring too soon: %s\n\n", domainsExpiringTooSoon); + errorPrintStream.printf( + "Domains expiring too soon: %s\n\n", + domainsExpiringTooSoon.entrySet().stream() + .collect(toImmutableMap(Entry::getKey, e -> formatInstant(e.getValue())))); } checkArgument(!foundInvalidDomains, "Aborting because some domains cannot be unrenewed"); } @@ -145,7 +145,7 @@ class UnrenewDomainCommand extends ConfirmingCommand { @Override protected String prompt() { StringBuilder resultBuilder = new StringBuilder(); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); for (String domainName : mainParameters) { Domain domain = ForeignKeyUtils.loadResource(Domain.class, domainName, now).get(); Instant previousTime = domain.getRegistrationExpirationTime(); @@ -169,7 +169,7 @@ class UnrenewDomainCommand extends ConfirmingCommand { private void unrenewDomain(String domainName) { tm().assertInTransaction(); - DateTime now = tm().getTransactionTime(); + Instant now = tm().getTxTime(); Optional domainOptional = ForeignKeyUtils.loadResource(Domain.class, domainName, now); // Transactional sanity checks on the off chance that something changed between init() running // and here. @@ -184,7 +184,7 @@ class UnrenewDomainCommand extends ConfirmingCommand { "Domain %s has prohibited status values", domainName); checkState( - minusYears(domain.getRegistrationExpirationTime(), period).isAfter(toInstant(now)), + minusYears(domain.getRegistrationExpirationTime(), period).isAfter(now), "Domain %s expires too soon", domainName); @@ -192,7 +192,7 @@ class UnrenewDomainCommand extends ConfirmingCommand { DomainHistory domainHistory = new DomainHistory.Builder() .setDomain(domain) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .setBySuperuser(true) .setType(Type.SYNTHETIC) .setRegistrarId(domain.getCurrentSponsorRegistrarId()) @@ -224,12 +224,12 @@ class UnrenewDomainCommand extends ConfirmingCommand { // End the old autorenew billing event and poll message now. BillingRecurrence existingBillingRecurrence = tm().loadByKey(domain.getAutorenewBillingEvent()); updateAutorenewRecurrenceEndTime( - domain, existingBillingRecurrence, toInstant(now), domainHistory.getHistoryEntryId()); + domain, existingBillingRecurrence, now, domainHistory.getHistoryEntryId()); Domain newDomain = domain .asBuilder() .setRegistrationExpirationTime(newExpirationTime) - .setLastEppUpdateTime(toInstant(now)) + .setLastEppUpdateTime(now) .setLastEppUpdateRegistrarId(domain.getCurrentSponsorRegistrarId()) .setAutorenewBillingEvent(newAutorenewEvent.createVKey()) .setAutorenewPollMessage(newAutorenewPollMessage.createVKey()) diff --git a/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java b/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java index 54bf06261..2ef3e554d 100644 --- a/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java +++ b/core/src/main/java/google/registry/tools/UpdateCursorsCommand.java @@ -41,7 +41,6 @@ final class UpdateCursorsCommand extends ConfirmingCommand implements Command { names = "--timestamp", description = "The new timestamp to set.", converter = InstantParameter.class, - validateWith = InstantParameter.class, required = true) private Instant newTimestamp; diff --git a/core/src/main/java/google/registry/tools/UpdatePremiumListCommand.java b/core/src/main/java/google/registry/tools/UpdatePremiumListCommand.java index bee609b54..43e24195e 100644 --- a/core/src/main/java/google/registry/tools/UpdatePremiumListCommand.java +++ b/core/src/main/java/google/registry/tools/UpdatePremiumListCommand.java @@ -63,7 +63,7 @@ class UpdatePremiumListCommand extends CreateOrUpdatePremiumListCommand { checkArgument(!inputData.isEmpty(), "New premium list data cannot be empty"); currency = existingList.getCurrency(); PremiumList updatedPremiumList = - PremiumListUtils.parseToPremiumList(name, currency, inputData, clock.nowUtc()); + PremiumListUtils.parseToPremiumList(name, currency, inputData, clock.now()); if (!existingList .getLabelsToPrices() .entrySet() 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 0ddfe54c6..43c2effd2 100644 --- a/core/src/main/java/google/registry/tools/server/GenerateZoneFilesAction.java +++ b/core/src/main/java/google/registry/tools/server/GenerateZoneFilesAction.java @@ -38,7 +38,6 @@ 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; @@ -239,7 +238,6 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA NS_FORMAT, domainLabel, tld.getDnsNsTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(dnsDefaultNsTtl) .toSeconds(), // Load the nameservers at the export time in case they've been renamed or deleted. @@ -251,7 +249,6 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA DS_FORMAT, domainLabel, tld.getDnsDsTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(dnsDefaultDsTtl) .toSeconds(), dsData.getKeyTag(), @@ -285,7 +282,6 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA A_FORMAT, stripTld(host.getHostName(), tldStr), tld.getDnsAPlusAaaaTtl() - .map(DateTimeUtils::toJavaDuration) .orElse(dnsDefaultATtl) .toSeconds(), rrSetClass, diff --git a/core/src/main/java/google/registry/tools/server/ListDomainsAction.java b/core/src/main/java/google/registry/tools/server/ListDomainsAction.java index 4b1e424f1..e62f3f90c 100644 --- a/core/src/main/java/google/registry/tools/server/ListDomainsAction.java +++ b/core/src/main/java/google/registry/tools/server/ListDomainsAction.java @@ -78,7 +78,7 @@ public final class ListDomainsAction extends ListObjectsAction { .setParameter("tlds", tlds) .setMaxResults(limit) .getResultStream() - .map(EppResourceUtils.transformAtTime(tm().getTransactionTime())) + .map(EppResourceUtils.transformAtTime(tm().getTxTime())) .collect(toImmutableList())); } } 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 20965695b..873f6363b 100644 --- a/core/src/main/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java +++ b/core/src/main/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java @@ -23,8 +23,8 @@ import static google.registry.persistence.PersistenceModule.TransactionIsolation import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.request.RequestParameters.PARAM_BATCH_SIZE; import static google.registry.request.RequestParameters.PARAM_TLDS; -import static google.registry.util.DateTimeUtils.END_OF_TIME; -import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.END_INSTANT; +import static jakarta.servlet.http.HttpServletResponse.SC_OK; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -36,12 +36,11 @@ import google.registry.request.auth.Auth; import jakarta.inject.Inject; import jakarta.persistence.TypedQuery; import java.time.Duration; +import java.time.Instant; 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; /** * A task that enqueues DNS publish tasks on all active domains on the specified TLD(s). @@ -86,7 +85,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable { private final Random random; - private final DateTime activeOrDeletedSince; + private final Instant activeOrDeletedSince; @Inject RefreshDnsForAllDomainsAction( @@ -94,13 +93,13 @@ public class RefreshDnsForAllDomainsAction implements Runnable { @Parameter(PARAM_TLDS) ImmutableSet tlds, @Parameter(PARAM_BATCH_SIZE) Optional batchSize, @Parameter("refreshQps") Optional refreshQps, - @Parameter("activeOrDeletedSince") Optional activeOrDeletedSince, + @Parameter("activeOrDeletedSince") Optional activeOrDeletedSince, Random random) { this.response = response; this.tlds = tlds; this.batchSize = batchSize.orElse(DEFAULT_BATCH_SIZE); this.refreshQps = refreshQps.orElse(DEFAULT_REFRESH_QPS); - this.activeOrDeletedSince = activeOrDeletedSince.orElse(END_OF_TIME); + this.activeOrDeletedSince = activeOrDeletedSince.orElse(END_INSTANT); this.random = random; } @@ -134,7 +133,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable { + " :activeOrDeletedSince", Long.class) .setParameter("tlds", tlds) - .setParameter("activeOrDeletedSince", toInstant(activeOrDeletedSince)) + .setParameter("activeOrDeletedSince", activeOrDeletedSince) .getSingleResult(); Duration smear = Duration.ofSeconds(Math.max(activeDomains / refreshQps, 1)); logger.atInfo().log("Smearing %d domain DNS refresh tasks across %s.", activeDomains, smear); @@ -150,7 +149,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable { TypedQuery query = tm().query(sql, String.class) .setParameter("tlds", tlds) - .setParameter("activeOrDeletedSince", toInstant(activeOrDeletedSince)); + .setParameter("activeOrDeletedSince", activeOrDeletedSince); lastInPreviousBatch.ifPresent(l -> query.setParameter("lastInPreviousBatch", l)); return query.setMaxResults(batchSize).getResultStream().collect(toImmutableList()); } @@ -164,7 +163,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable { 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); + response.setStatus(SC_OK); } return domainBatch; } diff --git a/core/src/main/java/google/registry/tools/server/ToolsServerModule.java b/core/src/main/java/google/registry/tools/server/ToolsServerModule.java index 366652156..5a1830d54 100644 --- a/core/src/main/java/google/registry/tools/server/ToolsServerModule.java +++ b/core/src/main/java/google/registry/tools/server/ToolsServerModule.java @@ -16,7 +16,7 @@ package google.registry.tools.server; import static com.google.common.base.Strings.emptyToNull; import static google.registry.request.RequestParameters.extractIntParameter; -import static google.registry.request.RequestParameters.extractOptionalDatetimeParameter; +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.extractRequiredParameter; @@ -26,8 +26,8 @@ import dagger.Provides; import google.registry.request.Parameter; import google.registry.tools.server.UpdateUserGroupAction.Mode; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** Dagger module for the tools package. */ @Module @@ -79,8 +79,8 @@ public class ToolsServerModule { @Provides @Parameter("activeOrDeletedSince") - static Optional provideDeletionTime(HttpServletRequest req) { - return extractOptionalDatetimeParameter(req, "activeOrDeletedSince"); + static Optional provideDeletionTime(HttpServletRequest req) { + return extractOptionalInstantParameter(req, "activeOrDeletedSince"); } @Provides diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleApiAction.java b/core/src/main/java/google/registry/ui/server/console/ConsoleApiAction.java index c244adca4..322c55992 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleApiAction.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleApiAction.java @@ -211,7 +211,8 @@ public abstract class ConsoleApiAction implements Runnable { The following changes were made in registry %s environment to the registrar %s by\ %s: - %s""", + %s\ + """, environment, registrar.getRegistrarId(), consoleApiParams.authResult().userIdForLogging(), @@ -265,7 +266,7 @@ public abstract class ConsoleApiAction implements Runnable { builder.setActingUser(consoleApiParams.authResult().user().get()); builder.setUrl(consoleApiParams.request().getRequestURI()); builder.setMethod(consoleApiParams.request().getMethod()); - builder.setModificationTime(tm().getTransactionTime()); + builder.setModificationTime(tm().getTxTime()); tm().put(builder.build()); } diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleDomainGetAction.java b/core/src/main/java/google/registry/ui/server/console/ConsoleDomainGetAction.java index a6f472886..4959984fa 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleDomainGetAction.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleDomainGetAction.java @@ -54,7 +54,7 @@ public class ConsoleDomainGetAction extends ConsoleApiAction { tm().transact( () -> ForeignKeyUtils.loadResourceByCacheIfEnabled( - Domain.class, paramDomain, tm().getTransactionTime())); + Domain.class, paramDomain, tm().getTxTime())); if (possibleDomain.isEmpty()) { consoleApiParams.response().setStatus(SC_NOT_FOUND); return; diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleDomainListAction.java b/core/src/main/java/google/registry/ui/server/console/ConsoleDomainListAction.java index 319566e7d..956510922 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleDomainListAction.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleDomainListAction.java @@ -17,7 +17,6 @@ package google.registry.ui.server.console; import static com.google.common.base.Preconditions.checkArgument; import static google.registry.model.console.ConsolePermission.DOWNLOAD_DOMAINS; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; -import static google.registry.util.DateTimeUtils.toInstant; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import com.google.common.annotations.VisibleForTesting; @@ -32,9 +31,9 @@ import google.registry.request.Parameter; import google.registry.request.auth.Auth; import jakarta.inject.Inject; import jakarta.persistence.TypedQuery; +import java.time.Instant; import java.util.List; import java.util.Optional; -import org.joda.time.DateTime; /** Returns a (paginated) list of domains for a particular registrar. */ @Action( @@ -54,7 +53,7 @@ public class ConsoleDomainListAction extends ConsoleApiAction { private static final String ORDER_BY_STATEMENT = " ORDER BY creationTime DESC"; private final String registrarId; - private final Optional checkpointTime; + private final Optional checkpointTime; private final int pageNumber; private final int resultsPerPage; private final Optional totalResults; @@ -64,7 +63,7 @@ public class ConsoleDomainListAction extends ConsoleApiAction { public ConsoleDomainListAction( ConsoleApiParams consoleApiParams, @Parameter("registrarId") String registrarId, - @Parameter("checkpointTime") Optional checkpointTime, + @Parameter("checkpointTime") Optional checkpointTime, @Parameter("pageNumber") Optional pageNumber, @Parameter("resultsPerPage") Optional resultsPerPage, @Parameter("totalResults") Optional totalResults, @@ -93,8 +92,8 @@ public class ConsoleDomainListAction extends ConsoleApiAction { // We have to use a constant checkpoint time in order to have stable pagination, since domains // can be constantly created or deleted - DateTime checkpoint = checkpointTime.orElseGet(tm()::getTransactionTime); - CreateAutoTimestamp checkpointTimestamp = CreateAutoTimestamp.create(toInstant(checkpoint)); + Instant checkpoint = checkpointTime.orElseGet(tm()::getTxTime); + CreateAutoTimestamp checkpointTimestamp = CreateAutoTimestamp.create(checkpoint); // Don't compute the number of total results over and over if we don't need to long actualTotalResults = totalResults.orElseGet( @@ -102,13 +101,13 @@ public class ConsoleDomainListAction extends ConsoleApiAction { createCountQuery() .setParameter("registrarId", registrarId) .setParameter("createdBeforeTime", checkpointTimestamp) - .setParameter("deletedAfterTime", toInstant(checkpoint)) + .setParameter("deletedAfterTime", checkpoint) .getSingleResult()); List domains = createDomainQuery() .setParameter("registrarId", registrarId) .setParameter("createdBeforeTime", checkpointTimestamp) - .setParameter("deletedAfterTime", toInstant(checkpoint)) + .setParameter("deletedAfterTime", checkpoint) .setFirstResult(numResultsToSkip) .setMaxResults(resultsPerPage) .getResultList(); @@ -146,10 +145,10 @@ public class ConsoleDomainListAction extends ConsoleApiAction { @VisibleForTesting static final class DomainListResult { @Expose List domains; - @Expose DateTime checkpointTime; + @Expose Instant checkpointTime; @Expose long totalResults; - private DomainListResult(List domains, DateTime checkpointTime, long totalResults) { + private DomainListResult(List domains, Instant checkpointTime, long totalResults) { this.domains = domains; this.checkpointTime = checkpointTime; this.totalResults = totalResults; diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleDumDownloadAction.java b/core/src/main/java/google/registry/ui/server/console/ConsoleDumDownloadAction.java index c609a7d02..4af134206 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleDumDownloadAction.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleDumDownloadAction.java @@ -16,6 +16,8 @@ package google.registry.ui.server.console; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.request.Action.Method.GET; +import static google.registry.util.DateTimeUtils.toLocalDate; +import static java.time.ZoneOffset.UTC; import com.google.common.collect.ImmutableList; import com.google.common.flogger.FluentLogger; @@ -84,7 +86,8 @@ public class ConsoleDumDownloadAction extends ConsoleApiAction { .setHeader("Cache-Control", "max-age=86400"); // 86400 seconds = 1 day consoleApiParams .response() - .setDateHeader("Expires", clock.nowUtc().withTimeAtStartOfDay().plusDays(1)); + .setDateHeader( + "Expires", toLocalDate(clock.now()).atStartOfDay(UTC).plusDays(1).toInstant()); try (var writer = consoleApiParams.response().getWriter()) { CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT); @@ -106,7 +109,7 @@ public class ConsoleDumDownloadAction extends ConsoleApiAction { } private void writeCsv(CSVPrinter printer) throws IOException { - String sql = SQL_TEMPLATE.replaceAll(":now", clock.nowUtc().toString()); + String sql = SQL_TEMPLATE.replaceAll(":now", clock.now().toString()); printer.printRecord( ImmutableList.of("Domain Name", "Creation Time", "Expiration Time", "Domain Statuses")); diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleModule.java b/core/src/main/java/google/registry/ui/server/console/ConsoleModule.java index 807629891..c886f65be 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleModule.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleModule.java @@ -38,8 +38,8 @@ import google.registry.ui.server.console.ConsoleRegistryLockAction.ConsoleRegist import google.registry.ui.server.console.ConsoleUsersAction.UserData; import google.registry.ui.server.console.PasswordResetRequestAction.PasswordResetRequestData; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; /** Dagger module for the Registrar Console parameters. */ @Module @@ -213,8 +213,8 @@ public final class ConsoleModule { @Provides @Parameter("checkpointTime") - public static Optional provideCheckpointTime(HttpServletRequest req) { - return extractOptionalParameter(req, "checkpointTime").map(DateTime::parse); + public static Optional provideCheckpointTime(HttpServletRequest req) { + return extractOptionalParameter(req, "checkpointTime").map(Instant::parse); } @Provides diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleRegistryLockAction.java b/core/src/main/java/google/registry/ui/server/console/ConsoleRegistryLockAction.java index f165972df..7902059aa 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleRegistryLockAction.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleRegistryLockAction.java @@ -44,9 +44,9 @@ import google.registry.util.PasswordUtils.HashAlgorithm; import jakarta.inject.Inject; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; +import java.time.Duration; import java.util.Optional; import javax.annotation.Nullable; -import org.joda.time.Duration; /** * Handler for retrieving / creating registry lock requests in the console. @@ -163,7 +163,7 @@ public class ConsoleRegistryLockAction extends ConsoleApiAction { domainName, registrarId, isAdmin, - relockDurationMillis.map(Duration::millis)); + relockDurationMillis.map(Duration::ofMillis)); sendVerificationEmail(registryLock, registryLockEmail, isLock); }); response.setStatus(SC_OK); diff --git a/core/src/main/java/google/registry/ui/server/console/PasswordResetVerifyAction.java b/core/src/main/java/google/registry/ui/server/console/PasswordResetVerifyAction.java index ce5efb5dd..796c4512f 100644 --- a/core/src/main/java/google/registry/ui/server/console/PasswordResetVerifyAction.java +++ b/core/src/main/java/google/registry/ui/server/console/PasswordResetVerifyAction.java @@ -77,7 +77,7 @@ public class PasswordResetVerifyAction extends ConsoleApiAction { case EPP -> handleEppPasswordReset(request); case REGISTRY_LOCK -> handleRegistryLockPasswordReset(request); } - tm().put(request.asBuilder().setFulfillmentTime(tm().getTransactionTime()).build()); + tm().put(request.asBuilder().setFulfillmentTime(tm().getTxTime()).build()); finishAndPersistConsoleUpdateHistory( new ConsoleUpdateHistory.Builder() diff --git a/core/src/main/java/google/registry/xjc/bindings.xjb b/core/src/main/java/google/registry/xjc/bindings.xjb index 409c4b31f..bd01e5677 100644 --- a/core/src/main/java/google/registry/xjc/bindings.xjb +++ b/core/src/main/java/google/registry/xjc/bindings.xjb @@ -10,9 +10,9 @@ - - + diff --git a/core/src/main/java/google/registry/xml/DateAdapter.java b/core/src/main/java/google/registry/xml/DateAdapter.java index e9d0f39dc..47c1e5cd7 100644 --- a/core/src/main/java/google/registry/xml/DateAdapter.java +++ b/core/src/main/java/google/registry/xml/DateAdapter.java @@ -15,34 +15,33 @@ package google.registry.xml; import static com.google.common.base.Strings.isNullOrEmpty; -import static org.joda.time.DateTimeZone.UTC; +import google.registry.util.DateTimeUtils; import jakarta.xml.bind.annotation.adapters.XmlAdapter; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; /** - * Adapter to use Joda {@link LocalDate} when marshalling the XML Schema {@code date} type. + * Adapter to use java.time {@link LocalDate} when marshalling the XML Schema {@code date} type. * *

Dates are represented as midnight in UTC. The parser aims to be permissive in what it accepts. * Timestamps are converted to UTC if a zone is specified and then the time section is truncated. - * This can lead to unexpected behavior, but it will be your fault. */ public class DateAdapter extends XmlAdapter { - /** @see ISODateTimeFormat#date */ - private static final DateTimeFormatter MARSHAL_FORMAT = ISODateTimeFormat.date(); + private static final DateTimeFormatter MARSHAL_FORMAT = DateTimeFormatter.ISO_LOCAL_DATE; - /** @see ISODateTimeFormat#dateTimeParser */ - private static final DateTimeFormatter UNMARSHAL_FORMAT = ISODateTimeFormat.dateTimeParser(); + private static final DateTimeFormatter UNMARSHAL_FORMAT = + DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC); /** - * Parses an ISO timestamp string into a UTC {@link LocalDate} object, converting timezones - * and truncating time to midnight if necessary. If {@code timestamp} is empty or {@code null} - * then {@code null} is returned. + * Parses an ISO timestamp string into a UTC {@link LocalDate} object, converting timezones and + * truncating time to midnight if necessary. If {@code timestamp} is empty or {@code null} then + * {@code null} is returned. */ @Nullable @CheckForNull @@ -51,18 +50,23 @@ public class DateAdapter extends XmlAdapter { if (isNullOrEmpty(timestamp)) { return null; } - return UNMARSHAL_FORMAT.parseDateTime(timestamp).withZone(UTC).toLocalDate(); + // If it's already just a date, parse it as such. + if (timestamp.length() == 10 && timestamp.chars().filter(c -> c == '-').count() == 2) { + return LocalDate.parse(timestamp); + } + // Otherwise, parse as a date-time and convert to UTC. + return DateTimeUtils.toLocalDate(OffsetDateTime.parse(timestamp, UNMARSHAL_FORMAT).toInstant()); } /** - * Converts {@link LocalDate} to UTC and returns it as an RFC3339 string. If {@code timestamp} - * is {@code null} then an empty string is returned. + * Converts {@link LocalDate} to UTC and returns it as an RFC3339 string. If {@code timestamp} is + * {@code null} then an empty string is returned. */ @Override public String marshal(@Nullable LocalDate date) { if (date == null) { return ""; } - return MARSHAL_FORMAT.print(date.toDateTimeAtStartOfDay(UTC)); + return MARSHAL_FORMAT.format(date); } } diff --git a/core/src/main/resources/META-INF/persistence.xml b/core/src/main/resources/META-INF/persistence.xml index 5ba7f2b6d..438e7ddae 100644 --- a/core/src/main/resources/META-INF/persistence.xml +++ b/core/src/main/resources/META-INF/persistence.xml @@ -84,7 +84,6 @@ google.registry.persistence.converter.BloomFilterConverter google.registry.persistence.converter.CurrencyUnitConverter google.registry.persistence.converter.DateTimeConverter - google.registry.persistence.converter.LocalDateConverter google.registry.model.billing.VKeyConverter_BillingCancellation diff --git a/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java b/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java index c90d06b0a..c9bce92ad 100644 --- a/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java +++ b/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java @@ -101,7 +101,7 @@ public class AsyncTaskEnqueuerTest { .param(PARAM_RESOURCE_KEY, host.createVKey().stringify()) .param(PARAM_REQUESTED_TIME, now.toString()) .param(PARAM_RESAVE_TIMES, "2015-05-20T14:34:56Z,2015-05-21T15:34:56Z") - .scheduleTime(clock.nowUtc().plusHours(24))); + .scheduleTime(plusHours(clock.now(), 24))); } @MockitoSettings(strictness = Strictness.LENIENT) diff --git a/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java b/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java index abf07993c..449051472 100644 --- a/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java +++ b/core/src/test/java/google/registry/batch/BulkDomainTransferActionTest.java @@ -20,10 +20,9 @@ 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.END_INSTANT; 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; @@ -39,7 +38,6 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.FakeClock; import google.registry.testing.FakeLockHandler; import google.registry.testing.FakeResponse; -import google.registry.util.DateTimeUtils; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -68,12 +66,11 @@ public class BulkDomainTransferActionTest { Instant now = fakeClock.now(); // The default registrar is TheRegistrar, which will be the losing registrar activeDomain = - persistDomainWithDependentResources( - "active", "tld", now, minusDays(now, 1), DateTimeUtils.END_INSTANT); + persistDomainWithDependentResources("active", "tld", now, minusDays(now, 1), END_INSTANT); alreadyTransferredDomain = persistResource( persistDomainWithDependentResources( - "alreadytransferred", "tld", now, minusDays(now, 1), DateTimeUtils.END_INSTANT) + "alreadytransferred", "tld", now, minusDays(now, 1), END_INSTANT) .asBuilder() .setPersistedCurrentSponsorRegistrarId("NewRegistrar") .build()); @@ -84,7 +81,7 @@ public class BulkDomainTransferActionTest { .asBuilder() .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE)) .build()); - deletedDomain = persistDeletedDomain("deleted.tld", toDateTime(minusMonths(now, 1))); + deletedDomain = persistDeletedDomain("deleted.tld", minusDays(now, 30)); } @Test diff --git a/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java b/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java index 1aa63cfce..66a806d64 100644 --- a/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java +++ b/core/src/test/java/google/registry/batch/DeleteProberDataActionTest.java @@ -29,7 +29,6 @@ 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.plusYears; -import static google.registry.util.DateTimeUtils.toDateTime; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableSet; @@ -264,7 +263,7 @@ class DeleteProberDataActionTest { @Test void test_domainWithSubordinateHosts_isSkipped() throws Exception { persistActiveHost("ns1.blah.ib-any.test"); - Domain nakedDomain = persistDeletedDomain("todelete.ib-any.test", clock.nowUtc().minusYears(1)); + Domain nakedDomain = persistDeletedDomain("todelete.ib-any.test", minusYears(clock.now(), 1)); Domain domainWithSubord = persistDomainAsDeleted( DatabaseHelper.newDomain("blah.ib-any.test") @@ -294,7 +293,7 @@ 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, toDateTime(DELETION_TIME)); + Domain domain = persistDeletedDomain(fqdn, DELETION_TIME); DomainHistory historyEntry = persistResource( new DomainHistory.Builder() diff --git a/core/src/test/java/google/registry/batch/RelockDomainActionTest.java b/core/src/test/java/google/registry/batch/RelockDomainActionTest.java index d937c80bb..bf1bc6a15 100644 --- a/core/src/test/java/google/registry/batch/RelockDomainActionTest.java +++ b/core/src/test/java/google/registry/batch/RelockDomainActionTest.java @@ -197,7 +197,7 @@ public class RelockDomainActionTest { @Test public void testFailure_transientFailure_enqueuesTask() { // Hard-delete the domain to simulate a DB failure - deleteTestDomain(domain, clock.nowUtc()); + deleteTestDomain(domain, clock.now()); action.run(); assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT); // Cannot assert the entire payload status since the Java object ID will vary @@ -208,7 +208,7 @@ public class RelockDomainActionTest { @Test void testFailure_sufficientTransientFailures_sendsEmail() throws Exception { // Hard-delete the domain to simulate a DB failure - deleteTestDomain(domain, clock.nowUtc()); + deleteTestDomain(domain, clock.now()); action = createAction(oldLock.getRevisionId(), RelockDomainAction.FAILURES_BEFORE_EMAIL); action.run(); assertTaskEnqueued(RelockDomainAction.FAILURES_BEFORE_EMAIL + 1); @@ -242,7 +242,7 @@ public class RelockDomainActionTest { @Test void testFailure_slowsDown() throws Exception { - deleteTestDomain(domain, clock.nowUtc()); + deleteTestDomain(domain, clock.now()); action = createAction(oldLock.getRevisionId(), RelockDomainAction.ATTEMPTS_BEFORE_SLOWDOWN); action.run(); assertTaskEnqueued( @@ -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().plusMillis((int) duration.toMillis()))); + .scheduleTime(clock.now().plus(duration))); } 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 ce1daa516..da3e0fe2c 100644 --- a/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java +++ b/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java @@ -141,7 +141,7 @@ 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().plusDays(5))); + .scheduleTime(plusDays(clock.now(), 5))); } @Test diff --git a/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java b/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java index 55d283ef4..41fa5dcb1 100644 --- a/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java +++ b/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java @@ -20,7 +20,6 @@ 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; import static org.mockito.ArgumentMatchers.any; @@ -48,7 +47,6 @@ import java.security.cert.X509Certificate; import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -73,7 +71,7 @@ class SendExpiringCertificateNotificationEmailActionTest { final JpaIntegrationTestExtension jpa = new JpaTestExtensions.Builder().buildIntegrationTestExtension(); - private final FakeClock clock = new FakeClock(DateTime.parse("2021-05-24T20:21:22Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2021-05-24T20:21:22Z")); private final GmailClient sendEmailService = mock(GmailClient.class); private CertificateChecker certificateChecker; private SendExpiringCertificateNotificationEmailAction action; @@ -86,7 +84,7 @@ class SendExpiringCertificateNotificationEmailActionTest { certificateChecker = new CertificateChecker( - ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398), + ImmutableSortedMap.of(START_INSTANT, 825, Instant.parse("2020-09-01T00:00:00Z"), 398), 30, 15, 2048, @@ -111,8 +109,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); Optional cert = Optional.of(certificateChecker.serializeCertificate(expiringCertificate)); @@ -133,8 +131,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); Optional cert = Optional.of(certificateChecker.serializeCertificate(expiringCertificate)); @@ -159,8 +157,8 @@ class SendExpiringCertificateNotificationEmailActionTest { "testName", SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(), null) .build()); @@ -174,8 +172,8 @@ class SendExpiringCertificateNotificationEmailActionTest { certificateChecker.serializeCertificate( SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert())))) .isEqualTo(false); } @@ -185,8 +183,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-02T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-02T00:00:00Z")) .cert(); Optional cert = Optional.of(certificateChecker.serializeCertificate(expiringCertificate)); @@ -204,8 +202,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); Optional cert = Optional.of(certificateChecker.serializeCertificate(expiringCertificate)); @@ -260,8 +258,8 @@ class SendExpiringCertificateNotificationEmailActionTest { "name" + i, SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(), null) .build()); @@ -281,8 +279,8 @@ class SendExpiringCertificateNotificationEmailActionTest { null, SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert()) .build()); persistSampleContacts(registrar, Type.TECH); @@ -295,8 +293,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); for (int i = 1; i <= 3; i++) { @@ -334,8 +332,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-02T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-02T00:00:00Z")) .cert(); Registrar registrar = createRegistrar("testClientId", "registrar", expiringCertificate, null).build(); @@ -350,8 +348,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); Registrar registrar = createRegistrar("testClientId", "registrar", null, expiringCertificate).build(); @@ -366,8 +364,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); Registrar registrar = createRegistrar("testClientId", "registrar", null, expiringCertificate).build(); @@ -386,8 +384,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); Registrar registrar = createRegistrar("testClientId", "registrar", null, expiringCertificate).build(); @@ -406,14 +404,14 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); X509Certificate certificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); int numOfRegistrars = 10; int numOfRegistrarsWithExpiringCertificates = 2; @@ -435,14 +433,14 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); X509Certificate certificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); int numOfRegistrars = 10; int numOfRegistrarsWithExpiringCertificates = 2; @@ -463,8 +461,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate expiringCertificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(); int numOfRegistrarsWithExpiringCertificates = 5; @@ -481,8 +479,8 @@ class SendExpiringCertificateNotificationEmailActionTest { X509Certificate certificate = SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); int numOfRegistrars = 10; for (int i = 1; i <= numOfRegistrars; i++) { @@ -646,8 +644,8 @@ class SendExpiringCertificateNotificationEmailActionTest { "name" + i, SelfSignedCaCertificate.create( "www.example.tld", - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-06-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-06-01T00:00:00Z")) .cert(), null) .build()); diff --git a/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java b/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java index ae4d1747d..b7558e78e 100644 --- a/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java +++ b/core/src/test/java/google/registry/batch/SyncRemoteCacheActionTest.java @@ -22,6 +22,7 @@ import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.DatabaseHelper.persistDeletedDomain; import static google.registry.testing.DatabaseHelper.persistDeletedHost; +import static google.registry.util.DateTimeUtils.minusDays; 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; @@ -43,7 +44,6 @@ 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.ExtendWith; @@ -58,7 +58,7 @@ import org.mockito.quality.Strictness; @MockitoSettings(strictness = Strictness.LENIENT) class SyncRemoteCacheActionTest { - private final FakeClock clock = new FakeClock(DateTime.parse("2025-01-01T00:00:00Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2025-01-01T00:00:00Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -136,7 +136,7 @@ class SyncRemoteCacheActionTest { @Test void test_syncDomains_withDeletedDomains() { Domain activeDomain = persistActiveDomain("active.tld"); - persistDeletedDomain("deleted.tld", clock.nowUtc().minusDays(1)); + persistDeletedDomain("deleted.tld", minusDays(clock.now(), 1)); action.run(); @@ -202,7 +202,7 @@ class SyncRemoteCacheActionTest { @Test void test_syncHosts_withDeletedHosts() { Host active = persistActiveHost("ns1.example.tld"); - Host deleted = persistDeletedHost("ns2.example.tld", clock.nowUtc().minusDays(1)); + Host deleted = persistDeletedHost("ns2.example.tld", minusDays(clock.now(), 1)); action.run(); 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 7e47d1c1f..970b9491d 100644 --- a/core/src/test/java/google/registry/beam/billing/ExpandBillingRecurrencesPipelineTest.java +++ b/core/src/test/java/google/registry/beam/billing/ExpandBillingRecurrencesPipelineTest.java @@ -34,8 +34,6 @@ import static google.registry.util.DateTimeUtils.minusHours; import static google.registry.util.DateTimeUtils.minusYears; 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; @@ -61,6 +59,7 @@ import google.registry.persistence.PersistenceModule.TransactionIsolationLevel; 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.Arrays; import java.util.Comparator; @@ -70,8 +69,6 @@ import org.apache.beam.sdk.Pipeline.PipelineExecutionException; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.hibernate.cfg.AvailableSettings; import org.joda.money.Money; -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; @@ -360,7 +357,7 @@ public class ExpandBillingRecurrencesPipelineTest { @Test void testSuccess_expandMultipleEvents_multipleEventTime() { - clock.advanceBy(Duration.standardDays(365)); + clock.advanceBy(Duration.ofDays(365)); endTime = plusYears(endTime, 1); options.setEndTime(endTime.toString()); @@ -376,7 +373,7 @@ public class ExpandBillingRecurrencesPipelineTest { domain.getTld(), // We report this when the autorenew grace period ends. plusYears(domain.getCreationTime(), 2) - .plusMillis(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD.getMillis()), + .plus(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD), TransactionReportField.netRenewsFieldFromYears(1), 1))) .build()); @@ -400,8 +397,7 @@ public class ExpandBillingRecurrencesPipelineTest { .asBuilder() .setEventTime(plusYears(domain.getCreationTime(), 2)) .setBillingTime( - plusYears(domain.getCreationTime(), 2) - .plusMillis(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD.getMillis())) + plusYears(domain.getCreationTime(), 2).plus(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD)) .build(), billingRecurrence .asBuilder() @@ -460,7 +456,7 @@ public class ExpandBillingRecurrencesPipelineTest { domain.getTld(), // We report this when the autorenew grace period ends. plusYears(domain.getCreationTime(), 1) - .plusMillis(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD.getMillis()), + .plus(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD), TransactionReportField.netRenewsFieldFromYears(1), 1))) .build(); @@ -474,8 +470,7 @@ public class ExpandBillingRecurrencesPipelineTest { Domain domain, DomainHistory history, BillingRecurrence billingRecurrence, int cost) { return new BillingEvent.Builder() .setBillingTime( - plusYears(domain.getCreationTime(), 1) - .plusMillis(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD.getMillis())) + plusYears(domain.getCreationTime(), 1).plus(Tld.DEFAULT_AUTO_RENEW_GRACE_PERIOD)) .setRegistrarId("TheRegistrar") .setCost(Money.of(USD, cost)) .setEventTime(plusYears(domain.getCreationTime(), 1)) @@ -526,12 +521,8 @@ public class ExpandBillingRecurrencesPipelineTest { assertThat(cursor.getCursorTime()).isEqualTo(expectedCursorTime); } - private static void assertCursorAt(DateTime expectedCursorTime) { - assertCursorAt(toInstant(expectedCursorTime)); - } - private static BillingRecurrence createDomainAtTime(String domainName, Instant createTime) { - Domain domain = persistActiveDomain(domainName, toDateTime(createTime)); + Domain domain = persistActiveDomain(domainName, createTime); DomainHistory domainHistory = persistResource( new DomainHistory.Builder() 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 fac89c919..a77412883 100644 --- a/core/src/test/java/google/registry/beam/rde/RdePipelineTest.java +++ b/core/src/test/java/google/registry/beam/rde/RdePipelineTest.java @@ -37,7 +37,7 @@ import static google.registry.testing.DatabaseHelper.persistNewRegistrar; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResources; import static google.registry.util.DateTimeUtils.plusDays; -import static google.registry.util.DateTimeUtils.toDateTime; +import static google.registry.util.DateTimeUtils.toLocalDate; import static google.registry.util.ResourceUtils.readResourceUtf8; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertThrows; @@ -445,10 +445,10 @@ public class RdePipelineTest { "soy_2000-01-01_full_S1_R1-report.xml.ghostryde"); assertThat(loadCursorTime(CursorType.BRDA)).isEquivalentAccordingToCompareTo(plusDays(now, 1)); - assertThat(loadRevision(toDateTime(now), THIN)).isEqualTo(1); + assertThat(loadRevision(now, THIN)).isEqualTo(1); assertThat(loadCursorTime(RDE_STAGING)).isEquivalentAccordingToCompareTo(plusDays(now, 1)); - assertThat(loadRevision(toDateTime(now), FULL)).isEqualTo(1); + assertThat(loadRevision(now, FULL)).isEqualTo(1); cloudTasksHelper.assertTasksEnqueued( "brda", new TaskMatcher() @@ -483,10 +483,10 @@ public class RdePipelineTest { "soy_2000-01-01_full_S1_R0-report.xml.ghostryde"); assertThat(loadCursorTime(CursorType.BRDA)).isEquivalentAccordingToCompareTo(now); - assertThat(loadRevision(toDateTime(now), THIN)).isEqualTo(0); + assertThat(loadRevision(now, THIN)).isEqualTo(0); assertThat(loadCursorTime(RDE_STAGING)).isEquivalentAccordingToCompareTo(now); - assertThat(loadRevision(toDateTime(now), FULL)).isEqualTo(0); + assertThat(loadRevision(now, FULL)).isEqualTo(0); cloudTasksHelper.assertNoTasksEnqueued("brda", "rde-upload"); } @@ -538,13 +538,12 @@ public class RdePipelineTest { new String(gcsUtils.readBytesFrom(BlobId.of("gcs-bucket", lengthFilename)), UTF_8)); } - private static int loadRevision(DateTime now, RdeMode mode) { + private static int loadRevision(Instant now, RdeMode mode) { return tm().transact( () -> tm().loadByKey( VKey.create( - RdeRevision.class, - RdeRevisionId.create("soy", now.toLocalDate(), mode))) + RdeRevision.class, RdeRevisionId.create("soy", toLocalDate(now), mode))) .getRevision()); } 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 30caf574c..ae4316f02 100644 --- a/core/src/test/java/google/registry/beam/resave/ResaveAllEppResourcesPipelineTest.java +++ b/core/src/test/java/google/registry/beam/resave/ResaveAllEppResourcesPipelineTest.java @@ -25,9 +25,8 @@ import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.DatabaseHelper.persistDomainWithDependentResources; import static google.registry.testing.DatabaseHelper.persistDomainWithPendingTransfer; import static google.registry.testing.DatabaseHelper.persistNewRegistrars; +import static google.registry.util.DateTimeUtils.minusDays; 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,11 +43,11 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.persistence.transaction.JpaTransactionManager; import google.registry.persistence.transaction.TransactionManagerFactory; import google.registry.testing.FakeClock; +import java.time.Duration; 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; -import org.joda.time.Duration; 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.mockito.ArgumentCaptor; /** Tests for {@link ResaveAllEppResourcesPipeline}. */ public class ResaveAllEppResourcesPipelineTest { - private final FakeClock fakeClock = new FakeClock(DateTime.parse("2020-03-10T00:00:00.000Z")); + private final FakeClock fakeClock = new FakeClock(Instant.parse("2020-03-10T00:00:00.000Z")); @RegisterExtension final TestPipelineExtension testPipeline = @@ -101,12 +100,12 @@ public class ResaveAllEppResourcesPipelineTest { persistDomainWithDependentResources( "domain", "tld", - toDateTime(now.minus(5, DAYS)), - toDateTime(now.minus(5, DAYS)), - toDateTime(plusYears(now, 2))), - toDateTime(now.minus(4, DAYS)), - toDateTime(now.minus(1, DAYS)), - toDateTime(plusYears(now, 2))); + now.minus(5, ChronoUnit.DAYS), + now.minus(5, ChronoUnit.DAYS), + plusYears(now, 2)), + now.minus(4, ChronoUnit.DAYS), + minusDays(now, 1), + plusYears(now, 2)); assertThat(domain.getStatusValues()).contains(StatusValue.PENDING_TRANSFER); assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(now); fakeClock.advanceOneMilli(); @@ -120,10 +119,9 @@ public class ResaveAllEppResourcesPipelineTest { void testPipeline_autorenewedDomain() { Instant now = fakeClock.now(); Domain domain = - persistDomainWithDependentResources( - "domain", "tld", toDateTime(now), toDateTime(now), toDateTime(plusYears(now, 1))); + persistDomainWithDependentResources("domain", "tld", now, now, plusYears(now, 1)); assertThat(domain.getRegistrationExpirationTime()).isEqualTo(plusYears(now, 1)); - fakeClock.advanceBy(Duration.standardDays(500)); + fakeClock.advanceBy(Duration.ofDays(500)); runPipeline(); Domain postPipeline = loadByEntity(domain); assertThat(postPipeline.getRegistrationExpirationTime()).isEqualTo(plusYears(now, 2)); @@ -132,10 +130,9 @@ public class ResaveAllEppResourcesPipelineTest { @Test void testPipeline_expiredGracePeriod() { Instant now = fakeClock.now(); - persistDomainWithDependentResources( - "domain", "tld", toDateTime(now), toDateTime(now), toDateTime(plusYears(now, 1))); + persistDomainWithDependentResources("domain", "tld", now, now, plusYears(now, 1)); assertThat(loadAllOf(GracePeriod.class)).hasSize(1); - fakeClock.advanceBy(Duration.standardDays(500)); + fakeClock.advanceBy(Duration.ofDays(500)); runPipeline(); assertThat(loadAllOf(GracePeriod.class)).isEmpty(); } @@ -143,9 +140,8 @@ public class ResaveAllEppResourcesPipelineTest { @Test void testPipeline_fastOnlySavesChanged() { Instant now = fakeClock.now(); - persistDomainWithDependentResources( - "renewed", "tld", toDateTime(now), toDateTime(now), toDateTime(plusYears(now, 1))); - persistActiveDomain("nonrenewed.tld", toDateTime(now), toDateTime(plusYears(now, 20))); + persistDomainWithDependentResources("renewed", "tld", now, now, plusYears(now, 1)); + persistActiveDomain("nonrenewed.tld", now, plusYears(now, 20)); // Spy the transaction manager so we can be sure we're only saving the renewed domain JpaTransactionManager spy = spy(tm()); TransactionManagerFactory.setJpaTm(() -> spy); @@ -159,11 +155,11 @@ public class ResaveAllEppResourcesPipelineTest { @Test void testPipeline_notFastResavesAll() { options.setFast(false); - DateTime now = fakeClock.nowUtc(); + Instant now = fakeClock.now(); Domain renewed = - persistDomainWithDependentResources("renewed", "tld", now, now, now.plusYears(1)); + persistDomainWithDependentResources("renewed", "tld", now, now, plusYears(now, 1)); Domain nonRenewed = - persistDomainWithDependentResources("nonrenewed", "tld", now, now, now.plusYears(20)); + persistDomainWithDependentResources("nonrenewed", "tld", now, now, plusYears(now, 20)); // Spy the transaction manager so we can be sure we're attempting to save everything JpaTransactionManager spy = spy(tm()); TransactionManagerFactory.setJpaTm(() -> spy); diff --git a/core/src/test/java/google/registry/beam/spec11/Spec11PipelineTest.java b/core/src/test/java/google/registry/beam/spec11/Spec11PipelineTest.java index 8b36ec71b..4de36e2df 100644 --- a/core/src/test/java/google/registry/beam/spec11/Spec11PipelineTest.java +++ b/core/src/test/java/google/registry/beam/spec11/Spec11PipelineTest.java @@ -53,6 +53,7 @@ import google.registry.util.Retrier; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; +import java.time.LocalDate; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.SerializableCoder; import org.apache.beam.sdk.options.PipelineOptionsFactory; @@ -64,7 +65,6 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.checkerframework.checker.nullness.qual.Nullable; import org.joda.time.DateTime; -import org.joda.time.LocalDate; import org.json.JSONObject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -149,35 +149,35 @@ class Spec11PipelineTest { .setDomainName("111.com") .setDomainRepoId("123456789-COM") .setRegistrarId("hello-registrar") - .setCheckDate(new LocalDate(2020, 1, 27)) + .setCheckDate(LocalDate.of(2020, 1, 27)) .setThreatTypes(ImmutableSet.of(ThreatType.MALWARE)) .build(), new Spec11ThreatMatch.Builder() .setDomainName("party-night.net") .setDomainRepoId("2244AABBC-NET") .setRegistrarId("kitty-registrar") - .setCheckDate(new LocalDate(2020, 1, 27)) + .setCheckDate(LocalDate.of(2020, 1, 27)) .setThreatTypes(ImmutableSet.of(ThreatType.SOCIAL_ENGINEERING)) .build(), new Spec11ThreatMatch.Builder() .setDomainName("bitcoin.bank") .setDomainRepoId("1C3D5E7F9-BANK") .setRegistrarId("hello-registrar") - .setCheckDate(new LocalDate(2020, 1, 27)) + .setCheckDate(LocalDate.of(2020, 1, 27)) .setThreatTypes(ImmutableSet.of(ThreatType.POTENTIALLY_HARMFUL_APPLICATION)) .build(), new Spec11ThreatMatch.Builder() .setDomainName("no-email.com") .setDomainRepoId("2A4BA9BBC-COM") .setRegistrarId("kitty-registrar") - .setCheckDate(new LocalDate(2020, 1, 27)) + .setCheckDate(LocalDate.of(2020, 1, 27)) .setThreatTypes(ImmutableSet.of(ThreatType.THREAT_TYPE_UNSPECIFIED)) .build(), new Spec11ThreatMatch.Builder() .setDomainName("anti-anti-anti-virus.dev") .setDomainRepoId("555666888-DEV") .setRegistrarId("cool-registrar") - .setCheckDate(new LocalDate(2020, 1, 27)) + .setCheckDate(LocalDate.of(2020, 1, 27)) .setThreatTypes(ImmutableSet.of(ThreatType.UNWANTED_SOFTWARE)) .build()); } @@ -276,7 +276,7 @@ class Spec11PipelineTest { tm().transact( () -> { ImmutableList spec11ThreatMatches = - Spec11ThreatMatchDao.loadEntriesByDate(tm(), new LocalDate(2020, 1, 27)); + Spec11ThreatMatchDao.loadEntriesByDate(tm(), LocalDate.of(2020, 1, 27)); assertThat(spec11ThreatMatches) .comparingElementsUsing(immutableObjectCorrespondence("id")) .containsExactlyElementsIn(sqlThreatMatches); diff --git a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java index 0121fd979..8f8be28fc 100644 --- a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java @@ -82,9 +82,7 @@ class BsaDownloadFunctionalTest { .forEach( tld -> persistResource( - tld.asBuilder() - .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) - .build())); + tld.asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build())); gcsClient = new GcsClient(new GcsUtils(LocalStorageHelper.getOptions()), "my-bucket", "SHA-256"); response = new FakeResponse(); diff --git a/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java index d4d01fa12..34e92c98b 100644 --- a/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaRefreshFunctionalTest.java @@ -122,9 +122,7 @@ class BsaRefreshFunctionalTest { .forEach( tld -> persistResource( - tld.asBuilder() - .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) - .build())); + tld.asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build())); createReservedList(RESERVED_LIST_NAME, "dummy", RESERVED_FOR_SPECIFIC_USE); addReservedListsToTld("app", ImmutableList.of(RESERVED_LIST_NAME)); @@ -155,8 +153,8 @@ class BsaRefreshFunctionalTest { @Test void newRegisteredDomain_addedAsUnblockable() throws Exception { - persistActiveDomain("blocked1.dev", fakeClock.nowUtc()); - persistActiveDomain("dummy.dev", fakeClock.nowUtc()); + persistActiveDomain("blocked1.dev", fakeClock.now()); + persistActiveDomain("dummy.dev", fakeClock.now()); String jobName = getRefreshJobName(fakeClock.now()); action.run(); UnblockableDomain newUnblockable = new UnblockableDomain("blocked1.dev", Reason.REGISTERED); @@ -171,12 +169,12 @@ class BsaRefreshFunctionalTest { @Test void registeredUnblockable_unregistered() { - Domain domain = persistActiveDomain("blocked1.dev", fakeClock.nowUtc()); + Domain domain = persistActiveDomain("blocked1.dev", fakeClock.now()); action.run(); assertThat(queryUnblockableDomains()) .containsExactly(new UnblockableDomain("blocked1.dev", Reason.REGISTERED)); fakeClock.advanceOneMilli(); - deleteTestDomain(domain, fakeClock.nowUtc()); + deleteTestDomain(domain, fakeClock.now()); fakeClock.advanceOneMilli(); String jobName = getRefreshJobName(fakeClock.now()); @@ -219,12 +217,12 @@ class BsaRefreshFunctionalTest { void registeredAndReservedUnblockable_noLongerRegistered_stillUnblockable() throws Exception { addReservedDomainToList( RESERVED_LIST_NAME, ImmutableMap.of("blocked1", RESERVED_FOR_SPECIFIC_USE)); - Domain domain = persistActiveDomain("blocked1.app", fakeClock.nowUtc()); + Domain domain = persistActiveDomain("blocked1.app", fakeClock.now()); action.run(); assertThat(queryUnblockableDomains()) .containsExactly(new UnblockableDomain("blocked1.app", Reason.REGISTERED)); fakeClock.advanceOneMilli(); - deleteTestDomain(domain, fakeClock.nowUtc()); + deleteTestDomain(domain, fakeClock.now()); fakeClock.advanceOneMilli(); String jobName = getRefreshJobName(fakeClock.now()); @@ -251,7 +249,7 @@ class BsaRefreshFunctionalTest { assertThat(queryUnblockableDomains()) .containsExactly(new UnblockableDomain("blocked1.app", Reason.RESERVED)); fakeClock.advanceOneMilli(); - persistActiveDomain("blocked1.app", fakeClock.nowUtc()); + persistActiveDomain("blocked1.app", fakeClock.now()); fakeClock.advanceOneMilli(); Mockito.reset(bsaReportSender); @@ -274,7 +272,7 @@ class BsaRefreshFunctionalTest { void newRegisteredAndReservedDomain_addedAsRegisteredUnblockable() throws Exception { addReservedDomainToList( RESERVED_LIST_NAME, ImmutableMap.of("blocked1", RESERVED_FOR_SPECIFIC_USE)); - persistActiveDomain("blocked1.app", fakeClock.nowUtc()); + persistActiveDomain("blocked1.app", fakeClock.now()); String jobName = getRefreshJobName(fakeClock.now()); action.run(); UnblockableDomain newUnblockable = new UnblockableDomain("blocked1.app", Reason.REGISTERED); @@ -287,7 +285,7 @@ class BsaRefreshFunctionalTest { void registeredAndReservedUnblockable_noLongerReserved_noChange() throws Exception { addReservedDomainToList( RESERVED_LIST_NAME, ImmutableMap.of("blocked1", RESERVED_FOR_SPECIFIC_USE)); - persistActiveDomain("blocked1.app", fakeClock.nowUtc()); + persistActiveDomain("blocked1.app", fakeClock.now()); action.run(); assertThat(queryUnblockableDomains()) .containsExactly(new UnblockableDomain("blocked1.app", Reason.REGISTERED)); @@ -311,7 +309,7 @@ class BsaRefreshFunctionalTest { @Test void registeredUblockable_becomesReserved_noChange() throws Exception { - persistActiveDomain("blocked1.app", fakeClock.nowUtc()); + persistActiveDomain("blocked1.app", 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 a5047e620..111036609 100644 --- a/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java +++ b/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java @@ -25,7 +25,7 @@ import static google.registry.bsa.persistence.BsaTestingUtils.persistUnblockable 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 google.registry.util.DateTimeUtils.START_INSTANT; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.startsWith; @@ -237,7 +237,7 @@ public class BsaValidateActionTest { @Test void isStalenessAllowed_newDomain_allowed() { persistBsaLabel("label"); - Domain domain = persistActiveDomain("label.app", fakeClock.nowUtc()); + Domain domain = persistActiveDomain("label.app", fakeClock.now()); fakeClock.advanceBy(MAX_STALENESS.minusSeconds(1)); assertThat(action.isStalenessAllowed(domain)).isTrue(); } @@ -245,7 +245,7 @@ public class BsaValidateActionTest { @Test void isStalenessAllowed_newDomain_notAllowed() { persistBsaLabel("label"); - Domain domain = persistActiveDomain("label.app", fakeClock.nowUtc()); + Domain domain = persistActiveDomain("label.app", fakeClock.now()); fakeClock.advanceBy(MAX_STALENESS); assertThat(action.isStalenessAllowed(domain)).isFalse(); } @@ -276,9 +276,9 @@ public class BsaValidateActionTest { @Test void checkForMissingReservedUnblockables_success() { persistResource( - createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); persistResource( - createTld("dev").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + createTld("dev").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); persistBsaLabel("registered-reserved"); persistBsaLabel("reserved-only"); persistBsaLabel("reserved-missing"); @@ -302,9 +302,9 @@ public class BsaValidateActionTest { @Test void checkForMissingReservedUnblockablesInOneTld_success() { persistResource( - createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); persistResource( - createTld("dev").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + createTld("dev").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); persistBsaLabel("reserved-missing-in-app"); persistUnblockableDomain( UnblockableDomain.of("reserved-missing-in-app", "dev", Reason.REGISTERED)); @@ -324,7 +324,7 @@ public class BsaValidateActionTest { @Test void checkForMissingReservedUnblockables_unblockedReservedNotReported() { persistResource( - createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); createReservedList( "rl", @@ -339,7 +339,7 @@ public class BsaValidateActionTest { @Test void checkForMissingRegisteredUnblockables_success() { persistResource( - createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + createTld("app").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); persistBsaLabel("registered"); persistBsaLabel("registered-missing"); persistUnblockableDomain(UnblockableDomain.of("registered", "app", Reason.REGISTERED)); diff --git a/core/src/test/java/google/registry/bsa/IdnCheckerTest.java b/core/src/test/java/google/registry/bsa/IdnCheckerTest.java index ec764a41c..97bd33f03 100644 --- a/core/src/test/java/google/registry/bsa/IdnCheckerTest.java +++ b/core/src/test/java/google/registry/bsa/IdnCheckerTest.java @@ -58,28 +58,28 @@ public class IdnCheckerTest { persistResource( jaonly .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc())) + .setBsaEnrollStartTime(Optional.of(fakeClock.now())) .setIdnTables(ImmutableSet.of(JA)) .build()); jandelatin = persistResource( jandelatin .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc())) + .setBsaEnrollStartTime(Optional.of(fakeClock.now())) .setIdnTables(ImmutableSet.of(JA, EXTENDED_LATIN)) .build()); strictlatin = persistResource( strictlatin .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc())) + .setBsaEnrollStartTime(Optional.of(fakeClock.now())) .setIdnTables(ImmutableSet.of(UNCONFUSABLE_LATIN)) .build()); auglatin = persistResource( auglatin .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc())) + .setBsaEnrollStartTime(Optional.of(fakeClock.now())) .setIdnTables(ImmutableSet.of(AUGMENTED_LATIN)) .build()); fakeClock.advanceOneMilli(); diff --git a/core/src/test/java/google/registry/bsa/ReservedDomainsTestingUtils.java b/core/src/test/java/google/registry/bsa/ReservedDomainsTestingUtils.java index 03ee29ee4..6c8c7f23e 100644 --- a/core/src/test/java/google/registry/bsa/ReservedDomainsTestingUtils.java +++ b/core/src/test/java/google/registry/bsa/ReservedDomainsTestingUtils.java @@ -15,7 +15,7 @@ package google.registry.bsa; 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 com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -42,7 +42,7 @@ public final class ReservedDomainsTestingUtils { ReservedListDao.save( new ReservedList.Builder() .setName(listName) - .setCreationTimestamp(START_OF_TIME) + .setCreationTimestamp(START_INSTANT) .setReservedListMap(entries) .build()); } @@ -74,7 +74,7 @@ public final class ReservedDomainsTestingUtils { ReservedListDao.save( new ReservedList.Builder() .setName(listName) - .setCreationTimestamp(START_OF_TIME) + .setCreationTimestamp(START_INSTANT) .setReservedListMap( new ImmutableMap.Builder() .putAll(existingEntries) @@ -94,7 +94,7 @@ public final class ReservedDomainsTestingUtils { ReservedListDao.save( new ReservedList.Builder() .setName(listName) - .setCreationTimestamp(START_OF_TIME) + .setCreationTimestamp(START_INSTANT) .setReservedListMap(newEntries) .build()); } diff --git a/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java b/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java index 5f816e413..222182866 100644 --- a/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java +++ b/core/src/test/java/google/registry/bsa/UploadBsaUnavailableDomainsActionTest.java @@ -22,6 +22,7 @@ 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_INSTANT; +import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.NetworkUtils.pickUnusedPort; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.Executors.newSingleThreadExecutor; @@ -112,7 +113,7 @@ public class UploadBsaUnavailableDomainsActionTest { Tld.get("tld") .asBuilder() .setReservedLists(reservedList) - .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) + .setBsaEnrollStartTime(Optional.of(START_INSTANT)) .setTldType(TldType.REAL) .build()); action = @@ -124,7 +125,7 @@ public class UploadBsaUnavailableDomainsActionTest { void calculatesEntriesCorrectly() throws Exception { persistActiveDomain("foobar.tld"); persistActiveDomain("ace.tld"); - persistDeletedDomain("not-blocked.tld", clock.nowUtc().minusDays(1)); + persistDeletedDomain("not-blocked.tld", minusDays(clock.now(), 1)); action.run(); BlobId existingFile = BlobId.of(BUCKET, String.format("unavailable_domains_%s.txt", clock.now())); @@ -146,7 +147,7 @@ public class UploadBsaUnavailableDomainsActionTest { persistActiveDomain("foobar.tld"); persistActiveDomain("ace.tld"); - persistDeletedDomain("not-blocked.tld", clock.nowUtc().minusDays(1)); + persistDeletedDomain("not-blocked.tld", minusDays(clock.now(), 1)); var testServer = startTestServer(); action.apiUrl = testServer.getUrl("/upload").toURI().toString(); diff --git a/core/src/test/java/google/registry/bsa/persistence/DomainsRefresherTest.java b/core/src/test/java/google/registry/bsa/persistence/DomainsRefresherTest.java index cef87283e..2ad1e9f5d 100644 --- a/core/src/test/java/google/registry/bsa/persistence/DomainsRefresherTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/DomainsRefresherTest.java @@ -57,7 +57,7 @@ public class DomainsRefresherTest { persistResource( Tld.get("tld") .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc().minusMillis(1))) + .setBsaEnrollStartTime(Optional.of(fakeClock.now().minusMillis(1))) .build()); refresher = new DomainsRefresher(START_INSTANT, fakeClock.now(), Duration.ZERO, 100); } 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 43308c9e2..dccaca2a6 100644 --- a/core/src/test/java/google/registry/bsa/persistence/LabelDiffUpdatesTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/LabelDiffUpdatesTest.java @@ -74,7 +74,7 @@ class LabelDiffUpdatesTest { () -> tm().put( tld.asBuilder() - .setBsaEnrollStartTimeInstant(Optional.of(START_INSTANT)) + .setBsaEnrollStartTime(Optional.of(START_INSTANT)) .setIdnTables(ImmutableSet.of(UNCONFUSABLE_LATIN)) .build())); app = tm().transact(() -> tm().loadByEntity(tld)); diff --git a/core/src/test/java/google/registry/bsa/persistence/QueriesTest.java b/core/src/test/java/google/registry/bsa/persistence/QueriesTest.java index 03b0cbd6d..f185aeb7c 100644 --- a/core/src/test/java/google/registry/bsa/persistence/QueriesTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/QueriesTest.java @@ -208,14 +208,14 @@ class QueriesTest { createTlds("tld"); persistNewRegistrar("TheRegistrar"); // time 0: - persistActiveDomain("d1.tld", fakeClock.nowUtc()); + persistActiveDomain("d1.tld", fakeClock.now()); // time 0, deletion time 1 persistDomainAsDeleted( newDomain("will-delete.tld").asBuilder().setCreationTimeForTest(fakeClock.now()).build(), fakeClock.now().plusMillis(1)); fakeClock.advanceOneMilli(); // time 1 - persistActiveDomain("d2.tld", fakeClock.nowUtc()); + persistActiveDomain("d2.tld", fakeClock.now()); fakeClock.advanceOneMilli(); // Now is time 2 assertThat( @@ -232,14 +232,14 @@ class QueriesTest { createTlds("tld"); persistNewRegistrar("TheRegistrar"); // time 0: - persistActiveDomain("d1.tld", fakeClock.nowUtc()); + persistActiveDomain("d1.tld", fakeClock.now()); // time 0, deletion time 1 persistDomainAsDeleted( newDomain("will-delete.tld").asBuilder().setCreationTimeForTest(fakeClock.now()).build(), fakeClock.now().plusMillis(1)); fakeClock.advanceOneMilli(); // time 1 - persistActiveDomain("d2.tld", fakeClock.nowUtc()); + persistActiveDomain("d2.tld", fakeClock.now()); fakeClock.advanceOneMilli(); // Now is time 2, ask for domains created since time 1 assertThat( @@ -255,8 +255,8 @@ class QueriesTest { Instant testStartTime = fakeClock.now(); createTlds("tld", "tld2"); persistNewRegistrar("TheRegistrar"); - persistActiveDomain("d1.tld", fakeClock.nowUtc()); - persistActiveDomain("d2.tld2", fakeClock.nowUtc()); + persistActiveDomain("d1.tld", fakeClock.now()); + persistActiveDomain("d2.tld2", fakeClock.now()); fakeClock.advanceOneMilli(); assertThat( bsaQuery( @@ -271,10 +271,10 @@ class QueriesTest { createTlds("tld", "tld2"); persistNewRegistrar("TheRegistrar"); Instant time1 = fakeClock.now(); - persistActiveDomain("unblocked1.tld", fakeClock.nowUtc()); - persistActiveDomain("unblocked2.tld2", fakeClock.nowUtc()); - persistActiveDomain("label1.tld", fakeClock.nowUtc()); - persistActiveDomain("label2.tld2", fakeClock.nowUtc()); + persistActiveDomain("unblocked1.tld", fakeClock.now()); + persistActiveDomain("unblocked2.tld2", fakeClock.now()); + persistActiveDomain("label1.tld", fakeClock.now()); + persistActiveDomain("label2.tld2", fakeClock.now()); fakeClock.advanceOneMilli(); Instant time2 = fakeClock.now(); persistDomainAsDeleted( @@ -283,7 +283,7 @@ class QueriesTest { // Deleted in the future persistDomainAsDeleted( newDomain("label3.tld2").asBuilder().setCreationTimeForTest(fakeClock.now()).build(), - fakeClock.nowUtc().plusHours(1)); + plusHours(fakeClock.now(), 1)); fakeClock.advanceOneMilli(); assertThat( (ImmutableList) diff --git a/core/src/test/java/google/registry/cache/SimplifiedJedisClientTest.java b/core/src/test/java/google/registry/cache/SimplifiedJedisClientTest.java index 0811e1f20..e8909998c 100644 --- a/core/src/test/java/google/registry/cache/SimplifiedJedisClientTest.java +++ b/core/src/test/java/google/registry/cache/SimplifiedJedisClientTest.java @@ -20,7 +20,6 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.DatabaseHelper.persistDeletedDomain; -import static org.joda.time.DateTimeZone.UTC; import com.google.common.collect.ImmutableList; import google.registry.model.domain.Domain; @@ -29,7 +28,7 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.FakeClock; import io.github.ss_bhatt.testcontainers.valkey.ValkeyContainer; -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; @@ -44,7 +43,7 @@ public class SimplifiedJedisClientTest { @Container private static final ValkeyContainer valkey = new ValkeyContainer(); - private final FakeClock fakeClock = new FakeClock(DateTime.parse("2025-01-01T00:00:00.000Z")); + private final FakeClock fakeClock = new FakeClock(Instant.parse("2025-01-01T00:00:00.000Z")); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -77,7 +76,7 @@ public class SimplifiedJedisClientTest { @Test void testSet_withExpiration() throws Exception { SimplifiedJedisClient client = createJedisClient(); - Domain pendingDelete = persistDeletedDomain("example.tld", DateTime.now(UTC).plusMillis(100)); + Domain pendingDelete = persistDeletedDomain("example.tld", fakeClock.now().plusMillis(100)); client.set(new SimplifiedJedisClient.JedisResource<>("example1.tld", pendingDelete)); Thread.sleep(101); assertThat(client.get(Domain.class, "example1.tld")).isEmpty(); diff --git a/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java b/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java index 509e1cf40..5cb6dd412 100644 --- a/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java +++ b/core/src/test/java/google/registry/dns/RefreshDnsOnHostRenameActionTest.java @@ -23,6 +23,7 @@ import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.DatabaseHelper.persistDeletedHost; import static google.registry.testing.DatabaseHelper.persistDomainAsDeleted; import static google.registry.testing.DatabaseHelper.persistResource; +import static google.registry.util.DateTimeUtils.minusDays; import static jakarta.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static jakarta.servlet.http.HttpServletResponse.SC_OK; @@ -70,7 +71,7 @@ public class RefreshDnsOnHostRenameActionTest { .asBuilder() .setStatusValues(ImmutableSet.of(StatusValue.CLIENT_HOLD)) .build()); - persistDomainAsDeleted(newDomain("deleted.tld", host), clock.nowUtc().minusDays(1)); + persistDomainAsDeleted(newDomain("deleted.tld", host), minusDays(clock.now(), 1)); createAction(host.createVKey().stringify()); action.run(); assertDomainDnsRequests("example.tld", "otherexample.tld"); @@ -89,7 +90,7 @@ public class RefreshDnsOnHostRenameActionTest { @Test void testFailure_deletedHost() { - Host host = persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1)); + Host host = persistDeletedHost("ns1.example.tld", minusDays(clock.now(), 1)); persistResource(newDomain("example.tld", host)); createAction(host.createVKey().stringify()); action.run(); 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 b633b007d..b399a8c0b 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,6 +54,7 @@ import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; +import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -119,18 +120,18 @@ public class CloudDnsWriterTest { persistResource( Tld.get("tld") .asBuilder() - .setDnsAPlusAaaaTtl(org.joda.time.Duration.standardSeconds(11)) - .setDnsNsTtl(org.joda.time.Duration.standardSeconds(222)) - .setDnsDsTtl(org.joda.time.Duration.standardSeconds(3333)) + .setDnsAPlusAaaaTtl(Duration.ofSeconds(11)) + .setDnsNsTtl(Duration.ofSeconds(222)) + .setDnsDsTtl(Duration.ofSeconds(3333)) .build()); writer = new CloudDnsWriter( dnsConnection, "projectId", "triple.secret.tld", // used by testInvalidZoneNames() - java.time.Duration.ZERO, - java.time.Duration.ZERO, - java.time.Duration.ZERO, + Duration.ZERO, + Duration.ZERO, + Duration.ZERO, RateLimiter.create(20), 10, // max num threads new SystemClock(), @@ -401,9 +402,9 @@ public class CloudDnsWriterTest { dnsConnection, "projectId", "triple.secret.tld", - java.time.Duration.ofSeconds(11), - java.time.Duration.ofSeconds(222), - java.time.Duration.ofSeconds(3333), + Duration.ofSeconds(11), + Duration.ofSeconds(222), + Duration.ofSeconds(3333), RateLimiter.create(20), 10, new SystemClock(), 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 b5164872c..2cdace400 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 @@ -25,6 +25,7 @@ import static google.registry.testing.DatabaseHelper.persistActiveSubordinateHos import static google.registry.testing.DatabaseHelper.persistDeletedDomain; import static google.registry.testing.DatabaseHelper.persistDeletedHost; import static google.registry.testing.DatabaseHelper.persistResource; +import static google.registry.util.DateTimeUtils.minusDays; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; @@ -44,11 +45,11 @@ 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.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -94,12 +95,7 @@ public class DnsUpdateWriterTest { writer = new DnsUpdateWriter( - "tld", - java.time.Duration.ZERO, - java.time.Duration.ZERO, - java.time.Duration.ZERO, - mockResolver, - clock); + "tld", Duration.ZERO, Duration.ZERO, Duration.ZERO, mockResolver, clock); } @Test @@ -124,7 +120,7 @@ public class DnsUpdateWriterTest { update, "example.tld.", Type.NS, - Duration.ZERO.getStandardSeconds(), + Duration.ZERO.toSeconds(), "ns1.example.tld.", "ns2.example.tld."); assertThatTotalUpdateSetsIs(update, 2); // The delete and NS sets @@ -183,9 +179,9 @@ public class DnsUpdateWriterTest { assertThatUpdateDeletes(update, "example1.tld.", Type.ANY); assertThatUpdateDeletes(update, "example2.tld.", Type.ANY); assertThatUpdateAdds( - update, "example1.tld.", Type.NS, Duration.ZERO.getStandardSeconds(), "ns.example1.tld."); + update, "example1.tld.", Type.NS, Duration.ZERO.toSeconds(), "ns.example1.tld."); assertThatUpdateAdds( - update, "example2.tld.", Type.NS, Duration.ZERO.getStandardSeconds(), "ns.example2.tld."); + update, "example2.tld.", Type.NS, Duration.ZERO.toSeconds(), "ns.example2.tld."); assertThatTotalUpdateSetsIs(update, 4); // The delete and NS sets for each TLD } @@ -208,13 +204,9 @@ public class DnsUpdateWriterTest { assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateAdds( - update, "example.tld.", Type.NS, Duration.ZERO.getStandardSeconds(), "ns1.example.tld."); + update, "example.tld.", Type.NS, Duration.ZERO.toSeconds(), "ns1.example.tld."); assertThatUpdateAdds( - update, - "example.tld.", - Type.DS, - Duration.ZERO.getStandardSeconds(), - "1 3 1 " + BASE16_SHA1_DIGEST); + update, "example.tld.", Type.DS, Duration.ZERO.toSeconds(), "1 3 1 " + BASE16_SHA1_DIGEST); assertThatTotalUpdateSetsIs(update, 3); // The delete, the NS, and DS sets } @@ -223,8 +215,8 @@ public class DnsUpdateWriterTest { persistResource( Tld.get("tld") .asBuilder() - .setDnsNsTtl(Duration.millis(500)) - .setDnsDsTtl(Duration.millis(400)) + .setDnsNsTtl(Duration.ofMillis(500)) + .setDnsDsTtl(Duration.ofMillis(400)) .build()); Domain domain = persistActiveDomain("example.tld") @@ -243,16 +235,12 @@ public class DnsUpdateWriterTest { assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateAdds( - update, - "example.tld.", - Type.NS, - Duration.millis(500).getStandardSeconds(), - "ns1.example.tld."); + update, "example.tld.", Type.NS, Duration.ofMillis(500).toSeconds(), "ns1.example.tld."); assertThatUpdateAdds( update, "example.tld.", Type.DS, - Duration.millis(400).getStandardSeconds(), + Duration.ofMillis(400).toSeconds(), "1 3 1 " + BASE16_SHA1_DIGEST); assertThatTotalUpdateSetsIs(update, 3); // The delete, the NS, and DS sets } @@ -279,7 +267,7 @@ public class DnsUpdateWriterTest { @Test void testPublishDomainDelete_removesDnsRecords() throws Exception { - persistDeletedDomain("example.tld", clock.nowUtc().minusDays(1)); + persistDeletedDomain("example.tld", minusDays(clock.now(), 1)); writer.publishDomain("example.tld"); writer.commit(); @@ -319,20 +307,15 @@ public class DnsUpdateWriterTest { assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateDeletes(update, "ns1.example.tld.", Type.ANY); assertThatUpdateAdds( - update, - "ns1.example.tld.", - Type.A, - Duration.ZERO.getStandardSeconds(), - "10.0.0.1", - "10.1.0.1"); + update, "ns1.example.tld.", Type.A, Duration.ZERO.toSeconds(), "10.0.0.1", "10.1.0.1"); assertThatUpdateAdds( update, "ns1.example.tld.", Type.AAAA, - Duration.ZERO.getStandardSeconds(), + Duration.ZERO.toSeconds(), "fd0e:a5c8:6dfb:6a5e:0:0:0:1"); assertThatUpdateAdds( - update, "example.tld.", Type.NS, Duration.ZERO.getStandardSeconds(), "ns1.example.tld."); + update, "example.tld.", Type.NS, Duration.ZERO.toSeconds(), "ns1.example.tld."); assertThatTotalUpdateSetsIs(update, 5); } @@ -341,8 +324,8 @@ public class DnsUpdateWriterTest { persistResource( Tld.get("tld") .asBuilder() - .setDnsAPlusAaaaTtl(Duration.millis(500)) - .setDnsNsTtl(Duration.millis(400)) + .setDnsAPlusAaaaTtl(Duration.ofMillis(500)) + .setDnsNsTtl(Duration.ofMillis(400)) .build()); Host host = persistResource( @@ -373,27 +356,23 @@ public class DnsUpdateWriterTest { update, "ns1.example.tld.", Type.A, - Duration.millis(500).getStandardSeconds(), + Duration.ofMillis(500).toSeconds(), "10.0.0.1", "10.1.0.1"); assertThatUpdateAdds( update, "ns1.example.tld.", Type.AAAA, - Duration.millis(500).getStandardSeconds(), + Duration.ofMillis(500).toSeconds(), "fd0e:a5c8:6dfb:6a5e:0:0:0:1"); assertThatUpdateAdds( - update, - "example.tld.", - Type.NS, - Duration.millis(400).getStandardSeconds(), - "ns1.example.tld."); + update, "example.tld.", Type.NS, Duration.ofMillis(400).toSeconds(), "ns1.example.tld."); assertThatTotalUpdateSetsIs(update, 5); } @Test void testPublishHostDelete_removesDnsRecords() throws Exception { - persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1)); + persistDeletedHost("ns1.example.tld", minusDays(clock.now(), 1)); persistActiveDomain("example.tld"); writer.publishHost("ns1.example.tld"); @@ -409,7 +388,7 @@ public class DnsUpdateWriterTest { @Test void testPublishHostDelete_removesGlueRecords() throws Exception { - persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1)); + persistDeletedHost("ns1.example.tld", minusDays(clock.now(), 1)); persistResource( persistActiveDomain("example.tld") .asBuilder() @@ -425,7 +404,7 @@ public class DnsUpdateWriterTest { assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateDeletes(update, "ns1.example.tld.", Type.ANY); assertThatUpdateAdds( - update, "example.tld.", Type.NS, Duration.ZERO.getStandardSeconds(), "ns1.example.com."); + update, "example.tld.", Type.NS, Duration.ZERO.toSeconds(), "ns1.example.com."); assertThatTotalUpdateSetsIs(update, 3); } @@ -464,21 +443,16 @@ public class DnsUpdateWriterTest { update, "example.tld.", Type.NS, - Duration.ZERO.getStandardSeconds(), + Duration.ZERO.toSeconds(), "ns1.example.com.", "ns1.example.tld."); assertThatUpdateAdds( - update, - "ns1.example.tld.", - Type.A, - Duration.ZERO.getStandardSeconds(), - "10.0.0.1", - "10.1.0.1"); + update, "ns1.example.tld.", Type.A, Duration.ZERO.toSeconds(), "10.0.0.1", "10.1.0.1"); assertThatUpdateAdds( update, "ns1.example.tld.", Type.AAAA, - Duration.ZERO.getStandardSeconds(), + Duration.ZERO.toSeconds(), "fd0e:a5c8:6dfb:6a5e:0:0:0:1"); assertThatTotalUpdateSetsIs(update, 5); } @@ -514,19 +488,14 @@ public class DnsUpdateWriterTest { assertThatUpdateDeletes(update, "ns1.example.tld.", Type.ANY); assertThatUpdateDeletes(update, "foo.example.tld.", Type.ANY); assertThatUpdateAdds( - update, "example.tld.", Type.NS, Duration.ZERO.getStandardSeconds(), "ns1.example.tld."); + update, "example.tld.", Type.NS, Duration.ZERO.toSeconds(), "ns1.example.tld."); assertThatUpdateAdds( - update, - "ns1.example.tld.", - Type.A, - Duration.ZERO.getStandardSeconds(), - "10.0.0.1", - "10.1.0.1"); + update, "ns1.example.tld.", Type.A, Duration.ZERO.toSeconds(), "10.0.0.1", "10.1.0.1"); assertThatUpdateAdds( update, "ns1.example.tld.", Type.AAAA, - Duration.ZERO.getStandardSeconds(), + Duration.ZERO.toSeconds(), "fd0e:a5c8:6dfb:6a5e:0:0:0:1"); assertThatTotalUpdateSetsIs(update, 6); } diff --git a/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java b/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java index 8aa746d09..c4d1f0408 100644 --- a/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java +++ b/core/src/test/java/google/registry/export/ExportDomainListsActionTest.java @@ -22,6 +22,7 @@ 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_INSTANT; import static google.registry.util.DateTimeUtils.plusDays; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -48,9 +49,7 @@ 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; import org.junit.jupiter.api.extension.RegisterExtension; @@ -99,7 +98,7 @@ class ExportDomainListsActionTest { void test_outputsOnlyActiveDomains_txt() throws Exception { persistActiveDomain("onetwo.tld"); persistActiveDomain("rudnitzky.tld"); - persistDeletedDomain("mortuary.tld", DateTime.parse("2001-03-14T10:11:12Z")); + persistDeletedDomain("mortuary.tld", Instant.parse("2001-03-14T10:11:12Z")); action.run(); BlobId existingFile = BlobId.of("outputbucket", "tld.txt"); String tlds = new String(gcsUtils.readBytesFrom(existingFile), UTF_8); @@ -114,7 +113,7 @@ class ExportDomainListsActionTest { persistFeatureFlag(ACTIVE); persistActiveDomain("onetwo.tld"); persistActiveDomain("rudnitzky.tld"); - persistDeletedDomain("mortuary.tld", DateTime.parse("2001-03-14T10:11:12Z")); + persistDeletedDomain("mortuary.tld", Instant.parse("2001-03-14T10:11:12Z")); action.run(); BlobId existingFile = BlobId.of("outputbucket", "tld.txt"); String tlds = new String(gcsUtils.readBytesFrom(existingFile), UTF_8); @@ -262,7 +261,7 @@ class ExportDomainListsActionTest { new FeatureFlag() .asBuilder() .setFeatureName(INCLUDE_PENDING_DELETE_DATE_FOR_DOMAINS) - .setStatusMap(ImmutableSortedMap.of(DateTimeUtils.START_OF_TIME, status)) + .setStatusMap(ImmutableSortedMap.of(START_INSTANT, status)) .build()); } } diff --git a/core/src/test/java/google/registry/flows/CheckApiActionTest.java b/core/src/test/java/google/registry/flows/CheckApiActionTest.java index 37c224197..927edef4e 100644 --- a/core/src/test/java/google/registry/flows/CheckApiActionTest.java +++ b/core/src/test/java/google/registry/flows/CheckApiActionTest.java @@ -26,7 +26,7 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistReservedList; 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.mockito.Mockito.verify; import google.registry.bsa.persistence.BsaTestingUtils; @@ -39,9 +39,9 @@ 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.Instant; import java.util.Map; import java.util.Optional; -import org.joda.time.DateTime; import org.json.simple.JSONValue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -56,7 +56,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class CheckApiActionTest { - private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z"); + private static final Instant START_TIME = Instant.parse("2000-01-01T00:00:00.0Z"); private final FakeClock fakeClock = new FakeClock(START_TIME); @RegisterExtension @@ -66,7 +66,7 @@ class CheckApiActionTest { @Mock private CheckApiMetrics checkApiMetrics; @Captor private ArgumentCaptor metricCaptor; - private DateTime endTime; + private Instant endTime; @BeforeEach void beforeEach() { @@ -91,7 +91,7 @@ class CheckApiActionTest { action.metricBuilder = CheckApiMetric.builder(fakeClock); action.checkApiMetrics = checkApiMetrics; fakeClock.advanceOneMilli(); - endTime = fakeClock.nowUtc(); + endTime = fakeClock.now(); action.run(); return (Map) JSONValue.parse(((FakeResponse) action.response).getPayload()); @@ -289,7 +289,7 @@ class CheckApiActionTest { void testSuccess_blockedByBsa() { BsaTestingUtils.persistBsaLabel("rich"); persistResource( - Tld.get("example").asBuilder().setBsaEnrollStartTime(Optional.of(START_OF_TIME)).build()); + Tld.get("example").asBuilder().setBsaEnrollStartTime(Optional.of(START_INSTANT)).build()); assertThat(getCheckResponse("rich.example")) .containsExactly( "tier", "premium", diff --git a/core/src/test/java/google/registry/flows/EppLifecycleDomainTest.java b/core/src/test/java/google/registry/flows/EppLifecycleDomainTest.java index 322d651c4..94004613d 100644 --- a/core/src/test/java/google/registry/flows/EppLifecycleDomainTest.java +++ b/core/src/test/java/google/registry/flows/EppLifecycleDomainTest.java @@ -540,8 +540,7 @@ class EppLifecycleDomainTest extends EppTestCase { .setPeriodYears(1) .setCost(Money.parse("USD 100.00")) .setEventTime(createTime) - .setBillingTime( - createTime.plusMillis(Tld.get("tld").getRenewGracePeriodLength().getMillis())) + .setBillingTime(createTime.plus(Tld.get("tld").getRenewGracePeriodLength())) .setDomainHistory( getOnlyHistoryEntryOfType(domain, Type.DOMAIN_CREATE, DomainHistory.class)) .build(); diff --git a/core/src/test/java/google/registry/flows/EppLifecycleHostTest.java b/core/src/test/java/google/registry/flows/EppLifecycleHostTest.java index ccb5705c7..c5dbb7bd0 100644 --- a/core/src/test/java/google/registry/flows/EppLifecycleHostTest.java +++ b/core/src/test/java/google/registry/flows/EppLifecycleHostTest.java @@ -27,7 +27,7 @@ import google.registry.model.domain.Domain; import google.registry.model.host.Host; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -192,7 +192,7 @@ class EppLifecycleHostTest extends EppTestCase { "host_create_response.xml", ImmutableMap.of("HOSTNAME", "ns1.example.tld", "CRDATE", "2000-06-01T00:05:00Z")); - DateTime timeAfterCreates = DateTime.parse("2000-06-01T00:06:00Z"); + Instant timeAfterCreates = Instant.parse("2000-06-01T00:06:00Z"); Host exampleBarFooTldHost = loadResource(Host.class, "ns1.example.bar.foo.tld", timeAfterCreates).get(); diff --git a/core/src/test/java/google/registry/flows/EppLoggedOutTest.java b/core/src/test/java/google/registry/flows/EppLoggedOutTest.java index 119ac1ccf..63758c6f5 100644 --- a/core/src/test/java/google/registry/flows/EppLoggedOutTest.java +++ b/core/src/test/java/google/registry/flows/EppLoggedOutTest.java @@ -14,10 +14,10 @@ package google.registry.flows; -import static org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis; import com.google.common.collect.ImmutableMap; -import org.joda.time.DateTime; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; /** Test flows without login. */ @@ -25,10 +25,12 @@ class EppLoggedOutTest extends EppTestCase { @Test void testHello() throws Exception { - DateTime now = clock.nowUtc(); + Instant now = clock.now(); assertThatCommand("hello.xml", null) .atTime(now) - .hasResponse("greeting.xml", ImmutableMap.of("DATE", now.toString(dateTimeNoMillis()))); + .hasResponse( + "greeting.xml", + ImmutableMap.of("DATE", now.truncatedTo(ChronoUnit.SECONDS).toString())); } @Test diff --git a/core/src/test/java/google/registry/flows/EppLoginTlsTest.java b/core/src/test/java/google/registry/flows/EppLoginTlsTest.java index c27e35690..2d7c71f93 100644 --- a/core/src/test/java/google/registry/flows/EppLoginTlsTest.java +++ b/core/src/test/java/google/registry/flows/EppLoginTlsTest.java @@ -17,8 +17,7 @@ package google.registry.flows; import static google.registry.testing.CertificateSamples.SAMPLE_CERT3_HASH; import static google.registry.testing.DatabaseHelper.loadRegistrar; import static google.registry.testing.DatabaseHelper.persistResource; -import static google.registry.util.DateTimeUtils.START_OF_TIME; -import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.X509Utils.getCertificateHash; import com.google.common.collect.ImmutableMap; @@ -33,11 +32,12 @@ import google.registry.testing.SystemPropertyExtension; import google.registry.util.SelfSignedCaCertificate; import java.io.StringWriter; import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; import java.util.Optional; import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator; import org.bouncycastle.util.io.pem.PemObjectGenerator; import org.bouncycastle.util.io.pem.PemWriter; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -56,7 +56,7 @@ class EppLoginTlsTest extends EppTestCase { private final CertificateChecker certificateChecker = new CertificateChecker( - ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398), + ImmutableSortedMap.of(START_INSTANT, 825, Instant.parse("2020-09-01T00:00:00Z"), 398), 30, 15, 2048, @@ -74,7 +74,7 @@ class EppLoginTlsTest extends EppTestCase { @BeforeEach void beforeEach() { - clock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + clock.setTo(Instant.parse("2020-11-01T00:00:00Z")); persistResource( loadRegistrar("NewRegistrar") .asBuilder() @@ -100,7 +100,7 @@ class EppLoginTlsTest extends EppTestCase { setCredentials(SAMPLE_CERT3_HASH); // For TLS login, we also check the epp xml password. assertThatLogin("NewRegistrar", "incorrect") - .atTime(clock.nowUtc()) + .atTime(clock.now()) .hasResponse( "response_error.xml", ImmutableMap.of("CODE", "2200", "MSG", "Registrar password is incorrect")); @@ -114,7 +114,7 @@ class EppLoginTlsTest extends EppTestCase { assertThatLoginSucceeds("NewRegistrar", "foo-BAR2"); assertThatLogoutSucceeds(); assertThatLogin("TheRegistrar", "password2") - .atTime(clock.nowUtc()) + .atTime(clock.now()) .hasResponse( "response_error.xml", ImmutableMap.of( @@ -153,12 +153,12 @@ class EppLoginTlsTest extends EppTestCase { @Test void testGoodPrimaryCertificate() throws Exception { setCredentials(SAMPLE_CERT3_HASH); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); persistResource( loadRegistrar("NewRegistrar") .asBuilder() - .setClientCertificate(CertificateSamples.SAMPLE_CERT3, toInstant(now)) - .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT2, toInstant(now)) + .setClientCertificate(CertificateSamples.SAMPLE_CERT3, now) + .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT2, now) .build()); assertThatLoginSucceeds("NewRegistrar", "foo-BAR2"); } @@ -166,12 +166,12 @@ class EppLoginTlsTest extends EppTestCase { @Test void testGoodFailoverCertificate() throws Exception { setCredentials(SAMPLE_CERT3_HASH); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); persistResource( loadRegistrar("NewRegistrar") .asBuilder() - .setClientCertificate(CertificateSamples.SAMPLE_CERT, toInstant(now)) - .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT3, toInstant(now)) + .setClientCertificate(CertificateSamples.SAMPLE_CERT, now) + .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT3, now) .build()); assertThatLoginSucceeds("NewRegistrar", "foo-BAR2"); } @@ -179,12 +179,12 @@ class EppLoginTlsTest extends EppTestCase { @Test void testMissingPrimaryCertificateButHasFailover_usesFailover() throws Exception { setCredentials(SAMPLE_CERT3_HASH); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); persistResource( loadRegistrar("NewRegistrar") .asBuilder() - .setClientCertificate(null, toInstant(now)) - .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT3, toInstant(now)) + .setClientCertificate(null, now) + .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT3, now) .build()); assertThatLoginSucceeds("NewRegistrar", "foo-BAR2"); } @@ -192,12 +192,12 @@ class EppLoginTlsTest extends EppTestCase { @Test void testRegistrarHasNoCertificatesOnFile_fails() throws Exception { setCredentials("laffo"); - DateTime now = clock.nowUtc(); + Instant now = clock.now(); persistResource( loadRegistrar("NewRegistrar") .asBuilder() - .setClientCertificate(null, toInstant(now)) - .setFailoverClientCertificate(null, toInstant(now)) + .setClientCertificate(null, now) + .setFailoverClientCertificate(null, now) .build()); assertThatLogin("NewRegistrar", "foo-BAR2") .hasResponse( @@ -231,7 +231,9 @@ class EppLoginTlsTest extends EppTestCase { void testCertificateDoesNotMeetMultipleRequirements_fails() throws Exception { X509Certificate certificate = SelfSignedCaCertificate.create( - "test", clock.nowUtc().minusDays(5000), clock.nowUtc().minusDays(100)) + "test", + clock.now().minus(Duration.ofDays(5000)), + clock.now().minus(Duration.ofDays(100))) .cert(); StringWriter sw = new StringWriter(); diff --git a/core/src/test/java/google/registry/flows/EppPointInTimeTest.java b/core/src/test/java/google/registry/flows/EppPointInTimeTest.java index cb5febaf6..8cc445557 100644 --- a/core/src/test/java/google/registry/flows/EppPointInTimeTest.java +++ b/core/src/test/java/google/registry/flows/EppPointInTimeTest.java @@ -22,8 +22,6 @@ import static google.registry.testing.DatabaseHelper.loadAllOf; import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.persistActiveHost; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.joda.time.DateTimeZone.UTC; -import static org.joda.time.Duration.standardDays; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; @@ -35,7 +33,8 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.EppLoader; import google.registry.testing.FakeClock; import google.registry.testing.FakeHttpSession; -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; @@ -43,7 +42,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Test that we can reload EPP resources as they were in the past. */ class EppPointInTimeTest { - private final FakeClock clock = new FakeClock(DateTime.now(UTC)); + private final FakeClock clock = new FakeClock(Instant.now()); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -81,21 +80,21 @@ class EppPointInTimeTest { @Test void testLoadAtPointInTime() throws Exception { - clock.setTo(DateTime.parse("1984-12-18T12:30Z")); // not midnight + clock.setTo(Instant.parse("1984-12-18T12:30:00Z")); // not midnight persistActiveHost("ns1.example.net"); persistActiveHost("ns2.example.net"); - clock.advanceBy(standardDays(1)); - DateTime timeAtCreate = clock.nowUtc(); + clock.advanceBy(Duration.ofDays(1)); + Instant timeAtCreate = clock.now(); clock.setTo(timeAtCreate); eppLoader = new EppLoader(this, "domain_create.xml", ImmutableMap.of("DOMAIN", "example.tld")); runFlow(); Domain domainAfterCreate = Iterables.getOnlyElement(loadAllOf(Domain.class)); assertThat(domainAfterCreate.getDomainName()).isEqualTo("example.tld"); - clock.advanceBy(standardDays(2)); - DateTime timeAtFirstUpdate = clock.nowUtc(); + clock.advanceBy(Duration.ofDays(2)); + Instant timeAtFirstUpdate = clock.now(); eppLoader = new EppLoader(this, "domain_update_dsdata_add.xml"); runFlow(); @@ -103,13 +102,13 @@ class EppPointInTimeTest { assertThat(domainAfterCreate).isNotEqualTo(domainAfterFirstUpdate); clock.advanceOneMilli(); // same day as first update - DateTime timeAtSecondUpdate = clock.nowUtc(); + Instant timeAtSecondUpdate = clock.now(); eppLoader = new EppLoader(this, "domain_update_dsdata_rem.xml"); runFlow(); Domain domainAfterSecondUpdate = loadByEntity(domainAfterCreate); - clock.advanceBy(standardDays(2)); - DateTime timeAtDelete = clock.nowUtc(); // before 'add' grace period ends + clock.advanceBy(Duration.ofDays(2)); + Instant timeAtDelete = clock.now(); // before 'add' grace period ends eppLoader = new EppLoader(this, "domain_delete.xml", ImmutableMap.of("DOMAIN", "example.tld")); runFlow(); @@ -124,7 +123,7 @@ class EppPointInTimeTest { assertThat(loadAtPointInTime(latest, timeAtCreate.plusMillis(1))).isNotNull(); assertAboutImmutableObjects() - .that(loadAtPointInTime(latest, timeAtCreate.plusDays(1))) + .that(loadAtPointInTime(latest, timeAtCreate.plus(Duration.ofDays(1)))) .isEqualExceptFields(domainAfterCreate, "updateTimestamp"); // In SQL, we are not limited by the day granularity, so when we request the object @@ -139,7 +138,7 @@ class EppPointInTimeTest { .isEqualExceptFields(domainAfterSecondUpdate, "updateTimestamp"); assertAboutImmutableObjects() - .that(loadAtPointInTime(latest, timeAtSecondUpdate.plusDays(1))) + .that(loadAtPointInTime(latest, timeAtSecondUpdate.plus(Duration.ofDays(1)))) .isEqualExceptFields(domainAfterSecondUpdate, "updateTimestamp"); // Deletion time has millisecond granularity due to isActive() check. diff --git a/core/src/test/java/google/registry/flows/EppTestCase.java b/core/src/test/java/google/registry/flows/EppTestCase.java index 373a2cfe1..fe8f84c2e 100644 --- a/core/src/test/java/google/registry/flows/EppTestCase.java +++ b/core/src/test/java/google/registry/flows/EppTestCase.java @@ -19,7 +19,8 @@ import static google.registry.testing.DatabaseHelper.getOnlyHistoryEntryOfType; import static google.registry.testing.DatabaseHelper.loadAllOf; import static google.registry.testing.DatabaseHelper.stripBillingEventId; import static google.registry.testing.TestDataHelper.loadFile; -import static google.registry.util.DateTimeUtils.toDateTime; +import static google.registry.util.DateTimeUtils.formatInstant; +import static google.registry.util.DateTimeUtils.plusMinutes; import static google.registry.xml.XmlTestUtils.assertXmlEqualsWithMessage; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static java.nio.charset.StandardCharsets.UTF_8; @@ -49,7 +50,6 @@ import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.joda.money.Money; -import org.joda.time.DateTime; public class EppTestCase { @@ -81,27 +81,22 @@ public class EppTestCase { public class CommandAsserter { private final String inputFilename; @Nullable private final Map inputSubstitutions; - private DateTime now; + private Instant now; private CommandAsserter( String inputFilename, @Nullable Map inputSubstitutions) { this.inputFilename = inputFilename; this.inputSubstitutions = inputSubstitutions; - now = clock.nowUtc(); + now = clock.now(); } - public CommandAsserter atTime(DateTime now) { + public CommandAsserter atTime(Instant now) { this.now = now; return this; } - public CommandAsserter atTime(Instant now) { - this.now = toDateTime(now); - return this; - } - public CommandAsserter atTime(String now) { - return atTime(DateTime.parse(now)); + return atTime(Instant.parse(now)); } public String hasResponse(String outputFilename) throws Exception { @@ -115,14 +110,14 @@ public class EppTestCase { } public void hasSuccessfulLogin() throws Exception { - assertLoginCommandAndResponse(inputFilename, inputSubstitutions, null, clock.nowUtc()); + assertLoginCommandAndResponse(inputFilename, inputSubstitutions, null, clock.now()); } private void assertLoginCommandAndResponse( String inputFilename, @Nullable Map inputSubstitutions, @Nullable Map outputSubstitutions, - DateTime now) + Instant now) throws Exception { String outputFilename = "generic_success_response.xml"; clock.setTo(now); @@ -139,7 +134,7 @@ public class EppTestCase { @Nullable Map inputSubstitutions, String outputFilename, @Nullable Map outputSubstitutions, - DateTime now) + Instant now) throws Exception { clock.setTo(now); String input = loadFile(EppTestCase.class, inputFilename, inputSubstitutions); @@ -201,11 +196,11 @@ public class EppTestCase { CommandAsserter assertThatLogin(String registrarId, String password) { return assertThatCommand("login.xml", ImmutableMap.of("CLID", registrarId, "PW", password)) - .atTime(clock.nowUtc()); + .atTime(clock.now()); } protected void assertThatLoginSucceeds(String registrarId, String password) throws Exception { - assertThatLogin(registrarId, password).atTime(clock.nowUtc()).hasSuccessfulLogin(); + assertThatLogin(registrarId, password).atTime(clock.now()).hasSuccessfulLogin(); } protected void assertThatLogoutSucceeds() throws Exception { @@ -232,21 +227,25 @@ public class EppTestCase { /** Create the two hosts. */ void createHosts() throws Exception { - DateTime createTime = DateTime.parse("2000-06-01T00:00:00Z"); + Instant createTime = Instant.parse("2000-06-01T00:00:00Z"); assertThatCommand("host_create.xml", ImmutableMap.of("HOSTNAME", "ns1.example.external")) - .atTime(createTime.plusMinutes(2)) + .atTime(plusMinutes(createTime, 2)) .hasResponse( "host_create_response.xml", ImmutableMap.of( - "HOSTNAME", "ns1.example.external", - "CRDATE", createTime.plusMinutes(2).toString())); + "HOSTNAME", + "ns1.example.external", + "CRDATE", + formatInstant(plusMinutes(createTime, 2)))); assertThatCommand("host_create.xml", ImmutableMap.of("HOSTNAME", "ns2.example.external")) - .atTime(createTime.plusMinutes(3)) + .atTime(plusMinutes(createTime, 3)) .hasResponse( "host_create_response.xml", ImmutableMap.of( - "HOSTNAME", "ns2.example.external", - "CRDATE", createTime.plusMinutes(3).toString())); + "HOSTNAME", + "ns2.example.external", + "CRDATE", + formatInstant(plusMinutes(createTime, 3)))); } /** Creates the domain fakesite.example with two nameservers on it. */ @@ -294,8 +293,7 @@ public class EppTestCase { .setCost(Money.parse("USD 24.00")) .setPeriodYears(2) .setEventTime(createTime) - .setBillingTime( - createTime.plusMillis(Tld.get(domain.getTld()).getAddGracePeriodLength().getMillis())) + .setBillingTime(createTime.plus(Tld.get(domain.getTld()).getAddGracePeriodLength())) .setDomainHistory( getOnlyHistoryEntryOfType(domain, Type.DOMAIN_CREATE, DomainHistory.class)) .build(); @@ -310,8 +308,7 @@ public class EppTestCase { .setCost(Money.parse("USD 33.00")) .setPeriodYears(3) .setEventTime(renewTime) - .setBillingTime( - renewTime.plusMillis(Tld.get(domain.getTld()).getRenewGracePeriodLength().getMillis())) + .setBillingTime(renewTime.plus(Tld.get(domain.getTld()).getRenewGracePeriodLength())) .setDomainHistory(getOnlyHistoryEntryOfType(domain, Type.DOMAIN_RENEW, DomainHistory.class)) .build(); } @@ -356,8 +353,7 @@ public class EppTestCase { .setRegistrarId(domain.getCurrentSponsorRegistrarId()) .setEventTime(deleteTime) .setBillingEvent(findKeyToActualOneTimeBillingEvent(billingEventToCancel)) - .setBillingTime( - createTime.plusMillis(Tld.get(domain.getTld()).getAddGracePeriodLength().getMillis())) + .setBillingTime(createTime.plus(Tld.get(domain.getTld()).getAddGracePeriodLength())) .setReason(Reason.CREATE) .setDomainHistory( getOnlyHistoryEntryOfType(domain, Type.DOMAIN_DELETE, DomainHistory.class)) @@ -372,8 +368,7 @@ public class EppTestCase { .setRegistrarId(domain.getCurrentSponsorRegistrarId()) .setEventTime(deleteTime) .setBillingEvent(findKeyToActualOneTimeBillingEvent(billingEventToCancel)) - .setBillingTime( - renewTime.plusMillis(Tld.get(domain.getTld()).getRenewGracePeriodLength().getMillis())) + .setBillingTime(renewTime.plus(Tld.get(domain.getTld()).getRenewGracePeriodLength())) .setReason(Reason.RENEW) .setDomainHistory( getOnlyHistoryEntryOfType(domain, Type.DOMAIN_DELETE, DomainHistory.class)) diff --git a/core/src/test/java/google/registry/flows/FlowRunnerTest.java b/core/src/test/java/google/registry/flows/FlowRunnerTest.java index 7461238dd..4fdc99147 100644 --- a/core/src/test/java/google/registry/flows/FlowRunnerTest.java +++ b/core/src/test/java/google/registry/flows/FlowRunnerTest.java @@ -19,7 +19,7 @@ import static com.google.common.truth.Truth.assertWithMessage; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.TestDataHelper.loadFile; import static google.registry.testing.TestLogHandlerUtils.findFirstLogMessageByPrefix; -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.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -42,9 +42,9 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.FakeClock; import google.registry.testing.FakeHttpSession; import google.registry.util.JdkLoggerConfig; +import java.time.Instant; import java.util.List; 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; @@ -65,7 +65,7 @@ class FlowRunnerTest { private final CertificateChecker certificateChecker = new CertificateChecker( - ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398), + ImmutableSortedMap.of(START_INSTANT, 825, Instant.parse("2020-09-01T00:00:00Z"), 398), 30, 15, 2048, diff --git a/core/src/test/java/google/registry/flows/FlowTestCase.java b/core/src/test/java/google/registry/flows/FlowTestCase.java index ec390bbbc..5777c84be 100644 --- a/core/src/test/java/google/registry/flows/FlowTestCase.java +++ b/core/src/test/java/google/registry/flows/FlowTestCase.java @@ -23,8 +23,8 @@ import static google.registry.flows.FlowUtils.marshalWithLenientRetry; import static google.registry.model.eppcommon.EppXmlTransformer.marshal; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.stripBillingEventId; -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 google.registry.xml.XmlTestUtils.assertXmlEquals; import static java.nio.charset.StandardCharsets.UTF_8; import static org.joda.time.DateTimeZone.UTC; @@ -165,7 +165,7 @@ public abstract class FlowTestCase { } protected void assertNoHistory() { - assertThat(HistoryEntryDao.loadAllHistoryObjects(START_OF_TIME, END_OF_TIME)).isEmpty(); + assertThat(HistoryEntryDao.loadAllHistoryObjects(START_INSTANT, END_INSTANT)).isEmpty(); } /** diff --git a/core/src/test/java/google/registry/flows/ResourceFlowTestCase.java b/core/src/test/java/google/registry/flows/ResourceFlowTestCase.java index fdf97568d..8b9f04a1b 100644 --- a/core/src/test/java/google/registry/flows/ResourceFlowTestCase.java +++ b/core/src/test/java/google/registry/flows/ResourceFlowTestCase.java @@ -17,7 +17,6 @@ package google.registry.flows; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.LogsSubject.assertAboutLogs; -import static google.registry.util.DateTimeUtils.toInstant; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -38,9 +37,9 @@ import google.registry.testing.TestCacheExtension; import google.registry.util.JdkLoggerConfig; import google.registry.util.TypeUtils.TypeInstantiator; import java.time.Duration; +import java.time.Instant; import java.util.logging.Level; import javax.annotation.Nullable; -import org.joda.time.DateTime; import org.json.simple.JSONValue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.RegisterExtension; @@ -69,20 +68,20 @@ public abstract class ResourceFlowTestCase T reloadResourceAndCloneAtTime(T resource, DateTime now) { + protected T reloadResourceAndCloneAtTime(T resource, Instant now) { @SuppressWarnings("unchecked") T refreshedResource = - (T) tm().transact(() -> tm().loadByEntity(resource)).cloneProjectedAtTime(toInstant(now)); + (T) tm().transact(() -> tm().loadByEntity(resource)).cloneProjectedAtTime(now); return refreshedResource; } diff --git a/core/src/test/java/google/registry/flows/TlsCredentialsTest.java b/core/src/test/java/google/registry/flows/TlsCredentialsTest.java index 1634aebbb..fc596b381 100644 --- a/core/src/test/java/google/registry/flows/TlsCredentialsTest.java +++ b/core/src/test/java/google/registry/flows/TlsCredentialsTest.java @@ -19,7 +19,7 @@ import static google.registry.testing.CertificateSamples.SAMPLE_CERT; import static google.registry.testing.CertificateSamples.SAMPLE_CERT_HASH; import static google.registry.testing.DatabaseHelper.loadRegistrar; 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.Mockito.mock; import static org.mockito.Mockito.when; @@ -38,8 +38,8 @@ import google.registry.testing.FakeClock; import google.registry.util.CidrAddressBlock; import google.registry.util.ProxyHttpHeaders; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -54,7 +54,7 @@ final class TlsCredentialsTest { private final CertificateChecker certificateChecker = new CertificateChecker( - ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398), + ImmutableSortedMap.of(START_INSTANT, 825, Instant.parse("2020-09-01T00:00:00Z"), 398), 30, 15, 2048, diff --git a/core/src/test/java/google/registry/flows/certs/CertificateCheckerTest.java b/core/src/test/java/google/registry/flows/certs/CertificateCheckerTest.java index 7d7cc99e2..fb0a8a2fa 100644 --- a/core/src/test/java/google/registry/flows/certs/CertificateCheckerTest.java +++ b/core/src/test/java/google/registry/flows/certs/CertificateCheckerTest.java @@ -23,7 +23,7 @@ import static google.registry.flows.certs.CertificateChecker.CertificateViolatio import static google.registry.flows.certs.CertificateChecker.CertificateViolation.VALIDITY_LENGTH_TOO_LONG; import static google.registry.testing.CertificateSamples.SAMPLE_CERT; import static google.registry.testing.CertificateSamples.SAMPLE_CERT3; -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.ImmutableSet; @@ -36,8 +36,8 @@ import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; +import java.time.Instant; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; /** Unit tests for {@link CertificateChecker} */ @@ -48,7 +48,7 @@ class CertificateCheckerTest { private FakeClock fakeClock = new FakeClock(); private CertificateChecker certificateChecker = new CertificateChecker( - ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398), + ImmutableSortedMap.of(START_INSTANT, 825, Instant.parse("2020-09-01T00:00:00Z"), 398), 30, 15, 2048, @@ -57,19 +57,19 @@ class CertificateCheckerTest { @Test void test_checkCertificate_compliantCertPasses() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).isEmpty(); } @Test void test_checkCertificate_severalViolations() throws Exception { - fakeClock.setTo(DateTime.parse("2010-01-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2010-01-01T00:00:00Z")); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); keyGen.initialize(1024, new SecureRandom()); @@ -77,8 +77,8 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2010-04-01T00:00:00Z"), - DateTime.parse("2014-07-01T00:00:00Z")) + Instant.parse("2010-04-01T00:00:00Z"), + Instant.parse("2014-07-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)) @@ -87,36 +87,36 @@ class CertificateCheckerTest { @Test void test_checkCertificate_expiredCertificate() throws Exception { - fakeClock.setTo(DateTime.parse("2014-01-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2014-01-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2010-04-01T00:00:00Z"), - DateTime.parse("2012-07-01T00:00:00Z")) + Instant.parse("2010-04-01T00:00:00Z"), + Instant.parse("2012-07-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).containsExactly(EXPIRED); } @Test void test_checkCertificate_notYetValid() throws Exception { - fakeClock.setTo(DateTime.parse("2010-01-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2010-01-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2010-04-01T00:00:00Z"), - DateTime.parse("2012-07-01T00:00:00Z")) + Instant.parse("2010-04-01T00:00:00Z"), + Instant.parse("2012-07-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).containsExactly(NOT_YET_VALID); } @Test void test_checkCertificate_validityLengthWayTooLong() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2016-04-01T00:00:00Z"), - DateTime.parse("2021-07-01T00:00:00Z")) + Instant.parse("2016-04-01T00:00:00Z"), + Instant.parse("2021-07-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)) .containsExactly(VALIDITY_LENGTH_TOO_LONG); @@ -124,12 +124,12 @@ class CertificateCheckerTest { @Test void test_checkCertificate_olderValidityLengthIssuedAfterCutoff() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2022-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2022-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)) .containsExactly(VALIDITY_LENGTH_TOO_LONG); @@ -137,19 +137,19 @@ class CertificateCheckerTest { @Test void test_checkCertificate_olderValidityLengthIssuedBeforeCutoff() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2019-09-01T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2019-09-01T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).isEmpty(); } @Test void test_checkCertificate_rsaKeyLengthTooShort() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); keyGen.initialize(1024, new SecureRandom()); @@ -157,8 +157,8 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)) @@ -167,7 +167,7 @@ class CertificateCheckerTest { @Test void test_checkCertificate_rsaKeyLengthLongerThanRequired() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); keyGen.initialize(4096, new SecureRandom()); @@ -175,8 +175,8 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).isEmpty(); @@ -184,7 +184,7 @@ class CertificateCheckerTest { @Test void test_checkCertificate_invalidAlgorithm() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", new BouncyCastleProvider()); keyGen.initialize(2048, new SecureRandom()); @@ -192,8 +192,8 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)) @@ -202,7 +202,7 @@ class CertificateCheckerTest { @Test void test_checkCertificate_validCertificateString() { - fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-11-01T00:00:00Z")); assertThat(certificateChecker.checkCertificate(SAMPLE_CERT3)).isEmpty(); assertThat(certificateChecker.checkCertificate(SAMPLE_CERT)) .containsExactly(VALIDITY_LENGTH_TOO_LONG); @@ -210,7 +210,7 @@ class CertificateCheckerTest { @Test void test_checkCertificate_invalidCertificateString() { - fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-11-01T00:00:00Z")); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, @@ -232,8 +232,8 @@ class CertificateCheckerTest { X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); assertThat(certificateChecker.getCertificate(certificateStr).equals(certificate)).isTrue(); @@ -244,8 +244,8 @@ class CertificateCheckerTest { X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat( certificateChecker.getCertificate(certificateChecker.serializeCertificate(certificate))) @@ -254,43 +254,43 @@ class CertificateCheckerTest { @Test void test_shouldReceiveExpiringNotification_returnsFalse_greaterThan30() throws Exception { - fakeClock.setTo(DateTime.parse("2021-07-20T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-07-20T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr)) + assertThat(certificateChecker.shouldReceiveExpiringNotification(START_INSTANT, certificateStr)) .isFalse(); } @Test void test_shouldReceiveExpiringNotification_returnsFalse_hasExpired() throws Exception { - fakeClock.setTo(DateTime.parse("2021-10-20T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-10-20T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr)) + assertThat(certificateChecker.shouldReceiveExpiringNotification(START_INSTANT, certificateStr)) .isFalse(); } @Test void test_shouldReceiveExpiringNotification_returnsTrue_on15days() throws Exception { - fakeClock.setTo(DateTime.parse("2021-08-16T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-08-16T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-08-30T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-08-30T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-08-01T00:00:00Z"); + Instant lastExpiringNotificationSentDate = Instant.parse("2021-08-01T00:00:00Z"); assertThat( certificateChecker.shouldReceiveExpiringNotification( lastExpiringNotificationSentDate, certificateStr)) @@ -299,15 +299,15 @@ class CertificateCheckerTest { @Test void test_shouldReceiveExpiringNotification_returnsTrue_on30days() throws Exception { - fakeClock.setTo(DateTime.parse("2021-01-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-01-01T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-01-02T00:00:00Z"), - DateTime.parse("2021-01-30T00:00:00Z")) + Instant.parse("2020-01-02T00:00:00Z"), + Instant.parse("2021-01-30T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr)) + assertThat(certificateChecker.shouldReceiveExpiringNotification(START_INSTANT, certificateStr)) .isTrue(); } @@ -315,15 +315,15 @@ class CertificateCheckerTest { void test_shouldReceiveExpiringNotification_returnsFalse_between30and15_lastSentDateIsNotStartOfTime() throws Exception { - fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-07-05T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-06-02T00:00:00Z"), - DateTime.parse("2021-07-25T00:00:00Z")) + Instant.parse("2020-06-02T00:00:00Z"), + Instant.parse("2021-07-25T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-07-04T00:00:00Z"); + Instant lastExpiringNotificationSentDate = Instant.parse("2021-07-04T00:00:00Z"); assertThat( certificateChecker.shouldReceiveExpiringNotification( lastExpiringNotificationSentDate, certificateStr)) @@ -333,15 +333,15 @@ class CertificateCheckerTest { @Test void test_shouldReceiveExpiringNotification_returnsTrue_between30and15_lastSentDateIsStartOfTime() throws Exception { - fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-07-05T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-06-02T00:00:00Z"), - DateTime.parse("2021-07-25T00:00:00Z")) + Instant.parse("2020-06-02T00:00:00Z"), + Instant.parse("2021-07-25T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr)) + assertThat(certificateChecker.shouldReceiveExpiringNotification(START_INSTANT, certificateStr)) .isTrue(); } @@ -349,15 +349,15 @@ class CertificateCheckerTest { void test_shouldReceiveExpiringNotification_returnsFalse_between15and0_lastSentDateBetween30and15_butLate() throws Exception { - fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-07-05T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-06-02T00:00:00Z"), - DateTime.parse("2021-07-18T00:00:00Z")) + Instant.parse("2020-06-02T00:00:00Z"), + Instant.parse("2021-07-18T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-07-01T00:00:00Z"); + Instant lastExpiringNotificationSentDate = Instant.parse("2021-07-01T00:00:00Z"); // The first notification date is late and difference between now and // lastExpiringNotificationSentDate is within expirationWarningIntervalDays. assertThat( @@ -369,15 +369,15 @@ class CertificateCheckerTest { @Test void test_shouldReceiveExpiringNotification_returnsTrue_between15and0_lastSentDateBetween30and15() throws Exception { - fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z")); + fakeClock.setTo(Instant.parse("2021-07-05T00:00:00Z")); X509Certificate certificate = SelfSignedCaCertificate.create( SSL_HOST, - DateTime.parse("2020-06-02T00:00:00Z"), - DateTime.parse("2021-07-18T00:00:00Z")) + Instant.parse("2020-06-02T00:00:00Z"), + Instant.parse("2021-07-18T00:00:00Z")) .cert(); String certificateStr = certificateChecker.serializeCertificate(certificate); - DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-06-20T00:00:00Z"); + Instant lastExpiringNotificationSentDate = Instant.parse("2021-06-20T00:00:00Z"); assertThat( certificateChecker.shouldReceiveExpiringNotification( lastExpiringNotificationSentDate, certificateStr)) @@ -399,7 +399,7 @@ class CertificateCheckerTest { @Test void test_checkCurveName_invalidCurve_returnsViolation() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); // Invalid curve KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); AlgorithmParameters apParam = AlgorithmParameters.getInstance("EC"); @@ -410,8 +410,8 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)) .containsExactly(INVALID_ECDSA_CURVE); @@ -419,7 +419,7 @@ class CertificateCheckerTest { @Test void test_checkCurveName_p256Curve_returnsNoViolations() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); // valid P-256 curve KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); AlgorithmParameters apParam = AlgorithmParameters.getInstance("EC"); @@ -430,15 +430,15 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).isEmpty(); } @Test void test_checkCurveName_p384Curve_returnsNoViolations() throws Exception { - fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); + fakeClock.setTo(Instant.parse("2020-10-01T00:00:00Z")); // valid P-384 curve KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); AlgorithmParameters apParam = AlgorithmParameters.getInstance("EC"); @@ -449,8 +449,8 @@ class CertificateCheckerTest { SelfSignedCaCertificate.create( keyGen.generateKeyPair(), SSL_HOST, - DateTime.parse("2020-09-02T00:00:00Z"), - DateTime.parse("2021-10-01T00:00:00Z")) + Instant.parse("2020-09-02T00:00:00Z"), + Instant.parse("2021-10-01T00:00:00Z")) .cert(); assertThat(certificateChecker.checkCertificate(certificate)).isEmpty(); } diff --git a/core/src/test/java/google/registry/flows/custom/TestDomainCreateFlowCustomLogic.java b/core/src/test/java/google/registry/flows/custom/TestDomainCreateFlowCustomLogic.java index fac1f64d9..91a0bf98d 100644 --- a/core/src/test/java/google/registry/flows/custom/TestDomainCreateFlowCustomLogic.java +++ b/core/src/test/java/google/registry/flows/custom/TestDomainCreateFlowCustomLogic.java @@ -35,7 +35,7 @@ public class TestDomainCreateFlowCustomLogic extends DomainCreateFlowCustomLogic PollMessage extraPollMessage = new PollMessage.OneTime.Builder() .setHistoryEntry(parameters.historyEntry()) - .setEventTime(tm().getTransactionTime()) + .setEventTime(tm().getTxTime()) .setRegistrarId(getSessionMetadata().get().getRegistrarId()) .setMsg("Custom logic was triggered") .build(); diff --git a/core/src/test/java/google/registry/flows/domain/DomainCheckFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainCheckFlowTest.java index b6e7858f7..e5bc3eee2 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainCheckFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainCheckFlowTest.java @@ -160,10 +160,7 @@ class DomainCheckFlowTest extends ResourceCheckFlowTestCase autorenewVKey = domain.getAutorenewBillingEvent(); @@ -767,7 +765,7 @@ class DomainCreateFlowTest extends ResourceFlowTestCase getDeletionTimeFromCache(String domainName) { + private Optional getDeletionTimeFromCache(String domainName) { return tm().transact(() -> cache.getDeletionTimeForDomain(domainName)); } } diff --git a/core/src/test/java/google/registry/flows/domain/DomainRenewFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainRenewFlowTest.java index b30992d40..887fee81c 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainRenewFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainRenewFlowTest.java @@ -105,11 +105,11 @@ import google.registry.model.reporting.HistoryEntry.HistoryEntryId; import google.registry.model.tld.Tld; import google.registry.persistence.VKey; import google.registry.testing.DatabaseHelper; +import java.time.Duration; import java.time.Instant; import java.util.Map; import javax.annotation.Nullable; import org.joda.money.Money; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -283,8 +283,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase .setCost(totalRenewCost) .setPeriodYears(renewalYears) .setEventTime(clock.now()) - .setBillingTime( - clock.now().plusMillis(Tld.get("tld").getRenewGracePeriodLength().getMillis())) + .setBillingTime(clock.now().plus(Tld.get("tld").getRenewGracePeriodLength())) .setDomainHistory(historyEntryDomainRenew) .build(); assertBillingEvents( @@ -330,7 +329,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase GracePeriod.create( GracePeriodStatus.RENEW, domain.getRepoId(), - clock.now().plusMillis(Tld.get("tld").getRenewGracePeriodLength().getMillis()), + clock.now().plus(Tld.get("tld").getRenewGracePeriodLength()), renewalClientId, null), renewBillingEvent)); @@ -779,7 +778,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase @Test void testSuccess_nonDefaultRenewGracePeriod() throws Exception { persistResource( - Tld.get("tld").asBuilder().setRenewGracePeriodLength(Duration.standardMinutes(9)).build()); + Tld.get("tld").asBuilder().setRenewGracePeriodLength(Duration.ofMinutes(9)).build()); persistDomain(); doSuccessfulTest( "domain_renew_response.xml", @@ -888,7 +887,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase @Test void testFailure_existedButWasDeleted() throws Exception { - persistDeletedDomain(getUniqueIdFromCommand(), clock.nowUtc().minusDays(1)); + persistDeletedDomain(getUniqueIdFromCommand(), minusDays(clock.now(), 1)); ResourceDoesNotExistException thrown = assertThrows(ResourceDoesNotExistException.class, this::runFlow); assertThat(thrown).hasMessageThat().contains(String.format("(%s)", getUniqueIdFromCommand())); @@ -1092,7 +1091,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase persistDomain(); // Test with a nonstandard Renew period to ensure the reporting time is correct regardless persistResource( - Tld.get("tld").asBuilder().setRenewGracePeriodLength(Duration.standardMinutes(9)).build()); + Tld.get("tld").asBuilder().setRenewGracePeriodLength(Duration.ofMinutes(9)).build()); runFlow(); Domain domain = reloadResourceByForeignKey(); DomainHistory historyEntry = diff --git a/core/src/test/java/google/registry/flows/domain/DomainRestoreRequestFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainRestoreRequestFlowTest.java index 91262931c..6ca88a20f 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainRestoreRequestFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainRestoreRequestFlowTest.java @@ -30,7 +30,6 @@ import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DomainSubject.assertAboutDomains; import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions; 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.minusDays; import static google.registry.util.DateTimeUtils.plusDays; @@ -175,7 +174,7 @@ class DomainRestoreRequestFlowTest extends ResourceFlowTestCase doFailingTest("domain_transfer_cancel.xml")); @@ -378,8 +378,8 @@ class DomainTransferCancelFlowTest persistResource( Tld.get("tld") .asBuilder() - .setAutomaticTransferLength(Duration.standardDays(2)) - .setTransferGracePeriodLength(Duration.standardDays(3)) + .setAutomaticTransferLength(Duration.ofDays(2)) + .setTransferGracePeriodLength(Duration.ofDays(3)) .build()); DomainTransactionRecord previousSuccessRecord = DomainTransactionRecord.create("tld", plusDays(clock.now(), 1), TRANSFER_SUCCESSFUL, 1); diff --git a/core/src/test/java/google/registry/flows/domain/DomainTransferFlowTestCase.java b/core/src/test/java/google/registry/flows/domain/DomainTransferFlowTestCase.java index 898fe82aa..dac13c49a 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainTransferFlowTestCase.java +++ b/core/src/test/java/google/registry/flows/domain/DomainTransferFlowTestCase.java @@ -44,8 +44,8 @@ import google.registry.model.tld.Tld; import google.registry.model.transfer.DomainTransferData; import google.registry.model.transfer.TransferStatus; import google.registry.persistence.transaction.JpaTransactionManagerExtension; +import java.time.Duration; import java.time.Instant; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; /** @@ -62,8 +62,8 @@ abstract class DomainTransferFlowTestCase static final Instant TRANSFER_REQUEST_TIME = Instant.parse("2000-06-06T22:00:00.0Z"); static final Instant TRANSFER_EXPIRATION_TIME = - TRANSFER_REQUEST_TIME.plusMillis(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH.getMillis()); - private static final Duration TIME_SINCE_REQUEST = Duration.standardDays(3); + TRANSFER_REQUEST_TIME.plus(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH); + private static final Duration TIME_SINCE_REQUEST = Duration.ofDays(3); private static final int EXTENDED_REGISTRATION_YEARS = 1; private static final Instant REGISTRATION_EXPIRATION_TIME = Instant.parse("2001-09-08T22:00:00.0Z"); @@ -75,8 +75,8 @@ abstract class DomainTransferFlowTestCase private DomainHistory historyEntryDomainCreate; DomainTransferFlowTestCase() { - checkState(!Tld.DEFAULT_TRANSFER_GRACE_PERIOD.isShorterThan(TIME_SINCE_REQUEST)); - clock.setTo(TRANSFER_REQUEST_TIME.plusMillis(TIME_SINCE_REQUEST.getMillis())); + checkState(Tld.DEFAULT_TRANSFER_GRACE_PERIOD.compareTo(TIME_SINCE_REQUEST) >= 0); + clock.setTo(TRANSFER_REQUEST_TIME.plus(TIME_SINCE_REQUEST)); } @BeforeEach diff --git a/core/src/test/java/google/registry/flows/domain/DomainTransferQueryFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainTransferQueryFlowTest.java index 1c3e76627..4cec8272d 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainTransferQueryFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainTransferQueryFlowTest.java @@ -37,6 +37,7 @@ import google.registry.model.domain.DomainAuthInfo; import google.registry.model.eppcommon.AuthInfo.PasswordAuth; import google.registry.model.reporting.HistoryEntry; import google.registry.model.transfer.TransferStatus; +import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -66,9 +67,9 @@ class DomainTransferQueryFlowTest getGainingClientAutorenewEvent(), getLosingClientAutorenewEvent()); // Look in the future and make sure the poll messages for implicit ack are there. - assertThat(getPollMessages("NewRegistrar", clock.nowUtc().plusYears(1))) + assertThat(getPollMessages("NewRegistrar", clock.now().plus(Duration.ofDays(365)))) .hasSize(numPollMessages); - assertThat(getPollMessages("TheRegistrar", clock.nowUtc().plusYears(1))).hasSize(1); + assertThat(getPollMessages("TheRegistrar", clock.now().plus(Duration.ofDays(365)))).hasSize(1); } private void doFailingTest(String commandFilename) throws Exception { @@ -215,7 +216,7 @@ class DomainTransferQueryFlowTest @Test void testFailure_nonexistentDomain() throws Exception { - deleteTestDomain(domain, clock.nowUtc()); + deleteTestDomain(domain, clock.now()); ResourceDoesNotExistException thrown = assertThrows( ResourceDoesNotExistException.class, () -> doFailingTest("domain_transfer_query.xml")); diff --git a/core/src/test/java/google/registry/flows/domain/DomainTransferRejectFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainTransferRejectFlowTest.java index 86edb652d..ac3c69a3b 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainTransferRejectFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainTransferRejectFlowTest.java @@ -59,8 +59,8 @@ import google.registry.model.tld.Tld; import google.registry.model.transfer.DomainTransferData; import google.registry.model.transfer.TransferResponse; import google.registry.model.transfer.TransferStatus; +import java.time.Duration; import java.time.Instant; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -86,8 +86,8 @@ class DomainTransferRejectFlowTest getGainingClientAutorenewEvent(), getLosingClientAutorenewEvent()); // Look in the future and make sure the poll messages for implicit ack are there. - assertThat(getPollMessages("NewRegistrar", clock.nowUtc().plusMonths(1))).hasSize(1); - assertThat(getPollMessages("TheRegistrar", clock.nowUtc().plusMonths(1))).hasSize(1); + assertThat(getPollMessages("NewRegistrar", clock.now().plus(Duration.ofDays(31)))).hasSize(1); + assertThat(getPollMessages("TheRegistrar", clock.now().plus(Duration.ofDays(31)))).hasSize(1); // Setup done; run the test. assertMutatingFlow(true); Instant originalExpirationTime = domain.getRegistrationExpirationTime(); @@ -119,7 +119,7 @@ class DomainTransferRejectFlowTest assertBillingEvents( getLosingClientAutorenewEvent().asBuilder().setRecurrenceEndTime(END_INSTANT).build()); // The poll message (in the future) to the losing registrar for implicit ack should be gone. - assertThat(getPollMessages("TheRegistrar", clock.nowUtc().plusMonths(1))).isEmpty(); + assertThat(getPollMessages("TheRegistrar", clock.now().plus(Duration.ofDays(31)))).isEmpty(); // The poll message in the future to the gaining registrar should be gone too, but there // should be one at the current time to the gaining registrar. PollMessage gainingPollMessage = getOnlyPollMessage("NewRegistrar"); @@ -308,7 +308,7 @@ class DomainTransferRejectFlowTest @Test void testFailure_nonexistentDomain() throws Exception { - persistDomainAsDeleted(domain, clock.nowUtc()); + persistDomainAsDeleted(domain, clock.now()); ResourceDoesNotExistException thrown = assertThrows( ResourceDoesNotExistException.class, () -> doFailingTest("domain_transfer_reject.xml")); @@ -329,8 +329,8 @@ class DomainTransferRejectFlowTest persistResource( Tld.get("tld") .asBuilder() - .setAutomaticTransferLength(Duration.standardDays(2)) - .setTransferGracePeriodLength(Duration.standardDays(3)) + .setAutomaticTransferLength(Duration.ofDays(2)) + .setTransferGracePeriodLength(Duration.ofDays(3)) .build()); } diff --git a/core/src/test/java/google/registry/flows/domain/DomainTransferRequestFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainTransferRequestFlowTest.java index 40fdc51a1..01a88b7d8 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainTransferRequestFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainTransferRequestFlowTest.java @@ -129,12 +129,12 @@ import google.registry.persistence.VKey; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.DatabaseHelper; import java.math.BigDecimal; +import java.time.Duration; import java.time.Instant; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.joda.money.Money; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -277,8 +277,7 @@ class DomainTransferRequestFlowTest .setTargetId(domain.getDomainName()) .setEventTime(implicitTransferTime) .setBillingTime( - implicitTransferTime.plusMillis( - registry.getTransferGracePeriodLength().getMillis())) + implicitTransferTime.plus(registry.getTransferGracePeriodLength())) .setRegistrarId("NewRegistrar") .setCost(transferCost.orElse(Money.of(USD, 11))) .setPeriodYears(1) @@ -351,8 +350,7 @@ class DomainTransferRequestFlowTest GracePeriod.create( GracePeriodStatus.TRANSFER, domain.getRepoId(), - implicitTransferTime.plusMillis( - registry.getTransferGracePeriodLength().getMillis()), + implicitTransferTime.plus(registry.getTransferGracePeriodLength()), "NewRegistrar", null), optionalTransferBillingEvent.get())); @@ -366,7 +364,7 @@ class DomainTransferRequestFlowTest // Assert that there exists a poll message to notify the losing registrar that a transfer was // requested. If the implicit transfer time is now (i.e. the automatic transfer length is zero) // then also expect a server approved poll message. - assertThat(getPollMessages("TheRegistrar", clock.nowUtc())) + assertThat(getPollMessages("TheRegistrar", clock.now())) .hasSize(implicitTransferTime.equals(clock.now()) ? 2 : 1); // Two poll messages on the gaining registrar's side at the expected expiration time: a @@ -397,7 +395,7 @@ class DomainTransferRequestFlowTest // transfer pending message, and a transfer approved message (both OneTime messages). assertThat(getPollMessages("TheRegistrar", implicitTransferTime)).hasSize(2); PollMessage losingTransferPendingPollMessage = - getPollMessages("TheRegistrar", clock.nowUtc()).stream() + getPollMessages("TheRegistrar", clock.now()).stream() .filter(pollMessage -> TransferStatus.PENDING.getMessage().equals(pollMessage.getMsg())) .collect(onlyElement()); PollMessage losingTransferApprovedPollMessage = @@ -454,8 +452,8 @@ class DomainTransferRequestFlowTest domain.cloneProjectedAtTime( clock .now() - .plusMillis(registry.getAutomaticTransferLength().getMillis()) - .plusMillis(registry.getTransferGracePeriodLength().getMillis())); + .plus(registry.getAutomaticTransferLength()) + .plus(registry.getTransferGracePeriodLength())); assertThat(afterGracePeriod.getGracePeriods()).isEmpty(); } @@ -478,8 +476,7 @@ class DomainTransferRequestFlowTest // for the request test we want that same 'now' to be the initial request time, so we shift // the transfer timeline 3 days later by adjusting the implicit transfer time here. Tld registry = Tld.get(domain.getTld()); - Instant implicitTransferTime = - clock.now().plusMillis(registry.getAutomaticTransferLength().getMillis()); + Instant implicitTransferTime = clock.now().plus(registry.getAutomaticTransferLength()); // Setup done; run the test. assertMutatingFlow(true); runFlowAssertResponse(loadFile(expectedXmlFilename, substitutions)); @@ -501,7 +498,7 @@ class DomainTransferRequestFlowTest assertTransferRequested( domain, implicitTransferTime, Period.create(1, Unit.YEARS), expectedExpirationTime); - subordinateHost = reloadResourceAndCloneAtTime(subordinateHost, clock.nowUtc()); + subordinateHost = reloadResourceAndCloneAtTime(subordinateHost, clock.now()); assertAboutHosts().that(subordinateHost).hasNoHistoryEntries(); assertHistoryEntriesContainBillingEventsAndGracePeriods( @@ -524,7 +521,7 @@ class DomainTransferRequestFlowTest .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, domain.createVKey().stringify()) .param(PARAM_REQUESTED_TIME, clock.now().toString()) - .scheduleTime(clock.nowUtc().plus(registry.getAutomaticTransferLength()))); + .scheduleTime(clock.now().plus(registry.getAutomaticTransferLength()))); } private void doSuccessfulTest( @@ -577,8 +574,7 @@ class DomainTransferRequestFlowTest // For all of the other transfer flow tests, 'now' corresponds to day 3 of the transfer, but // for the request test we want that same 'now' to be the initial request time, so we shift // the transfer timeline 3 days later by adjusting the implicit transfer time here. - Instant implicitTransferTime = - clock.now().plusMillis(expectedAutomaticTransferLength.getMillis()); + Instant implicitTransferTime = clock.now().plus(expectedAutomaticTransferLength); // Setup done; run the test. assertMutatingFlow(true); runFlowAssertResponse( @@ -607,7 +603,7 @@ class DomainTransferRequestFlowTest // Verify correct fields were set. assertTransferRequested(domain, implicitTransferTime, expectedPeriod, expectedExpirationTime); - subordinateHost = reloadResourceAndCloneAtTime(subordinateHost, clock.nowUtc()); + subordinateHost = reloadResourceAndCloneAtTime(subordinateHost, clock.now()); assertAboutHosts().that(subordinateHost).hasNoHistoryEntries(); boolean expectTransferBillingEvent = expectedPeriod.getValue() != 0; @@ -752,10 +748,7 @@ class DomainTransferRequestFlowTest void testSuccess_nonDefaultAutomaticTransferLength() throws Exception { setupDomain("example", "tld"); persistResource( - Tld.get("tld") - .asBuilder() - .setAutomaticTransferLength(Duration.standardMinutes(15)) - .build()); + Tld.get("tld").asBuilder().setAutomaticTransferLength(Duration.ofMinutes(15)).build()); doSuccessfulTest( "domain_transfer_request.xml", "domain_transfer_request_response_15_minutes.xml"); } @@ -764,10 +757,7 @@ class DomainTransferRequestFlowTest void testSuccess_nonDefaultTransferGracePeriod() throws Exception { setupDomain("example", "tld"); persistResource( - Tld.get("tld") - .asBuilder() - .setTransferGracePeriodLength(Duration.standardMinutes(5)) - .build()); + Tld.get("tld").asBuilder().setTransferGracePeriodLength(Duration.ofMinutes(5)).build()); doSuccessfulTest("domain_transfer_request.xml", "domain_transfer_request_response.xml"); } @@ -824,7 +814,7 @@ class DomainTransferRequestFlowTest ImmutableMap.of("PERIOD", "0", "AUTOMATIC_TRANSFER_LENGTH", "5"), Optional.empty(), Period.create(0, Unit.YEARS), - Duration.standardDays(5)); + Duration.ofDays(5)); } @Test @@ -853,7 +843,7 @@ class DomainTransferRequestFlowTest ImmutableMap.of("PERIOD", "1", "AUTOMATIC_TRANSFER_LENGTH", "5"), Optional.empty(), Period.create(1, Unit.YEARS), - Duration.standardDays(5)); + Duration.ofDays(5)); } @Test @@ -873,8 +863,7 @@ class DomainTransferRequestFlowTest GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), - autorenewTime.plusMillis( - Tld.get("tld").getAutoRenewGracePeriodLength().getMillis()), + autorenewTime.plus(Tld.get("tld").getAutoRenewGracePeriodLength()), "TheRegistrar", existingAutorenewEvent)) .build()); @@ -969,8 +958,7 @@ class DomainTransferRequestFlowTest doSuccessfulTest( "domain_transfer_request.xml", "domain_transfer_request_response_10_year_cap.xml", - plusYears( - clock.now().plusMillis(Tld.get("tld").getAutomaticTransferLength().getMillis()), 10)); + plusYears(clock.now().plus(Tld.get("tld").getAutomaticTransferLength()), 10)); } @Test @@ -1054,8 +1042,7 @@ class DomainTransferRequestFlowTest // Set the domain to have auto-renewed long enough ago that it is still in the autorenew grace // period at the transfer request time, but will have exited it by the automatic transfer time. Instant autorenewTime = - plusDays( - clock.now().minusMillis(Tld.get("tld").getAutoRenewGracePeriodLength().getMillis()), 1); + plusDays(clock.now().minus(Tld.get("tld").getAutoRenewGracePeriodLength()), 1); Instant expirationTime = plusYears(autorenewTime, 1); domain = persistResource( @@ -1066,8 +1053,7 @@ class DomainTransferRequestFlowTest GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), - autorenewTime.plusMillis( - Tld.get("tld").getAutoRenewGracePeriodLength().getMillis()), + autorenewTime.plus(Tld.get("tld").getAutoRenewGracePeriodLength()), "TheRegistrar", domain.getAutorenewBillingEvent())) .build()); @@ -1097,8 +1083,7 @@ class DomainTransferRequestFlowTest GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), - autorenewTime.plusMillis( - Tld.get("tld").getAutoRenewGracePeriodLength().getMillis()), + autorenewTime.plus(Tld.get("tld").getAutoRenewGracePeriodLength()), "TheRegistrar", existingAutorenewEvent)) .build()); @@ -1114,11 +1099,8 @@ class DomainTransferRequestFlowTest .setTargetId("example.tld") .setRegistrarId("TheRegistrar") // The cancellation happens at the moment of transfer. - .setEventTime( - clock.now().plusMillis(Tld.get("tld").getAutomaticTransferLength().getMillis())) - .setBillingTime( - autorenewTime.plusMillis( - Tld.get("tld").getAutoRenewGracePeriodLength().getMillis())) + .setEventTime(clock.now().plus(Tld.get("tld").getAutomaticTransferLength())) + .setBillingTime(autorenewTime.plus(Tld.get("tld").getAutoRenewGracePeriodLength())) // The cancellation should refer to the old autorenew billing event. .setBillingRecurrence(existingAutorenewEvent)); } @@ -1144,11 +1126,8 @@ class DomainTransferRequestFlowTest .setTargetId("example.tld") .setRegistrarId("TheRegistrar") // The cancellation happens at the moment of transfer. - .setEventTime( - clock.now().plusMillis(Tld.get("tld").getAutomaticTransferLength().getMillis())) - .setBillingTime( - expirationTime.plusMillis( - Tld.get("tld").getAutoRenewGracePeriodLength().getMillis())) + .setEventTime(clock.now().plus(Tld.get("tld").getAutomaticTransferLength())) + .setBillingTime(expirationTime.plus(Tld.get("tld").getAutoRenewGracePeriodLength())) // The cancellation should refer to the old autorenew billing event. .setBillingRecurrence(existingAutorenewEvent)); } @@ -1746,8 +1725,8 @@ class DomainTransferRequestFlowTest persistResource( Tld.get("tld") .asBuilder() - .setAutomaticTransferLength(Duration.standardDays(2)) - .setTransferGracePeriodLength(Duration.standardDays(3)) + .setAutomaticTransferLength(Duration.ofDays(2)) + .setTransferGracePeriodLength(Duration.ofDays(3)) .build()); clock.advanceOneMilli(); runTest("domain_transfer_request.xml", UserPrivileges.NORMAL); diff --git a/core/src/test/java/google/registry/flows/domain/DomainUpdateFlowTest.java b/core/src/test/java/google/registry/flows/domain/DomainUpdateFlowTest.java index 2ff05e41f..1d24f9db5 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainUpdateFlowTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainUpdateFlowTest.java @@ -51,6 +51,7 @@ import static google.registry.testing.DomainSubject.assertAboutDomains; import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions; import static google.registry.testing.HistoryEntrySubject.assertAboutHistoryEntries; import static google.registry.util.DateTimeUtils.START_INSTANT; +import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusDays; import static google.registry.util.DateTimeUtils.plusYears; import static org.joda.money.CurrencyUnit.USD; @@ -1046,7 +1047,7 @@ class DomainUpdateFlowTest extends ResourceFlowTestCase { @Test void testOneExistsButWasDeleted() throws Exception { - persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1)); + persistDeletedHost("ns1.example.tld", minusDays(clock.now(), 1)); // These ids come from the check xml. doCheckTest( create(true, "ns1.example.tld", null), diff --git a/core/src/test/java/google/registry/flows/host/HostCreateFlowTest.java b/core/src/test/java/google/registry/flows/host/HostCreateFlowTest.java index 76319cbd4..12e04d1f1 100644 --- a/core/src/test/java/google/registry/flows/host/HostCreateFlowTest.java +++ b/core/src/test/java/google/registry/flows/host/HostCreateFlowTest.java @@ -27,6 +27,7 @@ import static google.registry.testing.DatabaseHelper.persistDeletedHost; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions; import static google.registry.testing.HostSubject.assertAboutHosts; +import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusDays; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -135,7 +136,7 @@ class HostCreateFlowTest extends ResourceFlowTestCase { doSuccessfulInternalTest("tld"); Host host = reloadResourceByForeignKey(); Domain superordinateDomain = - ForeignKeyUtils.loadResource(Domain.class, "example.tld", clock.nowUtc()).get(); + ForeignKeyUtils.loadResource(Domain.class, "example.tld", clock.now()).get(); assertAboutHosts().that(host).hasSuperordinateDomain(superordinateDomain.createVKey()); assertThat(superordinateDomain.getSubordinateHosts()).containsExactly("ns1.example.tld"); assertHostDnsRequests("ns1.example.tld"); @@ -174,7 +175,7 @@ class HostCreateFlowTest extends ResourceFlowTestCase { @Test void testSuccess_externalExistedButWasDeleted() throws Exception { - persistDeletedHost(getUniqueIdFromCommand(), clock.nowUtc().minusDays(1)); + persistDeletedHost(getUniqueIdFromCommand(), minusDays(clock.now(), 1)); doSuccessfulTest(); assertAboutHosts().that(reloadResourceByForeignKey()).hasSuperordinateDomain(null); assertNoDnsRequests(); @@ -182,11 +183,11 @@ class HostCreateFlowTest extends ResourceFlowTestCase { @Test void testSuccess_internalExistedButWasDeleted() throws Exception { - persistDeletedHost(getUniqueIdFromCommand(), clock.nowUtc().minusDays(1)); + persistDeletedHost(getUniqueIdFromCommand(), minusDays(clock.now(), 1)); doSuccessfulInternalTest("tld"); Host host = reloadResourceByForeignKey(); Domain superordinateDomain = - ForeignKeyUtils.loadResource(Domain.class, "example.tld", clock.nowUtc()).get(); + ForeignKeyUtils.loadResource(Domain.class, "example.tld", clock.now()).get(); assertAboutHosts().that(host).hasSuperordinateDomain(superordinateDomain.createVKey()); assertThat(superordinateDomain.getSubordinateHosts()).containsExactly("ns1.example.tld"); assertHostDnsRequests("ns1.example.tld"); diff --git a/core/src/test/java/google/registry/flows/host/HostDeleteFlowTest.java b/core/src/test/java/google/registry/flows/host/HostDeleteFlowTest.java index 8f413c926..19c95a846 100644 --- a/core/src/test/java/google/registry/flows/host/HostDeleteFlowTest.java +++ b/core/src/test/java/google/registry/flows/host/HostDeleteFlowTest.java @@ -102,7 +102,7 @@ class HostDeleteFlowTest extends ResourceFlowTestCase { @Test void testFailure_existedButWasDeleted() { - persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1)); + persistDeletedHost("ns1.example.tld", minusDays(clock.now(), 1)); ResourceDoesNotExistException thrown = assertThrows(ResourceDoesNotExistException.class, this::runFlow); assertThat(thrown).hasMessageThat().contains("(ns1.example.tld)"); @@ -238,8 +238,7 @@ class HostDeleteFlowTest extends ResourceFlowTestCase { createTld("tld"); // Setup a transfer that should have been server approved a day ago. Instant now = clock.now(); - Instant requestTime = - minusDays(now, 1).minusMillis(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH.getMillis()); + Instant requestTime = minusDays(now, 1).minus(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH); Instant transferExpirationTime = minusDays(now, 1); Domain domain = persistResource( @@ -273,8 +272,7 @@ class HostDeleteFlowTest extends ResourceFlowTestCase { createTld("tld"); // Setup a transfer that should have been server approved a day ago. Instant now = clock.now(); - Instant requestTime = - minusDays(now, 1).minusMillis(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH.getMillis()); + Instant requestTime = minusDays(now, 1).minus(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH); Instant transferExpirationTime = minusDays(now, 1); Domain domain = persistResource( @@ -345,7 +343,7 @@ class HostDeleteFlowTest extends ResourceFlowTestCase { private void assertSqlDeleteSuccess(boolean isSubordinate) throws Exception { assertThat(reloadResourceByForeignKey()).isNull(); - Host deletedHost = reloadResourceByForeignKey(clock.nowUtc().minusMillis(1)); + Host deletedHost = reloadResourceByForeignKey(clock.now().minusMillis(1)); assertAboutHosts() .that(deletedHost) .isNotActiveAt(clock.now()) diff --git a/core/src/test/java/google/registry/flows/host/HostUpdateFlowTest.java b/core/src/test/java/google/registry/flows/host/HostUpdateFlowTest.java index d597d87d3..8a7bb8d88 100644 --- a/core/src/test/java/google/registry/flows/host/HostUpdateFlowTest.java +++ b/core/src/test/java/google/registry/flows/host/HostUpdateFlowTest.java @@ -83,6 +83,7 @@ import google.registry.model.transfer.DomainTransferData; import google.registry.model.transfer.TransferStatus; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.DatabaseHelper; +import java.time.Duration; import java.time.Instant; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; @@ -116,8 +117,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { */ private Domain createDomainWithServerApprovedTransfer(String domainName) { Instant now = clock.now(); - Instant requestTime = - minusDays(now, 1).minusMillis(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH.getMillis()); + Instant requestTime = minusDays(now, 1).minus(Tld.DEFAULT_AUTOMATIC_TRANSFER_LENGTH); Instant transferExpirationTime = minusDays(now, 1); return DatabaseHelper.newDomain(domainName) .asBuilder() @@ -173,7 +173,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { assertThat(reloadResourceByForeignKey()).isNull(); // However, it should load correctly if we use the new name (taken from the xml). Host renamedHost = - ForeignKeyUtils.loadResource(Host.class, "ns2.example.tld", clock.nowUtc()).get(); + ForeignKeyUtils.loadResource(Host.class, "ns2.example.tld", clock.now()).get(); assertAboutHosts() .that(renamedHost) .hasOnlyOneHistoryEntryWhich() @@ -190,7 +190,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { Host renamedHost = doSuccessfulTest(); assertThat(renamedHost.isSubordinate()).isTrue(); assertHostDnsRequests("ns1.example.tld", "ns2.example.tld"); - assertThat(ForeignKeyUtils.loadKey(Host.class, oldHostName(), clock.nowUtc())).isEmpty(); + assertThat(ForeignKeyUtils.loadKey(Host.class, oldHostName(), clock.now())).isEmpty(); } @Test @@ -245,7 +245,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { sessionMetadata.setRegistrarId("NewRegistrar"); setEppInput("host_update_name_unchanged.xml"); createTld("tld"); - // Create a domain that will belong to NewRegistrar after cloneProjectedAtInstant is called. + // Create a domain that will belong to NewRegistrar after cloneProjectedAtTime is called. Domain domain = persistResource(createDomainWithServerApprovedTransfer("example.tld")); Host oldHost = persistActiveSubordinateHost(oldHostName(), domain); clock.advanceOneMilli(); @@ -906,7 +906,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { @Test void testFailure_existedButWasDeleted() throws Exception { - persistDeletedHost(oldHostName(), clock.nowUtc().minusDays(1)); + persistDeletedHost(oldHostName(), clock.now().minus(Duration.ofDays(1))); ResourceDoesNotExistException thrown = assertThrows(ResourceDoesNotExistException.class, this::runFlow); assertThat(thrown).hasMessageThat().contains(String.format("(%s)", getUniqueIdFromCommand())); @@ -1234,7 +1234,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { void testSuccess_authorizedClientReadFromTransferredSuperordinate() throws Exception { sessionMetadata.setRegistrarId("NewRegistrar"); createTld("tld"); - // Create a domain that will belong to NewRegistrar after cloneProjectedAtInstant is called. + // Create a domain that will belong to NewRegistrar after cloneProjectedAtTime is called. Domain domain = persistResource(createDomainWithServerApprovedTransfer("example.tld")); persistResource( newHost("ns1.example.tld") @@ -1252,7 +1252,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { void testFailure_unauthorizedClientReadFromTransferredSuperordinate() { sessionMetadata.setRegistrarId("TheRegistrar"); createTld("tld"); - // Create a domain that will belong to NewRegistrar after cloneProjectedAtInstant is called. + // Create a domain that will belong to NewRegistrar after cloneProjectedAtTime is called. Domain domain = persistResource(createDomainWithServerApprovedTransfer("example.tld")); persistResource( newHost("ns1.example.tld") @@ -1293,7 +1293,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { createTld("foo"); createTld("tld"); Host host = persistActiveSubordinateHost(oldHostName(), persistActiveDomain("example.foo")); - // The domain will belong to NewRegistrar after cloneProjectedAtInstant is called. + // The domain will belong to NewRegistrar after cloneProjectedAtTime is called. Domain domain = persistResource(createDomainWithServerApprovedTransfer("example.tld")); assertAboutDomains().that(domain).hasPersistedCurrentSponsorRegistrarId("TheRegistrar"); assertAboutHosts().that(host).hasPersistedCurrentSponsorRegistrarId("TheRegistrar"); @@ -1309,7 +1309,7 @@ class HostUpdateFlowTest extends ResourceFlowTestCase { sessionMetadata.setRegistrarId("NewRegistrar"); createTld("foo"); createTld("tld"); - // The domain will belong to NewRegistrar after cloneProjectedAtInstant is called. + // The domain will belong to NewRegistrar after cloneProjectedAtTime is called. Domain domain = persistResource(createDomainWithServerApprovedTransfer("example.tld")); Domain superordinate = persistResource( diff --git a/core/src/test/java/google/registry/flows/poll/PollAckFlowTest.java b/core/src/test/java/google/registry/flows/poll/PollAckFlowTest.java index 05116f2ac..c0e3de115 100644 --- a/core/src/test/java/google/registry/flows/poll/PollAckFlowTest.java +++ b/core/src/test/java/google/registry/flows/poll/PollAckFlowTest.java @@ -18,8 +18,11 @@ import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatabaseHelper.createHistoryEntryForEppResource; import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistResource; -import static google.registry.util.DateTimeUtils.END_OF_TIME; -import static google.registry.util.DateTimeUtils.toInstant; +import static google.registry.util.DateTimeUtils.END_INSTANT; +import static google.registry.util.DateTimeUtils.minusDays; +import static google.registry.util.DateTimeUtils.minusMonths; +import static google.registry.util.DateTimeUtils.minusYears; +import static google.registry.util.DateTimeUtils.plusDays; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableMap; @@ -31,7 +34,7 @@ import google.registry.flows.poll.PollAckFlow.NotAuthorizedToAckMessageException import google.registry.model.domain.Domain; import google.registry.model.poll.PollMessage; import google.registry.testing.DatabaseHelper; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -46,7 +49,7 @@ class PollAckFlowTest extends FlowTestCase { @BeforeEach void setUp() { setEppInput("poll_ack.xml", ImmutableMap.of("MSGID", "3-2011")); - clock.setTo(DateTime.parse("2011-01-02T01:01:01Z")); + clock.setTo(Instant.parse("2011-01-02T01:01:01Z")); setRegistrarIdForFlow("NewRegistrar"); createTld("example"); domain = persistResource(DatabaseHelper.newDomain("test.example")); @@ -57,18 +60,18 @@ class PollAckFlowTest extends FlowTestCase { new PollMessage.OneTime.Builder() .setId(messageId) .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .setMsg("Some poll message.") .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); } - private void persistAutorenewPollMessage(DateTime eventTime, DateTime endTime) { + private void persistAutorenewPollMessage(Instant eventTime, Instant endTime) { persistResource( new PollMessage.Autorenew.Builder() .setId(MESSAGE_ID) .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(toInstant(eventTime)) + .setEventTime(eventTime) .setAutorenewEndTime(endTime) .setMsg("Domain was auto-renewed.") .setTargetId("example.com") @@ -85,7 +88,7 @@ class PollAckFlowTest extends FlowTestCase { @Test void testSuccess_recentActiveAutorenew() throws Exception { setEppInput("poll_ack.xml", ImmutableMap.of("MSGID", "3-2010")); - persistAutorenewPollMessage(clock.nowUtc().minusMonths(6), END_OF_TIME); + persistAutorenewPollMessage(minusMonths(clock.now(), 6), END_INSTANT); assertMutatingFlow(true); runFlowAssertResponse(loadFile("poll_ack_response_empty.xml")); } @@ -93,7 +96,7 @@ class PollAckFlowTest extends FlowTestCase { @Test void testSuccess_oldActiveAutorenew() throws Exception { setEppInput("poll_ack.xml", ImmutableMap.of("MSGID", "3-2009")); - persistAutorenewPollMessage(clock.nowUtc().minusYears(2), END_OF_TIME); + persistAutorenewPollMessage(minusYears(clock.now(), 2), END_INSTANT); // Create three other messages to be queued for retrieval to get our count right, since the poll // ack response wants there to be 4 messages in the queue when the ack comes back. for (int i = 1; i < 4; i++) { @@ -107,7 +110,7 @@ class PollAckFlowTest extends FlowTestCase { @Test void testSuccess_oldInactiveAutorenew() throws Exception { setEppInput("poll_ack.xml", ImmutableMap.of("MSGID", "3-2010")); - persistAutorenewPollMessage(clock.nowUtc().minusMonths(6), clock.nowUtc()); + persistAutorenewPollMessage(minusMonths(clock.now(), 6), clock.now()); assertMutatingFlow(true); runFlowAssertResponse(loadFile("poll_ack_response_empty.xml")); } @@ -164,7 +167,7 @@ class PollAckFlowTest extends FlowTestCase { new PollMessage.OneTime.Builder() .setId(MESSAGE_ID) .setRegistrarId("TheRegistrar") - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .setMsg("Some poll message.") .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); @@ -178,7 +181,7 @@ class PollAckFlowTest extends FlowTestCase { new PollMessage.OneTime.Builder() .setId(MESSAGE_ID) .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().plusDays(1)) + .setEventTime(plusDays(clock.now(), 1)) .setMsg("Some poll message.") .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); diff --git a/core/src/test/java/google/registry/flows/poll/PollRequestFlowTest.java b/core/src/test/java/google/registry/flows/poll/PollRequestFlowTest.java index ef9df13e2..8074020b6 100644 --- a/core/src/test/java/google/registry/flows/poll/PollRequestFlowTest.java +++ b/core/src/test/java/google/registry/flows/poll/PollRequestFlowTest.java @@ -38,7 +38,8 @@ import google.registry.model.reporting.HistoryEntry; import google.registry.model.transfer.TransferResponse.DomainTransferResponse; import google.registry.model.transfer.TransferStatus; import google.registry.testing.DatabaseHelper; -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; @@ -51,7 +52,7 @@ class PollRequestFlowTest extends FlowTestCase { @BeforeEach void setUp() { setEppInput("poll.xml"); - clock.setTo(DateTime.parse("2011-01-02T01:01:01Z")); + clock.setTo(Instant.parse("2011-01-02T01:01:01Z")); setRegistrarIdForFlow("NewRegistrar"); createTld("example"); persistNewRegistrar("BadRegistrar"); @@ -63,7 +64,7 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .setMsg("Transfer approved.") .setResponseData( ImmutableList.of( @@ -100,15 +101,12 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .setMsg("Domain deleted.") .setResponseData( ImmutableList.of( DomainPendingActionNotificationResponse.create( - "test.example", - true, - Trid.create("ABC-12345", "other-trid"), - clock.nowUtc()))) + "test.example", true, Trid.create("ABC-12345", "other-trid"), clock.now()))) .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); assertMutatingFlow(false); @@ -120,19 +118,19 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc()) + .setEventTime(clock.now()) .setMsg( String.format( "Domain %s was deleted by registry administrator with final deletion" + " effective: %s", - domain.getDomainName(), clock.nowUtc().minusMinutes(5))) + domain.getDomainName(), clock.now().minus(Duration.ofMinutes(5)))) .setResponseData( ImmutableList.of( DomainPendingActionNotificationResponse.create( domain.getDomainName(), true, Trid.create("ABC-12345", "other-trid"), - clock.nowUtc()))) + clock.now()))) .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); assertMutatingFlow(false); @@ -144,7 +142,7 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.Autorenew.Builder() .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .setMsg("Domain was auto-renewed.") .setTargetId("test.example") .setHistoryEntry(createHistoryEntryForEppResource(domain)) @@ -163,7 +161,7 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId("BadRegistrar") - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .setMsg("Poll message") .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); @@ -175,7 +173,7 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().plusDays(1)) + .setEventTime(clock.now().plus(Duration.ofDays(1))) .setMsg("Poll message") .setHistoryEntry(createHistoryEntryForEppResource(domain)) .build()); @@ -187,7 +185,7 @@ class PollRequestFlowTest extends FlowTestCase { persistResource( new PollMessage.Autorenew.Builder() .setRegistrarId(getRegistrarIdForFlow()) - .setEventTime(clock.nowUtc().plusDays(1)) + .setEventTime(clock.now().plus(Duration.ofDays(1))) .setMsg("Domain was auto-renewed.") .setTargetId("target.example") .setHistoryEntry(createHistoryEntryForEppResource(domain)) @@ -213,7 +211,7 @@ class PollRequestFlowTest extends FlowTestCase { .setRegistrarId("NewRegistrar") .setMsg("Deleted host ns1.test.example") .setHistoryEntry(historyEntry) - .setEventTime(clock.nowUtc().minusDays(1)) + .setEventTime(minusDays(clock.now(), 1)) .build()); clock.advanceOneMilli(); assertMutatingFlow(false); diff --git a/core/src/test/java/google/registry/flows/session/HelloFlowTest.java b/core/src/test/java/google/registry/flows/session/HelloFlowTest.java index ca2eab1fc..cc346acd3 100644 --- a/core/src/test/java/google/registry/flows/session/HelloFlowTest.java +++ b/core/src/test/java/google/registry/flows/session/HelloFlowTest.java @@ -15,13 +15,14 @@ package google.registry.flows.session; import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions; -import static org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableMap; import google.registry.flows.EppException; import google.registry.flows.FlowTestCase; import google.registry.flows.FlowUtils.GenericXmlSyntaxErrorException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; /** Unit tests for {@link HelloFlow}. */ @@ -31,9 +32,11 @@ class HelloFlowTest extends FlowTestCase { void testHello() throws Exception { setEppInput("hello.xml"); assertMutatingFlow(false); + Instant now = clock.now(); runFlowAssertResponse( loadFile( - "greeting.xml", ImmutableMap.of("DATE", clock.nowUtc().toString(dateTimeNoMillis())))); + "greeting.xml", + ImmutableMap.of("DATE", now.truncatedTo(ChronoUnit.SECONDS).toString()))); } @Test diff --git a/core/src/test/java/google/registry/flows/session/LoginFlowTestCase.java b/core/src/test/java/google/registry/flows/session/LoginFlowTestCase.java index d1afedcbd..9a5af584c 100644 --- a/core/src/test/java/google/registry/flows/session/LoginFlowTestCase.java +++ b/core/src/test/java/google/registry/flows/session/LoginFlowTestCase.java @@ -22,7 +22,7 @@ import static google.registry.testing.DatabaseHelper.deleteResource; import static google.registry.testing.DatabaseHelper.loadRegistrar; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions; -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.ImmutableMap; @@ -64,7 +64,7 @@ public abstract class LoginFlowTestCase extends FlowTestCase { persistResource( new FeatureFlag.Builder() .setFeatureName(PROHIBIT_CONTACT_OBJECTS_ON_LOGIN) - .setStatusMap(ImmutableSortedMap.of(START_OF_TIME, FeatureStatus.ACTIVE)) + .setStatusMap(ImmutableSortedMap.of(START_INSTANT, FeatureStatus.ACTIVE)) .build()); } @@ -137,7 +137,7 @@ public abstract class LoginFlowTestCase extends FlowTestCase { persistResource( FeatureFlag.get(PROHIBIT_CONTACT_OBJECTS_ON_LOGIN) .asBuilder() - .setStatusMap(ImmutableSortedMap.of(START_OF_TIME, FeatureStatus.INACTIVE)) + .setStatusMap(ImmutableSortedMap.of(START_INSTANT, FeatureStatus.INACTIVE)) .build()); doSuccessfulTest("login_with_contact_objuri.xml"); } @@ -147,7 +147,7 @@ public abstract class LoginFlowTestCase extends FlowTestCase { persistResource( FeatureFlag.get(PROHIBIT_CONTACT_OBJECTS_ON_LOGIN) .asBuilder() - .setStatusMap(ImmutableSortedMap.of(START_OF_TIME, FeatureStatus.INACTIVE)) + .setStatusMap(ImmutableSortedMap.of(START_INSTANT, FeatureStatus.INACTIVE)) .build()); doSuccessfulTest("login_valid.xml"); } diff --git a/core/src/test/java/google/registry/flows/session/LoginFlowViaTlsTest.java b/core/src/test/java/google/registry/flows/session/LoginFlowViaTlsTest.java index 3da258894..01090d1bd 100644 --- a/core/src/test/java/google/registry/flows/session/LoginFlowViaTlsTest.java +++ b/core/src/test/java/google/registry/flows/session/LoginFlowViaTlsTest.java @@ -15,7 +15,7 @@ package google.registry.flows.session; 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 com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -30,8 +30,8 @@ import google.registry.model.registrar.Registrar; import google.registry.testing.CertificateSamples; import google.registry.util.CidrAddressBlock; import java.net.InetAddress; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; /** Unit tests for {@link LoginFlow} when accessed via a TLS transport. */ @@ -52,7 +52,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase { Optional.of(InetAddresses.forString("2001:db8::2")); private final CertificateChecker certificateChecker = new CertificateChecker( - ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398), + ImmutableSortedMap.of(START_INSTANT, 825, Instant.parse("2020-09-01T00:00:00Z"), 398), 30, 15, 2048, @@ -68,7 +68,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase { @Test void testSuccess_withGoodCredentials() throws Exception { - clock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + clock.setTo(Instant.parse("2020-11-01T00:00:00Z")); persistResource(getRegistrarBuilder().build()); credentials = new TlsCredentials(true, GOOD_CERT_HASH, GOOD_IP, certificateChecker); doSuccessfulTest("login_valid.xml"); @@ -76,7 +76,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase { @Test void testSuccess_withGoodCredentialsIpv6() throws Exception { - clock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + clock.setTo(Instant.parse("2020-11-01T00:00:00Z")); persistResource( getRegistrarBuilder() .setIpAddressAllowList( @@ -88,7 +88,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase { @Test void testSuccess_withIpv6AddressInSubnet() throws Exception { - clock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + clock.setTo(Instant.parse("2020-11-01T00:00:00Z")); persistResource( getRegistrarBuilder() .setIpAddressAllowList( @@ -100,7 +100,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase { @Test void testSuccess_withIpv4AddressInSubnet() throws Exception { - clock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); + clock.setTo(Instant.parse("2020-11-01T00:00:00Z")); persistResource( getRegistrarBuilder() .setIpAddressAllowList(ImmutableList.of(CidrAddressBlock.create("192.168.1.255/24"))) diff --git a/core/src/test/java/google/registry/model/EppResourceTest.java b/core/src/test/java/google/registry/model/EppResourceTest.java index 6532cc190..6b9bddb71 100644 --- a/core/src/test/java/google/registry/model/EppResourceTest.java +++ b/core/src/test/java/google/registry/model/EppResourceTest.java @@ -43,7 +43,7 @@ public class EppResourceTest extends EntityTestCase { originalHost.asBuilder().setLastTransferTime(minusDays(fakeClock.now(), 60)).build()); assertThat(EppResource.loadByCacheIfEnabled(ImmutableList.of(originalHost.createVKey()))) .containsExactly(originalHost.createVKey(), originalHost); - assertThat(ForeignKeyUtils.loadResource(Host.class, "ns1.example.com", fakeClock.nowUtc())) + assertThat(ForeignKeyUtils.loadResource(Host.class, "ns1.example.com", fakeClock.now())) .hasValue(modifiedHost); } } diff --git a/core/src/test/java/google/registry/model/EppResourceUtilsTest.java b/core/src/test/java/google/registry/model/EppResourceUtilsTest.java index f83671a84..b250739fa 100644 --- a/core/src/test/java/google/registry/model/EppResourceUtilsTest.java +++ b/core/src/test/java/google/registry/model/EppResourceUtilsTest.java @@ -20,13 +20,12 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.newHost; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.util.DateTimeUtils.START_INSTANT; -import static org.joda.time.DateTimeZone.UTC; import google.registry.model.host.Host; 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.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -34,7 +33,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link EppResourceUtils}. */ class EppResourceUtilsTest { - private final FakeClock clock = new FakeClock(DateTime.now(UTC)); + private final FakeClock clock = new FakeClock(Instant.now()); @RegisterExtension final JpaIntegrationTestExtension jpa = @@ -52,7 +51,7 @@ class EppResourceUtilsTest { Host host = persistResource( newHost("ns1.cat.tld").asBuilder().setCreationTimeForTest(clock.now()).build()); - assertThat(loadAtPointInTime(host, clock.nowUtc().minusMillis(1))).isNull(); + assertThat(loadAtPointInTime(host, clock.now().minusMillis(1))).isNull(); } @Test @@ -62,6 +61,6 @@ class EppResourceUtilsTest { Host host = persistResource( newHost("ns1.cat.tld").asBuilder().setCreationTimeForTest(START_INSTANT).build()); - assertThat(loadAtPointInTime(host, clock.nowUtc())).isEqualTo(host); + assertThat(loadAtPointInTime(host, clock.now())).isEqualTo(host); } } diff --git a/core/src/test/java/google/registry/model/ForeignKeyUtilsTest.java b/core/src/test/java/google/registry/model/ForeignKeyUtilsTest.java index d1d88a499..b61250468 100644 --- a/core/src/test/java/google/registry/model/ForeignKeyUtilsTest.java +++ b/core/src/test/java/google/registry/model/ForeignKeyUtilsTest.java @@ -20,7 +20,6 @@ import static google.registry.testing.DatabaseHelper.persistActiveDomain; import static google.registry.testing.DatabaseHelper.persistActiveHost; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.util.DateTimeUtils.minusDays; -import static org.joda.time.DateTimeZone.UTC; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -31,7 +30,7 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationT import google.registry.testing.FakeClock; import google.registry.testing.TestCacheExtension; import java.time.Duration; -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; @@ -39,7 +38,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link ForeignKeyUtils}. */ class ForeignKeyUtilsTest { - private final FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); + private final FakeClock fakeClock = new FakeClock(Instant.parse("2024-03-27T10:15:30.105Z")); @RegisterExtension public final JpaIntegrationTestExtension jpaIntegrationTestExtension = @@ -60,14 +59,14 @@ class ForeignKeyUtilsTest { @Test void testSuccess_loadHostKey() { Host host = persistActiveHost("ns1.example.com"); - assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.nowUtc())) + assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.now())) .hasValue(host.createVKey()); } @Test void testSuccess_loadDomainKey() { Domain domain = persistActiveDomain("example.com"); - assertThat(ForeignKeyUtils.loadKey(Domain.class, "example.com", fakeClock.nowUtc())) + assertThat(ForeignKeyUtils.loadKey(Domain.class, "example.com", fakeClock.now())) .hasValue(domain.createVKey()); } @@ -77,22 +76,20 @@ class ForeignKeyUtilsTest { persistResource(host.asBuilder().setDeletionTime(minusDays(fakeClock.now(), 1)).build()); fakeClock.advanceOneMilli(); Host newHost = persistActiveHost("ns1.example.com"); - assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.nowUtc())) + assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.now())) .hasValue(newHost.createVKey()); } @Test void testSuccess_loadKeyNonexistentForeignKey_returnsNull() { - assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.nowUtc())) - .isEmpty(); + assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.now())).isEmpty(); } @Test void testSuccess_loadKeyDeletedForeignKey_returnsNull() { Host host = persistActiveHost("ns1.example.com"); persistResource(host.asBuilder().setDeletionTime(minusDays(fakeClock.now(), 1)).build()); - assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.nowUtc())) - .isEmpty(); + assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.now())).isEmpty(); } @Test @@ -100,8 +97,7 @@ class ForeignKeyUtilsTest { Host host1 = persistActiveHost("ns1.example.com"); fakeClock.advanceOneMilli(); persistResource(host1.asBuilder().setDeletionTime(fakeClock.now()).build()); - assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.nowUtc())) - .isEmpty(); + assertThat(ForeignKeyUtils.loadKey(Host.class, "ns1.example.com", fakeClock.now())).isEmpty(); } @Test @@ -113,7 +109,7 @@ class ForeignKeyUtilsTest { ForeignKeyUtils.loadKeys( Host.class, ImmutableList.of("ns1.example.com", "ns2.example.com", "ns3.example.com"), - fakeClock.nowUtc())) + fakeClock.now())) .containsExactlyEntriesIn(ImmutableMap.of("ns1.example.com", host1.createVKey())); persistResource(host1.asBuilder().setDeletionTime(fakeClock.now()).build()); fakeClock.advanceOneMilli(); @@ -122,7 +118,7 @@ class ForeignKeyUtilsTest { ForeignKeyUtils.loadKeysByCacheIfEnabled( Host.class, ImmutableList.of("ns1.example.com", "ns2.example.com", "ns3.example.com"), - fakeClock.nowUtc())) + fakeClock.now())) .containsExactlyEntriesIn(ImmutableMap.of("ns1.example.com", newHost1.createVKey())); } @@ -135,7 +131,7 @@ class ForeignKeyUtilsTest { ForeignKeyUtils.loadKeysByCacheIfEnabled( Host.class, ImmutableList.of("ns1.example.com", "ns2.example.com", "ns3.example.com"), - fakeClock.nowUtc())) + fakeClock.now())) .containsExactlyEntriesIn(ImmutableMap.of("ns1.example.com", host1.createVKey())); persistResource(host1.asBuilder().setDeletionTime(fakeClock.now()).build()); fakeClock.advanceOneMilli(); @@ -145,7 +141,7 @@ class ForeignKeyUtilsTest { ForeignKeyUtils.loadKeysByCacheIfEnabled( Host.class, ImmutableList.of("ns1.example.com", "ns2.example.com", "ns3.example.com"), - fakeClock.nowUtc())) + fakeClock.now())) .containsExactlyEntriesIn(ImmutableMap.of("ns1.example.com", host1.createVKey())); } } diff --git a/core/src/test/java/google/registry/model/ImmutableObjectTest.java b/core/src/test/java/google/registry/model/ImmutableObjectTest.java index 683c2806d..a3e019262 100644 --- a/core/src/test/java/google/registry/model/ImmutableObjectTest.java +++ b/core/src/test/java/google/registry/model/ImmutableObjectTest.java @@ -19,7 +19,7 @@ import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ImmutableObject.cloneEmptyToNull; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -32,6 +32,7 @@ import google.registry.util.CidrAddressBlock; import jakarta.persistence.Entity; import jakarta.persistence.Id; import java.lang.reflect.Field; +import java.time.Instant; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; @@ -39,7 +40,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -70,7 +70,8 @@ public class ImmutableObjectTest { SimpleObject: { a=foo b=null - }"""); + }\ + """); } @Test @@ -86,7 +87,7 @@ public class ImmutableObjectTest { Boolean boolObject; int integer; Integer integerObject; - DateTime datetime; + Instant instant; } @Test @@ -96,12 +97,12 @@ public class ImmutableObjectTest { object.boolObject = true; object.integer = 1; object.integerObject = 1; - object.datetime = START_OF_TIME; + object.instant = START_INSTANT; assertThat(object.toDiffableFieldMap()).containsEntry("bool", true); assertThat(object.toDiffableFieldMap()).containsEntry("boolObject", true); assertThat(object.toDiffableFieldMap()).containsEntry("integer", 1); assertThat(object.toDiffableFieldMap()).containsEntry("integerObject", 1); - assertThat(object.toDiffableFieldMap()).containsEntry("datetime", "1970-01-01T00:00:00.000Z"); + assertThat(object.toDiffableFieldMap()).containsEntry("instant", "1970-01-01T00:00:00.000Z"); } /** Subclass of ImmutableObject with a nested ImmutableObject. */ diff --git a/core/src/test/java/google/registry/model/OteAccountBuilderTest.java b/core/src/test/java/google/registry/model/OteAccountBuilderTest.java index 40dccc441..8affd6073 100644 --- a/core/src/test/java/google/registry/model/OteAccountBuilderTest.java +++ b/core/src/test/java/google/registry/model/OteAccountBuilderTest.java @@ -45,14 +45,15 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; +import google.registry.testing.FakeClock; import google.registry.tools.IamClient; import google.registry.util.CidrAddressBlock; import google.registry.util.SystemClock; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; import org.joda.money.Money; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -63,6 +64,7 @@ public final class OteAccountBuilderTest { final JpaIntegrationTestExtension jpa = new JpaTestExtensions.Builder().buildIntegrationTestExtension(); + private final FakeClock fakeClock = new FakeClock(Instant.parse("2024-01-01T00:00:00Z")); private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(); private final IamClient iamClient = mock(IamClient.class); @@ -81,19 +83,19 @@ public final class OteAccountBuilderTest { persistPremiumList("default_sandbox_list", USD, "sandbox,USD 1000"); } - private static void assertTldExists(String tld, TldState tldState, Money eapFee) { + private void assertTldExists(String tld, TldState tldState, Money eapFee) { Tld registry = Tld.get(tld); assertThat(registry).isNotNull(); assertThat(registry.getPremiumListName()).hasValue("default_sandbox_list"); assertThat(registry.getTldStateTransitions()).containsExactly(START_INSTANT, tldState); assertThat(registry.getDnsWriters()).containsExactly("VoidDnsWriter"); - assertThat(registry.getAddGracePeriodLength()).isEqualTo(Duration.standardHours(1)); - assertThat(registry.getPendingDeleteLength()).isEqualTo(Duration.standardMinutes(5)); - assertThat(registry.getRedemptionGracePeriodLength()).isEqualTo(Duration.standardMinutes(10)); + assertThat(registry.getAddGracePeriodLength()).isEqualTo(Duration.ofHours(1)); + assertThat(registry.getPendingDeleteLength()).isEqualTo(Duration.ofMinutes(5)); + assertThat(registry.getRedemptionGracePeriodLength()).isEqualTo(Duration.ofMinutes(10)); assertThat(registry.getCurrency()).isEqualTo(eapFee.getCurrencyUnit()); // This uses "now" on purpose - so the test will break at 2022 when the current EapFee in OTE // goes back to 0 - assertThat(registry.getEapFeeFor(Instant.now()).getCost()).isEqualTo(eapFee.getAmount()); + assertThat(registry.getEapFeeFor(fakeClock.now()).getCost()).isEqualTo(eapFee.getAmount()); } private static void assertRegistrarExists(String registrarId, String tld) { @@ -215,7 +217,7 @@ public final class OteAccountBuilderTest { @Test void testCreateOteEntities_setCertificate() { OteAccountBuilder.forRegistrarId("myclientid") - .setCertificate(SAMPLE_CERT, new SystemClock().nowUtc()) + .setCertificate(SAMPLE_CERT, new SystemClock().now()) .buildAndPersist(); assertThat(Registrar.loadByRegistrarId("myclientid-3").get().getClientCertificateHash()) diff --git a/core/src/test/java/google/registry/model/OteStatsTestHelper.java b/core/src/test/java/google/registry/model/OteStatsTestHelper.java index 30d8d53ed..139565293 100644 --- a/core/src/test/java/google/registry/model/OteStatsTestHelper.java +++ b/core/src/test/java/google/registry/model/OteStatsTestHelper.java @@ -24,7 +24,6 @@ import static google.registry.testing.DatabaseHelper.persistPremiumList; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.TestDataHelper.loadBytes; import static google.registry.util.DateTimeUtils.END_INSTANT; -import static google.registry.util.DateTimeUtils.toInstant; import static org.joda.money.CurrencyUnit.USD; import google.registry.model.domain.Domain; @@ -33,22 +32,22 @@ import google.registry.model.eppcommon.Trid; import google.registry.model.host.HostHistory; import google.registry.model.reporting.HistoryEntry.Type; import java.io.IOException; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.Instant; +import java.time.temporal.ChronoUnit; public final class OteStatsTestHelper { public static void setupCompleteOte(String baseClientId) throws IOException { setupIncompleteOte(baseClientId); String oteAccount1 = String.format("%s-1", baseClientId); - DateTime now = DateTime.now(DateTimeZone.UTC); + Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS); persistResource( new DomainHistory.Builder() .setDomain(persistActiveDomain("xn--abc-873b2e7eb1k8a4lpjvv.tld")) .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_CREATE) .setXmlBytes(getBytes("domain_create_idn.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -56,7 +55,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_RESTORE) .setXmlBytes(getBytes("domain_restore.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new HostHistory.Builder() @@ -64,7 +63,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.HOST_DELETE) .setXmlBytes(getBytes("host_delete.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); } @@ -84,14 +83,14 @@ public final class OteStatsTestHelper { persistPremiumList("default_sandbox_list", USD, "sandbox,USD 1000"); OteAccountBuilder.forRegistrarId(baseClientId).buildAndPersist(); String oteAccount1 = String.format("%s-1", baseClientId); - DateTime now = DateTime.now(DateTimeZone.UTC); + Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS); persistResource( new DomainHistory.Builder() .setDomain(loadOrCreateDomain("exampleone.tld")) .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_CREATE) .setXmlBytes(getBytes("domain_create_sunrise.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -99,7 +98,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_CREATE) .setXmlBytes(getBytes("domain_create_claim_notice.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); Domain exampleDomain = loadOrCreateDomain("example.tld"); persistResource( @@ -108,7 +107,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_CREATE) .setXmlBytes(getBytes("domain_create_anchor_tenant_fee_standard.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -116,7 +115,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_CREATE) .setXmlBytes(getBytes("domain_create_dsdata.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -124,7 +123,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_DELETE) .setXmlBytes(getBytes("domain_delete.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -132,7 +131,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_TRANSFER_APPROVE) .setXmlBytes(getBytes("domain_transfer_approve.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -140,7 +139,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_TRANSFER_CANCEL) .setXmlBytes(getBytes("domain_transfer_cancel.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -148,7 +147,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_TRANSFER_REJECT) .setXmlBytes(getBytes("domain_transfer_reject.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -156,7 +155,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_TRANSFER_REQUEST) .setXmlBytes(getBytes("domain_transfer_request.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new DomainHistory.Builder() @@ -164,7 +163,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.DOMAIN_UPDATE) .setXmlBytes(getBytes("domain_update_with_secdns.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); persistResource( new HostHistory.Builder() @@ -172,7 +171,7 @@ public final class OteStatsTestHelper { .setRegistrarId(oteAccount1) .setType(Type.HOST_CREATE) .setXmlBytes(getBytes("host_create_complete.xml")) - .setModificationTime(toInstant(now)) + .setModificationTime(now) .build()); // Persist 10 host updates for a total of 25 history entries. Since these also sort last by // modification time, when these cause all tests to pass, only the first will be recorded and @@ -196,7 +195,7 @@ public final class OteStatsTestHelper { private static Domain loadOrCreateDomain(String domainName) { return tm().transact( - () -> ForeignKeyUtils.loadResource(Domain.class, domainName, tm().getTransactionTime())) + () -> ForeignKeyUtils.loadResource(Domain.class, domainName, tm().getTxTime())) .orElseGet(() -> persistActiveDomain(domainName)); } } diff --git a/core/src/test/java/google/registry/model/common/FeatureFlagTest.java b/core/src/test/java/google/registry/model/common/FeatureFlagTest.java index 58148fd3e..d168779b6 100644 --- a/core/src/test/java/google/registry/model/common/FeatureFlagTest.java +++ b/core/src/test/java/google/registry/model/common/FeatureFlagTest.java @@ -23,7 +23,7 @@ import static google.registry.model.common.FeatureFlag.FeatureStatus.INACTIVE; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.loadByEntity; 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 com.google.common.collect.ImmutableSet; @@ -31,8 +31,8 @@ import com.google.common.collect.ImmutableSortedMap; import google.registry.model.EntityTestCase; import google.registry.model.common.FeatureFlag.FeatureFlagNotFoundException; import google.registry.model.common.FeatureFlag.FeatureStatus; -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 FeatureFlag}. */ @@ -48,9 +48,9 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(TEST_FEATURE) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()) .build(); persistResource(featureFlag); @@ -65,9 +65,9 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(TEST_FEATURE) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()) .build(); persistResource(featureFlag); @@ -81,9 +81,9 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(TEST_FEATURE) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()) .build()); FeatureFlag featureFlag2 = @@ -91,9 +91,9 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(MINIMUM_DATASET_CONTACTS_OPTIONAL) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(3), INACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(21)), INACTIVE) .build()) .build()); FeatureFlag featureFlag3 = @@ -101,8 +101,8 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(MINIMUM_DATASET_CONTACTS_PROHIBITED) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) .build()) .build()); ImmutableSet featureFlags = @@ -121,18 +121,18 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(TEST_FEATURE) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()) .build()); persistResource( new FeatureFlag.Builder() .setFeatureName(MINIMUM_DATASET_CONTACTS_OPTIONAL) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(3), INACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(21)), INACTIVE) .build()) .build()); FeatureFlagNotFoundException thrown = @@ -163,9 +163,9 @@ public class FeatureFlagTest extends EntityTestCase { FeatureFlag.Builder featureFlagBuilder = new FeatureFlag.Builder() .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> featureFlagBuilder.build()); @@ -180,8 +180,8 @@ public class FeatureFlagTest extends EntityTestCase { IllegalArgumentException.class, () -> featureFlagBuilder.setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build())); assertThat(thrown) .hasMessageThat() @@ -190,18 +190,18 @@ public class FeatureFlagTest extends EntityTestCase { @Test void testSuccess_isActiveNow() { - fakeClock.setTo(DateTime.parse("2010-10-17TZ")); + fakeClock.setTo(Instant.parse("2010-10-17T00:00:00Z")); persistResource( new FeatureFlag.Builder() .setFeatureName(TEST_FEATURE) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()) .build()); assertThat(tm().transact(() -> FeatureFlag.isActiveNow(TEST_FEATURE))).isFalse(); - fakeClock.setTo(DateTime.parse("2011-10-17TZ")); + fakeClock.setTo(Instant.parse("2011-10-17T00:00:00Z")); assertThat(tm().transact(() -> FeatureFlag.isActiveNow(TEST_FEATURE))).isTrue(); } @@ -211,16 +211,16 @@ public class FeatureFlagTest extends EntityTestCase { new FeatureFlag.Builder() .setFeatureName(TEST_FEATURE) .setStatusMap( - ImmutableSortedMap.naturalOrder() - .put(START_OF_TIME, INACTIVE) - .put(fakeClock.nowUtc().plusWeeks(8), ACTIVE) + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, INACTIVE) + .put(fakeClock.now().plus(Duration.ofDays(56)), ACTIVE) .build()) .build()); tm().transact( () -> { assertThat(FeatureFlag.isActiveNow(TEST_FEATURE)).isFalse(); }); - fakeClock.advanceBy(Duration.standardDays(365)); + fakeClock.advanceBy(Duration.ofDays(365)); tm().transact( () -> { assertThat(FeatureFlag.isActiveNow(TEST_FEATURE)).isTrue(); diff --git a/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java b/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java index 1a5812e68..a2f673a7e 100644 --- a/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java +++ b/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java @@ -15,29 +15,29 @@ package google.registry.model.common; import static com.google.common.truth.Truth.assertThat; -import static google.registry.util.DateTimeUtils.END_OF_TIME; -import static google.registry.util.DateTimeUtils.START_OF_TIME; -import static org.joda.time.DateTimeZone.UTC; +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.common.collect.ImmutableSortedMap; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Unit tests for {@link TimedTransitionProperty}. */ class TimedTransitionPropertyTest { - private static final DateTime A_LONG_TIME_AGO = new DateTime(Long.MIN_VALUE, UTC); + private static final Instant A_LONG_TIME_AGO = Instant.MIN; - private static final DateTime DATE_1 = DateTime.parse("2001-01-01T00:00:00.0Z"); - private static final DateTime DATE_2 = DateTime.parse("2002-01-01T00:00:00.0Z"); - private static final DateTime DATE_3 = DateTime.parse("2003-01-01T00:00:00.0Z"); + private static final Instant DATE_1 = Instant.parse("2001-01-01T00:00:00.0Z"); + private static final Instant DATE_2 = Instant.parse("2002-01-01T00:00:00.0Z"); + private static final Instant DATE_3 = Instant.parse("2003-01-01T00:00:00.0Z"); - private static final ImmutableSortedMap values = ImmutableSortedMap.of( - START_OF_TIME, "0", - DATE_1, "1", - DATE_2, "2", - DATE_3, "3"); + private static final ImmutableSortedMap values = + ImmutableSortedMap.of( + START_INSTANT, "0", + DATE_1, "1", + DATE_2, "2", + DATE_3, "3"); private TimedTransitionProperty timedString; @@ -53,8 +53,8 @@ class TimedTransitionPropertyTest { private static void testGetValueAtTime(TimedTransitionProperty timedString) { assertThat(timedString.getValueAtTime(A_LONG_TIME_AGO)).isEqualTo("0"); - assertThat(timedString.getValueAtTime(START_OF_TIME.minusMillis(1))).isEqualTo("0"); - assertThat(timedString.getValueAtTime(START_OF_TIME)).isEqualTo("0"); + assertThat(timedString.getValueAtTime(START_INSTANT.minusMillis(1))).isEqualTo("0"); + assertThat(timedString.getValueAtTime(START_INSTANT)).isEqualTo("0"); assertThat(timedString.getValueAtTime(DATE_1.minusMillis(1))).isEqualTo("0"); assertThat(timedString.getValueAtTime(DATE_1)).isEqualTo("1"); assertThat(timedString.getValueAtTime(DATE_1.plusMillis(1))).isEqualTo("1"); @@ -64,7 +64,7 @@ class TimedTransitionPropertyTest { assertThat(timedString.getValueAtTime(DATE_3.minusMillis(1))).isEqualTo("2"); assertThat(timedString.getValueAtTime(DATE_3)).isEqualTo("3"); assertThat(timedString.getValueAtTime(DATE_3.plusMillis(1))).isEqualTo("3"); - assertThat(timedString.getValueAtTime(END_OF_TIME)).isEqualTo("3"); + assertThat(timedString.getValueAtTime(END_INSTANT)).isEqualTo("3"); } @Test @@ -75,7 +75,7 @@ class TimedTransitionPropertyTest { @Test void testSuccess_getNextTransitionAfter() { assertThat(timedString.getNextTransitionAfter(A_LONG_TIME_AGO)).isEqualTo(DATE_1); - assertThat(timedString.getNextTransitionAfter(START_OF_TIME.plusMillis(1))).isEqualTo(DATE_1); + assertThat(timedString.getNextTransitionAfter(START_INSTANT.plusMillis(1))).isEqualTo(DATE_1); assertThat(timedString.getNextTransitionAfter(DATE_1.minusMillis(1))).isEqualTo(DATE_1); assertThat(timedString.getNextTransitionAfter(DATE_1)).isEqualTo(DATE_2); assertThat(timedString.getNextTransitionAfter(DATE_2.minusMillis(1))).isEqualTo(DATE_2); @@ -89,8 +89,8 @@ class TimedTransitionPropertyTest { IllegalArgumentException.class, () -> TimedTransitionProperty.fromValueMap( - ImmutableSortedMap.reverseOrder() - .put(START_OF_TIME, "0") + ImmutableSortedMap.reverseOrder() + .put(START_INSTANT, "0") .build())); } diff --git a/core/src/test/java/google/registry/model/console/ConsoleUpdateHistoryTest.java b/core/src/test/java/google/registry/model/console/ConsoleUpdateHistoryTest.java index accf0fb9c..182afc75e 100644 --- a/core/src/test/java/google/registry/model/console/ConsoleUpdateHistoryTest.java +++ b/core/src/test/java/google/registry/model/console/ConsoleUpdateHistoryTest.java @@ -19,10 +19,10 @@ import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.persistDomainWithDependentResources; import static google.registry.testing.DatabaseHelper.persistResource; +import static google.registry.util.DateTimeUtils.END_INSTANT; import google.registry.model.EntityTestCase; import google.registry.testing.DatabaseHelper; -import google.registry.util.DateTimeUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,11 +35,7 @@ public class ConsoleUpdateHistoryTest extends EntityTestCase { void beforeEach() { createTld("tld"); persistDomainWithDependentResources( - "example", - "tld", - fakeClock.nowUtc(), - fakeClock.nowUtc(), - DateTimeUtils.END_OF_TIME); + "example", "tld", fakeClock.now(), fakeClock.now(), END_INSTANT); } @Test @@ -52,7 +48,7 @@ public class ConsoleUpdateHistoryTest extends EntityTestCase { .setMethod("POST") .setUrl("/console-api/bulk-domain") .setDescription("example.tld") - .setModificationTime(fakeClock.nowUtc()) + .setModificationTime(fakeClock.now()) .build(); persistResource(history); assertThat(loadByEntity(history)).isEqualTo(history); 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 089915796..45bafd620 100644 --- a/core/src/test/java/google/registry/model/domain/DomainTest.java +++ b/core/src/test/java/google/registry/model/domain/DomainTest.java @@ -34,7 +34,6 @@ import static google.registry.util.DateTimeUtils.START_INSTANT; 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.junit.jupiter.api.Assertions.assertThrows; @@ -75,8 +74,6 @@ import java.time.Duration; import java.time.Instant; 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 +82,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; @SuppressWarnings("WeakerAccess") // Referred to by EppInputTest. public class DomainTest { - protected FakeClock fakeClock = new FakeClock(DateTime.now(DateTimeZone.UTC)); + protected FakeClock fakeClock = new FakeClock(Instant.parse("2020-09-01T00:00:00Z")); @RegisterExtension final JpaIntegrationWithCoverageExtension jpa = @@ -239,7 +236,7 @@ public class DomainTest { // stored under the primary key ("domain" is the domain loaded from the the database, not the // original domain object). String foreignKey = domain.getForeignKey(); - assertThat(ForeignKeyUtils.loadResource(Domain.class, foreignKey, fakeClock.nowUtc())) + assertThat(ForeignKeyUtils.loadResource(Domain.class, foreignKey, fakeClock.now())) .hasValue(domain); } @@ -388,16 +385,16 @@ public class DomainTest { } private void assertTransferred( - Domain domain, DateTime newExpirationTime, VKey newAutorenewEvent) { + Domain domain, Instant newExpirationTime, VKey newAutorenewEvent) { assertThat(domain.getTransferData().getTransferStatus()) .isEqualTo(TransferStatus.SERVER_APPROVED); assertThat(domain.getCurrentSponsorRegistrarId()).isEqualTo("TheRegistrar"); assertThat(domain.getLastTransferTime()).isEqualTo(plusDays(fakeClock.now(), 1)); - assertThat(domain.getRegistrationExpirationTime()).isEqualTo(toInstant(newExpirationTime)); + assertThat(domain.getRegistrationExpirationTime()).isEqualTo(newExpirationTime); assertThat(domain.getAutorenewBillingEvent()).isEqualTo(newAutorenewEvent); } - private void doExpiredTransferTest(DateTime oldExpirationTime) { + private void doExpiredTransferTest(Instant oldExpirationTime) { DomainHistory historyEntry = persistResource( new DomainHistory.Builder() @@ -416,9 +413,8 @@ public class DomainTest { .setBillingTime( fakeClock .now() - .plusMillis( - Duration.ofDays(1).toMillis() - + Tld.get("com").getTransferGracePeriodLength().getMillis())) + .plus(Duration.ofDays(1)) + .plus(Tld.get("com").getTransferGracePeriodLength())) .setCost(Money.of(USD, 11)) .setPeriodYears(1) .setDomainHistory(historyEntry) @@ -426,7 +422,7 @@ public class DomainTest { domain = domain .asBuilder() - .setRegistrationExpirationTime(toInstant(oldExpirationTime)) + .setRegistrationExpirationTime(oldExpirationTime) .setTransferData( domain .getTransferData() @@ -452,7 +448,7 @@ public class DomainTest { oneTimeBillKey)) .build(); Domain afterTransfer = domain.cloneProjectedAtTime(plusDays(fakeClock.now(), 1)); - DateTime newExpirationTime = oldExpirationTime.plusYears(1); + Instant newExpirationTime = plusYears(oldExpirationTime, 1); VKey serverApproveAutorenewEvent = domain.getTransferData().getServerApproveAutorenewEvent(); assertTransferred(afterTransfer, newExpirationTime, serverApproveAutorenewEvent); @@ -463,27 +459,25 @@ public class DomainTest { domain.getRepoId(), fakeClock .now() - .plusMillis( - Duration.ofDays(1).toMillis() - + Tld.get("com").getTransferGracePeriodLength().getMillis()), + .plus(Duration.ofDays(1)) + .plus(Tld.get("com").getTransferGracePeriodLength()), "TheRegistrar", transferBillingEvent.createVKey(), afterTransfer.getGracePeriods().iterator().next().getGracePeriodId())); // If we project after the grace period expires all should be the same except the grace period. Domain afterGracePeriod = domain.cloneProjectedAtTime( - toInstant( - fakeClock - .nowUtc() - .plusDays(2) - .plus(Tld.get("com").getTransferGracePeriodLength()))); + fakeClock + .now() + .plus(Duration.ofDays(2)) + .plus(Tld.get("com").getTransferGracePeriodLength())); assertTransferred(afterGracePeriod, newExpirationTime, serverApproveAutorenewEvent); assertThat(afterGracePeriod.getGracePeriods()).isEmpty(); } @Test void testExpiredTransfer() { - doExpiredTransferTest(fakeClock.nowUtc().plusMonths(1)); + doExpiredTransferTest(fakeClock.now().plus(Duration.ofDays(30))); } @Test @@ -491,7 +485,7 @@ public class DomainTest { // Since transfer swallows a preceding autorenew, this should be identical to the regular // transfer case (and specifically, the new expiration and grace periods will be the same as if // there was no autorenew). - doExpiredTransferTest(fakeClock.nowUtc().minusDays(1)); + doExpiredTransferTest(fakeClock.now().minus(Duration.ofDays(1))); } private void setupPendingTransferDomain( @@ -516,44 +510,44 @@ public class DomainTest { @Test void testEppLastUpdateTimeAndClientId_autoRenewBeforeTransferSuccess() { Instant now = fakeClock.now(); - Instant transferRequestDateTime = plusDays(now, 1); - Instant autorenewDateTime = plusDays(now, 3); - Instant transferSuccessDateTime = plusDays(now, 5); - setupPendingTransferDomain(autorenewDateTime, transferRequestDateTime, transferSuccessDateTime); + Instant transferRequestInstant = plusDays(now, 1); + Instant autorenewInstant = plusDays(now, 3); + Instant transferSuccessInstant = plusDays(now, 5); + setupPendingTransferDomain(autorenewInstant, transferRequestInstant, transferSuccessInstant); - Domain beforeAutoRenew = domain.cloneProjectedAtTime(minusDays(autorenewDateTime, 1)); - assertThat(beforeAutoRenew.getLastEppUpdateTime()).isEqualTo(transferRequestDateTime); + Domain beforeAutoRenew = domain.cloneProjectedAtTime(minusDays(autorenewInstant, 1)); + assertThat(beforeAutoRenew.getLastEppUpdateTime()).isEqualTo(transferRequestInstant); assertThat(beforeAutoRenew.getLastEppUpdateRegistrarId()).isEqualTo("TheRegistrar"); // If autorenew happens before transfer succeeds(before transfer grace period starts as well), // lastEppUpdateRegistrarId should still be the current sponsor client id - Domain afterAutoRenew = domain.cloneProjectedAtTime(plusDays(autorenewDateTime, 1)); - assertThat(afterAutoRenew.getLastEppUpdateTime()).isEqualTo(autorenewDateTime); + Domain afterAutoRenew = domain.cloneProjectedAtTime(plusDays(autorenewInstant, 1)); + assertThat(afterAutoRenew.getLastEppUpdateTime()).isEqualTo(autorenewInstant); assertThat(afterAutoRenew.getLastEppUpdateRegistrarId()).isEqualTo("NewRegistrar"); } @Test void testEppLastUpdateTimeAndClientId_autoRenewAfterTransferSuccess() { Instant now = fakeClock.now(); - Instant transferRequestDateTime = plusDays(now, 1); - Instant autorenewDateTime = plusDays(now, 3); - Instant transferSuccessDateTime = plusDays(now, 5); - setupPendingTransferDomain(autorenewDateTime, transferRequestDateTime, transferSuccessDateTime); + Instant transferRequestInstant = plusDays(now, 1); + Instant autorenewInstant = plusDays(now, 3); + Instant transferSuccessInstant = plusDays(now, 5); + setupPendingTransferDomain(autorenewInstant, transferRequestInstant, transferSuccessInstant); - Domain beforeAutoRenew = domain.cloneProjectedAtTime(minusDays(autorenewDateTime, 1)); - assertThat(beforeAutoRenew.getLastEppUpdateTime()).isEqualTo(transferRequestDateTime); + Domain beforeAutoRenew = domain.cloneProjectedAtTime(minusDays(autorenewInstant, 1)); + assertThat(beforeAutoRenew.getLastEppUpdateTime()).isEqualTo(transferRequestInstant); assertThat(beforeAutoRenew.getLastEppUpdateRegistrarId()).isEqualTo("TheRegistrar"); - Domain afterTransferSuccess = domain.cloneProjectedAtTime(plusDays(transferSuccessDateTime, 1)); - assertThat(afterTransferSuccess.getLastEppUpdateTime()).isEqualTo(transferSuccessDateTime); + Domain afterTransferSuccess = domain.cloneProjectedAtTime(plusDays(transferSuccessInstant, 1)); + assertThat(afterTransferSuccess.getLastEppUpdateTime()).isEqualTo(transferSuccessInstant); assertThat(afterTransferSuccess.getLastEppUpdateRegistrarId()).isEqualTo("TheRegistrar"); } - private void setupUnmodifiedDomain(DateTime oldExpirationTime) { + private void setupUnmodifiedDomain(Instant oldExpirationTime) { domain = domain .asBuilder() - .setRegistrationExpirationTime(toInstant(oldExpirationTime)) + .setRegistrationExpirationTime(oldExpirationTime) .setTransferData(DomainTransferData.EMPTY) .setGracePeriods(ImmutableSet.of()) .setLastEppUpdateTime((Instant) null) @@ -563,16 +557,16 @@ public class DomainTest { @Test void testEppLastUpdateTimeAndClientId_isSetCorrectlyWithNullPreviousValue() { - DateTime now = fakeClock.nowUtc(); - DateTime autorenewDateTime = now.plusDays(3); - setupUnmodifiedDomain(autorenewDateTime); + Instant now = fakeClock.now(); + Instant autorenewInstant = plusDays(now, 3); + setupUnmodifiedDomain(autorenewInstant); - Domain beforeAutoRenew = domain.cloneProjectedAtTime(toInstant(autorenewDateTime.minusDays(1))); + Domain beforeAutoRenew = domain.cloneProjectedAtTime(minusDays(autorenewInstant, 1)); assertThat(beforeAutoRenew.getLastEppUpdateTime()).isEqualTo(null); assertThat(beforeAutoRenew.getLastEppUpdateRegistrarId()).isEqualTo(null); - Domain afterAutoRenew = domain.cloneProjectedAtTime(toInstant(autorenewDateTime.plusDays(1))); - assertThat(afterAutoRenew.getLastEppUpdateTime()).isEqualTo(toInstant(autorenewDateTime)); + Domain afterAutoRenew = domain.cloneProjectedAtTime(plusDays(autorenewInstant, 1)); + assertThat(afterAutoRenew.getLastEppUpdateTime()).isEqualTo(autorenewInstant); assertThat(afterAutoRenew.getLastEppUpdateRegistrarId()).isEqualTo("NewRegistrar"); } @@ -705,7 +699,7 @@ public class DomainTest { GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), plusYears(oldExpirationTime, 2) - .plusMillis(Tld.get("com").getAutoRenewGracePeriodLength().getMillis()), + .plus(Tld.get("com").getAutoRenewGracePeriodLength()), renewedThreeTimes.getCurrentSponsorRegistrarId(), renewedThreeTimes.autorenewBillingEvent, renewedThreeTimes.getGracePeriods().iterator().next().getGracePeriodId())); @@ -738,106 +732,106 @@ public class DomainTest { @Test void testClone_doNotExtendExpirationOnDeletedDomain() { - DateTime now = DateTime.now(DateTimeZone.UTC); + Instant now = fakeClock.now(); domain = persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(now.minusDays(1))) - .setDeletionTime(toInstant(now.minusDays(10))) + .setRegistrationExpirationTime(minusDays(now, 1)) + .setDeletionTime(minusDays(now, 10)) .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE, StatusValue.INACTIVE)) .build()); - assertThat(domain.cloneProjectedAtTime(toInstant(now)).getRegistrationExpirationTime()) - .isEqualTo(toInstant(now.minusDays(1))); + assertThat(domain.cloneProjectedAtTime(now).getRegistrationExpirationTime()) + .isEqualTo(minusDays(now, 1)); } @Test void testClone_doNotExtendExpirationOnFutureDeletedDomain() { // if a domain is in pending deletion (StatusValue.PENDING_DELETE), don't extend expiration - DateTime now = DateTime.now(DateTimeZone.UTC); + Instant now = fakeClock.now(); domain = persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(now.plusDays(1))) - .setDeletionTime(toInstant(now.plusDays(20))) + .setRegistrationExpirationTime(plusDays(now, 1)) + .setDeletionTime(plusDays(now, 20)) .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE, StatusValue.INACTIVE)) .build()); - assertThat(domain.cloneProjectedAtTime(toInstant(now)).getRegistrationExpirationTime()) - .isEqualTo(toInstant(now.plusDays(1))); + assertThat(domain.cloneProjectedAtTime(now).getRegistrationExpirationTime()) + .isEqualTo(plusDays(now, 1)); } @Test void testClone_extendsExpirationForExpiredTransferredDomain() { // If the transfer implicitly succeeded, the expiration time should be extended - DateTime now = DateTime.now(DateTimeZone.UTC); - DateTime transferExpirationTime = now.minusDays(1); - DateTime previousExpiration = now.minusDays(2); + Instant now = fakeClock.now(); + Instant transferExpirationTime = minusDays(now, 1); + Instant previousExpiration = minusDays(now, 2); DomainTransferData transferData = new DomainTransferData.Builder() - .setPendingTransferExpirationTime(toInstant(transferExpirationTime)) + .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.PENDING) .setGainingRegistrarId("TheRegistrar") .build(); Period extensionPeriod = transferData.getTransferPeriod(); - DateTime newExpiration = previousExpiration.plusYears(extensionPeriod.getValue()); + Instant newExpiration = plusYears(previousExpiration, extensionPeriod.getValue()); domain = persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(previousExpiration)) + .setRegistrationExpirationTime(previousExpiration) .setTransferData(transferData) .build()); - assertThat(domain.cloneProjectedAtTime(toInstant(now)).getRegistrationExpirationTime()) - .isEqualTo(toInstant(newExpiration)); + assertThat(domain.cloneProjectedAtTime(now).getRegistrationExpirationTime()) + .isEqualTo(newExpiration); } @Test 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(DateTimeZone.UTC); - DateTime transferExpirationTime = now.minusDays(1); - DateTime previousExpiration = now.plusWeeks(2); + Instant now = fakeClock.now(); + Instant transferExpirationTime = minusDays(now, 1); + Instant previousExpiration = plusDays(now, 14); // 2 weeks DomainTransferData transferData = new DomainTransferData.Builder() - .setPendingTransferExpirationTime(toInstant(transferExpirationTime)) + .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.PENDING) .setGainingRegistrarId("TheRegistrar") .build(); Period extensionPeriod = transferData.getTransferPeriod(); - DateTime newExpiration = previousExpiration.plusYears(extensionPeriod.getValue()); + Instant newExpiration = plusYears(previousExpiration, extensionPeriod.getValue()); domain = persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(previousExpiration)) + .setRegistrationExpirationTime(previousExpiration) .setTransferData(transferData) .build()); - assertThat(domain.cloneProjectedAtTime(toInstant(now)).getRegistrationExpirationTime()) - .isEqualTo(toInstant(newExpiration)); + assertThat(domain.cloneProjectedAtTime(now).getRegistrationExpirationTime()) + .isEqualTo(newExpiration); } @Test 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(DateTimeZone.UTC); - DateTime transferExpirationTime = now.minusDays(1); - DateTime previousExpiration = now.plusWeeks(2); + Instant now = fakeClock.now(); + Instant transferExpirationTime = minusDays(now, 1); + Instant previousExpiration = plusDays(now, 14); // 2 weeks DomainTransferData transferData = new DomainTransferData.Builder() - .setPendingTransferExpirationTime(toInstant(transferExpirationTime)) + .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.PENDING) .setGainingRegistrarId("TheRegistrar") .build(); Period extensionPeriod = transferData.getTransferPeriod(); - DateTime newExpiration = previousExpiration.plusYears(extensionPeriod.getValue()); + Instant newExpiration = plusYears(previousExpiration, extensionPeriod.getValue()); AllocationToken allocationToken = persistResource( new AllocationToken.Builder() @@ -853,27 +847,27 @@ public class DomainTest { persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(previousExpiration)) + .setRegistrationExpirationTime(previousExpiration) .setTransferData(transferData) .setCurrentBulkToken(allocationToken.createVKey()) .build()); assertThat(domain.getCurrentBulkToken()).isPresent(); - Domain clonedDomain = domain.cloneProjectedAtTime(toInstant(now)); - assertThat(clonedDomain.getRegistrationExpirationTime()).isEqualTo(toInstant(newExpiration)); + Domain clonedDomain = domain.cloneProjectedAtTime(now); + assertThat(clonedDomain.getRegistrationExpirationTime()).isEqualTo(newExpiration); assertThat(clonedDomain.getCurrentBulkToken()).isEmpty(); } @Test void testClone_doesNotExtendExpirationForPendingTransfer() { // Pending transfers shouldn't affect the expiration time - DateTime now = DateTime.now(DateTimeZone.UTC); - DateTime transferExpirationTime = now.plusDays(1); - DateTime previousExpiration = now.plusWeeks(2); + Instant now = fakeClock.now(); + Instant transferExpirationTime = plusDays(now, 1); + Instant previousExpiration = plusDays(now, 14); // 2 weeks DomainTransferData transferData = new DomainTransferData.Builder() - .setPendingTransferExpirationTime(toInstant(transferExpirationTime)) + .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.PENDING) .setGainingRegistrarId("TheRegistrar") .build(); @@ -881,24 +875,24 @@ public class DomainTest { persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(previousExpiration)) + .setRegistrationExpirationTime(previousExpiration) .setTransferData(transferData) .build()); - assertThat(domain.cloneProjectedAtTime(toInstant(now)).getRegistrationExpirationTime()) - .isEqualTo(toInstant(previousExpiration)); + assertThat(domain.cloneProjectedAtTime(now).getRegistrationExpirationTime()) + .isEqualTo(previousExpiration); } @Test void testClone_doesNotRemoveBulkTokenForPendingTransfer() { // Pending transfers shouldn't affect the expiration time - DateTime now = DateTime.now(DateTimeZone.UTC); - DateTime transferExpirationTime = now.plusDays(1); - DateTime previousExpiration = now.plusWeeks(2); + Instant now = fakeClock.now(); + Instant transferExpirationTime = plusDays(now, 1); + Instant previousExpiration = plusDays(now, 14); // 2 weeks DomainTransferData transferData = new DomainTransferData.Builder() - .setPendingTransferExpirationTime(toInstant(transferExpirationTime)) + .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.PENDING) .setGainingRegistrarId("TheRegistrar") .build(); @@ -917,14 +911,13 @@ public class DomainTest { persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(previousExpiration)) + .setRegistrationExpirationTime(previousExpiration) .setTransferData(transferData) .setCurrentBulkToken(allocationToken.createVKey()) .build()); - Domain clonedDomain = domain.cloneProjectedAtTime(toInstant(now)); - assertThat(clonedDomain.getRegistrationExpirationTime()) - .isEqualTo(toInstant(previousExpiration)); + Domain clonedDomain = domain.cloneProjectedAtTime(now); + assertThat(clonedDomain.getRegistrationExpirationTime()).isEqualTo(previousExpiration); assertThat(clonedDomain.getCurrentBulkToken().get()).isEqualTo(allocationToken.createVKey()); } @@ -932,13 +925,13 @@ 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(DateTimeZone.UTC); - DateTime transferExpirationTime = now.minusDays(1); - DateTime previousExpiration = now.minusDays(2); + Instant now = fakeClock.now(); + Instant transferExpirationTime = minusDays(now, 1); + Instant previousExpiration = minusDays(now, 2); DomainTransferData transferData = new DomainTransferData.Builder() - .setPendingTransferExpirationTime(toInstant(transferExpirationTime)) + .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.PENDING) .setGainingRegistrarId("TheRegistrar") .setServerApproveAutorenewEvent(recurrenceBillKey) @@ -948,19 +941,19 @@ public class DomainTest { persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(previousExpiration)) + .setRegistrationExpirationTime(previousExpiration) .setGracePeriods( ImmutableSet.of( GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), - toInstant(now.plusDays(1)), + plusDays(now, 1), "NewRegistrar", recurrenceBillKey))) .setTransferData(transferData) .setAutorenewBillingEvent(recurrenceBillKey) .build()); - Domain clone = domain.cloneProjectedAtTime(toInstant(now)); + Domain clone = domain.cloneProjectedAtTime(now); assertThat(clone.getRegistrationExpirationTime()) .isEqualTo(plusYears(domain.getRegistrationExpirationTime(), 1)); // Transferring removes the AUTORENEW grace period and adds a TRANSFER grace period @@ -971,24 +964,24 @@ public class DomainTest { @Test void testHistoryIdRestoration() { // Verify that history ids for billing events are restored during load. - DateTime now = fakeClock.nowUtc(); + Instant now = fakeClock.now(); domain = persistResource( domain .asBuilder() - .setRegistrationExpirationTime(toInstant(now.plusYears(1))) + .setRegistrationExpirationTime(plusYears(now, 1)) .setGracePeriods( ImmutableSet.of( GracePeriod.createForRecurrence( GracePeriodStatus.AUTO_RENEW, domain.getRepoId(), - toInstant(now.plusDays(1)), + plusDays(now, 1), "NewRegistrar", recurrenceBillKey), GracePeriod.create( GracePeriodStatus.RENEW, domain.getRepoId(), - toInstant(now.plusDays(1)), + plusDays(now, 1), "NewRegistrar", oneTimeBillKey))) .build()); diff --git a/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java b/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java index 4c9accf9e..8d26630b1 100644 --- a/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java +++ b/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java @@ -428,7 +428,7 @@ public class AllocationTokenTest extends EntityTestCase { .build())); assertThat(thrown) .hasMessageThat() - .isEqualTo("tokenStatusTransitions map must start at START_OF_TIME."); + .isEqualTo("tokenStatusTransitions map must start at START_INSTANT."); } @Test diff --git a/core/src/test/java/google/registry/model/poll/PollMessageExternalKeyConverterTest.java b/core/src/test/java/google/registry/model/poll/PollMessageExternalKeyConverterTest.java index f7ec25014..bcef7ff6e 100644 --- a/core/src/test/java/google/registry/model/poll/PollMessageExternalKeyConverterTest.java +++ b/core/src/test/java/google/registry/model/poll/PollMessageExternalKeyConverterTest.java @@ -34,7 +34,7 @@ import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.DatabaseHelper; 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.RegisterExtension; @@ -47,7 +47,7 @@ public class PollMessageExternalKeyConverterTest { new JpaTestExtensions.Builder().buildIntegrationTestExtension(); private HistoryEntry historyEntry; - private final FakeClock clock = new FakeClock(DateTime.parse("2007-07-07T01:01:01Z")); + private final FakeClock clock = new FakeClock(Instant.parse("2007-07-07T01:01:01Z")); @BeforeEach void beforeEach() { @@ -74,7 +74,7 @@ public class PollMessageExternalKeyConverterTest { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId("TheRegistrar") - .setEventTime(clock.nowUtc()) + .setEventTime(clock.now()) .setMsg("Test poll message") .setHistoryEntry(historyEntry) .build()); @@ -91,7 +91,7 @@ public class PollMessageExternalKeyConverterTest { persistResource( new PollMessage.OneTime.Builder() .setRegistrarId("TheRegistrar") - .setEventTime(clock.nowUtc()) + .setEventTime(clock.now()) .setMsg("Test poll message") .setHistoryEntry(historyEntry) .build()); diff --git a/core/src/test/java/google/registry/model/poll/PollMessageTest.java b/core/src/test/java/google/registry/model/poll/PollMessageTest.java index 590c055c3..7bd81d339 100644 --- a/core/src/test/java/google/registry/model/poll/PollMessageTest.java +++ b/core/src/test/java/google/registry/model/poll/PollMessageTest.java @@ -19,6 +19,7 @@ import static google.registry.persistence.transaction.TransactionManagerFactory. import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.loadByKey; import static google.registry.testing.DatabaseHelper.persistResource; +import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusYears; import static java.nio.charset.StandardCharsets.UTF_8; @@ -80,7 +81,7 @@ public class PollMessageTest extends EntityTestCase { .setEventTime(fakeClock.now()) .setMsg("Test poll message") .setHistoryEntry(historyEntry) - .setAutorenewEndTime(plusYears(fakeClock.nowUtc(), 1)) + .setAutorenewEndTime(plusYears(fakeClock.now(), 1)) .setTargetId("foobar.foo") .build(); } @@ -118,7 +119,7 @@ public class PollMessageTest extends EntityTestCase { "test.example", true, Trid.create("ABC-123", "server-trid"), - fakeClock.nowUtc().minusDays(5)); + minusDays(fakeClock.now(), 5)); PollMessage.OneTime pollMessage = new PollMessage.OneTime.Builder() @@ -159,7 +160,7 @@ public class PollMessageTest extends EntityTestCase { .setEventTime(fakeClock.now()) .setMsg("Test poll message") .setHistoryEntry(historyEntry) - .setAutorenewEndTime(plusYears(fakeClock.nowUtc(), 1)) + .setAutorenewEndTime(plusYears(fakeClock.now(), 1)) .setTargetId("foobar.foo") .build()); assertThat(tm().transact(() -> tm().loadByEntity(pollMessage))).isEqualTo(pollMessage); @@ -174,7 +175,7 @@ public class PollMessageTest extends EntityTestCase { .setEventTime(fakeClock.now()) .setMsg("Test poll message") .setHistoryEntry(historyEntry) - .setAutorenewEndTime(plusYears(fakeClock.nowUtc(), 1)) + .setAutorenewEndTime(plusYears(fakeClock.now(), 1)) .setTargetId("foobar.foo") .build()); PollMessage persisted = tm().transact(() -> tm().loadByEntity(pollMessage)); 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 70d70c895..36d0ca82f 100644 --- a/core/src/test/java/google/registry/model/rde/RdeRevisionTest.java +++ b/core/src/test/java/google/registry/model/rde/RdeRevisionTest.java @@ -19,7 +19,7 @@ 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 google.registry.util.DateTimeUtils.toLocalDate; import static java.time.temporal.ChronoUnit.DAYS; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -120,7 +120,7 @@ public class RdeRevisionTest extends EntityTestCase { } public static void save(String tld, Instant date, RdeMode mode, int revision) { - RdeRevision object = RdeRevision.create(tld, toJodaLocalDate(date), mode, revision); + RdeRevision object = RdeRevision.create(tld, toLocalDate(date), mode, revision); tm().transact(() -> tm().put(object)); } } diff --git a/core/src/test/java/google/registry/model/reporting/HistoryEntryDaoTest.java b/core/src/test/java/google/registry/model/reporting/HistoryEntryDaoTest.java index 5d392d5b0..d197dba01 100644 --- a/core/src/test/java/google/registry/model/reporting/HistoryEntryDaoTest.java +++ b/core/src/test/java/google/registry/model/reporting/HistoryEntryDaoTest.java @@ -20,8 +20,8 @@ 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.testing.DatabaseHelper.persistResource; -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 java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableSet; @@ -74,21 +74,20 @@ class HistoryEntryDaoTest extends EntityTestCase { @Test void testSimpleLoadAll() { - assertThat(HistoryEntryDao.loadAllHistoryObjects(START_OF_TIME, END_OF_TIME)) + assertThat(HistoryEntryDao.loadAllHistoryObjects(START_INSTANT, END_INSTANT)) .comparingElementsUsing(immutableObjectCorrespondence("nsHosts", "resource")) .containsExactly(domainHistory); } @Test void testSkips_tooEarly() { - assertThat(HistoryEntryDao.loadAllHistoryObjects(fakeClock.nowUtc().plusMillis(1), END_OF_TIME)) + assertThat(HistoryEntryDao.loadAllHistoryObjects(fakeClock.now().plusMillis(1), END_INSTANT)) .isEmpty(); } @Test void testSkips_tooLate() { - assertThat( - HistoryEntryDao.loadAllHistoryObjects(START_OF_TIME, fakeClock.nowUtc().minusMillis(1))) + assertThat(HistoryEntryDao.loadAllHistoryObjects(START_INSTANT, fakeClock.now().minusMillis(1))) .isEmpty(); } @@ -105,7 +104,7 @@ class HistoryEntryDaoTest extends EntityTestCase { void testLoadByResource_skips_tooEarly() { assertThat( HistoryEntryDao.loadHistoryObjectsForResource( - domain.createVKey(), fakeClock.nowUtc().plusMillis(1), END_OF_TIME)) + domain.createVKey(), fakeClock.now().plusMillis(1), END_INSTANT)) .isEmpty(); } @@ -113,7 +112,7 @@ class HistoryEntryDaoTest extends EntityTestCase { void testLoadByResource_skips_tooLate() { assertThat( HistoryEntryDao.loadHistoryObjectsForResource( - domain.createVKey(), START_OF_TIME, fakeClock.nowUtc().minusMillis(1))) + domain.createVKey(), START_INSTANT, fakeClock.now().minusMillis(1))) .isEmpty(); } diff --git a/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchDaoTest.java b/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchDaoTest.java index 4eef4d167..ed92bf2c2 100644 --- a/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchDaoTest.java +++ b/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchDaoTest.java @@ -26,15 +26,15 @@ import google.registry.model.EntityTestCase; import google.registry.model.domain.Domain; import google.registry.model.reporting.Spec11ThreatMatch.ThreatType; import google.registry.testing.DatabaseHelper; -import org.joda.time.LocalDate; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Unit tests for {@link Spec11ThreatMatchDao}. */ class Spec11ThreatMatchDaoTest extends EntityTestCase { - private static final LocalDate TODAY = new LocalDate(2020, 8, 4); - private static final LocalDate YESTERDAY = new LocalDate(2020, 8, 3); + private static final LocalDate TODAY = LocalDate.of(2020, 8, 4); + private static final LocalDate YESTERDAY = LocalDate.of(2020, 8, 3); private Domain todayComDomain; private Domain todayOrgDomain; diff --git a/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchTest.java b/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchTest.java index c5dac7159..0891ea15a 100644 --- a/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchTest.java +++ b/core/src/test/java/google/registry/model/reporting/Spec11ThreatMatchTest.java @@ -30,8 +30,7 @@ import google.registry.model.EntityTestCase; import google.registry.model.domain.Domain; import google.registry.model.host.Host; import google.registry.persistence.VKey; -import org.joda.time.LocalDate; -import org.joda.time.format.ISODateTimeFormat; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -40,7 +39,7 @@ import org.junit.jupiter.api.Test; public final class Spec11ThreatMatchTest extends EntityTestCase { private static final String REGISTRAR_ID = "registrar"; - private static final LocalDate DATE = LocalDate.parse("2020-06-10", ISODateTimeFormat.date()); + private static final LocalDate DATE = LocalDate.parse("2020-06-10"); private Spec11ThreatMatch threat; private Domain domain; diff --git a/core/src/test/java/google/registry/model/tld/RegistryLockDaoTest.java b/core/src/test/java/google/registry/model/tld/RegistryLockDaoTest.java index fd227f195..80082ea46 100644 --- a/core/src/test/java/google/registry/model/tld/RegistryLockDaoTest.java +++ b/core/src/test/java/google/registry/model/tld/RegistryLockDaoTest.java @@ -28,8 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import google.registry.model.EntityTestCase; import google.registry.model.domain.RegistryLock; +import java.time.Duration; import java.util.Optional; -import org.joda.time.Duration; import org.junit.jupiter.api.Test; /** Unit tests for {@link RegistryLockDao}. */ @@ -79,13 +79,13 @@ public final class RegistryLockDaoTest extends EntityTestCase { .setLockCompletionTime(fakeClock.now()) .setUnlockRequestTime(fakeClock.now()) .setUnlockCompletionTime(fakeClock.now()) - .setRelockDuration(Duration.standardHours(6)) + .setRelockDuration(Duration.ofHours(6)) .build()); RegistryLock fromDatabase = getRegistryLockByVerificationCode(lock.getVerificationCode()).get(); assertThat(fromDatabase.getUnlockRequestTime()).hasValue(fakeClock.now()); assertThat(fromDatabase.getUnlockCompletionTime()).hasValue(fakeClock.now()); assertThat(fromDatabase.isLocked()).isFalse(); - assertThat(fromDatabase.getRelockDuration()).hasValue(Duration.standardHours(6)); + assertThat(fromDatabase.getRelockDuration()).hasValue(Duration.ofHours(6)); } @Test diff --git a/core/src/test/java/google/registry/model/tld/TldTest.java b/core/src/test/java/google/registry/model/tld/TldTest.java index f863eeff4..ffb94d84b 100644 --- a/core/src/test/java/google/registry/model/tld/TldTest.java +++ b/core/src/test/java/google/registry/model/tld/TldTest.java @@ -33,7 +33,6 @@ import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.TestDataHelper.loadFile; import static google.registry.util.DateTimeUtils.END_INSTANT; import static google.registry.util.DateTimeUtils.START_INSTANT; -import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusDays; import static google.registry.util.DateTimeUtils.plusMonths; @@ -59,10 +58,10 @@ import google.registry.persistence.VKey; import google.registry.tldconfig.idn.IdnTableEnum; import google.registry.util.SerializeUtils; import java.math.BigDecimal; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import org.joda.money.Money; -import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -106,7 +105,7 @@ public final class TldTest extends EntityTestCase { @Test void testTldToYaml() throws Exception { - fakeClock.setTo(START_OF_TIME); + fakeClock.setTo(START_INSTANT); AllocationToken defaultToken = persistResource( new AllocationToken.Builder() @@ -117,7 +116,7 @@ public final class TldTest extends EntityTestCase { Tld existingTld = createTld("tld") .asBuilder() - .setDnsAPlusAaaaTtl(Duration.standardHours(1)) + .setDnsAPlusAaaaTtl(Duration.ofHours(1)) .setDnsWriters(ImmutableSet.of("baz", "bang")) .setEapFeeSchedule( ImmutableSortedMap.of( @@ -139,7 +138,7 @@ public final class TldTest extends EntityTestCase { @Test void testYamlToTld() throws Exception { - fakeClock.setTo(START_OF_TIME); + fakeClock.setTo(START_INSTANT); AllocationToken defaultToken = persistResource( new AllocationToken.Builder() @@ -150,7 +149,7 @@ public final class TldTest extends EntityTestCase { Tld existingTld = createTld("tld") .asBuilder() - .setDnsAPlusAaaaTtl(Duration.standardHours(1)) + .setDnsAPlusAaaaTtl(Duration.ofHours(1)) .setDnsWriters(ImmutableSet.of("baz", "bang")) // set create billing cost back to the default (database helper sets it to $13) .setEapFeeSchedule( @@ -289,7 +288,7 @@ public final class TldTest extends EntityTestCase { .setName("tld-reserved15") .setReservedListMapFromLines( ImmutableList.of("potato,FULLY_BLOCKED", "phone,FULLY_BLOCKED")) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build()); ReservedList rl16 = persistReservedList( @@ -297,7 +296,7 @@ public final class TldTest extends EntityTestCase { .setName("tld-reserved16") .setReservedListMapFromLines( ImmutableList.of("port,FULLY_BLOCKED", "manteau,FULLY_BLOCKED")) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build()); Tld registry1 = newTld("propter", "PROPTER").asBuilder().setReservedLists(ImmutableSet.of(rl15)).build(); @@ -344,7 +343,7 @@ public final class TldTest extends EntityTestCase { .setName("tld-reserved5") .setReservedListMapFromLines( ImmutableList.of("potato,FULLY_BLOCKED", "phone,FULLY_BLOCKED")) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build()); ReservedList rl6 = persistReservedList( @@ -352,7 +351,7 @@ public final class TldTest extends EntityTestCase { .setName("tld-reserved6") .setReservedListMapFromLines( ImmutableList.of("port,FULLY_BLOCKED", "manteau,FULLY_BLOCKED")) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build()); Tld r = Tld.get("tld").asBuilder().setReservedLists(ImmutableSet.of(rl5, rl6)).build(); assertThat(r.getReservedListNames()).containsExactly("tld-reserved5", "tld-reserved6"); @@ -367,14 +366,14 @@ public final class TldTest extends EntityTestCase { .setName("tld-reserved15") .setReservedListMapFromLines( ImmutableList.of("potato,FULLY_BLOCKED", "phone,FULLY_BLOCKED")) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build()); persistReservedList( new ReservedList.Builder() .setName("tld-reserved16") .setReservedListMapFromLines( ImmutableList.of("port,FULLY_BLOCKED", "manteau,FULLY_BLOCKED")) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build()); Tld r = Tld.get("tld") diff --git a/core/src/test/java/google/registry/model/tld/TldsTest.java b/core/src/test/java/google/registry/model/tld/TldsTest.java index 115b43e78..f939e8aa0 100644 --- a/core/src/test/java/google/registry/model/tld/TldsTest.java +++ b/core/src/test/java/google/registry/model/tld/TldsTest.java @@ -98,7 +98,7 @@ class TldsTest { @Test void testHasActiveBsaEnrollment_noneEnrolled() { initTestTlds(); - assertThat(hasActiveBsaEnrollment(fakeClock.nowUtc())).isFalse(); + assertThat(hasActiveBsaEnrollment(fakeClock.now())).isFalse(); } @Test @@ -107,9 +107,9 @@ class TldsTest { persistResource( Tld.get("foo") .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc().plusSeconds(1))) + .setBsaEnrollStartTime(Optional.of(fakeClock.now().plusSeconds(1))) .build()); - assertThat(hasActiveBsaEnrollment(fakeClock.nowUtc())).isFalse(); + assertThat(hasActiveBsaEnrollment(fakeClock.now())).isFalse(); } @Test @@ -119,9 +119,9 @@ class TldsTest { Tld.get("foo") .asBuilder() .setTldType(TldType.TEST) - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc().minusMillis(1))) + .setBsaEnrollStartTime(Optional.of(fakeClock.now().minusMillis(1))) .build()); - assertThat(hasActiveBsaEnrollment(fakeClock.nowUtc())).isFalse(); + assertThat(hasActiveBsaEnrollment(fakeClock.now())).isFalse(); } @Test @@ -130,8 +130,8 @@ class TldsTest { persistResource( Tld.get("foo") .asBuilder() - .setBsaEnrollStartTime(Optional.of(fakeClock.nowUtc().minusMillis(1))) + .setBsaEnrollStartTime(Optional.of(fakeClock.now().minusMillis(1))) .build()); - assertThat(hasActiveBsaEnrollment(fakeClock.nowUtc())).isTrue(); + assertThat(hasActiveBsaEnrollment(fakeClock.now())).isTrue(); } } diff --git a/core/src/test/java/google/registry/model/tld/label/PremiumListDaoTest.java b/core/src/test/java/google/registry/model/tld/label/PremiumListDaoTest.java index d7b4225b3..fb8fccad8 100644 --- a/core/src/test/java/google/registry/model/tld/label/PremiumListDaoTest.java +++ b/core/src/test/java/google/registry/model/tld/label/PremiumListDaoTest.java @@ -78,7 +78,7 @@ public class PremiumListDaoTest { .setName("testname") .setCurrency(USD) .setLabelsToPrices(TEST_PRICES) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build(); } @@ -91,7 +91,7 @@ public class PremiumListDaoTest { assertThat(persistedListOpt).isPresent(); PremiumList persistedList = persistedListOpt.get(); assertThat(persistedList.getLabelsToPrices()).containsExactlyEntriesIn(TEST_PRICES); - assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); }); } @@ -112,7 +112,7 @@ public class PremiumListDaoTest { assertThat(persistedListOpt).isPresent(); PremiumList persistedList = persistedListOpt.get(); assertThat(persistedList.getLabelsToPrices()).containsExactlyEntriesIn(TEST_PRICES); - assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); }); } @@ -136,7 +136,7 @@ public class PremiumListDaoTest { BigDecimal.valueOf(0.01), "silver", BigDecimal.valueOf(30.03))) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build())); tm().transact( () -> { @@ -152,7 +152,7 @@ public class PremiumListDaoTest { BigDecimal.valueOf(0.01), "silver", BigDecimal.valueOf(30.03))); - assertThat(savedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(savedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); assertThat(savedList.getRevisionId()).isGreaterThan(firstRevisionId); }); } @@ -178,7 +178,7 @@ public class PremiumListDaoTest { .setName("list1") .setCurrency(USD) .setLabelsToPrices(ImmutableMap.of("wrong", BigDecimal.valueOf(1000.50))) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build())); tm().transact( () -> @@ -187,7 +187,7 @@ public class PremiumListDaoTest { .setName("list1") .setCurrency(USD) .setLabelsToPrices(TEST_PRICES) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build())); tm().transact( () -> { @@ -209,7 +209,7 @@ public class PremiumListDaoTest { .setName("list1") .setCurrency(JPY) .setLabelsToPrices(TEST_PRICES) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build())); tm().transact( () -> { @@ -235,7 +235,7 @@ public class PremiumListDaoTest { .setName("premlist") .setCurrency(USD) .setLabelsToPrices(TEST_PRICES) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build())); persistResource(newTld("foobar", "FOOBAR").asBuilder().setPremiumList(premiumList).build()); assertThat(PremiumListDao.getPremiumPrice("premlist", "silver")).hasValue(Money.of(USD, 10.23)); @@ -260,7 +260,7 @@ public class PremiumListDaoTest { BigDecimal.valueOf(1000.0), "palladium", BigDecimal.valueOf(15000))) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build())); persistResource(newTld("foobar", "FOOBAR").asBuilder().setPremiumList(premiumList).build()); assertThat(PremiumListDao.getPremiumPrice("premlist", "silver")).hasValue(moneyOf(JPY, 10)); @@ -302,7 +302,7 @@ public class PremiumListDaoTest { .setName("testname") .setCurrency(USD) .setLabelsToPrices(prices) - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .build(); tm().transact(() -> PremiumListDao.save(list)); long duration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS); diff --git a/core/src/test/java/google/registry/model/tld/label/PremiumListUtilsTest.java b/core/src/test/java/google/registry/model/tld/label/PremiumListUtilsTest.java index c1d7b525d..2e6594488 100644 --- a/core/src/test/java/google/registry/model/tld/label/PremiumListUtilsTest.java +++ b/core/src/test/java/google/registry/model/tld/label/PremiumListUtilsTest.java @@ -21,13 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableList; import java.math.BigDecimal; -import org.joda.time.DateTime; +import java.time.Instant; import org.junit.jupiter.api.Test; /** Unit tests for {@link PremiumListUtils}. */ class PremiumListUtilsTest { - private static final DateTime SAMPLE_TIME = DateTime.parse("2026-01-26T21:06:12.284Z"); + private static final Instant SAMPLE_TIME = Instant.parse("2026-01-26T21:06:12.284Z"); @Test void parseInputToPremiumList_works() { diff --git a/core/src/test/java/google/registry/model/tld/label/ReservedListDaoTest.java b/core/src/test/java/google/registry/model/tld/label/ReservedListDaoTest.java index bbe6b65c3..6c7bb582a 100644 --- a/core/src/test/java/google/registry/model/tld/label/ReservedListDaoTest.java +++ b/core/src/test/java/google/registry/model/tld/label/ReservedListDaoTest.java @@ -53,7 +53,7 @@ public class ReservedListDaoTest { testReservedList = new ReservedList.Builder() .setName("testlist") - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .setReservedListMap(testReservations) .build(); } @@ -69,7 +69,7 @@ public class ReservedListDaoTest { .getSingleResult(); assertThat(persistedList.getReservedListEntries()) .containsExactlyEntriesIn(testReservations); - assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); }); } @@ -92,7 +92,7 @@ public class ReservedListDaoTest { .getSingleResult(); assertThat(persistedList.getReservedListEntries()) .containsExactlyEntriesIn(testReservations); - assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); }); } @@ -124,7 +124,7 @@ public class ReservedListDaoTest { ReservedListDao.save(testReservedList); ReservedList persistedList = ReservedListDao.getLatestRevision("testlist").get(); assertThat(persistedList.getRevisionId()).isAtLeast(1L); - assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); assertThat(persistedList.getName()).isEqualTo("testlist"); assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(testReservations); } @@ -134,7 +134,7 @@ public class ReservedListDaoTest { ReservedListDao.save( new ReservedList.Builder() .setName("testlist") - .setCreationTimestamp(fakeClock.nowUtc()) + .setCreationTimestamp(fakeClock.now()) .setReservedListMap( ImmutableMap.of( "old", @@ -144,7 +144,7 @@ public class ReservedListDaoTest { ReservedListDao.save(testReservedList); ReservedList persistedList = ReservedListDao.getLatestRevision("testlist").get(); assertThat(persistedList.getRevisionId()).isAtLeast(1L); - assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc()); + assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.now()); assertThat(persistedList.getName()).isEqualTo("testlist"); assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(testReservations); } diff --git a/core/src/test/java/google/registry/monitoring/whitebox/CheckApiMetricTest.java b/core/src/test/java/google/registry/monitoring/whitebox/CheckApiMetricTest.java index 19d12028a..39b1f8eaf 100644 --- a/core/src/test/java/google/registry/monitoring/whitebox/CheckApiMetricTest.java +++ b/core/src/test/java/google/registry/monitoring/whitebox/CheckApiMetricTest.java @@ -18,13 +18,13 @@ import static com.google.common.truth.Truth.assertThat; import google.registry.monitoring.whitebox.CheckApiMetric.Status; 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; /** Unit tests for {@link CheckApiMetric}. */ class CheckApiMetricTest { - private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z"); + private static final Instant START_TIME = Instant.parse("2000-01-01T00:00:00.0Z"); private final FakeClock clock = new FakeClock(START_TIME); private CheckApiMetric.Builder metricBuilder; @@ -40,6 +40,6 @@ class CheckApiMetricTest { CheckApiMetric metric = metricBuilder.status(Status.SUCCESS).build(); assertThat(metric.startTimestamp()).isEqualTo(START_TIME); - assertThat(metric.endTimestamp()).isEqualTo(clock.nowUtc()); + assertThat(metric.endTimestamp()).isEqualTo(clock.now()); } } diff --git a/core/src/test/java/google/registry/persistence/converter/AllocationTokenStatusTransitionUserTypeTest.java b/core/src/test/java/google/registry/persistence/converter/AllocationTokenStatusTransitionUserTypeTest.java index ceaa79604..bccacfe41 100644 --- a/core/src/test/java/google/registry/persistence/converter/AllocationTokenStatusTransitionUserTypeTest.java +++ b/core/src/test/java/google/registry/persistence/converter/AllocationTokenStatusTransitionUserTypeTest.java @@ -20,7 +20,7 @@ import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT import static google.registry.model.domain.token.AllocationToken.TokenStatus.VALID; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; 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 com.google.common.collect.ImmutableSortedMap; import google.registry.model.ImmutableObject; @@ -31,8 +31,8 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaUnitTestExte import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import java.time.Instant; import org.hibernate.annotations.Type; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -45,13 +45,13 @@ public class AllocationTokenStatusTransitionUserTypeTest { .withEntityClass(AllocationTokenStatusTransitionConverterTestEntity.class) .buildUnitTestExtension(); - private static final ImmutableSortedMap values = + private static final ImmutableSortedMap values = ImmutableSortedMap.of( - START_OF_TIME, + START_INSTANT, NOT_STARTED, - DateTime.parse("2001-01-01T00:00:00.0Z"), + Instant.parse("2001-01-01T00:00:00.0Z"), VALID, - DateTime.parse("2002-01-01T00:00:00.0Z"), + Instant.parse("2002-01-01T00:00:00.0Z"), ENDED); @Test diff --git a/core/src/test/java/google/registry/persistence/converter/BillingCostTransitionUserTypeTest.java b/core/src/test/java/google/registry/persistence/converter/BillingCostTransitionUserTypeTest.java index ed9b14011..ebc2a9de7 100644 --- a/core/src/test/java/google/registry/persistence/converter/BillingCostTransitionUserTypeTest.java +++ b/core/src/test/java/google/registry/persistence/converter/BillingCostTransitionUserTypeTest.java @@ -17,7 +17,7 @@ package google.registry.persistence.converter; import static com.google.common.truth.Truth.assertThat; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; 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.joda.money.CurrencyUnit.USD; import com.google.common.collect.ImmutableSortedMap; @@ -28,9 +28,9 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaUnitTestExte import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import java.time.Instant; import org.hibernate.annotations.Type; import org.joda.money.Money; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -41,11 +41,11 @@ public class BillingCostTransitionUserTypeTest { public final JpaUnitTestExtension jpa = new JpaTestExtensions.Builder().withEntityClass(TestEntity.class).buildUnitTestExtension(); - private static final ImmutableSortedMap values = + private static final ImmutableSortedMap values = ImmutableSortedMap.of( - START_OF_TIME, + START_INSTANT, Money.of(USD, 8), - DateTime.parse("2001-01-01T00:00:00.0Z"), + Instant.parse("2001-01-01T00:00:00.0Z"), Money.of(USD, 0)); @Test diff --git a/core/src/test/java/google/registry/persistence/converter/DurationUserTypeTest.java b/core/src/test/java/google/registry/persistence/converter/DurationUserTypeTest.java index c5481e840..510aab199 100644 --- a/core/src/test/java/google/registry/persistence/converter/DurationUserTypeTest.java +++ b/core/src/test/java/google/registry/persistence/converter/DurationUserTypeTest.java @@ -24,8 +24,8 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaUnitTestExte import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import java.time.Duration; import org.hibernate.annotations.Type; -import org.joda.time.Duration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -60,33 +60,25 @@ public class DurationUserTypeTest { @Test void testRoundTrip() { Duration testDuration = - Duration.standardDays(6) - .plus(Duration.standardHours(10)) - .plus(Duration.standardMinutes(30)) - .plus(Duration.standardSeconds(15)) - .plus(Duration.millis(7)); + Duration.ofDays(6).plusHours(10).plusMinutes(30).plusSeconds(15).plusMillis(7); assertPersistedEntityHasSameDuration(testDuration); } @Test void testRoundTripLargeNumberOfDays() { - Duration testDuration = - Duration.standardDays(10001).plus(Duration.standardHours(100)).plus(Duration.millis(790)); + Duration testDuration = Duration.ofDays(10001).plusHours(100).plusMillis(790); assertPersistedEntityHasSameDuration(testDuration); } @Test void testRoundTripLessThanOneDay() { - Duration testDuration = - Duration.standardHours(15) - .plus(Duration.standardMinutes(40)) - .plus(Duration.standardSeconds(50)); + Duration testDuration = Duration.ofHours(15).plusMinutes(40).plusSeconds(50); assertPersistedEntityHasSameDuration(testDuration); } @Test void testRoundTripExactOneDay() { - Duration testDuration = Duration.standardDays(1); + Duration testDuration = Duration.ofDays(1); assertPersistedEntityHasSameDuration(testDuration); } @@ -95,7 +87,7 @@ public class DurationUserTypeTest { persistResource(entity); DurationTestEntity persisted = tm().transact(() -> tm().getEntityManager().find(DurationTestEntity.class, "id")); - assertThat(persisted.duration.getMillis()).isEqualTo(duration.getMillis()); + assertThat(persisted.duration).isEqualTo(duration); } @Entity(name = "TestEntity") // Override entity name to avoid the nested class reference. diff --git a/core/src/test/java/google/registry/persistence/converter/TimedTransitionBaseUserTypeTest.java b/core/src/test/java/google/registry/persistence/converter/TimedTransitionBaseUserTypeTest.java index 71b1557a7..a9b0dc9bf 100644 --- a/core/src/test/java/google/registry/persistence/converter/TimedTransitionBaseUserTypeTest.java +++ b/core/src/test/java/google/registry/persistence/converter/TimedTransitionBaseUserTypeTest.java @@ -17,7 +17,8 @@ package google.registry.persistence.converter; import static com.google.common.truth.Truth.assertThat; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; 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 google.registry.util.DateTimeUtils.formatInstant; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableSortedMap; @@ -29,8 +30,8 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.NoResultException; +import java.time.Instant; import org.hibernate.annotations.Type; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -41,12 +42,12 @@ class TimedTransitionBaseUserTypeTest { public final JpaUnitTestExtension jpa = new JpaTestExtensions.Builder().withEntityClass(TestEntity.class).buildUnitTestExtension(); - private static final DateTime DATE_1 = DateTime.parse("2001-01-01T00:00:00.000Z"); - private static final DateTime DATE_2 = DateTime.parse("2002-01-01T00:00:00.000Z"); + private static final Instant DATE_1 = Instant.parse("2001-01-01T00:00:00.000Z"); + private static final Instant DATE_2 = Instant.parse("2002-01-01T00:00:00.000Z"); - private static final ImmutableSortedMap VALUES = + private static final ImmutableSortedMap VALUES = ImmutableSortedMap.of( - START_OF_TIME, "val1", + START_INSTANT, "val1", DATE_1, "val2", DATE_2, "val3"); @@ -71,7 +72,7 @@ class TimedTransitionBaseUserTypeTest { tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id")); assertThat(persisted.property.toValueMap()) .containsExactlyEntriesIn(TIMED_TRANSITION_PROPERTY.toValueMap()); - ImmutableSortedMap newValues = ImmutableSortedMap.of(START_OF_TIME, "val4"); + ImmutableSortedMap newValues = ImmutableSortedMap.of(START_INSTANT, "val4"); persisted.property = TimedTransitionProperty.fromValueMap(newValues); tm().transact(() -> tm().getEntityManager().merge(persisted)); TestEntity updated = tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id")); @@ -96,11 +97,11 @@ class TimedTransitionBaseUserTypeTest { assertThat( getSingleResultFromNativeQuery( "SELECT property -> 'val1' FROM \"TestEntity\" WHERE name = 'id'")) - .isEqualTo(START_OF_TIME.toString()); + .isEqualTo(formatInstant(START_INSTANT)); assertThat( getSingleResultFromNativeQuery( "SELECT property -> 'val2' FROM \"TestEntity\" WHERE name = 'id'")) - .isEqualTo(DATE_1.toString()); + .isEqualTo(formatInstant(DATE_1)); executeNativeQuery( "UPDATE \"TestEntity\" SET property = 'val3=>2002-01-01T00:00:00.000Z' WHERE name = 'id'"); @@ -108,7 +109,7 @@ class TimedTransitionBaseUserTypeTest { assertThat( getSingleResultFromNativeQuery( "SELECT property -> 'val3' FROM \"TestEntity\" WHERE name = 'id'")) - .isEqualTo(DATE_2.toString()); + .isEqualTo(formatInstant(DATE_2)); executeNativeQuery("DELETE FROM \"TestEntity\" WHERE name = 'id'"); diff --git a/core/src/test/java/google/registry/persistence/converter/TldStateTransitionUserTypeTest.java b/core/src/test/java/google/registry/persistence/converter/TldStateTransitionUserTypeTest.java index 7a93ec988..099a62922 100644 --- a/core/src/test/java/google/registry/persistence/converter/TldStateTransitionUserTypeTest.java +++ b/core/src/test/java/google/registry/persistence/converter/TldStateTransitionUserTypeTest.java @@ -17,7 +17,7 @@ package google.registry.persistence.converter; import static com.google.common.truth.Truth.assertThat; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; 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 com.google.common.collect.ImmutableSortedMap; import google.registry.model.ImmutableObject; @@ -28,8 +28,8 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaUnitTestExte import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import java.time.Instant; import org.hibernate.annotations.Type; -import org.joda.time.DateTime; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -40,15 +40,15 @@ class TldStateTransitionUserTypeTest { public final JpaUnitTestExtension jpa = new JpaTestExtensions.Builder().withEntityClass(TestEntity.class).buildUnitTestExtension(); - private static final ImmutableSortedMap values = + private static final ImmutableSortedMap values = ImmutableSortedMap.of( - START_OF_TIME, + START_INSTANT, TldState.PREDELEGATION, - DateTime.parse("2001-01-01T00:00:00.0Z"), + Instant.parse("2001-01-01T00:00:00.0Z"), TldState.QUIET_PERIOD, - DateTime.parse("2002-01-01T00:00:00.0Z"), + Instant.parse("2002-01-01T00:00:00.0Z"), TldState.PDT, - DateTime.parse("2003-01-01T00:00:00.0Z"), + Instant.parse("2003-01-01T00:00:00.0Z"), TldState.GENERAL_AVAILABILITY); @Test diff --git a/core/src/test/java/google/registry/persistence/transaction/DummyJpaTransactionManagerTest.java b/core/src/test/java/google/registry/persistence/transaction/DummyJpaTransactionManagerTest.java index d2f15f570..28cf7ba65 100644 --- a/core/src/test/java/google/registry/persistence/transaction/DummyJpaTransactionManagerTest.java +++ b/core/src/test/java/google/registry/persistence/transaction/DummyJpaTransactionManagerTest.java @@ -25,6 +25,6 @@ class DummyJpaTransactionManagerTest { @Test void throwsExceptionWhenAnyMethodIsInvoked() { assertThrows(UnsupportedOperationException.class, () -> tm().transact(() -> null)); - assertThrows(UnsupportedOperationException.class, () -> tm().getTransactionTime()); + assertThrows(UnsupportedOperationException.class, () -> tm().getTxTime()); } } diff --git a/core/src/test/java/google/registry/persistence/transaction/TransactionManagerTest.java b/core/src/test/java/google/registry/persistence/transaction/TransactionManagerTest.java index adafd5e81..0ca5d7b8e 100644 --- a/core/src/test/java/google/registry/persistence/transaction/TransactionManagerTest.java +++ b/core/src/test/java/google/registry/persistence/transaction/TransactionManagerTest.java @@ -78,11 +78,11 @@ public class TransactionManagerTest { } @Test - void getTransactionTime_throwsExceptionWhenNotInTransaction() { - assertThrows(IllegalStateException.class, () -> tm().getTransactionTime()); + void getTxTime_throwsExceptionWhenNotInTransaction() { + assertThrows(IllegalStateException.class, () -> tm().getTxTime()); fakeClock.disableAutoIncrement(); - tm().transact(() -> assertThat(tm().getTransactionTime()).isEqualTo(fakeClock.nowUtc())); - assertThrows(IllegalStateException.class, () -> tm().getTransactionTime()); + tm().transact(() -> assertThat(tm().getTxTime()).isEqualTo(fakeClock.now())); + assertThrows(IllegalStateException.class, () -> tm().getTxTime()); } @Test diff --git a/core/src/test/java/google/registry/rdap/RdapDomainActionTest.java b/core/src/test/java/google/registry/rdap/RdapDomainActionTest.java index 27503619d..0ae1c4fe3 100644 --- a/core/src/test/java/google/registry/rdap/RdapDomainActionTest.java +++ b/core/src/test/java/google/registry/rdap/RdapDomainActionTest.java @@ -27,10 +27,12 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHistoryEntr import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar; import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarPocs; import static google.registry.testing.GsonSubject.assertAboutJson; -import static google.registry.util.DateTimeUtils.START_OF_TIME; +import static google.registry.util.DateTimeUtils.START_INSTANT; import static google.registry.util.DateTimeUtils.minusDays; +import static google.registry.util.DateTimeUtils.minusMonths; import static google.registry.util.DateTimeUtils.minusYears; import static google.registry.util.DateTimeUtils.plusDays; +import static google.registry.util.DateTimeUtils.plusYears; import static org.mockito.Mockito.verify; import com.google.common.collect.ImmutableList; @@ -51,8 +53,8 @@ import google.registry.rdap.RdapMetrics.SearchType; import google.registry.rdap.RdapMetrics.WildcardType; import google.registry.rdap.RdapSearchResults.IncompletenessWarningType; import google.registry.request.Action; +import java.time.Instant; import java.util.Optional; -import org.joda.time.DateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -74,10 +76,10 @@ class RdapDomainActionTest extends RdapActionBaseTestCase { persistResource( makeRegistrar("evilregistrar", "Yes Virginia