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

@ -16,6 +16,7 @@ package google.registry.export;
import static com.google.common.base.MoreObjects.firstNonNull;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.common.collect.ImmutableMap;
@ -52,7 +53,9 @@ public final class PublishDetailReportAction implements Runnable, JsonAction {
/** Endpoint to which JSON should be sent for this servlet. See {@code web.xml}. */
public static final String PATH = "/_dr/publishDetailReport";
/** Name of parameter indicating the registrar for which this report will be published. */
/**
* Name of parameter indicating the registrar client ID for which this report will be published.
*/
public static final String REGISTRAR_ID_PARAM = "registrar";
/** Name of parameter providing a name for the report file placed in Drive (the base name). */
@ -83,10 +86,13 @@ public final class PublishDetailReportAction implements Runnable, JsonAction {
try {
logger.infofmt("Publishing detail report for parameters: %s", json);
String registrarId = getParam(json, REGISTRAR_ID_PARAM);
Registrar registrar = checkArgumentNotNull(Registrar.loadByClientIdCached(registrarId),
"Registrar %s not found", registrarId);
String driveFolderId = checkArgumentNotNull(registrar.getDriveFolderId(),
"No drive folder associated with registrar " + registrarId);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientId(registrarId), "Registrar %s not found", registrarId);
String driveFolderId =
checkArgumentNotNull(
registrar.getDriveFolderId(),
"No drive folder associated with registrar " + registrarId);
String gcsBucketName = getParam(json, GCS_BUCKET_PARAM);
String gcsObjectName =
getParam(json, GCS_FOLDER_PREFIX_PARAM) + getParam(json, DETAIL_REPORT_NAME_PARAM);

View file

@ -231,7 +231,7 @@ public class DomainFlowUtils {
/** Check if the registrar running the flow has access to the TLD in question. */
public static void checkAllowedAccessToTld(String clientId, String tld)
throws EppException {
if (!Registrar.loadByClientIdCached(clientId).getAllowedTlds().contains(tld)) {
if (!Registrar.loadByClientIdCached(clientId).get().getAllowedTlds().contains(tld)) {
throw new DomainFlowUtils.NotAuthorizedForTldException(tld);
}
}
@ -433,7 +433,7 @@ public class DomainFlowUtils {
static void verifyPremiumNameIsNotBlocked(
String domainName, DateTime priceTime, String clientId) throws EppException {
if (isDomainPremium(domainName, priceTime)) {
if (Registrar.loadByClientIdCached(clientId).getBlockPremiumNames()) {
if (Registrar.loadByClientIdCached(clientId).get().getBlockPremiumNames()) {
throw new PremiumNameBlockedException();
}
}

View file

@ -17,6 +17,7 @@ package google.registry.flows.session;
import static com.google.common.collect.Sets.difference;
import static google.registry.util.CollectionUtils.nullToEmpty;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import google.registry.flows.EppException;
import google.registry.flows.EppException.AuthenticationErrorClosingConnectionException;
@ -116,14 +117,14 @@ public class LoginFlow implements Flow {
}
serviceExtensionUrisBuilder.add(uri);
}
Registrar registrar = Registrar.loadByClientIdCached(login.getClientId());
if (registrar == null) {
Optional<Registrar> registrar = Registrar.loadByClientIdCached(login.getClientId());
if (!registrar.isPresent()) {
throw new BadRegistrarClientIdException(login.getClientId());
}
// AuthenticationErrorExceptions will propagate up through here.
try {
credentials.validate(registrar, login.getPassword());
credentials.validate(registrar.get(), login.getPassword());
} catch (AuthenticationErrorException e) {
sessionMetadata.incrementFailedLoginAttempts();
if (sessionMetadata.getFailedLoginAttempts() > MAX_FAILED_LOGIN_ATTEMPTS_PER_CONNECTION) {
@ -132,7 +133,7 @@ public class LoginFlow implements Flow {
throw e;
}
}
if (registrar.getState().equals(Registrar.State.PENDING)) {
if (registrar.get().getState().equals(Registrar.State.PENDING)) {
throw new RegistrarAccountNotActiveException();
}
if (login.getNewPassword() != null) { // We don't support in-band password changes.

View file

@ -36,8 +36,10 @@ import static google.registry.util.X509Utils.getCertificateHash;
import static google.registry.util.X509Utils.loadCertificate;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
@ -901,15 +903,16 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable
return CACHE_BY_CLIENT_ID.get().values();
}
/** Load a registrar entity by its client id directly from Datastore. */
@Nullable
public static Registrar loadByClientId(String clientId) {
return ofy().load().type(Registrar.class).parent(getCrossTldKey()).id(clientId).now();
/** Loads and returns a registrar entity by its client id directly from Datastore. */
public static Optional<Registrar> loadByClientId(String clientId) {
checkArgument(!Strings.isNullOrEmpty(clientId), "clientId must be specified");
return Optional.fromNullable(
ofy().load().type(Registrar.class).parent(getCrossTldKey()).id(clientId).now());
}
/** Load a registrar entity by its client id using an in-memory cache. */
@Nullable
public static Registrar loadByClientIdCached(String clientId) {
return CACHE_BY_CLIENT_ID.get().get(clientId);
/** Loads and returns a registrar entity by its client id using an in-memory cache. */
public static Optional<Registrar> loadByClientIdCached(String clientId) {
checkArgument(!Strings.isNullOrEmpty(clientId), "clientId must be specified");
return Optional.fromNullable(CACHE_BY_CLIENT_ID.get().get(clientId));
}
}

View file

@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -163,10 +164,10 @@ public class RdeImportUtils {
// validate that all registrars exist
while (parser.nextRegistrar()) {
XjcRdeRegistrar registrar = parser.getRegistrar();
if (Registrar.loadByClientIdCached(registrar.getId()) == null) {
throw new IllegalArgumentException(
String.format("Registrar '%s' not found in the registry", registrar.getId()));
}
checkArgumentPresent(
Registrar.loadByClientIdCached(registrar.getId()),
"Registrar '%s' not found in the registry",
registrar.getId());
}
} catch (XMLStreamException | JAXBException e) {
throw new IllegalArgumentException(

View file

@ -16,6 +16,7 @@ package google.registry.tmch;
import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.model.ofy.ObjectifyService.ofy;
import com.google.appengine.api.taskqueue.LeaseOptions;
@ -26,6 +27,7 @@ import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.appengine.api.taskqueue.TransientFailureException;
import com.google.apphosting.api.DeadlineExceededException;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Uninterruptibles;
@ -150,11 +152,10 @@ public class LordnTask {
/** Retrieves the IANA identifier for a registrar based on the client id. */
private static String getIanaIdentifier(String clientId) {
Registrar registrar = checkNotNull(
Registrar.loadByClientIdCached(clientId),
"No registrar found for client id: %s", clientId);
Optional<Registrar> registrar = Registrar.loadByClientIdCached(clientId);
checkState(registrar.isPresent(), "No registrar found for client id: %s", clientId);
// Return the string "null" for null identifiers, since some Registrar.Types such as OTE will
// have null iana ids.
return String.valueOf(registrar.getIanaIdentifier());
return String.valueOf(registrar.get().getIanaIdentifier());
}
}

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

View file

@ -16,6 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.net.HttpHeaders.LOCATION;
import static com.google.common.net.HttpHeaders.X_FRAME_OPTIONS;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY;
import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
@ -118,9 +119,12 @@ public final class ConsoleUiAction implements Runnable {
.render());
return;
}
Registrar registrar = Registrar.loadByClientIdCached(sessionUtils.getRegistrarClientId(req));
String clientId = sessionUtils.getRegistrarClientId(req);
Registrar registrar =
checkArgumentPresent(
Registrar.loadByClientIdCached(clientId), "Registrar %s does not exist", clientId);
data.put("xsrfToken", xsrfTokenManager.generateToken(user.getEmail()));
data.put("clientId", registrar.getClientId());
data.put("clientId", clientId);
data.put("showPaymentLink", registrar.getBillingMethod() == Registrar.BillingMethod.BRAINTREE);
String payload = TOFU_SUPPLIER.get()

View file

@ -17,6 +17,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.google.appengine.api.users.User;
import com.google.common.base.Optional;
@ -60,7 +61,9 @@ public class SessionUtils {
if (!checkRegistrarConsoleLogin(request, authResult.userAuthInfo().get().user())) {
throw new ForbiddenException("Not authorized to access Registrar Console");
}
return Registrar.loadByClientIdCached(getRegistrarClientId(request));
String clientId = getRegistrarClientId(request);
return checkArgumentPresent(
Registrar.loadByClientIdCached(clientId), "Registrar %s not found", clientId);
}
/**
@ -129,8 +132,7 @@ public class SessionUtils {
return Optional.absent();
}
String registrarClientId = contact.getParent().getName();
Optional<Registrar> result =
Optional.fromNullable(Registrar.loadByClientIdCached(registrarClientId));
Optional<Registrar> result = Registrar.loadByClientIdCached(registrarClientId);
if (!result.isPresent()) {
logger.severefmt(
"A contact record exists for non-existent registrar: %s.", Key.create(contact));
@ -140,12 +142,12 @@ public class SessionUtils {
/** @see #hasAccessToRegistrar(Registrar, String) */
private static boolean hasAccessToRegistrar(String clientId, final String gaeUserId) {
Registrar registrar = Registrar.loadByClientIdCached(clientId);
if (registrar == null) {
Optional<Registrar> registrar = Registrar.loadByClientIdCached(clientId);
if (!registrar.isPresent()) {
logger.warningfmt("Registrar '%s' disappeared from Datastore!", clientId);
return false;
}
return hasAccessToRegistrar(registrar, gaeUserId);
return hasAccessToRegistrar(registrar.get(), gaeUserId);
}
/** Returns {@code true} if {@code gaeUserId} is listed in contacts. */

View file

@ -16,6 +16,7 @@ package google.registry.util;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Optional;
import javax.annotation.Nullable;
/** Utility methods related to preconditions checking. */
@ -45,4 +46,28 @@ public class PreconditionsUtils {
checkArgument(reference != null, errorMessageTemplate, errorMessageArgs);
return reference;
}
/** Checks if the provided Optional is present, returns its value if so, and throws IAE if not. */
public static <T> T checkArgumentPresent(Optional<T> reference) {
checkArgumentNotNull(reference);
checkArgument(reference.isPresent());
return reference.get();
}
/** Checks if the provided Optional is present, returns its value if so, and throws IAE if not. */
public static <T> T checkArgumentPresent(Optional<T> reference, @Nullable Object errorMessage) {
checkArgumentNotNull(reference, errorMessage);
checkArgument(reference.isPresent(), errorMessage);
return reference.get();
}
/** Checks if the provided Optional is present, returns its value if so, and throws IAE if not. */
public static <T> T checkArgumentPresent(
Optional<T> reference,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
checkArgumentNotNull(reference, errorMessageTemplate, errorMessageArgs);
checkArgument(reference.isPresent(), errorMessageTemplate, errorMessageArgs);
return reference.get();
}
}

View file

@ -15,6 +15,7 @@
package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.tryFind;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.CollectionUtils.isNullOrEmpty;
@ -67,11 +68,13 @@ final class DomainWhoisResponse extends WhoisResponseImpl {
@Override
public WhoisResponseResults getResponse(final boolean preferUnicode, String disclaimer) {
Registrar registrar =
checkNotNull(
Registrar.loadByClientId(domain.getCurrentSponsorClientId()),
"Could not load registrar %s",
domain.getCurrentSponsorClientId());
Optional<Registrar> registrarOptional =
Registrar.loadByClientIdCached(domain.getCurrentSponsorClientId());
checkState(
registrarOptional.isPresent(),
"Could not load registrar %s",
domain.getCurrentSponsorClientId());
Registrar registrar = registrarOptional.get();
Optional<RegistrarContact> abuseContact =
Iterables.tryFind(
registrar.getContacts(),

View file

@ -15,9 +15,11 @@
package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.model.ofy.ObjectifyService.ofy;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.net.InetAddresses;
import google.registry.model.host.HostResource;
@ -53,8 +55,8 @@ final class NameserverWhoisResponse extends WhoisResponseImpl {
.cloneProjectedAtTime(getTimestamp())
.getCurrentSponsorClientId()
: host.getPersistedCurrentSponsorClientId();
Registrar registrar =
checkNotNull(Registrar.loadByClientId(clientId), "Could not load registrar %s", clientId);
Optional<Registrar> registrar = Registrar.loadByClientIdCached(clientId);
checkState(registrar.isPresent(), "Could not load registrar %s", clientId);
emitter
.emitField(
"Server Name", maybeFormatHostname(host.getFullyQualifiedHostName(), preferUnicode))
@ -67,9 +69,9 @@ final class NameserverWhoisResponse extends WhoisResponseImpl {
return InetAddresses.toAddrString(addr);
}
})
.emitField("Registrar", registrar.getRegistrarName())
.emitField("Registrar WHOIS Server", registrar.getWhoisServer())
.emitField("Registrar URL", registrar.getReferralUrl());
.emitField("Registrar", registrar.get().getRegistrarName())
.emitField("Registrar WHOIS Server", registrar.get().getWhoisServer())
.emitField("Registrar URL", registrar.get().getReferralUrl());
if (i < hosts.size() - 1) {
emitter.emitNewline();
}