Make Registrar load methods return Optionals instead of Nullables

This makes the code more understandable from callsites, and also forces
users of this function to deal with the situation where the registrar
with a given client ID might not be present (it was previously silently
NPEing from some of the callsites).

This also adds a test helper method loadRegistrar(clientId) that retains
the old functionality for terseness in tests. It also fixes some instances
of using the load method with the wrong cachedness -- some uses in high-
traffic situations (WHOIS) that should have caching, but also low-traffic
reporting that don't benefit from caching so might as well always be
current.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=162990468
This commit is contained in:
mcilwain 2017-07-24 14:43:20 -07:00 committed by Ben McIlwain
parent 84fdeebc2f
commit d536cef20f
81 changed files with 707 additions and 602 deletions

View file

@ -17,8 +17,8 @@ package google.registry.tools;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.model.registry.Registries.assertTldExists;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static org.joda.time.DateTimeZone.UTC;
import com.beust.jcommander.Parameter;
@ -157,13 +157,17 @@ final class CreateAuctionCreditsCommand extends MutatingCommand {
List<String> fields = splitCsvLine(line);
checkArgument(CsvHeader.getHeaders().size() == fields.size(), "Wrong number of fields");
try {
String registrarId = fields.get(CsvHeader.AFFILIATE.ordinal());
Registrar registrar = checkNotNull(
Registrar.loadByClientId(registrarId), "Registrar %s not found", registrarId);
String clientId = fields.get(CsvHeader.AFFILIATE.ordinal());
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
CurrencyUnit tldCurrency = Registry.get(tld).getCurrency();
CurrencyUnit currency = CurrencyUnit.of((fields.get(CsvHeader.CURRENCY_CODE.ordinal())));
checkArgument(tldCurrency.equals(currency),
"Credit in wrong currency (%s should be %s)", currency, tldCurrency);
checkArgument(
tldCurrency.equals(currency),
"Credit in wrong currency (%s should be %s)",
currency,
tldCurrency);
// We use BigDecimal and BigMoney to preserve fractional currency units when computing the
// total amount of each credit (since auction credits are percentages of winning bids).
BigDecimal creditAmount = new BigDecimal(fields.get(CsvHeader.COMMISSIONS.ordinal()));

View file

@ -16,6 +16,7 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -34,7 +35,7 @@ final class CreateCreditBalanceCommand extends MutatingCommand {
names = "--registrar",
description = "Client ID of the registrar owning the credit to create a new balance for",
required = true)
private String registrarId;
private String clientId;
@Parameter(
names = "--credit_id",
@ -56,14 +57,15 @@ final class CreateCreditBalanceCommand extends MutatingCommand {
@Override
public void init() throws Exception {
Registrar registrar = checkNotNull(
Registrar.loadByClientId(registrarId), "Registrar %s not found", registrarId);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
RegistrarCredit credit = ofy().load()
.type(RegistrarCredit.class)
.parent(registrar)
.id(creditId)
.now();
checkNotNull(credit, "Registrar credit for %s with ID %s not found", registrarId, creditId);
checkNotNull(credit, "Registrar credit for %s with ID %s not found", clientId, creditId);
RegistrarCreditBalance newBalance = new RegistrarCreditBalance.Builder()
.setParent(credit)
.setEffectiveTime(effectiveTime)

View file

@ -14,7 +14,7 @@
package google.registry.tools;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static org.joda.time.DateTimeZone.UTC;
import com.beust.jcommander.Parameter;
@ -35,7 +35,7 @@ final class CreateCreditCommand extends MutatingCommand {
names = "--registrar",
description = "Client ID of the registrar who will be awarded this credit",
required = true)
private String registrarId;
private String clientId;
@Parameter(
names = "--type",
@ -70,8 +70,9 @@ final class CreateCreditCommand extends MutatingCommand {
@Override
protected void init() throws Exception {
DateTime now = DateTime.now(UTC);
Registrar registrar = checkNotNull(
Registrar.loadByClientId(registrarId), "Registrar %s not found", registrarId);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
RegistrarCredit credit = new RegistrarCredit.Builder()
.setParent(registrar)
.setType(type)

View file

@ -79,13 +79,18 @@ final class CreateRegistrarCommand extends CreateOrUpdateRegistrarCommand
"Client identifier (%s) can only contain lowercase letters, numbers, and hyphens",
clientId);
}
checkState(Registrar.loadByClientId(clientId) == null, "Registrar %s already exists", clientId);
checkState(
!Registrar.loadByClientId(clientId).isPresent(), "Registrar %s already exists", clientId);
List<Registrar> collisions =
newArrayList(filter(Registrar.loadAll(), new Predicate<Registrar>() {
@Override
public boolean apply(Registrar registrar) {
return normalizeClientId(registrar.getClientId()).equals(clientId);
}}));
newArrayList(
filter(
Registrar.loadAll(),
new Predicate<Registrar>() {
@Override
public boolean apply(Registrar registrar) {
return normalizeClientId(registrar.getClientId()).equals(clientId);
}
}));
if (!collisions.isEmpty()) {
throw new IllegalArgumentException(String.format(
"The registrar client identifier %s normalizes identically to existing registrar %s",

View file

@ -15,7 +15,7 @@
package google.registry.tools;
import static com.google.common.collect.Iterables.transform;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -53,8 +53,9 @@ public class CreateRegistrarGroupsCommand extends ConfirmingCommand
@Override
protected void init() throws IOException {
for (String clientId : clientIds) {
Registrar registrar = Registrar.loadByClientId(clientId);
checkArgumentNotNull(registrar, "Could not load registrar with id " + clientId);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Could not load registrar with id %s", clientId);
registrars.add(registrar);
}
}

View file

@ -16,6 +16,7 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -31,7 +32,7 @@ final class DeleteCreditCommand extends MutatingCommand {
names = "--registrar",
description = "Client ID of the registrar owning the credit to delete",
required = true)
private String registrarId;
private String clientId;
@Parameter(
names = "--credit_id",
@ -42,13 +43,14 @@ final class DeleteCreditCommand extends MutatingCommand {
@Override
protected void init() throws Exception {
Registrar registrar =
checkNotNull(Registrar.loadByClientId(registrarId), "Registrar %s not found", registrarId);
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
RegistrarCredit credit = ofy().load()
.type(RegistrarCredit.class)
.parent(registrar)
.id(creditId)
.now();
checkNotNull(credit, "Registrar credit for %s with ID %s not found", registrarId, creditId);
checkNotNull(credit, "Registrar credit for %s with ID %s not found", clientId, creditId);
stageEntityChange(credit, null);
for (RegistrarCreditBalance balance :

View file

@ -22,7 +22,7 @@ import static com.google.common.collect.Maps.filterValues;
import static com.google.common.io.Resources.getResource;
import static google.registry.model.registry.Registries.findTldForNameOrThrow;
import static google.registry.tools.CommandUtilities.addHeader;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static google.registry.xml.XmlTransformer.prettyPrint;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -100,8 +100,8 @@ abstract class EppToolCommand extends ConfirmingCommand implements ServerSideCom
}
protected void addXmlCommand(String clientId, String xml) {
checkArgumentNotNull(Registrar.loadByClientId(clientId),
"Registrar with client ID %s not found", clientId);
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar with client ID %s not found", clientId);
commands.add(new XmlEppParameters(clientId, xml));
}

View file

@ -132,9 +132,9 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
// Output records for the registrars of any applications we emitted above.
for (String clientId : registrars) {
Registrar registrar =
checkNotNull(Registrar.loadByClientId(clientId), "Registrar %s does not exist", clientId);
result.add(emitRegistrar(registrar));
Optional<Registrar> registrar = Registrar.loadByClientId(clientId);
checkState(registrar.isPresent(), "Registrar %s does not exist", clientId);
result.add(emitRegistrar(registrar.get()));
}
Files.write(output, result, UTF_8);

View file

@ -14,7 +14,7 @@
package google.registry.tools;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -34,9 +34,9 @@ final class GetRegistrarCommand implements RemoteApiCommand {
@Override
public void run() {
for (String clientId : mainParameters) {
Registrar registrar = Registrar.loadByClientId(clientId);
checkState(registrar != null, "Registrar does not exist");
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar with id %s does not exist", clientId);
System.out.println(registrar);
}
}

View file

@ -92,11 +92,11 @@ class LoadTestCommand extends ConfirmingCommand implements ServerSideCommand {
// Check validity of TLD and Client Id.
if (!Registries.getTlds().contains(tld)) {
System.err.println("No such TLD: " + tld);
System.err.printf("No such TLD: %s\n", tld);
return false;
}
if (Registrar.loadByClientId(clientId) == null) {
System.err.println("No such client: " + clientId);
if (!Registrar.loadByClientId(clientId).isPresent()) {
System.err.printf("No such client: %s\n", clientId);
return false;
}

View file

@ -14,7 +14,7 @@
package google.registry.tools;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -34,7 +34,7 @@ public class PublishDetailReportCommand extends ConfirmingCommand
names = "--registrar_id",
description = "Client identifier of the registrar to publish the report for",
required = true)
private String registrarId;
private String clientId;
@Parameter(
names = "--report_name",
@ -73,8 +73,9 @@ public class PublishDetailReportCommand extends ConfirmingCommand
// TODO(b/18611424): Fix PublishDetailReportAction to take fewer error-prone parameters.
gcsFolderPrefix =
(gcsFolder.isEmpty() || gcsFolder.endsWith("/")) ? gcsFolder : gcsFolder + "/";
Registrar registrar = checkNotNull(
Registrar.loadByClientId(registrarId), "Registrar with ID %s not found", registrarId);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar with ID %s not found", clientId);
driveFolderUrl = String.format(DRIVE_FOLDER_URL_TEMPLATE, registrar.getDriveFolderId());
}
@ -82,7 +83,7 @@ public class PublishDetailReportCommand extends ConfirmingCommand
protected String prompt() {
String gcsFile = String.format("gs://%s/%s%s", gcsBucket, gcsFolderPrefix, reportName);
return "Publish detail report:\n"
+ " - Registrar: " + registrarId + "\n"
+ " - Registrar: " + clientId + "\n"
+ " - Drive folder: " + driveFolderUrl + "\n"
+ " - GCS file: " + gcsFile;
}
@ -90,7 +91,7 @@ public class PublishDetailReportCommand extends ConfirmingCommand
@Override
protected String execute() throws Exception {
final ImmutableMap<String, String> params = ImmutableMap.of(
PublishDetailReportAction.REGISTRAR_ID_PARAM, registrarId,
PublishDetailReportAction.REGISTRAR_ID_PARAM, clientId,
PublishDetailReportAction.DETAIL_REPORT_NAME_PARAM, reportName,
PublishDetailReportAction.GCS_FOLDER_PREFIX_PARAM, gcsFolderPrefix,
PublishDetailReportAction.GCS_BUCKET_PARAM, gcsBucket);

View file

@ -20,6 +20,7 @@ import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Iterables.transform;
import static google.registry.util.CollectionUtils.nullToEmpty;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.beust.jcommander.Parameter;
@ -151,7 +152,8 @@ final class RegistrarContactCommand extends MutatingCommand {
"Must specify exactly one client identifier: %s", ImmutableList.copyOf(mainParameters));
String clientId = mainParameters.get(0);
Registrar registrar =
checkNotNull(Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
// If the contact_type parameter is not specified, we should not make any changes.
if (contactTypeNames == null) {
contactTypes = null;

View file

@ -20,6 +20,7 @@ import static google.registry.model.EppResourceUtils.loadDomainApplication;
import static google.registry.model.domain.launch.ApplicationStatus.ALLOCATED;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -66,7 +67,7 @@ final class UpdateApplicationStatusCommand extends MutatingCommand {
@Override
protected void init() throws Exception {
checkArgumentNotNull(
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar with client ID %s not found", clientId);
for (final String applicationId : ids) {
ofy().transact(new VoidWork() {

View file

@ -14,7 +14,7 @@
package google.registry.tools;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameters;
import google.registry.model.registrar.Registrar;
@ -25,7 +25,7 @@ final class UpdateRegistrarCommand extends CreateOrUpdateRegistrarCommand {
@Override
Registrar getOldRegistrar(String clientId) {
return checkNotNull(
return checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
}
}

View file

@ -17,6 +17,7 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static google.registry.util.X509Utils.getCertificateHash;
import static google.registry.util.X509Utils.loadCertificate;
import static java.nio.charset.StandardCharsets.US_ASCII;
@ -75,7 +76,9 @@ final class ValidateLoginCredentialsCommand implements RemoteApiCommand {
clientCertificateHash = getCertificateHash(
loadCertificate(new String(Files.readAllBytes(clientCertificatePath), US_ASCII)));
}
Registrar registrar = Registrar.loadByClientId(clientId);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
new TlsCredentials(clientCertificateHash, Optional.of(clientIpAddress), null)
.validate(registrar, password);
checkState(!registrar.getState().equals(Registrar.State.PENDING), "Account pending");

View file

@ -16,8 +16,8 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Predicates.notNull;
import static com.google.common.base.Verify.verifyNotNull;
import static google.registry.model.registrar.Registrar.loadByClientId;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -79,7 +79,8 @@ final class VerifyOteCommand implements ServerSideCommand {
// OT&E registrars are created with clientIDs of registrarName-[1-4], but this command is
// passed registrarName. So check the existence of the first persisted registrar to see if
// the input is valid.
verifyNotNull(loadByClientId(clientId + "-1"), "Registrar %s does not exist.", clientId);
checkArgumentPresent(
loadByClientId(clientId + "-1"), "Registrar %s does not exist.", clientId);
}
Collection<String> registrars =
mainParameters.isEmpty() ? getAllRegistrarNames() : mainParameters;

View file

@ -121,12 +121,12 @@ public class CreateGroupsAction implements Runnable {
if (!clientId.isPresent()) {
respondToBadRequest("Error creating Google Groups, missing parameter: clientId");
}
final Registrar registrar = Registrar.loadByClientId(clientId.get());
if (registrar == null) {
Optional<Registrar> registrar = Registrar.loadByClientId(clientId.get());
if (!registrar.isPresent()) {
respondToBadRequest(String.format(
"Error creating Google Groups; could not find registrar with id %s", clientId.get()));
}
return registrar;
return registrar.get();
}
private void respondToBadRequest(String message) {