1
0
mirror of https://github.com/google/nomulus synced 2026-04-21 16:50:44 +00:00

Bring codebase up to more recent Java standards (#2422)

This includes using the new switch format (though IntelliJ does not yet
understand patterns including default so those aren't used), multiline strings,
replacing some unnecessary type declarations with <>, converting some classes to
records, replacing some Guava predicates with native Java code, and some other
miscellaneous Code Inspection fixes.
This commit is contained in:
Ben McIlwain
2024-05-01 16:48:38 -04:00
committed by GitHub
parent 570618705e
commit 4b6ade0b14
154 changed files with 1454 additions and 1535 deletions

View File

@@ -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(

View File

@@ -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));
}
}
}

View File

@@ -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";

View File

@@ -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) {

View File

@@ -50,16 +50,17 @@ public class RegistryPipelineWorkerInitializer implements JvmInitializer {
environment.setup();
RegistryPipelineComponent registryPipelineComponent =
toRegistryPipelineComponent(registryOptions);
Lazy<JpaTransactionManager> transactionManagerLazy;
switch (registryOptions.getJpaTransactionManagerType()) {
case READ_ONLY_REPLICA:
transactionManagerLazy =
registryPipelineComponent.getReadOnlyReplicaJpaTransactionManager();
break;
case REGULAR:
default:
transactionManagerLazy = registryPipelineComponent.getJpaTransactionManager();
}
Lazy<JpaTransactionManager> 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");
}

View File

@@ -688,27 +688,26 @@ public class RdePipeline implements Serializable {
protected abstract static class TupleTags {
protected static final TupleTag<KV<PendingDeposit, DepositFragment>> DOMAIN_FRAGMENTS =
new TupleTag<KV<PendingDeposit, DepositFragment>>() {};
new TupleTag<>() {};
protected static final TupleTag<KV<String, PendingDeposit>> REFERENCED_CONTACTS =
new TupleTag<KV<String, PendingDeposit>>() {};
new TupleTag<>() {};
protected static final TupleTag<KV<String, PendingDeposit>> REFERENCED_HOSTS =
new TupleTag<KV<String, PendingDeposit>>() {};
new TupleTag<>() {};
protected static final TupleTag<KV<String, KV<String, CoGbkResult>>> SUPERORDINATE_DOMAINS =
new TupleTag<KV<String, KV<String, CoGbkResult>>>() {};
new TupleTag<>() {};
protected static final TupleTag<KV<PendingDeposit, DepositFragment>> EXTERNAL_HOST_FRAGMENTS =
new TupleTag<KV<PendingDeposit, DepositFragment>>() {};
new TupleTag<>() {};
protected static final TupleTag<PendingDeposit> PENDING_DEPOSIT =
new TupleTag<PendingDeposit>() {};
protected static final TupleTag<PendingDeposit> PENDING_DEPOSIT = new TupleTag<>() {};
protected static final TupleTag<KV<String, CoGbkResult>> HOST_TO_PENDING_DEPOSIT =
new TupleTag<KV<String, CoGbkResult>>() {};
new TupleTag<>() {};
protected static final TupleTag<Long> REVISION_ID = new TupleTag<Long>() {};
protected static final TupleTag<Long> REVISION_ID = new TupleTag<>() {};
}
@Singleton

View File

@@ -62,7 +62,7 @@ class BsaDiffCreator {
this.gcsClient = gcsClient;
}
private <K, V extends Comparable> Multimap<K, V> listBackedMultiMap() {
private <K, V extends Comparable<?>> Multimap<K, V> listBackedMultiMap() {
return newListMultimap(newHashMap(), Lists::newArrayList);
}

View File

@@ -80,7 +80,7 @@ public class IdnChecker {
}
private static ImmutableMap<IdnTableEnum, ImmutableSet<Tld>> getIdnToTldMap(DateTime now) {
ImmutableMultimap.Builder<IdnTableEnum, Tld> idnToTldMap = new ImmutableMultimap.Builder();
var idnToTldMap = new ImmutableMultimap.Builder<IdnTableEnum, Tld>();
Tlds.getTldEntitiesOfType(TldType.REAL).stream()
.filter(tld -> isEnrolledWithBsa(tld, now))
.forEach(

View File

@@ -34,7 +34,7 @@ public record BlockOrder(long orderId, OrderType orderType) {
public static BlockOrder deserialize(String text) {
List<String> 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);
}

View File

@@ -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)

View File

@@ -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<BsaDownload> vKey(long jobId) {
return VKey.create(BsaDownload.class, Long.valueOf(jobId));
return VKey.create(BsaDownload.class, jobId);
}
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -72,7 +72,7 @@ public final class LabelDiffUpdates {
for (Map.Entry<LabelType, ImmutableList<BlockLabel>> 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<String> 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<String> 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;
}
}
}
});

View File

@@ -103,7 +103,7 @@ public final class Queries {
static ImmutableList<BsaUnblockableDomain> batchReadUnblockables(
Optional<BsaUnblockableDomain> lastRead, int batchSize) {
return ImmutableList.copyOf(
return ImmutableList.<BsaUnblockableDomain>copyOf(
bsaQuery(
() ->
tm().getEntityManager()

View File

@@ -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.
* <p>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)) {

View File

@@ -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);
}
});
}

View File

@@ -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
* <a href="https://tools.ietf.org/html/rfc2136">RFC 2136</a>. 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 <a
* href="https://tools.ietf.org/html/rfc2136">RFC 2136</a>. 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.
* <p>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.
*
* <p>The general strategy of the publish methods is to delete <em>all</em> resource records of any
* <em>type</em> that match the exact domain/host name supplied. And then for create/update cases,
@@ -73,8 +73,8 @@ import org.xbill.DNS.Update;
* <p>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.
*
* <p>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
* <p>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.
*/

View File

@@ -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}.
* <p>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;

View File

@@ -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<ReservationType> 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<PollMessage.Autorenew> autorenewPollMessage =
Optional<Autorenew> 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<Fee> 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) {

View File

@@ -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(

View File

@@ -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<? extends Flow> 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<? extends Flow> 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 <update>}, but logically a totally

View File

@@ -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);

View File

@@ -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;
};
}
}

View File

@@ -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<Object>() {
@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);
}

View File

@@ -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());
}
}
}

View File

@@ -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.
* <p>If no match is found for xmlName, null is returned.
*/
@Nullable
public static GracePeriodStatus fromXmlName(String xmlName) {

View File

@@ -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
* <p>"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."
*/

View File

@@ -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();

View File

@@ -67,12 +67,13 @@ public enum ReservationType {
return messageForCheck;
}
private static final Ordering<ReservationType> ORDERING = new Ordering<ReservationType>() {
@Override
public int compare(ReservationType left, ReservationType right) {
return Integer.compare(left.ordinal(), right.ordinal());
}
};
private static final Ordering<ReservationType> 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

View File

@@ -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;
}
}

View File

@@ -100,7 +100,7 @@ public class IntervalDescriptor extends AbstractTypeDescriptor<PGInterval>
@Override
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>(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<PGInterval>
@Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>(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);

View File

@@ -115,7 +115,7 @@ public class StringCollectionDescriptor extends AbstractTypeDescriptor<StringCol
@Override
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>(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<StringCol
st.setArray(index, null);
return;
}
if (value instanceof StringCollection) {
StringCollection stringCollection = (StringCollection) value;
if (value instanceof StringCollection stringCollection) {
if (stringCollection.getCollection() == null) {
st.setArray(index, null);
} else {
@@ -154,7 +153,7 @@ public class StringCollectionDescriptor extends AbstractTypeDescriptor<StringCol
@Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>(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);

View File

@@ -105,7 +105,7 @@ public class StringMapDescriptor extends AbstractTypeDescriptor<StringMap>
@Override
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>(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<StringMap>
@Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>(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);

View File

@@ -78,8 +78,7 @@ public class DatabaseException extends PersistenceException {
static String getSqlError(Throwable t) {
ImmutableList.Builder<String> 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();

View File

@@ -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<EntityId> getEntityIdsFromEntity(
EntityType<?> entityType, Object entity) {

View File

@@ -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);
}
}
}

View File

@@ -52,18 +52,13 @@ import org.joda.time.DateTime;
*
* <p>This implementation is geared towards RDAP replies, and hence has RDAP-specific quirks.
* Specifically:
*
* - Fields with empty arrays are not shown at all
*
* - VCards are a built-in special case (Not implemented yet)
*
* - DateTime conversion is specifically supported as if it were a primitive
*
* - Arrays are considered to be SETS rather than lists, meaning repeated values are removed and the
* order isn't guaranteed
*
* 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;
}

View File

@@ -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.
* <p>Also mentioned in the RDAP Technical Implementation Guide 3.6.
*
* @see <a href="http://mm.icann.org/pipermail/gtld-tech/2016-October/000822.html">Questions about
* the ICANN RDAP Profile</a>
@@ -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.
* <p>Also mentioned in the RDAP Technical Implementation Guide 3.5.
*
* @see <a href="http://mm.icann.org/pipermail/gtld-tech/2016-October/000822.html">Questions about
* the ICANN RDAP Profile</a>

View File

@@ -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;
};
}
/**

View File

@@ -47,7 +47,7 @@ final class RdapObjectClasses {
/**
* Temporary implementation of VCards.
*
* Will create a better implementation soon.
* <p>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.
* <p>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<Notice> 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) {

View File

@@ -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()

View File

@@ -97,8 +97,7 @@ public final class CopyDetailReportsAction implements Runnable {
response.setPayload(String.format("Failure, encountered %s", e.getMessage()));
return;
}
ImmutableMap.Builder<String, Throwable> copyErrorsBuilder =
new ImmutableMap.Builder<String, Throwable>();
ImmutableMap.Builder<String, Throwable> 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.

View File

@@ -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()));

View File

@@ -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));
};
}
}

View File

@@ -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.");

View File

@@ -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());

View File

@@ -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.");

View File

@@ -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",

View File

@@ -80,7 +80,7 @@ public final class TmchCertificateAuthority {
private static final LoadingCache<TmchCaMode, X509CRL> CRL_CACHE =
CacheUtils.newCacheBuilder(getSingletonCacheRefreshDuration())
.build(
new CacheLoader<TmchCaMode, X509CRL>() {
new CacheLoader<>() {
@Override
public X509CRL load(final TmchCaMode tmchCaMode) throws GeneralSecurityException {
Optional<TmchCrl> storedCrl = TmchCrl.get();

View File

@@ -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) {

View File

@@ -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(

View File

@@ -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<CurrencyUnit, String> newBillingAccountMap = new LinkedHashMap<>();
@@ -384,8 +370,8 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand {
}
List<Object> 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

View File

@@ -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() {

View File

@@ -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 {

View File

@@ -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()));
}
}
}

View File

@@ -76,7 +76,7 @@ final class GhostrydeCommand implements Command {
Provider<PGPPrivateKey> 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");

View File

@@ -54,7 +54,7 @@ public class GsonUtils {
if (!GsonPostProcessable.class.isAssignableFrom(type.getRawType())) {
return originalAdapter;
}
return new TypeAdapter<T>() {
return new TypeAdapter<>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
originalAdapter.write(out, value);

View File

@@ -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");

View File

@@ -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 {

View File

@@ -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);
}

View File

@@ -28,7 +28,7 @@ import javax.inject.Inject;
final class PendingEscrowCommand implements Command {
private static final Ordering<PendingDeposit> SORTER =
new Ordering<PendingDeposit>() {
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;

View File

@@ -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) {

View File

@@ -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;

View File

@@ -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();
};
}
}

View File

@@ -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();

View File

@@ -60,11 +60,12 @@ public class RecreateBillingRecurrencesCommand extends ConfirmingCommand {
ImmutableList<BillingRecurrence> 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));
});
}

View File

@@ -90,14 +90,11 @@ public final class SoyTemplateUtils {
private static ImmutableMap<String, String> 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);
}

View File

@@ -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);

View File

@@ -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));
}
}
}

View File

@@ -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));
}
}
}

View File

@@ -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(),

View File

@@ -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;

View File

@@ -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("&quot;", "")));
}
// 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(),

View File

@@ -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 <container-id> | 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 <container-id> | 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();

View File

@@ -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")));

View File

@@ -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";

View File

@@ -45,7 +45,7 @@ public abstract class BeamActionTestBase {
protected FlexTemplates templates = mock(FlexTemplates.class);
protected Launch launch = mock(Launch.class);
private Answer<LaunchFlexTemplateResponse> answer =
new Answer<LaunchFlexTemplateResponse>() {
new Answer<>() {
private Integer times = 0;
@Override

View File

@@ -376,7 +376,7 @@ public class TestPipelineExtension extends Pipeline
providerRuntimeValues.put(uuid, runtimeValue);
return ValueProvider.NestedValueProvider.of(
options.as(TestValueProviderOptions.class).getProviderRuntimeValues(),
new GetFromRuntimeValues<T>(uuid));
new GetFromRuntimeValues<>(uuid));
}
private final Map<String, Object> providerRuntimeValues = Maps.newHashMap();

View File

@@ -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<String>().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<byte[], Integer> consumer = invocation.getArgument(0);
consumer.accept(bytes, bytes.length);
return null;
}
invocation -> {
BiConsumer<byte[], Integer> consumer = invocation.getArgument(0);
consumer.accept(bytes, bytes.length);
return null;
})
.when(blockList)
.consumeAll(any(BiConsumer.class));

View File

@@ -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

View File

@@ -89,7 +89,7 @@ class GcsClientTest {
void readWriteLabelDiffs_success() throws Exception {
ImmutableList<BlockLabel> 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());

View File

@@ -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();
}

View File

@@ -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);
}

View File

@@ -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");

View File

@@ -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."""));
}
}

View File

@@ -168,7 +168,7 @@ class DomainFlowUtilsTest extends ResourceFlowTestCase<DomainInfoFlow, Domain> {
}
@Test
void testCheckHasBillingAccount_failsOnRealTld() throws EppException {
void testCheckHasBillingAccount_failsOnRealTld() {
persistFoobarTld(TldType.REAL);
MissingBillingAccountMapException thrown =
assertThrows(

View File

@@ -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,

View File

@@ -68,9 +68,10 @@ class HostCreateFlowTest extends ResourceFlowTestCase<HostCreateFlow, Host> {
private void setEppHostCreateInputWithIps(String hostName) {
setEppHostCreateInput(
hostName,
"<host:addr ip=\"v4\">192.0.2.2</host:addr>\n"
+ "<host:addr ip=\"v4\">192.0.2.29</host:addr>\n"
+ "<host:addr ip=\"v6\">1080:0:0:0:8:800:200C:417A</host:addr>");
"""
<host:addr ip="v4">192.0.2.2</host:addr>
<host:addr ip="v4">192.0.2.29</host:addr>
<host:addr ip="v6">1080:0:0:0:8:800:200C:417A</host:addr>""");
}
HostCreateFlowTest() {
@@ -267,9 +268,10 @@ class HostCreateFlowTest extends ResourceFlowTestCase<HostCreateFlow, Host> {
void testFailure_ip4AddressWithIp6Declaration() {
setEppHostCreateInput(
"ns1.example.tld",
"<host:addr ip=\"v4\">192.0.2.2</host:addr>\n"
+ "<host:addr ip=\"v6\">192.0.2.29</host:addr>\n"
+ "<host:addr ip=\"v6\">1080:0:0:0:8:800:200C:417A</host:addr>");
"""
<host:addr ip="v4">192.0.2.2</host:addr>
<host:addr ip="v6">192.0.2.29</host:addr>
<host:addr ip="v6">1080:0:0:0:8:800:200C:417A</host:addr>""");
EppException thrown = assertThrows(IpAddressVersionMismatchException.class, this::runFlow);
assertAboutEppExceptions().that(thrown).marshalsToXml();
}

View File

@@ -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));

View File

@@ -46,66 +46,68 @@ class KeySerializerTest {
* <p>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"
+ "GDrHg5CQBVZ3N6NBob9bGoEhi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ZOsEIegy1pRkoO8u72T
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();

View File

@@ -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

View File

@@ -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);
}
}

View File

@@ -49,18 +49,20 @@ class AddressTest {
new JpaTestExtensions.Builder().withEntityClass(TestEntity.class).buildUnitTestExtension();
private static final String ENTITY_XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
+ "<testEntity>\n"
+ " <address>\n"
+ " <street>123 W 14th St</street>\n"
+ " <street>8th Fl</street>\n"
+ " <street>Rm 8</street>\n"
+ " <city>New York</city>\n"
+ " <sp>NY</sp>\n"
+ " <pc>10011</pc>\n"
+ " <cc>US</cc>\n"
+ " </address>\n"
+ "</testEntity>\n";
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testEntity>
<address>
<street>123 W 14th St</street>
<street>8th Fl</street>
<street>Rm 8</street>
<city>New York</city>
<sp>NY</sp>
<pc>10011</pc>
<cc>US</cc>
</address>
</testEntity>
""";
private TestAddress address = createAddress("123 W 14th St", "8th Fl", "Rm 8");
private TestEntity entity = new TestEntity(1L, address);

View File

@@ -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));
}

View File

@@ -114,27 +114,15 @@ abstract class RdapActionBaseTestCase<A extends RdapActionBase> {
}
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",

View File

@@ -90,21 +90,19 @@ class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDomainSear
private JsonObject generateActualJson(RequestType requestType, String paramValue, String cursor) {
String requestTypeParam;
switch (requestType) {
case NAME:
case NAME -> {
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) {

View File

@@ -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 =

View File

@@ -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();

View File

@@ -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);

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