mirror of
https://github.com/google/nomulus
synced 2026-05-13 03:11:49 +00:00
Enable new errorprone checks and fix violations (#3018)
This commit is contained in:
@@ -33,6 +33,8 @@ import com.google.common.truth.Fact;
|
||||
import com.google.common.truth.FailureMetadata;
|
||||
import com.google.common.truth.SimpleSubjectBuilder;
|
||||
import com.google.common.truth.Subject;
|
||||
import com.google.errorprone.annotations.FormatMethod;
|
||||
import com.google.errorprone.annotations.FormatString;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Collection;
|
||||
@@ -125,8 +127,9 @@ public class TextDiffSubject extends Subject {
|
||||
return assertThat(Resources.asCharSource(resourceUrl, UTF_8).readLines());
|
||||
}
|
||||
|
||||
@FormatMethod
|
||||
public static SimpleSubjectBuilder<TextDiffSubject, URL> assertWithMessageAboutUrlSource(
|
||||
String format, Object... params) {
|
||||
@FormatString String format, Object... params) {
|
||||
return assertWithMessage(format, params).about(urlFactory());
|
||||
}
|
||||
|
||||
@@ -192,7 +195,7 @@ public class TextDiffSubject extends Subject {
|
||||
|
||||
private record SideBySideRowFormatter(int maxExpectedLineLength, int maxActualLineLength) {
|
||||
|
||||
public String formatRow(String expected, String actual, char padChar) {
|
||||
String formatRow(String expected, String actual, char padChar) {
|
||||
return String.format(
|
||||
"|%s|%s|",
|
||||
Strings.padEnd(expected, maxExpectedLineLength, padChar),
|
||||
|
||||
@@ -114,7 +114,9 @@ public class ExpandBillingRecurrencesAction implements Runnable {
|
||||
.getCursorTimeInstant()));
|
||||
checkArgument(
|
||||
startTime.isBefore(endTime),
|
||||
String.format("Start time (%s) must be before end time (%s)", startTime, endTime));
|
||||
"Start time (%s) must be before end time (%s)",
|
||||
startTime,
|
||||
endTime);
|
||||
LaunchFlexTemplateParameter launchParameter =
|
||||
new LaunchFlexTemplateParameter()
|
||||
.setJobName(
|
||||
|
||||
@@ -156,12 +156,12 @@ public class ExpandBillingRecurrencesPipeline implements Serializable {
|
||||
ExpandBillingRecurrencesPipeline(ExpandBillingRecurrencesPipelineOptions options, Clock clock) {
|
||||
startTime = Instant.parse(options.getStartTime());
|
||||
endTime = Instant.parse(options.getEndTime());
|
||||
checkArgument(
|
||||
!endTime.isAfter(clock.now()),
|
||||
String.format("End time %s must be at or before now.", endTime));
|
||||
checkArgument(!endTime.isAfter(clock.now()), "End time %s must be at or before now.", endTime);
|
||||
checkArgument(
|
||||
startTime.isBefore(endTime),
|
||||
String.format("[%s, %s) is not a valid window of operation.", startTime, endTime));
|
||||
"[%s, %s) is not a valid window of operation.",
|
||||
startTime,
|
||||
endTime);
|
||||
isDryRun = options.getIsDryRun();
|
||||
advanceCursor = options.getAdvanceCursor();
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ public class RdeIO {
|
||||
private final byte[] stagingKeyBytes;
|
||||
private final RdeMarshaller marshaller;
|
||||
|
||||
protected RdeWriter(
|
||||
RdeWriter(
|
||||
GcsUtils gcsUtils,
|
||||
String rdeBucket,
|
||||
byte[] stagingKeyBytes,
|
||||
@@ -144,7 +144,7 @@ public class RdeIO {
|
||||
this.marshaller = new RdeMarshaller(validationMode);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@SuppressWarnings({"EffectivelyPrivate", "unused"})
|
||||
@Setup
|
||||
public void setup() {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
|
||||
@@ -154,9 +154,7 @@ public class ResaveAllEppResourcesPipeline implements Serializable {
|
||||
}
|
||||
|
||||
@ProcessElement
|
||||
public void processElement(
|
||||
@Element KV<ShardedKey<Integer>, Iterable<String>> element,
|
||||
OutputReceiver<Void> outputReceiver) {
|
||||
public void processElement(@Element KV<ShardedKey<Integer>, Iterable<String>> element) {
|
||||
tm().transact(
|
||||
() -> {
|
||||
DateTime now = tm().getTransactionTime();
|
||||
|
||||
@@ -210,8 +210,8 @@ public class Spec11Pipeline implements Serializable {
|
||||
String registrarId = kv.getKey();
|
||||
checkArgument(
|
||||
kv.getValue().iterator().hasNext(),
|
||||
String.format(
|
||||
"Registrar with ID %s had no corresponding threats", registrarId));
|
||||
"Registrar with ID %s had no corresponding threats",
|
||||
registrarId);
|
||||
String email = kv.getValue().iterator().next().email();
|
||||
JSONObject output = new JSONObject();
|
||||
try {
|
||||
|
||||
@@ -29,8 +29,8 @@ public final class BigqueryJobFailureException extends RuntimeException {
|
||||
|
||||
/** Delegate {@link IOException} errors, checking for {@link GoogleJsonResponseException} */
|
||||
public static BigqueryJobFailureException create(IOException cause) {
|
||||
if (cause instanceof GoogleJsonResponseException) {
|
||||
return create((GoogleJsonResponseException) cause);
|
||||
if (cause instanceof GoogleJsonResponseException googleJsonResponseException) {
|
||||
return create(googleJsonResponseException);
|
||||
} else {
|
||||
return new BigqueryJobFailureException(cause.getMessage(), cause, null, null);
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ public class BlockListFetcher {
|
||||
// TODO: use more informative exceptions to describe retriable errors
|
||||
return retrier.callWithRetry(
|
||||
() -> tryFetch(blockListType),
|
||||
e -> e instanceof BsaException && ((BsaException) e).isRetriable());
|
||||
e -> e instanceof BsaException bsaException && bsaException.isRetriable());
|
||||
}
|
||||
|
||||
LazyBlockList tryFetch(BlockListType blockListType) {
|
||||
|
||||
@@ -71,19 +71,19 @@ public class BsaReportSender {
|
||||
public void sendOrderStatusReport(String payload) {
|
||||
retrier.callWithRetry(
|
||||
() -> trySendData(this.orderStatusUrl, payload),
|
||||
e -> e instanceof BsaException && ((BsaException) e).isRetriable());
|
||||
e -> e instanceof BsaException bsaException && bsaException.isRetriable());
|
||||
}
|
||||
|
||||
public void addUnblockableDomainsUpdates(String payload) {
|
||||
retrier.callWithRetry(
|
||||
() -> trySendData(this.addUnblockableDomainsUrl, payload),
|
||||
e -> e instanceof BsaException && ((BsaException) e).isRetriable());
|
||||
e -> e instanceof BsaException bsaException && bsaException.isRetriable());
|
||||
}
|
||||
|
||||
public void removeUnblockableDomainsUpdates(String payload) {
|
||||
retrier.callWithRetry(
|
||||
() -> trySendData(this.removeUnblockableDomainsUrl, payload),
|
||||
e -> e instanceof BsaException && ((BsaException) e).isRetriable());
|
||||
e -> e instanceof BsaException bsaException && bsaException.isRetriable());
|
||||
}
|
||||
|
||||
Void trySendData(String urlString, String payload) {
|
||||
|
||||
@@ -131,7 +131,7 @@ public class DelegatedCredentials extends GoogleCredentials {
|
||||
Clock clock,
|
||||
Duration tokenRefreshDelay) {
|
||||
checkArgument(
|
||||
tokenRefreshDelay.getSeconds() <= MAX_TOKEN_REFRESH_DELAY.getSeconds(),
|
||||
tokenRefreshDelay.toSeconds() <= MAX_TOKEN_REFRESH_DELAY.toSeconds(),
|
||||
"Max refresh delay must not exceed %s.",
|
||||
MAX_TOKEN_REFRESH_DELAY);
|
||||
|
||||
@@ -206,7 +206,7 @@ public class DelegatedCredentials extends GoogleCredentials {
|
||||
JsonWebToken.Payload payload = new JsonWebToken.Payload();
|
||||
payload.setIssuer(this.delegatedServiceAccountUser);
|
||||
payload.setIssuedAtTimeSeconds(currentTime / 1000);
|
||||
payload.setExpirationTimeSeconds(currentTime / 1000 + tokenRefreshDelay.getSeconds());
|
||||
payload.setExpirationTimeSeconds(currentTime / 1000 + tokenRefreshDelay.toSeconds());
|
||||
payload.setSubject(delegatingUserEmail);
|
||||
payload.put("scope", Joiner.on(' ').join(scopes));
|
||||
payload.setAudience(DEFAULT_TOKEN_URI);
|
||||
@@ -241,10 +241,10 @@ public class DelegatedCredentials extends GoogleCredentials {
|
||||
if (value == null) {
|
||||
throw new IOException(String.format(VALUE_NOT_FOUND_MESSAGE, errorPrefix, key));
|
||||
}
|
||||
if (!(value instanceof String)) {
|
||||
if (!(value instanceof String string)) {
|
||||
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "string", key));
|
||||
}
|
||||
return (String) value;
|
||||
return string;
|
||||
}
|
||||
|
||||
/** Return the specified integer from JSON or throw a helpful error message. */
|
||||
@@ -257,9 +257,9 @@ public class DelegatedCredentials extends GoogleCredentials {
|
||||
if (value instanceof BigDecimal bigDecimalValue) {
|
||||
return bigDecimalValue.intValueExact();
|
||||
}
|
||||
if (!(value instanceof Integer)) {
|
||||
if (!(value instanceof Integer i)) {
|
||||
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "integer", key));
|
||||
}
|
||||
return (Integer) value;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,8 @@ public class ExportPremiumTermsAction implements Runnable {
|
||||
String premiumListName = tld.getPremiumListName().get();
|
||||
checkState(
|
||||
PremiumListDao.getLatestRevision(premiumListName).isPresent(),
|
||||
"Could not load premium list for " + tldStr);
|
||||
"Could not load premium list for %s",
|
||||
tldStr);
|
||||
SortedSet<String> premiumTerms =
|
||||
PremiumListDao.loadAllPremiumEntries(premiumListName).stream()
|
||||
.map(PremiumEntry::toString)
|
||||
|
||||
@@ -76,7 +76,7 @@ public class SyncRegistrarsSheetAction implements Runnable {
|
||||
}};
|
||||
|
||||
private final int statusCode;
|
||||
protected final String message;
|
||||
final String message;
|
||||
|
||||
Result(int statusCode, String message) {
|
||||
this.statusCode = statusCode;
|
||||
@@ -84,7 +84,7 @@ public class SyncRegistrarsSheetAction implements Runnable {
|
||||
}
|
||||
|
||||
/** Log an error message. Results that use log levels other than info should override this. */
|
||||
protected void log(@Nullable Exception cause) {
|
||||
void log(@Nullable Exception cause) {
|
||||
logger.atInfo().withCause(cause).log(message);
|
||||
}
|
||||
|
||||
|
||||
@@ -217,12 +217,13 @@ public abstract class EppException extends Exception {
|
||||
public static class UnimplementedCommandException extends EppException {
|
||||
|
||||
public UnimplementedCommandException(InnerCommand command) {
|
||||
super(String.format(
|
||||
"No flow found for %s with extension %s",
|
||||
command.getClass().getSimpleName(),
|
||||
command instanceof ResourceCommandWrapper
|
||||
? ((ResourceCommandWrapper) command).getResourceCommand().getClass().getSimpleName()
|
||||
: null));
|
||||
super(
|
||||
String.format(
|
||||
"No flow found for %s with extension %s",
|
||||
command.getClass().getSimpleName(),
|
||||
command instanceof ResourceCommandWrapper resourceCommandWrapper
|
||||
? resourceCommandWrapper.getResourceCommand().getClass().getSimpleName()
|
||||
: null));
|
||||
}
|
||||
|
||||
public UnimplementedCommandException(String message) {
|
||||
|
||||
@@ -23,6 +23,7 @@ import com.google.common.flogger.FluentLogger;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
@@ -140,7 +141,7 @@ public class EppXmlSanitizer {
|
||||
}
|
||||
}
|
||||
xmlEventWriter.flush();
|
||||
return outputXmlBytes.toString(inputEncoding);
|
||||
return outputXmlBytes.toString(Charset.forName(inputEncoding));
|
||||
}
|
||||
|
||||
private static String maskSensitiveData(String original) {
|
||||
|
||||
@@ -60,10 +60,10 @@ public final class DomainFlowTmchUtils {
|
||||
if (signedMarks.size() > 1) {
|
||||
throw new TooManySignedMarksException();
|
||||
}
|
||||
if (!(signedMarks.get(0) instanceof EncodedSignedMark)) {
|
||||
if (!(signedMarks.get(0) instanceof EncodedSignedMark encodedSignedMark)) {
|
||||
throw new SignedMarksMustBeEncodedException();
|
||||
}
|
||||
SignedMark signedMark = verifyEncodedSignedMark((EncodedSignedMark) signedMarks.get(0), now);
|
||||
SignedMark signedMark = verifyEncodedSignedMark(encodedSignedMark, now);
|
||||
return verifySignedMarkValidForDomainLabel(signedMark, domainLabel);
|
||||
}
|
||||
|
||||
|
||||
@@ -127,11 +127,11 @@ public class FeesAndCredits extends ImmutableObject implements Buildable {
|
||||
}
|
||||
|
||||
public Builder addFeeOrCredit(BaseFee feeOrCredit) {
|
||||
if (feeOrCredit instanceof Credit) {
|
||||
if (feeOrCredit instanceof Credit credit) {
|
||||
getInstance().credits =
|
||||
new ImmutableList.Builder<Credit>()
|
||||
.addAll(nullToEmptyImmutableCopy(getInstance().credits))
|
||||
.add((Credit) feeOrCredit)
|
||||
.add(credit)
|
||||
.build();
|
||||
} else {
|
||||
getInstance().fees =
|
||||
@@ -147,8 +147,8 @@ public class FeesAndCredits extends ImmutableObject implements Buildable {
|
||||
ImmutableList.Builder<Fee> feeBuilder = new ImmutableList.Builder<>();
|
||||
ImmutableList.Builder<Credit> creditBuilder = new ImmutableList.Builder<>();
|
||||
for (BaseFee feeOrCredit : feesAndCredits) {
|
||||
if (feeOrCredit instanceof Credit) {
|
||||
creditBuilder.add((Credit) feeOrCredit);
|
||||
if (feeOrCredit instanceof Credit credit) {
|
||||
creditBuilder.add(credit);
|
||||
} else {
|
||||
feeBuilder.add((Fee) feeOrCredit);
|
||||
}
|
||||
|
||||
@@ -90,8 +90,12 @@ public class FlowPicker {
|
||||
/** Get the flow associated with this {@link EppInput} or return null to signal no match. */
|
||||
Class<? extends Flow> get(EppInput eppInput) {
|
||||
InnerCommand innerCommand = eppInput.getCommandWrapper().getCommand();
|
||||
return get(eppInput, innerCommand, (innerCommand instanceof ResourceCommandWrapper)
|
||||
? ((ResourceCommandWrapper) innerCommand).getResourceCommand() : null);
|
||||
return get(
|
||||
eppInput,
|
||||
innerCommand,
|
||||
(innerCommand instanceof ResourceCommandWrapper resourceCommandWrapper)
|
||||
? resourceCommandWrapper.getResourceCommand()
|
||||
: null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,10 +133,10 @@ public class FlowPicker {
|
||||
@Override
|
||||
Class<? extends Flow> get(
|
||||
EppInput eppInput, InnerCommand innerCommand, ResourceCommand resourceCommand) {
|
||||
if (!(innerCommand instanceof Poll)) {
|
||||
if (!(innerCommand instanceof Poll poll)) {
|
||||
return null;
|
||||
}
|
||||
return switch (((Poll) innerCommand).getPollOp()) {
|
||||
return switch (poll.getPollOp()) {
|
||||
case ACK -> PollAckFlow.class;
|
||||
case REQUEST -> PollRequestFlow.class;
|
||||
};
|
||||
@@ -222,28 +226,51 @@ public class FlowPicker {
|
||||
}};
|
||||
|
||||
/** Transfer flows have an {@link InnerCommand} of type {@link Transfer}. */
|
||||
private static final FlowProvider TRANSFER_FLOW_PROVIDER = new FlowProvider() {
|
||||
private final Table<Class<?>, TransferOp, Class<? extends Flow>> transferFlows = ImmutableTable
|
||||
.<Class<?>, TransferOp, Class<? extends Flow>>builder()
|
||||
.put(ContactCommand.Transfer.class, TransferOp.APPROVE, ContactTransferApproveFlow.class)
|
||||
.put(ContactCommand.Transfer.class, TransferOp.CANCEL, ContactTransferCancelFlow.class)
|
||||
.put(ContactCommand.Transfer.class, TransferOp.QUERY, ContactTransferQueryFlow.class)
|
||||
.put(ContactCommand.Transfer.class, TransferOp.REJECT, ContactTransferRejectFlow.class)
|
||||
.put(ContactCommand.Transfer.class, TransferOp.REQUEST, ContactTransferRequestFlow.class)
|
||||
.put(DomainCommand.Transfer.class, TransferOp.APPROVE, DomainTransferApproveFlow.class)
|
||||
.put(DomainCommand.Transfer.class, TransferOp.CANCEL, DomainTransferCancelFlow.class)
|
||||
.put(DomainCommand.Transfer.class, TransferOp.QUERY, DomainTransferQueryFlow.class)
|
||||
.put(DomainCommand.Transfer.class, TransferOp.REJECT, DomainTransferRejectFlow.class)
|
||||
.put(DomainCommand.Transfer.class, TransferOp.REQUEST, DomainTransferRequestFlow.class)
|
||||
.build();
|
||||
private static final FlowProvider TRANSFER_FLOW_PROVIDER =
|
||||
new FlowProvider() {
|
||||
private final Table<Class<?>, TransferOp, Class<? extends Flow>> transferFlows =
|
||||
ImmutableTable.<Class<?>, TransferOp, Class<? extends Flow>>builder()
|
||||
.put(
|
||||
ContactCommand.Transfer.class,
|
||||
TransferOp.APPROVE,
|
||||
ContactTransferApproveFlow.class)
|
||||
.put(
|
||||
ContactCommand.Transfer.class,
|
||||
TransferOp.CANCEL,
|
||||
ContactTransferCancelFlow.class)
|
||||
.put(
|
||||
ContactCommand.Transfer.class, TransferOp.QUERY, ContactTransferQueryFlow.class)
|
||||
.put(
|
||||
ContactCommand.Transfer.class,
|
||||
TransferOp.REJECT,
|
||||
ContactTransferRejectFlow.class)
|
||||
.put(
|
||||
ContactCommand.Transfer.class,
|
||||
TransferOp.REQUEST,
|
||||
ContactTransferRequestFlow.class)
|
||||
.put(
|
||||
DomainCommand.Transfer.class,
|
||||
TransferOp.APPROVE,
|
||||
DomainTransferApproveFlow.class)
|
||||
.put(
|
||||
DomainCommand.Transfer.class, TransferOp.CANCEL, DomainTransferCancelFlow.class)
|
||||
.put(DomainCommand.Transfer.class, TransferOp.QUERY, DomainTransferQueryFlow.class)
|
||||
.put(
|
||||
DomainCommand.Transfer.class, TransferOp.REJECT, DomainTransferRejectFlow.class)
|
||||
.put(
|
||||
DomainCommand.Transfer.class,
|
||||
TransferOp.REQUEST,
|
||||
DomainTransferRequestFlow.class)
|
||||
.build();
|
||||
|
||||
@Override
|
||||
Class<? extends Flow> get(
|
||||
EppInput eppInput, InnerCommand innerCommand, ResourceCommand resourceCommand) {
|
||||
return resourceCommand != null && innerCommand instanceof Transfer
|
||||
? transferFlows.get(resourceCommand.getClass(), ((Transfer) innerCommand).getTransferOp())
|
||||
: null;
|
||||
}};
|
||||
@Override
|
||||
Class<? extends Flow> get(
|
||||
EppInput eppInput, InnerCommand innerCommand, ResourceCommand resourceCommand) {
|
||||
return resourceCommand != null && innerCommand instanceof Transfer transfer
|
||||
? transferFlows.get(resourceCommand.getClass(), transfer.getTransferOp())
|
||||
: null;
|
||||
}
|
||||
};
|
||||
|
||||
private static final ImmutableList<FlowProvider> FLOW_PROVIDERS =
|
||||
ImmutableList.of(
|
||||
|
||||
@@ -182,7 +182,7 @@ public class GcsUtils implements Serializable {
|
||||
// These two methods are needed to check whether serialization is done correctly in tests.
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj instanceof GcsUtils && ((GcsUtils) obj).storageOptions.equals(storageOptions);
|
||||
return obj instanceof GcsUtils gcsUtils && gcsUtils.storageOptions.equals(storageOptions);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -68,7 +68,7 @@ public class DirectoryGroupsConnection implements GroupsConnection {
|
||||
@VisibleForTesting
|
||||
static Groups getDefaultGroupPermissions() {
|
||||
Groups permissions = new Groups();
|
||||
permissions.setAllowExternalMembers(Boolean.TRUE.toString());
|
||||
permissions.setAllowExternalMembers("true");
|
||||
permissions.setWhoCanPostMessage("ALL_MANAGERS_CAN_POST");
|
||||
permissions.setWhoCanViewGroup("ALL_MANAGERS_CAN_VIEW");
|
||||
permissions.setWhoCanViewMembership("ALL_MANAGERS_CAN_VIEW");
|
||||
|
||||
@@ -174,8 +174,8 @@ public final class GmailClient {
|
||||
|
||||
@Override
|
||||
public boolean test(Throwable e) {
|
||||
if (e instanceof HttpResponseException) {
|
||||
return testHttpResponse((HttpResponseException) e);
|
||||
if (e instanceof HttpResponseException httpResponseException) {
|
||||
return testHttpResponse(httpResponseException);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -280,9 +280,9 @@ public class LoadTestAction implements Runnable {
|
||||
"clientId",
|
||||
registrarId,
|
||||
"superuser",
|
||||
Boolean.FALSE.toString(),
|
||||
"false",
|
||||
"dryRun",
|
||||
Boolean.FALSE.toString(),
|
||||
"false",
|
||||
"xml",
|
||||
xmls.get(i)))
|
||||
.toBuilder()
|
||||
|
||||
@@ -94,7 +94,8 @@ public abstract class ImmutableObject implements Cloneable {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof ImmutableObject && equalsImmutableObject((ImmutableObject) other);
|
||||
return other instanceof ImmutableObject immutableObject
|
||||
&& equalsImmutableObject(immutableObject);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -141,8 +142,8 @@ public abstract class ImmutableObject implements Cloneable {
|
||||
NavigableMap<String, Object> sortedFields = new TreeMap<>();
|
||||
for (Entry<Field, Object> entry : getSignificantFields().entrySet()) {
|
||||
Object value = entry.getValue();
|
||||
if (value instanceof Instant) {
|
||||
value = ISO_8601_FORMATTER.format((Instant) value);
|
||||
if (value instanceof Instant instant) {
|
||||
value = ISO_8601_FORMATTER.format(instant);
|
||||
}
|
||||
sortedFields.put(entry.getKey().getName(), value);
|
||||
}
|
||||
@@ -159,8 +160,8 @@ public abstract class ImmutableObject implements Cloneable {
|
||||
field.isAnnotationPresent(DoNotHydrate.class)
|
||||
? entry.getValue()
|
||||
: hydrate(entry.getValue());
|
||||
if (value instanceof Instant) {
|
||||
value = ISO_8601_FORMATTER.format((Instant) value);
|
||||
if (value instanceof Instant instant) {
|
||||
value = ISO_8601_FORMATTER.format(instant);
|
||||
}
|
||||
sortedFields.put(field.getName(), value);
|
||||
}
|
||||
@@ -176,17 +177,17 @@ public abstract class ImmutableObject implements Cloneable {
|
||||
|
||||
/** Helper function to recursively hydrate an ImmutableObject. */
|
||||
private static Object hydrate(Object value) {
|
||||
if (value instanceof Map) {
|
||||
return transformValues((Map<?, ?>) value, ImmutableObject::hydrate);
|
||||
if (value instanceof Map map) {
|
||||
return transformValues(map, ImmutableObject::hydrate);
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
return transform((Collection<?>) value, ImmutableObject::hydrate);
|
||||
if (value instanceof Collection collection) {
|
||||
return transform(collection, ImmutableObject::hydrate);
|
||||
}
|
||||
if (value instanceof ImmutableObject) {
|
||||
return ((ImmutableObject) value).toHydratedString();
|
||||
if (value instanceof ImmutableObject immutableObject) {
|
||||
return immutableObject.toHydratedString();
|
||||
}
|
||||
if (value instanceof Instant) {
|
||||
return ISO_8601_FORMATTER.format((Instant) value);
|
||||
if (value instanceof Instant instant) {
|
||||
return ISO_8601_FORMATTER.format(instant);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -195,22 +196,21 @@ public abstract class ImmutableObject implements Cloneable {
|
||||
private static Object toMapRecursive(Object o) {
|
||||
if (o == null) {
|
||||
return null;
|
||||
} else if (o instanceof ImmutableObject) {
|
||||
} else if (o instanceof ImmutableObject immutableObject) {
|
||||
// LinkedHashMap to preserve field ordering and because ImmutableMap forbids null
|
||||
// values.
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
for (Entry<Field, Object> entry : ((ImmutableObject) o).getSignificantFields().entrySet()) {
|
||||
for (Entry<Field, Object> entry : immutableObject.getSignificantFields().entrySet()) {
|
||||
Field field = entry.getKey();
|
||||
if (!field.isAnnotationPresent(IgnoredInDiffableMap.class)) {
|
||||
result.put(field.getName(), toMapRecursive(entry.getValue()));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} else if (o instanceof Map) {
|
||||
return transformValues((Map<?, ?>) o, ImmutableObject::toMapRecursive);
|
||||
} else if (o instanceof Set) {
|
||||
return ((Set<?>) o)
|
||||
.stream()
|
||||
} else if (o instanceof Map map) {
|
||||
return transformValues(map, ImmutableObject::toMapRecursive);
|
||||
} else if (o instanceof Set<?> set) {
|
||||
return set.stream()
|
||||
.map(ImmutableObject::toMapRecursive)
|
||||
// We can't use toImmutableSet here, because values can be null (especially since the
|
||||
// original ImmutableObject might have been the result of a cloneEmptyToNull call).
|
||||
@@ -218,15 +218,14 @@ public abstract class ImmutableObject implements Cloneable {
|
||||
// We can't use toSet either, because we want to preserve order. So we use LinkedHashSet
|
||||
// instead.
|
||||
.collect(toCollection(LinkedHashSet::new));
|
||||
} else if (o instanceof Collection) {
|
||||
return ((Collection<?>) o)
|
||||
.stream()
|
||||
} else if (o instanceof Collection<?> collection) {
|
||||
return collection.stream()
|
||||
.map(ImmutableObject::toMapRecursive)
|
||||
// We can't use toImmutableList here, because values can be null (especially since the
|
||||
// original ImmutableObject might have been the result of a cloneEmptyToNull call).
|
||||
.collect(toList());
|
||||
} else if (o instanceof Instant) {
|
||||
return ISO_8601_FORMATTER.format((Instant) o);
|
||||
} else if (o instanceof Instant instant) {
|
||||
return ISO_8601_FORMATTER.format(instant);
|
||||
} else if (o instanceof Number || o instanceof Boolean) {
|
||||
return o;
|
||||
} else {
|
||||
|
||||
@@ -167,9 +167,9 @@ public class ModelUtils {
|
||||
// Recurse into maps with ImmutableObject values.
|
||||
return transformValues((Map<?, ?>) obj, ModelUtils::cloneEmptyToNullRecursive);
|
||||
}
|
||||
if (obj instanceof ImmutableObject) {
|
||||
if (obj instanceof ImmutableObject immutableObject) {
|
||||
// Recurse on the fields of an ImmutableObject.
|
||||
ImmutableObject copy = ImmutableObject.clone((ImmutableObject) obj);
|
||||
ImmutableObject copy = ImmutableObject.clone(immutableObject);
|
||||
for (Field field : getAllFields(obj.getClass()).values()) {
|
||||
Object oldValue = getFieldValue(obj, field);
|
||||
Object newValue = cloneEmptyToNullRecursive(oldValue);
|
||||
|
||||
@@ -50,8 +50,8 @@ public class FeeCheckCommandExtensionV06 extends ImmutableObject
|
||||
ImmutableList<? extends FeeCheckResponseExtensionItem> items) {
|
||||
ImmutableList.Builder<FeeCheckResponseExtensionItemV06> builder = new ImmutableList.Builder<>();
|
||||
for (FeeCheckResponseExtensionItem item : items) {
|
||||
if (item instanceof FeeCheckResponseExtensionItemV06) {
|
||||
builder.add((FeeCheckResponseExtensionItemV06) item);
|
||||
if (item instanceof FeeCheckResponseExtensionItemV06 feeCheckResponseExtensionItemV06) {
|
||||
builder.add(feeCheckResponseExtensionItemV06);
|
||||
}
|
||||
}
|
||||
return FeeCheckResponseExtensionV06.create(builder.build());
|
||||
|
||||
@@ -54,8 +54,8 @@ public class FeeCheckCommandExtensionV12 extends ImmutableObject
|
||||
ImmutableList<? extends FeeCheckResponseExtensionItem> items) {
|
||||
ImmutableList.Builder<FeeCheckResponseExtensionItemV12> builder = new ImmutableList.Builder<>();
|
||||
for (FeeCheckResponseExtensionItem item : items) {
|
||||
if (item instanceof FeeCheckResponseExtensionItemV12) {
|
||||
builder.add((FeeCheckResponseExtensionItemV12) item);
|
||||
if (item instanceof FeeCheckResponseExtensionItemV12 feeCheckResponseExtensionItemV12) {
|
||||
builder.add(feeCheckResponseExtensionItemV12);
|
||||
}
|
||||
}
|
||||
return FeeCheckResponseExtensionV12.create(currency, builder.build());
|
||||
|
||||
@@ -89,9 +89,9 @@ public class LaunchPhase extends ImmutableObject {
|
||||
/** A special equals implementation that only considers the string value. */
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof LaunchPhase
|
||||
&& Objects.equals(phase, ((LaunchPhase) other).phase)
|
||||
&& Objects.equals(subphase, ((LaunchPhase) other).subphase);
|
||||
return other instanceof LaunchPhase launchPhase
|
||||
&& Objects.equals(phase, launchPhase.phase)
|
||||
&& Objects.equals(subphase, launchPhase.subphase);
|
||||
}
|
||||
|
||||
/** A special hashCode implementation that only considers the string value. */
|
||||
|
||||
@@ -18,7 +18,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.flows.FeeExtensionXmlTagNormalizer;
|
||||
import google.registry.model.ImmutableObject;
|
||||
import google.registry.model.domain.fee.FeeCheckResponseExtension;
|
||||
@@ -60,9 +59,6 @@ public class EppXmlTransformer {
|
||||
"allocationToken-1.0.xsd",
|
||||
"bulkToken.xsd");
|
||||
|
||||
// XML schemas that should not be used in production (yet)
|
||||
private static final ImmutableSet<String> NON_PROD_SCHEMAS = ImmutableSet.of("fee-std-v1.xsd");
|
||||
|
||||
private static final XmlTransformer INPUT_TRANSFORMER =
|
||||
new XmlTransformer(getSchemas(), EppInput.class);
|
||||
|
||||
|
||||
@@ -125,8 +125,8 @@ public class EppInput extends ImmutableObject {
|
||||
@Nullable
|
||||
private ResourceCommand getResourceCommand() {
|
||||
InnerCommand innerCommand = commandWrapper.getCommand();
|
||||
return innerCommand instanceof ResourceCommandWrapper
|
||||
? ((ResourceCommandWrapper) innerCommand).getResourceCommand()
|
||||
return innerCommand instanceof ResourceCommandWrapper resourceCommandWrapper
|
||||
? resourceCommandWrapper.getResourceCommand()
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -136,8 +136,8 @@ public class EppInput extends ImmutableObject {
|
||||
*/
|
||||
public Optional<String> getSingleTargetId() {
|
||||
ResourceCommand resourceCommand = getResourceCommand();
|
||||
return resourceCommand instanceof SingleResourceCommand
|
||||
? Optional.of(((SingleResourceCommand) resourceCommand).getTargetId())
|
||||
return resourceCommand instanceof SingleResourceCommand singleResourceCommand
|
||||
? Optional.of(singleResourceCommand.getTargetId())
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
@@ -147,10 +147,10 @@ public class EppInput extends ImmutableObject {
|
||||
*/
|
||||
public ImmutableList<String> getTargetIds() {
|
||||
ResourceCommand resourceCommand = getResourceCommand();
|
||||
if (resourceCommand instanceof SingleResourceCommand) {
|
||||
return ImmutableList.of(((SingleResourceCommand) resourceCommand).getTargetId());
|
||||
} else if (resourceCommand instanceof ResourceCheck) {
|
||||
return ((ResourceCheck) resourceCommand).getTargetIds();
|
||||
if (resourceCommand instanceof SingleResourceCommand singleResourceCommand) {
|
||||
return ImmutableList.of(singleResourceCommand.getTargetId());
|
||||
} else if (resourceCommand instanceof ResourceCheck resourceCheck) {
|
||||
return resourceCheck.getTargetIds();
|
||||
} else {
|
||||
return ImmutableList.of();
|
||||
}
|
||||
|
||||
@@ -1095,18 +1095,17 @@ public class Registrar extends UpdateAutoTimestampEntity implements Buildable, J
|
||||
"Must specify at least one of localized or internationalized address");
|
||||
checkArgument(
|
||||
getInstance().type.isValidIanaId(getInstance().ianaIdentifier),
|
||||
String.format(
|
||||
"Supplied IANA ID is not valid for %s registrar type: %s",
|
||||
getInstance().type, getInstance().ianaIdentifier));
|
||||
"Supplied IANA ID is not valid for %s registrar type: %s",
|
||||
getInstance().type,
|
||||
getInstance().ianaIdentifier);
|
||||
|
||||
// We do not allow creating Real registrars with IANA ID that's already in the system
|
||||
// b/315007360 - for more details
|
||||
checkArgument(
|
||||
isNotADuplicateIanaId(loadAllCached(), getInstance()),
|
||||
String.format(
|
||||
"Rejected attempt to create a registrar with ianaId that's already in the system -"
|
||||
+ " %s",
|
||||
getInstance().ianaIdentifier));
|
||||
"Rejected attempt to create a registrar with ianaId that's already in the system -"
|
||||
+ " %s",
|
||||
getInstance().ianaIdentifier);
|
||||
|
||||
// In order to grant access to real TLDs, the registrar must have a corresponding billing
|
||||
// account ID for that TLD's billing currency.
|
||||
|
||||
@@ -364,10 +364,10 @@ public abstract class HistoryEntry extends ImmutableObject
|
||||
|
||||
public static <E extends EppResource>
|
||||
HistoryEntry.Builder<? extends HistoryEntry, ?> createBuilderForResource(E parent) {
|
||||
if (parent instanceof DomainBase) {
|
||||
return new DomainHistory.Builder().setDomain((DomainBase) parent);
|
||||
} else if (parent instanceof HostBase) {
|
||||
return new HostHistory.Builder().setHost((HostBase) parent);
|
||||
if (parent instanceof DomainBase domainBase) {
|
||||
return new DomainHistory.Builder().setDomain(domainBase);
|
||||
} else if (parent instanceof HostBase hostBase) {
|
||||
return new HostHistory.Builder().setHost(hostBase);
|
||||
} else {
|
||||
throw new IllegalStateException(
|
||||
String.format(
|
||||
|
||||
@@ -140,19 +140,17 @@ public class Lock extends ImmutableObject implements Serializable {
|
||||
Lock lock = acquireResult.existingLock();
|
||||
DateTime now = acquireResult.transactionTime();
|
||||
switch (acquireResult.lockState()) {
|
||||
case IN_USE:
|
||||
logger.atInfo().log(
|
||||
"Existing lock by request is still valid now %s (until %s) lock: %s",
|
||||
now, lock.expirationTime, lock.lockId);
|
||||
break;
|
||||
case TIMED_OUT:
|
||||
logger.atInfo().log(
|
||||
"Existing lock by request is timed out now %s (was valid until %s) lock: %s",
|
||||
now, lock.expirationTime, lock.lockId);
|
||||
break;
|
||||
case FREE:
|
||||
case IN_USE ->
|
||||
logger.atInfo().log(
|
||||
"Existing lock by request is still valid now %s (until %s) lock: %s",
|
||||
now, lock.expirationTime, lock.lockId);
|
||||
case TIMED_OUT ->
|
||||
logger.atInfo().log(
|
||||
"Existing lock by request is timed out now %s (was valid until %s) lock: %s",
|
||||
now, lock.expirationTime, lock.lockId);
|
||||
case FREE -> {
|
||||
// There was no existing lock
|
||||
break;
|
||||
}
|
||||
}
|
||||
Lock newLock = acquireResult.newLock();
|
||||
if (acquireResult.newLock() != null) {
|
||||
|
||||
@@ -1164,7 +1164,6 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public static final Pattern ROID_SUFFIX_PATTERN = Pattern.compile("^[A-Z\\d]{1,8}$");
|
||||
|
||||
public Builder setRoidSuffix(String roidSuffix) {
|
||||
@@ -1217,15 +1216,15 @@ public class Tld extends ImmutableObject implements Buildable, UnsafeSerializabl
|
||||
AllocationToken token = tm().loadByKey(tokenKey);
|
||||
checkArgument(
|
||||
token.getTokenType().equals(TokenType.DEFAULT_PROMO),
|
||||
String.format(
|
||||
"Token %s has an invalid token type of %s. DefaultPromoTokens must be of"
|
||||
+ " the type DEFAULT_PROMO",
|
||||
token.getToken(), token.getTokenType()));
|
||||
"Token %s has an invalid token type of %s. DefaultPromoTokens must be of"
|
||||
+ " the type DEFAULT_PROMO",
|
||||
token.getToken(),
|
||||
token.getTokenType());
|
||||
checkArgument(
|
||||
token.getAllowedTlds().contains(getInstance().tldStr),
|
||||
String.format(
|
||||
"The token %s is not valid for this TLD. The valid TLDs for it are %s",
|
||||
token.getToken(), token.getAllowedTlds()));
|
||||
"The token %s is not valid for this TLD. The valid TLDs for it are %s",
|
||||
token.getToken(),
|
||||
token.getAllowedTlds());
|
||||
}
|
||||
getInstance().defaultPromoTokens = promoTokens;
|
||||
});
|
||||
|
||||
@@ -29,11 +29,6 @@ import javax.annotation.Nullable;
|
||||
*/
|
||||
public enum ReservationType {
|
||||
|
||||
// We explicitly set the severity, even though we have a checkState that makes it equal to the
|
||||
// ordinal, so that no one accidentally reorders these values and changes the sort order. If a
|
||||
// label has multiple reservation types, its message is the that of the one with the highest
|
||||
// severity.
|
||||
|
||||
/** The domain can only be registered during sunrise, and is reserved thereafter. */
|
||||
ALLOWED_IN_SUNRISE("Reserved", 0),
|
||||
|
||||
@@ -55,6 +50,13 @@ public enum ReservationType {
|
||||
@Nullable
|
||||
private final String messageForCheck;
|
||||
|
||||
/**
|
||||
* We explicitly set the severity, even though we have a checkState that makes it equal to the
|
||||
* ordinal, so that no one accidentally reorders these values and changes the sort order. If a
|
||||
* label has multiple reservation types, its message is the that of the one with the highest
|
||||
* severity.
|
||||
*/
|
||||
@SuppressWarnings("EnumOrdinal")
|
||||
ReservationType(@Nullable String messageForCheck, int severity) {
|
||||
this.messageForCheck = messageForCheck;
|
||||
checkState(
|
||||
@@ -67,13 +69,7 @@ public enum ReservationType {
|
||||
return messageForCheck;
|
||||
}
|
||||
|
||||
private static final Ordering<ReservationType> ORDERING =
|
||||
new Ordering<>() {
|
||||
@Override
|
||||
public int compare(ReservationType left, ReservationType right) {
|
||||
return Integer.compare(left.ordinal(), right.ordinal());
|
||||
}
|
||||
};
|
||||
private static final Ordering<ReservationType> ORDERING = Ordering.natural();
|
||||
|
||||
/**
|
||||
* Returns the {@code ReservationType} with the highest severity, used when a label has multiple
|
||||
|
||||
@@ -151,7 +151,7 @@ public final class ReservedList
|
||||
private static class Builder
|
||||
extends DomainLabelEntry.Builder<ReservedListEntry, ReservedListEntry.Builder> {
|
||||
|
||||
public Builder() {}
|
||||
Builder() {}
|
||||
|
||||
private Builder(ReservedListEntry instance) {
|
||||
super(instance);
|
||||
|
||||
@@ -305,8 +305,8 @@ public class MosApiMetrics {
|
||||
Metric metric = new Metric().setType(METRIC_DOMAIN + suffix).setLabels(labels);
|
||||
|
||||
TypedValue tv = new TypedValue();
|
||||
if (val instanceof Double) {
|
||||
tv.setDoubleValue((Double) val);
|
||||
if (val instanceof Double d) {
|
||||
tv.setDoubleValue(d);
|
||||
} else {
|
||||
tv.setInt64Value(val.longValue());
|
||||
}
|
||||
|
||||
@@ -114,10 +114,10 @@ public final class MosApiModule {
|
||||
try (PEMParser pemParser = new PEMParser(new StringReader(tlsKey))) {
|
||||
Object parsedObj = pemParser.readObject();
|
||||
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
|
||||
if (parsedObj instanceof PEMKeyPair) {
|
||||
return converter.getPrivateKey(((PEMKeyPair) parsedObj).getPrivateKeyInfo());
|
||||
} else if (parsedObj instanceof PrivateKeyInfo) {
|
||||
return converter.getPrivateKey((PrivateKeyInfo) parsedObj);
|
||||
if (parsedObj instanceof PEMKeyPair pemKeyPair) {
|
||||
return converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());
|
||||
} else if (parsedObj instanceof PrivateKeyInfo privateKeyInfo) {
|
||||
return converter.getPrivateKey(privateKeyInfo);
|
||||
}
|
||||
throw new IllegalArgumentException(
|
||||
String.format(
|
||||
|
||||
@@ -36,8 +36,8 @@ public final class JpaRetries {
|
||||
((Predicate<Throwable>) OptimisticLockException.class::isInstance)
|
||||
.or(
|
||||
e ->
|
||||
e instanceof SQLException
|
||||
&& RETRIABLE_TXN_SQL_STATE.contains(((SQLException) e).getSQLState()));
|
||||
e instanceof SQLException sqlException
|
||||
&& RETRIABLE_TXN_SQL_STATE.contains(sqlException.getSQLState()));
|
||||
|
||||
public static boolean isFailedTxnRetriable(Throwable throwable) {
|
||||
Throwable t = throwable;
|
||||
|
||||
@@ -173,7 +173,7 @@ public class SecretManagerClientImpl implements SecretManagerClient {
|
||||
}
|
||||
|
||||
private static boolean isRetryableException(Throwable e) {
|
||||
return e instanceof ApiException && ((ApiException) e).isRetryable();
|
||||
return e instanceof ApiException apiException && apiException.isRetryable();
|
||||
}
|
||||
|
||||
private static Replication defaultReplicationPolicy() {
|
||||
|
||||
@@ -325,14 +325,14 @@ abstract class AbstractJsonableObject implements Jsonable {
|
||||
verifyAllowedJsonKeyName(name, member, jsonable.getClass());
|
||||
return jsonable.toJson();
|
||||
}
|
||||
if (object instanceof String) {
|
||||
return new JsonPrimitive((String) object);
|
||||
if (object instanceof String string) {
|
||||
return new JsonPrimitive(string);
|
||||
}
|
||||
if (object instanceof Number) {
|
||||
return new JsonPrimitive((Number) object);
|
||||
if (object instanceof Number number) {
|
||||
return new JsonPrimitive(number);
|
||||
}
|
||||
if (object instanceof Boolean) {
|
||||
return new JsonPrimitive((Boolean) object);
|
||||
if (object instanceof Boolean b) {
|
||||
return new JsonPrimitive(b);
|
||||
}
|
||||
if (object instanceof DateTime) {
|
||||
// According to RFC 9083 section 3, the syntax of dates and times is defined in RFC3339.
|
||||
@@ -340,11 +340,11 @@ abstract class AbstractJsonableObject implements Jsonable {
|
||||
// According to RFC3339, we should use ISO8601, which is what DateTime.toString does!
|
||||
return new JsonPrimitive(object.toString());
|
||||
}
|
||||
if (object instanceof Instant) {
|
||||
if (object instanceof Instant instant) {
|
||||
// According to RFC 9083 section 3, the syntax of dates and times is defined in RFC3339.
|
||||
//
|
||||
// According to RFC3339, we should use ISO8601, so we use ISO_8601_FORMATTER.
|
||||
return new JsonPrimitive(ISO_8601_FORMATTER.format((Instant) object));
|
||||
return new JsonPrimitive(ISO_8601_FORMATTER.format(instant));
|
||||
}
|
||||
if (object == null) {
|
||||
return JsonNull.INSTANCE;
|
||||
|
||||
@@ -156,9 +156,9 @@ public abstract class RdapActionBase implements Runnable {
|
||||
|
||||
ReplyPayloadBase replyObject =
|
||||
getJsonObjectForResource(pathSearchString, requestMethod == Action.Method.HEAD);
|
||||
if (replyObject instanceof BaseSearchResponse) {
|
||||
if (replyObject instanceof BaseSearchResponse baseSearchResponse) {
|
||||
metricInformationBuilder.setIncompletenessWarningType(
|
||||
((BaseSearchResponse) replyObject).incompletenessWarningType());
|
||||
baseSearchResponse.incompletenessWarningType());
|
||||
}
|
||||
// RFC7480 5.1 - if the server has the information requested and wishes to respond, it returns
|
||||
// that answer in the body of a 200 (OK) response
|
||||
|
||||
@@ -33,7 +33,6 @@ import google.registry.request.Parameter;
|
||||
import google.registry.request.ParameterMap;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
@@ -257,14 +256,10 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
|
||||
|
||||
private void appendParameter(
|
||||
StringBuilder stringBuilder, String name, String value, boolean first) {
|
||||
try {
|
||||
stringBuilder.append(first ? '?' : '&');
|
||||
stringBuilder.append(URLEncoder.encode(name, "UTF-8"));
|
||||
stringBuilder.append('=');
|
||||
stringBuilder.append(URLEncoder.encode(value, "UTF-8"));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
stringBuilder.append(first ? '?' : '&');
|
||||
stringBuilder.append(URLEncoder.encode(name, UTF_8));
|
||||
stringBuilder.append('=');
|
||||
stringBuilder.append(URLEncoder.encode(value, UTF_8));
|
||||
}
|
||||
|
||||
/** Creates the URL for this same search with a different starting point cursor. */
|
||||
|
||||
@@ -45,15 +45,11 @@ abstract class RdapSearchResults {
|
||||
abstract ImmutableMap<String, URI> navigationLinks();
|
||||
|
||||
@JsonableElement("notices") ImmutableList<Notice> getIncompletenessWarnings() {
|
||||
switch (incompletenessWarningType()) {
|
||||
case TRUNCATED:
|
||||
return TRUNCATION_NOTICES;
|
||||
case MIGHT_BE_INCOMPLETE:
|
||||
return POSSIBLY_INCOMPLETE_NOTICES;
|
||||
case COMPLETE:
|
||||
break;
|
||||
}
|
||||
return ImmutableList.of();
|
||||
return switch (incompletenessWarningType()) {
|
||||
case TRUNCATED -> TRUNCATION_NOTICES;
|
||||
case MIGHT_BE_INCOMPLETE -> POSSIBLY_INCOMPLETE_NOTICES;
|
||||
case COMPLETE -> ImmutableList.of();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -141,7 +141,7 @@ final class DomainToXjcConverter {
|
||||
}
|
||||
|
||||
switch (mode) {
|
||||
case FULL:
|
||||
case FULL -> {
|
||||
// o Zero or more OPTIONAL <rgpStatus> element to represent
|
||||
// "pendingDelete" sub-statuses, including "redemptionPeriod",
|
||||
// "pendingRestore", and "pendingDelete", that a domain name can be
|
||||
@@ -206,10 +206,8 @@ final class DomainToXjcConverter {
|
||||
bean.setTrnData(convertTransferData(model.getTransferData()));
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case THIN:
|
||||
break;
|
||||
}
|
||||
case THIN -> {}
|
||||
}
|
||||
|
||||
return bean;
|
||||
|
||||
@@ -170,8 +170,9 @@ public final class RdeMarshaller implements Serializable {
|
||||
}
|
||||
|
||||
private XmlFragmentMarshaller getMarshaller() {
|
||||
return memoizedMarshaller != null
|
||||
? memoizedMarshaller
|
||||
: (memoizedMarshaller = XjcXmlTransformer.get().createFragmentMarshaller());
|
||||
if (memoizedMarshaller == null) {
|
||||
memoizedMarshaller = XjcXmlTransformer.get().createFragmentMarshaller();
|
||||
}
|
||||
return memoizedMarshaller;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,10 +99,9 @@ public final class RdeReportAction implements Runnable, EscrowTask {
|
||||
RdeRevision.getCurrentRevision(tld, watermark, FULL)
|
||||
.orElseThrow(
|
||||
() -> new IllegalStateException("RdeRevision was not set on generated deposit"));
|
||||
if (prefix.isEmpty()) {
|
||||
prefix = Optional.of(findMostRecentPrefixForWatermark(watermark, bucket, tld, gcsUtils));
|
||||
}
|
||||
String name = prefix.get() + RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, revision);
|
||||
var actualPrefix =
|
||||
prefix.orElseGet(() -> findMostRecentPrefixForWatermark(watermark, bucket, tld, gcsUtils));
|
||||
String name = actualPrefix + RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, revision);
|
||||
BlobId reportFilename = BlobId.of(bucket, name + "-report.xml.ghostryde");
|
||||
verify(gcsUtils.existsAndNotEmpty(reportFilename), "Missing file: %s", reportFilename);
|
||||
reporter.send(readReportFromGcs(reportFilename));
|
||||
|
||||
@@ -136,9 +136,8 @@ public final class RdeUploadAction implements Runnable, EscrowTask {
|
||||
public void runWithLock(final DateTime watermark) throws Exception {
|
||||
// If a prefix is not provided,try to determine the prefix. This should only happen when the RDE
|
||||
// upload cron job runs to catch up any un-retried (i. e. expected) RDE failures.
|
||||
if (prefix.isEmpty()) {
|
||||
prefix = Optional.of(findMostRecentPrefixForWatermark(watermark, bucket, tld, gcsUtils));
|
||||
}
|
||||
String actualPrefix =
|
||||
prefix.orElseGet(() -> findMostRecentPrefixForWatermark(watermark, bucket, tld, gcsUtils));
|
||||
logger.atInfo().log("Verifying readiness to upload the RDE deposit.");
|
||||
Optional<Cursor> cursor =
|
||||
tm().transact(
|
||||
@@ -175,7 +174,7 @@ public final class RdeUploadAction implements Runnable, EscrowTask {
|
||||
() -> new IllegalStateException("RdeRevision was not set on generated deposit"));
|
||||
final String nameWithoutPrefix =
|
||||
RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, revision);
|
||||
final String name = prefix.get() + nameWithoutPrefix;
|
||||
final String name = actualPrefix + nameWithoutPrefix;
|
||||
final BlobId xmlFilename = BlobId.of(bucket, name + ".xml.ghostryde");
|
||||
final BlobId xmlLengthFilename = BlobId.of(bucket, name + ".xml.length");
|
||||
BlobId reportFilename = BlobId.of(bucket, name + "-report.xml.ghostryde");
|
||||
|
||||
@@ -19,9 +19,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
|
||||
import static com.google.common.base.Strings.isNullOrEmpty;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -147,11 +147,7 @@ final class RdeUploadUrl implements Comparable<RdeUploadUrl> {
|
||||
* @see URLEncoder#encode(String, String)
|
||||
*/
|
||||
private static String urlencode(String str) {
|
||||
try {
|
||||
return URLEncoder.encode(str, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return URLEncoder.encode(str, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** @see java.net.URI#compareTo(java.net.URI) */
|
||||
@@ -164,7 +160,7 @@ final class RdeUploadUrl implements Comparable<RdeUploadUrl> {
|
||||
@Override
|
||||
public boolean equals(@Nullable Object object) {
|
||||
return object == this
|
||||
|| (object instanceof RdeUploadUrl && Objects.equals(uri, ((RdeUploadUrl) object).uri));
|
||||
|| (object instanceof RdeUploadUrl rdeUploadUrl && Objects.equals(uri, rdeUploadUrl.uri));
|
||||
}
|
||||
|
||||
/** @see java.net.URI#hashCode() */
|
||||
@@ -199,9 +195,9 @@ final class RdeUploadUrl implements Comparable<RdeUploadUrl> {
|
||||
@Override
|
||||
public boolean equals(@Nullable Object object) {
|
||||
return object == this
|
||||
|| (object instanceof Protocol
|
||||
&& port == ((Protocol) object).port
|
||||
&& Objects.equals(name, ((Protocol) object).name));
|
||||
|| (object instanceof Protocol protocol
|
||||
&& port == protocol.port
|
||||
&& Objects.equals(name, protocol.name));
|
||||
}
|
||||
|
||||
/** @see Object#hashCode() */
|
||||
|
||||
@@ -148,7 +148,7 @@ public class RouterDisplayHelper {
|
||||
return headerToString(formatString)
|
||||
+ String.format("%n")
|
||||
+ Streams.stream(routes)
|
||||
.sorted(Comparator.comparing((Route route) -> route.action().service().ordinal()))
|
||||
.sorted(Comparator.comparing((Route route) -> route.action().service()))
|
||||
.map(route -> routeToString(route, formatString))
|
||||
.collect(joining(String.format("%n")));
|
||||
}
|
||||
|
||||
@@ -21,13 +21,14 @@ import java.util.Optional;
|
||||
@Immutable
|
||||
abstract class LanguageValidator {
|
||||
|
||||
/** A registry of all known language validators keyed by their language code. */
|
||||
private static final ImmutableMap<String, LanguageValidator> LANGUAGE_VALIDATORS =
|
||||
ImmutableMap.of("ja", new JapaneseLanguageValidator());
|
||||
|
||||
/** Return the language validator for the given language code (if one exists). */
|
||||
static Optional<LanguageValidator> get(String language) {
|
||||
return Optional.ofNullable(LANGUAGE_VALIDATORS.get(language));
|
||||
return Optional.ofNullable(ValidatorsHolder.LANGUAGE_VALIDATORS.get(language));
|
||||
}
|
||||
|
||||
private static class ValidatorsHolder {
|
||||
private static final ImmutableMap<String, LanguageValidator> LANGUAGE_VALIDATORS =
|
||||
ImmutableMap.of("ja", new JapaneseLanguageValidator());
|
||||
}
|
||||
|
||||
/** Returns true if the label meets the context rules for this language. */
|
||||
|
||||
@@ -132,17 +132,11 @@ public final class NordnVerifyAction implements Runnable {
|
||||
}
|
||||
for (Entry<String, LordnLog.Result> result : log) {
|
||||
switch (result.getValue().getOutcome()) {
|
||||
case OK:
|
||||
break;
|
||||
case WARNING:
|
||||
// fall through
|
||||
case ERROR:
|
||||
logger.atWarning().log(result.toString());
|
||||
break;
|
||||
default:
|
||||
logger.atWarning().log(
|
||||
"LORDN verify task %s: Unexpected outcome: %s", actionLogId, result);
|
||||
break;
|
||||
case OK -> {}
|
||||
case WARNING, ERROR -> logger.atWarning().log(result.toString());
|
||||
default ->
|
||||
logger.atWarning().log(
|
||||
"LORDN verify task %s: Unexpected outcome: %s", actionLogId, result);
|
||||
}
|
||||
}
|
||||
return log;
|
||||
|
||||
@@ -164,10 +164,10 @@ public final class TmchCertificateAuthority {
|
||||
root.checkValidity(clock.nowUtc().toDate());
|
||||
return root;
|
||||
} catch (Exception e) {
|
||||
if (e instanceof GeneralSecurityException) {
|
||||
throw (GeneralSecurityException) e;
|
||||
} else if (e instanceof RuntimeException) {
|
||||
throw (RuntimeException) e;
|
||||
if (e instanceof GeneralSecurityException generalSecurityException) {
|
||||
throw generalSecurityException;
|
||||
} else if (e instanceof RuntimeException runtimeException) {
|
||||
throw runtimeException;
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -177,10 +177,10 @@ public final class TmchCertificateAuthority {
|
||||
try {
|
||||
return CRL_CACHE.get(tmchCaMode);
|
||||
} catch (Exception e) {
|
||||
if (e.getCause() instanceof GeneralSecurityException) {
|
||||
throw (GeneralSecurityException) e.getCause();
|
||||
} else if (e instanceof RuntimeException) {
|
||||
throw (RuntimeException) e;
|
||||
if (e.getCause() instanceof GeneralSecurityException generalSecurityException) {
|
||||
throw generalSecurityException;
|
||||
} else if (e instanceof RuntimeException runtimeException) {
|
||||
throw runtimeException;
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
|
||||
package google.registry.tools;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
|
||||
import com.google.common.base.Ascii;
|
||||
import google.registry.model.EppResource;
|
||||
import google.registry.model.ForeignKeyUtils;
|
||||
@@ -52,10 +50,7 @@ class CommandUtilities {
|
||||
|
||||
/** Prompts for yes/no input using promptText, defaulting to no. */
|
||||
static boolean promptForYes(String promptText) {
|
||||
checkState(
|
||||
System.console() != null,
|
||||
"Unable to access stdin (are you running with `gradle registryTool`?), try using -f.");
|
||||
String input = System.console().readLine(promptText + " (y/N): ");
|
||||
String input = System.console().readLine("%s (y/N): ", promptText);
|
||||
// Null represents end-of-file (e.g. ^-D) so interpret that as a negative response.
|
||||
return input != null && Ascii.toUpperCase(input).startsWith("Y");
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import com.beust.jcommander.Parameter;
|
||||
import com.google.common.base.Strings;
|
||||
import java.io.PrintStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
/** A {@link Command} that implements a confirmation step before executing. */
|
||||
public abstract class ConfirmingCommand implements Command {
|
||||
@@ -34,12 +33,8 @@ public abstract class ConfirmingCommand implements Command {
|
||||
public PrintStream errorPrintStream;
|
||||
|
||||
protected ConfirmingCommand() {
|
||||
try {
|
||||
printStream = new PrintStream(System.out, false, UTF_8.name());
|
||||
errorPrintStream = new PrintStream(System.err, false, UTF_8.name());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
printStream = new PrintStream(System.out, false, UTF_8);
|
||||
errorPrintStream = new PrintStream(System.err, false, UTF_8);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -365,9 +365,8 @@ class GenerateAllocationTokensCommand implements Command {
|
||||
getExistingTokenStrings(ImmutableSet.copyOf(tokenStrings));
|
||||
checkArgument(
|
||||
existingTokenStrings.isEmpty(),
|
||||
String.format(
|
||||
"Cannot create specified tokens; the following tokens already exist: %s",
|
||||
existingTokenStrings));
|
||||
"Cannot create specified tokens; the following tokens already exist: %s",
|
||||
existingTokenStrings);
|
||||
}
|
||||
|
||||
private Stream<String> getNextTokenBatch(int tokensSaved) {
|
||||
|
||||
@@ -24,7 +24,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import google.registry.model.tld.Tld;
|
||||
import jakarta.inject.Inject;
|
||||
import java.io.PrintStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.List;
|
||||
|
||||
/** Command to show a TLD record. */
|
||||
@@ -39,11 +38,11 @@ final class GetTldCommand implements Command {
|
||||
@Inject ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public void run() throws JsonProcessingException, UnsupportedEncodingException {
|
||||
public void run() throws JsonProcessingException {
|
||||
// Don't use try-with-resources to manage standard output streams, closing the stream will
|
||||
// cause subsequent output to standard output or standard error to be lost
|
||||
// See: https://errorprone.info/bugpattern/ClosingStandardOutputStreams
|
||||
PrintStream printStream = new PrintStream(System.out, false, UTF_8.name());
|
||||
PrintStream printStream = new PrintStream(System.out, false, UTF_8);
|
||||
for (String tld : assertTldsExist(mainParameters)) {
|
||||
printStream.println(objectMapper.writeValueAsString(Tld.get(tld)));
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ abstract class ListObjectsCommand implements CommandWithConnection {
|
||||
params.put(PRINT_HEADER_ROW_PARAM, printHeaderRow);
|
||||
}
|
||||
if (fullFieldNames) {
|
||||
params.put(FULL_FIELD_NAMES_PARAM, Boolean.TRUE);
|
||||
params.put(FULL_FIELD_NAMES_PARAM, true);
|
||||
}
|
||||
params.putAll(getParameterMap());
|
||||
// Call the server and get the response data.
|
||||
|
||||
@@ -51,13 +51,13 @@ public abstract class MutatingCommand extends ConfirmingCommand {
|
||||
private static class EntityChange {
|
||||
|
||||
/** The possible types of mutation that can be performed on an entity. */
|
||||
public enum ChangeType {
|
||||
enum ChangeType {
|
||||
CREATE,
|
||||
DELETE,
|
||||
UPDATE;
|
||||
|
||||
/** Return the ChangeType corresponding to the given combination of version existences. */
|
||||
public static ChangeType get(boolean hasOldVersion, boolean hasNewVersion) {
|
||||
static ChangeType get(boolean hasOldVersion, boolean hasNewVersion) {
|
||||
checkArgument(
|
||||
hasOldVersion || hasNewVersion,
|
||||
"An entity change must have an old version or a new version (or both)");
|
||||
|
||||
@@ -220,8 +220,8 @@ final class RegistryCli implements CommandRunner {
|
||||
private void runCommand(Command command) throws Exception {
|
||||
injectReflectively(RegistryToolComponent.class, component, command);
|
||||
|
||||
if (command instanceof CommandWithConnection) {
|
||||
((CommandWithConnection) command).setConnection(getConnection());
|
||||
if (command instanceof CommandWithConnection commandWithConnection) {
|
||||
commandWithConnection.setConnection(getConnection());
|
||||
}
|
||||
|
||||
// Reset the JPA transaction manager after every command to avoid a situation where a test can
|
||||
|
||||
@@ -75,12 +75,12 @@ public class PasswordResetRequestAction extends ConsoleApiAction {
|
||||
String destinationEmail;
|
||||
String emailSubject;
|
||||
switch (type) {
|
||||
case EPP:
|
||||
case EPP -> {
|
||||
requiredPermission = ConsolePermission.EDIT_REGISTRAR_DETAILS;
|
||||
destinationEmail = getAdminPocEmail(registrarId);
|
||||
emailSubject = "EPP password reset request";
|
||||
break;
|
||||
case REGISTRY_LOCK:
|
||||
}
|
||||
case REGISTRY_LOCK -> {
|
||||
checkArgument(
|
||||
passwordResetRequestData.registryLockEmail != null,
|
||||
"Must provide registry lock email to reset");
|
||||
@@ -88,9 +88,8 @@ public class PasswordResetRequestAction extends ConsoleApiAction {
|
||||
destinationEmail = passwordResetRequestData.registryLockEmail;
|
||||
checkUserExistsWithRegistryLockEmail(destinationEmail);
|
||||
emailSubject = "Registry lock password reset request";
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Unknown type " + type);
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unknown type " + type);
|
||||
}
|
||||
|
||||
checkPermission(user, registrarId, requiredPermission);
|
||||
|
||||
@@ -111,9 +111,9 @@ public class TestPipelineExtension extends Pipeline
|
||||
private static class PipelineRunEnforcement {
|
||||
|
||||
@SuppressWarnings("WeakerAccess")
|
||||
protected boolean enableAutoRunIfMissing;
|
||||
boolean enableAutoRunIfMissing;
|
||||
|
||||
protected final Pipeline pipeline;
|
||||
final Pipeline pipeline;
|
||||
|
||||
boolean runAttempted;
|
||||
|
||||
@@ -129,9 +129,9 @@ public class TestPipelineExtension extends Pipeline
|
||||
runAttempted = true;
|
||||
}
|
||||
|
||||
protected void afterPipelineExecution() {}
|
||||
void afterPipelineExecution() {}
|
||||
|
||||
protected void afterUserCodeFinished() {
|
||||
void afterUserCodeFinished() {
|
||||
if (!runAttempted && enableAutoRunIfMissing) {
|
||||
pipeline.run().waitUntilFinish();
|
||||
}
|
||||
@@ -346,8 +346,8 @@ public class TestPipelineExtension extends Pipeline
|
||||
verifyPAssertsSucceeded(this, pipelineResult);
|
||||
} catch (RuntimeException exc) {
|
||||
Throwable cause = exc.getCause();
|
||||
if (cause instanceof AssertionError) {
|
||||
throw (AssertionError) cause;
|
||||
if (cause instanceof AssertionError assertionError) {
|
||||
throw assertionError;
|
||||
} else {
|
||||
throw exc;
|
||||
}
|
||||
@@ -504,7 +504,7 @@ public class TestPipelineExtension extends Pipeline
|
||||
private static class IsEmptyVisitor extends PipelineVisitor.Defaults {
|
||||
private boolean empty = true;
|
||||
|
||||
public boolean isEmpty() {
|
||||
boolean isEmpty() {
|
||||
return empty;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,12 @@ public class ExportPremiumTermsActionTest {
|
||||
private static final ImmutableList<String> PREMIUM_NAMES =
|
||||
ImmutableList.of("2048,USD 549", "0,USD 549");
|
||||
private static final String EXPECTED_FILE_CONTENT =
|
||||
"# Premium Terms Export Disclaimer\n# TLD: tld\n0, 549.00\n" + "2048, 549.00\n";
|
||||
"""
|
||||
# Premium Terms Export Disclaimer
|
||||
# TLD: tld
|
||||
0, 549.00
|
||||
2048, 549.00
|
||||
""";
|
||||
|
||||
@RegisterExtension
|
||||
final JpaIntegrationTestExtension jpa =
|
||||
|
||||
@@ -158,7 +158,7 @@ public abstract class FlowTestCase<F extends Flow> {
|
||||
assertThat(flowClass).isAssignableTo(MutatingFlow.class);
|
||||
} else {
|
||||
// There's no "isNotAssignableTo" in Truth.
|
||||
assertWithMessage(flowClass.getSimpleName() + " implements MutatingFlow")
|
||||
assertWithMessage("%s implements MutatingFlow", flowClass.getSimpleName())
|
||||
.that(MutatingFlow.class.isAssignableFrom(flowClass))
|
||||
.isFalse();
|
||||
}
|
||||
@@ -192,7 +192,7 @@ public abstract class FlowTestCase<F extends Flow> {
|
||||
}
|
||||
|
||||
private static BillingBase expandGracePeriod(GracePeriod gracePeriod) {
|
||||
assertWithMessage("Billing event is present for grace period: " + gracePeriod)
|
||||
assertWithMessage("Billing event is present for grace period: %s", gracePeriod)
|
||||
.that(gracePeriod.hasBillingEvent())
|
||||
.isTrue();
|
||||
return tm().transact(
|
||||
|
||||
@@ -73,7 +73,7 @@ public class PremiumListTest {
|
||||
BloomFilter<String> bloomFilter = pl.getBloomFilter();
|
||||
assertThat(bloomFilter.mightContain("notpremium")).isFalse();
|
||||
for (String label : ImmutableList.of("rich", "lol", "johnny-be-goode", "icann")) {
|
||||
assertWithMessage(label + " should be a probable premium")
|
||||
assertWithMessage("%s should be a probable premium", label)
|
||||
.that(bloomFilter.mightContain(label))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ public class ReservedListDaoTest {
|
||||
assertThat(ReservedListDao.getLatestRevision("testlist").isPresent()).isFalse();
|
||||
ReservedListDao.save(testReservedList);
|
||||
ReservedList persistedList = ReservedListDao.getLatestRevision("testlist").get();
|
||||
assertThat(persistedList.getRevisionId()).isNotNull();
|
||||
assertThat(persistedList.getRevisionId()).isAtLeast(1L);
|
||||
assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc());
|
||||
assertThat(persistedList.getName()).isEqualTo("testlist");
|
||||
assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(testReservations);
|
||||
@@ -143,7 +143,7 @@ public class ReservedListDaoTest {
|
||||
.build());
|
||||
ReservedListDao.save(testReservedList);
|
||||
ReservedList persistedList = ReservedListDao.getLatestRevision("testlist").get();
|
||||
assertThat(persistedList.getRevisionId()).isNotNull();
|
||||
assertThat(persistedList.getRevisionId()).isAtLeast(1L);
|
||||
assertThat(persistedList.getCreationTimestamp()).isEqualTo(fakeClock.nowUtc());
|
||||
assertThat(persistedList.getName()).isEqualTo("testlist");
|
||||
assertThat(persistedList.getReservedListEntries()).containsExactlyEntriesIn(testReservations);
|
||||
|
||||
@@ -99,7 +99,7 @@ public class DateTimeConverterTest {
|
||||
|
||||
DateTime dt;
|
||||
|
||||
public TestEntity() {}
|
||||
TestEntity() {}
|
||||
|
||||
TestEntity(String name, DateTime dt) {
|
||||
this.name = name;
|
||||
|
||||
@@ -67,7 +67,7 @@ public class LocalDateConverterTest {
|
||||
|
||||
LocalDate date;
|
||||
|
||||
public LocalDateConverterTestEntity() {}
|
||||
LocalDateConverterTestEntity() {}
|
||||
|
||||
LocalDateConverterTestEntity(LocalDate date) {
|
||||
this.date = date;
|
||||
|
||||
@@ -41,7 +41,8 @@ class JpaTestExtensionsSqlLoggingTest {
|
||||
@BeforeEach
|
||||
void beforeEach() {
|
||||
orgStdout = System.out;
|
||||
System.setOut(new PrintStream(stdoutBuffer = new ByteArrayOutputStream()));
|
||||
stdoutBuffer = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(stdoutBuffer));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -56,6 +57,6 @@ class JpaTestExtensionsSqlLoggingTest {
|
||||
tm().getEntityManager()
|
||||
.createNativeQuery("select 1", long.class)
|
||||
.getSingleResult());
|
||||
assertThat(stdoutBuffer.toString(UTF_8.name())).contains("select 1");
|
||||
assertThat(stdoutBuffer.toString(UTF_8)).contains("select 1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -906,12 +906,12 @@ class JpaTransactionManagerImplTest {
|
||||
}
|
||||
|
||||
@Id
|
||||
public String getNameField() {
|
||||
String getNameField() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Id
|
||||
public int getAgeField() {
|
||||
int getAgeField() {
|
||||
return age;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ public class QueryComposerTest {
|
||||
.withEntityClass(TestEntity.class)
|
||||
.buildUnitTestExtension();
|
||||
|
||||
public QueryComposerTest() {}
|
||||
QueryComposerTest() {}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -324,18 +324,18 @@ public class QueryComposerTest {
|
||||
@Column(name = "some_value")
|
||||
private int val;
|
||||
|
||||
public TestEntity() {}
|
||||
TestEntity() {}
|
||||
|
||||
public TestEntity(String name, int val) {
|
||||
TestEntity(String name, int val) {
|
||||
this.name = name;
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
public int getVal() {
|
||||
int getVal() {
|
||||
return val;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ class RdapActionBaseTest extends RdapActionBaseTestCase<RdapActionBaseTest.RdapT
|
||||
throw new RuntimeException();
|
||||
}
|
||||
return new ReplyPayloadBase(BoilerplateType.OTHER) {
|
||||
@JsonableElement public String key = "value";
|
||||
@JsonableElement String key = "value";
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ final class RdapDataStructuresTest {
|
||||
|
||||
@Test
|
||||
void testLanguage() {
|
||||
assertThat(LanguageIdentifier.EN.toJson()).isEqualTo(createJson("'en'"));
|
||||
assertThat(createJson("'en'")).isEqualTo(LanguageIdentifier.EN.toJson());
|
||||
assertRestrictedNames(LanguageIdentifier.EN, "lang");
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ final class RdapDataStructuresTest {
|
||||
|
||||
@Test
|
||||
void testRdapStatus() {
|
||||
assertThat(RdapStatus.ACTIVE.toJson()).isEqualTo(createJson("'active'"));
|
||||
assertThat(createJson("'active'")).isEqualTo(RdapStatus.ACTIVE.toJson());
|
||||
assertRestrictedNames(RdapStatus.ACTIVE, "status[]");
|
||||
}
|
||||
|
||||
@@ -178,7 +178,7 @@ final class RdapDataStructuresTest {
|
||||
|
||||
@Test
|
||||
void testObjectClassName() {
|
||||
assertThat(ObjectClassName.DOMAIN.toJson()).isEqualTo(createJson("'domain'"));
|
||||
assertThat(createJson("'domain'")).isEqualTo(ObjectClassName.DOMAIN.toJson());
|
||||
assertRestrictedNames(ObjectClassName.DOMAIN, "objectClassName");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeHistoryEntr
|
||||
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
|
||||
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarPocs;
|
||||
import static google.registry.testing.GsonSubject.assertAboutJson;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
@@ -523,7 +524,7 @@ class RdapDomainSearchActionTest extends RdapSearchActionTestCase<RdapDomainSear
|
||||
assertThat(linkToNext).isNotNull();
|
||||
int pos = linkToNext.indexOf("cursor=");
|
||||
assertThat(pos).isAtLeast(0);
|
||||
cursor = URLDecoder.decode(linkToNext.substring(pos + 7), "UTF-8");
|
||||
cursor = URLDecoder.decode(linkToNext.substring(pos + 7), UTF_8);
|
||||
JsonArray searchResults = results.getAsJsonArray("domainSearchResults");
|
||||
assertThat(searchResults).hasSize(action.rdapResultSetMaxSize);
|
||||
for (JsonElement item : searchResults) {
|
||||
|
||||
@@ -23,6 +23,7 @@ import static google.registry.testing.DatabaseHelper.persistResources;
|
||||
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
|
||||
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarPocs;
|
||||
import static google.registry.testing.GsonSubject.assertAboutJson;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
@@ -214,7 +215,7 @@ class RdapEntitySearchActionTest extends RdapSearchActionTestCase<RdapEntitySear
|
||||
assertThat(linkToNext).isNotNull();
|
||||
int pos = linkToNext.indexOf("cursor=");
|
||||
assertThat(pos).isAtLeast(0);
|
||||
cursor = URLDecoder.decode(linkToNext.substring(pos + 7), "UTF-8");
|
||||
cursor = URLDecoder.decode(linkToNext.substring(pos + 7), UTF_8);
|
||||
JsonArray searchResults = results.getAsJsonArray("entitySearchResults");
|
||||
assertThat(searchResults).hasSize(action.rdapResultSetMaxSize);
|
||||
for (JsonElement item : searchResults) {
|
||||
|
||||
@@ -377,7 +377,7 @@ class RdapJsonFormatterTest {
|
||||
.that(
|
||||
TopLevelReplyObject.create(
|
||||
new ReplyPayloadBase(BoilerplateType.OTHER) {
|
||||
@JsonableElement public static final String key = "value";
|
||||
@JsonableElement static final String key = "value";
|
||||
},
|
||||
rdapJsonFormatter.createTosNotice())
|
||||
.toJson())
|
||||
@@ -390,7 +390,7 @@ class RdapJsonFormatterTest {
|
||||
.that(
|
||||
TopLevelReplyObject.create(
|
||||
new ReplyPayloadBase(BoilerplateType.DOMAIN) {
|
||||
@JsonableElement public static final String key = "value";
|
||||
@JsonableElement static final String key = "value";
|
||||
},
|
||||
rdapJsonFormatter.createTosNotice())
|
||||
.toJson())
|
||||
|
||||
@@ -25,6 +25,7 @@ import static google.registry.testing.FullFieldsTestEntityHelper.makeDomain;
|
||||
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrar;
|
||||
import static google.registry.testing.FullFieldsTestEntityHelper.makeRegistrarPocs;
|
||||
import static google.registry.testing.GsonSubject.assertAboutJson;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
@@ -653,7 +654,7 @@ class RdapNameserverSearchActionTest extends RdapSearchActionTestCase<RdapNamese
|
||||
assertThat(linkToNext).isNotNull();
|
||||
int pos = linkToNext.indexOf("cursor=");
|
||||
assertThat(pos).isAtLeast(0);
|
||||
cursor = URLDecoder.decode(linkToNext.substring(pos + 7), "UTF-8");
|
||||
cursor = URLDecoder.decode(linkToNext.substring(pos + 7), UTF_8);
|
||||
JsonArray searchResults = results.getAsJsonArray("nameserverSearchResults");
|
||||
assertThat(searchResults).hasSize(action.rdapResultSetMaxSize);
|
||||
for (JsonElement item : searchResults) {
|
||||
|
||||
@@ -67,10 +67,12 @@ abstract class AbstractEppResourceSubject<
|
||||
@Override
|
||||
public void isEqualTo(@Nullable Object other) {
|
||||
// If the objects differ and we can show an interesting ImmutableObject diff, do so.
|
||||
if (actual != null && other instanceof ImmutableObject && !actual.equals(other)) {
|
||||
if (actual != null
|
||||
&& other instanceof ImmutableObject immutableObject
|
||||
&& !actual.equals(other)) {
|
||||
String diffText =
|
||||
prettyPrintEntityDeepDiff(
|
||||
((ImmutableObject) other).toDiffableFieldMap(), actual.toDiffableFieldMap());
|
||||
immutableObject.toDiffableFieldMap(), actual.toDiffableFieldMap());
|
||||
failWithoutActual(fact("expected", other), fact("but was", actual), fact("diff", diffText));
|
||||
}
|
||||
// Otherwise, fall back to regular behavior.
|
||||
|
||||
@@ -300,7 +300,7 @@ public class CloudTasksHelper implements Serializable {
|
||||
params = paramBuilder.build();
|
||||
}
|
||||
|
||||
public Map<String, Object> toMap() {
|
||||
Map<String, Object> toMap() {
|
||||
Map<String, Object> builder = new HashMap<>();
|
||||
builder.put("taskName", taskName);
|
||||
builder.put("method", method);
|
||||
|
||||
@@ -226,8 +226,8 @@ public final class FullFieldsTestEntityHelper {
|
||||
.setBySuperuser(false)
|
||||
.setReason(reason)
|
||||
.setRequestedByRegistrar(false);
|
||||
if (builder instanceof DomainHistory.Builder) {
|
||||
((DomainHistory.Builder) builder).setPeriod(period);
|
||||
if (builder instanceof DomainHistory.Builder domainHistoryBuilder) {
|
||||
domainHistoryBuilder.setPeriod(period);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@@ -110,8 +110,7 @@ public final class GpgSystemCommandExtension implements BeforeEachCallback, Afte
|
||||
publicKeyring.copyTo(pid.getOutputStream());
|
||||
pid.getOutputStream().close();
|
||||
int returnValue = pid.waitFor();
|
||||
assertWithMessage(
|
||||
String.format("Failed to import public keyring: \n%s", slurp(pid.getErrorStream())))
|
||||
assertWithMessage("Failed to import public keyring: \n%s", slurp(pid.getErrorStream()))
|
||||
.that(returnValue)
|
||||
.isEqualTo(0);
|
||||
|
||||
@@ -119,8 +118,7 @@ public final class GpgSystemCommandExtension implements BeforeEachCallback, Afte
|
||||
privateKeyring.copyTo(pid.getOutputStream());
|
||||
pid.getOutputStream().close();
|
||||
returnValue = pid.waitFor();
|
||||
assertWithMessage(
|
||||
String.format("Failed to import private keyring: \n%s", slurp(pid.getErrorStream())))
|
||||
assertWithMessage("Failed to import private keyring: \n%s", slurp(pid.getErrorStream()))
|
||||
.that(returnValue)
|
||||
.isEqualTo(0);
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ public class LogsSubject extends Subject {
|
||||
for (String messageCandidate : messagesAtLevel) {
|
||||
if (messageCandidate.contains(message)) {
|
||||
return new Which<>(
|
||||
assertWithMessage(String.format("log message at %s matching '%s'", level, message))
|
||||
assertWithMessage("log message at %s matching '%s'", level, message)
|
||||
.that(messageCandidate));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.ListMultimap;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
/**
|
||||
@@ -65,15 +64,13 @@ public final class UriParameters {
|
||||
|
||||
private static String decodeString(String str, int start, int end) {
|
||||
try {
|
||||
return URLDecoder.decode(str.substring(start, end), UTF_8.name());
|
||||
return URLDecoder.decode(str.substring(start, end), UTF_8);
|
||||
} catch (IllegalArgumentException iae) {
|
||||
// According to the javadoc of URLDecoder, when the input string is
|
||||
// illegal, it could either leave the illegal characters alone or throw
|
||||
// an IllegalArgumentException! To deal with both consistently, we
|
||||
// ignore IllegalArgumentException and just return the original string.
|
||||
return str.substring(start, end);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import static com.google.common.collect.Iterables.concat;
|
||||
import static com.google.common.collect.Iterables.toArray;
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
|
||||
import static java.nio.charset.StandardCharsets.US_ASCII;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import com.beust.jcommander.JCommander;
|
||||
@@ -83,9 +84,9 @@ public abstract class CommandTestCase<C extends Command> {
|
||||
// Capture standard output/error. Use a single-byte encoding to emulate platforms where default
|
||||
// charset is not UTF_8.
|
||||
oldStdout = System.out;
|
||||
System.setOut(new PrintStream(new OutputSplitter(System.out, stdout), false, "US-ASCII"));
|
||||
System.setOut(new PrintStream(new OutputSplitter(System.out, stdout), false, US_ASCII));
|
||||
oldStderr = System.err;
|
||||
System.setErr(new PrintStream(new OutputSplitter(System.err, stderr), false, "US-ASCII"));
|
||||
System.setErr(new PrintStream(new OutputSplitter(System.err, stderr), false, US_ASCII));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
@@ -183,7 +183,7 @@ public class EppToolVerifier {
|
||||
assertThat(map).containsEntry("dryRun", Boolean.toString(dryRun));
|
||||
assertThat(map).containsEntry("clientId", registrarId);
|
||||
assertThat(map).containsEntry("superuser", Boolean.toString(superuser));
|
||||
return URLDecoder.decode(map.get("xml"), UTF_8.toString());
|
||||
return URLDecoder.decode(map.get("xml"), UTF_8);
|
||||
}
|
||||
|
||||
private EppToolVerifier verifySentContents(String expectedXmlContent) throws Exception {
|
||||
|
||||
@@ -19,7 +19,6 @@ import static com.google.common.truth.Truth.assertWithMessage;
|
||||
import static google.registry.tools.GenerateSqlErDiagramCommand.FLYWAY_FILE_ELEMENT_ID;
|
||||
import static google.registry.tools.GenerateSqlErDiagramCommand.getLastFlywayFileName;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import google.registry.util.ResourceUtils;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
@@ -33,15 +32,14 @@ class GenerateSqlErDiagramCommandTest extends CommandTestCase<GenerateSqlErDiagr
|
||||
|
||||
private static final String GOLDEN_DIAGRAM_FOLDER = "sql/er_diagram";
|
||||
private static final String UPDATE_INSTRUCTIONS =
|
||||
Joiner.on('\n')
|
||||
.join(
|
||||
"",
|
||||
"-------------------------------------------------------------------------------",
|
||||
"Your changes affect SQL ER diagrams. To update the checked-in version, run the"
|
||||
+ " following command in the repository root:",
|
||||
"./gradlew devTool --args=\"-e localhost generate_sql_er_diagram -o"
|
||||
+ " ../db/src/main/resources/sql/er_diagram\"",
|
||||
"");
|
||||
"""
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
Your changes affect SQL ER diagrams. To update the checked-in version, run the \
|
||||
following command in the repository root:
|
||||
./gradlew devTool --args="-e localhost generate_sql_er_diagram -o \
|
||||
../db/src/main/resources/sql/er_diagram"
|
||||
""";
|
||||
|
||||
@Test
|
||||
void testSchemaGeneration() throws Exception {
|
||||
|
||||
@@ -57,10 +57,12 @@ public class GetFeatureFlagCommandTest extends CommandTestCase<GetFeatureFlagCom
|
||||
.build());
|
||||
runCommand("TEST_FEATURE");
|
||||
assertInStdout(
|
||||
"featureName: \"TEST_FEATURE\"\n"
|
||||
+ "status:\n"
|
||||
+ " \"1970-01-01T00:00:00.000Z\": \"INACTIVE\"\n"
|
||||
+ " \"2000-02-26T00:00:00.000Z\": \"ACTIVE\"");
|
||||
"""
|
||||
featureName: "TEST_FEATURE"
|
||||
status:
|
||||
"1970-01-01T00:00:00.000Z": "INACTIVE"
|
||||
"2000-02-26T00:00:00.000Z": "ACTIVE\"\
|
||||
""");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,16 +88,18 @@ public class GetFeatureFlagCommandTest extends CommandTestCase<GetFeatureFlagCom
|
||||
.build());
|
||||
runCommand("TEST_FEATURE", "MINIMUM_DATASET_CONTACTS_OPTIONAL");
|
||||
assertInStdout(
|
||||
"featureName: \"TEST_FEATURE\"\n"
|
||||
+ "status:\n"
|
||||
+ " \"1970-01-01T00:00:00.000Z\": \"INACTIVE\"\n"
|
||||
+ " \"2000-02-26T00:00:00.000Z\": \"ACTIVE\""
|
||||
+ "\n\n"
|
||||
+ "featureName: \"MINIMUM_DATASET_CONTACTS_OPTIONAL\"\n"
|
||||
+ "status:\n"
|
||||
+ " \"1970-01-01T00:00:00.000Z\": \"INACTIVE\"\n"
|
||||
+ " \"2000-01-22T00:00:00.000Z\": \"ACTIVE\"\n"
|
||||
+ " \"2000-02-12T00:00:00.000Z\": \"INACTIVE\"");
|
||||
"""
|
||||
featureName: "TEST_FEATURE"
|
||||
status:
|
||||
"1970-01-01T00:00:00.000Z": "INACTIVE"
|
||||
"2000-02-26T00:00:00.000Z": "ACTIVE"
|
||||
|
||||
featureName: "MINIMUM_DATASET_CONTACTS_OPTIONAL"
|
||||
status:
|
||||
"1970-01-01T00:00:00.000Z": "INACTIVE"
|
||||
"2000-01-22T00:00:00.000Z": "ACTIVE"
|
||||
"2000-02-12T00:00:00.000Z": "INACTIVE\"\
|
||||
""");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -56,27 +56,29 @@ class SecurityActionTest extends ConsoleActionBaseTestCase {
|
||||
private Registrar testRegistrar;
|
||||
|
||||
private static final String VALIDITY_TOO_LONG_CERT_PEM =
|
||||
"-----BEGIN CERTIFICATE-----\n"
|
||||
+ "MIIDejCCAv+gAwIBAgIQHNcSEt4VENkSgtozEEoQLzAKBggqhkjOPQQDAzB8MQsw\n"
|
||||
+ "CQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0b24xGDAW\n"
|
||||
+ "BgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBSb290IENl\n"
|
||||
+ "cnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzAeFw0xOTAzMDcxOTQyNDJaFw0zNDAz\n"
|
||||
+ "MDMxOTQyNDJaMG8xCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UE\n"
|
||||
+ "BwwHSG91c3RvbjERMA8GA1UECgwIU1NMIENvcnAxKzApBgNVBAMMIlNTTC5jb20g\n"
|
||||
+ "U1NMIEludGVybWVkaWF0ZSBDQSBFQ0MgUjIwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\n"
|
||||
+ "AASEOWn30uEYKDLFu4sCjFQ1VupFaeMtQjqVWyWSA7+KFljnsVaFQ2hgs4cQk1f/\n"
|
||||
+ "RQ2INSwdVCYU0i5qsbom20rigUhDh9dM/r6bEZ75eFE899kSCI14xqThYVLPdLEl\n"
|
||||
+ "+dyjggFRMIIBTTASBgNVHRMBAf8ECDAGAQH/AgEAMB8GA1UdIwQYMBaAFILRhXMw\n"
|
||||
+ "5zUE044CkvvlpNHEIejNMHgGCCsGAQUFBwEBBGwwajBGBggrBgEFBQcwAoY6aHR0\n"
|
||||
+ "cDovL3d3dy5zc2wuY29tL3JlcG9zaXRvcnkvU1NMY29tLVJvb3RDQS1FQ0MtMzg0\n"
|
||||
+ "LVIxLmNydDAgBggrBgEFBQcwAYYUaHR0cDovL29jc3BzLnNzbC5jb20wEQYDVR0g\n"
|
||||
+ "BAowCDAGBgRVHSAAMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATA7BgNV\n"
|
||||
+ "HR8ENDAyMDCgLqAshipodHRwOi8vY3Jscy5zc2wuY29tL3NzbC5jb20tZWNjLVJv\n"
|
||||
+ "b3RDQS5jcmwwHQYDVR0OBBYEFA10Zgpen+Is7NXCXSUEf3Uyuv99MA4GA1UdDwEB\n"
|
||||
+ "/wQEAwIBhjAKBggqhkjOPQQDAwNpADBmAjEAxYt6Ylk/N8Fch/3fgKYKwI5A011Q\n"
|
||||
+ "MKW0h3F9JW/NX/F7oYtWrxljheH8n2BrkDybAjEAlCxkLE0vQTYcFzrR24oogyw6\n"
|
||||
+ "VkgTm92+jiqJTO5SSA9QUa092S5cTKiHkH2cOM6m\n"
|
||||
+ "-----END CERTIFICATE-----";
|
||||
"""
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDejCCAv+gAwIBAgIQHNcSEt4VENkSgtozEEoQLzAKBggqhkjOPQQDAzB8MQsw
|
||||
CQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0b24xGDAW
|
||||
BgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBSb290IENl
|
||||
cnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzAeFw0xOTAzMDcxOTQyNDJaFw0zNDAz
|
||||
MDMxOTQyNDJaMG8xCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UE
|
||||
BwwHSG91c3RvbjERMA8GA1UECgwIU1NMIENvcnAxKzApBgNVBAMMIlNTTC5jb20g
|
||||
U1NMIEludGVybWVkaWF0ZSBDQSBFQ0MgUjIwdjAQBgcqhkjOPQIBBgUrgQQAIgNi
|
||||
AASEOWn30uEYKDLFu4sCjFQ1VupFaeMtQjqVWyWSA7+KFljnsVaFQ2hgs4cQk1f/
|
||||
RQ2INSwdVCYU0i5qsbom20rigUhDh9dM/r6bEZ75eFE899kSCI14xqThYVLPdLEl
|
||||
+dyjggFRMIIBTTASBgNVHRMBAf8ECDAGAQH/AgEAMB8GA1UdIwQYMBaAFILRhXMw
|
||||
5zUE044CkvvlpNHEIejNMHgGCCsGAQUFBwEBBGwwajBGBggrBgEFBQcwAoY6aHR0
|
||||
cDovL3d3dy5zc2wuY29tL3JlcG9zaXRvcnkvU1NMY29tLVJvb3RDQS1FQ0MtMzg0
|
||||
LVIxLmNydDAgBggrBgEFBQcwAYYUaHR0cDovL29jc3BzLnNzbC5jb20wEQYDVR0g
|
||||
BAowCDAGBgRVHSAAMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATA7BgNV
|
||||
HR8ENDAyMDCgLqAshipodHRwOi8vY3Jscy5zc2wuY29tL3NzbC5jb20tZWNjLVJv
|
||||
b3RDQS5jcmwwHQYDVR0OBBYEFA10Zgpen+Is7NXCXSUEf3Uyuv99MA4GA1UdDwEB
|
||||
/wQEAwIBhjAKBggqhkjOPQQDAwNpADBmAjEAxYt6Ylk/N8Fch/3fgKYKwI5A011Q
|
||||
MKW0h3F9JW/NX/F7oYtWrxljheH8n2BrkDybAjEAlCxkLE0vQTYcFzrR24oogyw6
|
||||
VkgTm92+jiqJTO5SSA9QUa092S5cTKiHkH2cOM6m
|
||||
-----END CERTIFICATE-----\
|
||||
""";
|
||||
|
||||
private AuthenticatedRegistrarAccessor registrarAccessor =
|
||||
AuthenticatedRegistrarAccessor.createForTesting(
|
||||
|
||||
@@ -42,10 +42,10 @@ class XjcObjectTest {
|
||||
XjcRdeDeposit deposit = unmarshalFullDeposit();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
deposit.marshal(out, UTF_8);
|
||||
String xml = out.toString(UTF_8.toString());
|
||||
String xml = out.toString(UTF_8);
|
||||
Pattern pat = Pattern.compile("^<\\?xml version=\"1\\.0\" encoding=\"UTF[-_]?8\"");
|
||||
assertWithMessage("bad xml declaration: " + xml).that(pat.matcher(xml).find()).isTrue();
|
||||
assertWithMessage("encode/decode didn't work: " + xml).that(xml).contains("jdoe@example.test");
|
||||
assertWithMessage("bad xml declaration: %s", xml).that(pat.matcher(xml).find()).isTrue();
|
||||
assertWithMessage("encode/decode didn't work: %s", xml).that(xml).contains("jdoe@example.test");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,10 +53,10 @@ class XjcObjectTest {
|
||||
XjcRdeDeposit deposit = unmarshalFullDeposit();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
deposit.marshal(out, UTF_16);
|
||||
String xml = out.toString(UTF_16.toString());
|
||||
String xml = out.toString(UTF_16);
|
||||
Pattern pat = Pattern.compile("^<\\?xml version=\"1\\.0\" encoding=\"UTF[-_]?16\"");
|
||||
assertWithMessage(xml).that(pat.matcher(xml).find()).isTrue();
|
||||
assertWithMessage("encode/decode didn't work: " + xml).that(xml).contains("jdoe@example.test");
|
||||
assertWithMessage("encode/decode didn't work: %s", xml).that(xml).contains("jdoe@example.test");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -210,7 +210,7 @@ public class XmlTestUtils {
|
||||
// an empty map, so normalize that here.
|
||||
return new AbstractMap.SimpleEntry<>(elementName, map.isEmpty() ? "" : map);
|
||||
}
|
||||
if (obj instanceof JSONArray) {
|
||||
if (obj instanceof JSONArray jsonArray) {
|
||||
// Another problem resulting from JSONification: If the array contains elements whose names
|
||||
// are the same before URI expansion, but different after URI expansion, because they use
|
||||
// xmlns attribute that define the namespaces differently, we will screw up. Again, hopefully
|
||||
@@ -220,9 +220,9 @@ public class XmlTestUtils {
|
||||
// hands and just assume that the URI expansion of the first element holds for all others.
|
||||
Set<Object> set = new HashSet<>();
|
||||
String mappedKey = null;
|
||||
for (int i = 0; i < ((JSONArray) obj).length(); ++i) {
|
||||
for (int i = 0; i < jsonArray.length(); ++i) {
|
||||
Map.Entry<String, Object> simpleEntry =
|
||||
normalize(null, ((JSONArray) obj).get(i), path, ignoredPaths, nsMap);
|
||||
normalize(null, jsonArray.get(i), path, ignoredPaths, nsMap);
|
||||
if (i == 0) {
|
||||
mappedKey = simpleEntry.getKey();
|
||||
}
|
||||
@@ -233,8 +233,8 @@ public class XmlTestUtils {
|
||||
if (obj instanceof Number) {
|
||||
return new AbstractMap.SimpleEntry<>(null, obj.toString());
|
||||
}
|
||||
if (obj instanceof Boolean) {
|
||||
return new AbstractMap.SimpleEntry<>(null, ((Boolean) obj) ? "1" : "0");
|
||||
if (obj instanceof Boolean b) {
|
||||
return new AbstractMap.SimpleEntry<>(null, b ? "1" : "0");
|
||||
}
|
||||
if (obj instanceof String) {
|
||||
// Turn stringified booleans into integers. Both are acceptable as xml boolean values, but
|
||||
|
||||
@@ -99,14 +99,6 @@ tasks.withType(Test).configureEach {
|
||||
}
|
||||
systemProperty gcp_integration_env_property, targetEnv
|
||||
}
|
||||
|
||||
// This environment variable along with testcontainers 1.15.2 works around
|
||||
// a race condition introduced in 1.15.0. This can be removed once httpclient5
|
||||
// becomes the default transport type in testcontainers, which may happen
|
||||
// in 1.16.x.
|
||||
// See https://github.com/testcontainers/testcontainers-java/issues/3531
|
||||
// for more information.
|
||||
environment('TESTCONTAINERS_TRANSPORT_TYPE', 'httpclient5')
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
@@ -124,9 +116,7 @@ tasks.withType(JavaCompile).configureEach {
|
||||
// Allow unused methods in tests.
|
||||
options.errorprone.disable("UnusedMethod")
|
||||
// Allow unused variables in tests.
|
||||
// TODO(b/498588847): uncomment below when the global suppression
|
||||
// below is removed.
|
||||
// options.errorprone.disable("UnusedVariable")
|
||||
options.errorprone.disable("UnusedVariable")
|
||||
}
|
||||
// Allow using non-constant strings in log.
|
||||
options.errorprone.disable("FloggerLogString")
|
||||
@@ -140,31 +130,8 @@ tasks.withType(JavaCompile).configureEach {
|
||||
options.errorprone.disable("LongDoubleConversion")
|
||||
// Allow import of commonly-used names such as "Type".
|
||||
options.errorprone.disable("BadImport")
|
||||
|
||||
// TODO(b/498588847): Review suppressed checks below
|
||||
// Disable new checks in 2.48.0 that break the build with -Werror
|
||||
options.errorprone.disable("ExpensiveLenientFormatString")
|
||||
options.errorprone.disable("EnumOrdinal")
|
||||
// Triggered by JapaneseLanguageValidator
|
||||
options.errorprone.disable("ClassInitializationDeadlock")
|
||||
// Allow unused variables globally.
|
||||
options.errorprone.disable("UnusedVariable")
|
||||
options.errorprone.disable("AnnotateFormatMethod")
|
||||
options.errorprone.disable("EffectivelyPrivate")
|
||||
options.errorprone.disable("JdkObsolete")
|
||||
options.errorprone.disable("ImpossibleNullComparison")
|
||||
// Allow assignment to injected variables: too many to fix.
|
||||
options.errorprone.disable("UnnecessaryAssignment")
|
||||
options.errorprone.disable("PatternMatchingInstanceof")
|
||||
options.errorprone.disable("IntLiteralCast")
|
||||
options.errorprone.disable("SystemConsoleNull")
|
||||
options.errorprone.disable("FormatStringShouldUsePlaceholders")
|
||||
options.errorprone.disable("BooleanLiteral")
|
||||
options.errorprone.disable("StatementSwitchToExpressionSwitch")
|
||||
options.errorprone.disable("AssignmentExpression")
|
||||
options.errorprone.disable("JavaDurationGetSecondsToToSeconds")
|
||||
options.errorprone.disable("StringConcatToTextBlock")
|
||||
options.errorprone.disable("TruthConstantAsserts")
|
||||
options.errorprone.disable("NullArgumentForNonNullParameter")
|
||||
|
||||
options.errorprone.disableWarningsInGeneratedCode = true
|
||||
options.errorprone.errorproneArgumentProviders.add([
|
||||
|
||||
@@ -152,9 +152,8 @@ public class SslServerInitializer<C extends Channel> extends ChannelInitializer<
|
||||
PublicKey clientPublicKey = clientCertificate.getPublicKey();
|
||||
// Note that for non-RSA keys the length would be -1.
|
||||
int clientCertificateLength = -1;
|
||||
if (clientPublicKey instanceof RSAPublicKey) {
|
||||
clientCertificateLength =
|
||||
((RSAPublicKey) clientPublicKey).getModulus().bitLength();
|
||||
if (clientPublicKey instanceof RSAPublicKey rsaPublicKey) {
|
||||
clientCertificateLength = rsaPublicKey.getModulus().bitLength();
|
||||
}
|
||||
logger.atInfo().log(
|
||||
"""
|
||||
|
||||
@@ -26,7 +26,6 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -302,12 +301,9 @@ public class EppMessage {
|
||||
throw new EppClientException("unknown error converting Document to intermediate string");
|
||||
}
|
||||
String encoding = xml.getXmlEncoding();
|
||||
// this is actually not a problem since we can just use the default
|
||||
if (encoding == null) {
|
||||
encoding = Charset.defaultCharset().name();
|
||||
}
|
||||
return resultString.getBytes(encoding);
|
||||
} catch (TransformerException | UnsupportedEncodingException e) {
|
||||
Charset charset = (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding);
|
||||
return resultString.getBytes(charset);
|
||||
} catch (TransformerException e) {
|
||||
throw new EppClientException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,8 +114,8 @@ public class ProxyProtocolHandler extends ByteToMessageDecoder {
|
||||
|
||||
private static String getSourceIP(ChannelHandlerContext ctx) {
|
||||
SocketAddress remoteAddress = ctx.channel().remoteAddress();
|
||||
return (remoteAddress instanceof InetSocketAddress)
|
||||
? ((InetSocketAddress) remoteAddress).getAddress().getHostAddress()
|
||||
return (remoteAddress instanceof InetSocketAddress inetSocketAddress)
|
||||
? inetSocketAddress.getAddress().getHostAddress()
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
@@ -93,8 +93,8 @@ public class RelayHandler<I> extends SimpleChannelInboundHandler<I> {
|
||||
// to zero and its buffer will be freed. After the buffer is freed, the message cannot be used
|
||||
// anymore, even if in Java's eye the object still exist, its content is gone. We increment a
|
||||
// count here so that the message can be retried, in case the relay is not successful.
|
||||
if (msg instanceof ReferenceCounted) {
|
||||
((ReferenceCounted) msg).retain();
|
||||
if (msg instanceof ReferenceCounted referenceCounted) {
|
||||
referenceCounted.retain();
|
||||
}
|
||||
ChannelFuture unusedFuture =
|
||||
relayChannel
|
||||
|
||||
@@ -150,8 +150,8 @@ public final class TestUtils {
|
||||
private static void assertHttpMessageEquivalent(HttpMessage msg1, HttpMessage msg2) {
|
||||
assertThat(msg1.protocolVersion()).isEqualTo(msg2.protocolVersion());
|
||||
assertThat(msg1.headers()).isEqualTo(msg2.headers());
|
||||
if (msg1 instanceof FullHttpRequest && msg2 instanceof FullHttpRequest) {
|
||||
assertThat(((FullHttpRequest) msg1).content()).isEqualTo(((FullHttpRequest) msg2).content());
|
||||
if (msg1 instanceof FullHttpRequest req1 && msg2 instanceof FullHttpRequest req2) {
|
||||
assertThat(req1.content()).isEqualTo(req2.content());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -302,8 +302,7 @@ class TokenStoreTest {
|
||||
// Verify that a task is scheduled.
|
||||
ArgumentCaptor<Runnable> argument = ArgumentCaptor.forClass(Runnable.class);
|
||||
verify(refreshExecutor)
|
||||
.scheduleWithFixedDelay(
|
||||
argument.capture(), eq((long) 5), eq((long) 5), eq(TimeUnit.SECONDS));
|
||||
.scheduleWithFixedDelay(argument.capture(), eq(5L), eq(5L), eq(TimeUnit.SECONDS));
|
||||
|
||||
// Verify that the scheduled task calls TokenStore.refresh().
|
||||
argument.getValue().run();
|
||||
|
||||
@@ -16,6 +16,8 @@ package google.registry.util;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
|
||||
import com.google.errorprone.annotations.FormatMethod;
|
||||
import com.google.errorprone.annotations.FormatString;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@@ -41,9 +43,10 @@ public class PreconditionsUtils {
|
||||
}
|
||||
|
||||
/** Checks whether the provided reference is null, throws IAE if it is, and returns it if not. */
|
||||
@FormatMethod
|
||||
public static <T> T checkArgumentNotNull(
|
||||
@Nullable T reference,
|
||||
@Nullable String errorMessageTemplate,
|
||||
@Nullable @FormatString String errorMessageTemplate,
|
||||
@Nullable Object... errorMessageArgs) {
|
||||
checkArgument(reference != null, errorMessageTemplate, errorMessageArgs);
|
||||
return reference;
|
||||
@@ -65,9 +68,10 @@ public class PreconditionsUtils {
|
||||
}
|
||||
|
||||
/** Checks if the provided Optional is present, returns its value if so, and throws IAE if not. */
|
||||
@FormatMethod
|
||||
public static <T> T checkArgumentPresent(
|
||||
@Nullable Optional<T> reference,
|
||||
@Nullable String errorMessageTemplate,
|
||||
@Nullable @FormatString String errorMessageTemplate,
|
||||
@Nullable Object... errorMessageArgs) {
|
||||
checkArgumentNotNull(reference, errorMessageTemplate, errorMessageArgs);
|
||||
checkArgument(reference.isPresent(), errorMessageTemplate, errorMessageArgs);
|
||||
|
||||
@@ -81,9 +81,9 @@ public final class SqlTemplate {
|
||||
String key = matcher.group(2);
|
||||
String rightQuote = matcher.group(3);
|
||||
String value = substitutions.get(key);
|
||||
checkArgumentNotNull(value, "%%s% found in template but no substitution specified", key);
|
||||
checkArgumentNotNull(value, "%s found in template but no substitution specified", wholeMatch);
|
||||
checkArgument(leftQuote.equals(rightQuote), "Quote mismatch: %s", wholeMatch);
|
||||
matcher.appendReplacement(result, String.format("%s%s%s", leftQuote, value, rightQuote));
|
||||
matcher.appendReplacement(result, leftQuote + value + rightQuote);
|
||||
found.add(key);
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
|
||||
@@ -82,7 +82,7 @@ class SerializeUtilsTest {
|
||||
|
||||
@Test
|
||||
void testStringifyParse_longValue_maintainsValue() {
|
||||
assertThat(parse(Serializable.class, stringify((long) 12345))).isEqualTo((long) 12345);
|
||||
assertThat(parse(Serializable.class, stringify(12345L))).isEqualTo(12345L);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user