diff --git a/common/src/testing/java/google/registry/testing/truth/TextDiffSubject.java b/common/src/testing/java/google/registry/testing/truth/TextDiffSubject.java index 53bc369d8..43bd53f7a 100644 --- a/common/src/testing/java/google/registry/testing/truth/TextDiffSubject.java +++ b/common/src/testing/java/google/registry/testing/truth/TextDiffSubject.java @@ -175,14 +175,7 @@ public class TextDiffSubject extends Subject { .orElse(0); } - private static class SideBySideRowFormatter { - private final int maxExpectedLineLength; - private final int maxActualLineLength; - - private SideBySideRowFormatter(int maxExpectedLineLength, int maxActualLineLength) { - this.maxExpectedLineLength = maxExpectedLineLength; - this.maxActualLineLength = maxActualLineLength; - } + private record SideBySideRowFormatter(int maxExpectedLineLength, int maxActualLineLength) { public String formatRow(String expected, String actual, char padChar) { return String.format( diff --git a/core/src/main/java/google/registry/batch/CheckBulkComplianceAction.java b/core/src/main/java/google/registry/batch/CheckBulkComplianceAction.java index 16beb6ef7..19686ca25 100644 --- a/core/src/main/java/google/registry/batch/CheckBulkComplianceAction.java +++ b/core/src/main/java/google/registry/batch/CheckBulkComplianceAction.java @@ -187,18 +187,12 @@ public class CheckBulkComplianceAction implements Runnable { .getLastNotificationSent() .map(sentDate -> Days.daysBetween(sentDate, clock.nowUtc()).getDays()) .orElse(Integer.MAX_VALUE); - if (daysSinceLastNotification < THIRTY_DAYS) { - // Don't send an email if notification was already sent within the last 30 - // days - continue; - } else if (daysSinceLastNotification < FORTY_DAYS) { - // Send an upgrade email if last email was between 30 and 40 days ago + // Send a warning email if 30-39 days since last notification and an upgrade email if 40+ days + if (daysSinceLastNotification >= THIRTY_DAYS) { sendActiveDomainOverageEmail( - /* warning= */ false, bulkPricingPackage, overageList.get(bulkPricingPackage)); - } else { - // Send a warning email - sendActiveDomainOverageEmail( - /* warning= */ true, bulkPricingPackage, overageList.get(bulkPricingPackage)); + /* warning= */ daysSinceLastNotification >= FORTY_DAYS, + bulkPricingPackage, + overageList.get(bulkPricingPackage)); } } } diff --git a/core/src/main/java/google/registry/batch/RelockDomainAction.java b/core/src/main/java/google/registry/batch/RelockDomainAction.java index 9d5d87605..6410e092b 100644 --- a/core/src/main/java/google/registry/batch/RelockDomainAction.java +++ b/core/src/main/java/google/registry/batch/RelockDomainAction.java @@ -66,11 +66,15 @@ public class RelockDomainAction implements Runnable { private static final Duration ONE_HOUR = Duration.standardHours(1); private static final String RELOCK_SUCCESS_EMAIL_TEMPLATE = - "The domain %s was successfully re-locked.\n\nPlease contact support at %s if you have any " - + "questions."; + """ + The domain %s was successfully re-locked. + + Please contact support at %s if you have any questions."""; private static final String RELOCK_NON_RETRYABLE_FAILURE_EMAIL_TEMPLATE = - "There was an error when automatically re-locking %s. Error message: %s\n\nPlease contact " - + "support at %s if you have any questions."; + """ + There was an error when automatically re-locking %s. Error message: %s + + Please contact support at %s if you have any questions."""; private static final String RELOCK_TRANSIENT_FAILURE_EMAIL_TEMPLATE = "There was an unexpected error when automatically re-locking %s. We will continue retrying " + "the lock for five hours. Please contact support at %s if you have any questions"; diff --git a/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java b/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java index c76119978..8582732b7 100644 --- a/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java +++ b/core/src/main/java/google/registry/batch/SendExpiringCertificateNotificationEmailAction.java @@ -206,7 +206,7 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable () -> { Registrar.Builder newRegistrar = tm().loadByEntity(registrar).asBuilder(); switch (certificateType) { - case PRIMARY: + case PRIMARY -> { newRegistrar.setLastExpiringCertNotificationSentDate(now); tm().put(newRegistrar.build()); logger.atInfo().log( @@ -215,8 +215,8 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable DATE_FORMATTER.print(now), certificateType.getDisplayName(), registrar.getRegistrarName()); - break; - case FAILOVER: + } + case FAILOVER -> { newRegistrar.setLastExpiringFailoverCertNotificationSentDate(now); tm().put(newRegistrar.build()); logger.atInfo().log( @@ -225,13 +225,13 @@ public class SendExpiringCertificateNotificationEmailAction implements Runnable DATE_FORMATTER.print(now), certificateType.getDisplayName(), registrar.getRegistrarName()); - break; - default: - throw new IllegalArgumentException( - String.format( - "Unsupported certificate type: %s being passed in when updating " - + "the last notification sent date to registrar %s.", - certificateType.toString(), registrar.getRegistrarName())); + } + default -> + throw new IllegalArgumentException( + String.format( + "Unsupported certificate type: %s being passed in when updating " + + "the last notification sent date to registrar %s.", + certificateType.toString(), registrar.getRegistrarName())); } }); } catch (Exception e) { diff --git a/core/src/main/java/google/registry/beam/common/RegistryPipelineWorkerInitializer.java b/core/src/main/java/google/registry/beam/common/RegistryPipelineWorkerInitializer.java index 801ab8443..5dd54019b 100644 --- a/core/src/main/java/google/registry/beam/common/RegistryPipelineWorkerInitializer.java +++ b/core/src/main/java/google/registry/beam/common/RegistryPipelineWorkerInitializer.java @@ -50,16 +50,17 @@ public class RegistryPipelineWorkerInitializer implements JvmInitializer { environment.setup(); RegistryPipelineComponent registryPipelineComponent = toRegistryPipelineComponent(registryOptions); - Lazy transactionManagerLazy; - switch (registryOptions.getJpaTransactionManagerType()) { - case READ_ONLY_REPLICA: - transactionManagerLazy = - registryPipelineComponent.getReadOnlyReplicaJpaTransactionManager(); - break; - case REGULAR: - default: - transactionManagerLazy = registryPipelineComponent.getJpaTransactionManager(); - } + Lazy transactionManagerLazy = + switch (registryOptions.getJpaTransactionManagerType()) { + case READ_ONLY_REPLICA -> + registryPipelineComponent.getReadOnlyReplicaJpaTransactionManager(); + case REGULAR -> registryPipelineComponent.getJpaTransactionManager(); + default -> + throw new IllegalStateException( + String.format( + "Unknown JPA transaction manager type: %s", + registryOptions.getJpaTransactionManagerType())); + }; TransactionManagerFactory.setJpaTmOnBeamWorker(transactionManagerLazy::get); SystemPropertySetter.PRODUCTION_IMPL.setProperty(PROPERTY, "true"); } diff --git a/core/src/main/java/google/registry/beam/rde/RdePipeline.java b/core/src/main/java/google/registry/beam/rde/RdePipeline.java index 49a628a49..9a5983395 100644 --- a/core/src/main/java/google/registry/beam/rde/RdePipeline.java +++ b/core/src/main/java/google/registry/beam/rde/RdePipeline.java @@ -688,27 +688,26 @@ public class RdePipeline implements Serializable { protected abstract static class TupleTags { protected static final TupleTag> DOMAIN_FRAGMENTS = - new TupleTag>() {}; + new TupleTag<>() {}; protected static final TupleTag> REFERENCED_CONTACTS = - new TupleTag>() {}; + new TupleTag<>() {}; protected static final TupleTag> REFERENCED_HOSTS = - new TupleTag>() {}; + new TupleTag<>() {}; protected static final TupleTag>> SUPERORDINATE_DOMAINS = - new TupleTag>>() {}; + new TupleTag<>() {}; protected static final TupleTag> EXTERNAL_HOST_FRAGMENTS = - new TupleTag>() {}; + new TupleTag<>() {}; - protected static final TupleTag PENDING_DEPOSIT = - new TupleTag() {}; + protected static final TupleTag PENDING_DEPOSIT = new TupleTag<>() {}; protected static final TupleTag> HOST_TO_PENDING_DEPOSIT = - new TupleTag>() {}; + new TupleTag<>() {}; - protected static final TupleTag REVISION_ID = new TupleTag() {}; + protected static final TupleTag REVISION_ID = new TupleTag<>() {}; } @Singleton diff --git a/core/src/main/java/google/registry/bsa/BsaDiffCreator.java b/core/src/main/java/google/registry/bsa/BsaDiffCreator.java index ca25b1ed4..d3280c9e9 100644 --- a/core/src/main/java/google/registry/bsa/BsaDiffCreator.java +++ b/core/src/main/java/google/registry/bsa/BsaDiffCreator.java @@ -62,7 +62,7 @@ class BsaDiffCreator { this.gcsClient = gcsClient; } - private Multimap listBackedMultiMap() { + private > Multimap listBackedMultiMap() { return newListMultimap(newHashMap(), Lists::newArrayList); } diff --git a/core/src/main/java/google/registry/bsa/IdnChecker.java b/core/src/main/java/google/registry/bsa/IdnChecker.java index 0a92a9428..f90c489c7 100644 --- a/core/src/main/java/google/registry/bsa/IdnChecker.java +++ b/core/src/main/java/google/registry/bsa/IdnChecker.java @@ -80,7 +80,7 @@ public class IdnChecker { } private static ImmutableMap> getIdnToTldMap(DateTime now) { - ImmutableMultimap.Builder idnToTldMap = new ImmutableMultimap.Builder(); + var idnToTldMap = new ImmutableMultimap.Builder(); Tlds.getTldEntitiesOfType(TldType.REAL).stream() .filter(tld -> isEnrolledWithBsa(tld, now)) .forEach( diff --git a/core/src/main/java/google/registry/bsa/api/BlockOrder.java b/core/src/main/java/google/registry/bsa/api/BlockOrder.java index 54319a748..360469102 100644 --- a/core/src/main/java/google/registry/bsa/api/BlockOrder.java +++ b/core/src/main/java/google/registry/bsa/api/BlockOrder.java @@ -34,7 +34,7 @@ public record BlockOrder(long orderId, OrderType orderType) { public static BlockOrder deserialize(String text) { List items = SPLITTER.splitToList(text); try { - return create(Long.valueOf(items.get(0)), OrderType.valueOf(items.get(1))); + return create(Long.parseLong(items.get(0)), OrderType.valueOf(items.get(1))); } catch (NumberFormatException ne) { throw new IllegalArgumentException(text); } diff --git a/core/src/main/java/google/registry/bsa/persistence/BsaDomainRefresh.java b/core/src/main/java/google/registry/bsa/persistence/BsaDomainRefresh.java index e5073f36d..288f27a38 100644 --- a/core/src/main/java/google/registry/bsa/persistence/BsaDomainRefresh.java +++ b/core/src/main/java/google/registry/bsa/persistence/BsaDomainRefresh.java @@ -96,10 +96,9 @@ class BsaDomainRefresh { if (this == o) { return true; } - if (!(o instanceof BsaDomainRefresh)) { + if (!(o instanceof BsaDomainRefresh that)) { return false; } - BsaDomainRefresh that = (BsaDomainRefresh) o; return Objects.equal(jobId, that.jobId) && Objects.equal(creationTime, that.creationTime) && Objects.equal(updateTime, that.updateTime) diff --git a/core/src/main/java/google/registry/bsa/persistence/BsaDownload.java b/core/src/main/java/google/registry/bsa/persistence/BsaDownload.java index 89e2397a0..db2eb3654 100644 --- a/core/src/main/java/google/registry/bsa/persistence/BsaDownload.java +++ b/core/src/main/java/google/registry/bsa/persistence/BsaDownload.java @@ -120,10 +120,9 @@ class BsaDownload { if (this == o) { return true; } - if (!(o instanceof BsaDownload)) { + if (!(o instanceof BsaDownload that)) { return false; } - BsaDownload that = (BsaDownload) o; return Objects.equal(creationTime, that.creationTime) && Objects.equal(updateTime, that.updateTime) && Objects.equal(blockListChecksums, that.blockListChecksums) @@ -136,6 +135,6 @@ class BsaDownload { } static VKey vKey(long jobId) { - return VKey.create(BsaDownload.class, Long.valueOf(jobId)); + return VKey.create(BsaDownload.class, jobId); } } diff --git a/core/src/main/java/google/registry/bsa/persistence/BsaLabel.java b/core/src/main/java/google/registry/bsa/persistence/BsaLabel.java index 6bb5903b9..bcca7954d 100644 --- a/core/src/main/java/google/registry/bsa/persistence/BsaLabel.java +++ b/core/src/main/java/google/registry/bsa/persistence/BsaLabel.java @@ -61,10 +61,9 @@ final class BsaLabel { if (this == o) { return true; } - if (!(o instanceof BsaLabel)) { + if (!(o instanceof BsaLabel label1)) { return false; } - BsaLabel label1 = (BsaLabel) o; return Objects.equal(label, label1.label) && Objects.equal(creationTime, label1.creationTime); } diff --git a/core/src/main/java/google/registry/bsa/persistence/BsaUnblockableDomain.java b/core/src/main/java/google/registry/bsa/persistence/BsaUnblockableDomain.java index bfaa90e18..30d0d2b4a 100644 --- a/core/src/main/java/google/registry/bsa/persistence/BsaUnblockableDomain.java +++ b/core/src/main/java/google/registry/bsa/persistence/BsaUnblockableDomain.java @@ -84,10 +84,9 @@ class BsaUnblockableDomain { if (this == o) { return true; } - if (!(o instanceof BsaUnblockableDomain)) { + if (!(o instanceof BsaUnblockableDomain that)) { return false; } - BsaUnblockableDomain that = (BsaUnblockableDomain) o; return Objects.equal(label, that.label) && Objects.equal(tld, that.tld) && reason == that.reason @@ -142,10 +141,9 @@ class BsaUnblockableDomain { if (this == o) { return true; } - if (!(o instanceof BsaUnblockableDomainId)) { + if (!(o instanceof BsaUnblockableDomainId that)) { return false; } - BsaUnblockableDomainId that = (BsaUnblockableDomainId) o; return Objects.equal(label, that.label) && Objects.equal(tld, that.tld); } diff --git a/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java b/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java index 4b58294c0..c376d9287 100644 --- a/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java +++ b/core/src/main/java/google/registry/bsa/persistence/LabelDiffUpdates.java @@ -72,7 +72,7 @@ public final class LabelDiffUpdates { for (Map.Entry> entry : labelsByType.entrySet()) { switch (entry.getKey()) { - case CREATE: + case CREATE -> { // With current Cloud SQL, label upsert throughput is about 200/second. If // better performance is needed, consider bulk insert in native SQL. tm().putAll( @@ -86,8 +86,8 @@ public final class LabelDiffUpdates { // cached BsaLabels. Eventually will be consistent. nonBlockedDomains.addAll( tallyUnblockableDomainsForNewLabels(entry.getValue(), idnChecker, now)); - break; - case DELETE: + } + case DELETE -> { ImmutableSet deletedLabels = entry.getValue().stream() .filter(label -> isValidInAtLeastOneTld(label, idnChecker)) @@ -100,8 +100,8 @@ public final class LabelDiffUpdates { "Only found %s entities among the %s labels: [%s]", nDeleted, deletedLabels.size(), deletedLabels); } - break; - case NEW_ORDER_ASSOCIATION: + } + case NEW_ORDER_ASSOCIATION -> { ImmutableSet affectedLabels = entry.getValue().stream() .filter(label -> isValidInAtLeastOneTld(label, idnChecker)) @@ -120,13 +120,12 @@ public final class LabelDiffUpdates { Queries.queryBsaUnblockableDomainByLabels(affectedLabels) .map(BsaUnblockableDomain::toUnblockableDomain) .forEach(nonBlockedDomains::add); - for (BlockLabel label : entry.getValue()) { getInvalidTldsForLabel(label, idnChecker) .map(tld -> UnblockableDomain.of(label.label(), tld, Reason.INVALID)) .forEach(nonBlockedDomains::add); } - break; + } } } }); diff --git a/core/src/main/java/google/registry/bsa/persistence/Queries.java b/core/src/main/java/google/registry/bsa/persistence/Queries.java index d04457318..4dc08e06d 100644 --- a/core/src/main/java/google/registry/bsa/persistence/Queries.java +++ b/core/src/main/java/google/registry/bsa/persistence/Queries.java @@ -103,7 +103,7 @@ public final class Queries { static ImmutableList batchReadUnblockables( Optional lastRead, int batchSize) { - return ImmutableList.copyOf( + return ImmutableList.copyOf( bsaQuery( () -> tm().getEntityManager() diff --git a/core/src/main/java/google/registry/dns/DnsWriterProxy.java b/core/src/main/java/google/registry/dns/DnsWriterProxy.java index 40549f167..0dd70997d 100644 --- a/core/src/main/java/google/registry/dns/DnsWriterProxy.java +++ b/core/src/main/java/google/registry/dns/DnsWriterProxy.java @@ -38,7 +38,7 @@ public final class DnsWriterProxy { /** * Returns the instance of {@link DnsWriter} by class name. * - * If the DnsWriter doesn't belong to this TLD, will return null. + *

If the DnsWriter doesn't belong to this TLD, will return null. */ public DnsWriter getByClassNameForTld(String className, String tld) { if (!Tld.get(tld).getDnsWriters().contains(className)) { diff --git a/core/src/main/java/google/registry/dns/RefreshDnsAction.java b/core/src/main/java/google/registry/dns/RefreshDnsAction.java index 1be7b6855..d543f7396 100644 --- a/core/src/main/java/google/registry/dns/RefreshDnsAction.java +++ b/core/src/main/java/google/registry/dns/RefreshDnsAction.java @@ -63,16 +63,15 @@ public final class RefreshDnsAction implements Runnable { tm().transact( () -> { switch (type) { - case DOMAIN: + case DOMAIN -> { loadAndVerifyExistence(Domain.class, domainOrHostName); requestDomainDnsRefresh(domainOrHostName); - break; - case HOST: + } + case HOST -> { verifyHostIsSubordinate(loadAndVerifyExistence(Host.class, domainOrHostName)); requestHostDnsRefresh(domainOrHostName); - break; - default: - throw new BadRequestException("Unsupported type: " + type); + } + default -> throw new BadRequestException("Unsupported type: " + type); } }); } 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 20a749f4c..62037c631 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 @@ -55,14 +55,14 @@ import org.xbill.DNS.Type; import org.xbill.DNS.Update; /** - * A DnsWriter that implements the DNS UPDATE protocol as specified in - * RFC 2136. Publishes changes in the - * domain-registry to a (capable) external DNS server, sometimes called a "hidden master". DNS - * UPDATE messages are sent via a supplied "transport" class. + * A DnsWriter that implements the DNS UPDATE protocol as specified in RFC 2136. Publishes changes in the domain-registry + * to a (capable) external DNS server, sometimes called a "hidden master". DNS UPDATE messages are + * sent via a supplied "transport" class. * - * On call to {@link #commit()}, a single UPDATE message is created containing the records required - * to "synchronize" the DNS with the current (at the time of processing) state of the registry, for - * the supplied domain/host. + *

On call to {@link #commit()}, a single UPDATE message is created containing the records + * required to "synchronize" the DNS with the current (at the time of processing) state of the + * registry, for the supplied domain/host. * *

The general strategy of the publish methods is to delete all resource records of any * type that match the exact domain/host name supplied. And then for create/update cases, @@ -73,8 +73,8 @@ import org.xbill.DNS.Update; *

Only NS, DS, A, and AAAA records are published, and in particular no DNSSEC signing is done * assuming that this will be done by a third party DNS provider. * - *

Each commit call is treated as an atomic update to the DNS. If a commit fails an exception - * is thrown. The SOA record serial number is implicitly incremented by the server on each UPDATE + *

Each commit call is treated as an atomic update to the DNS. If a commit fails an exception is + * thrown. The SOA record serial number is implicitly incremented by the server on each UPDATE * message, as required by RFC 2136. Care must be taken to make sure the SOA serial number does not * go backwards if the entire TLD (zone) is "reset" to empty and republished. */ diff --git a/core/src/main/java/google/registry/flows/TransportCredentials.java b/core/src/main/java/google/registry/flows/TransportCredentials.java index 382776aee..e2a50a948 100644 --- a/core/src/main/java/google/registry/flows/TransportCredentials.java +++ b/core/src/main/java/google/registry/flows/TransportCredentials.java @@ -22,9 +22,9 @@ public interface TransportCredentials { /** * Check that these credentials are valid for the registrar and optionally check the password. * - * Called by {@link google.registry.flows.session.LoginFlow LoginFlow} to check the transport - * credentials against the stored registrar's credentials. If they do not match, throw an - * {@link AuthenticationErrorException}. + *

Called by {@link google.registry.flows.session.LoginFlow LoginFlow} to check the transport + * credentials against the stored registrar's credentials. If they do not match, throw an {@link + * AuthenticationErrorException}. */ void validate(Registrar registrar, String password) throws AuthenticationErrorException; 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 12072ee97..ba3d2373d 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java +++ b/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java @@ -16,12 +16,10 @@ package google.registry.flows.domain; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap; -import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.intersection; import static com.google.common.collect.Sets.union; @@ -95,6 +93,7 @@ import google.registry.model.domain.DomainCommand.Update; import google.registry.model.domain.DomainHistory; import google.registry.model.domain.ForeignKeyedDesignatedContact; import google.registry.model.domain.Period; +import google.registry.model.domain.Period.Unit; import google.registry.model.domain.fee.BaseFee; import google.registry.model.domain.fee.BaseFee.FeeType; import google.registry.model.domain.fee.Credit; @@ -121,7 +120,7 @@ import google.registry.model.domain.token.AllocationToken.RegistrationBehavior; import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppoutput.EppResponse.ResponseExtension; import google.registry.model.host.Host; -import google.registry.model.poll.PollMessage; +import google.registry.model.poll.PollMessage.Autorenew; import google.registry.model.registrar.Registrar; import google.registry.model.registrar.RegistrarBase.State; import google.registry.model.reporting.DomainTransactionRecord; @@ -206,7 +205,7 @@ public class DomainFlowUtils { if (parts.size() <= 1) { throw new BadDomainNamePartsCountException(); } - if (any(parts, equalTo(""))) { + if (parts.stream().anyMatch(String::isEmpty)) { throw new EmptyDomainNamePartException(); } validateFirstLabel(parts.get(0)); @@ -329,7 +328,7 @@ public class DomainFlowUtils { /** Check if the registrar running the flow has access to the TLD in question. */ public static void checkAllowedAccessToTld(String registrarId, String tld) throws EppException { if (!Registrar.loadByRegistrarIdCached(registrarId).get().getAllowedTlds().contains(tld)) { - throw new DomainFlowUtils.NotAuthorizedForTldException(tld); + throw new NotAuthorizedForTldException(tld); } } @@ -344,7 +343,7 @@ public class DomainFlowUtils { .get() .getBillingAccountMap() .containsKey(tld.getCurrency())) { - throw new DomainFlowUtils.MissingBillingAccountMapException(tld.getCurrency()); + throw new MissingBillingAccountMapException(tld.getCurrency()); } } @@ -405,7 +404,7 @@ public class DomainFlowUtils { /** We only allow specifying years in a period. */ static Period verifyUnitIsYears(Period period) throws EppException { - if (!checkNotNull(period).getUnit().equals(Period.Unit.YEARS)) { + if (!checkNotNull(period).getUnit().equals(Unit.YEARS)) { throw new BadPeriodUnitException(); } return period; @@ -534,7 +533,7 @@ public class DomainFlowUtils { public static boolean isReserved(InternetDomainName domainName, boolean isSunrise) { ImmutableSet types = getReservationTypes(domainName); - return !Sets.intersection(types, RESERVED_TYPES).isEmpty() + return !intersection(types, RESERVED_TYPES).isEmpty() || !(isSunrise || intersection(TYPES_ALLOWED_FOR_CREATE_ONLY_IN_SUNRISE, types).isEmpty()); } @@ -601,8 +600,8 @@ public class DomainFlowUtils { * Fills in a builder with the data needed for an autorenew poll message for this domain. This * does not copy over the id of the current autorenew poll message. */ - public static PollMessage.Autorenew.Builder newAutorenewPollMessage(Domain domain) { - return new PollMessage.Autorenew.Builder() + public static Autorenew.Builder newAutorenewPollMessage(Domain domain) { + return new Autorenew.Builder() .setTargetId(domain.getDomainName()) .setRegistrarId(domain.getCurrentSponsorRegistrarId()) .setEventTime(domain.getRegistrationExpirationTime()) @@ -623,7 +622,7 @@ public class DomainFlowUtils { BillingRecurrence existingBillingRecurrence, DateTime newEndTime, @Nullable HistoryEntryId historyId) { - Optional autorenewPollMessage = + Optional autorenewPollMessage = tm().loadByKeyIfPresent(domain.getAutorenewPollMessage()); // Construct an updated autorenew poll message. If the autorenew poll message no longer exists, @@ -632,7 +631,7 @@ public class DomainFlowUtils { // message to be deleted), and then subsequently the transfer was canceled, rejected, or deleted // (which would cause the poll message to be recreated here). In the latter case, the history id // of the event that created the new poll message will also be used. - PollMessage.Autorenew updatedAutorenewPollMessage; + Autorenew updatedAutorenewPollMessage; if (autorenewPollMessage.isPresent()) { updatedAutorenewPollMessage = autorenewPollMessage.get().asBuilder().setAutorenewEndTime(newEndTime).build(); @@ -706,7 +705,7 @@ public class DomainFlowUtils { String feeClass = null; ImmutableList fees = ImmutableList.of(); switch (feeRequest.getCommandName()) { - case CREATE: + case CREATE -> { // Don't return a create price for reserved names. if (isReserved(domainName, isSunrise) && !isAvailable) { feeClass = "reserved"; @@ -726,16 +725,16 @@ public class DomainFlowUtils { allocationToken) .getFees(); } - break; - case RENEW: + } + case RENEW -> { builder.setAvailIfSupported(true); fees = pricingLogic .getRenewPrice( tld, domainNameString, now, years, billingRecurrence, allocationToken) .getFees(); - break; - case RESTORE: + } + case RESTORE -> { // The minimum allowable period per the EPP spec is 1, so, strangely, 1 year still has to be // passed in as the period for a restore even if the domain would *not* be renewed as part // of a restore. This is fixed in RFC 8748 (which is a more recent version of the fee @@ -751,21 +750,20 @@ public class DomainFlowUtils { boolean isExpired = domain.isPresent() && domain.get().getRegistrationExpirationTime().isBefore(now); fees = pricingLogic.getRestorePrice(tld, domainNameString, now, isExpired).getFees(); - break; - case TRANSFER: + } + case TRANSFER -> { if (years != 1) { throw new TransfersAreAlwaysForOneYearException(); } builder.setAvailIfSupported(true); fees = pricingLogic.getTransferPrice(tld, domainNameString, now, billingRecurrence).getFees(); - break; - case UPDATE: + } + case UPDATE -> { builder.setAvailIfSupported(true); fees = pricingLogic.getUpdatePrice(tld, domainNameString, now).getFees(); - break; - default: - throw new UnknownFeeCommandException(feeRequest.getUnparsedCommandName()); + } + default -> throw new UnknownFeeCommandException(feeRequest.getUnparsedCommandName()); } if (feeClass == null) { diff --git a/core/src/main/java/google/registry/flows/domain/DomainPricingLogic.java b/core/src/main/java/google/registry/flows/domain/DomainPricingLogic.java index bbd479de2..12ed6f10b 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainPricingLogic.java +++ b/core/src/main/java/google/registry/flows/domain/DomainPricingLogic.java @@ -138,14 +138,14 @@ public final class DomainPricingLogic { isRenewCostPremiumPrice = domainPrices.isPremium(); } else { switch (billingRecurrence.getRenewalPriceBehavior()) { - case DEFAULT: + case DEFAULT -> { renewCost = getDomainRenewCostWithDiscount(tld, domainPrices, dateTime, years, allocationToken); isRenewCostPremiumPrice = domainPrices.isPremium(); - break; + } // if the renewal price behavior is specified, then the renewal price should be the same // as the creation price, which is stored in the billing event as the renewal price - case SPECIFIED: + case SPECIFIED -> { checkArgumentPresent( billingRecurrence.getRenewalPrice(), "Unexpected behavior: renewal price cannot be null when renewal behavior is" @@ -153,20 +153,20 @@ public final class DomainPricingLogic { // Don't apply allocation token to renewal price when SPECIFIED renewCost = billingRecurrence.getRenewalPrice().get().multipliedBy(years); isRenewCostPremiumPrice = false; - break; + } // if the renewal price behavior is nonpremium, it means that the domain should be renewed // at standard price of domains at the time, even if the domain is premium - case NONPREMIUM: + case NONPREMIUM -> { renewCost = getDomainCostWithDiscount( false, years, allocationToken, tld.getStandardRenewCost(dateTime)); isRenewCostPremiumPrice = false; - break; - default: - throw new IllegalArgumentException( - String.format( - "Unknown RenewalPriceBehavior enum value: %s", - billingRecurrence.getRenewalPriceBehavior())); + } + default -> + throw new IllegalArgumentException( + String.format( + "Unknown RenewalPriceBehavior enum value: %s", + billingRecurrence.getRenewalPriceBehavior())); } } return customLogic.customizeRenewPrice( diff --git a/core/src/main/java/google/registry/flows/picker/FlowPicker.java b/core/src/main/java/google/registry/flows/picker/FlowPicker.java index 68819ec74..4440fa568 100644 --- a/core/src/main/java/google/registry/flows/picker/FlowPicker.java +++ b/core/src/main/java/google/registry/flows/picker/FlowPicker.java @@ -124,22 +124,21 @@ public class FlowPicker { }}; /** Poll flows have an {@link InnerCommand} of type {@link Poll}. */ - private static final FlowProvider POLL_FLOW_PROVIDER = new FlowProvider() { - @Override - Class get( - EppInput eppInput, InnerCommand innerCommand, ResourceCommand resourceCommand) { - if (!(innerCommand instanceof Poll)) { - return null; - } - switch (((Poll) innerCommand).getPollOp()) { - case ACK: - return PollAckFlow.class; - case REQUEST: - return PollRequestFlow.class; - default: - return UnimplementedFlow.class; - } - }}; + private static final FlowProvider POLL_FLOW_PROVIDER = + new FlowProvider() { + @Override + Class get( + EppInput eppInput, InnerCommand innerCommand, ResourceCommand resourceCommand) { + if (!(innerCommand instanceof Poll)) { + return null; + } + return switch (((Poll) innerCommand).getPollOp()) { + case ACK -> PollAckFlow.class; + case REQUEST -> PollRequestFlow.class; + default -> UnimplementedFlow.class; + }; + } + }; /** * The domain restore command is technically a domain {@literal }, but logically a totally diff --git a/core/src/main/java/google/registry/flows/poll/PollFlowUtils.java b/core/src/main/java/google/registry/flows/poll/PollFlowUtils.java index c494cc9d7..8b5893913 100644 --- a/core/src/main/java/google/registry/flows/poll/PollFlowUtils.java +++ b/core/src/main/java/google/registry/flows/poll/PollFlowUtils.java @@ -54,8 +54,7 @@ public final class PollFlowUtils { if (pollMessage instanceof PollMessage.OneTime) { // One-time poll messages are deleted once acked. tm().delete(pollMessage.createVKey()); - } else if (pollMessage instanceof PollMessage.Autorenew) { - PollMessage.Autorenew autorenewPollMessage = (PollMessage.Autorenew) pollMessage; + } else if (pollMessage instanceof PollMessage.Autorenew autorenewPollMessage) { // Move the eventTime of this autorenew poll message forward by a year. DateTime nextEventTime = autorenewPollMessage.getEventTime().plusYears(1); diff --git a/core/src/main/java/google/registry/keyring/api/PgpHelper.java b/core/src/main/java/google/registry/keyring/api/PgpHelper.java index 725781694..1b0729174 100644 --- a/core/src/main/java/google/registry/keyring/api/PgpHelper.java +++ b/core/src/main/java/google/registry/keyring/api/PgpHelper.java @@ -130,23 +130,22 @@ public final class PgpHelper { while (keys.hasNext()) { PGPPublicKey key = keys.next(); switch (want) { - case ENCRYPT: + case ENCRYPT -> { if (key.isEncryptionKey()) { return Optional.of(key); } - break; - case SIGN: + } + case SIGN -> { if (isSigningKey(key)) { return Optional.of(key); } - break; - case ENCRYPT_SIGN: + } + case ENCRYPT_SIGN -> { if (key.isEncryptionKey() && isSigningKey(key)) { return Optional.of(key); } - break; - default: - throw new AssertionError(); + } + default -> throw new AssertionError(); } } return Optional.empty(); @@ -154,14 +153,9 @@ public final class PgpHelper { /** Returns {@code true} if this key can be used for signing. */ public static boolean isSigningKey(PGPPublicKey key) { - switch (key.getAlgorithm()) { - case RSA_GENERAL: - case RSA_SIGN: - case DSA: - case ELGAMAL_GENERAL: - return true; - default: - return false; - } + return switch (key.getAlgorithm()) { + case RSA_GENERAL, RSA_SIGN, DSA, ELGAMAL_GENERAL -> true; + default -> false; + }; } } diff --git a/core/src/main/java/google/registry/model/ModelUtils.java b/core/src/main/java/google/registry/model/ModelUtils.java index a3e410190..e8f19431f 100644 --- a/core/src/main/java/google/registry/model/ModelUtils.java +++ b/core/src/main/java/google/registry/model/ModelUtils.java @@ -109,16 +109,18 @@ public class ModelUtils { if (value != null && value.getClass().isArray()) { // It's surprisingly difficult to convert arrays into lists if the array might be primitive. final Object arrayValue = value; - value = new AbstractList() { - @Override - public Object get(int index) { - return Array.get(arrayValue, index); - } + value = + new AbstractList<>() { + @Override + public Object get(int index) { + return Array.get(arrayValue, index); + } - @Override - public int size() { - return Array.getLength(arrayValue); - }}; + @Override + public int size() { + return Array.getLength(arrayValue); + } + }; } values.put(field, value); } 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 f9c204484..83ce948f8 100644 --- a/core/src/main/java/google/registry/model/domain/DomainBase.java +++ b/core/src/main/java/google/registry/model/domain/DomainBase.java @@ -659,22 +659,17 @@ public class DomainBase extends EppResource contact.getType()); contactsDiscovered.add(contact.getType()); switch (contact.getType()) { - case BILLING: - billingContact = contact.getContactKey(); - break; - case TECH: - techContact = contact.getContactKey(); - break; - case ADMIN: - adminContact = contact.getContactKey(); - break; - case REGISTRANT: + case BILLING -> billingContact = contact.getContactKey(); + case TECH -> techContact = contact.getContactKey(); + case ADMIN -> adminContact = contact.getContactKey(); + case REGISTRANT -> { if (includeRegistrant) { registrantContact = contact.getContactKey(); } - break; - default: - throw new IllegalArgumentException("Unknown contact resource type: " + contact.getType()); + } + default -> + throw new IllegalArgumentException( + "Unknown contact resource type: " + contact.getType()); } } } diff --git a/core/src/main/java/google/registry/model/domain/rgp/GracePeriodStatus.java b/core/src/main/java/google/registry/model/domain/rgp/GracePeriodStatus.java index 6eb4db63e..4ba768235 100644 --- a/core/src/main/java/google/registry/model/domain/rgp/GracePeriodStatus.java +++ b/core/src/main/java/google/registry/model/domain/rgp/GracePeriodStatus.java @@ -103,7 +103,7 @@ public enum GracePeriodStatus implements EppEnum { /** * Maps from xmlName to {@link GracePeriodStatus}. * - * If no match is found for xmlName, null is returned. + *

If no match is found for xmlName, null is returned. */ @Nullable public static GracePeriodStatus fromXmlName(String xmlName) { diff --git a/core/src/main/java/google/registry/model/eppoutput/Result.java b/core/src/main/java/google/registry/model/eppoutput/Result.java index 21b1acc63..f3952b943 100644 --- a/core/src/main/java/google/registry/model/eppoutput/Result.java +++ b/core/src/main/java/google/registry/model/eppoutput/Result.java @@ -34,7 +34,7 @@ public class Result extends ImmutableObject { * [RFC5321]. EPP uses four decimal digits to describe the success or failure of each EPP command. * Each of the digits of the reply have special significance." * - * "The first digit denotes command success or failure. The second digit denotes the response + *

"The first digit denotes command success or failure. The second digit denotes the response * category, such as command syntax or security. The third and fourth digits provide explicit * response detail within each response category." */ 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 72cc4dc2b..15b9d0893 100644 --- a/core/src/main/java/google/registry/model/poll/PollMessage.java +++ b/core/src/main/java/google/registry/model/poll/PollMessage.java @@ -529,8 +529,7 @@ public abstract class PollMessage extends ImmutableObject // Set the identifier according to the TransferResponse type. if (instance.transferResponse instanceof ContactTransferResponse) { instance.contactId = ((ContactTransferResponse) instance.transferResponse).getContactId(); - } else if (instance.transferResponse instanceof DomainTransferResponse) { - DomainTransferResponse response = (DomainTransferResponse) instance.transferResponse; + } else if (instance.transferResponse instanceof DomainTransferResponse response) { instance.domainName = response.getDomainName(); instance.extendedRegistrationExpirationTime = response.getExtendedRegistrationExpirationTime(); diff --git a/core/src/main/java/google/registry/model/tld/label/ReservationType.java b/core/src/main/java/google/registry/model/tld/label/ReservationType.java index c3ba711ef..431bfde58 100644 --- a/core/src/main/java/google/registry/model/tld/label/ReservationType.java +++ b/core/src/main/java/google/registry/model/tld/label/ReservationType.java @@ -67,12 +67,13 @@ public enum ReservationType { return messageForCheck; } - private static final Ordering ORDERING = new Ordering() { - @Override - public int compare(ReservationType left, ReservationType right) { - return Integer.compare(left.ordinal(), right.ordinal()); - } - }; + private static final Ordering ORDERING = + new Ordering<>() { + @Override + public int compare(ReservationType left, ReservationType right) { + return Integer.compare(left.ordinal(), right.ordinal()); + } + }; /** * Returns the {@code ReservationType} with the highest severity, used when a label has multiple diff --git a/core/src/main/java/google/registry/model/tmch/TmchCrl.java b/core/src/main/java/google/registry/model/tmch/TmchCrl.java index ffccf8fea..445156d7b 100644 --- a/core/src/main/java/google/registry/model/tmch/TmchCrl.java +++ b/core/src/main/java/google/registry/model/tmch/TmchCrl.java @@ -60,17 +60,17 @@ public final class TmchCrl extends CrossTldSingleton { } /** ASCII-armored X.509 certificate revocation list. */ - public final String getCrl() { + public String getCrl() { return crl; } /** Returns the URL that the CRL was downloaded from. */ - public final String getUrl() { + public String getUrl() { return crl; } /** Time we last updated the Database with a newer ICANN CRL. */ - public final DateTime getUpdated() { + public DateTime getUpdated() { return updated; } } diff --git a/core/src/main/java/google/registry/persistence/converter/IntervalDescriptor.java b/core/src/main/java/google/registry/persistence/converter/IntervalDescriptor.java index 9994f20cf..f397d0956 100644 --- a/core/src/main/java/google/registry/persistence/converter/IntervalDescriptor.java +++ b/core/src/main/java/google/registry/persistence/converter/IntervalDescriptor.java @@ -100,7 +100,7 @@ public class IntervalDescriptor extends AbstractTypeDescriptor @Override public ValueBinder getBinder(JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { + return new BasicBinder<>(javaTypeDescriptor, this) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { @@ -117,7 +117,7 @@ public class IntervalDescriptor extends AbstractTypeDescriptor @Override public ValueExtractor getExtractor(JavaTypeDescriptor javaTypeDescriptor) { - return new BasicExtractor(javaTypeDescriptor, this) { + return new BasicExtractor<>(javaTypeDescriptor, this) { @Override protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { return javaTypeDescriptor.wrap(rs.getObject(name), options); diff --git a/core/src/main/java/google/registry/persistence/converter/StringCollectionDescriptor.java b/core/src/main/java/google/registry/persistence/converter/StringCollectionDescriptor.java index 8ee11e19f..d21a69bd1 100644 --- a/core/src/main/java/google/registry/persistence/converter/StringCollectionDescriptor.java +++ b/core/src/main/java/google/registry/persistence/converter/StringCollectionDescriptor.java @@ -115,7 +115,7 @@ public class StringCollectionDescriptor extends AbstractTypeDescriptor ValueBinder getBinder(JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { + return new BasicBinder<>(javaTypeDescriptor, this) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { @@ -123,8 +123,7 @@ public class StringCollectionDescriptor extends AbstractTypeDescriptor ValueExtractor getExtractor(JavaTypeDescriptor javaTypeDescriptor) { - return new BasicExtractor(javaTypeDescriptor, this) { + return new BasicExtractor<>(javaTypeDescriptor, this) { @Override protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { return javaTypeDescriptor.wrap(rs.getArray(name), options); diff --git a/core/src/main/java/google/registry/persistence/converter/StringMapDescriptor.java b/core/src/main/java/google/registry/persistence/converter/StringMapDescriptor.java index ebaa1256b..5cacb0410 100644 --- a/core/src/main/java/google/registry/persistence/converter/StringMapDescriptor.java +++ b/core/src/main/java/google/registry/persistence/converter/StringMapDescriptor.java @@ -105,7 +105,7 @@ public class StringMapDescriptor extends AbstractTypeDescriptor @Override public ValueBinder getBinder(JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { + return new BasicBinder<>(javaTypeDescriptor, this) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { @@ -136,7 +136,7 @@ public class StringMapDescriptor extends AbstractTypeDescriptor @Override public ValueExtractor getExtractor(JavaTypeDescriptor javaTypeDescriptor) { - return new BasicExtractor(javaTypeDescriptor, this) { + return new BasicExtractor<>(javaTypeDescriptor, this) { @Override protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { return javaTypeDescriptor.wrap(rs.getObject(name), options); diff --git a/core/src/main/java/google/registry/persistence/transaction/DatabaseException.java b/core/src/main/java/google/registry/persistence/transaction/DatabaseException.java index 3219c5c11..89cf8c5d9 100644 --- a/core/src/main/java/google/registry/persistence/transaction/DatabaseException.java +++ b/core/src/main/java/google/registry/persistence/transaction/DatabaseException.java @@ -78,8 +78,7 @@ public class DatabaseException extends PersistenceException { static String getSqlError(Throwable t) { ImmutableList.Builder errMessageBuilder = new ImmutableList.Builder<>(); do { - if (t instanceof SQLException) { - SQLException e = (SQLException) t; + if (t instanceof SQLException e) { getSqlExceptionDetails(e).ifPresent(errMessageBuilder::add); } t = t.getCause(); 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 59a06ce9d..436d7a5c7 100644 --- a/core/src/main/java/google/registry/persistence/transaction/JpaTransactionManagerImpl.java +++ b/core/src/main/java/google/registry/persistence/transaction/JpaTransactionManagerImpl.java @@ -544,15 +544,7 @@ public class JpaTransactionManagerImpl implements JpaTransactionManager { return emf.getMetamodel().entity(clazz); } - private static class EntityId { - private final String name; - private final Object value; - - private EntityId(String name, Object value) { - this.name = name; - this.value = value; - } - } + private record EntityId(String name, Object value) {} private static ImmutableSet getEntityIdsFromEntity( EntityType entityType, Object entity) { diff --git a/core/src/main/java/google/registry/privileges/secretmanager/SecretManagerClientImpl.java b/core/src/main/java/google/registry/privileges/secretmanager/SecretManagerClientImpl.java index e2b8b7206..cc3ae8e6c 100644 --- a/core/src/main/java/google/registry/privileges/secretmanager/SecretManagerClientImpl.java +++ b/core/src/main/java/google/registry/privileges/secretmanager/SecretManagerClientImpl.java @@ -165,12 +165,9 @@ public class SecretManagerClientImpl implements SecretManagerClient { return retrier.callWithRetry(callable, SecretManagerClientImpl::isRetryableException); } catch (ApiException e) { switch (e.getStatusCode().getCode()) { - case ALREADY_EXISTS: - throw new SecretAlreadyExistsException(e); - case NOT_FOUND: - throw new NoSuchSecretResourceException(e); - default: - throw new SecretManagerException(e); + case ALREADY_EXISTS -> throw new SecretAlreadyExistsException(e); + case NOT_FOUND -> throw new NoSuchSecretResourceException(e); + default -> throw new SecretManagerException(e); } } } diff --git a/core/src/main/java/google/registry/rdap/AbstractJsonableObject.java b/core/src/main/java/google/registry/rdap/AbstractJsonableObject.java index 63e980540..983d9bc98 100644 --- a/core/src/main/java/google/registry/rdap/AbstractJsonableObject.java +++ b/core/src/main/java/google/registry/rdap/AbstractJsonableObject.java @@ -52,18 +52,13 @@ import org.joda.time.DateTime; * *

This implementation is geared towards RDAP replies, and hence has RDAP-specific quirks. * Specifically: - * * - Fields with empty arrays are not shown at all - * * - VCards are a built-in special case (Not implemented yet) - * * - DateTime conversion is specifically supported as if it were a primitive - * * - Arrays are considered to be SETS rather than lists, meaning repeated values are removed and the * order isn't guaranteed * * Usage: - * * {@link JsonableElement} * ----------------------- * @@ -324,8 +319,7 @@ abstract class AbstractJsonableObject implements Jsonable { /** Converts an Object to a JsonElement. */ private static JsonElement toJsonElement(String name, Member member, Object object) { - if (object instanceof Jsonable) { - Jsonable jsonable = (Jsonable) object; + if (object instanceof Jsonable jsonable) { verifyAllowedJsonKeyName(name, member, jsonable.getClass()); return jsonable.toJson(); } @@ -414,8 +408,7 @@ abstract class AbstractJsonableObject implements Jsonable { object, "Member '%s' is null. If you want an optional member - use Optional", member); // We ignore any Optional that are empty, as if they didn't exist at all - if (object instanceof Optional) { - Optional optional = (Optional) object; + if (object instanceof Optional optional) { if (optional.isEmpty()) { return; } diff --git a/core/src/main/java/google/registry/rdap/RdapIcannStandardInformation.java b/core/src/main/java/google/registry/rdap/RdapIcannStandardInformation.java index 936cb0ef6..3f255d944 100644 --- a/core/src/main/java/google/registry/rdap/RdapIcannStandardInformation.java +++ b/core/src/main/java/google/registry/rdap/RdapIcannStandardInformation.java @@ -79,7 +79,7 @@ public class RdapIcannStandardInformation { /** * Required by ICANN RDAP Profile section 1.4.9, as corrected by Gustavo Lozano of ICANN. * - * Also mentioned in the RDAP Technical Implementation Guide 3.6. + *

Also mentioned in the RDAP Technical Implementation Guide 3.6. * * @see Questions about * the ICANN RDAP Profile @@ -95,7 +95,7 @@ public class RdapIcannStandardInformation { /** * Required by ICANN RDAP Profile section 1.4.8, as corrected by Gustavo Lozano of ICANN. * - * Also mentioned in the RDAP Technical Implementation Guide 3.5. + *

Also mentioned in the RDAP Technical Implementation Guide 3.5. * * @see Questions about * the ICANN RDAP Profile diff --git a/core/src/main/java/google/registry/rdap/RdapJsonFormatter.java b/core/src/main/java/google/registry/rdap/RdapJsonFormatter.java index aa10270a3..1aa027ec1 100644 --- a/core/src/main/java/google/registry/rdap/RdapJsonFormatter.java +++ b/core/src/main/java/google/registry/rdap/RdapJsonFormatter.java @@ -808,17 +808,12 @@ public class RdapJsonFormatter { /** Converts a domain registry contact type into a role as defined by RFC 9083. */ private static RdapEntity.Role convertContactTypeToRdapRole(DesignatedContact.Type contactType) { - switch (contactType) { - case REGISTRANT: - return RdapEntity.Role.REGISTRANT; - case TECH: - return RdapEntity.Role.TECH; - case BILLING: - return RdapEntity.Role.BILLING; - case ADMIN: - return RdapEntity.Role.ADMIN; - } - throw new AssertionError(); + return switch (contactType) { + case REGISTRANT -> RdapEntity.Role.REGISTRANT; + case TECH -> RdapEntity.Role.TECH; + case BILLING -> RdapEntity.Role.BILLING; + case ADMIN -> RdapEntity.Role.ADMIN; + }; } /** diff --git a/core/src/main/java/google/registry/rdap/RdapObjectClasses.java b/core/src/main/java/google/registry/rdap/RdapObjectClasses.java index 67583931f..cd3d7350e 100644 --- a/core/src/main/java/google/registry/rdap/RdapObjectClasses.java +++ b/core/src/main/java/google/registry/rdap/RdapObjectClasses.java @@ -47,7 +47,7 @@ final class RdapObjectClasses { /** * Temporary implementation of VCards. * - * Will create a better implementation soon. + *

Will create a better implementation soon. */ @RestrictJsonNames({}) @AutoValue @@ -146,7 +146,7 @@ final class RdapObjectClasses { /** * An object that can be used to create a TopLevelReply. * - * All Actions need to return an object of this type. + *

All Actions need to return an object of this type. */ abstract static class ReplyPayloadBase extends AbstractJsonableObject { final BoilerplateType boilerplateType; @@ -173,15 +173,14 @@ final class RdapObjectClasses { @JsonableElement("notices[]") abstract Notice aTosNotice(); @JsonableElement("notices") ImmutableList boilerplateNotices() { - switch (aAreplyObject().boilerplateType) { - case DOMAIN: - return RdapIcannStandardInformation.domainBoilerplateNotices; - case NAMESERVER: - case ENTITY: - return RdapIcannStandardInformation.nameserverAndEntityBoilerplateNotices; - default: // things other than domains, nameservers and entities do not yet have boilerplate - return ImmutableList.of(); - } + return switch (aAreplyObject().boilerplateType) { + case DOMAIN -> RdapIcannStandardInformation.domainBoilerplateNotices; + case NAMESERVER, ENTITY -> + RdapIcannStandardInformation.nameserverAndEntityBoilerplateNotices; + default -> // things other than domains, nameservers and entities do not yet have + // boilerplate + ImmutableList.of(); + }; } static TopLevelReplyObject create(ReplyPayloadBase replyObject, Notice tosNotice) { diff --git a/core/src/main/java/google/registry/rde/RdeFragmenter.java b/core/src/main/java/google/registry/rde/RdeFragmenter.java index 142f05beb..c13d03dcb 100644 --- a/core/src/main/java/google/registry/rde/RdeFragmenter.java +++ b/core/src/main/java/google/registry/rde/RdeFragmenter.java @@ -70,8 +70,7 @@ public class RdeFragmenter { cache.put(WatermarkModePair.create(watermark, RdeMode.FULL), result); cache.put(WatermarkModePair.create(watermark, RdeMode.THIN), result); return result; - } else if (resource instanceof Host) { - Host host = (Host) resource; + } else if (resource instanceof Host host) { result = Optional.of( host.isSubordinate() diff --git a/core/src/main/java/google/registry/reporting/billing/CopyDetailReportsAction.java b/core/src/main/java/google/registry/reporting/billing/CopyDetailReportsAction.java index 0eb388335..a7070654e 100644 --- a/core/src/main/java/google/registry/reporting/billing/CopyDetailReportsAction.java +++ b/core/src/main/java/google/registry/reporting/billing/CopyDetailReportsAction.java @@ -97,8 +97,7 @@ public final class CopyDetailReportsAction implements Runnable { response.setPayload(String.format("Failure, encountered %s", e.getMessage())); return; } - ImmutableMap.Builder copyErrorsBuilder = - new ImmutableMap.Builder(); + ImmutableMap.Builder copyErrorsBuilder = new ImmutableMap.Builder<>(); for (String detailReportName : detailReportObjectNames) { // The standard report format is "invoice_details_yyyy-MM_registrarId_tld.csv // TODO(larryruili): Determine a safer way of enforcing this. diff --git a/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java b/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java index c8071761a..a5875fcb0 100644 --- a/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java +++ b/core/src/main/java/google/registry/reporting/billing/PublishInvoicesAction.java @@ -97,22 +97,22 @@ public class PublishInvoicesAction implements Runnable { Job job = dataflow.projects().locations().jobs().get(projectId, jobRegion, jobId).execute(); String state = job.getCurrentState(); switch (state) { - case JOB_DONE: + case JOB_DONE -> { logger.atInfo().log("Dataflow job %s finished successfully, publishing results.", jobId); response.setStatus(SC_OK); enqueueCopyDetailReportsTask(); emailUtils.emailOverallInvoice(); - break; - case JOB_FAILED: + } + case JOB_FAILED -> { logger.atSevere().log("Dataflow job %s finished unsuccessfully.", jobId); response.setStatus(SC_NO_CONTENT); emailUtils.sendAlertEmail( String.format("Dataflow job %s ended in status failure.", jobId)); - break; - default: + } + default -> { logger.atInfo().log("Job in non-terminal state %s, retrying:", state); response.setStatus(SC_SERVICE_UNAVAILABLE); - break; + } } } catch (IOException e) { emailUtils.sendAlertEmail(String.format("Publish action failed due to %s", e.getMessage())); diff --git a/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java b/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java index 5b9a0adce..ecd4890a2 100644 --- a/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java +++ b/core/src/main/java/google/registry/reporting/icann/IcannHttpReporter.java @@ -79,7 +79,7 @@ public class IcannHttpReporter { /** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */ public boolean send(byte[] reportBytes, String reportFilename) - throws GeneralSecurityException, XmlException, IOException { + throws GeneralSecurityException, IOException { validateReportFilename(reportFilename); URL uploadUrl = makeUrl(reportFilename); logger.atInfo().log( @@ -153,17 +153,15 @@ public class IcannHttpReporter { } private String getUrlPrefix(ReportType reportType) { - switch (reportType) { - case TRANSACTIONS: - return icannTransactionsUrl; - case ACTIVITY: - return icannActivityUrl; - default: - throw new IllegalStateException( - String.format( - "Received invalid reportTypes! Expected ACTIVITY or TRANSACTIONS, got %s.", - reportType)); - } + return switch (reportType) { + case TRANSACTIONS -> icannTransactionsUrl; + case ACTIVITY -> icannActivityUrl; + default -> + throw new IllegalStateException( + String.format( + "Received invalid reportTypes! Expected ACTIVITY or TRANSACTIONS, got %s.", + reportType)); + }; } } diff --git a/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java b/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java index 2b4c85660..b9657efa8 100644 --- a/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java +++ b/core/src/main/java/google/registry/reporting/spec11/PublishSpec11ReportAction.java @@ -107,7 +107,7 @@ public class PublishSpec11ReportAction implements Runnable { Job job = dataflow.projects().locations().jobs().get(projectId, jobRegion, jobId).execute(); String state = job.getCurrentState(); switch (state) { - case JOB_DONE: + case JOB_DONE -> { logger.atInfo().log("Dataflow job %s finished successfully, publishing results.", jobId); response.setStatus(SC_OK); if (shouldSendMonthlySpec11Email()) { @@ -125,18 +125,18 @@ public class PublishSpec11ReportAction implements Runnable { response.setStatus(SC_NO_CONTENT); } } - break; - case JOB_FAILED: + } + case JOB_FAILED -> { logger.atSevere().log("Dataflow job %s finished unsuccessfully.", jobId); response.setStatus(SC_NO_CONTENT); emailUtils.sendAlertEmail( String.format("Spec11 Dataflow Pipeline Failure %s", date), String.format("Spec11 %s job %s ended in status failure.", date, jobId)); - break; - default: + } + default -> { logger.atInfo().log("Job in non-terminal state %s, retrying:", state); response.setStatus(SC_SERVICE_UNAVAILABLE); - break; + } } } catch (IOException | JSONException e) { logger.atSevere().withCause(e).log("Failed to publish Spec11 reports."); diff --git a/core/src/main/java/google/registry/request/Modules.java b/core/src/main/java/google/registry/request/Modules.java index ebd5712fc..2a0fe638e 100644 --- a/core/src/main/java/google/registry/request/Modules.java +++ b/core/src/main/java/google/registry/request/Modules.java @@ -37,8 +37,7 @@ public final class Modules { static UrlConnectionService provideUrlConnectionService() { return url -> { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - if (connection instanceof HttpsURLConnection) { - HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; + if (connection instanceof HttpsURLConnection httpsConnection) { SSLContext tls13Context = SSLContext.getInstance("TLSv1.3"); tls13Context.init(null, null, null); httpsConnection.setSSLSocketFactory(tls13Context.getSocketFactory()); diff --git a/core/src/main/java/google/registry/request/auth/RequestAuthenticator.java b/core/src/main/java/google/registry/request/auth/RequestAuthenticator.java index 817d45af1..b1a62c0c6 100644 --- a/core/src/main/java/google/registry/request/auth/RequestAuthenticator.java +++ b/core/src/main/java/google/registry/request/auth/RequestAuthenticator.java @@ -88,7 +88,7 @@ public class RequestAuthenticator { AuthResult authResult; switch (authMethod) { // API-based user authentication mechanisms, such as OIDC. - case API: + case API -> { for (AuthenticationMechanism authMechanism : apiAuthenticationMechanisms) { authResult = authMechanism.authenticate(req); if (authResult.isAuthenticated()) { @@ -97,15 +97,15 @@ public class RequestAuthenticator { return authResult; } } - break; + } // Legacy authentication via UserService - case LEGACY: + case LEGACY -> { authResult = legacyAuthenticationMechanism.authenticate(req); if (authResult.isAuthenticated()) { logger.atInfo().log("Authenticated via legacy auth: %s", authResult); return authResult; } - break; + } } } logger.atInfo().log("No authentication found."); diff --git a/core/src/main/java/google/registry/tmch/Marksdb.java b/core/src/main/java/google/registry/tmch/Marksdb.java index 51727f5c0..501cb7918 100644 --- a/core/src/main/java/google/registry/tmch/Marksdb.java +++ b/core/src/main/java/google/registry/tmch/Marksdb.java @@ -77,13 +77,12 @@ public final class Marksdb { "No OpenPGP packets found in signature.\n%s", dumpHex(signature))); } - if (!(object instanceof PGPSignatureList)) { + if (!(object instanceof PGPSignatureList sigs)) { throw new SignatureException(String.format( "Expected PGPSignatureList packet but got %s\n%s", object.getClass().getSimpleName(), dumpHex(signature))); } - PGPSignatureList sigs = (PGPSignatureList) object; if (sigs.isEmpty()) { throw new SignatureException(String.format( "PGPSignatureList doesn't have a PGPSignature.\n%s", diff --git a/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java b/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java index 8c0c52812..3d95ab1c6 100644 --- a/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java +++ b/core/src/main/java/google/registry/tmch/TmchCertificateAuthority.java @@ -80,7 +80,7 @@ public final class TmchCertificateAuthority { private static final LoadingCache CRL_CACHE = CacheUtils.newCacheBuilder(getSingletonCacheRefreshDuration()) .build( - new CacheLoader() { + new CacheLoader<>() { @Override public X509CRL load(final TmchCaMode tmchCaMode) throws GeneralSecurityException { Optional storedCrl = TmchCrl.get(); diff --git a/core/src/main/java/google/registry/tmch/TmchXmlSignature.java b/core/src/main/java/google/registry/tmch/TmchXmlSignature.java index a1f772db5..da3b0eabb 100644 --- a/core/src/main/java/google/registry/tmch/TmchXmlSignature.java +++ b/core/src/main/java/google/registry/tmch/TmchXmlSignature.java @@ -158,11 +158,9 @@ public class TmchXmlSignature { return null; } for (Object keyInfoChild : keyInfo.getContent()) { - if (keyInfoChild instanceof X509Data) { - X509Data x509Data = (X509Data) keyInfoChild; + if (keyInfoChild instanceof X509Data x509Data) { for (Object x509DataChild : x509Data.getContent()) { - if (x509DataChild instanceof X509Certificate) { - X509Certificate cert = (X509Certificate) x509DataChild; + if (x509DataChild instanceof X509Certificate cert) { try { tmchCertificateAuthority.verify(cert); } catch (SignatureException e) { diff --git a/core/src/main/java/google/registry/tools/AuthModule.java b/core/src/main/java/google/registry/tools/AuthModule.java index 9fbc750fe..be957689e 100644 --- a/core/src/main/java/google/registry/tools/AuthModule.java +++ b/core/src/main/java/google/registry/tools/AuthModule.java @@ -150,7 +150,7 @@ public class AuthModule { @Nullable @Config("credentialFilePath") String credentialFilePath) { try { if (credentialFilePath != null) { - return new String(Files.readAllBytes(Paths.get(credentialFilePath)), UTF_8); + return Files.readString(Paths.get(credentialFilePath)); } else { return new Gson() .toJson( diff --git a/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java b/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java index 35c27ec79..719678632 100644 --- a/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java +++ b/core/src/main/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java @@ -15,7 +15,6 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Predicates.isNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; @@ -36,7 +35,7 @@ import google.registry.tools.params.KeyValueMapParameter.CurrencyUnitToStringMap import google.registry.tools.params.OptionalLongParameter; import google.registry.tools.params.OptionalPhoneNumberParameter; import google.registry.tools.params.OptionalStringParameter; -import google.registry.tools.params.PathParameter; +import google.registry.tools.params.PathParameter.InputFile; import google.registry.tools.params.StringListParameter; import google.registry.util.CidrAddressBlock; import java.nio.file.Files; @@ -46,6 +45,7 @@ import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import javax.inject.Inject; @@ -129,7 +129,7 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { @Parameter( names = "--cert_file", description = "File containing client certificate (X.509 PEM)", - validateWith = PathParameter.InputFile.class) + validateWith = InputFile.class) Path clientCertificateFilename; @Parameter( @@ -143,7 +143,7 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { @Parameter( names = "--failover_cert_file", description = "File containing failover client certificate (X.509 PEM)", - validateWith = PathParameter.InputFile.class) + validateWith = InputFile.class) Path failoverClientCertificateFilename; @Parameter( @@ -293,24 +293,13 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { // On creates, fall back to ICANN referral email (if present). builder.setEmailAddress(icannReferralEmail); } - if (url != null) { - builder.setUrl(url.orElse(null)); - } - if (phone != null) { - builder.setPhoneNumber(phone.orElse(null)); - } - if (fax != null) { - builder.setFaxNumber(fax.orElse(null)); - } - if (registrarType != null) { - builder.setType(registrarType); - } - if (registrarState != null) { - builder.setState(registrarState); - } - if (driveFolderId != null) { - builder.setDriveFolderId(driveFolderId.orElse(null)); - } + Optional.ofNullable(url).ifPresent(u -> builder.setUrl(u.orElse(null))); + Optional.ofNullable(phone).ifPresent(p -> builder.setPhoneNumber(p.orElse(null))); + Optional.ofNullable(fax).ifPresent(f -> builder.setFaxNumber(f.orElse(null))); + Optional.ofNullable(registrarType).ifPresent(builder::setType); + Optional.ofNullable(registrarState).ifPresent(builder::setState); + Optional.ofNullable(driveFolderId).ifPresent(d -> builder.setDriveFolderId(d.orElse(null))); + if (!allowedTlds.isEmpty() || !addAllowedTlds.isEmpty()) { checkModifyAllowedTlds(oldRegistrar); } @@ -338,7 +327,7 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { ipAllowList.stream().map(CidrAddressBlock::create).collect(toImmutableList())); } if (clientCertificateFilename != null) { - String asciiCert = new String(Files.readAllBytes(clientCertificateFilename), US_ASCII); + String asciiCert = Files.readString(clientCertificateFilename, US_ASCII); // An empty certificate file is allowed in order to provide a functionality for removing an // existing certificate without providing a replacement. An uploaded empty certificate file // will prevent the registrar from being able to establish EPP connections. @@ -361,16 +350,13 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { } if (failoverClientCertificateFilename != null) { - String asciiCert = - new String(Files.readAllBytes(failoverClientCertificateFilename), US_ASCII); + String asciiCert = Files.readString(failoverClientCertificateFilename, US_ASCII); if (!asciiCert.equals("")) { certificateChecker.validateCertificate(asciiCert); } builder.setFailoverClientCertificate(asciiCert, now); } - if (ianaId != null) { - builder.setIanaIdentifier(ianaId.orElse(null)); - } + Optional.ofNullable(ianaId).ifPresent(i -> builder.setIanaIdentifier(i.orElse(null))); Optional.ofNullable(poNumber).ifPresent(builder::setPoNumber); if (billingAccountMap != null) { LinkedHashMap newBillingAccountMap = new LinkedHashMap<>(); @@ -384,8 +370,8 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { } List streetAddressFields = Arrays.asList(street, city, state, zip, countryCode); checkArgument( - streetAddressFields.stream().anyMatch(isNull()) - == streetAddressFields.stream().allMatch(isNull()), + streetAddressFields.stream().anyMatch(Objects::isNull) + == streetAddressFields.stream().allMatch(Objects::isNull), "Must specify all fields of address"); if (street != null) { // We always set the localized address for now. That should be safe to do since it supports diff --git a/core/src/main/java/google/registry/tools/EppToolCommand.java b/core/src/main/java/google/registry/tools/EppToolCommand.java index a7ca8dcd3..c3bdcf69b 100644 --- a/core/src/main/java/google/registry/tools/EppToolCommand.java +++ b/core/src/main/java/google/registry/tools/EppToolCommand.java @@ -61,14 +61,7 @@ abstract class EppToolCommand extends ConfirmingCommand implements CommandWithCo private ServiceConnection connection; - static class XmlEppParameters { - final String clientId; - final String xml; - - XmlEppParameters(String clientId, String xml) { - this.clientId = clientId; - this.xml = xml; - } + record XmlEppParameters(String clientId, String xml) { @Override public String toString() { diff --git a/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java b/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java index 8bed1eaeb..efb1bc3ed 100644 --- a/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java +++ b/core/src/main/java/google/registry/tools/GenerateDnsReportCommand.java @@ -62,7 +62,7 @@ final class GenerateDnsReportCommand implements Command { @Override public void run() throws Exception { assertTldExists(tld); - Files.write(output, new Generator().generate().getBytes(US_ASCII)); + Files.writeString(output, new Generator().generate(), US_ASCII); } private class Generator { diff --git a/core/src/main/java/google/registry/tools/GetKeyringSecretCommand.java b/core/src/main/java/google/registry/tools/GetKeyringSecretCommand.java index f41db23ce..62bc1e410 100644 --- a/core/src/main/java/google/registry/tools/GetKeyringSecretCommand.java +++ b/core/src/main/java/google/registry/tools/GetKeyringSecretCommand.java @@ -55,58 +55,42 @@ final class GetKeyringSecretCommand implements Command { Security.addProvider(new BouncyCastleProvider()); switch (keyringKeyName) { - case BRDA_RECEIVER_PUBLIC_KEY: - out.write(KeySerializer.serializePublicKey(keyring.getBrdaReceiverKey())); - break; - case BRDA_SIGNING_KEY_PAIR: - out.write(KeySerializer.serializeKeyPair(keyring.getBrdaSigningKey())); - break; - case BRDA_SIGNING_PUBLIC_KEY: - out.write(KeySerializer.serializePublicKey(keyring.getBrdaSigningKey().getPublicKey())); - break; - case BSA_API_KEY: - out.write(KeySerializer.serializeString(keyring.getBsaApiKey())); - break; - case ICANN_REPORTING_PASSWORD: - out.write(KeySerializer.serializeString(keyring.getIcannReportingPassword())); - break; - case SAFE_BROWSING_API_KEY: - out.write(KeySerializer.serializeString(keyring.getSafeBrowsingAPIKey())); - break; - case MARKSDB_DNL_LOGIN_AND_PASSWORD: - out.write(KeySerializer.serializeString(keyring.getMarksdbDnlLoginAndPassword())); - break; - case MARKSDB_LORDN_PASSWORD: - out.write(KeySerializer.serializeString(keyring.getMarksdbLordnPassword())); - break; - case MARKSDB_SMDRL_LOGIN_AND_PASSWORD: - out.write(KeySerializer.serializeString(keyring.getMarksdbSmdrlLoginAndPassword())); - break; - case RDE_RECEIVER_PUBLIC_KEY: - out.write(KeySerializer.serializePublicKey(keyring.getRdeReceiverKey())); - break; - case RDE_SIGNING_KEY_PAIR: - out.write(KeySerializer.serializeKeyPair(keyring.getRdeSigningKey())); - break; - case RDE_SIGNING_PUBLIC_KEY: - out.write(KeySerializer.serializePublicKey(keyring.getRdeSigningKey().getPublicKey())); - break; - case RDE_SSH_CLIENT_PRIVATE_KEY: - out.write(KeySerializer.serializeString(keyring.getRdeSshClientPrivateKey())); - break; - case RDE_SSH_CLIENT_PUBLIC_KEY: - out.write(KeySerializer.serializeString(keyring.getRdeSshClientPublicKey())); - break; - case RDE_STAGING_KEY_PAIR: - // Note that we're saving a key pair rather than just the private key because we can't - // serialize a private key on its own. See {@link KeySerializer}. - out.write(KeySerializer.serializeKeyPair( - new PGPKeyPair( - keyring.getRdeStagingEncryptionKey(), keyring.getRdeStagingDecryptionKey()))); - break; - case RDE_STAGING_PUBLIC_KEY: - out.write(KeySerializer.serializePublicKey(keyring.getRdeStagingEncryptionKey())); - break; + case BRDA_RECEIVER_PUBLIC_KEY -> + out.write(KeySerializer.serializePublicKey(keyring.getBrdaReceiverKey())); + case BRDA_SIGNING_KEY_PAIR -> + out.write(KeySerializer.serializeKeyPair(keyring.getBrdaSigningKey())); + case BRDA_SIGNING_PUBLIC_KEY -> + out.write(KeySerializer.serializePublicKey(keyring.getBrdaSigningKey().getPublicKey())); + case BSA_API_KEY -> out.write(KeySerializer.serializeString(keyring.getBsaApiKey())); + case ICANN_REPORTING_PASSWORD -> + out.write(KeySerializer.serializeString(keyring.getIcannReportingPassword())); + case SAFE_BROWSING_API_KEY -> + out.write(KeySerializer.serializeString(keyring.getSafeBrowsingAPIKey())); + case MARKSDB_DNL_LOGIN_AND_PASSWORD -> + out.write(KeySerializer.serializeString(keyring.getMarksdbDnlLoginAndPassword())); + case MARKSDB_LORDN_PASSWORD -> + out.write(KeySerializer.serializeString(keyring.getMarksdbLordnPassword())); + case MARKSDB_SMDRL_LOGIN_AND_PASSWORD -> + out.write(KeySerializer.serializeString(keyring.getMarksdbSmdrlLoginAndPassword())); + case RDE_RECEIVER_PUBLIC_KEY -> + out.write(KeySerializer.serializePublicKey(keyring.getRdeReceiverKey())); + case RDE_SIGNING_KEY_PAIR -> + out.write(KeySerializer.serializeKeyPair(keyring.getRdeSigningKey())); + case RDE_SIGNING_PUBLIC_KEY -> + out.write(KeySerializer.serializePublicKey(keyring.getRdeSigningKey().getPublicKey())); + case RDE_SSH_CLIENT_PRIVATE_KEY -> + out.write(KeySerializer.serializeString(keyring.getRdeSshClientPrivateKey())); + case RDE_SSH_CLIENT_PUBLIC_KEY -> + out.write(KeySerializer.serializeString(keyring.getRdeSshClientPublicKey())); + case RDE_STAGING_KEY_PAIR -> + // Note that we're saving a key pair rather than just the private key because we can't + // serialize a private key on its own. See {@link KeySerializer}. + out.write( + KeySerializer.serializeKeyPair( + new PGPKeyPair( + keyring.getRdeStagingEncryptionKey(), keyring.getRdeStagingDecryptionKey()))); + case RDE_STAGING_PUBLIC_KEY -> + out.write(KeySerializer.serializePublicKey(keyring.getRdeStagingEncryptionKey())); } } } diff --git a/core/src/main/java/google/registry/tools/GhostrydeCommand.java b/core/src/main/java/google/registry/tools/GhostrydeCommand.java index e34a300ef..985155209 100644 --- a/core/src/main/java/google/registry/tools/GhostrydeCommand.java +++ b/core/src/main/java/google/registry/tools/GhostrydeCommand.java @@ -76,7 +76,7 @@ final class GhostrydeCommand implements Command { Provider rdeStagingDecryptionKey; @Override - public final void run() throws Exception { + public void run() throws Exception { checkArgument(encrypt ^ decrypt, "Please specify either --encrypt or --decrypt"); if (encrypt) { checkArgumentNotNull(output, "--output path is required in --encrypt mode"); diff --git a/core/src/main/java/google/registry/tools/GsonUtils.java b/core/src/main/java/google/registry/tools/GsonUtils.java index 96a22dc4d..bcaf690ea 100644 --- a/core/src/main/java/google/registry/tools/GsonUtils.java +++ b/core/src/main/java/google/registry/tools/GsonUtils.java @@ -54,7 +54,7 @@ public class GsonUtils { if (!GsonPostProcessable.class.isAssignableFrom(type.getRawType())) { return originalAdapter; } - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public void write(JsonWriter out, T value) throws IOException { originalAdapter.write(out, value); diff --git a/core/src/main/java/google/registry/tools/ListObjectsCommand.java b/core/src/main/java/google/registry/tools/ListObjectsCommand.java index 0195ad38f..3592c2fd5 100644 --- a/core/src/main/java/google/registry/tools/ListObjectsCommand.java +++ b/core/src/main/java/google/registry/tools/ListObjectsCommand.java @@ -98,10 +98,9 @@ abstract class ListObjectsCommand implements CommandWithConnection { if (obj == null) { throw new VerifyException("Server returned no status"); } - if (!(obj instanceof String)) { + if (!(obj instanceof String status)) { throw new VerifyException("Server returned non-string status"); } - String status = (String) obj; // Handle errors. if (status.equals("error")) { obj = responseMap.get("error"); diff --git a/core/src/main/java/google/registry/tools/LoginCommand.java b/core/src/main/java/google/registry/tools/LoginCommand.java index 14eef9959..b63460762 100644 --- a/core/src/main/java/google/registry/tools/LoginCommand.java +++ b/core/src/main/java/google/registry/tools/LoginCommand.java @@ -52,12 +52,22 @@ final class LoginCommand implements Command { url -> { int remotePort = forwardingServerReceiver.getRemotePort(); System.out.printf( - "Please first run the following command in a separate terminal on your local " - + "host:\n\n ssh -L %s:localhost:%s %s\n\n", + """ + Please first run the following command in a separate terminal on your local\ + host: + + ssh -L %s:localhost:%s %s + + """, port, remotePort, remoteHost); System.out.printf( - "Please then open the following URL in your local browser and follow the" - + " instructions:\n\n %s\n\n", + """ + Please then open the following URL in your local browser and follow the\ + instructions: + + %s + + """, url); }); } else { diff --git a/core/src/main/java/google/registry/tools/MutatingCommand.java b/core/src/main/java/google/registry/tools/MutatingCommand.java index b72778ee6..a39cfec71 100644 --- a/core/src/main/java/google/registry/tools/MutatingCommand.java +++ b/core/src/main/java/google/registry/tools/MutatingCommand.java @@ -159,15 +159,18 @@ public abstract class MutatingCommand extends ConfirmingCommand { ? ((ImmutableObject) existingEntity.get()).toDiffableFieldMap() : ImmutableMap.of())); switch (change.type) { - case CREATE: + case CREATE -> { tm().insert(change.newEntity); return; - case UPDATE: + } + case UPDATE -> { tm().update(change.newEntity); return; - case DELETE: + } + case DELETE -> { tm().delete(change.vKey); return; + } } throw new UnsupportedOperationException("Unknown entity change type: " + change.type); } diff --git a/core/src/main/java/google/registry/tools/PendingEscrowCommand.java b/core/src/main/java/google/registry/tools/PendingEscrowCommand.java index 539e85f0a..d3263b9a6 100644 --- a/core/src/main/java/google/registry/tools/PendingEscrowCommand.java +++ b/core/src/main/java/google/registry/tools/PendingEscrowCommand.java @@ -28,7 +28,7 @@ import javax.inject.Inject; final class PendingEscrowCommand implements Command { private static final Ordering SORTER = - new Ordering() { + new Ordering<>() { @Override public int compare(PendingDeposit left, PendingDeposit right) { return ComparisonChain.start() @@ -36,7 +36,8 @@ final class PendingEscrowCommand implements Command { .compare(left.mode(), right.mode()) .compare(left.watermark(), right.watermark()) .result(); - }}; + } + }; @Inject PendingDepositChecker checker; diff --git a/core/src/main/java/google/registry/tools/RegistrarPocCommand.java b/core/src/main/java/google/registry/tools/RegistrarPocCommand.java index 173545eb8..64c6c2ce4 100644 --- a/core/src/main/java/google/registry/tools/RegistrarPocCommand.java +++ b/core/src/main/java/google/registry/tools/RegistrarPocCommand.java @@ -20,7 +20,6 @@ import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.PreconditionsUtils.checkArgumentPresent; -import static java.nio.charset.StandardCharsets.UTF_8; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; @@ -194,16 +193,14 @@ final class RegistrarPocCommand extends MutatingCommand { } RegistrarPoc oldContact; switch (mode) { - case LIST: - listContacts(contacts); - break; - case CREATE: + case LIST -> listContacts(contacts); + case CREATE -> { stageEntityChange(null, createContact(registrar)); if (visibleInDomainWhoisAsAbuse != null && visibleInDomainWhoisAsAbuse) { unsetOtherWhoisAbuseFlags(contacts, null); } - break; - case UPDATE: + } + case UPDATE -> { oldContact = checkNotNull( contactsMap.get(checkNotNull(email, "--email is required when --mode=UPDATE")), @@ -219,8 +216,8 @@ final class RegistrarPocCommand extends MutatingCommand { if (visibleInDomainWhoisAsAbuse != null && visibleInDomainWhoisAsAbuse) { unsetOtherWhoisAbuseFlags(contacts, oldContact.getEmailAddress()); } - break; - case DELETE: + } + case DELETE -> { oldContact = checkNotNull( contactsMap.get(checkNotNull(email, "--email is required when --mode=DELETE")), @@ -230,9 +227,8 @@ final class RegistrarPocCommand extends MutatingCommand { !oldContact.getVisibleInDomainWhoisAsAbuse(), "Cannot delete the domain WHOIS abuse contact; set the flag on another contact first"); stageEntityChange(oldContact, null); - break; - default: - throw new AssertionError(); + } + default -> throw new AssertionError(); } if (MODES_REQUIRING_CONTACT_SYNC.contains(mode)) { stageEntityChange(registrar, registrar.asBuilder().setContactsRequireSyncing(true).build()); @@ -244,7 +240,7 @@ final class RegistrarPocCommand extends MutatingCommand { for (RegistrarPoc c : contacts) { result.add(c.toStringMultilinePlainText()); } - Files.write(output, Joiner.on('\n').join(result).getBytes(UTF_8)); + Files.writeString(output, Joiner.on('\n').join(result)); } private RegistrarPoc createContact(Registrar registrar) { diff --git a/core/src/main/java/google/registry/tools/RegistryCli.java b/core/src/main/java/google/registry/tools/RegistryCli.java index 23f679a66..0b3400ec6 100644 --- a/core/src/main/java/google/registry/tools/RegistryCli.java +++ b/core/src/main/java/google/registry/tools/RegistryCli.java @@ -191,9 +191,10 @@ final class RegistryCli implements CommandRunner { e.printStackTrace(); System.err.println("==================================================================="); System.err.println( - "This error is likely the result of having another instance of\n" - + "nomulus running at the same time. Check your system, shut down\n" - + "the other instance, and try again."); + """ + This error is likely the result of having another instance of + nomulus running at the same time. Check your system, shut down + the other instance, and try again."""); System.err.println("==================================================================="); } else { throw e; diff --git a/core/src/main/java/google/registry/tools/ServiceConnection.java b/core/src/main/java/google/registry/tools/ServiceConnection.java index 8ba86926e..3eaa2898b 100644 --- a/core/src/main/java/google/registry/tools/ServiceConnection.java +++ b/core/src/main/java/google/registry/tools/ServiceConnection.java @@ -163,18 +163,12 @@ public class ServiceConnection { } public static URL getServer(Service service) { - switch (service) { - case DEFAULT: - return RegistryConfig.getDefaultServer(); - case TOOLS: - return RegistryConfig.getToolsServer(); - case BACKEND: - return RegistryConfig.getBackendServer(); - case BSA: - return RegistryConfig.getBsaServer(); - case PUBAPI: - return RegistryConfig.getPubapiServer(); - } - throw new IllegalStateException("Unknown service: " + service); + return switch (service) { + case DEFAULT -> RegistryConfig.getDefaultServer(); + case TOOLS -> RegistryConfig.getToolsServer(); + case BACKEND -> RegistryConfig.getBackendServer(); + case BSA -> RegistryConfig.getBsaServer(); + case PUBAPI -> RegistryConfig.getPubapiServer(); + }; } } diff --git a/core/src/main/java/google/registry/tools/UpdateKeyringSecretCommand.java b/core/src/main/java/google/registry/tools/UpdateKeyringSecretCommand.java index 96e7a80a9..1bb4961ee 100644 --- a/core/src/main/java/google/registry/tools/UpdateKeyringSecretCommand.java +++ b/core/src/main/java/google/registry/tools/UpdateKeyringSecretCommand.java @@ -54,62 +54,48 @@ final class UpdateKeyringSecretCommand implements Command { byte[] input = Files.readAllBytes(inputPath); switch (keyringKeyName) { - case BRDA_RECEIVER_PUBLIC_KEY: - secretManagerKeyringUpdater.setBrdaReceiverPublicKey(deserializePublicKey(input)); - break; - case BRDA_SIGNING_KEY_PAIR: - secretManagerKeyringUpdater.setBrdaSigningKey(deserializeKeyPair(input)); - break; - case BRDA_SIGNING_PUBLIC_KEY: - throw new IllegalArgumentException( - "Can't update BRDA_SIGNING_PUBLIC_KEY directly." - + " Must update public and private keys together using BRDA_SIGNING_KEY_PAIR."); - case BSA_API_KEY: - secretManagerKeyringUpdater.setBsaApiKey(deserializeString(input)); - break; - case ICANN_REPORTING_PASSWORD: - secretManagerKeyringUpdater.setIcannReportingPassword(deserializeString(input)); - break; - case MARKSDB_DNL_LOGIN_AND_PASSWORD: - secretManagerKeyringUpdater.setMarksdbDnlLoginAndPassword(deserializeString(input)); - break; - case MARKSDB_LORDN_PASSWORD: - secretManagerKeyringUpdater.setMarksdbLordnPassword(deserializeString(input)); - break; - case MARKSDB_SMDRL_LOGIN_AND_PASSWORD: - secretManagerKeyringUpdater.setMarksdbSmdrlLoginAndPassword(deserializeString(input)); - break; - case RDE_RECEIVER_PUBLIC_KEY: - secretManagerKeyringUpdater.setRdeReceiverPublicKey(deserializePublicKey(input)); - break; - case RDE_SIGNING_KEY_PAIR: - secretManagerKeyringUpdater.setRdeSigningKey(deserializeKeyPair(input)); - break; - case RDE_SIGNING_PUBLIC_KEY: - throw new IllegalArgumentException( - "Can't update RDE_SIGNING_PUBLIC_KEY directly." - + " Must update public and private keys together using RDE_SIGNING_KEY_PAIR."); - // Note that RDE_SSH_CLIENT public / private keys are slightly different than other key pairs, - // since they are just regular strings rather than {@link PGPKeyPair}s (because OpenSSH - // doesn't use PGP-style keys) - // - // Hence we can and need to update the private and public keys individually. - case RDE_SSH_CLIENT_PRIVATE_KEY: - secretManagerKeyringUpdater.setRdeSshClientPrivateKey(deserializeString(input)); - break; - case RDE_SSH_CLIENT_PUBLIC_KEY: - secretManagerKeyringUpdater.setRdeSshClientPublicKey(deserializeString(input)); - break; - case RDE_STAGING_KEY_PAIR: - secretManagerKeyringUpdater.setRdeStagingKey(deserializeKeyPair(input)); - break; - case SAFE_BROWSING_API_KEY: - secretManagerKeyringUpdater.setSafeBrowsingAPIKey(deserializeString(input)); - break; - case RDE_STAGING_PUBLIC_KEY: - throw new IllegalArgumentException( - "Can't update RDE_STAGING_PUBLIC_KEY directly." - + " Must update public and private keys together using RDE_STAGING_KEY_PAIR."); + case BRDA_RECEIVER_PUBLIC_KEY -> + secretManagerKeyringUpdater.setBrdaReceiverPublicKey(deserializePublicKey(input)); + case BRDA_SIGNING_KEY_PAIR -> + secretManagerKeyringUpdater.setBrdaSigningKey(deserializeKeyPair(input)); + case BRDA_SIGNING_PUBLIC_KEY -> + throw new IllegalArgumentException( + "Can't update BRDA_SIGNING_PUBLIC_KEY directly." + + " Must update public and private keys together using BRDA_SIGNING_KEY_PAIR."); + case BSA_API_KEY -> secretManagerKeyringUpdater.setBsaApiKey(deserializeString(input)); + case ICANN_REPORTING_PASSWORD -> + secretManagerKeyringUpdater.setIcannReportingPassword(deserializeString(input)); + case MARKSDB_DNL_LOGIN_AND_PASSWORD -> + secretManagerKeyringUpdater.setMarksdbDnlLoginAndPassword(deserializeString(input)); + case MARKSDB_LORDN_PASSWORD -> + secretManagerKeyringUpdater.setMarksdbLordnPassword(deserializeString(input)); + case MARKSDB_SMDRL_LOGIN_AND_PASSWORD -> + secretManagerKeyringUpdater.setMarksdbSmdrlLoginAndPassword(deserializeString(input)); + case RDE_RECEIVER_PUBLIC_KEY -> + secretManagerKeyringUpdater.setRdeReceiverPublicKey(deserializePublicKey(input)); + case RDE_SIGNING_KEY_PAIR -> + secretManagerKeyringUpdater.setRdeSigningKey(deserializeKeyPair(input)); + case RDE_SIGNING_PUBLIC_KEY -> + throw new IllegalArgumentException( + "Can't update RDE_SIGNING_PUBLIC_KEY directly." + + " Must update public and private keys together using RDE_SIGNING_KEY_PAIR."); + // Note that RDE_SSH_CLIENT public / private keys are slightly different than other key + // pairs, since they are just regular strings rather than {@link PGPKeyPair}s (because + // OpenSSH doesn't use PGP-style keys) + // + // Hence we can and need to update the private and public keys individually. + case RDE_SSH_CLIENT_PRIVATE_KEY -> + secretManagerKeyringUpdater.setRdeSshClientPrivateKey(deserializeString(input)); + case RDE_SSH_CLIENT_PUBLIC_KEY -> + secretManagerKeyringUpdater.setRdeSshClientPublicKey(deserializeString(input)); + case RDE_STAGING_KEY_PAIR -> + secretManagerKeyringUpdater.setRdeStagingKey(deserializeKeyPair(input)); + case SAFE_BROWSING_API_KEY -> + secretManagerKeyringUpdater.setSafeBrowsingAPIKey(deserializeString(input)); + case RDE_STAGING_PUBLIC_KEY -> + throw new IllegalArgumentException( + "Can't update RDE_STAGING_PUBLIC_KEY directly." + + " Must update public and private keys together using RDE_STAGING_KEY_PAIR."); } secretManagerKeyringUpdater.update(); diff --git a/core/src/main/java/google/registry/tools/javascrap/RecreateBillingRecurrencesCommand.java b/core/src/main/java/google/registry/tools/javascrap/RecreateBillingRecurrencesCommand.java index 64f49a353..f003e6165 100644 --- a/core/src/main/java/google/registry/tools/javascrap/RecreateBillingRecurrencesCommand.java +++ b/core/src/main/java/google/registry/tools/javascrap/RecreateBillingRecurrencesCommand.java @@ -60,11 +60,12 @@ public class RecreateBillingRecurrencesCommand extends ConfirmingCommand { ImmutableList newRecurrences = convertRecurrencesWithoutSaving(existingRecurrences); return String.format( - "Create new BillingRecurrence(s)?\n" - + "Existing recurrences:\n" - + "%s\n" - + "New recurrences:\n" - + "%s", + """ + Create new BillingRecurrence(s)? + Existing recurrences: + %s + New recurrences: + %s""", Joiner.on('\n').join(existingRecurrences), Joiner.on('\n').join(newRecurrences)); }); } diff --git a/core/src/main/java/google/registry/ui/server/SoyTemplateUtils.java b/core/src/main/java/google/registry/ui/server/SoyTemplateUtils.java index a7ece3b08..dc177f0b4 100644 --- a/core/src/main/java/google/registry/ui/server/SoyTemplateUtils.java +++ b/core/src/main/java/google/registry/ui/server/SoyTemplateUtils.java @@ -90,14 +90,11 @@ public final class SoyTemplateUtils { private static ImmutableMap getCssRenames(URL cssMap, URL cssMapDebug) { try { - switch (ConsoleDebug.get()) { - case RAW: - return ImmutableMap.of(); // See firstNonNull() above for clarification. - case DEBUG: - return extractCssRenames(Resources.toString(cssMapDebug, UTF_8)); - default: - return extractCssRenames(Resources.toString(cssMap, UTF_8)); - } + return switch (ConsoleDebug.get()) { + case RAW -> ImmutableMap.of(); // See firstNonNull() above for clarification. + case DEBUG -> extractCssRenames(Resources.toString(cssMapDebug, UTF_8)); + default -> extractCssRenames(Resources.toString(cssMap, UTF_8)); + }; } catch (IOException e) { throw new RuntimeException("Failed to load css map", e); } diff --git a/core/src/main/java/google/registry/ui/server/console/ConsoleUserDataAction.java b/core/src/main/java/google/registry/ui/server/console/ConsoleUserDataAction.java index 314013cf3..8258314e7 100644 --- a/core/src/main/java/google/registry/ui/server/console/ConsoleUserDataAction.java +++ b/core/src/main/java/google/registry/ui/server/console/ConsoleUserDataAction.java @@ -22,6 +22,7 @@ import google.registry.config.RegistryConfig.Config; import google.registry.model.console.User; import google.registry.request.Action; import google.registry.request.auth.Auth; +import google.registry.security.XsrfTokenManager; import google.registry.ui.server.registrar.ConsoleApiParams; import jakarta.servlet.http.Cookie; import javax.inject.Inject; @@ -61,7 +62,7 @@ public class ConsoleUserDataAction extends ConsoleApiAction { // for angular to read - https://angular.io/guide/http-security-xsrf-protection Cookie xsrfCookie = new Cookie( - consoleApiParams.xsrfTokenManager().X_CSRF_TOKEN, + XsrfTokenManager.X_CSRF_TOKEN, consoleApiParams.xsrfTokenManager().generateToken(user.getEmailAddress())); xsrfCookie.setSecure(true); consoleApiParams.response().addCookie(xsrfCookie); diff --git a/core/src/main/java/google/registry/ui/server/registrar/ConsoleOteSetupAction.java b/core/src/main/java/google/registry/ui/server/registrar/ConsoleOteSetupAction.java index 8c3b6dc61..10cdac2af 100644 --- a/core/src/main/java/google/registry/ui/server/registrar/ConsoleOteSetupAction.java +++ b/core/src/main/java/google/registry/ui/server/registrar/ConsoleOteSetupAction.java @@ -27,6 +27,7 @@ import com.google.template.soy.tofu.SoyTofu; import google.registry.model.OteAccountBuilder; import google.registry.request.Action; import google.registry.request.Action.Method; +import google.registry.request.HttpException.BadRequestException; import google.registry.request.Parameter; import google.registry.request.auth.Auth; import google.registry.request.auth.AuthenticatedRegistrarAccessor; @@ -106,14 +107,16 @@ public final class ConsoleOteSetupAction extends HtmlAction { return; } switch (method) { - case POST: + case POST -> { runPost(data); - return; - case GET: + } + case GET -> { runGet(data); - return; - default: - return; + } + default -> { + throw new BadRequestException( + String.format("Action cannot be called with method %s", method)); + } } } diff --git a/core/src/main/java/google/registry/ui/server/registrar/ConsoleRegistrarCreatorAction.java b/core/src/main/java/google/registry/ui/server/registrar/ConsoleRegistrarCreatorAction.java index c65349fec..e0097488e 100644 --- a/core/src/main/java/google/registry/ui/server/registrar/ConsoleRegistrarCreatorAction.java +++ b/core/src/main/java/google/registry/ui/server/registrar/ConsoleRegistrarCreatorAction.java @@ -33,6 +33,7 @@ import google.registry.model.registrar.RegistrarPoc; import google.registry.request.Action; import google.registry.request.Action.Method; import google.registry.request.Action.Service; +import google.registry.request.HttpException.BadRequestException; import google.registry.request.Parameter; import google.registry.request.auth.Auth; import google.registry.request.auth.AuthenticatedRegistrarAccessor; @@ -128,14 +129,16 @@ public final class ConsoleRegistrarCreatorAction extends HtmlAction { return; } switch (method) { - case POST: + case POST -> { runPost(data); - return; - case GET: + } + case GET -> { runGet(data); - return; - default: - return; + } + default -> { + throw new BadRequestException( + String.format("Action cannot be called with method %s", method)); + } } } diff --git a/core/src/main/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java b/core/src/main/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java index c80fa4909..79fa179bc 100644 --- a/core/src/main/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java +++ b/core/src/main/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java @@ -154,20 +154,16 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA "Received request '%s' on registrar '%s' with args %s", op, registrarId, args); String status = "SUCCESS"; try { - switch (op) { - case "update": - return update(args, registrarId).toJsonResponse(); - case "read": - return read(registrarId).toJsonResponse(); - default: - throw new IllegalArgumentException("Unknown or unsupported operation: " + op); - } + return switch (op) { + case "update" -> update(args, registrarId).toJsonResponse(); + case "read" -> read(registrarId).toJsonResponse(); + default -> throw new IllegalArgumentException("Unknown or unsupported operation: " + op); + }; } catch (Throwable e) { logger.atWarning().withCause(e).log( "Failed to perform operation '%s' on registrar '%s' for args %s", op, registrarId, args); status = "ERROR: " + e.getClass().getSimpleName(); - if (e instanceof FormFieldException) { - FormFieldException formFieldException = (FormFieldException) e; + if (e instanceof FormFieldException formFieldException) { return JsonResponseHelper.createFormFieldError( formFieldException.getMessage(), formFieldException.getFieldName()); } @@ -641,8 +637,11 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA "Registrar %s (%s) updated in registry %s environment", existingRegistrar.getRegistrarName(), existingRegistrar.getRegistrarId(), environment), String.format( - "The following changes were made in registry %s environment to " - + "the registrar %s by %s:\n\n%s", + """ + The following changes were made in registry %s environment to the registrar %s by\ + %s: + + %s""", environment, existingRegistrar.getRegistrarId(), authResult.userIdForLogging(), diff --git a/core/src/main/java/google/registry/ui/server/registrar/RegistryLockPostAction.java b/core/src/main/java/google/registry/ui/server/registrar/RegistryLockPostAction.java index e268d9fca..41274c092 100644 --- a/core/src/main/java/google/registry/ui/server/registrar/RegistryLockPostAction.java +++ b/core/src/main/java/google/registry/ui/server/registrar/RegistryLockPostAction.java @@ -75,8 +75,11 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc private static final Gson GSON = new Gson(); private static final String VERIFICATION_EMAIL_TEMPLATE = - "Please click the link below to perform the lock / unlock action on domain %s. Note: " - + "this code will expire in one hour.\n\n%s"; + """ + Please click the link below to perform the lock / unlock action on domain %s. Note: this\ + code will expire in one hour. + + %s"""; private final HttpServletRequest req; private final JsonActionRunner jsonActionRunner; diff --git a/core/src/main/java/google/registry/xml/XmlTransformer.java b/core/src/main/java/google/registry/xml/XmlTransformer.java index 41de0de95..ca0933c6d 100644 --- a/core/src/main/java/google/registry/xml/XmlTransformer.java +++ b/core/src/main/java/google/registry/xml/XmlTransformer.java @@ -148,9 +148,8 @@ public class XmlTransformer { XML_INPUT_FACTORY.createXMLStreamReader(new StreamSource(autoClosingStream, SYSTEM_ID)))); } catch (UnmarshalException e) { // Plain old parsing exceptions have a SAXParseException with no further cause. - if (e.getLinkedException() instanceof SAXParseException + if (e.getLinkedException() instanceof SAXParseException sae && e.getLinkedException().getCause() == null) { - SAXParseException sae = (SAXParseException) e.getLinkedException(); throw new XmlException(String.format( "Syntax error at line %d, column %d: %s", sae.getLineNumber(), @@ -158,8 +157,7 @@ public class XmlTransformer { nullToEmpty(sae.getMessage()).replaceAll(""", ""))); } // These get thrown for attempted XXE attacks. - if (e.getLinkedException() instanceof XMLStreamException) { - XMLStreamException xse = (XMLStreamException) e.getLinkedException(); + if (e.getLinkedException() instanceof XMLStreamException xse) { throw new XmlException(String.format( "Syntax error at line %d, column %d: %s", xse.getLocation().getLineNumber(), diff --git a/core/src/nonprod/java/google/registry/tools/GenerateSqlSchemaCommand.java b/core/src/nonprod/java/google/registry/tools/GenerateSqlSchemaCommand.java index dea597191..834bfbabf 100644 --- a/core/src/nonprod/java/google/registry/tools/GenerateSqlSchemaCommand.java +++ b/core/src/nonprod/java/google/registry/tools/GenerateSqlSchemaCommand.java @@ -14,8 +14,6 @@ package google.registry.tools; -import static java.nio.charset.StandardCharsets.UTF_8; - import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.annotations.VisibleForTesting; @@ -94,15 +92,21 @@ public class GenerateSqlSchemaCommand implements Command { databasePort = postgresContainer.getMappedPort(POSTGRESQL_PORT); } else if (databaseHost == null) { System.err.println( - "You must specify either --start_postgresql to start a PostgreSQL database in a\n" - + "docker instance, or specify --db_host (and, optionally, --db_port) to identify\n" - + "the location of a running instance. To start a long-lived instance (suitable\n" - + "for running this command multiple times) run this:\n\n" - + " docker run --rm --name some-postgres -e POSTGRES_PASSWORD=domain-registry \\\n" - + " -d postgres:9.6.12\n\n" - + "Copy the container id output from the command, then run:\n\n" - + " docker inspect | grep IPAddress\n\n" - + "To obtain the value for --db-host.\n"); + """ + You must specify either --start_postgresql to start a PostgreSQL database in a + docker instance, or specify --db_host (and, optionally, --db_port) to identify + the location of a running instance. To start a long-lived instance (suitable + for running this command multiple times) run this: + + docker run --rm --name some-postgres -e POSTGRES_PASSWORD=domain-registry \\ + -d postgres:9.6.12 + + Copy the container id output from the command, then run: + + docker inspect | grep IPAddress + + To obtain the value for --db-host. + """); // TODO(mmuller): need exit(1), see above. return; } @@ -119,21 +123,23 @@ public class GenerateSqlSchemaCommand implements Command { // appends to the existing file, so this has the additional desired effect of clearing any // existing data in the file. String copyright = - "-- Copyright 2019 The Nomulus Authors. All Rights Reserved.\n" - + "--\n" - + "-- Licensed under the Apache License, Version 2.0 (the \"License\");\n" - + "-- you may not use this file except in compliance with the License.\n" - + "-- You may obtain a copy of the License at\n" - + "--\n" - + "-- http://www.apache.org/licenses/LICENSE-2.0\n" - + "--\n" - + "-- Unless required by applicable law or agreed to in writing, software\n" - + "-- distributed under the License is distributed on an \"AS IS\" BASIS,\n" - + "-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" - + "-- See the License for the specific language governing permissions and\n" - + "-- limitations under the License.\n"; + """ + -- Copyright 2019 The Nomulus Authors. All Rights Reserved. + -- + -- Licensed under the Apache License, Version 2.0 (the "License"); + -- you may not use this file except in compliance with the License. + -- You may obtain a copy of the License at + -- + -- http://www.apache.org/licenses/LICENSE-2.0 + -- + -- Unless required by applicable law or agreed to in writing, software + -- distributed under the License is distributed on an "AS IS" BASIS, + -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + -- See the License for the specific language governing permissions and + -- limitations under the License. + """; try { - Files.write(outputFile.toPath(), copyright.getBytes(UTF_8)); + Files.writeString(outputFile.toPath(), copyright); } catch (IOException e) { System.err.println("Error writing sql file: " + e); e.printStackTrace(); diff --git a/core/src/test/java/google/registry/batch/RelockDomainActionTest.java b/core/src/test/java/google/registry/batch/RelockDomainActionTest.java index 219874073..d0eb1814f 100644 --- a/core/src/test/java/google/registry/batch/RelockDomainActionTest.java +++ b/core/src/test/java/google/registry/batch/RelockDomainActionTest.java @@ -254,8 +254,10 @@ public class RelockDomainActionTest { EmailMessage.newBuilder() .setSubject("Successful re-lock of domain example.tld") .setBody( - "The domain example.tld was successfully re-locked.\n\nPlease " - + "contact support at support@example.com if you have any questions.") + """ + The domain example.tld was successfully re-locked. + + Please contact support at support@example.com if you have any questions.""") .setRecipients( ImmutableSet.of(new InternetAddress("Marla.Singer.RegistryLock@crr.com"))) .build(); @@ -265,8 +267,10 @@ public class RelockDomainActionTest { private void assertNonTransientFailureEmail(String exceptionMessage) throws Exception { String expectedBody = String.format( - "There was an error when automatically re-locking example.tld. Error message: %s\n\n" - + "Please contact support at support@example.com if you have any questions.", + """ + There was an error when automatically re-locking example.tld. Error message: %s + + Please contact support at support@example.com if you have any questions.""", exceptionMessage); assertFailureEmailWithBody( expectedBody, ImmutableSet.of(new InternetAddress("Marla.Singer.RegistryLock@crr.com"))); diff --git a/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java b/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java index 2b0cd2b1a..a76a21655 100644 --- a/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java +++ b/core/src/test/java/google/registry/batch/SendExpiringCertificateNotificationEmailActionTest.java @@ -56,18 +56,14 @@ import org.junit.jupiter.api.extension.RegisterExtension; class SendExpiringCertificateNotificationEmailActionTest { private static final String EXPIRATION_WARNING_EMAIL_BODY_TEXT = - " Dear %1$s,\n" - + '\n' - + "We would like to inform you that your %2$s certificate will expire at %3$s." - + '\n' - + " Kind update your account using the following steps: " - + '\n' - + " 1. Navigate to support and login using your %4$s@registry.example credentials.\n" - + " 2. Click Settings -> Privacy on the top left corner.\n" - + " 3. Click Edit and enter certificate string." - + " 3. Click Save" - + "Regards," - + "Example Registry"; + """ + Dear %1$s, + + We would like to inform you that your %2$s certificate will expire at %3$s. + Kind update your account using the following steps: + 1. Navigate to support and login using your %4$s@registry.example credentials. + 2. Click Settings -> Privacy on the top left corner. + 3. Click Edit and enter certificate string. 3. Click SaveRegards,Example Registry"""; private static final String EXPIRATION_WARNING_EMAIL_SUBJECT_TEXT = "Expiration Warning Email"; diff --git a/core/src/test/java/google/registry/beam/BeamActionTestBase.java b/core/src/test/java/google/registry/beam/BeamActionTestBase.java index e6c9023dd..648802291 100644 --- a/core/src/test/java/google/registry/beam/BeamActionTestBase.java +++ b/core/src/test/java/google/registry/beam/BeamActionTestBase.java @@ -45,7 +45,7 @@ public abstract class BeamActionTestBase { protected FlexTemplates templates = mock(FlexTemplates.class); protected Launch launch = mock(Launch.class); private Answer answer = - new Answer() { + new Answer<>() { private Integer times = 0; @Override diff --git a/core/src/test/java/google/registry/beam/TestPipelineExtension.java b/core/src/test/java/google/registry/beam/TestPipelineExtension.java index da2a1536a..b48d711b4 100644 --- a/core/src/test/java/google/registry/beam/TestPipelineExtension.java +++ b/core/src/test/java/google/registry/beam/TestPipelineExtension.java @@ -376,7 +376,7 @@ public class TestPipelineExtension extends Pipeline providerRuntimeValues.put(uuid, runtimeValue); return ValueProvider.NestedValueProvider.of( options.as(TestValueProviderOptions.class).getProviderRuntimeValues(), - new GetFromRuntimeValues(uuid)); + new GetFromRuntimeValues<>(uuid)); } private final Map providerRuntimeValues = Maps.newHashMap(); diff --git a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java index a8baa2587..e64fd0caf 100644 --- a/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java +++ b/core/src/test/java/google/registry/bsa/BsaDownloadFunctionalTest.java @@ -53,9 +53,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.stubbing.Answer; /** Functional tests of BSA block list download and processing. */ @ExtendWith(MockitoExtension.class) @@ -170,20 +168,17 @@ class BsaDownloadFunctionalTest { throws Exception { byte[] bytes = Joiner.on('\n') - .join(new ImmutableList.Builder().add(BSA_CSV_HEADER).addAll(dataLines).build()) + .join(new ImmutableList.Builder().add(BSA_CSV_HEADER).addAll(dataLines).build()) .getBytes(UTF_8); String checksum = generateChecksum(bytes); LazyBlockList blockList = mock(LazyBlockList.class); when(blockList.checksum()).thenReturn(checksum); when(blockList.getName()).thenReturn(blockListType); doAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - BiConsumer consumer = invocation.getArgument(0); - consumer.accept(bytes, bytes.length); - return null; - } + invocation -> { + BiConsumer consumer = invocation.getArgument(0); + consumer.accept(bytes, bytes.length); + return null; }) .when(blockList) .consumeAll(any(BiConsumer.class)); diff --git a/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java b/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java index d38c71dc5..806b7bbe3 100644 --- a/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java +++ b/core/src/test/java/google/registry/bsa/BsaValidateActionTest.java @@ -404,7 +404,11 @@ public class BsaValidateActionTest { assertThat(message.body()).startsWith("Most recent download is"); assertThat(message.body()) .isEqualTo( - "Most recent download is 2023-11-09t020857.880z.\n\n" + "Error line 1.\nError line 2"); + """ + Most recent download is 2023-11-09t020857.880z. + + Error line 1. + Error line 2"""); } @Test diff --git a/core/src/test/java/google/registry/bsa/GcsClientTest.java b/core/src/test/java/google/registry/bsa/GcsClientTest.java index c542c651f..e8c95ee48 100644 --- a/core/src/test/java/google/registry/bsa/GcsClientTest.java +++ b/core/src/test/java/google/registry/bsa/GcsClientTest.java @@ -89,7 +89,7 @@ class GcsClientTest { void readWriteLabelDiffs_success() throws Exception { ImmutableList labels = ImmutableList.of( - BlockLabel.create("1", LabelType.CREATE.CREATE, ImmutableSet.of()), + BlockLabel.create("1", LabelType.CREATE, ImmutableSet.of()), BlockLabel.create("2", LabelType.NEW_ORDER_ASSOCIATION, ImmutableSet.of("JA")), BlockLabel.create("3", LabelType.DELETE, ImmutableSet.of("JA", "EXTENDED_LATIN"))); gcsClient.writeLabelDiffs("job", labels.stream()); diff --git a/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java b/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java index 52e35d6d8..564b3b8f9 100644 --- a/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java +++ b/core/src/test/java/google/registry/bsa/persistence/DownloadSchedulerTest.java @@ -20,6 +20,7 @@ import static google.registry.bsa.DownloadStage.DONE; import static google.registry.bsa.DownloadStage.DOWNLOAD_BLOCK_LISTS; import static google.registry.bsa.DownloadStage.MAKE_ORDER_AND_LABEL_DIFF; import static google.registry.bsa.DownloadStage.NOP; +import static google.registry.bsa.persistence.DownloadScheduler.fetchTwoMostRecentDownloads; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static org.joda.time.Duration.standardDays; import static org.joda.time.Duration.standardMinutes; @@ -165,26 +166,26 @@ class DownloadSchedulerTest { @Test void loadRecentProcessedJobs_noneExists() { - assertThat(tm().transact(() -> scheduler.fetchTwoMostRecentDownloads())).isEmpty(); + assertThat(tm().transact(() -> fetchTwoMostRecentDownloads())).isEmpty(); } @Test void loadRecentProcessedJobs_nopJobsOnly() { insertOneJobAndAdvanceClock(DownloadStage.NOP); insertOneJobAndAdvanceClock(DownloadStage.CHECKSUMS_DO_NOT_MATCH); - assertThat(tm().transact(() -> scheduler.fetchTwoMostRecentDownloads())).isEmpty(); + assertThat(tm().transact(() -> fetchTwoMostRecentDownloads())).isEmpty(); } @Test void loadRecentProcessedJobs_oneInProgressJob() { BsaDownload job = insertOneJobAndAdvanceClock(MAKE_ORDER_AND_LABEL_DIFF); - assertThat(tm().transact(() -> scheduler.fetchTwoMostRecentDownloads())).containsExactly(job); + assertThat(tm().transact(() -> fetchTwoMostRecentDownloads())).containsExactly(job); } @Test void loadRecentProcessedJobs_oneDoneJob() { BsaDownload job = insertOneJobAndAdvanceClock(DONE); - assertThat(tm().transact(() -> scheduler.fetchTwoMostRecentDownloads())).containsExactly(job); + assertThat(tm().transact(() -> fetchTwoMostRecentDownloads())).containsExactly(job); } @Test @@ -195,7 +196,7 @@ class DownloadSchedulerTest { insertOneJobAndAdvanceClock(DownloadStage.NOP); insertOneJobAndAdvanceClock(DownloadStage.CHECKSUMS_DO_NOT_MATCH); BsaDownload inprogress = insertOneJobAndAdvanceClock(DownloadStage.APPLY_ORDER_AND_LABEL_DIFF); - assertThat(tm().transact(() -> scheduler.fetchTwoMostRecentDownloads())) + assertThat(tm().transact(() -> fetchTwoMostRecentDownloads())) .containsExactly(inprogress, completed) .inOrder(); } diff --git a/core/src/test/java/google/registry/cron/TldFanoutActionTest.java b/core/src/test/java/google/registry/cron/TldFanoutActionTest.java index 42195dfdc..2a5c13202 100644 --- a/core/src/test/java/google/registry/cron/TldFanoutActionTest.java +++ b/core/src/test/java/google/registry/cron/TldFanoutActionTest.java @@ -223,10 +223,12 @@ class TldFanoutActionTest { assertThat(taskList).hasSize(3); String expectedResponse = String.format( - "OK: Launched the following 3 tasks in queue the-queue\n" - + "- Task: '%s', tld: 'com', endpoint: 'https://backend.example.com/the/servlet'\n" - + "- Task: '%s', tld: 'net', endpoint: 'https://backend.example.com/the/servlet'\n" - + "- Task: '%s', tld: 'org', endpoint: 'https://backend.example.com/the/servlet'\n", + """ + OK: Launched the following 3 tasks in queue the-queue + - Task: '%s', tld: 'com', endpoint: 'https://backend.example.com/the/servlet' + - Task: '%s', tld: 'net', endpoint: 'https://backend.example.com/the/servlet' + - Task: '%s', tld: 'org', endpoint: 'https://backend.example.com/the/servlet' + """, taskList.get(0).getName(), taskList.get(1).getName(), taskList.get(2).getName()); assertThat(response.getPayload()).isEqualTo(expectedResponse); } @@ -240,8 +242,10 @@ class TldFanoutActionTest { assertThat(taskList).hasSize(1); String expectedResponse = String.format( - "OK: Launched the following 1 tasks in queue the-queue\n" - + "- Task: '%s', tld: '', endpoint: 'https://backend.example.com/the/servlet'\n", + """ + OK: Launched the following 1 tasks in queue the-queue + - Task: '%s', tld: '', endpoint: 'https://backend.example.com/the/servlet' + """, taskList.get(0).getName()); assertThat(response.getPayload()).isEqualTo(expectedResponse); } diff --git a/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java b/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java index 8531faf49..0f025cc8d 100644 --- a/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java +++ b/core/src/test/java/google/registry/export/sheet/SyncRegistrarsSheetTest.java @@ -199,40 +199,42 @@ public class SyncRegistrarsSheetTest { assertThat(row) .containsEntry( "primaryContacts", - "" - + "Jane Doe\n" - + "contact@example.com\n" - + "Tel: +1.1234567890\n" - + "Types: [ADMIN, BILLING]\n" - + "Visible in registrar WHOIS query as Admin contact: No\n" - + "Visible in registrar WHOIS query as Technical contact: No\n" - + "Phone number and email visible in domain WHOIS query as " - + "Registrar Abuse contact info: No\n" - + "Registrar-Console access: No\n" - + '\n' - + "John Doe\n" - + "john.doe@example.tld\n" - + "Tel: +1.1234567890\n" - + "Fax: +1.1234567891\n" - + "Types: [ADMIN]\n" - + "Visible in registrar WHOIS query as Admin contact: No\n" - + "Visible in registrar WHOIS query as Technical contact: Yes\n" - + "Phone number and email visible in domain WHOIS query as " - + "Registrar Abuse contact info: No\n" - + "Registrar-Console access: Yes\n" - + "Login Email Address: john.doe@example.tld\n"); + """ + Jane Doe + contact@example.com + Tel: +1.1234567890 + Types: [ADMIN, BILLING] + Visible in registrar WHOIS query as Admin contact: No + Visible in registrar WHOIS query as Technical contact: No + Phone number and email visible in domain WHOIS query as Registrar Abuse contact\ + info: No + Registrar-Console access: No + + John Doe + john.doe@example.tld + Tel: +1.1234567890 + Fax: +1.1234567891 + Types: [ADMIN] + Visible in registrar WHOIS query as Admin contact: No + Visible in registrar WHOIS query as Technical contact: Yes + Phone number and email visible in domain WHOIS query as Registrar Abuse contact\ + info: No + Registrar-Console access: Yes + Login Email Address: john.doe@example.tld + """); assertThat(row) .containsEntry( "techContacts", - "" - + "Jane Smith\n" - + "pride@example.net\n" - + "Types: [TECH]\n" - + "Visible in registrar WHOIS query as Admin contact: No\n" - + "Visible in registrar WHOIS query as Technical contact: No\n" - + "Phone number and email visible in domain WHOIS query as " - + "Registrar Abuse contact info: No\n" - + "Registrar-Console access: No\n"); + """ + Jane Smith + pride@example.net + Types: [TECH] + Visible in registrar WHOIS query as Admin contact: No + Visible in registrar WHOIS query as Technical contact: No + Phone number and email visible in domain WHOIS query as Registrar Abuse contact\ + info: No + Registrar-Console access: No + """); assertThat(row).containsEntry("marketingContacts", ""); assertThat(row).containsEntry("abuseContacts", ""); assertThat(row).containsEntry("whoisInquiryContacts", ""); @@ -240,32 +242,34 @@ public class SyncRegistrarsSheetTest { assertThat(row) .containsEntry( "billingContacts", - "" - + "Jane Doe\n" - + "contact@example.com\n" - + "Tel: +1.1234567890\n" - + "Types: [ADMIN, BILLING]\n" - + "Visible in registrar WHOIS query as Admin contact: No\n" - + "Visible in registrar WHOIS query as Technical contact: No\n" - + "Phone number and email visible in domain WHOIS query as " - + "Registrar Abuse contact info: No\n" - + "Registrar-Console access: No\n"); + """ + Jane Doe + contact@example.com + Tel: +1.1234567890 + Types: [ADMIN, BILLING] + Visible in registrar WHOIS query as Admin contact: No + Visible in registrar WHOIS query as Technical contact: No + Phone number and email visible in domain WHOIS query as Registrar Abuse contact\ + info: No + Registrar-Console access: No + """); assertThat(row).containsEntry("contactsMarkedAsWhoisAdmin", ""); assertThat(row) .containsEntry( "contactsMarkedAsWhoisTech", - "" - + "John Doe\n" - + "john.doe@example.tld\n" - + "Tel: +1.1234567890\n" - + "Fax: +1.1234567891\n" - + "Types: [ADMIN]\n" - + "Visible in registrar WHOIS query as Admin contact: No\n" - + "Visible in registrar WHOIS query as Technical contact: Yes\n" - + "Phone number and email visible in domain WHOIS query as " - + "Registrar Abuse contact info: No\n" - + "Registrar-Console access: Yes\n" - + "Login Email Address: john.doe@example.tld\n"); + """ + John Doe + john.doe@example.tld + Tel: +1.1234567890 + Fax: +1.1234567891 + Types: [ADMIN] + Visible in registrar WHOIS query as Admin contact: No + Visible in registrar WHOIS query as Technical contact: Yes + Phone number and email visible in domain WHOIS query as Registrar Abuse contact\ + info: No + Registrar-Console access: Yes + Login Email Address: john.doe@example.tld + """); assertThat(row).containsEntry("emailAddress", "nowhere@example.org"); assertThat(row).containsEntry( "address.street", "I get fallen back upon since there's no l10n addr"); diff --git a/core/src/test/java/google/registry/flows/EppLoginTlsTest.java b/core/src/test/java/google/registry/flows/EppLoginTlsTest.java index 9a3da248c..8e81978d8 100644 --- a/core/src/test/java/google/registry/flows/EppLoginTlsTest.java +++ b/core/src/test/java/google/registry/flows/EppLoginTlsTest.java @@ -254,9 +254,10 @@ class EppLoginTlsTest extends EppTestCase { "CODE", "2200", "MSG", - "Registrar certificate contains the following security violations:\n" - + "Certificate is expired.\n" - + "Certificate validity period is too long; it must be less than or equal to" - + " 398 days.")); + """ + Registrar certificate contains the following security violations: + Certificate is expired. + Certificate validity period is too long; it must be less than or equal to 398\ + days.""")); } } diff --git a/core/src/test/java/google/registry/flows/domain/DomainFlowUtilsTest.java b/core/src/test/java/google/registry/flows/domain/DomainFlowUtilsTest.java index aa970271f..9925e1dd2 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainFlowUtilsTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainFlowUtilsTest.java @@ -168,7 +168,7 @@ class DomainFlowUtilsTest extends ResourceFlowTestCase { } @Test - void testCheckHasBillingAccount_failsOnRealTld() throws EppException { + void testCheckHasBillingAccount_failsOnRealTld() { persistFoobarTld(TldType.REAL); MissingBillingAccountMapException thrown = assertThrows( diff --git a/core/src/test/java/google/registry/flows/domain/DomainPricingLogicTest.java b/core/src/test/java/google/registry/flows/domain/DomainPricingLogicTest.java index 9aefa0791..f3eff276a 100644 --- a/core/src/test/java/google/registry/flows/domain/DomainPricingLogicTest.java +++ b/core/src/test/java/google/registry/flows/domain/DomainPricingLogicTest.java @@ -247,8 +247,7 @@ public class DomainPricingLogicTest { @Test void - testGetDomainRenewPrice_oneYear_premiumDomain_default_withTokenNotValidForPremiums_throwsException() - throws EppException { + testGetDomainRenewPrice_oneYear_premiumDomain_default_withTokenNotValidForPremiums_throwsException() { AllocationToken allocationToken = persistResource( new AllocationToken.Builder() @@ -315,8 +314,7 @@ public class DomainPricingLogicTest { @Test void - testGetDomainRenewPrice_multiYear_premiumDomain_default_withTokenNotValidForPremiums_throwsException() - throws EppException { + testGetDomainRenewPrice_multiYear_premiumDomain_default_withTokenNotValidForPremiums_throwsException() { AllocationToken allocationToken = persistResource( new AllocationToken.Builder() @@ -724,7 +722,7 @@ public class DomainPricingLogicTest { } @Test - void testGetDomainRenewPrice_negativeYear_throwsException() throws EppException { + void testGetDomainRenewPrice_negativeYear_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, 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 7a58b2073..7721a6e29 100644 --- a/core/src/test/java/google/registry/flows/host/HostCreateFlowTest.java +++ b/core/src/test/java/google/registry/flows/host/HostCreateFlowTest.java @@ -68,9 +68,10 @@ class HostCreateFlowTest extends ResourceFlowTestCase { private void setEppHostCreateInputWithIps(String hostName) { setEppHostCreateInput( hostName, - "192.0.2.2\n" - + "192.0.2.29\n" - + "1080:0:0:0:8:800:200C:417A"); + """ + 192.0.2.2 + 192.0.2.29 + 1080:0:0:0:8:800:200C:417A"""); } HostCreateFlowTest() { @@ -267,9 +268,10 @@ class HostCreateFlowTest extends ResourceFlowTestCase { void testFailure_ip4AddressWithIp6Declaration() { setEppHostCreateInput( "ns1.example.tld", - "192.0.2.2\n" - + "192.0.2.29\n" - + "1080:0:0:0:8:800:200C:417A"); + """ + 192.0.2.2 + 192.0.2.29 + 1080:0:0:0:8:800:200C:417A"""); EppException thrown = assertThrows(IpAddressVersionMismatchException.class, this::runFlow); assertAboutEppExceptions().that(thrown).marshalsToXml(); } diff --git a/core/src/test/java/google/registry/groups/GmailClientTest.java b/core/src/test/java/google/registry/groups/GmailClientTest.java index acaa53281..eb83edb93 100644 --- a/core/src/test/java/google/registry/groups/GmailClientTest.java +++ b/core/src/test/java/google/registry/groups/GmailClientTest.java @@ -48,9 +48,7 @@ import javax.mail.internet.MimeMultipart; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.stubbing.Answer; /** Unit tests for {@link GmailClient}. */ @ExtendWith(MockitoExtension.class) @@ -159,13 +157,10 @@ public class GmailClientTest { MimeMessage mimeMessage = mock(MimeMessage.class); byte[] data = "My content".getBytes(UTF_8); doAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - OutputStream os = invocation.getArgument(0); - os.write(data); - return null; - } + invocation -> { + OutputStream os = invocation.getArgument(0); + os.write(data); + return null; }) .when(mimeMessage) .writeTo(any(OutputStream.class)); diff --git a/core/src/test/java/google/registry/keyring/api/KeySerializerTest.java b/core/src/test/java/google/registry/keyring/api/KeySerializerTest.java index e482018da..8a75c496d 100644 --- a/core/src/test/java/google/registry/keyring/api/KeySerializerTest.java +++ b/core/src/test/java/google/registry/keyring/api/KeySerializerTest.java @@ -46,66 +46,68 @@ class KeySerializerTest { *

Created using 'gpg --gen-key' followed by 'gpg --export-secret-key -a'. */ private static final String ARMORED_KEY_STRING = - "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" - + "Version: GnuPG v1\n" - + "\n" - + "lQO+BFjbx+IBCADO3hs5CE2fIorcq8+yBdnVb1+pyPrm/48vIHCIhFHeqBjmxuY9\n" - + "cdgRjiNTXp8Rs1N4e1cXWtiA2vuoBmkLF1REckgyPyocn/ssta/pRHd4fqskrQwJ\n" - + "CoIoQaP3bd+KSUJoxTSckWgXFQnoNWj1kg5gv8WnY7nWB0jtjwyGSQoHy/pK3h94\n" - + "GDrHg5CQBVZ3N6NBob9bGoEhi53gh/1UIUS8GVSLS9Qwt26+3oJ1RlGl7PQoDjeK\n" - + "oraY8i0sl9rD06qVTFtmXLHHogP4WgD6GItTam7flPqXXNzl0PUk0mTcv9cwt4VP\n" - + "WZ5YJ7y5CqNhwqU9YeirbooHq6T9+nHxU2ddABEBAAH+AwMCjPetoiDH5m5gRgn4\n" - + "FB3io2zclIcCEnvfby1VZ/82u2nZXtSK9N5twf6pWH4KD1/3VkgqlEBhrQkqz8v4\n" - + "C5AWObWT1lF1hQkh/O6OFTPN7DMUSqLX/z6qXv7c5fMFU69CGq6B64s/SMKxfI1p\n" - + "roDoFA912GlVH89ZT8BDtTahQQzJyHL/61KZVMidLt6IqeWsI3XCy1u8/WkLYkBG\n" - + "dqvCPBf2mlVeEOwmoAPWTMvV1lHlvauu4ofLJh8VYoO+wziX86yiQ37tsPN8Jspx\n" - + "gpaiSH6f2x+I7vXFKO2ThqC8jNjfQFLnQ9yWtDYVtLgA6POMLFNOb9c733lzvHPU\n" - + "UgQRCumAyTeX0wLoC2rEG3Qu/o+Sbm10BNQmkNBxH+Pkdk+ubO/4lvaY8+nxWw1t\n" - + "sIzoUoln1dHo5lbJsA/++ttNZsAMPlGB5nDC/EmhUHjKDhRpj9OwX+aFxAbBpJXg\n" - + "BKBirm7VnWp+rUd5YlwKDOJFLlNKgFmh8XBTTpe9DE/qKvnABlFjdhXpUXYEMfHw\n" - + "D7mS1J3gtd2Iz24pwbL52XA+M5nIWnX0A9N4pi/k+3M02T6up/qcqArjf/CFFZS1\n" - + "CSng1xYPBrxDJyIXTsFFQ7kEJrSUyvXylsLHVeXZmnwqmmjh8RFohTWecDSHgxi6\n" - + "R4m9ZHVagWxecDvNmxY5vPRzhNmP5w/teCMVnEHH5VXktBmbn8TW3hLaFHs2H88b\n" - + "xovFXrn1pQ7hg6KLURbhXsBQlL/3NXFSXYc5cimP4lewnd6sqlnSfY/o9JujgoAV\n" - + "v1Wo63Jjl9fhlu8Vr/sHrAPWQS9mWzMUJy6EcTJRop39J90fPqcsz7Iz4gdH8QNY\n" - + "ve/iLjIuGbkK4KevptD7oR4zUIwKUpIKVJTr1Q2ukKU0pAVCyn19nRAR1RGri81L\n" - + "jbRAR1RMRCBUZXN0ZXIgKFRoaXMga2V5IGlzIHVzZWQgZm9yIHRlc3RzIG9ubHkp\n" - + "IDx0ZXN0ZXJAdGVzdC50ZXN0PokBOAQTAQIAIgUCWNvH4gIbAwYLCQgHAwIGFQgC\n" - + "CQoLBBYCAwECHgECF4AACgkQxCHL9+c/Gv2LKgf+KdUPUlKq0N3oSzXk5RcXJZDT\n" - + "v8teeLXyu3loaXzEuK89/V5BdDL5nRu8+GUhfFRkd/LFv0rwehcJZ5TtXghukk6r\n" - + "5kvekPf8vVjgMO89RrmiW2oKqqmhP8VZd1T1vQacQ4J6eNKCjbuLym47m4Vp9VZm\n" - + "lHNGNgkDbU1zVxhF23rLqOqzltiIcyCafMPFJNRUANlLkEIvAo8dGziqn5l2X71w\n" - + "9KQw4LzQHrR1ulm0h4SbYwhQQ2Qz1FzfVjyuRUjye5QJxLEa9M92l1oLMjubt3Qx\n" - + "QEiL05Bp3uYd+S97BuxbDFz+hNUHfIaSVuwrVgdz2tcwBTyBl2jUTukKC2nMfJ0D\n" - + "vgRY28fiAQgA3qW5JTZNG26Iv9k+cysl5TWeAO71yrEAL4WAXoKQYIEVMcCi3Rt9\n" - + "YW+FhZ+z056n3EZsgIYsPniipdyRBrehQI5f9CRFcyqkMu8tuBIqsJaZAhcMcYoN\n" - + "zNWqk7mK5Wjp4yfQAEkyb13YXg+zFEtBiEOG5FPonA+vGIFeOUKSR0s+hoxhcBvS\n" - + "Q5BGXlHP20UQBdLtPfnOx+scI9sjYBtO13ZaURBnsHfHSyDnNa5HZD6eTk7V8bjy\n" - + "ScUDHOW/Ujva3yH/7KQeR42cdba38zpvSlivwIpnGtNlhABR+mZhee5BwxGNusJ9\n" - + "D/Xi8dSSjpwZH8b6fHhwoSpb5AK6tvGgHwARAQAB/gMDAoz3raIgx+ZuYJS4j+fX\n" - + "6PmrHg+nOoes3i2RufCvjMhRSMU+aZo1e8fNWP9NnVKPna9Ya2PHGkHHUZlx6CE9\n" - + "EPvMwl9d8web5vBSCkzNwtUtgCrShk7cyDbHq7dLzbqxZTZK+HKX6CGL3dAC1Z1J\n" - + "zvgpj6enpTZSKSbxkPSGcxlXkT/hm7x+wYXsPgbMGH/rRnHJ1Ycg4nlHxq7sPgHK\n" - + "Jgfl3a4WuyN6Ja1mVPPYxSSyKusFdXZHreqR+GLwGc2PsKjQy870uJPF4zBGYya1\n" - + "iJ/8o5xJ1OxLa+SrvPExgkFmt271SHFAYk0Xx/IUshZZVP+3i8HHo7yMKEANxM+n\n" - + "Mcr9MW963Dm8thbxy3yC2GvufYz13yJJeWnMel/enSDvSieUAFsEH4NalE7HX7Mv\n" - + "NoBx6wuQTFVdojauXrERD75vYGamMC1/0h+6rzejE4HP0iDHlujJmkucAD2K8ibb\n" - + "ax4QiRJtatel48wYqjIkhZ8x6mFaUiBL34iyh4t0vY0CgZOsEIegy1pRkoO8u72T\n" - + "rcgFHhHQgtf6OaPG4QnSWbxrftRmZe7W4K5tyrmoLHjsm6exAFcTmpl79qE8Mn+7\n" - + "jTspdKeTkhse5K/7ct749kZDD8FwVhSP9vqfbDhwmdmCQNp5rRQKm1+YBnamlnuz\n" - + "IEWzxmQ2NqjEeV65bk7BfnbHYe42ZNNIzE4XahzrBVwhtMaLGLz/7YF4Czwrbn0D\n" - + "KQwjp5qbjDAO+0FCOxN4xFItazp0bKlHnGYflEPLbFoeplBfi2sZfmQ6PUmA3UPr\n" - + "T96e6fHBsctYVa4JP0HWKGcwYIhih9uD53UFsg0BJW5iXsGfMzuEo2TUXBD5qFUN\n" - + "xrS5Nt/Ra1psaaZxXDeiHWM5qlmk37xoFjnPV5RV0014TqNr//VHgJknWNuhcMqJ\n" - + "AR8EGAECAAkFAljbx+ICGwwACgkQxCHL9+c/Gv1WzQf+Ihv0zeOFOZdvI6xOTVXS\n" - + "qBg6k1aMdbwqshaHEvLhAY00XQmhPr65ymEJVaWRloviQ76dN9k4tTi6lYX/CGob\n" - + "bi3fUNDNQGKdyvhoxtneKsXw/3LfFh7JphVWQizh/yJHsKFvzmmMpnC4WTJ3NBTe\n" - + "G+CcHlGdFYuxc4+Z9nZG2jOorQtlFGLEqLzdM8+OJ8KyOqvaOpa0vaMyvN40QiGv\n" - + "raEbRpkDbxJiPp4RuPiu7S8KwKpmjgmuAXaoYKcrL8KIt9WvYWQirW8oZcbP3g/1\n" - + "laUCBMklv75toeXKeYi5Y74CvnPuciCKsNtm0fZkmhfE1vpPFn4/UqRmDtPrToVQ\n" - + "GQ==\n" - + "=qeFB\n" - + "-----END PGP PRIVATE KEY BLOCK-----\n"; + """ + -----BEGIN PGP PRIVATE KEY BLOCK----- + Version: GnuPG v1 + + lQO+BFjbx+IBCADO3hs5CE2fIorcq8+yBdnVb1+pyPrm/48vIHCIhFHeqBjmxuY9 + cdgRjiNTXp8Rs1N4e1cXWtiA2vuoBmkLF1REckgyPyocn/ssta/pRHd4fqskrQwJ + CoIoQaP3bd+KSUJoxTSckWgXFQnoNWj1kg5gv8WnY7nWB0jtjwyGSQoHy/pK3h94 + GDrHg5CQBVZ3N6NBob9bGoEhi53gh/1UIUS8GVSLS9Qwt26+3oJ1RlGl7PQoDjeK + oraY8i0sl9rD06qVTFtmXLHHogP4WgD6GItTam7flPqXXNzl0PUk0mTcv9cwt4VP + WZ5YJ7y5CqNhwqU9YeirbooHq6T9+nHxU2ddABEBAAH+AwMCjPetoiDH5m5gRgn4 + FB3io2zclIcCEnvfby1VZ/82u2nZXtSK9N5twf6pWH4KD1/3VkgqlEBhrQkqz8v4 + C5AWObWT1lF1hQkh/O6OFTPN7DMUSqLX/z6qXv7c5fMFU69CGq6B64s/SMKxfI1p + roDoFA912GlVH89ZT8BDtTahQQzJyHL/61KZVMidLt6IqeWsI3XCy1u8/WkLYkBG + dqvCPBf2mlVeEOwmoAPWTMvV1lHlvauu4ofLJh8VYoO+wziX86yiQ37tsPN8Jspx + gpaiSH6f2x+I7vXFKO2ThqC8jNjfQFLnQ9yWtDYVtLgA6POMLFNOb9c733lzvHPU + UgQRCumAyTeX0wLoC2rEG3Qu/o+Sbm10BNQmkNBxH+Pkdk+ubO/4lvaY8+nxWw1t + sIzoUoln1dHo5lbJsA/++ttNZsAMPlGB5nDC/EmhUHjKDhRpj9OwX+aFxAbBpJXg + BKBirm7VnWp+rUd5YlwKDOJFLlNKgFmh8XBTTpe9DE/qKvnABlFjdhXpUXYEMfHw + D7mS1J3gtd2Iz24pwbL52XA+M5nIWnX0A9N4pi/k+3M02T6up/qcqArjf/CFFZS1 + CSng1xYPBrxDJyIXTsFFQ7kEJrSUyvXylsLHVeXZmnwqmmjh8RFohTWecDSHgxi6 + R4m9ZHVagWxecDvNmxY5vPRzhNmP5w/teCMVnEHH5VXktBmbn8TW3hLaFHs2H88b + xovFXrn1pQ7hg6KLURbhXsBQlL/3NXFSXYc5cimP4lewnd6sqlnSfY/o9JujgoAV + v1Wo63Jjl9fhlu8Vr/sHrAPWQS9mWzMUJy6EcTJRop39J90fPqcsz7Iz4gdH8QNY + ve/iLjIuGbkK4KevptD7oR4zUIwKUpIKVJTr1Q2ukKU0pAVCyn19nRAR1RGri81L + jbRAR1RMRCBUZXN0ZXIgKFRoaXMga2V5IGlzIHVzZWQgZm9yIHRlc3RzIG9ubHkp + IDx0ZXN0ZXJAdGVzdC50ZXN0PokBOAQTAQIAIgUCWNvH4gIbAwYLCQgHAwIGFQgC + CQoLBBYCAwECHgECF4AACgkQxCHL9+c/Gv2LKgf+KdUPUlKq0N3oSzXk5RcXJZDT + v8teeLXyu3loaXzEuK89/V5BdDL5nRu8+GUhfFRkd/LFv0rwehcJZ5TtXghukk6r + 5kvekPf8vVjgMO89RrmiW2oKqqmhP8VZd1T1vQacQ4J6eNKCjbuLym47m4Vp9VZm + lHNGNgkDbU1zVxhF23rLqOqzltiIcyCafMPFJNRUANlLkEIvAo8dGziqn5l2X71w + 9KQw4LzQHrR1ulm0h4SbYwhQQ2Qz1FzfVjyuRUjye5QJxLEa9M92l1oLMjubt3Qx + QEiL05Bp3uYd+S97BuxbDFz+hNUHfIaSVuwrVgdz2tcwBTyBl2jUTukKC2nMfJ0D + vgRY28fiAQgA3qW5JTZNG26Iv9k+cysl5TWeAO71yrEAL4WAXoKQYIEVMcCi3Rt9 + YW+FhZ+z056n3EZsgIYsPniipdyRBrehQI5f9CRFcyqkMu8tuBIqsJaZAhcMcYoN + zNWqk7mK5Wjp4yfQAEkyb13YXg+zFEtBiEOG5FPonA+vGIFeOUKSR0s+hoxhcBvS + Q5BGXlHP20UQBdLtPfnOx+scI9sjYBtO13ZaURBnsHfHSyDnNa5HZD6eTk7V8bjy + ScUDHOW/Ujva3yH/7KQeR42cdba38zpvSlivwIpnGtNlhABR+mZhee5BwxGNusJ9 + D/Xi8dSSjpwZH8b6fHhwoSpb5AK6tvGgHwARAQAB/gMDAoz3raIgx+ZuYJS4j+fX + 6PmrHg+nOoes3i2RufCvjMhRSMU+aZo1e8fNWP9NnVKPna9Ya2PHGkHHUZlx6CE9 + EPvMwl9d8web5vBSCkzNwtUtgCrShk7cyDbHq7dLzbqxZTZK+HKX6CGL3dAC1Z1J + zvgpj6enpTZSKSbxkPSGcxlXkT/hm7x+wYXsPgbMGH/rRnHJ1Ycg4nlHxq7sPgHK + Jgfl3a4WuyN6Ja1mVPPYxSSyKusFdXZHreqR+GLwGc2PsKjQy870uJPF4zBGYya1 + iJ/8o5xJ1OxLa+SrvPExgkFmt271SHFAYk0Xx/IUshZZVP+3i8HHo7yMKEANxM+n + Mcr9MW963Dm8thbxy3yC2GvufYz13yJJeWnMel/enSDvSieUAFsEH4NalE7HX7Mv + NoBx6wuQTFVdojauXrERD75vYGamMC1/0h+6rzejE4HP0iDHlujJmkucAD2K8ibb + ax4QiRJtatel48wYqjIkhZ8x6mFaUiBL34iyh4t0vY0CgZOsEIegy1pRkoO8u72T + rcgFHhHQgtf6OaPG4QnSWbxrftRmZe7W4K5tyrmoLHjsm6exAFcTmpl79qE8Mn+7 + jTspdKeTkhse5K/7ct749kZDD8FwVhSP9vqfbDhwmdmCQNp5rRQKm1+YBnamlnuz + IEWzxmQ2NqjEeV65bk7BfnbHYe42ZNNIzE4XahzrBVwhtMaLGLz/7YF4Czwrbn0D + KQwjp5qbjDAO+0FCOxN4xFItazp0bKlHnGYflEPLbFoeplBfi2sZfmQ6PUmA3UPr + T96e6fHBsctYVa4JP0HWKGcwYIhih9uD53UFsg0BJW5iXsGfMzuEo2TUXBD5qFUN + xrS5Nt/Ra1psaaZxXDeiHWM5qlmk37xoFjnPV5RV0014TqNr//VHgJknWNuhcMqJ + AR8EGAECAAkFAljbx+ICGwwACgkQxCHL9+c/Gv1WzQf+Ihv0zeOFOZdvI6xOTVXS + qBg6k1aMdbwqshaHEvLhAY00XQmhPr65ymEJVaWRloviQ76dN9k4tTi6lYX/CGob + bi3fUNDNQGKdyvhoxtneKsXw/3LfFh7JphVWQizh/yJHsKFvzmmMpnC4WTJ3NBTe + G+CcHlGdFYuxc4+Z9nZG2jOorQtlFGLEqLzdM8+OJ8KyOqvaOpa0vaMyvN40QiGv + raEbRpkDbxJiPp4RuPiu7S8KwKpmjgmuAXaoYKcrL8KIt9WvYWQirW8oZcbP3g/1 + laUCBMklv75toeXKeYi5Y74CvnPuciCKsNtm0fZkmhfE1vpPFn4/UqRmDtPrToVQ + GQ== + =qeFB + -----END PGP PRIVATE KEY BLOCK----- + """; private static final BcPGPSecretKeyRing SECRET_KEYRING = getSecretKeyring(); diff --git a/core/src/test/java/google/registry/model/ImmutableObjectTest.java b/core/src/test/java/google/registry/model/ImmutableObjectTest.java index f8077254e..21ccb957c 100644 --- a/core/src/test/java/google/registry/model/ImmutableObjectTest.java +++ b/core/src/test/java/google/registry/model/ImmutableObjectTest.java @@ -65,7 +65,12 @@ public class ImmutableObjectTest { void testToString_simpleClass() { SimpleObject object = new SimpleObject("foo", null); assertThat(object.toString()) - .isEqualTo("" + "SimpleObject: {\n" + " a=foo\n" + " b=null\n" + "}"); + .isEqualTo( + """ + SimpleObject: { + a=foo + b=null + }"""); } @Test diff --git a/core/src/test/java/google/registry/model/OteStatsTest.java b/core/src/test/java/google/registry/model/OteStatsTest.java index c4dcbd6e4..becf63600 100644 --- a/core/src/test/java/google/registry/model/OteStatsTest.java +++ b/core/src/test/java/google/registry/model/OteStatsTest.java @@ -59,39 +59,40 @@ public final class OteStatsTest { OteStatsTestHelper.setupCompleteOte("blobio"); OteStats stats = OteStats.getFromRegistrar("blobio"); String expected = - "contact creates: 0\n" - + "contact deletes: 0\n" - + "contact transfer approves: 0\n" - + "contact transfer cancels: 0\n" - + "contact transfer rejects: 0\n" - + "contact transfer requests: 0\n" - + "contact updates: 0\n" - + "domain autorenews: 0\n" - + "domain creates: 5\n" - + "domain creates ascii: 4\n" - + "domain creates idn: 1\n" - + "domain creates start date sunrise: 1\n" - + "domain creates with claims notice: 1\n" - + "domain creates with fee: 1\n" - + "domain creates with sec dns: 1\n" - + "domain creates without sec dns: 4\n" - + "domain deletes: 1\n" - + "domain renews: 0\n" - + "domain restores: 1\n" - + "domain transfer approves: 1\n" - + "domain transfer cancels: 1\n" - + "domain transfer rejects: 1\n" - + "domain transfer requests: 1\n" - + "domain updates: 1\n" - + "domain updates with sec dns: 1\n" - + "domain updates without sec dns: 0\n" - + "host creates: 1\n" - + "host creates external: 0\n" - + "host creates subordinate: 1\n" - + "host deletes: 1\n" - + "host updates: 1\n" - + "unclassified flows: 0\n" - + "TOTAL: 30"; + """ + contact creates: 0 + contact deletes: 0 + contact transfer approves: 0 + contact transfer cancels: 0 + contact transfer rejects: 0 + contact transfer requests: 0 + contact updates: 0 + domain autorenews: 0 + domain creates: 5 + domain creates ascii: 4 + domain creates idn: 1 + domain creates start date sunrise: 1 + domain creates with claims notice: 1 + domain creates with fee: 1 + domain creates with sec dns: 1 + domain creates without sec dns: 4 + domain deletes: 1 + domain renews: 0 + domain restores: 1 + domain transfer approves: 1 + domain transfer cancels: 1 + domain transfer rejects: 1 + domain transfer requests: 1 + domain updates: 1 + domain updates with sec dns: 1 + domain updates without sec dns: 0 + host creates: 1 + host creates external: 0 + host creates subordinate: 1 + host deletes: 1 + host updates: 1 + unclassified flows: 0 + TOTAL: 30"""; assertThat(stats.toString()).isEqualTo(expected); } @@ -100,39 +101,40 @@ public final class OteStatsTest { OteStatsTestHelper.setupIncompleteOte("blobio"); OteStats stats = OteStats.getFromRegistrar("blobio"); String expected = - "contact creates: 0\n" - + "contact deletes: 0\n" - + "contact transfer approves: 0\n" - + "contact transfer cancels: 0\n" - + "contact transfer rejects: 0\n" - + "contact transfer requests: 0\n" - + "contact updates: 0\n" - + "domain autorenews: 0\n" - + "domain creates: 4\n" - + "domain creates ascii: 4\n" - + "domain creates idn: 0\n" - + "domain creates start date sunrise: 1\n" - + "domain creates with claims notice: 1\n" - + "domain creates with fee: 1\n" - + "domain creates with sec dns: 1\n" - + "domain creates without sec dns: 3\n" - + "domain deletes: 1\n" - + "domain renews: 0\n" - + "domain restores: 0\n" - + "domain transfer approves: 1\n" - + "domain transfer cancels: 1\n" - + "domain transfer rejects: 1\n" - + "domain transfer requests: 1\n" - + "domain updates: 1\n" - + "domain updates with sec dns: 1\n" - + "domain updates without sec dns: 0\n" - + "host creates: 1\n" - + "host creates external: 0\n" - + "host creates subordinate: 1\n" - + "host deletes: 0\n" - + "host updates: 10\n" - + "unclassified flows: 0\n" - + "TOTAL: 34"; + """ + contact creates: 0 + contact deletes: 0 + contact transfer approves: 0 + contact transfer cancels: 0 + contact transfer rejects: 0 + contact transfer requests: 0 + contact updates: 0 + domain autorenews: 0 + domain creates: 4 + domain creates ascii: 4 + domain creates idn: 0 + domain creates start date sunrise: 1 + domain creates with claims notice: 1 + domain creates with fee: 1 + domain creates with sec dns: 1 + domain creates without sec dns: 3 + domain deletes: 1 + domain renews: 0 + domain restores: 0 + domain transfer approves: 1 + domain transfer cancels: 1 + domain transfer rejects: 1 + domain transfer requests: 1 + domain updates: 1 + domain updates with sec dns: 1 + domain updates without sec dns: 0 + host creates: 1 + host creates external: 0 + host creates subordinate: 1 + host deletes: 0 + host updates: 10 + unclassified flows: 0 + TOTAL: 34"""; assertThat(stats.toString()).isEqualTo(expected); } } diff --git a/core/src/test/java/google/registry/model/eppcommon/AddressTest.java b/core/src/test/java/google/registry/model/eppcommon/AddressTest.java index 48cd671a4..8c64130ec 100644 --- a/core/src/test/java/google/registry/model/eppcommon/AddressTest.java +++ b/core/src/test/java/google/registry/model/eppcommon/AddressTest.java @@ -49,18 +49,20 @@ class AddressTest { new JpaTestExtensions.Builder().withEntityClass(TestEntity.class).buildUnitTestExtension(); private static final String ENTITY_XML = - "\n" - + "\n" - + "

\n" - + " 123 W 14th St\n" - + " 8th Fl\n" - + " Rm 8\n" - + " New York\n" - + " NY\n" - + " 10011\n" - + " US\n" - + "
\n" - + "\n"; + """ + + +
+ 123 W 14th St + 8th Fl + Rm 8 + New York + NY + 10011 + US +
+
+ """; private TestAddress address = createAddress("123 W 14th St", "8th Fl", "Rm 8"); private TestEntity entity = new TestEntity(1L, address); diff --git a/core/src/test/java/google/registry/persistence/HibernateSchemaExporterTest.java b/core/src/test/java/google/registry/persistence/HibernateSchemaExporterTest.java index c50f248d9..1b50861b1 100644 --- a/core/src/test/java/google/registry/persistence/HibernateSchemaExporterTest.java +++ b/core/src/test/java/google/registry/persistence/HibernateSchemaExporterTest.java @@ -59,12 +59,14 @@ class HibernateSchemaExporterTest { exporter.export(ImmutableList.of(HibernateSchemaTestEntity.class), sqlFile); assertThat(Files.readAllBytes(sqlFile.toPath())) .isEqualTo( - ("\n" - + " create table \"TestEntity\" (\n" - + " name text not null,\n" - + " cu text,\n" - + " primary key (name)\n" - + " );\n") + """ + + create table "TestEntity" ( + name text not null, + cu text, + primary key (name) + ); + """ .getBytes(StandardCharsets.UTF_8)); } diff --git a/core/src/test/java/google/registry/rdap/RdapActionBaseTestCase.java b/core/src/test/java/google/registry/rdap/RdapActionBaseTestCase.java index e78ae58f7..245e1c095 100644 --- a/core/src/test/java/google/registry/rdap/RdapActionBaseTestCase.java +++ b/core/src/test/java/google/registry/rdap/RdapActionBaseTestCase.java @@ -114,27 +114,15 @@ abstract class RdapActionBaseTestCase { } JsonObject generateExpectedJsonError(String description, int code) { - String title; - switch (code) { - case 404: - title = "Not Found"; - break; - case 500: - title = "Internal Server Error"; - break; - case 501: - title = "Not Implemented"; - break; - case 400: - title = "Bad Request"; - break; - case 422: - title = "Unprocessable Entity"; - break; - default: - title = "ERR"; - break; - } + String title = + switch (code) { + case 404 -> "Not Found"; + case 500 -> "Internal Server Error"; + case 501 -> "Not Implemented"; + case 400 -> "Bad Request"; + case 422 -> "Unprocessable Entity"; + default -> "ERR"; + }; return RdapTestHelper.loadJsonFile( "rdap_error.json", "DESCRIPTION", diff --git a/core/src/test/java/google/registry/rdap/RdapDomainSearchActionTest.java b/core/src/test/java/google/registry/rdap/RdapDomainSearchActionTest.java index d21033ad2..b5e8fbd7c 100644 --- a/core/src/test/java/google/registry/rdap/RdapDomainSearchActionTest.java +++ b/core/src/test/java/google/registry/rdap/RdapDomainSearchActionTest.java @@ -90,21 +90,19 @@ class RdapDomainSearchActionTest extends RdapSearchActionTestCase { action.nameParam = Optional.of(paramValue); requestTypeParam = "name"; - break; - case NS_LDH_NAME: + } + case NS_LDH_NAME -> { action.nsLdhNameParam = Optional.of(paramValue); requestTypeParam = "nsLdhName"; - break; - case NS_IP: + } + case NS_IP -> { action.nsIpParam = Optional.of(paramValue); requestTypeParam = "nsIp"; - break; - default: - requestTypeParam = ""; - break; + } + default -> requestTypeParam = ""; } if (paramValue != null) { if (cursor == null) { diff --git a/core/src/test/java/google/registry/rdap/UpdateRegistrarRdapBaseUrlsActionTest.java b/core/src/test/java/google/registry/rdap/UpdateRegistrarRdapBaseUrlsActionTest.java index 8f08e920a..b6843add5 100644 --- a/core/src/test/java/google/registry/rdap/UpdateRegistrarRdapBaseUrlsActionTest.java +++ b/core/src/test/java/google/registry/rdap/UpdateRegistrarRdapBaseUrlsActionTest.java @@ -49,21 +49,23 @@ public final class UpdateRegistrarRdapBaseUrlsActionTest { // This reply simulates part of the actual IANA CSV reply private static final String CSV_REPLY = - "\"ID\",Registrar Name,Status,RDAP Base URL\n" - + "1,Reserved,Reserved,\n" - + "81,Gandi SAS,Accredited,https://rdap.gandi.net/\n" - + "100,Whois Corp.,Accredited,https://www.yesnic.com/rdap/\n" - + "134,BB-Online UK Limited,Accredited,https://rdap.bb-online.com/\n" - + "1316,\"Xiamen 35.Com Technology Co., Ltd.\",Accredited,https://rdap.35.com/rdap/\n" - + "1448,Blacknight Internet Solutions Ltd.,Accredited,https://rdap.blacknight.com/\n" - + "1463,\"Global Domains International, Inc. DBA" - + " DomainCostClub.com\",Accredited,https://rdap.domaincostclub.com/\n" - + "1556,\"Chengdu West Dimension Digital Technology Co.," - + " Ltd.\",Accredited,https://rdap.west.cn/rdap/\n" - + "2288,Metaregistrar BV,Accredited,https://rdap.metaregistrar.com/\n" - + "4000,Gname 031 Inc,Accredited,\n" - + "9999,Reserved for non-billable transactions where Registry Operator acts as" - + " Registrar,Reserved,\n"; + """ + "ID",Registrar Name,Status,RDAP Base URL + 1,Reserved,Reserved, + 81,Gandi SAS,Accredited,https://rdap.gandi.net/ + 100,Whois Corp.,Accredited,https://www.yesnic.com/rdap/ + 134,BB-Online UK Limited,Accredited,https://rdap.bb-online.com/ + 1316,"Xiamen 35.Com Technology Co., Ltd.",Accredited,https://rdap.35.com/rdap/ + 1448,Blacknight Internet Solutions Ltd.,Accredited,https://rdap.blacknight.com/ + 1463,"Global Domains International, Inc. DBA DomainCostClub.com",Accredited,\ + https://rdap.domaincostclub.com/ + 1556,"Chengdu West Dimension Digital Technology Co., Ltd.",Accredited,\ + https://rdap.west.cn/rdap/ + 2288,Metaregistrar BV,Accredited,https://rdap.metaregistrar.com/ + 4000,Gname 031 Inc,Accredited, + 9999,Reserved for non-billable transactions where Registry Operator acts as\ + Registrar,Reserved, + """; @RegisterExtension public JpaIntegrationTestExtension jpa = diff --git a/core/src/test/java/google/registry/rde/BouncyCastleTest.java b/core/src/test/java/google/registry/rde/BouncyCastleTest.java index 71dee51ef..69361c6d9 100644 --- a/core/src/test/java/google/registry/rde/BouncyCastleTest.java +++ b/core/src/test/java/google/registry/rde/BouncyCastleTest.java @@ -96,25 +96,27 @@ import org.junit.jupiter.api.extension.RegisterExtension; */ public class BouncyCastleTest { - private static final String FALL_OF_HYPERION_A_DREAM = "" - + "Fanatics have their dreams, wherewith they weave\n" - + "A paradise for a sect; the savage too\n" - + "From forth the loftiest fashion of his sleep\n" - + "Guesses at Heaven; pity these have not\n" - + "Trac'd upon vellum or wild Indian leaf\n" - + "The shadows of melodious utterance.\n" - + "But bare of laurel they live, dream, and die;\n" - + "For Poesy alone can tell her dreams,\n" - + "With the fine spell of words alone can save\n" - + "Imagination from the sable charm\n" - + "And dumb enchantment. Who alive can say,\n" - + "'Thou art no Poet may'st not tell thy dreams?'\n" - + "Since every man whose soul is not a clod\n" - + "Hath visions, and would speak, if he had loved\n" - + "And been well nurtured in his mother tongue.\n" - + "Whether the dream now purpos'd to rehearse\n" - + "Be poet's or fanatic's will be known\n" - + "When this warm scribe my hand is in the grave.\n"; + private static final String FALL_OF_HYPERION_A_DREAM = + """ + Fanatics have their dreams, wherewith they weave + A paradise for a sect; the savage too + From forth the loftiest fashion of his sleep + Guesses at Heaven; pity these have not + Trac'd upon vellum or wild Indian leaf + The shadows of melodious utterance. + But bare of laurel they live, dream, and die; + For Poesy alone can tell her dreams, + With the fine spell of words alone can save + Imagination from the sable charm + And dumb enchantment. Who alive can say, + 'Thou art no Poet may'st not tell thy dreams?' + Since every man whose soul is not a clod + Hath visions, and would speak, if he had loved + And been well nurtured in his mother tongue. + Whether the dream now purpos'd to rehearse + Be poet's or fanatic's will be known + When this warm scribe my hand is in the grave. + """; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); diff --git a/core/src/test/java/google/registry/rde/GhostrydeTest.java b/core/src/test/java/google/registry/rde/GhostrydeTest.java index a2da69252..49b20603c 100644 --- a/core/src/test/java/google/registry/rde/GhostrydeTest.java +++ b/core/src/test/java/google/registry/rde/GhostrydeTest.java @@ -194,13 +194,15 @@ public class GhostrydeTest { // .isEqualTo("expect error"); String encryptedInputBase64 = - " hQEMA6WcEy81iaHVAQgAnn9bS6IOCTW2uZnITPWH8zIYr6K7YJslv38c4YU5eQqVhHC5PN0NhM2l\n" - + " i89U3lUE6gp3DdEEbTbugwXCHWyRL4fYTlpiHZjBn2vZdSS21EAG+q1XuTaD8DTjkC2G060/sW6i\n" - + " 0gSIkksqgubbSVZTxHEqh92tv35KCqiYc52hjKZIIGI8FHhpJOtDa3bhMMad8nrMy3vbv5LiYNh5\n" - + " j3DUCFhskU8Ldi1vBfXIonqUNLBrD/R471VVJyQ3NoGQTVUF9uXLoy+2dL0oBLc1Avj1XNP5PQ08\n" - + " MWlqmezkLdY0oHnQqTHYhYDxRo/Sw7xO1GLwWR11rcx/IAJloJbKSHTFeNJUAcKFnKvPDwBk3nnr\n" - + " uR505HtOj/tZDT5weVjhrlnmWXzaBRmYASy6PXZu6KzTbPUQTf4JeeJWdyw7glLMr2WPdMVPGZ8e\n" - + " gcFAjSJZjZlqohZyBUpP\n"; + """ + hQEMA6WcEy81iaHVAQgAnn9bS6IOCTW2uZnITPWH8zIYr6K7YJslv38c4YU5eQqVhHC5PN0NhM2l + i89U3lUE6gp3DdEEbTbugwXCHWyRL4fYTlpiHZjBn2vZdSS21EAG+q1XuTaD8DTjkC2G060/sW6i + 0gSIkksqgubbSVZTxHEqh92tv35KCqiYc52hjKZIIGI8FHhpJOtDa3bhMMad8nrMy3vbv5LiYNh5 + j3DUCFhskU8Ldi1vBfXIonqUNLBrD/R471VVJyQ3NoGQTVUF9uXLoy+2dL0oBLc1Avj1XNP5PQ08 + MWlqmezkLdY0oHnQqTHYhYDxRo/Sw7xO1GLwWR11rcx/IAJloJbKSHTFeNJUAcKFnKvPDwBk3nnr + uR505HtOj/tZDT5weVjhrlnmWXzaBRmYASy6PXZu6KzTbPUQTf4JeeJWdyw7glLMr2WPdMVPGZ8e + gcFAjSJZjZlqohZyBUpP + """; byte[] result = Ghostryde.decode(Base64.getMimeDecoder().decode(encryptedInputBase64), privateKey); diff --git a/core/src/test/java/google/registry/rde/RdeMarshallerTest.java b/core/src/test/java/google/registry/rde/RdeMarshallerTest.java index 6bb996816..b242d69bd 100644 --- a/core/src/test/java/google/registry/rde/RdeMarshallerTest.java +++ b/core/src/test/java/google/registry/rde/RdeMarshallerTest.java @@ -40,39 +40,41 @@ public class RdeMarshallerTest { new RdeMarshaller(STRICT).marshalRegistrar(loadRegistrar("TheRegistrar")); assertThat(fragment.type()).isEqualTo(RdeResourceType.REGISTRAR); assertThat(fragment.error()).isEmpty(); - String expected = "" - + "\n" - + " TheRegistrar\n" - + " The Registrar\n" - + " 1\n" - + " ok\n" - + " \n" - + " \n" - + " 123 Example Bőulevard\n" - + " Williamsburg\n" - + " NY\n" - + " 11211\n" - + " US\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " 123 Example Boulevard\n" - + " Williamsburg\n" - + " NY\n" - + " 11211\n" - + " US\n" - + " \n" - + " \n" - + " +1.2223334444\n" - + " the.registrar@example.com\n" - + " http://my.fake.url\n" - + " \n" - + " whois.nic.fakewhois.example\n" - + " \n" - + " mine eyes have seen the glory\n" - + " of the coming of the borg\n" - + "\n"; + String expected = + """ + + TheRegistrar + The Registrar + 1 + ok + + + 123 Example Bőulevard + Williamsburg + NY + 11211 + US + + + + + 123 Example Boulevard + Williamsburg + NY + 11211 + US + + + +1.2223334444 + the.registrar@example.com + http://my.fake.url + + whois.nic.fakewhois.example + + mine eyes have seen the glory + of the coming of the borg + + """; XmlTestUtils.assertXmlEquals(DECLARATION + expected, DECLARATION + fragment.xml(), "registrar.crDate", "registrar.upDate"); diff --git a/core/src/test/java/google/registry/reporting/billing/CopyDetailReportsActionTest.java b/core/src/test/java/google/registry/reporting/billing/CopyDetailReportsActionTest.java index 58811a937..c4b9568e2 100644 --- a/core/src/test/java/google/registry/reporting/billing/CopyDetailReportsActionTest.java +++ b/core/src/test/java/google/registry/reporting/billing/CopyDetailReportsActionTest.java @@ -177,18 +177,22 @@ class CopyDetailReportsActionTest { "hello,world\n1,2".getBytes(UTF_8)); verify(emailUtils) .sendAlertEmail( - "Copied detail reports.\n" - + "The following errors were encountered:\n" - + "Registrar: TheRegistrar\n" - + "Error: java.io.IOException: expected\n"); + """ + Copied detail reports. + The following errors were encountered: + Registrar: TheRegistrar + Error: java.io.IOException: expected + """); assertThat(response.getStatus()).isEqualTo(SC_OK); assertThat(response.getContentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8); assertThat(response.getPayload()) .isEqualTo( - "Copied detail reports.\n" - + "The following errors were encountered:\n" - + "Registrar: TheRegistrar\n" - + "Error: java.io.IOException: expected\n"); + """ + Copied detail reports. + The following errors were encountered: + Registrar: TheRegistrar + Error: java.io.IOException: expected + """); } @Test diff --git a/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java b/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java index d5ec1d7ce..3c5bba0cf 100644 --- a/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java +++ b/core/src/test/java/google/registry/reporting/icann/IcannReportingStagerTest.java @@ -48,10 +48,9 @@ class IcannReportingStagerTest { private IcannReportingStager createStager() { IcannReportingStager action = new IcannReportingStager(); - ActivityReportingQueryBuilder activityBuilder = + action.activityQueryBuilder = new ActivityReportingQueryBuilder( "test-project", "icann_reporting", new BasicDnsCountQueryCoordinator(null)); - action.activityQueryBuilder = activityBuilder; action.transactionsQueryBuilder = new TransactionsReportingQueryBuilder("test-project", "icann_reporting"); action.reportingBucket = "test-bucket"; @@ -156,7 +155,7 @@ class IcannReportingStagerTest { } private ListenableFuture fakeFuture() { - return new ListenableFuture() { + return new ListenableFuture<>() { @Override public void addListener(Runnable runnable, Executor executor) { // No-op diff --git a/core/src/test/java/google/registry/request/UrlConnectionUtilsTest.java b/core/src/test/java/google/registry/request/UrlConnectionUtilsTest.java index 832817b19..60eb9d937 100644 --- a/core/src/test/java/google/registry/request/UrlConnectionUtilsTest.java +++ b/core/src/test/java/google/registry/request/UrlConnectionUtilsTest.java @@ -79,12 +79,14 @@ public class UrlConnectionUtilsTest { + " boundary=\"------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"", "294"); String payload = - "--------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n" - + "Content-Disposition: form-data; name=\"lol\"; filename=\"cat\"\r\n" - + "Content-Type: text/csv; charset=utf-8\r\n" - + "\r\n" - + "The nice people at the store say hello. ヘ(◕。◕ヘ)\r\n" - + "--------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA--\r\n"; + """ + --------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r + Content-Disposition: form-data; name="lol"; filename="cat"\r + Content-Type: text/csv; charset=utf-8\r + \r + The nice people at the store say hello. ヘ(◕。◕ヘ)\r + --------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA--\r + """; verify(connection).setDoOutput(true); verify(connection).getOutputStream(); assertThat(connectionOutputStream.toByteArray()).isEqualTo(payload.getBytes(UTF_8)); diff --git a/core/src/test/java/google/registry/server/RegistryTestServerMain.java b/core/src/test/java/google/registry/server/RegistryTestServerMain.java index 13e71586a..2c478a0d1 100644 --- a/core/src/test/java/google/registry/server/RegistryTestServerMain.java +++ b/core/src/test/java/google/registry/server/RegistryTestServerMain.java @@ -106,30 +106,34 @@ public final class RegistryTestServerMain { System.setProperty("VERBOSE", "true"); } - System.out.printf("\n" - + " CHARLESTON ROAD REGISTRY SHARED REGISTRATION SYSTEM\n" - + " ICANN-GTLD-AGB-20120604\n\n%s" - + " ▓█████▄ ▒█████ ███▄ ▄███▓ ▄▄▄ ██▓ ███▄ █\n" - + " ▒██▀ ██▌▒██▒ ██▒▓██▒▀█▀ ██▒▒████▄ ▓██▒ ██ ▀█ █\n" - + " ░██ █▌▒██░ ██▒▓██ ▓██░▒██ ▀█▄ ▒██▒▓██ ▀█ ██▒\n" - + " ░▓█▄ ▌▒██ ██░▒██ ▒██ ░██▄▄▄▄██ ░██░▓██▒ ▐▌██▒\n" - + " ░▒████▓ ░ ████▓▒░▒██▒ ░██▒ ▓█ ▓██▒░██░▒██░ ▓██░\n" - + " ▒▒▓ ▒ ░ ▒░▒░▒░ ░ ▒░ ░ ░ ▒▒ ▓▒█░░▓ ░ ▒░ ▒ ▒\n" - + " ░ ▒ ▒ ░ ▒ ▒░ ░ ░ ░ ▒ ▒▒ ░ ▒ ░░ ░░ ░ ▒░\n" - + " ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ▒ ▒ ░ ░ ░ ░\n" - + " ░ ░ ░ ░ ░ ░ ░ ░\n" - + " ░\n%s" - + " ██▀███ ▓█████ ▄████ ██▓ ██████ ▄▄▄█████▓ ██▀███ ▓██ ██▓\n" - + " ▓██ ▒ ██▒▓█ ▀ ██▒ ▀█▒▓██▒▒██ ▒ ▓ ██▒ ▓▒▓██ ▒ ██▒▒██ ██▒\n" - + " ▓██ ░▄█ ▒▒███ ▒██░▄▄▄░▒██▒░ ▓██▄ ▒ ▓██░ ▒░▓██ ░▄█ ▒ ▒██ ██░\n" - + " ▒██▀▀█▄ ▒▓█ ▄ ░▓█ ██▓░██░ ▒ ██▒░ ▓██▓ ░ ▒██▀▀█▄ ░ ▐██▓░\n" - + " ░██▓ ▒██▒░▒████▒░▒▓███▀▒░██░▒██████▒▒ ▒██▒ ░ ░██▓ ▒██▒ ░ ██▒▓░\n" - + " ░ ▒▓ ░▒▓░░░ ▒░ ░ ░▒ ▒ ░▓ ▒ ▒▓▒ ▒ ░ ▒ ░░ ░ ▒▓ ░▒▓░ ██▒▒▒\n" - + " ░▒ ░ ▒░ ░ ░ ░ ░ ░ ▒ ░░ ░▒ ░ ░ ░ ░▒ ░ ▒░▓██ ░▒░\n" - + " ░░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░░ ░ ▒ ▒ ░░\n" - + " ░ ░ ░ ░ ░ ░ ░ ░ ░\n" - + " ░ ░\n%s" - + "(✿◕ ‿◕ )ノ%s\n", + System.out.printf( + """ + + CHARLESTON ROAD REGISTRY SHARED REGISTRATION SYSTEM + ICANN-GTLD-AGB-20120604 + + %s ▓█████▄ ▒█████ ███▄ ▄███▓ ▄▄▄ ██▓ ███▄ █ + ▒██▀ ██▌▒██▒ ██▒▓██▒▀█▀ ██▒▒████▄ ▓██▒ ██ ▀█ █ + ░██ █▌▒██░ ██▒▓██ ▓██░▒██ ▀█▄ ▒██▒▓██ ▀█ ██▒ + ░▓█▄ ▌▒██ ██░▒██ ▒██ ░██▄▄▄▄██ ░██░▓██▒ ▐▌██▒ + ░▒████▓ ░ ████▓▒░▒██▒ ░██▒ ▓█ ▓██▒░██░▒██░ ▓██░ + ▒▒▓ ▒ ░ ▒░▒░▒░ ░ ▒░ ░ ░ ▒▒ ▓▒█░░▓ ░ ▒░ ▒ ▒ + ░ ▒ ▒ ░ ▒ ▒░ ░ ░ ░ ▒ ▒▒ ░ ▒ ░░ ░░ ░ ▒░ + ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ▒ ▒ ░ ░ ░ ░ + ░ ░ ░ ░ ░ ░ ░ ░ + ░ + %s ██▀███ ▓█████ ▄████ ██▓ ██████ ▄▄▄█████▓ ██▀███ ▓██ ██▓ + ▓██ ▒ ██▒▓█ ▀ ██▒ ▀█▒▓██▒▒██ ▒ ▓ ██▒ ▓▒▓██ ▒ ██▒▒██ ██▒ + ▓██ ░▄█ ▒▒███ ▒██░▄▄▄░▒██▒░ ▓██▄ ▒ ▓██░ ▒░▓██ ░▄█ ▒ ▒██ ██░ + ▒██▀▀█▄ ▒▓█ ▄ ░▓█ ██▓░██░ ▒ ██▒░ ▓██▓ ░ ▒██▀▀█▄ ░ ▐██▓░ + ░██▓ ▒██▒░▒████▒░▒▓███▀▒░██░▒██████▒▒ ▒██▒ ░ ░██▓ ▒██▒ ░ ██▒▓░ + ░ ▒▓ ░▒▓░░░ ▒░ ░ ░▒ ▒ ░▓ ▒ ▒▓▒ ▒ ░ ▒ ░░ ░ ▒▓ ░▒▓░ ██▒▒▒ + ░▒ ░ ▒░ ░ ░ ░ ░ ░ ▒ ░░ ░▒ ░ ░ ░ ░▒ ░ ▒░▓██ ░▒░ + ░░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░░ ░ ▒ ▒ ░░ + ░ ░ ░ ░ ░ ░ ░ ░ ░ + ░ ░ + %s(✿◕ ‿◕ )ノ%s + """, LIGHT_PURPLE, ORANGE, PINK, RESET); final RegistryTestServer server = new RegistryTestServer(address); diff --git a/core/src/test/java/google/registry/server/ServletWrapperDelegatorServlet.java b/core/src/test/java/google/registry/server/ServletWrapperDelegatorServlet.java index 00e4519c8..9f18918d6 100644 --- a/core/src/test/java/google/registry/server/ServletWrapperDelegatorServlet.java +++ b/core/src/test/java/google/registry/server/ServletWrapperDelegatorServlet.java @@ -52,7 +52,7 @@ public final class ServletWrapperDelegatorServlet extends HttpServlet { throws ServletException, IOException { FutureTask task = new FutureTask<>( - new Callable() { + new Callable<>() { @Nullable @Override public Void call() throws ServletException, IOException { diff --git a/core/src/test/java/google/registry/server/StaticResourceServlet.java b/core/src/test/java/google/registry/server/StaticResourceServlet.java index 75149750f..b14af05f7 100644 --- a/core/src/test/java/google/registry/server/StaticResourceServlet.java +++ b/core/src/test/java/google/registry/server/StaticResourceServlet.java @@ -107,14 +107,7 @@ public final class StaticResourceServlet extends HttpServlet { fileServer.get().doGet(req, rsp); } - private static final class FileServer { - private final Path root; - private final String prefix; - - FileServer(Path root, String prefix) { - this.root = root; - this.prefix = prefix; - } + private record FileServer(Path root, String prefix) { Optional doHead(HttpServletRequest req, HttpServletResponse rsp) throws IOException { verify(req.getRequestURI().startsWith(prefix)); diff --git a/core/src/test/java/google/registry/testing/CertificateSamples.java b/core/src/test/java/google/registry/testing/CertificateSamples.java index dcd552c6f..51dcbe5ad 100644 --- a/core/src/test/java/google/registry/testing/CertificateSamples.java +++ b/core/src/test/java/google/registry/testing/CertificateSamples.java @@ -17,35 +17,36 @@ package google.registry.testing; /** Utility methods for tests that involve certificates. */ public final class CertificateSamples { - /* * openssl req -new -nodes -x509 -days 10000 -newkey rsa:2048 -keyout client1.key -out client1.crt * -subj "/C=US/ST=New York/L=New York/O=Google/OU=domain-registry-test/CN=client1" */ - public static final String SAMPLE_CERT = "" - + "-----BEGIN CERTIFICATE-----\n" - + "MIIDvTCCAqWgAwIBAgIJAK/PgPT0jTwRMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV\n" - + "BAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8GA1UEBwwITmV3IFlvcmsxDzAN\n" - + "BgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWluLXJlZ2lzdHJ5LXRlc3QxEDAO\n" - + "BgNVBAMMB2NsaWVudDEwHhcNMTUwODI2MTkxODA4WhcNNDMwMTExMTkxODA4WjB1\n" - + "MQswCQYDVQQGEwJVUzERMA8GA1UECAwITmV3IFlvcmsxETAPBgNVBAcMCE5ldyBZ\n" - + "b3JrMQ8wDQYDVQQKDAZHb29nbGUxHTAbBgNVBAsMFGRvbWFpbi1yZWdpc3RyeS10\n" - + "ZXN0MRAwDgYDVQQDDAdjbGllbnQxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" - + "CgKCAQEAvoE/IoFJyzb0dU4NFhL8FYgy+B/GnUd5aA66CMx5xKRMbEAtIgxU8TTO\n" - + "W+9jdTsE00Grk3Ct4KdY73CYW+6IFXL4O0K/m5S+uajh+I2UMVZJV38RAIqNxue0\n" - + "Egv9M4haSsCVIPcX9b+6McywfYSF1bzPb2Gb2FAQO7Jb0BjlPhPMIROCrbG40qPg\n" - + "LWrl33dz+O52kO+DyZEzHqI55xH6au77sMITsJe+X23lzQcMFUUm8moiOw0EKrj/\n" - + "GaMTZLHP46BCRoJDAPTNx55seIwgAHbKA2VVtqrvmA2XYJQA6ipdhfKRoJFy8Z8H\n" - + "DYsorGtazQL2HhF/5uJD25z1m5eQHQIDAQABo1AwTjAdBgNVHQ4EFgQUParEmiSR\n" - + "U/Oqy8hr7k+MBKhZwVkwHwYDVR0jBBgwFoAUParEmiSRU/Oqy8hr7k+MBKhZwVkw\n" - + "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAojsUhF6PtZrStnHBFWNR\n" - + "ryzvANB8krZlYeX9Hkqn8zIVfAkpbVmL8aZQ7yj17jSpw47PQh3x5gwA9yc/SS0G\n" - + "E1rGuxYH02UGbua8G0+vviSQfLtskPQzK7EIR63WNhHEo/Q9umLJkZ0LguWEBf3L\n" - + "q8CoXv2i/RNvqVPcTNp/zCKXJZAa8wAjNRJs834AZj4k5xwyYZ3F8D5PGz+YMOmV\n" - + "M9Qd+NdXSC/Qn7HQzFhE8p5elBV35P8oX5dXEfn0S7zOXDenp5JvvLoggOWOcKsq\n" - + "KiWDQrsT+TMKmHL94/h4t7FghtQLMzY5SGYJsYTv/LG8tewrz6KRb/Wj3JNojyEw\n" - + "Ug==\n" - + "-----END CERTIFICATE-----\n"; + public static final String SAMPLE_CERT = + """ + -----BEGIN CERTIFICATE----- + MIIDvTCCAqWgAwIBAgIJAK/PgPT0jTwRMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV + BAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8GA1UEBwwITmV3IFlvcmsxDzAN + BgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWluLXJlZ2lzdHJ5LXRlc3QxEDAO + BgNVBAMMB2NsaWVudDEwHhcNMTUwODI2MTkxODA4WhcNNDMwMTExMTkxODA4WjB1 + MQswCQYDVQQGEwJVUzERMA8GA1UECAwITmV3IFlvcmsxETAPBgNVBAcMCE5ldyBZ + b3JrMQ8wDQYDVQQKDAZHb29nbGUxHTAbBgNVBAsMFGRvbWFpbi1yZWdpc3RyeS10 + ZXN0MRAwDgYDVQQDDAdjbGllbnQxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB + CgKCAQEAvoE/IoFJyzb0dU4NFhL8FYgy+B/GnUd5aA66CMx5xKRMbEAtIgxU8TTO + W+9jdTsE00Grk3Ct4KdY73CYW+6IFXL4O0K/m5S+uajh+I2UMVZJV38RAIqNxue0 + Egv9M4haSsCVIPcX9b+6McywfYSF1bzPb2Gb2FAQO7Jb0BjlPhPMIROCrbG40qPg + LWrl33dz+O52kO+DyZEzHqI55xH6au77sMITsJe+X23lzQcMFUUm8moiOw0EKrj/ + GaMTZLHP46BCRoJDAPTNx55seIwgAHbKA2VVtqrvmA2XYJQA6ipdhfKRoJFy8Z8H + DYsorGtazQL2HhF/5uJD25z1m5eQHQIDAQABo1AwTjAdBgNVHQ4EFgQUParEmiSR + U/Oqy8hr7k+MBKhZwVkwHwYDVR0jBBgwFoAUParEmiSRU/Oqy8hr7k+MBKhZwVkw + DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAojsUhF6PtZrStnHBFWNR + ryzvANB8krZlYeX9Hkqn8zIVfAkpbVmL8aZQ7yj17jSpw47PQh3x5gwA9yc/SS0G + E1rGuxYH02UGbua8G0+vviSQfLtskPQzK7EIR63WNhHEo/Q9umLJkZ0LguWEBf3L + q8CoXv2i/RNvqVPcTNp/zCKXJZAa8wAjNRJs834AZj4k5xwyYZ3F8D5PGz+YMOmV + M9Qd+NdXSC/Qn7HQzFhE8p5elBV35P8oX5dXEfn0S7zOXDenp5JvvLoggOWOcKsq + KiWDQrsT+TMKmHL94/h4t7FghtQLMzY5SGYJsYTv/LG8tewrz6KRb/Wj3JNojyEw + Ug== + -----END CERTIFICATE----- + """; /* * python -c "import sys;print sys.argv[1].decode('hex').encode('base64').strip('\n=')" $(openssl @@ -57,30 +58,32 @@ public final class CertificateSamples { * openssl req -new -nodes -x509 -days 10000 -newkey rsa:2048 -keyout client2.key -out client2.crt * -subj "/C=US/ST=New York/L=New York/O=Google/OU=domain-registry-test/CN=client2" */ - public static final String SAMPLE_CERT2 = "" - + "-----BEGIN CERTIFICATE-----\n" - + "MIIDvTCCAqWgAwIBAgIJANoEy6mYwalPMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV\n" - + "BAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8GA1UEBwwITmV3IFlvcmsxDzAN\n" - + "BgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWluLXJlZ2lzdHJ5LXRlc3QxEDAO\n" - + "BgNVBAMMB2NsaWVudDIwHhcNMTUwODI2MTkyODU3WhcNNDMwMTExMTkyODU3WjB1\n" - + "MQswCQYDVQQGEwJVUzERMA8GA1UECAwITmV3IFlvcmsxETAPBgNVBAcMCE5ldyBZ\n" - + "b3JrMQ8wDQYDVQQKDAZHb29nbGUxHTAbBgNVBAsMFGRvbWFpbi1yZWdpc3RyeS10\n" - + "ZXN0MRAwDgYDVQQDDAdjbGllbnQyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" - + "CgKCAQEAw2FtuDyoR+rUJHp6k7KwaoHGHPV1xnC8IpG9O0SZubOXrFrnBHggBsbu\n" - + "+DsknbHXjmoihSFFem0KQqJg5y34aDAHXQV3iqa7nDfb1x4oc5voVz9gqjdmGKNm\n" - + "WF4MTIPNMu8KY52M852mMCxODK+6MZYp7wCmVa63KdCm0bW/XsLgoA/+FVGwKLhf\n" - + "UqFzt10Cf+87zl4VHrSaJqcHBYM6yAO5lvkr5VC6g8rRQ+dJ+pBT2D99YpSF1aFc\n" - + "rWbBreIypixZAnXm/Xoogu6RnohS29VCJp2dXFAJmKXGwyKNQFXfEKxZBaBi8uKH\n" - + "XF459795eyF9xHgSckEgu7jZlxOk6wIDAQABo1AwTjAdBgNVHQ4EFgQUv26AsQyc\n" - + "kLOjkhqcFLOuueB33l4wHwYDVR0jBBgwFoAUv26AsQyckLOjkhqcFLOuueB33l4w\n" - + "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEANBuV+QDISSnGAEHKbR40\n" - + "zUYdOjdZ399zcFNqTSPHwmE0Qu8pbmXhofpBfjzrcv0tkVbhSLYnT22qhx7aDmhb\n" - + "bOS8CeVYCwl5eiDTkJly3pRZLzJpy+UT5z8SPxO3MrTqn+wuj0lBpWRTBCWYAUpr\n" - + "IFRmgVB3IwVb60UIuxhmuk8TVss2SzNrdhdt36eAIPJ0RWEb0KHYHi35Y6lt4f+t\n" - + "iVk+ZR0cCbHUs7Q1RqREXHd/ICuMRLY/MsadVQ9WDqVOridh198X/OIqdx/p9kvJ\n" - + "1R80jDcVGNhYVXLmHu4ho4xrOaliSYvUJSCmaaSEGVZ/xE5PI7S6A8RMdj0iXLSt\n" - + "Bg==\n" - + "-----END CERTIFICATE-----\n"; + public static final String SAMPLE_CERT2 = + """ + -----BEGIN CERTIFICATE----- + MIIDvTCCAqWgAwIBAgIJANoEy6mYwalPMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV + BAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8GA1UEBwwITmV3IFlvcmsxDzAN + BgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWluLXJlZ2lzdHJ5LXRlc3QxEDAO + BgNVBAMMB2NsaWVudDIwHhcNMTUwODI2MTkyODU3WhcNNDMwMTExMTkyODU3WjB1 + MQswCQYDVQQGEwJVUzERMA8GA1UECAwITmV3IFlvcmsxETAPBgNVBAcMCE5ldyBZ + b3JrMQ8wDQYDVQQKDAZHb29nbGUxHTAbBgNVBAsMFGRvbWFpbi1yZWdpc3RyeS10 + ZXN0MRAwDgYDVQQDDAdjbGllbnQyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB + CgKCAQEAw2FtuDyoR+rUJHp6k7KwaoHGHPV1xnC8IpG9O0SZubOXrFrnBHggBsbu + +DsknbHXjmoihSFFem0KQqJg5y34aDAHXQV3iqa7nDfb1x4oc5voVz9gqjdmGKNm + WF4MTIPNMu8KY52M852mMCxODK+6MZYp7wCmVa63KdCm0bW/XsLgoA/+FVGwKLhf + UqFzt10Cf+87zl4VHrSaJqcHBYM6yAO5lvkr5VC6g8rRQ+dJ+pBT2D99YpSF1aFc + rWbBreIypixZAnXm/Xoogu6RnohS29VCJp2dXFAJmKXGwyKNQFXfEKxZBaBi8uKH + XF459795eyF9xHgSckEgu7jZlxOk6wIDAQABo1AwTjAdBgNVHQ4EFgQUv26AsQyc + kLOjkhqcFLOuueB33l4wHwYDVR0jBBgwFoAUv26AsQyckLOjkhqcFLOuueB33l4w + DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEANBuV+QDISSnGAEHKbR40 + zUYdOjdZ399zcFNqTSPHwmE0Qu8pbmXhofpBfjzrcv0tkVbhSLYnT22qhx7aDmhb + bOS8CeVYCwl5eiDTkJly3pRZLzJpy+UT5z8SPxO3MrTqn+wuj0lBpWRTBCWYAUpr + IFRmgVB3IwVb60UIuxhmuk8TVss2SzNrdhdt36eAIPJ0RWEb0KHYHi35Y6lt4f+t + iVk+ZR0cCbHUs7Q1RqREXHd/ICuMRLY/MsadVQ9WDqVOridh198X/OIqdx/p9kvJ + 1R80jDcVGNhYVXLmHu4ho4xrOaliSYvUJSCmaaSEGVZ/xE5PI7S6A8RMdj0iXLSt + Bg== + -----END CERTIFICATE----- + """; /* * python -c "import sys;print sys.argv[1].decode('hex').encode('base64').strip('\n=')" $(openssl @@ -93,29 +96,31 @@ public final class CertificateSamples { * -subj "/C=US/ST=New York/L=New York/O=Google/OU=domain-registry-test/CN=client1" */ public static final String SAMPLE_CERT3 = - "-----BEGIN CERTIFICATE-----\n" - + "MIIDyzCCArOgAwIBAgIUJnhiVrxAxgwkLJzHPm1w/lBoNs4wDQYJKoZIhvcNAQEL\n" - + "BQAwdTELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE5ldyBZb3JrMREwDwYDVQQHDAhO\n" - + "ZXcgWW9yazEPMA0GA1UECgwGR29vZ2xlMR0wGwYDVQQLDBRkb21haW4tcmVnaXN0\n" - + "cnktdGVzdDEQMA4GA1UEAwwHY2xpZW50MTAeFw0yMDEwMTIxNzU5NDFaFw0yMTA0\n" - + "MzAxNzU5NDFaMHUxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8G\n" - + "A1UEBwwITmV3IFlvcmsxDzANBgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWlu\n" - + "LXJlZ2lzdHJ5LXRlc3QxEDAOBgNVBAMMB2NsaWVudDEwggEiMA0GCSqGSIb3DQEB\n" - + "AQUAA4IBDwAwggEKAoIBAQC0msirO7kXyGEC93stsNYGc02Z77Q2qfHFwaGYkUG8\n" - + "QvOF5SWN+jwTo5Td6Jj26A26a8MLCtK45TCBuMRNcUsHhajhT19ocphO20iY3zhi\n" - + "ycwV1id0iwME4kPd1m57BELRE9tUPOxF81/JQXdR1fwT5KRVHYRDWZhaZ5aBmlZY\n" - + "3t/H9Ly0RBYyApkMaGs3nlb94OOug6SouUfRt02S59ja3wsE2SVF/Eui647OXP7O\n" - + "QdYXofxuqLoNkE8EnAdl43/enGLiCIVd0G2lABibFF+gbxTtfgbg7YtfUZJdL+Mb\n" - + "RAcAtuLXEamNQ9H63JgVF16PlQVCDz2XyI3uCfPpDDiBAgMBAAGjUzBRMB0GA1Ud\n" - + "DgQWBBQ26bWk8qfEBjXs/xZ4m8JZyalnITAfBgNVHSMEGDAWgBQ26bWk8qfEBjXs\n" - + "/xZ4m8JZyalnITAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAZ\n" - + "VcsgslBKanKOieJ5ik2d9qzOMXKfBuWPRFWbkC3t9i5awhHqnGAaj6nICnnMZIyt\n" - + "rdx5lZW5aaQyf0EP/90JAA8Xmty4A6MXmEjQAMiCOpP3A7eeS6Xglgi8IOZl4/bg\n" - + "LonW62TUkilo5IiFt/QklFTeHIjXB+OvA8+2Quqyd+zp7v6KnhXjvaomim78DhwE\n" - + "0PIUnjmiRpGpHfTVioTdfhPHZ2Y93Y8K7juL93sQog9aBu5m9XRJCY6wGyWPE83i\n" - + "kmLfGzjcnaJ6kqCd9xQRFZ0JwHmGlkAQvFoeengbNUqSyjyVgsOoNkEsrWwe/JFO\n" - + "iqBvjEhJlvRoefvkdR98\n" - + "-----END CERTIFICATE-----\n"; + """ + -----BEGIN CERTIFICATE----- + MIIDyzCCArOgAwIBAgIUJnhiVrxAxgwkLJzHPm1w/lBoNs4wDQYJKoZIhvcNAQEL + BQAwdTELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE5ldyBZb3JrMREwDwYDVQQHDAhO + ZXcgWW9yazEPMA0GA1UECgwGR29vZ2xlMR0wGwYDVQQLDBRkb21haW4tcmVnaXN0 + cnktdGVzdDEQMA4GA1UEAwwHY2xpZW50MTAeFw0yMDEwMTIxNzU5NDFaFw0yMTA0 + MzAxNzU5NDFaMHUxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8G + A1UEBwwITmV3IFlvcmsxDzANBgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWlu + LXJlZ2lzdHJ5LXRlc3QxEDAOBgNVBAMMB2NsaWVudDEwggEiMA0GCSqGSIb3DQEB + AQUAA4IBDwAwggEKAoIBAQC0msirO7kXyGEC93stsNYGc02Z77Q2qfHFwaGYkUG8 + QvOF5SWN+jwTo5Td6Jj26A26a8MLCtK45TCBuMRNcUsHhajhT19ocphO20iY3zhi + ycwV1id0iwME4kPd1m57BELRE9tUPOxF81/JQXdR1fwT5KRVHYRDWZhaZ5aBmlZY + 3t/H9Ly0RBYyApkMaGs3nlb94OOug6SouUfRt02S59ja3wsE2SVF/Eui647OXP7O + QdYXofxuqLoNkE8EnAdl43/enGLiCIVd0G2lABibFF+gbxTtfgbg7YtfUZJdL+Mb + RAcAtuLXEamNQ9H63JgVF16PlQVCDz2XyI3uCfPpDDiBAgMBAAGjUzBRMB0GA1Ud + DgQWBBQ26bWk8qfEBjXs/xZ4m8JZyalnITAfBgNVHSMEGDAWgBQ26bWk8qfEBjXs + /xZ4m8JZyalnITAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAZ + VcsgslBKanKOieJ5ik2d9qzOMXKfBuWPRFWbkC3t9i5awhHqnGAaj6nICnnMZIyt + rdx5lZW5aaQyf0EP/90JAA8Xmty4A6MXmEjQAMiCOpP3A7eeS6Xglgi8IOZl4/bg + LonW62TUkilo5IiFt/QklFTeHIjXB+OvA8+2Quqyd+zp7v6KnhXjvaomim78DhwE + 0PIUnjmiRpGpHfTVioTdfhPHZ2Y93Y8K7juL93sQog9aBu5m9XRJCY6wGyWPE83i + kmLfGzjcnaJ6kqCd9xQRFZ0JwHmGlkAQvFoeengbNUqSyjyVgsOoNkEsrWwe/JFO + iqBvjEhJlvRoefvkdR98 + -----END CERTIFICATE----- + """; /* * python -c "import sys;print sys.argv[1].decode('hex').encode('base64').strip('\n=')" $(openssl diff --git a/core/src/test/java/google/registry/testing/DeterministicStringGenerator.java b/core/src/test/java/google/registry/testing/DeterministicStringGenerator.java index a91930d62..3043949ab 100644 --- a/core/src/test/java/google/registry/testing/DeterministicStringGenerator.java +++ b/core/src/test/java/google/registry/testing/DeterministicStringGenerator.java @@ -64,13 +64,13 @@ public class DeterministicStringGenerator extends StringGenerator { for (int i = 0; i < length; i++) { password.append(iterator.next()); } - switch (rule) { - case PREPEND_COUNTER: - return String.format("%04d_%s", counter++, password.toString()); - case DEFAULT: - default: - return password.toString(); - } + return switch (rule) { + case PREPEND_COUNTER -> String.format("%04d_%s", counter++, password.toString()); + case DEFAULT -> password.toString(); + default -> + throw new IllegalStateException( + String.format("Unknown string generation rule: %s", rule)); + }; } public DeterministicStringGenerator(@Named("alphabetBase64") String alphabet, Rule rule) { diff --git a/core/src/test/java/google/registry/testing/GpgSystemCommandExtension.java b/core/src/test/java/google/registry/testing/GpgSystemCommandExtension.java index 6ee36c90e..62985cb0d 100644 --- a/core/src/test/java/google/registry/testing/GpgSystemCommandExtension.java +++ b/core/src/test/java/google/registry/testing/GpgSystemCommandExtension.java @@ -79,7 +79,7 @@ public final class GpgSystemCommandExtension implements BeforeEachCallback, Afte * * @see Runtime#exec(String[]) */ - public final Process exec(String... args) throws IOException { + public Process exec(String... args) throws IOException { checkState(!Objects.equals(cwd, DEV_NULL)); checkArgument(args.length > 0, "args"); return runtime.exec(args, env, cwd); diff --git a/core/src/test/java/google/registry/testing/sftp/TestSftpServer.java b/core/src/test/java/google/registry/testing/sftp/TestSftpServer.java index af7da3a7c..47d643b4d 100644 --- a/core/src/test/java/google/registry/testing/sftp/TestSftpServer.java +++ b/core/src/test/java/google/registry/testing/sftp/TestSftpServer.java @@ -34,9 +34,6 @@ import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.scp.server.ScpCommandFactory; import org.apache.sshd.server.ServerBuilder; import org.apache.sshd.server.SshServer; -import org.apache.sshd.server.auth.password.PasswordAuthenticator; -import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; -import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMKeyPair; @@ -54,34 +51,36 @@ public class TestSftpServer implements FtpServer { Security.addProvider(new BouncyCastleProvider()); } - private static final String HOST_KEY = "" - + "-----BEGIN RSA PRIVATE KEY-----\n" - + "MIIEowIBAAKCAQEAx7uuoDyMR3c+sIg0fPfBeyoUjPa6hh3yN5S4/HLEOOaXcA2c\n" - + "uhNm8WwIXF/FwC32CJHZcCC3XhNeQDIpEt5wj9NHr++pjYWjp4Ue+n/2QbDO4LKB\n" - + "fb67zRbL++BZNswBKYwmzaiHoyWYERj+ZrZpf7hqHnKTAs4NIUCkhUvUHQzgdfT6\n" - + "vfEYv2HrM2VVVaqpUALrkogZHqQYfLA+InHXXZ3x+GmdSBCxaxUHHZypwETv+yBJ\n" - + "YAP+9Ofcmu3mpedK/3o3KJ2pD4OXwoXAtbHDOfnJMJylCKcCT3aodpdULSf4A8Zm\n" - + "o4fxppQCbGUw43D7u18he5qNdLDkgCV8iXewbQIDAQABAoIBAH/Fs9e0BDVvtj3u\n" - + "VE2hnTeyWsU2zWog3CPsU07ECH0yHqzDOIDdCpzk9JBLgFEJ1fvzebs+Yq+fCktd\n" - + "C2OTw0Ru78xAMCJl3KS9B21O0PWDK0UZTLdpffCcZc/y3H+ukAvJKcWky2h2E0rU\n" - + "x2JjzSe0jMZ/m0ZPFJ0yIk1XjhEqWgp3OCP9EHaO82+GM8UTuoBrfOs8gcv6aqiO\n" - + "L06BU6a6i75chUtZbSadaUnZOE8tIyXit6p63bBHp2oN4D8FiOPBuTDwFEI4zrA4\n" - + "vNcfRvKQWnQjlWm91BCajNxVqWi7XtWK7ikmwefZWNcd83RSf6vfb8ThpjwHmBaE\n" - + "dbbL9i0CgYEA+KwB5qiaRxryBI1xqQaH6HiQ5WtW06ft43l2FrTZGPocjyF7KyWn\n" - + "lS5q0J4tdSSkNfXqhT8aosm3VjfIxoDuQQO0ptD+km5qe1xu/qxLHJYd5FP67X9O\n" - + "66e8sxcDSuKSvZ6wNeKNOL5SC7dDLCuMZoRTvXxGneg9a1w2x1MVrZsCgYEAzZ56\n" - + "cqqNvavj4x2yDG+4oAB4/sQvVFK2+PopFpO5w8ezLDVfnoIv56gfmqMN9UdZH8Ew\n" - + "PJhuEFRcdePo2ZnNjsWf9NhniJSMsEPTIc5qOPyoo5DcQM6DU8f4HC236uR+5P0h\n" - + "jLfKRpvZl+N3skJi98QQr9PeLyb0sM8zRbZ0fpcCgYA9nuIZtk4EsLioSCSSLfwf\n" - + "r0C4mRC7AjIA3GhW2Bm0BsZs8W8EEiCk5wuxBoFdNec7N+UVf72p+TJlOw2Vov1n\n" - + "PvPVIpTy1EmuqAkZMriqLMjbe7QChjmYS8iG2H0IYXzbYCdqMumr1f2eyZrrpx7z\n" - + "iHb3zYPyPUp7AC7S1dPZYQKBgQCK0p+LQVk3IJFYalkmiltVM1x9bUkjHkFIseUB\n" - + "yDUYWIDArTxkkTL0rY7A4atv2X7zsIP3tVZCEiLmuTwhhfTBmu3W6jBkhx7Bdtla\n" - + "LrmKxhK5c/kwi/0gmJcLt1Y/8Ys24SxAjGm16E0tfjb3FFkrPKWjgGC25w83PH06\n" - + "aOgX+wKBgBLkLh/rwpiD4e8ZVjGuCn9A0H/2KZknXyNbkVjPho0FXBKIlfMa6c34\n" - + "fRLDvHVZ0xo4dQxp38Wg+ZzIwGoAHhuJpSsfMsWKVXwNwV4iMEt2zyZRomui3TzT\n" - + "+8awtDyALwvL05EBuxctT3iFGQcUj/fNCi0PeLoTSscdH2pdvHTb\n" - + "-----END RSA PRIVATE KEY-----\n"; + private static final String HOST_KEY = + """ + -----BEGIN RSA PRIVATE KEY----- + MIIEowIBAAKCAQEAx7uuoDyMR3c+sIg0fPfBeyoUjPa6hh3yN5S4/HLEOOaXcA2c + uhNm8WwIXF/FwC32CJHZcCC3XhNeQDIpEt5wj9NHr++pjYWjp4Ue+n/2QbDO4LKB + fb67zRbL++BZNswBKYwmzaiHoyWYERj+ZrZpf7hqHnKTAs4NIUCkhUvUHQzgdfT6 + vfEYv2HrM2VVVaqpUALrkogZHqQYfLA+InHXXZ3x+GmdSBCxaxUHHZypwETv+yBJ + YAP+9Ofcmu3mpedK/3o3KJ2pD4OXwoXAtbHDOfnJMJylCKcCT3aodpdULSf4A8Zm + o4fxppQCbGUw43D7u18he5qNdLDkgCV8iXewbQIDAQABAoIBAH/Fs9e0BDVvtj3u + VE2hnTeyWsU2zWog3CPsU07ECH0yHqzDOIDdCpzk9JBLgFEJ1fvzebs+Yq+fCktd + C2OTw0Ru78xAMCJl3KS9B21O0PWDK0UZTLdpffCcZc/y3H+ukAvJKcWky2h2E0rU + x2JjzSe0jMZ/m0ZPFJ0yIk1XjhEqWgp3OCP9EHaO82+GM8UTuoBrfOs8gcv6aqiO + L06BU6a6i75chUtZbSadaUnZOE8tIyXit6p63bBHp2oN4D8FiOPBuTDwFEI4zrA4 + vNcfRvKQWnQjlWm91BCajNxVqWi7XtWK7ikmwefZWNcd83RSf6vfb8ThpjwHmBaE + dbbL9i0CgYEA+KwB5qiaRxryBI1xqQaH6HiQ5WtW06ft43l2FrTZGPocjyF7KyWn + lS5q0J4tdSSkNfXqhT8aosm3VjfIxoDuQQO0ptD+km5qe1xu/qxLHJYd5FP67X9O + 66e8sxcDSuKSvZ6wNeKNOL5SC7dDLCuMZoRTvXxGneg9a1w2x1MVrZsCgYEAzZ56 + cqqNvavj4x2yDG+4oAB4/sQvVFK2+PopFpO5w8ezLDVfnoIv56gfmqMN9UdZH8Ew + PJhuEFRcdePo2ZnNjsWf9NhniJSMsEPTIc5qOPyoo5DcQM6DU8f4HC236uR+5P0h + jLfKRpvZl+N3skJi98QQr9PeLyb0sM8zRbZ0fpcCgYA9nuIZtk4EsLioSCSSLfwf + r0C4mRC7AjIA3GhW2Bm0BsZs8W8EEiCk5wuxBoFdNec7N+UVf72p+TJlOw2Vov1n + PvPVIpTy1EmuqAkZMriqLMjbe7QChjmYS8iG2H0IYXzbYCdqMumr1f2eyZrrpx7z + iHb3zYPyPUp7AC7S1dPZYQKBgQCK0p+LQVk3IJFYalkmiltVM1x9bUkjHkFIseUB + yDUYWIDArTxkkTL0rY7A4atv2X7zsIP3tVZCEiLmuTwhhfTBmu3W6jBkhx7Bdtla + LrmKxhK5c/kwi/0gmJcLt1Y/8Ys24SxAjGm16E0tfjb3FFkrPKWjgGC25w83PH06 + aOgX+wKBgBLkLh/rwpiD4e8ZVjGuCn9A0H/2KZknXyNbkVjPho0FXBKIlfMa6c34 + fRLDvHVZ0xo4dQxp38Wg+ZzIwGoAHhuJpSsfMsWKVXwNwV4iMEt2zyZRomui3TzT + +8awtDyALwvL05EBuxctT3iFGQcUj/fNCi0PeLoTSscdH2pdvHTb + -----END RSA PRIVATE KEY----- + """; private static final String KEY_TYPE = "ssh-rsa"; @@ -115,13 +114,8 @@ public class TestSftpServer implements FtpServer { // returns true, then the server will make sure that the user can prove they have that key. // Not that you would know this from the Apache javadocs. serverBuilder.publickeyAuthenticator( - new PublickeyAuthenticator() { - @Override - public boolean authenticate( - String username, PublicKey publicKey, ServerSession session) { - return Arrays.equals(publicKey.getEncoded(), authorizedPublicKey.getEncoded()); - } - }); + (username, publicKey, session) -> + Arrays.equals(publicKey.getEncoded(), authorizedPublicKey.getEncoded())); } serverBuilder.fileSystemFactory(new VirtualFileSystemFactory(home.toPath())); @@ -135,12 +129,8 @@ public class TestSftpServer implements FtpServer { if (authorizedPassword != null) { server.setPasswordAuthenticator( - new PasswordAuthenticator() { - @Override - public boolean authenticate(String username, String password, ServerSession session) { - return username.equals(authorizedUser) && password.equals(authorizedPassword); - } - }); + (username, password, session) -> + username.equals(authorizedUser) && password.equals(authorizedPassword)); } KeyPairProvider keyPairProvider = diff --git a/core/src/test/java/google/registry/tmch/NordnVerifyActionTest.java b/core/src/test/java/google/registry/tmch/NordnVerifyActionTest.java index 56c60be1c..7545fd7a4 100644 --- a/core/src/test/java/google/registry/tmch/NordnVerifyActionTest.java +++ b/core/src/test/java/google/registry/tmch/NordnVerifyActionTest.java @@ -48,30 +48,34 @@ import org.junit.jupiter.api.extension.RegisterExtension; class NordnVerifyActionTest { private static final String LOG_ACCEPTED = - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," - + "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,no-warnings,1\n" - + "roid,result-code\n" - + "SH8013-REP,2000"; + """ + 1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,no-warnings,1 + roid,result-code + SH8013-REP,2000"""; private static final String LOG_REJECTED = - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," - + "0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,rejected,no-warnings,1\n" - + "roid,result-code\n" - + "SH8013-REP,2001"; + """ + 1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,rejected,no-warnings,1 + roid,result-code + SH8013-REP,2001"""; private static final String LOG_WARNINGS = - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n" - + "roid,result-code\n" - + "SH8013-REP,2001\n" - + "lulz-roid,3609\n" - + "sabokitty-roid,3610\n"; + """ + 1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3 + roid,result-code + SH8013-REP,2001 + lulz-roid,3609 + sabokitty-roid,3610 + """; private static final String LOG_ERRORS = - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3\n" - + "roid,result-code\n" - + "SH8013-REP,2000\n" - + "lulz-roid,4601\n" - + "bogpog,4611\n"; + """ + 1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,0000000000000478Nzs+3VMkR8ckuUynOLmyeqTmZQSbzDuf/R50n2n5QX4=,accepted,warnings-present,3 + roid,result-code + SH8013-REP,2000 + lulz-roid,4601 + bogpog,4611 + """; @RegisterExtension final JpaIntegrationTestExtension jpa = diff --git a/core/src/test/java/google/registry/tools/AuthModuleTest.java b/core/src/test/java/google/registry/tools/AuthModuleTest.java index e3676d6bf..b1b550c6d 100644 --- a/core/src/test/java/google/registry/tools/AuthModuleTest.java +++ b/core/src/test/java/google/registry/tools/AuthModuleTest.java @@ -15,7 +15,6 @@ package google.registry.tools; import static com.google.common.truth.Truth.assertThat; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @@ -180,7 +179,7 @@ class AuthModuleTest { @MockitoSettings(strictness = Strictness.LENIENT) void test_provideExternalCredentialJson() throws Exception { File credentialFile = folder.resolve("credential.json").toFile(); - Files.write(credentialFile.toPath(), "{some_field: some_value}".getBytes(UTF_8)); + Files.writeString(credentialFile.toPath(), "{some_field: some_value}"); String credentialJson = AuthModule.provideLocalCredentialJson( AuthModuleTest::getSecrets, this::getCredential, credentialFile.getCanonicalPath()); diff --git a/core/src/test/java/google/registry/tools/CreatePremiumListCommandTest.java b/core/src/test/java/google/registry/tools/CreatePremiumListCommandTest.java index 5241734d8..947fdffe8 100644 --- a/core/src/test/java/google/registry/tools/CreatePremiumListCommandTest.java +++ b/core/src/test/java/google/registry/tools/CreatePremiumListCommandTest.java @@ -15,7 +15,6 @@ package google.registry.tools; import static com.google.common.truth.Truth.assertThat; -import static google.registry.testing.DatabaseHelper.createTld; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.io.Files; diff --git a/core/src/test/java/google/registry/tools/EppToolCommandTestCase.java b/core/src/test/java/google/registry/tools/EppToolCommandTestCase.java index 25264bfcd..8f1666f6f 100644 --- a/core/src/test/java/google/registry/tools/EppToolCommandTestCase.java +++ b/core/src/test/java/google/registry/tools/EppToolCommandTestCase.java @@ -22,8 +22,8 @@ import org.junit.jupiter.api.BeforeEach; /** * Abstract class for commands that construct + send EPP commands. * - * Has an EppToolVerifier member that needs to have all epp messages accounted for before the test - * has ended. + *

Has an EppToolVerifier member that needs to have all epp messages accounted for before the + * test has ended. * * @param the command type */ diff --git a/core/src/test/java/google/registry/tools/GenerateLordnCommandTest.java b/core/src/test/java/google/registry/tools/GenerateLordnCommandTest.java index 00328612d..83c90246c 100644 --- a/core/src/test/java/google/registry/tools/GenerateLordnCommandTest.java +++ b/core/src/test/java/google/registry/tools/GenerateLordnCommandTest.java @@ -55,17 +55,20 @@ class GenerateLordnCommandTest extends CommandTestCase { runCommand("-t tld", "-c " + claimsCsv, "-s " + sunriseCsv); assertThat(Files.readAllBytes(claimsCsv)) .isEqualTo( - ("1,2021-04-16T10:04:00.000Z,1\n" - + "roid,domain-name,notice-id,registrar-id,registration-datetime,ack-datetime,application-datetime\n" - + "6-TLD,fleecey.tld,smd3,1,1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.000Z\n") + """ + 1,2021-04-16T10:04:00.000Z,1 + roid,domain-name,notice-id,registrar-id,registration-datetime,ack-datetime,application-datetime + 6-TLD,fleecey.tld,smd3,1,1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.000Z + """ .getBytes(UTF_8)); assertThat(Files.readAllBytes(sunriseCsv)) .isEqualTo( - ("1,2021-04-16T10:04:00.001Z,2\n" - + "roid,domain-name,SMD-id,registrar-id,registration-datetime," - + "application-datetime\n" - + "2-TLD,sneezy.tld,smd1,1,1970-01-01T00:00:00.000Z\n" - + "4-TLD,wheezy.tld,smd2,1,1970-01-01T00:00:00.000Z\n") + """ + 1,2021-04-16T10:04:00.001Z,2 + roid,domain-name,SMD-id,registrar-id,registration-datetime,application-datetime + 2-TLD,sneezy.tld,smd1,1,1970-01-01T00:00:00.000Z + 4-TLD,wheezy.tld,smd2,1,1970-01-01T00:00:00.000Z + """ .getBytes(UTF_8)); } } diff --git a/core/src/test/java/google/registry/tools/GetClaimsListCommandTest.java b/core/src/test/java/google/registry/tools/GetClaimsListCommandTest.java index 9d7c51eb8..6bd4408e5 100644 --- a/core/src/test/java/google/registry/tools/GetClaimsListCommandTest.java +++ b/core/src/test/java/google/registry/tools/GetClaimsListCommandTest.java @@ -49,6 +49,6 @@ class GetClaimsListCommandTest extends CommandTestCase { ClaimsListDao.save(ClaimsList.create(DateTime.now(UTC), ImmutableMap.of("a", "1"))); File output = tmpDir.resolve("claims.txt").toFile(); runCommand("--output=" + output.getAbsolutePath()); - assertThat(new String(Files.readAllBytes(output.toPath()), UTF_8)).endsWith("\n"); + assertThat(Files.readString(output.toPath())).endsWith("\n"); } } diff --git a/core/src/test/java/google/registry/tools/GetHistoryEntriesCommandTest.java b/core/src/test/java/google/registry/tools/GetHistoryEntriesCommandTest.java index be66f4fbd..3fd5efe85 100644 --- a/core/src/test/java/google/registry/tools/GetHistoryEntriesCommandTest.java +++ b/core/src/test/java/google/registry/tools/GetHistoryEntriesCommandTest.java @@ -51,13 +51,15 @@ class GetHistoryEntriesCommandTest extends CommandTestCase\n" - + "\n" - + "\n"); + """ + Client: TheRegistrar + Time: 2000-01-01T00:00:00.000Z + Client TRID: ABC-123 + Server TRID: server-trid + + + + """); } @Test @@ -101,13 +103,15 @@ class GetHistoryEntriesCommandTest extends CommandTestCase\n" - + "\n" - + "\n"); + """ + Client: TheRegistrar + Time: 2000-01-01T00:00:00.000Z + Client TRID: ABC-123 + Server TRID: server-trid + + + + """); } @Test @@ -124,12 +128,14 @@ class GetHistoryEntriesCommandTest extends CommandTestCase\n" - + "\n" - + "\n"); + """ + Client: TheRegistrar + Time: 2000-01-01T00:00:00.000Z + Client TRID: null + Server TRID: null + + + + """); } } diff --git a/core/src/test/java/google/registry/tools/GetPremiumListCommandTest.java b/core/src/test/java/google/registry/tools/GetPremiumListCommandTest.java index 9a0369c5c..45fd40ffe 100644 --- a/core/src/test/java/google/registry/tools/GetPremiumListCommandTest.java +++ b/core/src/test/java/google/registry/tools/GetPremiumListCommandTest.java @@ -24,19 +24,21 @@ import org.junit.jupiter.api.Test; public class GetPremiumListCommandTest extends CommandTestCase { private static final String BASE_LIST_CONTENTS = - "tld:\n" - + "aluminum,USD 11.00\n" - + "brass,USD 20.00\n" - + "copper,USD 15.00\n" - + "diamond,USD 1000000.00\n" - + "gold,USD 24317.00\n" - + "iridium,USD 13117.00\n" - + "palladium,USD 877.00\n" - + "platinum,USD 87741.00\n" - + "rhodium,USD 88415.00\n" - + "rich,USD 100.00\n" - + "richer,USD 1000.00\n" - + "silver,USD 588.00\n"; + """ + tld: + aluminum,USD 11.00 + brass,USD 20.00 + copper,USD 15.00 + diamond,USD 1000000.00 + gold,USD 24317.00 + iridium,USD 13117.00 + palladium,USD 877.00 + platinum,USD 87741.00 + rhodium,USD 88415.00 + rich,USD 100.00 + richer,USD 1000.00 + silver,USD 588.00 + """; @BeforeEach void beforeEach() { diff --git a/core/src/test/java/google/registry/tools/GetReservedListCommandTest.java b/core/src/test/java/google/registry/tools/GetReservedListCommandTest.java index 0e34961a0..e6450375f 100644 --- a/core/src/test/java/google/registry/tools/GetReservedListCommandTest.java +++ b/core/src/test/java/google/registry/tools/GetReservedListCommandTest.java @@ -24,13 +24,15 @@ import org.junit.jupiter.api.Test; public class GetReservedListCommandTest extends CommandTestCase { private static final String BASE_LIST_CONTENTS = - "atlanta,RESERVED_FOR_SPECIFIC_USE # comment\n" - + "boston,RESERVED_FOR_SPECIFIC_USE\n" - + "chicago,FULLY_BLOCKED # another comment\n" - + "dallas,RESERVED_FOR_SPECIFIC_USE # cool city\n" - + "elpaso,RESERVED_FOR_SPECIFIC_USE\n" - + "fairbanks,RESERVED_FOR_ANCHOR_TENANT # alaska\n" - + "greensboro,RESERVED_FOR_SPECIFIC_USE\n"; + """ + atlanta,RESERVED_FOR_SPECIFIC_USE # comment + boston,RESERVED_FOR_SPECIFIC_USE + chicago,FULLY_BLOCKED # another comment + dallas,RESERVED_FOR_SPECIFIC_USE # cool city + elpaso,RESERVED_FOR_SPECIFIC_USE + fairbanks,RESERVED_FOR_ANCHOR_TENANT # alaska + greensboro,RESERVED_FOR_SPECIFIC_USE + """; @BeforeEach void beforeEach() { diff --git a/core/src/test/java/google/registry/tools/GhostrydeCommandTest.java b/core/src/test/java/google/registry/tools/GhostrydeCommandTest.java index cdb3295f5..9a0a10e0f 100644 --- a/core/src/test/java/google/registry/tools/GhostrydeCommandTest.java +++ b/core/src/test/java/google/registry/tools/GhostrydeCommandTest.java @@ -31,24 +31,27 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Unit tests for {@link GhostrydeCommand}. */ class GhostrydeCommandTest extends CommandTestCase { - private static final byte[] SONG_BY_CHRISTINA_ROSSETTI = ("" - + "When I am dead, my dearest, \n" - + " Sing no sad songs for me; \n" - + "Plant thou no roses at my head, \n" - + " Nor shady cypress tree: \n" - + "Be the green grass above me \n" - + " With showers and dewdrops wet; \n" - + "And if thou wilt, remember, \n" - + " And if thou wilt, forget. \n" - + " \n" - + "I shall not see the shadows, \n" - + " I shall not feel the rain; \n" - + "I shall not hear the nightingale \n" - + " Sing on, as if in pain: \n" - + "And dreaming through the twilight \n" - + " That doth not rise nor set, \n" - + "Haply I may remember, \n" - + " And haply may forget. \n").getBytes(UTF_8); + private static final byte[] SONG_BY_CHRISTINA_ROSSETTI = + """ + When I am dead, my dearest, \s + Sing no sad songs for me; \s + Plant thou no roses at my head, \s + Nor shady cypress tree: \s + Be the green grass above me \s + With showers and dewdrops wet; \s + And if thou wilt, remember, \s + And if thou wilt, forget. \s + \s + I shall not see the shadows, \s + I shall not feel the rain; \s + I shall not hear the nightingale \s + Sing on, as if in pain: \s + And dreaming through the twilight\s + That doth not rise nor set, \s + Haply I may remember, \s + And haply may forget. \s + """ + .getBytes(UTF_8); @RegisterExtension final BouncyCastleProviderExtension bouncy = new BouncyCastleProviderExtension(); diff --git a/core/src/test/java/google/registry/tools/MutatingCommandTest.java b/core/src/test/java/google/registry/tools/MutatingCommandTest.java index a3d42b286..76712d541 100644 --- a/core/src/test/java/google/registry/tools/MutatingCommandTest.java +++ b/core/src/test/java/google/registry/tools/MutatingCommandTest.java @@ -99,17 +99,19 @@ public class MutatingCommandTest { String changes = command.prompt(); assertThat(changes) .isEqualTo( - "Update Host@2-ROID\n" - + "lastEppUpdateTime: null -> 2014-09-09T09:09:09.000Z\n" - + "\n" - + "Update Host@3-ROID\n" - + "currentSponsorRegistrarId: TheRegistrar -> Registrar2\n" - + "\n" - + "Update Registrar@Registrar1\n" - + "poNumber: null -> 23\n" - + "\n" - + "Update Registrar@Registrar2\n" - + "blockPremiumNames: false -> true\n"); + """ + Update Host@2-ROID + lastEppUpdateTime: null -> 2014-09-09T09:09:09.000Z + + Update Host@3-ROID + currentSponsorRegistrarId: TheRegistrar -> Registrar2 + + Update Registrar@Registrar1 + poNumber: null -> 23 + + Update Registrar@Registrar2 + blockPremiumNames: false -> true + """); String results = command.execute(); assertThat(results).isEqualTo("Updated 4 entities.\n"); assertThat(loadByEntity(host1)).isEqualTo(newHost1); @@ -214,11 +216,13 @@ public class MutatingCommandTest { System.out.println(changes); assertThat(changes) .isEqualTo( - "Update Host@2-ROID\n" - + "[no changes]\n" - + "\n" - + "Update Registrar@Registrar1\n" - + "[no changes]\n"); + """ + Update Host@2-ROID + [no changes] + + Update Registrar@Registrar1 + [no changes] + """); String results = command.execute(); assertThat(results).isEqualTo("Updated 2 entities.\n"); assertThat(loadByEntity(host1)).isEqualTo(host1); diff --git a/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java b/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java index ca8d78282..8de35b4f9 100644 --- a/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java +++ b/core/src/test/java/google/registry/tools/UpdateCursorsCommandTest.java @@ -100,8 +100,10 @@ class UpdateCursorsCommandTest extends CommandTestCase { String changes = command.prompt(); assertThat(changes) .isEqualTo( - "Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z\n" - + "Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00.000Z\n"); + """ + Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z + Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00.000Z + """); } @Test @@ -117,8 +119,10 @@ class UpdateCursorsCommandTest extends CommandTestCase { String changes = command.prompt(); assertThat(changes) .isEqualTo( - "Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z\n" - + "Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00.000Z\n"); + """ + Change cursorTime of BRDA for Scope:foo to 1984-12-18T00:00:00.000Z + Change cursorTime of BRDA for Scope:bar to 1984-12-18T00:00:00.000Z + """); } @Test diff --git a/core/src/test/java/google/registry/tools/ValidateEscrowDepositCommandTest.java b/core/src/test/java/google/registry/tools/ValidateEscrowDepositCommandTest.java index bcd559697..6b1e5ee38 100644 --- a/core/src/test/java/google/registry/tools/ValidateEscrowDepositCommandTest.java +++ b/core/src/test/java/google/registry/tools/ValidateEscrowDepositCommandTest.java @@ -28,71 +28,77 @@ class ValidateEscrowDepositCommandTest extends CommandTestCaseEach of the Registrar fields can be changed only by a single {@link Role}. We make sure that * trying to update the field works if the user has the "correct" role, but fails if it doesn't. */ private void doTestUpdate( diff --git a/core/src/test/java/google/registry/webdriver/WebDriverScreenDiffer.java b/core/src/test/java/google/registry/webdriver/WebDriverScreenDiffer.java index 323f86fd2..0b62fb3a5 100644 --- a/core/src/test/java/google/registry/webdriver/WebDriverScreenDiffer.java +++ b/core/src/test/java/google/registry/webdriver/WebDriverScreenDiffer.java @@ -123,9 +123,10 @@ class WebDriverScreenDiffer implements ScreenDiffer { if (result.isConsideredSimilar()) { logger.atInfo().log( String.format( - "Screenshot test for [%s] passed:\n" - + " - golden image location: %s\n" - + " - screenshot image location: %s", + """ + Screenshot test for [%s] passed: + - golden image location: %s + - screenshot image location: %s""", imageName, goldenImagePath, persistedScreenshot.toAbsolutePath())); return ""; } else { @@ -138,9 +139,10 @@ class WebDriverScreenDiffer implements ScreenDiffer { } return String.format( - "Screenshot test for [%s] failed because %s:\n" - + " - golden image location: %s\n" - + " - screenshot image location: %s", + """ + Screenshot test for [%s] failed because %s: + - golden image location: %s + - screenshot image location: %s""", imageName, diffReason, result.isMissingGoldenImage() ? "missing" : goldenImagePath(imageName), diff --git a/core/src/test/java/google/registry/whois/DomainWhoisResponseTest.java b/core/src/test/java/google/registry/whois/DomainWhoisResponseTest.java index 7edaa02bb..b8654a76d 100644 --- a/core/src/test/java/google/registry/whois/DomainWhoisResponseTest.java +++ b/core/src/test/java/google/registry/whois/DomainWhoisResponseTest.java @@ -326,8 +326,10 @@ class DomainWhoisResponseTest { domainWhoisResponse .getResponse( false, - "Doodle Disclaimer\nI exist so that carriage return\n" - + "in disclaimer can be tested.") + """ + Doodle Disclaimer + I exist so that carriage return + in disclaimer can be tested.""") .plainTextOutput()) .contains("Domain Status: ok"); } diff --git a/core/src/test/java/google/registry/xml/XmlTestUtils.java b/core/src/test/java/google/registry/xml/XmlTestUtils.java index f89dcb978..3cbf47372 100644 --- a/core/src/test/java/google/registry/xml/XmlTestUtils.java +++ b/core/src/test/java/google/registry/xml/XmlTestUtils.java @@ -147,8 +147,7 @@ public class XmlTestUtils { @Nullable String path, Set ignoredPaths, Map nsMap) throws Exception { - if (obj instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) obj; + if (obj instanceof JSONObject jsonObject) { Map map = new HashMap<>(); String[] names = JSONObject.getNames(jsonObject); if (names != null) { diff --git a/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java b/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java index 638c40ef2..196aa22f2 100644 --- a/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java +++ b/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java @@ -158,14 +158,16 @@ public class SslServerInitializer extends ChannelInitializer< ((RSAPublicKey) clientPublicKey).getModulus().bitLength(); } logger.atInfo().log( - "--SSL Information--\n" - + "Client Certificate Hash: %s\n" - + "SSL Protocol: %s\n" - + "Cipher Suite: %s\n" - + "Not Before: %s\n" - + "Not After: %s\n" - + "Client Certificate Type: %s\n" - + "Client Certificate Length: %s\n", + """ + --SSL Information-- + Client Certificate Hash: %s + SSL Protocol: %s + Cipher Suite: %s + Not Before: %s + Not After: %s + Client Certificate Type: %s + Client Certificate Length: %s + """, getCertificateHash(clientCertificate), sslSession.getProtocol(), sslSession.getCipherSuite(), diff --git a/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java b/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java index aff49b3c9..3b1371bcd 100644 --- a/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java +++ b/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java @@ -131,16 +131,12 @@ public final class CertificateSupplierModule { @PemFile Lazy> pemPrivateKeySupplier, @P12File Lazy> p12PrivateKeySupplier, @SelfSigned Lazy> selfSignedPrivateKeySupplier) { - switch (mode) { - case PEM_FILE: - return pemPrivateKeySupplier.get(); - case P12_FILE: - return p12PrivateKeySupplier.get(); - case SELF_SIGNED: - return selfSignedPrivateKeySupplier.get(); - default: - throw new RuntimeException("Certificate provider mode exhausted."); - } + return switch (mode) { + case PEM_FILE -> pemPrivateKeySupplier.get(); + case P12_FILE -> p12PrivateKeySupplier.get(); + case SELF_SIGNED -> selfSignedPrivateKeySupplier.get(); + default -> throw new RuntimeException("Certificate provider mode exhausted."); + }; } @Singleton @@ -150,16 +146,12 @@ public final class CertificateSupplierModule { @PemFile Lazy>> pemCertificatesSupplier, @P12File Lazy>> p12CertificatesSupplier, @SelfSigned Lazy>> selfSignedCertificatesSupplier) { - switch (mode) { - case PEM_FILE: - return pemCertificatesSupplier.get(); - case P12_FILE: - return p12CertificatesSupplier.get(); - case SELF_SIGNED: - return selfSignedCertificatesSupplier.get(); - default: - throw new RuntimeException("Certificate provider mode exhausted."); - } + return switch (mode) { + case PEM_FILE -> pemCertificatesSupplier.get(); + case P12_FILE -> p12CertificatesSupplier.get(); + case SELF_SIGNED -> selfSignedCertificatesSupplier.get(); + default -> throw new RuntimeException("Certificate provider mode exhausted."); + }; } @Singleton diff --git a/networking/src/test/java/google/registry/networking/handler/NettyExtension.java b/networking/src/test/java/google/registry/networking/handler/NettyExtension.java index 9bbd3cedf..649bb8958 100644 --- a/networking/src/test/java/google/registry/networking/handler/NettyExtension.java +++ b/networking/src/test/java/google/registry/networking/handler/NettyExtension.java @@ -75,7 +75,7 @@ public final class NettyExtension implements AfterEachCallback { checkState(echoHandler == null, "Can't call setUpServer twice"); echoHandler = new EchoHandler(); ChannelInitializer serverInitializer = - new ChannelInitializer() { + new ChannelInitializer<>() { @Override protected void initChannel(LocalChannel ch) { // Add the given handler @@ -99,7 +99,7 @@ public final class NettyExtension implements AfterEachCallback { checkState(dumpHandler == null, "Can't call setUpClient twice"); dumpHandler = new DumpHandler(); ChannelInitializer clientInitializer = - new ChannelInitializer() { + new ChannelInitializer<>() { @Override protected void initChannel(LocalChannel ch) { // Add the given handler diff --git a/prober/src/main/java/google/registry/monitoring/blackbox/ProbingStep.java b/prober/src/main/java/google/registry/monitoring/blackbox/ProbingStep.java index 06f3b1e5e..9464cd5a7 100644 --- a/prober/src/main/java/google/registry/monitoring/blackbox/ProbingStep.java +++ b/prober/src/main/java/google/registry/monitoring/blackbox/ProbingStep.java @@ -72,9 +72,12 @@ public record ProbingStep( } @Override - public final String toString() { + public String toString() { return String.format( - "ProbingStep with Protocol: %s\n" + "OutboundMessage: %s\n", + """ + ProbingStep with Protocol: %s + OutboundMessage: %s + """, protocol(), messageTemplate().getClass().getName()); } diff --git a/prober/src/main/java/google/registry/monitoring/blackbox/connection/ProbingAction.java b/prober/src/main/java/google/registry/monitoring/blackbox/connection/ProbingAction.java index f0affc304..207c309b4 100644 --- a/prober/src/main/java/google/registry/monitoring/blackbox/connection/ProbingAction.java +++ b/prober/src/main/java/google/registry/monitoring/blackbox/connection/ProbingAction.java @@ -202,10 +202,12 @@ public abstract class ProbingAction implements Callable { @Override public final String toString() { return String.format( - "ProbingAction with delay: %d\n" - + "outboundMessage: %s\n" - + "protocol: %s\n" - + "host: %s\n", + """ + ProbingAction with delay: %d + outboundMessage: %s + protocol: %s + host: %s + """, delay().getStandardSeconds(), outboundMessage(), protocol(), host()); } @@ -268,7 +270,7 @@ public abstract class ProbingAction implements Callable { if (channel == null) { bootstrap .handler( - new ChannelInitializer() { + new ChannelInitializer<>() { @Override protected void initChannel(Channel outboundChannel) { // Uses Handlers from Protocol to fill pipeline in order of provided handlers. diff --git a/prober/src/main/java/google/registry/monitoring/blackbox/module/EppModule.java b/prober/src/main/java/google/registry/monitoring/blackbox/module/EppModule.java index db2ca6dde..ddba19339 100644 --- a/prober/src/main/java/google/registry/monitoring/blackbox/module/EppModule.java +++ b/prober/src/main/java/google/registry/monitoring/blackbox/module/EppModule.java @@ -264,11 +264,6 @@ public class EppModule { return new EppRequestMessage("hello", greetingResponse, null, (a, b) -> ImmutableMap.of()); } - /** - * Set of all possible {@link EppRequestMessage}s paired with their expected {@link - * EppResponseMessage}s. - */ - /** {@link Provides} login {@link EppRequestMessage} with expected response of success. */ @Provides @Named("loginSuccess") diff --git a/prober/src/test/java/google/registry/monitoring/blackbox/handler/EppActionHandlerTest.java b/prober/src/test/java/google/registry/monitoring/blackbox/handler/EppActionHandlerTest.java index a24e22e5b..f363ab189 100644 --- a/prober/src/test/java/google/registry/monitoring/blackbox/handler/EppActionHandlerTest.java +++ b/prober/src/test/java/google/registry/monitoring/blackbox/handler/EppActionHandlerTest.java @@ -75,20 +75,25 @@ class EppActionHandlerTest { private Document getResponse(EppResponseMessage response, boolean fail, String clTrid) throws Exception { switch (response.name()) { - case "greeting": + case "greeting" -> { if (fail) { return EppUtils.getBasicResponse(true, clTrid, SERVER_ID); } else { return EppUtils.getGreeting(); } - case "domainExists": + } + case "domainExists" -> { return EppUtils.getDomainCheck(!fail, clTrid, SERVER_ID, DOMAIN_NAME); - case "domainNotExists": + } + case "domainNotExists" -> { return EppUtils.getDomainCheck(fail, clTrid, SERVER_ID, DOMAIN_NAME); - case "success": + } + case "success" -> { return EppUtils.getBasicResponse(!fail, clTrid, SERVER_ID); - default: + } + default -> { return EppUtils.getBasicResponse(fail, clTrid, SERVER_ID); + } } } diff --git a/prober/src/test/java/google/registry/monitoring/blackbox/message/TestMessage.java b/prober/src/test/java/google/registry/monitoring/blackbox/message/TestMessage.java index dcaf4247a..75ab48bc2 100644 --- a/prober/src/test/java/google/registry/monitoring/blackbox/message/TestMessage.java +++ b/prober/src/test/java/google/registry/monitoring/blackbox/message/TestMessage.java @@ -14,8 +14,6 @@ package google.registry.monitoring.blackbox.message; -import google.registry.monitoring.blackbox.exception.UndeterminedStateException; - /** * {@link InboundMessageType} and {@link OutboundMessageType} type for the purpose of containing * String messages to be passed down channel @@ -34,7 +32,7 @@ public class TestMessage implements OutboundMessageType, InboundMessageType { } @Override - public OutboundMessageType modifyMessage(String... args) throws UndeterminedStateException { + public OutboundMessageType modifyMessage(String... args) { message = args[0]; return this; } diff --git a/prober/src/test/java/google/registry/monitoring/blackbox/testserver/TestServer.java b/prober/src/test/java/google/registry/monitoring/blackbox/testserver/TestServer.java index 9bdc8b5e2..176ddd7e1 100644 --- a/prober/src/test/java/google/registry/monitoring/blackbox/testserver/TestServer.java +++ b/prober/src/test/java/google/registry/monitoring/blackbox/testserver/TestServer.java @@ -56,7 +56,7 @@ public class TestServer { ImmutableList handlers) { // Creates ChannelInitializer with handlers specified ChannelInitializer serverInitializer = - new ChannelInitializer() { + new ChannelInitializer<>() { @Override protected void initChannel(LocalChannel ch) { for (ChannelHandler handler : handlers) { diff --git a/proxy/src/main/java/google/registry/proxy/GcpJsonFormatter.java b/proxy/src/main/java/google/registry/proxy/GcpJsonFormatter.java index 7fd3c0a53..b5dac7d3c 100644 --- a/proxy/src/main/java/google/registry/proxy/GcpJsonFormatter.java +++ b/proxy/src/main/java/google/registry/proxy/GcpJsonFormatter.java @@ -98,30 +98,15 @@ class GcpJsonFormatter extends Formatter { * href="https://github.com/googleapis/google-cloud-java/blob/master/google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java#L325">{@code LoggingHandler} */ private static String severityFor(Level level) { - switch (level.intValue()) { - // FINEST - case 300: - return "DEBUG"; - // FINER - case 400: - return "DEBUG"; - // FINE - case 500: - return "DEBUG"; - // CONFIG - case 700: - return "INFO"; - // INFO - case 800: - return "INFO"; - // WARNING - case 900: - return "WARNING"; - // SEVERE - case 1000: - return "ERROR"; - default: - return "DEFAULT"; - } + return switch (level.intValue()) { + case 300 -> "DEBUG"; // FINEST + case 400 -> "DEBUG"; // FINER + case 500 -> "DEBUG"; // FINE + case 700 -> "INFO"; // CONFIG + case 800 -> "INFO"; // INFO + case 900 -> "WARNING"; // WARNING + case 1000 -> "ERROR"; // SEVERE + default -> "DEFAULT"; + }; } } diff --git a/proxy/src/test/java/google/registry/proxy/EppProtocolModuleTest.java b/proxy/src/test/java/google/registry/proxy/EppProtocolModuleTest.java index b2e157b15..f6fb6f534 100644 --- a/proxy/src/test/java/google/registry/proxy/EppProtocolModuleTest.java +++ b/proxy/src/test/java/google/registry/proxy/EppProtocolModuleTest.java @@ -48,10 +48,12 @@ class EppProtocolModuleTest extends ProtocolModuleTest { private static final String CLIENT_ADDRESS = "epp.client.tld"; private static final byte[] HELLO_BYTES = - ("\n" - + "\n" - + " \n" - + "\n") + """ + + + + + """ .getBytes(UTF_8); private X509Certificate certificate; diff --git a/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java b/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java index 94130e757..c83b8b098 100644 --- a/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java +++ b/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java @@ -53,10 +53,12 @@ import org.junit.jupiter.api.Test; class EppServiceHandlerTest { private static final String HELLO = - "\n" - + "\n" - + " \n" - + "\n"; + """ + + + + + """; private static final String RELAY_HOST = "registry.example.tld"; private static final String RELAY_PATH = "/epp"; diff --git a/util/src/main/java/google/registry/util/CidrAddressBlock.java b/util/src/main/java/google/registry/util/CidrAddressBlock.java index f0d5ad4df..a0653bb03 100644 --- a/util/src/main/java/google/registry/util/CidrAddressBlock.java +++ b/util/src/main/java/google/registry/util/CidrAddressBlock.java @@ -441,7 +441,7 @@ public class CidrAddressBlock implements Iterable, Serializable { @Override public Iterator iterator() { - return new AbstractSequentialIterator(ip) { + return new AbstractSequentialIterator<>(ip) { @Override protected InetAddress computeNext(InetAddress previous) { if (InetAddresses.isMaximum(previous)) { @@ -463,11 +463,10 @@ public class CidrAddressBlock implements Iterable, Serializable { @Override public boolean equals(@Nullable Object o) { - if (!(o instanceof CidrAddressBlock)) { + if (!(o instanceof CidrAddressBlock cidr)) { return false; } - CidrAddressBlock cidr = (CidrAddressBlock) o; return ip.equals(cidr.ip) && (netmask == cidr.netmask); } diff --git a/util/src/main/java/google/registry/util/Concurrent.java b/util/src/main/java/google/registry/util/Concurrent.java index f1210811a..ad5f15345 100644 --- a/util/src/main/java/google/registry/util/Concurrent.java +++ b/util/src/main/java/google/registry/util/Concurrent.java @@ -68,8 +68,8 @@ public final class Concurrent { if (threadCount == 1) { return items.stream().map(funk).collect(toImmutableList()); } - ExecutorService executor = newFixedThreadPool(threadCount); - try { + ; + try (ExecutorService executor = newFixedThreadPool(threadCount)) { List> futures = new ArrayList<>(); for (final A item : items) { futures.add(executor.submit(() -> funk.apply(item))); @@ -83,8 +83,6 @@ public final class Concurrent { } } return results.build(); - } finally { - executor.shutdownNow(); } } diff --git a/util/src/main/java/google/registry/util/DiffUtils.java b/util/src/main/java/google/registry/util/DiffUtils.java index 9bc9eff15..4f953749d 100644 --- a/util/src/main/java/google/registry/util/DiffUtils.java +++ b/util/src/main/java/google/registry/util/DiffUtils.java @@ -33,20 +33,10 @@ import javax.annotation.Nullable; public final class DiffUtils { /** - * A helper class to store the two sides of a diff. If both sides are Sets then they will be + * A helper record to store the two sides of a diff. If both sides are Sets then they will be * diffed, otherwise the two objects are toStringed in Collection format "[a, b]". */ - private static class DiffPair { - @Nullable - final Object a; - - @Nullable - final Object b; - - DiffPair(@Nullable Object a, @Nullable Object b) { - this.a = a; - this.b = b; - } + private record DiffPair(@Nullable Object a, @Nullable Object b) { @Override public String toString() { @@ -133,10 +123,9 @@ public final class DiffUtils { Object value = entry.getValue(); if (value instanceof Map) { output = prettyPrintDiffedMap((Map) entry.getValue(), newPath); - } else if (value instanceof DiffPair + } else if (value instanceof DiffPair pair && ((DiffPair) value).a instanceof Set && ((DiffPair) value).b instanceof Set) { - DiffPair pair = ((DiffPair) value); String prettyLineDiff = prettyPrintSetDiff((Set) pair.a, (Set) pair.b) + "\n"; output = newPath + (prettyLineDiff.startsWith("\n") ? ":" : ": ") + prettyLineDiff; } else { diff --git a/util/src/main/java/google/registry/util/JdkLoggerConfig.java b/util/src/main/java/google/registry/util/JdkLoggerConfig.java index 1b617e24a..99b1e792d 100644 --- a/util/src/main/java/google/registry/util/JdkLoggerConfig.java +++ b/util/src/main/java/google/registry/util/JdkLoggerConfig.java @@ -68,8 +68,7 @@ public final class JdkLoggerConfig { * in all expected use cases, so it should be okay to retain all of them for the life of a task. */ // TODO(dbeaumont): Reassess the risk of memory leaks here and decide what to do about it. - private static final Map strongRefMap = - new ConcurrentHashMap(); + private static final Map strongRefMap = new ConcurrentHashMap<>(); /** Delegate logger. */ private final Logger logger; diff --git a/util/src/main/java/google/registry/util/NullIgnoringCollectionBuilder.java b/util/src/main/java/google/registry/util/NullIgnoringCollectionBuilder.java index 78eb706c3..b60d378a2 100644 --- a/util/src/main/java/google/registry/util/NullIgnoringCollectionBuilder.java +++ b/util/src/main/java/google/registry/util/NullIgnoringCollectionBuilder.java @@ -32,7 +32,7 @@ public class NullIgnoringCollectionBuilder> NullIgnoringCollectionBuilder create(B2 builder) { - return new NullIgnoringCollectionBuilder(builder); + return new NullIgnoringCollectionBuilder<>(builder); } /** If 'elem' is not null, add it to the builder. */ diff --git a/util/src/main/java/google/registry/util/PosixTarHeader.java b/util/src/main/java/google/registry/util/PosixTarHeader.java index 28be62457..4d9b40550 100644 --- a/util/src/main/java/google/registry/util/PosixTarHeader.java +++ b/util/src/main/java/google/registry/util/PosixTarHeader.java @@ -184,15 +184,11 @@ public final class PosixTarHeader { /** Returns the {@link Type} of file. */ public Type getType() { - switch (header[156]) { - case '\0': - case '0': - return Type.REGULAR; - case '5': - return Type.DIRECTORY; - default: - return Type.UNSUPPORTED; - } + return switch (header[156]) { + case '\0', '0' -> Type.REGULAR; + case '5' -> Type.DIRECTORY; + default -> Type.UNSUPPORTED; + }; } /** @@ -434,14 +430,9 @@ public final class PosixTarHeader { */ public Builder setType(Type type) { switch (type) { - case REGULAR: - header[156] = '0'; - break; - case DIRECTORY: - header[156] = '5'; - break; - default: - throw new UnsupportedOperationException(); + case REGULAR -> header[156] = '0'; + case DIRECTORY -> header[156] = '5'; + default -> throw new UnsupportedOperationException(); } return this; } diff --git a/util/src/main/java/google/registry/util/SafeSerializationUtils.java b/util/src/main/java/google/registry/util/SafeSerializationUtils.java index 9c980558b..6309e16fa 100644 --- a/util/src/main/java/google/registry/util/SafeSerializationUtils.java +++ b/util/src/main/java/google/registry/util/SafeSerializationUtils.java @@ -73,8 +73,7 @@ public final class SafeSerializationUtils { return null; } try (ObjectInputStream is = new SafeObjectInputStream(new ByteArrayInputStream(bytes))) { - Serializable ret = (Serializable) is.readObject(); - return ret; + return (Serializable) is.readObject(); } catch (IOException | ClassNotFoundException e) { throw new IllegalArgumentException("Failed to deserialize: " + Arrays.toString(bytes), e); } diff --git a/util/src/test/java/google/registry/util/DiffUtilsTest.java b/util/src/test/java/google/registry/util/DiffUtilsTest.java index 877a839fa..dc126e87d 100644 --- a/util/src/test/java/google/registry/util/DiffUtilsTest.java +++ b/util/src/test/java/google/registry/util/DiffUtilsTest.java @@ -76,14 +76,16 @@ class DiffUtilsTest { assertThat(prettyPrintSetDiff(ImmutableSet.of(a, b), ImmutableSet.of(a, c))) .isEqualTo( - "\n" - + " ADDED:\n" - + " {c}\n" - + " REMOVED:\n" - + " {b}\n" - + " FINAL CONTENTS:\n" - + " {a},\n" - + " {c}"); + """ + + ADDED: + {c} + REMOVED: + {b} + FINAL CONTENTS: + {a}, + {c}\ + """); } private static class DummyObject { diff --git a/util/src/test/java/google/registry/util/HexDumperTest.java b/util/src/test/java/google/registry/util/HexDumperTest.java index 683489e11..fce3293fe 100644 --- a/util/src/test/java/google/registry/util/HexDumperTest.java +++ b/util/src/test/java/google/registry/util/HexDumperTest.java @@ -36,8 +36,10 @@ class HexDumperTest { void testOneLine() { String input = "hello world"; String output = - "[11 bytes total]\n" - + "00000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 hello world \n"; + """ + [11 bytes total] + 00000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 hello world \s + """; assertThat(input).hasLength(11); assertThat(HexDumper.dumpHex(input.getBytes(UTF_8))).isEqualTo(output); } @@ -45,19 +47,22 @@ class HexDumperTest { @Test void testMultiLine() { String input = - "" - + "\n" - + "Maids heard the goblins cry:\n" - + "\"Come buy our orchard fruits,\n" - + "\"Come buy, come buy:\n"; + """ + + Maids heard the goblins cry: + "Come buy our orchard fruits, + "Come buy, come buy: + """; String output = - "[81 bytes total]\n" - + "00000000 0a 4d 61 69 64 73 20 68 65 61 72 64 20 74 68 65 .Maids heard the\n" - + "00000016 20 67 6f 62 6c 69 6e 73 20 63 72 79 3a 0a 22 43 goblins cry:.\"C\n" - + "00000032 6f 6d 65 20 62 75 79 20 6f 75 72 20 6f 72 63 68 ome buy our orch\n" - + "00000048 61 72 64 20 66 72 75 69 74 73 2c 0a 22 43 6f 6d ard fruits,.\"Com\n" - + "00000064 65 20 62 75 79 2c 20 63 6f 6d 65 20 62 75 79 3a e buy, come buy:\n" - + "00000080 0a . \n"; + """ + [81 bytes total] + 00000000 0a 4d 61 69 64 73 20 68 65 61 72 64 20 74 68 65 .Maids heard the + 00000016 20 67 6f 62 6c 69 6e 73 20 63 72 79 3a 0a 22 43 goblins cry:."C + 00000032 6f 6d 65 20 62 75 79 20 6f 75 72 20 6f 72 63 68 ome buy our orch + 00000048 61 72 64 20 66 72 75 69 74 73 2c 0a 22 43 6f 6d ard fruits,."Com + 00000064 65 20 62 75 79 2c 20 63 6f 6d 65 20 62 75 79 3a e buy, come buy: + 00000080 0a . \s + """; assertThat(input).hasLength(81); assertThat(HexDumper.dumpHex(input.getBytes(UTF_8))).isEqualTo(output); } @@ -66,8 +71,10 @@ class HexDumperTest { void testFullLine() { String input = "hello worldddddd"; String output = - "[16 bytes total]\n" - + "00000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 64 64 64 64 64 hello worldddddd\n"; + """ + [16 bytes total] + 00000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 64 64 64 64 64 hello worldddddd + """; assertThat(input).hasLength(16); assertThat(HexDumper.dumpHex(input.getBytes(UTF_8))).isEqualTo(output); } @@ -76,8 +83,10 @@ class HexDumperTest { void testUnicode() { String input = "(◕‿◕)"; String output = - "[11 bytes total]\n" - + "00000000 28 e2 97 95 e2 80 bf e2 97 95 29 (.........) \n"; + """ + [11 bytes total] + 00000000 28 e2 97 95 e2 80 bf e2 97 95 29 (.........) \s + """; assertThat(input).hasLength(5); assertThat(HexDumper.dumpHex(input.getBytes(UTF_8))).isEqualTo(output); } @@ -89,23 +98,25 @@ class HexDumperTest { input[n] = (byte) n; } String output = - "[256 bytes total]\n" - + "00000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................\n" - + "00000016 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ................\n" - + "00000032 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f !\"#$%&'()*+,-./\n" - + "00000048 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 0123456789:;<=>?\n" - + "00000064 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO\n" - + "00000080 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f PQRSTUVWXYZ[\\]^_\n" - + "00000096 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f `abcdefghijklmno\n" - + "00000112 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f pqrstuvwxyz{|}~.\n" - + "00000128 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f ................\n" - + "00000144 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f ................\n" - + "00000160 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af ................\n" - + "00000176 b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf ................\n" - + "00000192 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf ................\n" - + "00000208 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df ................\n" - + "00000224 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef ................\n" - + "00000240 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff ................\n"; + """ + [256 bytes total] + 00000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................ + 00000016 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ................ + 00000032 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f !"#$%&'()*+,-./ + 00000048 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 0123456789:;<=>? + 00000064 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO + 00000080 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f PQRSTUVWXYZ[\\]^_ + 00000096 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f `abcdefghijklmno + 00000112 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f pqrstuvwxyz{|}~. + 00000128 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f ................ + 00000144 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f ................ + 00000160 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af ................ + 00000176 b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf ................ + 00000192 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf ................ + 00000208 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df ................ + 00000224 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef ................ + 00000240 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff ................ + """; assertThat(HexDumper.dumpHex(input)).isEqualTo(output); } @@ -159,12 +170,14 @@ class HexDumperTest { void testPerLineIsOne() { String input = "hello"; String output = - "[5 bytes total]\n" - + "00000000 68 h\n" - + "00000001 65 e\n" - + "00000002 6c l\n" - + "00000003 6c l\n" - + "00000004 6f o\n"; + """ + [5 bytes total] + 00000000 68 h + 00000001 65 e + 00000002 6c l + 00000003 6c l + 00000004 6f o + """; assertThat(HexDumper.dumpHex(input.getBytes(UTF_8), 1, 0)).isEqualTo(output); } diff --git a/util/src/test/java/google/registry/util/SafeObjectInputStreamTest.java b/util/src/test/java/google/registry/util/SafeObjectInputStreamTest.java index 66e606438..1e844fee6 100644 --- a/util/src/test/java/google/registry/util/SafeObjectInputStreamTest.java +++ b/util/src/test/java/google/registry/util/SafeObjectInputStreamTest.java @@ -111,10 +111,9 @@ public class SafeObjectInputStreamTest { if (this == o) { return true; } - if (!(o instanceof NomulusEntity)) { + if (!(o instanceof NomulusEntity that)) { return false; } - NomulusEntity that = (NomulusEntity) o; return Objects.equal(value, that.value); }