mirror of
https://github.com/google/nomulus
synced 2026-07-15 04:22:24 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e03ae453c | |||
| 7a62aa0602 | |||
| 6a1e86ff33 | |||
| 5bf618e671 | |||
| b4676a9836 | |||
| ef9f3aeada |
@@ -345,7 +345,7 @@ public class DeleteContactsAndHostsAction implements Runnable {
|
||||
String resourceClientId = resource.getPersistedCurrentSponsorClientId();
|
||||
if (resource instanceof HostResource && ((HostResource) resource).isSubordinate()) {
|
||||
resourceClientId =
|
||||
tm().load(((HostResource) resource).getSuperordinateDomain())
|
||||
tm().loadByKey(((HostResource) resource).getSuperordinateDomain())
|
||||
.cloneProjectedAtTime(now)
|
||||
.getCurrentSponsorClientId();
|
||||
}
|
||||
@@ -465,7 +465,7 @@ public class DeleteContactsAndHostsAction implements Runnable {
|
||||
if (host.isSubordinate()) {
|
||||
dnsQueue.addHostRefreshTask(host.getHostName());
|
||||
tm().put(
|
||||
tm().load(host.getSuperordinateDomain())
|
||||
tm().loadByKey(host.getSuperordinateDomain())
|
||||
.asBuilder()
|
||||
.removeSubordinateHost(host.getHostName())
|
||||
.build());
|
||||
|
||||
@@ -30,6 +30,7 @@ import google.registry.keyring.kms.KmsModule;
|
||||
import google.registry.persistence.PersistenceModule;
|
||||
import google.registry.persistence.PersistenceModule.JdbcJpaTm;
|
||||
import google.registry.persistence.PersistenceModule.SocketFactoryJpaTm;
|
||||
import google.registry.persistence.PersistenceModule.TransactionIsolationLevel;
|
||||
import google.registry.persistence.transaction.JpaTransactionManager;
|
||||
import google.registry.privileges.secretmanager.SecretManagerModule;
|
||||
import google.registry.util.UtilsModule;
|
||||
@@ -57,6 +58,7 @@ public class BeamJpaModule {
|
||||
|
||||
@Nullable private final String sqlAccessInfoFile;
|
||||
@Nullable private final String cloudKmsProjectId;
|
||||
@Nullable private final TransactionIsolationLevel isolationOverride;
|
||||
|
||||
/**
|
||||
* Constructs a new instance of {@link BeamJpaModule}.
|
||||
@@ -73,10 +75,20 @@ public class BeamJpaModule {
|
||||
* real encrypted file on GCS as returned by {@link
|
||||
* BackupPaths#getCloudSQLCredentialFilePatterns} or an unencrypted file on local filesystem
|
||||
* with credentials to a test database.
|
||||
* @param cloudKmsProjectId the GCP project where the credential decryption key can be found
|
||||
* @param isolationOverride the desired Transaction Isolation level for all JDBC connections
|
||||
*/
|
||||
public BeamJpaModule(@Nullable String sqlAccessInfoFile, @Nullable String cloudKmsProjectId) {
|
||||
public BeamJpaModule(
|
||||
@Nullable String sqlAccessInfoFile,
|
||||
@Nullable String cloudKmsProjectId,
|
||||
@Nullable TransactionIsolationLevel isolationOverride) {
|
||||
this.sqlAccessInfoFile = sqlAccessInfoFile;
|
||||
this.cloudKmsProjectId = cloudKmsProjectId;
|
||||
this.isolationOverride = isolationOverride;
|
||||
}
|
||||
|
||||
public BeamJpaModule(@Nullable String sqlAccessInfoFile, @Nullable String cloudKmsProjectId) {
|
||||
this(sqlAccessInfoFile, cloudKmsProjectId, null);
|
||||
}
|
||||
|
||||
/** Returns true if the credential file is on GCS (and therefore expected to be encrypted). */
|
||||
@@ -154,6 +166,13 @@ public class BeamJpaModule {
|
||||
return "nomulus-tool-keyring";
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Config("beamIsolationOverride")
|
||||
@Nullable
|
||||
TransactionIsolationLevel providesIsolationOverride() {
|
||||
return isolationOverride;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Config("beamHibernateHikariMaximumPoolSize")
|
||||
static int getBeamHibernateHikariMaximumPoolSize() {
|
||||
|
||||
@@ -43,7 +43,6 @@ import google.registry.backup.CommitLogImports;
|
||||
import google.registry.backup.VersionedEntity;
|
||||
import google.registry.model.domain.DomainBase;
|
||||
import google.registry.model.ofy.ObjectifyService;
|
||||
import google.registry.model.ofy.Ofy;
|
||||
import google.registry.persistence.transaction.JpaTransactionManager;
|
||||
import google.registry.tools.LevelDbLogReader;
|
||||
import google.registry.util.SystemSleeper;
|
||||
@@ -432,7 +431,6 @@ public final class Transforms {
|
||||
private final SerializableSupplier<JpaTransactionManager> jpaSupplier;
|
||||
private final SerializableFunction<T, Object> jpaConverter;
|
||||
|
||||
private transient Ofy ofy;
|
||||
private transient SystemSleeper sleeper;
|
||||
|
||||
SqlBatchWriter(
|
||||
@@ -448,7 +446,6 @@ public final class Transforms {
|
||||
|
||||
try (AppEngineEnvironment env = new AppEngineEnvironment()) {
|
||||
ObjectifyService.initOfy();
|
||||
ofy = ObjectifyService.ofy();
|
||||
}
|
||||
|
||||
synchronized (SqlBatchWriter.class) {
|
||||
|
||||
@@ -139,7 +139,7 @@ public final class ResourceFlowUtils {
|
||||
Class<R> clazz, String targetId, DateTime now, String clientId) throws EppException {
|
||||
VKey<R> key = loadAndGetKey(clazz, targetId, now);
|
||||
if (key != null) {
|
||||
R resource = tm().load(key);
|
||||
R resource = tm().loadByKey(key);
|
||||
// These are similar exceptions, but we can track them internally as log-based metrics.
|
||||
if (Objects.equals(clientId, resource.getPersistedCurrentSponsorClientId())) {
|
||||
throw new ResourceAlreadyExistsForThisClientException(targetId);
|
||||
|
||||
@@ -15,9 +15,7 @@
|
||||
package google.registry.flows;
|
||||
|
||||
import static com.google.common.base.MoreObjects.toStringHelper;
|
||||
import static com.google.common.base.Strings.isNullOrEmpty;
|
||||
import static google.registry.request.RequestParameters.extractOptionalHeader;
|
||||
import static google.registry.request.RequestParameters.extractRequiredHeader;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
@@ -56,17 +54,17 @@ public class TlsCredentials implements TransportCredentials {
|
||||
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
|
||||
|
||||
private final boolean requireSslCertificates;
|
||||
private final String clientCertificateHash;
|
||||
private final InetAddress clientInetAddr;
|
||||
private final Optional<String> clientCertificateHash;
|
||||
private final Optional<InetAddress> clientInetAddr;
|
||||
|
||||
@Inject
|
||||
public TlsCredentials(
|
||||
@Config("requireSslCertificates") boolean requireSslCertificates,
|
||||
@Header("X-SSL-Certificate") String clientCertificateHash,
|
||||
@Header("X-SSL-Certificate") Optional<String> clientCertificateHash,
|
||||
@Header("X-Forwarded-For") Optional<String> clientAddress) {
|
||||
this.requireSslCertificates = requireSslCertificates;
|
||||
this.clientCertificateHash = clientCertificateHash;
|
||||
this.clientInetAddr = clientAddress.isPresent() ? parseInetAddress(clientAddress.get()) : null;
|
||||
this.clientInetAddr = clientAddress.map(TlsCredentials::parseInetAddress);
|
||||
}
|
||||
|
||||
static InetAddress parseInetAddress(String asciiAddr) {
|
||||
@@ -97,10 +95,14 @@ public class TlsCredentials implements TransportCredentials {
|
||||
registrar.getClientId());
|
||||
return;
|
||||
}
|
||||
for (CidrAddressBlock cidrAddressBlock : ipAddressAllowList) {
|
||||
if (cidrAddressBlock.contains(clientInetAddr)) {
|
||||
// IP address is in allow list; return early.
|
||||
return;
|
||||
// In the rare unexpected case that the client inet address wasn't passed along at all, then
|
||||
// by default deny access.
|
||||
if (clientInetAddr.isPresent()) {
|
||||
for (CidrAddressBlock cidrAddressBlock : ipAddressAllowList) {
|
||||
if (cidrAddressBlock.contains(clientInetAddr.get())) {
|
||||
// IP address is in allow list; return early.
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.atInfo().log(
|
||||
@@ -118,8 +120,8 @@ public class TlsCredentials implements TransportCredentials {
|
||||
*/
|
||||
@VisibleForTesting
|
||||
void validateCertificate(Registrar registrar) throws AuthenticationErrorException {
|
||||
if (isNullOrEmpty(registrar.getClientCertificateHash())
|
||||
&& isNullOrEmpty(registrar.getFailoverClientCertificateHash())) {
|
||||
if (!registrar.getClientCertificateHash().isPresent()
|
||||
&& !registrar.getFailoverClientCertificateHash().isPresent()) {
|
||||
if (requireSslCertificates) {
|
||||
throw new RegistrarCertificateNotConfiguredException();
|
||||
} else {
|
||||
@@ -128,7 +130,7 @@ public class TlsCredentials implements TransportCredentials {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isNullOrEmpty(clientCertificateHash)) {
|
||||
if (!clientCertificateHash.isPresent()) {
|
||||
logger.atInfo().log("Request did not include X-SSL-Certificate");
|
||||
throw new MissingRegistrarCertificateException();
|
||||
}
|
||||
@@ -154,21 +156,21 @@ public class TlsCredentials implements TransportCredentials {
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringHelper(getClass())
|
||||
.add("clientCertificateHash", clientCertificateHash)
|
||||
.add("clientAddress", clientInetAddr)
|
||||
.add("clientCertificateHash", clientCertificateHash.orElse(null))
|
||||
.add("clientAddress", clientInetAddr.orElse(null))
|
||||
.toString();
|
||||
}
|
||||
|
||||
/** Registrar certificate does not match stored certificate. */
|
||||
public static class BadRegistrarCertificateException extends AuthenticationErrorException {
|
||||
public BadRegistrarCertificateException() {
|
||||
BadRegistrarCertificateException() {
|
||||
super("Registrar certificate does not match stored certificate");
|
||||
}
|
||||
}
|
||||
|
||||
/** Registrar certificate not present. */
|
||||
public static class MissingRegistrarCertificateException extends AuthenticationErrorException {
|
||||
public MissingRegistrarCertificateException() {
|
||||
MissingRegistrarCertificateException() {
|
||||
super("Registrar certificate not present");
|
||||
}
|
||||
}
|
||||
@@ -176,14 +178,14 @@ public class TlsCredentials implements TransportCredentials {
|
||||
/** Registrar certificate is not configured. */
|
||||
public static class RegistrarCertificateNotConfiguredException
|
||||
extends AuthenticationErrorException {
|
||||
public RegistrarCertificateNotConfiguredException() {
|
||||
RegistrarCertificateNotConfiguredException() {
|
||||
super("Registrar certificate is not configured");
|
||||
}
|
||||
}
|
||||
|
||||
/** Registrar IP address is not in stored allow list. */
|
||||
public static class BadRegistrarIpAddressException extends AuthenticationErrorException {
|
||||
public BadRegistrarIpAddressException() {
|
||||
BadRegistrarIpAddressException() {
|
||||
super("Registrar IP address is not in stored allow list");
|
||||
}
|
||||
}
|
||||
@@ -191,10 +193,13 @@ public class TlsCredentials implements TransportCredentials {
|
||||
/** Dagger module for the EPP TLS endpoint. */
|
||||
@Module
|
||||
public static final class EppTlsModule {
|
||||
|
||||
@Provides
|
||||
@Header("X-SSL-Certificate")
|
||||
static String provideClientCertificateHash(HttpServletRequest req) {
|
||||
return extractRequiredHeader(req, "X-SSL-Certificate");
|
||||
static Optional<String> provideClientCertificateHash(HttpServletRequest req) {
|
||||
// Note: This header is actually required, we just want to handle its absence explicitly
|
||||
// by throwing an EPP exception rather than a generic Bad Request exception.
|
||||
return extractOptionalHeader(req, "X-SSL-Certificate");
|
||||
}
|
||||
|
||||
@Provides
|
||||
|
||||
@@ -225,7 +225,7 @@ public final class DomainDeleteFlow implements TransactionalFlow {
|
||||
if (gracePeriod.getOneTimeBillingEvent() != null) {
|
||||
// Take the amount of amount of registration time being refunded off the expiration time.
|
||||
// This can be either add grace periods or renew grace periods.
|
||||
BillingEvent.OneTime oneTime = tm().load(gracePeriod.getOneTimeBillingEvent());
|
||||
BillingEvent.OneTime oneTime = tm().loadByKey(gracePeriod.getOneTimeBillingEvent());
|
||||
newExpirationTime = newExpirationTime.minusYears(oneTime.getPeriodYears());
|
||||
} else if (gracePeriod.getRecurringBillingEvent() != null) {
|
||||
// Take 1 year off the registration if in the autorenew grace period (no need to load the
|
||||
@@ -372,12 +372,12 @@ public final class DomainDeleteFlow implements TransactionalFlow {
|
||||
private Money getGracePeriodCost(GracePeriod gracePeriod, DateTime now) {
|
||||
if (gracePeriod.getType() == GracePeriodStatus.AUTO_RENEW) {
|
||||
DateTime autoRenewTime =
|
||||
tm().load(checkNotNull(gracePeriod.getRecurringBillingEvent()))
|
||||
tm().loadByKey(checkNotNull(gracePeriod.getRecurringBillingEvent()))
|
||||
.getRecurrenceTimeOfYear()
|
||||
.getLastInstanceBeforeOrAt(now);
|
||||
return getDomainRenewCost(targetId, autoRenewTime, 1);
|
||||
}
|
||||
return tm().load(checkNotNull(gracePeriod.getOneTimeBillingEvent())).getCost();
|
||||
return tm().loadByKey(checkNotNull(gracePeriod.getOneTimeBillingEvent())).getCost();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
@@ -517,7 +517,7 @@ public class DomainFlowUtils {
|
||||
*/
|
||||
public static void updateAutorenewRecurrenceEndTime(DomainBase domain, DateTime newEndTime) {
|
||||
Optional<PollMessage.Autorenew> autorenewPollMessage =
|
||||
tm().maybeLoad(domain.getAutorenewPollMessage());
|
||||
tm().loadByKeyIfPresent(domain.getAutorenewPollMessage());
|
||||
|
||||
// Construct an updated autorenew poll message. If the autorenew poll message no longer exists,
|
||||
// create a new one at the same id. This can happen if a transfer was requested on a domain
|
||||
@@ -542,7 +542,7 @@ public class DomainFlowUtils {
|
||||
ofy().save().entity(updatedAutorenewPollMessage);
|
||||
}
|
||||
|
||||
Recurring recurring = tm().load(domain.getAutorenewBillingEvent());
|
||||
Recurring recurring = tm().loadByKey(domain.getAutorenewBillingEvent());
|
||||
ofy().save().entity(recurring.asBuilder().setRecurrenceEndTime(newEndTime).build());
|
||||
}
|
||||
|
||||
@@ -1022,7 +1022,7 @@ public class DomainFlowUtils {
|
||||
for (DesignatedContact contact : contacts) {
|
||||
builder.add(
|
||||
ForeignKeyedDesignatedContact.create(
|
||||
contact.getType(), tm().load(contact.getContactKey()).getContactId()));
|
||||
contact.getType(), tm().loadByKey(contact.getContactKey()).getContactId()));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@@ -101,8 +101,8 @@ public final class DomainInfoFlow implements Flow {
|
||||
flowCustomLogic.afterValidation(
|
||||
AfterValidationParameters.newBuilder().setDomain(domain).build());
|
||||
// Prefetch all referenced resources. Calling values() blocks until loading is done.
|
||||
tm().load(domain.getNameservers());
|
||||
tm().load(domain.getReferencedContacts());
|
||||
tm().loadByKeys(domain.getNameservers());
|
||||
tm().loadByKeys(domain.getReferencedContacts());
|
||||
// Registrars can only see a few fields on unauthorized domains.
|
||||
// This is a policy decision that is left up to us by the rfcs.
|
||||
DomainInfoData.Builder infoBuilder =
|
||||
@@ -110,7 +110,7 @@ public final class DomainInfoFlow implements Flow {
|
||||
.setFullyQualifiedDomainName(domain.getDomainName())
|
||||
.setRepoId(domain.getRepoId())
|
||||
.setCurrentSponsorClientId(domain.getCurrentSponsorClientId())
|
||||
.setRegistrant(tm().load(domain.getRegistrant()).getContactId());
|
||||
.setRegistrant(tm().loadByKey(domain.getRegistrant()).getContactId());
|
||||
// If authInfo is non-null, then the caller is authorized to see the full information since we
|
||||
// will have already verified the authInfo is valid.
|
||||
if (clientId.equals(domain.getCurrentSponsorClientId()) || authInfo.isPresent()) {
|
||||
|
||||
@@ -153,7 +153,7 @@ public class AllocationTokenFlowUtils {
|
||||
throw new InvalidAllocationTokenException();
|
||||
}
|
||||
Optional<AllocationToken> maybeTokenEntity =
|
||||
tm().maybeLoad(VKey.create(AllocationToken.class, token));
|
||||
tm().loadByKeyIfPresent(VKey.create(AllocationToken.class, token));
|
||||
if (maybeTokenEntity.isEmpty()) {
|
||||
throw new InvalidAllocationTokenException();
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ public final class HostDeleteFlow implements TransactionalFlow {
|
||||
// the client id, needs to be read off of it.
|
||||
EppResource owningResource =
|
||||
existingHost.isSubordinate()
|
||||
? tm().load(existingHost.getSuperordinateDomain()).cloneProjectedAtTime(now)
|
||||
? tm().loadByKey(existingHost.getSuperordinateDomain()).cloneProjectedAtTime(now)
|
||||
: existingHost;
|
||||
verifyResourceOwnership(clientId, owningResource);
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ public final class HostInfoFlow implements Flow {
|
||||
// there is no superordinate domain, the host's own values for these fields will be correct.
|
||||
if (host.isSubordinate()) {
|
||||
DomainBase superordinateDomain =
|
||||
tm().load(host.getSuperordinateDomain()).cloneProjectedAtTime(now);
|
||||
tm().loadByKey(host.getSuperordinateDomain()).cloneProjectedAtTime(now);
|
||||
hostInfoDataBuilder
|
||||
.setCurrentSponsorClientId(superordinateDomain.getCurrentSponsorClientId())
|
||||
.setLastTransferTime(host.computeLastTransferTime(superordinateDomain));
|
||||
|
||||
@@ -139,7 +139,7 @@ public final class HostUpdateFlow implements TransactionalFlow {
|
||||
String newHostName = firstNonNull(suppliedNewHostName, oldHostName);
|
||||
DomainBase oldSuperordinateDomain =
|
||||
existingHost.isSubordinate()
|
||||
? tm().load(existingHost.getSuperordinateDomain()).cloneProjectedAtTime(now)
|
||||
? tm().loadByKey(existingHost.getSuperordinateDomain()).cloneProjectedAtTime(now)
|
||||
: null;
|
||||
// Note that lookupSuperordinateDomain calls cloneProjectedAtTime on the domain for us.
|
||||
Optional<DomainBase> newSuperordinateDomain =
|
||||
@@ -286,7 +286,7 @@ public final class HostUpdateFlow implements TransactionalFlow {
|
||||
&& Objects.equals(
|
||||
existingHost.getSuperordinateDomain(), newHost.getSuperordinateDomain())) {
|
||||
tm().put(
|
||||
tm().load(existingHost.getSuperordinateDomain())
|
||||
tm().loadByKey(existingHost.getSuperordinateDomain())
|
||||
.asBuilder()
|
||||
.removeSubordinateHost(existingHost.getHostName())
|
||||
.addSubordinateHost(newHost.getHostName())
|
||||
@@ -295,14 +295,14 @@ public final class HostUpdateFlow implements TransactionalFlow {
|
||||
}
|
||||
if (existingHost.isSubordinate()) {
|
||||
tm().put(
|
||||
tm().load(existingHost.getSuperordinateDomain())
|
||||
tm().loadByKey(existingHost.getSuperordinateDomain())
|
||||
.asBuilder()
|
||||
.removeSubordinateHost(existingHost.getHostName())
|
||||
.build());
|
||||
}
|
||||
if (newHost.isSubordinate()) {
|
||||
tm().put(
|
||||
tm().load(newHost.getSuperordinateDomain())
|
||||
tm().loadByKey(newHost.getSuperordinateDomain())
|
||||
.asBuilder()
|
||||
.addSubordinateHost(newHost.getHostName())
|
||||
.build());
|
||||
|
||||
@@ -360,13 +360,13 @@ public abstract class EppResource extends BackupGroupRoot implements Buildable {
|
||||
|
||||
@Override
|
||||
public EppResource load(VKey<? extends EppResource> key) {
|
||||
return tm().doTransactionless(() -> tm().load(key));
|
||||
return tm().doTransactionless(() -> tm().loadByKey(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<VKey<? extends EppResource>, EppResource> loadAll(
|
||||
Iterable<? extends VKey<? extends EppResource>> keys) {
|
||||
return tm().doTransactionless(() -> tm().load(keys));
|
||||
return tm().doTransactionless(() -> tm().loadByKeys(keys));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -406,7 +406,7 @@ public abstract class EppResource extends BackupGroupRoot implements Buildable {
|
||||
public static ImmutableMap<VKey<? extends EppResource>, EppResource> loadCached(
|
||||
Iterable<VKey<? extends EppResource>> keys) {
|
||||
if (!RegistryConfig.isEppResourceCachingEnabled()) {
|
||||
return tm().load(keys);
|
||||
return tm().loadByKeys(keys);
|
||||
}
|
||||
try {
|
||||
return cacheEppResources.getAll(keys);
|
||||
@@ -423,7 +423,7 @@ public abstract class EppResource extends BackupGroupRoot implements Buildable {
|
||||
*/
|
||||
public static <T extends EppResource> T loadCached(VKey<T> key) {
|
||||
if (!RegistryConfig.isEppResourceCachingEnabled()) {
|
||||
return tm().load(key);
|
||||
return tm().loadByKey(key);
|
||||
}
|
||||
try {
|
||||
// Safe to cast because loading a Key<T> returns an entity of type T.
|
||||
|
||||
@@ -144,7 +144,7 @@ public final class EppResourceUtils {
|
||||
T resource =
|
||||
useCache
|
||||
? EppResource.loadCached(fki.getResourceKey())
|
||||
: transactIfJpaTm(() -> tm().maybeLoad(fki.getResourceKey()).orElse(null));
|
||||
: transactIfJpaTm(() -> tm().loadByKeyIfPresent(fki.getResourceKey()).orElse(null));
|
||||
if (resource == null || isAtOrAfter(now, resource.getDeletionTime())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@@ -17,15 +17,11 @@ package google.registry.model.domain;
|
||||
import com.googlecode.objectify.annotation.Embed;
|
||||
import com.googlecode.objectify.annotation.Ignore;
|
||||
import google.registry.model.ImmutableObject;
|
||||
import google.registry.model.ModelUtils;
|
||||
import google.registry.model.billing.BillingEvent;
|
||||
import google.registry.model.domain.rgp.GracePeriodStatus;
|
||||
import google.registry.persistence.BillingVKey.BillingEventVKey;
|
||||
import google.registry.persistence.BillingVKey.BillingRecurrenceVKey;
|
||||
import google.registry.persistence.VKey;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.persistence.Access;
|
||||
import javax.persistence.AccessType;
|
||||
import javax.persistence.Column;
|
||||
@@ -125,20 +121,4 @@ public class GracePeriodBase extends ImmutableObject {
|
||||
public VKey<BillingEvent.Recurring> getRecurringBillingEvent() {
|
||||
return billingEventRecurring == null ? null : billingEventRecurring.createVKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* Override {@link ImmutableObject#getSignificantFields()} to exclude "id", which breaks equality
|
||||
* testing in the unit tests.
|
||||
*/
|
||||
@Override
|
||||
protected Map<Field, Object> getSignificantFields() {
|
||||
// Can't use streams or ImmutableMap because we can have null values.
|
||||
Map<Field, Object> result = new LinkedHashMap();
|
||||
for (Map.Entry<Field, Object> entry : ModelUtils.getFieldValues(this).entrySet()) {
|
||||
if (!entry.getKey().getName().equals("id")) {
|
||||
result.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ package google.registry.model.ofy;
|
||||
|
||||
import static com.google.common.collect.ImmutableList.toImmutableList;
|
||||
import static com.google.common.collect.ImmutableMap.toImmutableMap;
|
||||
import static com.google.common.collect.ImmutableSet.toImmutableSet;
|
||||
import static google.registry.model.ofy.ObjectifyService.ofy;
|
||||
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
|
||||
|
||||
@@ -23,6 +24,8 @@ import com.google.common.base.Functions;
|
||||
import com.google.common.collect.ImmutableCollection;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.googlecode.objectify.Key;
|
||||
import com.googlecode.objectify.Result;
|
||||
@@ -177,26 +180,13 @@ public class DatastoreTransactionManager implements TransactionManager {
|
||||
// VKey instead of by ofy Key. But ideally, there should be one set of TransactionManager
|
||||
// interface tests that are applied to both the datastore and SQL implementations.
|
||||
@Override
|
||||
public <T> Optional<T> maybeLoad(VKey<T> key) {
|
||||
public <T> Optional<T> loadByKeyIfPresent(VKey<T> key) {
|
||||
return Optional.ofNullable(loadNullable(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T load(VKey<T> key) {
|
||||
T result = loadNullable(key);
|
||||
if (result == null) {
|
||||
throw new NoSuchElementException(key.toString());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T load(T entity) {
|
||||
return ofy().load().entity(entity).now();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableMap<VKey<? extends T>, T> load(Iterable<? extends VKey<? extends T>> keys) {
|
||||
public <T> ImmutableMap<VKey<? extends T>, T> loadByKeysIfPresent(
|
||||
Iterable<? extends VKey<? extends T>> keys) {
|
||||
// Keep track of the Key -> VKey mapping so we can translate them back.
|
||||
ImmutableMap<Key<T>, VKey<? extends T>> keyMap =
|
||||
StreamSupport.stream(keys.spliterator(), false)
|
||||
@@ -211,13 +201,51 @@ public class DatastoreTransactionManager implements TransactionManager {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadAll(Class<T> clazz) {
|
||||
return ImmutableList.copyOf(getOfy().load().type(clazz));
|
||||
public <T> ImmutableList<T> loadByEntitiesIfPresent(Iterable<T> entities) {
|
||||
return ImmutableList.copyOf(getOfy().load().entities(entities).values());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadAll(Iterable<T> entities) {
|
||||
return ImmutableList.copyOf(getOfy().load().entities(entities).values());
|
||||
public <T> T loadByKey(VKey<T> key) {
|
||||
T result = loadNullable(key);
|
||||
if (result == null) {
|
||||
throw new NoSuchElementException(key.toString());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableMap<VKey<? extends T>, T> loadByKeys(
|
||||
Iterable<? extends VKey<? extends T>> keys) {
|
||||
ImmutableMap<VKey<? extends T>, T> result = loadByKeysIfPresent(keys);
|
||||
ImmutableSet<? extends VKey<? extends T>> missingKeys =
|
||||
Streams.stream(keys).filter(k -> !result.containsKey(k)).collect(toImmutableSet());
|
||||
if (!missingKeys.isEmpty()) {
|
||||
// Ofy ignores nonexistent keys but the method contract specifies to throw if nonexistent
|
||||
throw new NoSuchElementException(
|
||||
String.format("Failed to load nonexistent entities for keys: %s", missingKeys));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T loadByEntity(T entity) {
|
||||
return ofy().load().entity(entity).now();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadByEntities(Iterable<T> entities) {
|
||||
ImmutableList<T> result = loadByEntitiesIfPresent(entities);
|
||||
if (result.size() != Iterables.size(entities)) {
|
||||
throw new NoSuchElementException(
|
||||
String.format("Attempted to load entities, some of which are missing: %s", entities));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadAllOf(Class<T> clazz) {
|
||||
return ImmutableList.copyOf(getOfy().load().type(clazz));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -97,7 +97,7 @@ public final class RdeRevision extends BackupGroupRoot implements NonReplicatedE
|
||||
RdeRevisionId sqlKey = RdeRevisionId.create(tld, date.toLocalDate(), mode);
|
||||
Key<RdeRevision> ofyKey = Key.create(RdeRevision.class, id);
|
||||
Optional<RdeRevision> revisionOptional =
|
||||
tm().maybeLoad(VKey.create(RdeRevision.class, sqlKey, ofyKey));
|
||||
tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, sqlKey, ofyKey));
|
||||
return revisionOptional.map(rdeRevision -> rdeRevision.revision + 1).orElse(0);
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ public final class RdeRevision extends BackupGroupRoot implements NonReplicatedE
|
||||
RdeRevisionId sqlKey = RdeRevisionId.create(tld, date.toLocalDate(), mode);
|
||||
Key<RdeRevision> ofyKey = Key.create(RdeRevision.class, triplet);
|
||||
Optional<RdeRevision> revisionOptional =
|
||||
tm().maybeLoad(VKey.create(RdeRevision.class, sqlKey, ofyKey));
|
||||
tm().loadByKeyIfPresent(VKey.create(RdeRevision.class, sqlKey, ofyKey));
|
||||
if (revision == 0) {
|
||||
revisionOptional.ifPresent(
|
||||
rdeRevision -> {
|
||||
|
||||
@@ -537,20 +537,24 @@ public class Registrar extends ImmutableObject
|
||||
return LIVE_STATES.contains(state) && PUBLICLY_VISIBLE_TYPES.contains(type);
|
||||
}
|
||||
|
||||
public String getClientCertificate() {
|
||||
return clientCertificate;
|
||||
/** Returns the client certificate string if it has been set, or empty otherwise. */
|
||||
public Optional<String> getClientCertificate() {
|
||||
return Optional.ofNullable(clientCertificate);
|
||||
}
|
||||
|
||||
public String getClientCertificateHash() {
|
||||
return clientCertificateHash;
|
||||
/** Returns the client certificate hash if it has been set, or empty otherwise. */
|
||||
public Optional<String> getClientCertificateHash() {
|
||||
return Optional.ofNullable(clientCertificateHash);
|
||||
}
|
||||
|
||||
public String getFailoverClientCertificate() {
|
||||
return failoverClientCertificate;
|
||||
/** Returns the failover client certificate string if it has been set, or empty otherwise. */
|
||||
public Optional<String> getFailoverClientCertificate() {
|
||||
return Optional.ofNullable(failoverClientCertificate);
|
||||
}
|
||||
|
||||
public String getFailoverClientCertificateHash() {
|
||||
return failoverClientCertificateHash;
|
||||
/** Returns the failover client certificate hash if it has been set, or empty otherwise. */
|
||||
public Optional<String> getFailoverClientCertificateHash() {
|
||||
return Optional.ofNullable(failoverClientCertificateHash);
|
||||
}
|
||||
|
||||
public ImmutableList<CidrAddressBlock> getIpAddressAllowList() {
|
||||
@@ -815,7 +819,8 @@ public class Registrar extends ImmutableObject
|
||||
.map(Registry::createVKey)
|
||||
.collect(toImmutableSet());
|
||||
Set<VKey<Registry>> missingTldKeys =
|
||||
Sets.difference(newTldKeys, transactIfJpaTm(() -> tm().load(newTldKeys)).keySet());
|
||||
Sets.difference(
|
||||
newTldKeys, transactIfJpaTm(() -> tm().loadByKeysIfPresent(newTldKeys)).keySet());
|
||||
checkArgument(missingTldKeys.isEmpty(), "Trying to set nonexisting TLDs: %s", missingTldKeys);
|
||||
getInstance().allowedTlds = ImmutableSortedSet.copyOf(allowedTlds);
|
||||
return this;
|
||||
@@ -983,7 +988,7 @@ public class Registrar extends ImmutableObject
|
||||
public static Iterable<Registrar> loadAll() {
|
||||
return tm().isOfy()
|
||||
? ImmutableList.copyOf(ofy().load().type(Registrar.class).ancestor(getCrossTldKey()))
|
||||
: tm().transact(() -> tm().loadAll(Registrar.class));
|
||||
: tm().transact(() -> tm().loadAllOf(Registrar.class));
|
||||
}
|
||||
|
||||
/** Loads all registrar entities using an in-memory cache. */
|
||||
@@ -994,7 +999,7 @@ public class Registrar extends ImmutableObject
|
||||
/** 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 transactIfJpaTm(() -> tm().maybeLoad(createVKey(clientId)));
|
||||
return transactIfJpaTm(() -> tm().loadByKeyIfPresent(createVKey(clientId)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -69,7 +69,7 @@ public final class Registries {
|
||||
.stream()
|
||||
.map(Key::getName)
|
||||
.collect(toImmutableSet())
|
||||
: tm().loadAll(Registry.class).stream()
|
||||
: tm().loadAllOf(Registry.class).stream()
|
||||
.map(Registry::getTldStr)
|
||||
.collect(toImmutableSet());
|
||||
return Registry.getAll(tlds).stream()
|
||||
|
||||
@@ -267,7 +267,7 @@ public class Registry extends ImmutableObject implements Buildable, DatastoreAnd
|
||||
public Optional<Registry> load(final String tld) {
|
||||
// Enter a transaction-less context briefly; we don't want to enroll every TLD in
|
||||
// a transaction that might be wrapping this call.
|
||||
return tm().doTransactionless(() -> tm().maybeLoad(createVKey(tld)));
|
||||
return tm().doTransactionless(() -> tm().loadByKeyIfPresent(createVKey(tld)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -275,7 +275,7 @@ public class Registry extends ImmutableObject implements Buildable, DatastoreAnd
|
||||
ImmutableMap<String, VKey<Registry>> keysMap =
|
||||
toMap(ImmutableSet.copyOf(tlds), Registry::createVKey);
|
||||
Map<VKey<? extends Registry>, Registry> entities =
|
||||
tm().doTransactionless(() -> tm().load(keysMap.values()));
|
||||
tm().doTransactionless(() -> tm().loadByKeys(keysMap.values()));
|
||||
return Maps.transformEntries(
|
||||
keysMap, (k, v) -> Optional.ofNullable(entities.getOrDefault(v, null)));
|
||||
}
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ public class ReservedListDualWriteDao {
|
||||
public static Optional<ReservedList> getLatestRevision(String reservedListName) {
|
||||
Optional<ReservedList> maybeDatastoreList =
|
||||
ofyTm()
|
||||
.maybeLoad(
|
||||
.loadByKeyIfPresent(
|
||||
VKey.createOfy(
|
||||
ReservedList.class,
|
||||
Key.create(getCrossTldKey(), ReservedList.class, reservedListName)));
|
||||
|
||||
@@ -77,7 +77,7 @@ public class ServerSecret extends CrossTldSingleton implements NonReplicatedEnti
|
||||
// transactionally create a new ServerSecret (once per app setup) if necessary.
|
||||
// return the ofy() result during Datastore-primary phase
|
||||
ServerSecret secret =
|
||||
ofyTm().maybeLoad(key).orElseGet(() -> create(UUID.randomUUID()));
|
||||
ofyTm().loadByKeyIfPresent(key).orElseGet(() -> create(UUID.randomUUID()));
|
||||
// During a dual-write period, write it to both Datastore and SQL
|
||||
// even if we didn't have to retrieve it from the DB
|
||||
ofyTm().transact(() -> ofyTm().putWithoutBackup(secret));
|
||||
|
||||
@@ -56,7 +56,7 @@ public final class TmchCrl extends CrossTldSingleton implements NonReplicatedEnt
|
||||
VKey.create(
|
||||
TmchCrl.class, SINGLETON_ID, Key.create(getCrossTldKey(), TmchCrl.class, SINGLETON_ID));
|
||||
// return the ofy() result during Datastore-primary phase
|
||||
return ofyTm().transact(() -> ofyTm().maybeLoad(key));
|
||||
return ofyTm().transact(() -> ofyTm().loadByKeyIfPresent(key));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.flogger.FluentLogger;
|
||||
import dagger.BindsOptionalOf;
|
||||
import dagger.Module;
|
||||
import dagger.Provides;
|
||||
import google.registry.config.RegistryConfig.Config;
|
||||
@@ -42,8 +43,12 @@ import google.registry.privileges.secretmanager.SqlUser.RobotUser;
|
||||
import google.registry.tools.AuthModule.CloudSqlClientCredential;
|
||||
import google.registry.util.Clock;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.sql.Connection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Provider;
|
||||
import javax.inject.Qualifier;
|
||||
import javax.inject.Singleton;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
@@ -52,7 +57,7 @@ import org.hibernate.cfg.Environment;
|
||||
|
||||
/** Dagger module class for the persistence layer. */
|
||||
@Module
|
||||
public class PersistenceModule {
|
||||
public abstract class PersistenceModule {
|
||||
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
|
||||
|
||||
// This name must be the same as the one defined in persistence.xml.
|
||||
@@ -102,25 +107,48 @@ public class PersistenceModule {
|
||||
@Config("cloudSqlJdbcUrl") String jdbcUrl,
|
||||
@Config("cloudSqlInstanceConnectionName") String instanceConnectionName,
|
||||
@DefaultHibernateConfigs ImmutableMap<String, String> defaultConfigs) {
|
||||
return createPartialSqlConfigs(jdbcUrl, instanceConnectionName, defaultConfigs);
|
||||
return createPartialSqlConfigs(
|
||||
jdbcUrl, instanceConnectionName, defaultConfigs, Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Optionally overrides the isolation level in the config file.
|
||||
*
|
||||
* <p>The binding for {@link TransactionIsolationLevel} may be {@link Nullable}. As a result, it
|
||||
* is a compile-time error to inject {@code Optional<TransactionIsolation>} (See {@link
|
||||
* BindsOptionalOf} for more information). User should inject {@code
|
||||
* Optional<Provider<TransactionIsolation>>} instead.
|
||||
*/
|
||||
@BindsOptionalOf
|
||||
@Config("beamIsolationOverride")
|
||||
abstract TransactionIsolationLevel bindBeamIsolationOverride();
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@BeamPipelineCloudSqlConfigs
|
||||
static ImmutableMap<String, String> provideBeamPipelineCloudSqlConfigs(
|
||||
@Config("beamCloudSqlJdbcUrl") String jdbcUrl,
|
||||
@Config("beamCloudSqlInstanceConnectionName") String instanceConnectionName,
|
||||
@DefaultHibernateConfigs ImmutableMap<String, String> defaultConfigs) {
|
||||
return createPartialSqlConfigs(jdbcUrl, instanceConnectionName, defaultConfigs);
|
||||
@DefaultHibernateConfigs ImmutableMap<String, String> defaultConfigs,
|
||||
@Config("beamIsolationOverride")
|
||||
Optional<Provider<TransactionIsolationLevel>> isolationOverride) {
|
||||
return createPartialSqlConfigs(
|
||||
jdbcUrl, instanceConnectionName, defaultConfigs, isolationOverride);
|
||||
}
|
||||
|
||||
private static ImmutableMap<String, String> createPartialSqlConfigs(
|
||||
String jdbcUrl, String instanceConnectionName, ImmutableMap<String, String> defaultConfigs) {
|
||||
@VisibleForTesting
|
||||
static ImmutableMap<String, String> createPartialSqlConfigs(
|
||||
String jdbcUrl,
|
||||
String instanceConnectionName,
|
||||
ImmutableMap<String, String> defaultConfigs,
|
||||
Optional<Provider<TransactionIsolationLevel>> isolationOverride) {
|
||||
HashMap<String, String> overrides = Maps.newHashMap(defaultConfigs);
|
||||
overrides.put(Environment.URL, jdbcUrl);
|
||||
overrides.put(HIKARI_DS_SOCKET_FACTORY, "com.google.cloud.sql.postgres.SocketFactory");
|
||||
overrides.put(HIKARI_DS_CLOUD_SQL_INSTANCE, instanceConnectionName);
|
||||
isolationOverride
|
||||
.map(Provider::get)
|
||||
.ifPresent(override -> overrides.put(Environment.ISOLATION, override.name()));
|
||||
return ImmutableMap.copyOf(overrides);
|
||||
}
|
||||
|
||||
@@ -254,6 +282,37 @@ public class PersistenceModule {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transaction isolation levels supported by Cloud SQL (mysql and postgresql).
|
||||
*
|
||||
* <p>Enum names may be used for property-based configuration, and must match the corresponding
|
||||
* variable names in {@link Connection}.
|
||||
*/
|
||||
public enum TransactionIsolationLevel {
|
||||
TRANSACTION_READ_UNCOMMITTED,
|
||||
TRANSACTION_READ_COMMITTED,
|
||||
TRANSACTION_REPEATABLE_READ,
|
||||
TRANSACTION_SERIALIZABLE;
|
||||
|
||||
private final int value;
|
||||
|
||||
TransactionIsolationLevel() {
|
||||
try {
|
||||
// name() is final in parent class (Enum.java), therefore safe to call in constructor.
|
||||
value = Connection.class.getField(name()).getInt(null);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(
|
||||
String.format(
|
||||
"%s Enum name %s has no matching public field in java.sql.Connection.",
|
||||
getClass().getSimpleName(), name()));
|
||||
}
|
||||
}
|
||||
|
||||
public final int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/** Dagger qualifier for {@link JpaTransactionManager} used for App Engine application. */
|
||||
@Qualifier
|
||||
@Documented
|
||||
|
||||
+53
-29
@@ -40,7 +40,7 @@ import google.registry.util.Clock;
|
||||
import google.registry.util.Retrier;
|
||||
import google.registry.util.SystemSleeper;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
@@ -356,33 +356,15 @@ public class JpaTransactionManagerImpl implements JpaTransactionManager {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> maybeLoad(VKey<T> key) {
|
||||
public <T> Optional<T> loadByKeyIfPresent(VKey<T> key) {
|
||||
checkArgumentNotNull(key, "key must be specified");
|
||||
assertInTransaction();
|
||||
return Optional.ofNullable(getEntityManager().find(key.getKind(), key.getSqlKey()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T load(VKey<T> key) {
|
||||
checkArgumentNotNull(key, "key must be specified");
|
||||
assertInTransaction();
|
||||
T result = getEntityManager().find(key.getKind(), key.getSqlKey());
|
||||
if (result == null) {
|
||||
throw new NoSuchElementException(key.toString());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T load(T entity) {
|
||||
checkArgumentNotNull(entity, "entity must be specified");
|
||||
assertInTransaction();
|
||||
return (T)
|
||||
load(VKey.createSql(entity.getClass(), emf.getPersistenceUnitUtil().getIdentifier(entity)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableMap<VKey<? extends T>, T> load(Iterable<? extends VKey<? extends T>> keys) {
|
||||
public <T> ImmutableMap<VKey<? extends T>, T> loadByKeysIfPresent(
|
||||
Iterable<? extends VKey<? extends T>> keys) {
|
||||
checkArgumentNotNull(keys, "keys must be specified");
|
||||
assertInTransaction();
|
||||
return StreamSupport.stream(keys.spliterator(), false)
|
||||
@@ -393,11 +375,58 @@ public class JpaTransactionManagerImpl implements JpaTransactionManager {
|
||||
new SimpleEntry<VKey<? extends T>, T>(
|
||||
key, getEntityManager().find(key.getKind(), key.getSqlKey())))
|
||||
.filter(entry -> entry.getValue() != null)
|
||||
.collect(toImmutableMap(Entry::getKey, Entry::getValue));
|
||||
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadAll(Class<T> clazz) {
|
||||
public <T> ImmutableList<T> loadByEntitiesIfPresent(Iterable<T> entities) {
|
||||
return Streams.stream(entities)
|
||||
.filter(this::exists)
|
||||
.map(this::loadByEntity)
|
||||
.collect(toImmutableList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T loadByKey(VKey<T> key) {
|
||||
checkArgumentNotNull(key, "key must be specified");
|
||||
assertInTransaction();
|
||||
T result = getEntityManager().find(key.getKind(), key.getSqlKey());
|
||||
if (result == null) {
|
||||
throw new NoSuchElementException(key.toString());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableMap<VKey<? extends T>, T> loadByKeys(
|
||||
Iterable<? extends VKey<? extends T>> keys) {
|
||||
ImmutableMap<VKey<? extends T>, T> existing = loadByKeysIfPresent(keys);
|
||||
ImmutableSet<? extends VKey<? extends T>> missingKeys =
|
||||
Streams.stream(keys).filter(k -> !existing.containsKey(k)).collect(toImmutableSet());
|
||||
if (!missingKeys.isEmpty()) {
|
||||
throw new NoSuchElementException(
|
||||
String.format(
|
||||
"Expected to find the following VKeys but they were missing: %s.", missingKeys));
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T loadByEntity(T entity) {
|
||||
checkArgumentNotNull(entity, "entity must be specified");
|
||||
assertInTransaction();
|
||||
return (T)
|
||||
loadByKey(
|
||||
VKey.createSql(entity.getClass(), emf.getPersistenceUnitUtil().getIdentifier(entity)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadByEntities(Iterable<T> entities) {
|
||||
return Streams.stream(entities).map(this::loadByEntity).collect(toImmutableList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadAllOf(Class<T> clazz) {
|
||||
checkArgumentNotNull(clazz, "clazz must be specified");
|
||||
assertInTransaction();
|
||||
return ImmutableList.copyOf(
|
||||
@@ -408,11 +437,6 @@ public class JpaTransactionManagerImpl implements JpaTransactionManager {
|
||||
.getResultList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ImmutableList<T> loadAll(Iterable<T> entities) {
|
||||
return Streams.stream(entities).map(this::load).collect(toImmutableList());
|
||||
}
|
||||
|
||||
private int internalDelete(VKey<?> key) {
|
||||
checkArgumentNotNull(key, "key must be specified");
|
||||
assertInTransaction();
|
||||
|
||||
+63
-30
@@ -29,17 +29,19 @@ import org.joda.time.DateTime;
|
||||
*/
|
||||
public interface TransactionManager {
|
||||
|
||||
/** Returns {@code true} if the caller is in a transaction.
|
||||
/**
|
||||
* Returns {@code true} if the caller is in a transaction.
|
||||
*
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
*/
|
||||
boolean inTransaction();
|
||||
|
||||
/** Throws {@link IllegalStateException} if the caller is not in a transaction.
|
||||
/**
|
||||
* Throws {@link IllegalStateException} if the caller is not in a transaction.
|
||||
*
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
*/
|
||||
void assertInTransaction();
|
||||
|
||||
@@ -58,10 +60,11 @@ public interface TransactionManager {
|
||||
*/
|
||||
<T> T transactNew(Supplier<T> work);
|
||||
|
||||
/** Pauses the current transaction (if any) and executes the work in a new transaction.
|
||||
/**
|
||||
* Pauses the current transaction (if any) and executes the work in a new transaction.
|
||||
*
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
*/
|
||||
void transactNew(Runnable work);
|
||||
|
||||
@@ -73,10 +76,11 @@ public interface TransactionManager {
|
||||
*/
|
||||
<R> R transactNewReadOnly(Supplier<R> work);
|
||||
|
||||
/** Executes the work in a read-only transaction.
|
||||
/**
|
||||
* Executes the work in a read-only transaction.
|
||||
*
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
* <p>Note that this function is kept for backward compatibility. We will review the use case
|
||||
* later when adding the cloud sql implementation.
|
||||
*/
|
||||
void transactNewReadOnly(Runnable work);
|
||||
|
||||
@@ -182,31 +186,60 @@ public interface TransactionManager {
|
||||
/** Returns whether the entity of given key exists. */
|
||||
<T> boolean exists(VKey<T> key);
|
||||
|
||||
/** Loads the entity by its id, returns empty if the entity doesn't exist. */
|
||||
<T> Optional<T> maybeLoad(VKey<T> key);
|
||||
|
||||
/** Loads the entity by its id, throws NoSuchElementException if it doesn't exist. */
|
||||
<T> T load(VKey<T> key);
|
||||
/** Loads the entity by its key, returns empty if the entity doesn't exist. */
|
||||
<T> Optional<T> loadByKeyIfPresent(VKey<T> key);
|
||||
|
||||
/**
|
||||
* Loads the given entity from the database, throws NoSuchElementException if it doesn't exist.
|
||||
*/
|
||||
<T> T load(T entity);
|
||||
|
||||
/**
|
||||
* Loads the set of entities by their key id.
|
||||
* Loads the set of entities by their keys.
|
||||
*
|
||||
* @throws NoSuchElementException if any of the keys are not found.
|
||||
* <p>Nonexistent keys / entities are absent from the resulting map, but no {@link
|
||||
* NoSuchElementException} will be thrown.
|
||||
*/
|
||||
<T> ImmutableMap<VKey<? extends T>, T> load(Iterable<? extends VKey<? extends T>> keys);
|
||||
|
||||
/** Loads all entities of the given type, returns empty if there is no such entity. */
|
||||
<T> ImmutableList<T> loadAll(Class<T> clazz);
|
||||
<T> ImmutableMap<VKey<? extends T>, T> loadByKeysIfPresent(
|
||||
Iterable<? extends VKey<? extends T>> keys);
|
||||
|
||||
/**
|
||||
* Loads all given entities from the database, throws NoSuchElementException if it doesn't exist.
|
||||
* Loads all given entities from the database if possible.
|
||||
*
|
||||
* <p>Nonexistent entities are absent from the resulting list, but no {@link
|
||||
* NoSuchElementException} will be thrown.
|
||||
*/
|
||||
<T> ImmutableList<T> loadAll(Iterable<T> entities);
|
||||
<T> ImmutableList<T> loadByEntitiesIfPresent(Iterable<T> entities);
|
||||
|
||||
/**
|
||||
* Loads the entity by its key.
|
||||
*
|
||||
* @throws NoSuchElementException if this key does not correspond to an existing entity.
|
||||
*/
|
||||
<T> T loadByKey(VKey<T> key);
|
||||
|
||||
/**
|
||||
* Loads the set of entities by their keys.
|
||||
*
|
||||
* @throws NoSuchElementException if any of the keys do not correspond to an existing entity.
|
||||
*/
|
||||
<T> ImmutableMap<VKey<? extends T>, T> loadByKeys(Iterable<? extends VKey<? extends T>> keys);
|
||||
|
||||
/**
|
||||
* Loads the given entity from the database.
|
||||
*
|
||||
* @throws NoSuchElementException if the entity does not exist in the database.
|
||||
*/
|
||||
<T> T loadByEntity(T entity);
|
||||
|
||||
/**
|
||||
* Loads all given entities from the database.
|
||||
*
|
||||
* @throws NoSuchElementException if any of the entities do not exist in the database.
|
||||
*/
|
||||
<T> ImmutableList<T> loadByEntities(Iterable<T> entities);
|
||||
|
||||
/**
|
||||
* Returns a stream of all entities of the given type that exist in the database.
|
||||
*
|
||||
* <p>The resulting stream is empty if there are no entities of this type.
|
||||
*/
|
||||
<T> ImmutableList<T> loadAllOf(Class<T> clazz);
|
||||
|
||||
/** Deletes the entity by its id. */
|
||||
void delete(VKey<?> key);
|
||||
|
||||
@@ -342,7 +342,7 @@ public class RdapJsonFormatter {
|
||||
// Kick off the database loads of the nameservers that we will need, so it can load
|
||||
// asynchronously while we load and process the contacts.
|
||||
ImmutableSet<HostResource> loadedHosts =
|
||||
ImmutableSet.copyOf(tm().load(domainBase.getNameservers()).values());
|
||||
ImmutableSet.copyOf(tm().loadByKeys(domainBase.getNameservers()).values());
|
||||
// Load the registrant and other contacts and add them to the data.
|
||||
Map<Key<ContactResource>, ContactResource> loadedContacts =
|
||||
ofy()
|
||||
@@ -429,7 +429,7 @@ public class RdapJsonFormatter {
|
||||
statuses.add(StatusValue.LINKED);
|
||||
}
|
||||
if (hostResource.isSubordinate()
|
||||
&& tm().load(hostResource.getSuperordinateDomain())
|
||||
&& tm().loadByKey(hostResource.getSuperordinateDomain())
|
||||
.cloneProjectedAtTime(getRequestTime())
|
||||
.getStatusValues()
|
||||
.contains(StatusValue.PENDING_TRANSFER)) {
|
||||
|
||||
@@ -172,7 +172,7 @@ final class DomainBaseToXjcConverter {
|
||||
if (registrant == null) {
|
||||
logger.atWarning().log("Domain %s has no registrant contact.", domainName);
|
||||
} else {
|
||||
ContactResource registrantContact = tm().load(registrant);
|
||||
ContactResource registrantContact = tm().loadByKey(registrant);
|
||||
checkState(
|
||||
registrantContact != null,
|
||||
"Registrant contact %s on domain %s does not exist",
|
||||
@@ -305,7 +305,7 @@ final class DomainBaseToXjcConverter {
|
||||
"Contact key for type %s is null on domain %s",
|
||||
model.getType(),
|
||||
domainName);
|
||||
ContactResource contact = tm().load(model.getContactKey());
|
||||
ContactResource contact = tm().loadByKey(model.getContactKey());
|
||||
checkState(
|
||||
contact != null,
|
||||
"Contact %s on domain %s does not exist",
|
||||
|
||||
@@ -203,7 +203,7 @@ public final class RdeStagingMapper extends Mapper<EppResource, PendingDeposit,
|
||||
host,
|
||||
// Note that loadAtPointInTime() does cloneProjectedAtTime(watermark) for
|
||||
// us.
|
||||
loadAtPointInTime(tm().load(host.getSuperordinateDomain()), watermark)
|
||||
loadAtPointInTime(tm().loadByKey(host.getSuperordinateDomain()), watermark)
|
||||
.now())
|
||||
: marshaller.marshalExternalHost(host));
|
||||
cache.put(WatermarkModePair.create(watermark, RdeMode.FULL), result);
|
||||
|
||||
@@ -310,7 +310,7 @@ public final class RequestParameters {
|
||||
* @param name case insensitive header name
|
||||
*/
|
||||
public static Optional<String> extractOptionalHeader(HttpServletRequest req, String name) {
|
||||
return Optional.ofNullable(req.getHeader(name));
|
||||
return Optional.ofNullable(emptyToNull(req.getHeader(name)));
|
||||
}
|
||||
|
||||
private RequestParameters() {}
|
||||
|
||||
@@ -131,6 +131,7 @@ public final class RegistryLock extends ImmutableObject implements Buildable, Sq
|
||||
private boolean isSuperuser;
|
||||
|
||||
/** The lock that undoes this lock, if this lock has been unlocked and the domain locked again. */
|
||||
// TODO(b/176498743): Lazy loading on scalar field not supported by default. See bug for details.
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "relockRevisionId", referencedColumnName = "revisionId")
|
||||
private RegistryLock relock;
|
||||
|
||||
@@ -75,7 +75,7 @@ final class DeleteAllocationTokensCommand extends UpdateOrDeleteAllocationTokens
|
||||
// Load the tokens in the same transaction as they are deleted to verify they weren't redeemed
|
||||
// since the query ran. This also filters out per-domain tokens if they're not to be deleted.
|
||||
ImmutableSet<VKey<AllocationToken>> tokensToDelete =
|
||||
tm().load(batch).values().stream()
|
||||
tm().loadByKeys(batch).values().stream()
|
||||
.filter(t -> withDomains || t.getDomainName().isEmpty())
|
||||
.filter(t -> SINGLE_USE.equals(t.getTokenType()))
|
||||
.filter(t -> !t.isRedeemed())
|
||||
|
||||
@@ -263,7 +263,7 @@ class GenerateAllocationTokensCommand implements CommandWithRemoteApi {
|
||||
savedTokens = tokens;
|
||||
} else {
|
||||
transactIfJpaTm(() -> tm().transact(() -> tm().putAll(tokens)));
|
||||
savedTokens = tm().transact(() -> tm().loadAll(tokens));
|
||||
savedTokens = tm().transact(() -> tm().loadByEntities(tokens));
|
||||
}
|
||||
savedTokens.forEach(
|
||||
t -> System.out.println(SKIP_NULLS.join(t.getDomainName().orElse(null), t.getToken())));
|
||||
@@ -293,7 +293,7 @@ class GenerateAllocationTokensCommand implements CommandWithRemoteApi {
|
||||
.collect(toImmutableSet());
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
tm().load(existingTokenKeys).values().stream()
|
||||
tm().loadByKeysIfPresent(existingTokenKeys).values().stream()
|
||||
.map(AllocationToken::getToken)
|
||||
.collect(toImmutableSet()));
|
||||
}
|
||||
|
||||
@@ -49,7 +49,8 @@ final class GetAllocationTokenCommand implements CommandWithRemoteApi {
|
||||
tokens.stream()
|
||||
.map(t -> VKey.create(AllocationToken.class, t))
|
||||
.collect(toImmutableList());
|
||||
tm().load(tokenKeys).forEach((k, v) -> builder.put(k.getSqlKey().toString(), v));
|
||||
tm().loadByKeysIfPresent(tokenKeys)
|
||||
.forEach((k, v) -> builder.put(k.getSqlKey().toString(), v));
|
||||
}
|
||||
ImmutableMap<String, AllocationToken> loadedTokens = builder.build();
|
||||
ImmutableMap<VKey<DomainBase>, DomainBase> domains = loadRedeemedDomains(loadedTokens.values());
|
||||
@@ -88,14 +89,14 @@ final class GetAllocationTokenCommand implements CommandWithRemoteApi {
|
||||
.map(AllocationToken::getRedemptionHistoryEntry)
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.map(key -> tm().load(key))
|
||||
.map(key -> tm().loadByKey(key))
|
||||
.map(he -> (Key<DomainBase>) he.getParent())
|
||||
.map(key -> VKey.create(DomainBase.class, key.getName(), key))
|
||||
.collect(toImmutableList());
|
||||
ImmutableMap.Builder<VKey<DomainBase>, DomainBase> domainsBuilder =
|
||||
new ImmutableMap.Builder<>();
|
||||
for (List<VKey<DomainBase>> keys : Lists.partition(domainKeys, BATCH_SIZE)) {
|
||||
tm().load(ImmutableList.copyOf(keys))
|
||||
tm().loadByKeys(ImmutableList.copyOf(keys))
|
||||
.forEach((k, v) -> domainsBuilder.put((VKey<DomainBase>) k, v));
|
||||
}
|
||||
return domainsBuilder.build();
|
||||
|
||||
@@ -56,7 +56,7 @@ public final class ResaveEppResourceCommand extends MutatingCommand {
|
||||
uniqueId);
|
||||
// Load the resource directly to bypass running cloneProjectedAtTime() automatically, which can
|
||||
// cause stageEntityChange() to fail due to implicit projection changes.
|
||||
EppResource resource = tm().load(resourceKey);
|
||||
EppResource resource = tm().loadByKey(resourceKey);
|
||||
stageEntityChange(resource, resource);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ final class UniformRapidSuspensionCommand extends MutatingEppToolCommand {
|
||||
|
||||
private ImmutableSortedSet<String> getExistingNameservers(DomainBase domain) {
|
||||
ImmutableSortedSet.Builder<String> nameservers = ImmutableSortedSet.naturalOrder();
|
||||
for (HostResource host : tm().load(domain.getNameservers()).values()) {
|
||||
for (HostResource host : tm().loadByKeys(domain.getNameservers()).values()) {
|
||||
nameservers.add(host.getForeignKey());
|
||||
}
|
||||
return nameservers.build();
|
||||
|
||||
@@ -107,7 +107,7 @@ final class UpdateAllocationTokensCommand extends UpdateOrDeleteAllocationTokens
|
||||
tokensToSave =
|
||||
transactIfJpaTm(
|
||||
() ->
|
||||
tm().load(getTokenKeys()).values().stream()
|
||||
tm().loadByKeys(getTokenKeys()).values().stream()
|
||||
.collect(toImmutableMap(Function.identity(), this::updateToken))
|
||||
.entrySet()
|
||||
.stream()
|
||||
|
||||
@@ -329,7 +329,7 @@ final class UpdateDomainCommand extends CreateOrUpdateDomainCommand {
|
||||
DomainBase domainBase, final DesignatedContact.Type contactType) {
|
||||
return domainBase.getContacts().stream()
|
||||
.filter(contact -> contact.getType().equals(contactType))
|
||||
.map(contact -> tm().load(contact.getContactKey()).getContactId())
|
||||
.map(contact -> tm().loadByKey(contact.getContactKey()).getContactId())
|
||||
.collect(toImmutableSet());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ abstract class UpdateOrDeleteAllocationTokensCommand extends ConfirmingCommand
|
||||
checkArgument(!prefix.isEmpty(), "Provided prefix should not be blank");
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
tm().loadAll(AllocationToken.class).stream()
|
||||
tm().loadAllOf(AllocationToken.class).stream()
|
||||
.filter(token -> token.getToken().startsWith(prefix))
|
||||
.map(AllocationToken::createVKey)
|
||||
.collect(toImmutableSet()));
|
||||
|
||||
@@ -61,6 +61,7 @@ final class ValidateLoginCredentialsCommand implements CommandWithRemoteApi {
|
||||
description = "Hash of the client certificate.")
|
||||
private String clientCertificateHash;
|
||||
|
||||
@Nullable
|
||||
@Parameter(
|
||||
names = {"-i", "--ip_address"},
|
||||
description = "Client ip address to pretend to use")
|
||||
@@ -78,7 +79,8 @@ final class ValidateLoginCredentialsCommand implements CommandWithRemoteApi {
|
||||
Registrar registrar =
|
||||
checkArgumentPresent(
|
||||
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
|
||||
new TlsCredentials(true, clientCertificateHash, Optional.of(clientIpAddress))
|
||||
new TlsCredentials(
|
||||
true, Optional.ofNullable(clientCertificateHash), Optional.ofNullable(clientIpAddress))
|
||||
.validate(registrar, password);
|
||||
checkState(
|
||||
registrar.isLive(), "Registrar %s has non-live state: %s", clientId, registrar.getState());
|
||||
|
||||
@@ -214,7 +214,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
|
||||
private void emitForSubordinateHosts(DomainBase domain) {
|
||||
ImmutableSet<String> subordinateHosts = domain.getSubordinateHosts();
|
||||
if (!subordinateHosts.isEmpty()) {
|
||||
for (HostResource unprojectedHost : tm().load(domain.getNameservers()).values()) {
|
||||
for (HostResource unprojectedHost : tm().loadByKeys(domain.getNameservers()).values()) {
|
||||
HostResource host = loadAtPointInTime(unprojectedHost, exportTime).now();
|
||||
// A null means the host was deleted (or not created) at this time.
|
||||
if ((host != null) && subordinateHosts.contains(host.getHostName())) {
|
||||
@@ -283,7 +283,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
|
||||
Duration dnsDefaultDsTtl) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
String domainLabel = stripTld(domain.getDomainName(), domain.getTld());
|
||||
for (HostResource nameserver : tm().load(domain.getNameservers()).values()) {
|
||||
for (HostResource nameserver : tm().loadByKeys(domain.getNameservers()).values()) {
|
||||
result.append(
|
||||
String.format(
|
||||
NS_FORMAT,
|
||||
|
||||
@@ -334,8 +334,9 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
|
||||
* Returns true if the registrar should accept the new certificate. Returns false if the
|
||||
* certificate is already the one stored for the registrar.
|
||||
*/
|
||||
private boolean validateCertificate(String existingCertificate, String certificateString) {
|
||||
if ((existingCertificate == null) || !existingCertificate.equals(certificateString)) {
|
||||
private boolean validateCertificate(
|
||||
Optional<String> existingCertificate, String certificateString) {
|
||||
if (!existingCertificate.isPresent() || !existingCertificate.get().equals(certificateString)) {
|
||||
certificateChecker.validateCertificate(certificateString);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ final class NameserverWhoisResponse extends WhoisResponseImpl {
|
||||
HostResource host = hosts.get(i);
|
||||
String clientId =
|
||||
host.isSubordinate()
|
||||
? tm().load(host.getSuperordinateDomain())
|
||||
? tm().loadByKey(host.getSuperordinateDomain())
|
||||
.cloneProjectedAtTime(getTimestamp())
|
||||
.getCurrentSponsorClientId()
|
||||
: host.getPersistedCurrentSponsorClientId();
|
||||
|
||||
@@ -243,7 +243,7 @@ public class ReplayCommitLogsToSqlActionTest {
|
||||
CommitLogMutation.create(manifestKey, TestObject.create("existing", "b")));
|
||||
action.run();
|
||||
TestObject fromDatabase =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(TestObject.class, "existing")));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(VKey.createSql(TestObject.class, "existing")));
|
||||
assertThat(fromDatabase.getField()).isEqualTo("b");
|
||||
}
|
||||
|
||||
@@ -276,7 +276,7 @@ public class ReplayCommitLogsToSqlActionTest {
|
||||
DomainBase domain = newDomainBase("example.tld");
|
||||
CommitLogMutation domainMutation =
|
||||
tm().transact(() -> CommitLogMutation.create(manifestKey, domain));
|
||||
ContactResource contact = tm().transact(() -> tm().load(domain.getRegistrant()));
|
||||
ContactResource contact = tm().transact(() -> tm().loadByKey(domain.getRegistrant()));
|
||||
CommitLogMutation contactMutation =
|
||||
tm().transact(() -> CommitLogMutation.create(manifestKey, contact));
|
||||
|
||||
@@ -348,7 +348,7 @@ public class ReplayCommitLogsToSqlActionTest {
|
||||
inOrder.verify(spy).delete(contact.createVKey());
|
||||
inOrder.verify(spy).put(putCaptor.capture());
|
||||
assertThat(putCaptor.getValue().getClass()).isEqualTo(ContactResource.class);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().load(contact.createVKey()).getEmailAddress()))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadByKey(contact.createVKey()).getEmailAddress()))
|
||||
.isEqualTo("replay@example.tld");
|
||||
}
|
||||
|
||||
@@ -450,7 +450,7 @@ public class ReplayCommitLogsToSqlActionTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() ->
|
||||
jpaTm().loadAll(TestObject.class).stream()
|
||||
jpaTm().loadAllOf(TestObject.class).stream()
|
||||
.map(TestObject::getId)
|
||||
.collect(toImmutableList()));
|
||||
assertThat(actualIds).containsExactlyElementsIn(expectedIds);
|
||||
|
||||
@@ -241,14 +241,15 @@ class InitSqlPipelineTest {
|
||||
initSqlPipeline.run().waitUntilFinish();
|
||||
try (AppEngineEnvironment env = new AppEngineEnvironment("test")) {
|
||||
assertHostResourceEquals(
|
||||
jpaTm().transact(() -> jpaTm().load(hostResource.createVKey())), hostResource);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAll(Registrar.class)))
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(hostResource.createVKey())), hostResource);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAllOf(Registrar.class)))
|
||||
.comparingElementsUsing(immutableObjectCorrespondence("lastUpdateTime"))
|
||||
.containsExactly(registrar1, registrar2);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAll(ContactResource.class)))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAllOf(ContactResource.class)))
|
||||
.comparingElementsUsing(immutableObjectCorrespondence("revisions", "updateTimestamp"))
|
||||
.containsExactly(contact1, contact2);
|
||||
assertCleansedDomainEquals(jpaTm().transact(() -> jpaTm().load(domain.createVKey())), domain);
|
||||
assertCleansedDomainEquals(
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(domain.createVKey())), domain);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ class WriteToSqlTest implements Serializable {
|
||||
.localDbJpaTransactionManager()));
|
||||
testPipeline.run().waitUntilFinish();
|
||||
|
||||
ImmutableList<?> sqlContacts = jpaTm().transact(() -> jpaTm().loadAll(ContactResource.class));
|
||||
ImmutableList<?> sqlContacts = jpaTm().transact(() -> jpaTm().loadAllOf(ContactResource.class));
|
||||
assertThat(sqlContacts)
|
||||
.comparingElementsUsing(immutableObjectCorrespondence("revisions", "updateTimestamp"))
|
||||
.containsExactlyElementsIn(
|
||||
|
||||
@@ -36,7 +36,8 @@ class EppLoginTlsTest extends EppTestCase {
|
||||
|
||||
void setClientCertificateHash(String clientCertificateHash) {
|
||||
setTransportCredentials(
|
||||
new TlsCredentials(true, clientCertificateHash, Optional.of("192.168.1.100:54321")));
|
||||
new TlsCredentials(
|
||||
true, Optional.ofNullable(clientCertificateHash), Optional.of("192.168.1.100:54321")));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -107,7 +108,7 @@ class EppLoginTlsTest extends EppTestCase {
|
||||
|
||||
@Test
|
||||
void testGfeDidntProvideClientCertificate_failsMissingCertificate2200() throws Exception {
|
||||
setClientCertificateHash("");
|
||||
setClientCertificateHash(null);
|
||||
assertThatLogin("NewRegistrar", "foo-BAR2")
|
||||
.hasResponse(
|
||||
"response_error.xml",
|
||||
|
||||
@@ -137,7 +137,8 @@ class FlowRunnerTest {
|
||||
|
||||
@Test
|
||||
void testRun_loggingStatement_tlsCredentials() throws Exception {
|
||||
flowRunner.credentials = new TlsCredentials(true, "abc123def", Optional.of("127.0.0.1"));
|
||||
flowRunner.credentials =
|
||||
new TlsCredentials(true, Optional.of("abc123def"), Optional.of("127.0.0.1"));
|
||||
flowRunner.run(eppMetricBuilder);
|
||||
assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t")))
|
||||
.contains("TlsCredentials{clientCertificateHash=abc123def, clientAddress=/127.0.0.1}");
|
||||
|
||||
@@ -203,7 +203,7 @@ public abstract class FlowTestCase<F extends Flow> {
|
||||
assertWithMessage("Billing event is present for grace period: " + gracePeriod)
|
||||
.that(gracePeriod.hasBillingEvent())
|
||||
.isTrue();
|
||||
return tm().load(
|
||||
return tm().loadByKey(
|
||||
firstNonNull(
|
||||
gracePeriod.getOneTimeBillingEvent(), gracePeriod.getRecurringBillingEvent()));
|
||||
}
|
||||
|
||||
@@ -87,7 +87,8 @@ public abstract class ResourceFlowTestCase<F extends Flow, R extends EppResource
|
||||
// Force the session to be cleared.
|
||||
tm().clearSessionCache();
|
||||
@SuppressWarnings("unchecked")
|
||||
T refreshedResource = (T) transactIfJpaTm(() -> tm().load(resource)).cloneProjectedAtTime(now);
|
||||
T refreshedResource =
|
||||
(T) transactIfJpaTm(() -> tm().loadByEntity(resource)).cloneProjectedAtTime(now);
|
||||
return refreshedResource;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
|
||||
package google.registry.flows;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
import static google.registry.testing.CertificateSamples.SAMPLE_CERT;
|
||||
import static google.registry.testing.DatabaseHelper.loadRegistrar;
|
||||
import static google.registry.testing.DatabaseHelper.persistResource;
|
||||
import static org.joda.time.DateTimeZone.UTC;
|
||||
@@ -22,9 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.flows.TlsCredentials.BadRegistrarIpAddressException;
|
||||
import google.registry.flows.TlsCredentials.MissingRegistrarCertificateException;
|
||||
import google.registry.model.registrar.Registrar;
|
||||
import google.registry.request.HttpException.BadRequestException;
|
||||
import google.registry.testing.AppEngineExtension;
|
||||
import google.registry.util.CidrAddressBlock;
|
||||
import java.util.Optional;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.joda.time.DateTime;
|
||||
@@ -42,22 +46,40 @@ final class TlsCredentialsTest {
|
||||
void testProvideClientCertificateHash() {
|
||||
HttpServletRequest req = mock(HttpServletRequest.class);
|
||||
when(req.getHeader("X-SSL-Certificate")).thenReturn("data");
|
||||
assertThat(TlsCredentials.EppTlsModule.provideClientCertificateHash(req)).isEqualTo("data");
|
||||
assertThat(TlsCredentials.EppTlsModule.provideClientCertificateHash(req)).hasValue("data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProvideClientCertificateHash_missing() {
|
||||
HttpServletRequest req = mock(HttpServletRequest.class);
|
||||
BadRequestException thrown =
|
||||
assertThrows(
|
||||
BadRequestException.class,
|
||||
() -> TlsCredentials.EppTlsModule.provideClientCertificateHash(req));
|
||||
assertThat(thrown).hasMessageThat().contains("Missing header: X-SSL-Certificate");
|
||||
void testClientCertificateHash_missing() {
|
||||
TlsCredentials tls = new TlsCredentials(true, Optional.empty(), Optional.of("192.168.1.1"));
|
||||
persistResource(
|
||||
loadRegistrar("TheRegistrar")
|
||||
.asBuilder()
|
||||
.setClientCertificate(SAMPLE_CERT, DateTime.now(UTC))
|
||||
.build());
|
||||
assertThrows(
|
||||
MissingRegistrarCertificateException.class,
|
||||
() -> tls.validateCertificate(Registrar.loadByClientId("TheRegistrar").get()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_missingIpAddress_doesntAllowAccess() {
|
||||
TlsCredentials tls = new TlsCredentials(false, Optional.of("certHash"), Optional.empty());
|
||||
persistResource(
|
||||
loadRegistrar("TheRegistrar")
|
||||
.asBuilder()
|
||||
.setClientCertificate(SAMPLE_CERT, DateTime.now(UTC))
|
||||
.setIpAddressAllowList(ImmutableSet.of(CidrAddressBlock.create("3.5.8.13")))
|
||||
.build());
|
||||
assertThrows(
|
||||
BadRegistrarIpAddressException.class,
|
||||
() -> tls.validate(Registrar.loadByClientId("TheRegistrar").get(), "password"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_validateCertificate_canBeConfiguredToBypassCertHashes() throws Exception {
|
||||
TlsCredentials tls = new TlsCredentials(false, "certHash", Optional.of("192.168.1.1"));
|
||||
TlsCredentials tls =
|
||||
new TlsCredentials(false, Optional.of("certHash"), Optional.of("192.168.1.1"));
|
||||
persistResource(
|
||||
loadRegistrar("TheRegistrar")
|
||||
.asBuilder()
|
||||
|
||||
@@ -265,7 +265,8 @@ class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow, Domain
|
||||
HistoryEntry historyEntry = getHistoryEntries(domain).get(0);
|
||||
assertAboutDomains()
|
||||
.that(domain)
|
||||
.hasRegistrationExpirationTime(tm().load(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
.hasRegistrationExpirationTime(
|
||||
tm().loadByKey(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
.and()
|
||||
.hasOnlyOneHistoryEntryWhich()
|
||||
.hasType(HistoryEntry.Type.DOMAIN_CREATE)
|
||||
|
||||
@@ -475,7 +475,7 @@ class DomainDeleteFlowTest extends ResourceFlowTestCase<DomainDeleteFlow, Domain
|
||||
assertThat(getPollMessages("TheRegistrar", deletionTime)).hasSize(1);
|
||||
assertThat(domain.getDeletePollMessage().getOfyKey())
|
||||
.isEqualTo(getOnlyPollMessage("TheRegistrar").createVKey().getOfyKey());
|
||||
PollMessage.OneTime deletePollMessage = tm().load(domain.getDeletePollMessage());
|
||||
PollMessage.OneTime deletePollMessage = tm().loadByKey(domain.getDeletePollMessage());
|
||||
assertThat(deletePollMessage.getMsg()).isEqualTo(expectedMessage);
|
||||
}
|
||||
|
||||
@@ -509,7 +509,7 @@ class DomainDeleteFlowTest extends ResourceFlowTestCase<DomainDeleteFlow, Domain
|
||||
// Modify the autorenew poll message so that it has unacked messages in the past. This should
|
||||
// prevent it from being deleted when the domain is deleted.
|
||||
persistResource(
|
||||
tm().load(reloadResourceByForeignKey().getAutorenewPollMessage())
|
||||
tm().loadByKey(reloadResourceByForeignKey().getAutorenewPollMessage())
|
||||
.asBuilder()
|
||||
.setEventTime(A_MONTH_FROM_NOW.minusYears(3))
|
||||
.build());
|
||||
|
||||
@@ -197,7 +197,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase<DomainRenewFlow, DomainBa
|
||||
DomainBase domain = reloadResourceByForeignKey();
|
||||
HistoryEntry historyEntryDomainRenew =
|
||||
getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_RENEW);
|
||||
assertThat(tm().load(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
assertThat(tm().loadByKey(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
.isEqualTo(newExpiration);
|
||||
assertAboutDomains()
|
||||
.that(domain)
|
||||
@@ -494,7 +494,7 @@ class DomainRenewFlowTest extends ResourceFlowTestCase<DomainRenewFlow, DomainBa
|
||||
persistDomain();
|
||||
// Modify the autorenew poll message so that it has an undelivered message in the past.
|
||||
persistResource(
|
||||
tm().load(reloadResourceByForeignKey().getAutorenewPollMessage())
|
||||
tm().loadByKey(reloadResourceByForeignKey().getAutorenewPollMessage())
|
||||
.asBuilder()
|
||||
.setEventTime(expirationTime.minusYears(1))
|
||||
.build());
|
||||
|
||||
@@ -150,7 +150,7 @@ class DomainRestoreRequestFlowTest
|
||||
DomainBase domain = reloadResourceByForeignKey();
|
||||
HistoryEntry historyEntryDomainRestore =
|
||||
getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_RESTORE);
|
||||
assertThat(tm().load(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
assertThat(tm().loadByKey(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
.isEqualTo(expirationTime);
|
||||
assertAboutDomains()
|
||||
.that(domain)
|
||||
@@ -218,7 +218,7 @@ class DomainRestoreRequestFlowTest
|
||||
DomainBase domain = reloadResourceByForeignKey();
|
||||
HistoryEntry historyEntryDomainRestore =
|
||||
getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_RESTORE);
|
||||
assertThat(tm().load(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
assertThat(tm().loadByKey(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
.isEqualTo(newExpirationTime);
|
||||
assertAboutDomains()
|
||||
.that(domain)
|
||||
|
||||
@@ -191,7 +191,7 @@ class DomainTransferApproveFlowTest
|
||||
assertAboutHistoryEntries().that(historyEntryTransferApproved).hasOtherClientId("NewRegistrar");
|
||||
assertTransferApproved(domain, originalTransferData);
|
||||
assertAboutDomains().that(domain).hasRegistrationExpirationTime(expectedExpirationTime);
|
||||
assertThat(tm().load(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
assertThat(tm().loadByKey(domain.getAutorenewBillingEvent()).getEventTime())
|
||||
.isEqualTo(expectedExpirationTime);
|
||||
// The poll message (in the future) to the losing registrar for implicit ack should be gone.
|
||||
assertThat(getPollMessages(domain, "TheRegistrar", clock.nowUtc().plusMonths(1))).isEmpty();
|
||||
|
||||
@@ -291,13 +291,13 @@ class DomainTransferRequestFlowTest
|
||||
// Assert that the domain's TransferData server-approve billing events match the above.
|
||||
if (expectTransferBillingEvent) {
|
||||
assertBillingEventsEqual(
|
||||
tm().load(domain.getTransferData().getServerApproveBillingEvent()),
|
||||
tm().loadByKey(domain.getTransferData().getServerApproveBillingEvent()),
|
||||
optionalTransferBillingEvent.get());
|
||||
} else {
|
||||
assertThat(domain.getTransferData().getServerApproveBillingEvent()).isNull();
|
||||
}
|
||||
assertBillingEventsEqual(
|
||||
tm().load(domain.getTransferData().getServerApproveAutorenewEvent()),
|
||||
tm().loadByKey(domain.getTransferData().getServerApproveAutorenewEvent()),
|
||||
gainingClientAutorenew);
|
||||
// Assert that the full set of server-approve billing events is exactly the extra ones plus
|
||||
// the transfer billing event (if present) and the gaining client autorenew.
|
||||
@@ -318,7 +318,7 @@ class DomainTransferRequestFlowTest
|
||||
BillingEvent.class),
|
||||
Sets.union(expectedServeApproveBillingEvents, extraBillingEvents));
|
||||
// The domain's autorenew billing event should still point to the losing client's event.
|
||||
BillingEvent.Recurring domainAutorenewEvent = tm().load(domain.getAutorenewBillingEvent());
|
||||
BillingEvent.Recurring domainAutorenewEvent = tm().loadByKey(domain.getAutorenewBillingEvent());
|
||||
assertThat(domainAutorenewEvent.getClientId()).isEqualTo("TheRegistrar");
|
||||
assertThat(domainAutorenewEvent.getRecurrenceEndTime()).isEqualTo(implicitTransferTime);
|
||||
// The original grace periods should remain untouched.
|
||||
@@ -414,7 +414,7 @@ class DomainTransferRequestFlowTest
|
||||
|
||||
// Assert that the poll messages show up in the TransferData server approve entities.
|
||||
assertPollMessagesEqual(
|
||||
tm().load(domain.getTransferData().getServerApproveAutorenewPollMessage()),
|
||||
tm().loadByKey(domain.getTransferData().getServerApproveAutorenewPollMessage()),
|
||||
autorenewPollMessage);
|
||||
// Assert that the full set of server-approve poll messages is exactly the server approve
|
||||
// OneTime messages to gaining and losing registrars plus the gaining client autorenew.
|
||||
@@ -446,7 +446,8 @@ class DomainTransferRequestFlowTest
|
||||
.hasLastEppUpdateTime(implicitTransferTime)
|
||||
.and()
|
||||
.hasLastEppUpdateClientId("NewRegistrar");
|
||||
assertThat(tm().load(domainAfterAutomaticTransfer.getAutorenewBillingEvent()).getEventTime())
|
||||
assertThat(
|
||||
tm().loadByKey(domainAfterAutomaticTransfer.getAutorenewBillingEvent()).getEventTime())
|
||||
.isEqualTo(expectedExpirationTime);
|
||||
// And after the expected grace time, the grace period should be gone.
|
||||
DomainBase afterGracePeriod =
|
||||
|
||||
@@ -330,7 +330,7 @@ class DomainUpdateFlowTest extends ResourceFlowTestCase<DomainUpdateFlow, Domain
|
||||
assertThat(domain.getNameservers()).hasSize(13);
|
||||
// getContacts does not return contacts of type REGISTRANT, so check these separately.
|
||||
assertThat(domain.getContacts()).hasSize(3);
|
||||
assertThat(tm().load(domain.getRegistrant()).getContactId()).isEqualTo("max_test_7");
|
||||
assertThat(tm().loadByKey(domain.getRegistrant()).getContactId()).isEqualTo("max_test_7");
|
||||
assertNoBillingEvents();
|
||||
assertDnsTasksEnqueued("example.tld");
|
||||
}
|
||||
@@ -1238,7 +1238,7 @@ class DomainUpdateFlowTest extends ResourceFlowTestCase<DomainUpdateFlow, Domain
|
||||
.setAllowedFullyQualifiedHostNames(ImmutableSet.of("ns1.example.foo"))
|
||||
.build());
|
||||
runFlow();
|
||||
assertThat(tm().load(reloadResourceByForeignKey().getRegistrant()).getContactId())
|
||||
assertThat(tm().loadByKey(reloadResourceByForeignKey().getRegistrant()).getContactId())
|
||||
.isEqualTo("sh8013");
|
||||
}
|
||||
|
||||
@@ -1252,9 +1252,9 @@ class DomainUpdateFlowTest extends ResourceFlowTestCase<DomainUpdateFlow, Domain
|
||||
.getContacts()
|
||||
.forEach(
|
||||
contact -> {
|
||||
assertThat(tm().load(contact.getContactKey()).getContactId()).isEqualTo("mak21");
|
||||
assertThat(tm().loadByKey(contact.getContactKey()).getContactId()).isEqualTo("mak21");
|
||||
});
|
||||
assertThat(tm().load(reloadResourceByForeignKey().getRegistrant()).getContactId())
|
||||
assertThat(tm().loadByKey(reloadResourceByForeignKey().getRegistrant()).getContactId())
|
||||
.isEqualTo("mak21");
|
||||
|
||||
runFlow();
|
||||
@@ -1263,9 +1263,10 @@ class DomainUpdateFlowTest extends ResourceFlowTestCase<DomainUpdateFlow, Domain
|
||||
.getContacts()
|
||||
.forEach(
|
||||
contact -> {
|
||||
assertThat(tm().load(contact.getContactKey()).getContactId()).isEqualTo("sh8013");
|
||||
assertThat(tm().loadByKey(contact.getContactKey()).getContactId())
|
||||
.isEqualTo("sh8013");
|
||||
});
|
||||
assertThat(tm().load(reloadResourceByForeignKey().getRegistrant()).getContactId())
|
||||
assertThat(tm().loadByKey(reloadResourceByForeignKey().getRegistrant()).getContactId())
|
||||
.isEqualTo("sh8013");
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,10 @@ import org.junit.jupiter.api.Test;
|
||||
/** Unit tests for {@link LoginFlow} when accessed via a TLS transport. */
|
||||
public class LoginFlowViaTlsTest extends LoginFlowTestCase {
|
||||
|
||||
private static final String GOOD_CERT = CertificateSamples.SAMPLE_CERT_HASH;
|
||||
private static final String BAD_CERT = CertificateSamples.SAMPLE_CERT2_HASH;
|
||||
private static final Optional<String> GOOD_CERT =
|
||||
Optional.of(CertificateSamples.SAMPLE_CERT_HASH);
|
||||
private static final Optional<String> BAD_CERT =
|
||||
Optional.of(CertificateSamples.SAMPLE_CERT2_HASH);
|
||||
private static final Optional<String> GOOD_IP = Optional.of("192.168.1.1");
|
||||
private static final Optional<String> BAD_IP = Optional.of("1.1.1.1");
|
||||
private static final Optional<String> GOOD_IPV6 = Optional.of("2001:db8::1");
|
||||
@@ -97,7 +99,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase {
|
||||
@Test
|
||||
void testFailure_missingClientCertificateHash() {
|
||||
persistResource(getRegistrarBuilder().build());
|
||||
credentials = new TlsCredentials(true, null, GOOD_IP);
|
||||
credentials = new TlsCredentials(true, Optional.empty(), GOOD_IP);
|
||||
doFailingTest("login_valid.xml", MissingRegistrarCertificateException.class);
|
||||
}
|
||||
|
||||
|
||||
@@ -163,9 +163,9 @@ public final class OteAccountBuilderTest {
|
||||
.buildAndPersist();
|
||||
|
||||
assertThat(Registrar.loadByClientId("myclientid-3").get().getClientCertificateHash())
|
||||
.isEqualTo(SAMPLE_CERT_HASH);
|
||||
.hasValue(SAMPLE_CERT_HASH);
|
||||
assertThat(Registrar.loadByClientId("myclientid-3").get().getClientCertificate())
|
||||
.isEqualTo(SAMPLE_CERT);
|
||||
.hasValue(SAMPLE_CERT);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -58,7 +58,7 @@ public class UpdateAutoTimestampTest {
|
||||
private UpdateAutoTimestampTestObject reload() {
|
||||
return tm().transact(
|
||||
() ->
|
||||
tm().load(
|
||||
tm().loadByKey(
|
||||
VKey.create(
|
||||
UpdateAutoTimestampTestObject.class,
|
||||
1L,
|
||||
|
||||
@@ -184,15 +184,16 @@ public class BillingEventTest extends EntityTestCase {
|
||||
|
||||
@TestOfyAndSql
|
||||
void testPersistence() {
|
||||
assertThat(transactIfJpaTm(() -> tm().load(oneTime))).isEqualTo(oneTime);
|
||||
assertThat(transactIfJpaTm(() -> tm().load(oneTimeSynthetic))).isEqualTo(oneTimeSynthetic);
|
||||
assertThat(transactIfJpaTm(() -> tm().load(recurring))).isEqualTo(recurring);
|
||||
assertThat(transactIfJpaTm(() -> tm().load(cancellationOneTime)))
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(oneTime))).isEqualTo(oneTime);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(oneTimeSynthetic)))
|
||||
.isEqualTo(oneTimeSynthetic);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(recurring))).isEqualTo(recurring);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(cancellationOneTime)))
|
||||
.isEqualTo(cancellationOneTime);
|
||||
assertThat(transactIfJpaTm(() -> tm().load(cancellationRecurring)))
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(cancellationRecurring)))
|
||||
.isEqualTo(cancellationRecurring);
|
||||
|
||||
ofyTmOrDoNothing(() -> assertThat(tm().load(modification)).isEqualTo(modification));
|
||||
ofyTmOrDoNothing(() -> assertThat(tm().loadByEntity(modification)).isEqualTo(modification));
|
||||
}
|
||||
|
||||
@TestOfyOnly
|
||||
@@ -220,8 +221,9 @@ public class BillingEventTest extends EntityTestCase {
|
||||
@TestOfyAndSql
|
||||
void testCancellationMatching() {
|
||||
VKey<?> recurringKey =
|
||||
transactIfJpaTm(() -> tm().load(oneTimeSynthetic).getCancellationMatchingBillingEvent());
|
||||
assertThat(transactIfJpaTm(() -> tm().load(recurringKey))).isEqualTo(recurring);
|
||||
transactIfJpaTm(
|
||||
() -> tm().loadByEntity(oneTimeSynthetic).getCancellationMatchingBillingEvent());
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByKey(recurringKey))).isEqualTo(recurring);
|
||||
}
|
||||
|
||||
@TestOfyOnly
|
||||
|
||||
@@ -140,7 +140,8 @@ public class ContactResourceTest extends EntityTestCase {
|
||||
.transact(
|
||||
() ->
|
||||
jpaTm()
|
||||
.load(VKey.createSql(ContactResource.class, originalContact.getRepoId())));
|
||||
.loadByKey(
|
||||
VKey.createSql(ContactResource.class, originalContact.getRepoId())));
|
||||
|
||||
ContactResource fixed =
|
||||
originalContact
|
||||
|
||||
@@ -139,7 +139,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase result = jpaTm().load(domain.createVKey());
|
||||
DomainBase result = jpaTm().loadByKey(domain.createVKey());
|
||||
assertEqualDomainExcept(result);
|
||||
});
|
||||
}
|
||||
@@ -177,14 +177,14 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
jpaTm().put(persisted.asBuilder().build());
|
||||
});
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
// Load the domain in its entirety.
|
||||
DomainBase result = jpaTm().load(domain.createVKey());
|
||||
DomainBase result = jpaTm().loadByKey(domain.createVKey());
|
||||
assertEqualDomainExcept(result);
|
||||
});
|
||||
}
|
||||
@@ -195,7 +195,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
DomainBase modified =
|
||||
persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build();
|
||||
jpaTm().put(modified);
|
||||
@@ -204,7 +204,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getGracePeriods()).isEmpty();
|
||||
});
|
||||
}
|
||||
@@ -215,7 +215,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
DomainBase modified = persisted.asBuilder().setGracePeriods(null).build();
|
||||
jpaTm().put(modified);
|
||||
});
|
||||
@@ -223,7 +223,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getGracePeriods()).isEmpty();
|
||||
});
|
||||
}
|
||||
@@ -234,7 +234,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
DomainBase modified =
|
||||
persisted
|
||||
.asBuilder()
|
||||
@@ -253,7 +253,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getGracePeriods())
|
||||
.containsExactly(
|
||||
GracePeriod.create(
|
||||
@@ -266,7 +266,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
DomainBase.Builder builder = persisted.asBuilder();
|
||||
for (GracePeriod gracePeriod : persisted.getGracePeriods()) {
|
||||
if (gracePeriod.getType() == GracePeriodStatus.RENEW) {
|
||||
@@ -279,7 +279,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertEqualDomainExcept(persisted);
|
||||
});
|
||||
}
|
||||
@@ -290,7 +290,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
DomainBase modified =
|
||||
persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build();
|
||||
jpaTm().put(modified);
|
||||
@@ -299,7 +299,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getGracePeriods()).isEmpty();
|
||||
DomainBase modified =
|
||||
persisted
|
||||
@@ -319,7 +319,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getGracePeriods())
|
||||
.containsExactly(
|
||||
GracePeriod.create(
|
||||
@@ -340,7 +340,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getDsData()).containsExactlyElementsIn(domain.getDsData());
|
||||
DomainBase modified = persisted.asBuilder().setDsData(unionDsData).build();
|
||||
jpaTm().put(modified);
|
||||
@@ -350,7 +350,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertThat(persisted.getDsData()).containsExactlyElementsIn(unionDsData);
|
||||
assertEqualDomainExcept(persisted, "dsData");
|
||||
});
|
||||
@@ -359,7 +359,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
jpaTm().put(persisted.asBuilder().setDsData(domain.getDsData()).build());
|
||||
});
|
||||
|
||||
@@ -367,7 +367,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase persisted = jpaTm().load(domain.createVKey());
|
||||
DomainBase persisted = jpaTm().loadByKey(domain.createVKey());
|
||||
assertEqualDomainExcept(persisted);
|
||||
});
|
||||
}
|
||||
@@ -388,7 +388,7 @@ public class DomainBaseSqlTest {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainBase result = jpaTm().load(domain.createVKey());
|
||||
DomainBase result = jpaTm().loadByKey(domain.createVKey());
|
||||
assertAboutImmutableObjects()
|
||||
.that(result)
|
||||
.isEqualExceptFields(domain, "updateTimestamp", "creationTime");
|
||||
@@ -528,7 +528,7 @@ public class DomainBaseSqlTest {
|
||||
});
|
||||
|
||||
// Store the existing BillingRecurrence VKey. This happens after the event has been persisted.
|
||||
DomainBase persisted = jpaTm().transact(() -> jpaTm().load(domain.createVKey()));
|
||||
DomainBase persisted = jpaTm().transact(() -> jpaTm().loadByKey(domain.createVKey()));
|
||||
|
||||
// Verify that the domain data has been persisted.
|
||||
// dsData still isn't persisted. gracePeriods appears to have the same values but for some
|
||||
@@ -537,7 +537,7 @@ public class DomainBaseSqlTest {
|
||||
|
||||
// Verify that the DomainContent object from the history record sets the fields correctly.
|
||||
DomainHistory persistedHistoryEntry =
|
||||
jpaTm().transact(() -> jpaTm().load(historyEntry.createVKey()));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(historyEntry.createVKey()));
|
||||
assertThat(persistedHistoryEntry.getDomainContent().get().getAutorenewPollMessage())
|
||||
.isEqualTo(domain.getAutorenewPollMessage());
|
||||
assertThat(persistedHistoryEntry.getDomainContent().get().getAutorenewBillingEvent())
|
||||
@@ -667,7 +667,7 @@ public class DomainBaseSqlTest {
|
||||
});
|
||||
|
||||
// Store the existing BillingRecurrence VKey. This happens after the event has been persisted.
|
||||
DomainBase persisted = jpaTm().transact(() -> jpaTm().load(domain.createVKey()));
|
||||
DomainBase persisted = jpaTm().transact(() -> jpaTm().loadByKey(domain.createVKey()));
|
||||
|
||||
// Verify that the domain data has been persisted.
|
||||
// dsData still isn't persisted. gracePeriods appears to have the same values but for some
|
||||
@@ -676,7 +676,7 @@ public class DomainBaseSqlTest {
|
||||
|
||||
// Verify that the DomainContent object from the history record sets the fields correctly.
|
||||
DomainHistory persistedHistoryEntry =
|
||||
jpaTm().transact(() -> jpaTm().load(historyEntry.createVKey()));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(historyEntry.createVKey()));
|
||||
assertThat(persistedHistoryEntry.getDomainContent().get().getAutorenewPollMessage())
|
||||
.isEqualTo(domain.getAutorenewPollMessage());
|
||||
assertThat(persistedHistoryEntry.getDomainContent().get().getAutorenewBillingEvent())
|
||||
|
||||
@@ -78,7 +78,8 @@ public class AllocationTokenTest extends EntityTestCase {
|
||||
.put(DateTime.now(UTC).plusWeeks(8), TokenStatus.ENDED)
|
||||
.build())
|
||||
.build());
|
||||
assertThat(transactIfJpaTm(() -> tm().load(unlimitedUseToken))).isEqualTo(unlimitedUseToken);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(unlimitedUseToken)))
|
||||
.isEqualTo(unlimitedUseToken);
|
||||
|
||||
DomainBase domain = persistActiveDomain("example.foo");
|
||||
Key<HistoryEntry> historyEntryKey = Key.create(Key.create(domain), HistoryEntry.class, 1);
|
||||
@@ -91,7 +92,7 @@ public class AllocationTokenTest extends EntityTestCase {
|
||||
.setCreationTimeForTest(DateTime.parse("2010-11-12T05:00:00Z"))
|
||||
.setTokenType(SINGLE_USE)
|
||||
.build());
|
||||
assertThat(transactIfJpaTm(() -> tm().load(singleUseToken))).isEqualTo(singleUseToken);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadByEntity(singleUseToken))).isEqualTo(singleUseToken);
|
||||
}
|
||||
|
||||
@TestOfyOnly
|
||||
|
||||
@@ -46,13 +46,13 @@ public class ContactHistoryTest extends EntityTestCase {
|
||||
ContactResource contact = newContactResourceWithRoid("contactId", "contact1");
|
||||
jpaTm().transact(() -> jpaTm().insert(contact));
|
||||
VKey<ContactResource> contactVKey = contact.createVKey();
|
||||
ContactResource contactFromDb = jpaTm().transact(() -> jpaTm().load(contactVKey));
|
||||
ContactResource contactFromDb = jpaTm().transact(() -> jpaTm().loadByKey(contactVKey));
|
||||
ContactHistory contactHistory = createContactHistory(contactFromDb, contact.getRepoId());
|
||||
jpaTm().transact(() -> jpaTm().insert(contactHistory));
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
ContactHistory fromDatabase = jpaTm().load(contactHistory.createVKey());
|
||||
ContactHistory fromDatabase = jpaTm().loadByKey(contactHistory.createVKey());
|
||||
assertContactHistoriesEqual(fromDatabase, contactHistory);
|
||||
assertThat(fromDatabase.getParentVKey()).isEqualTo(contactHistory.getParentVKey());
|
||||
});
|
||||
@@ -65,7 +65,7 @@ public class ContactHistoryTest extends EntityTestCase {
|
||||
ContactResource contact = newContactResourceWithRoid("contactId", "contact1");
|
||||
jpaTm().transact(() -> jpaTm().insert(contact));
|
||||
VKey<ContactResource> contactVKey = contact.createVKey();
|
||||
ContactResource contactFromDb = jpaTm().transact(() -> jpaTm().load(contactVKey));
|
||||
ContactResource contactFromDb = jpaTm().transact(() -> jpaTm().loadByKey(contactVKey));
|
||||
ContactHistory contactHistory =
|
||||
createContactHistory(contactFromDb, contact.getRepoId())
|
||||
.asBuilder()
|
||||
@@ -76,7 +76,7 @@ public class ContactHistoryTest extends EntityTestCase {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
ContactHistory fromDatabase = jpaTm().load(contactHistory.createVKey());
|
||||
ContactHistory fromDatabase = jpaTm().loadByKey(contactHistory.createVKey());
|
||||
assertContactHistoriesEqual(fromDatabase, contactHistory);
|
||||
assertThat(fromDatabase.getParentVKey()).isEqualTo(contactHistory.getParentVKey());
|
||||
});
|
||||
@@ -89,7 +89,7 @@ public class ContactHistoryTest extends EntityTestCase {
|
||||
ContactResource contact = newContactResourceWithRoid("contactId", "contact1");
|
||||
tm().transact(() -> tm().insert(contact));
|
||||
VKey<ContactResource> contactVKey = contact.createVKey();
|
||||
ContactResource contactFromDb = tm().transact(() -> tm().load(contactVKey));
|
||||
ContactResource contactFromDb = tm().transact(() -> tm().loadByKey(contactVKey));
|
||||
fakeClock.advanceOneMilli();
|
||||
ContactHistory contactHistory = createContactHistory(contactFromDb, contact.getRepoId());
|
||||
tm().transact(() -> tm().insert(contactHistory));
|
||||
@@ -100,8 +100,8 @@ public class ContactHistoryTest extends EntityTestCase {
|
||||
VKey<ContactHistory> contactHistoryVKey = contactHistory.createVKey();
|
||||
VKey<HistoryEntry> historyEntryVKey =
|
||||
VKey.createOfy(HistoryEntry.class, Key.create(contactHistory.asHistoryEntry()));
|
||||
ContactHistory hostHistoryFromDb = tm().transact(() -> tm().load(contactHistoryVKey));
|
||||
HistoryEntry historyEntryFromDb = tm().transact(() -> tm().load(historyEntryVKey));
|
||||
ContactHistory hostHistoryFromDb = tm().transact(() -> tm().loadByKey(contactHistoryVKey));
|
||||
HistoryEntry historyEntryFromDb = tm().transact(() -> tm().loadByKey(historyEntryVKey));
|
||||
|
||||
assertThat(hostHistoryFromDb).isEqualTo(historyEntryFromDb);
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class DomainHistoryTest extends EntityTestCase {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainHistory fromDatabase = jpaTm().load(domainHistory.createVKey());
|
||||
DomainHistory fromDatabase = jpaTm().loadByKey(domainHistory.createVKey());
|
||||
assertDomainHistoriesEqual(fromDatabase, domainHistory);
|
||||
assertThat(fromDatabase.getParentVKey()).isEqualTo(domainHistory.getParentVKey());
|
||||
});
|
||||
@@ -87,7 +87,7 @@ public class DomainHistoryTest extends EntityTestCase {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
DomainHistory fromDatabase = jpaTm().load(domainHistory.createVKey());
|
||||
DomainHistory fromDatabase = jpaTm().loadByKey(domainHistory.createVKey());
|
||||
assertDomainHistoriesEqual(fromDatabase, domainHistory);
|
||||
assertThat(fromDatabase.getParentVKey()).isEqualTo(domainHistory.getParentVKey());
|
||||
assertThat(fromDatabase.getNsHosts())
|
||||
@@ -125,8 +125,8 @@ public class DomainHistoryTest extends EntityTestCase {
|
||||
VKey<DomainHistory> domainHistoryVKey = domainHistory.createVKey();
|
||||
VKey<HistoryEntry> historyEntryVKey =
|
||||
VKey.createOfy(HistoryEntry.class, Key.create(domainHistory.asHistoryEntry()));
|
||||
DomainHistory domainHistoryFromDb = tm().transact(() -> tm().load(domainHistoryVKey));
|
||||
HistoryEntry historyEntryFromDb = tm().transact(() -> tm().load(historyEntryVKey));
|
||||
DomainHistory domainHistoryFromDb = tm().transact(() -> tm().loadByKey(domainHistoryVKey));
|
||||
HistoryEntry historyEntryFromDb = tm().transact(() -> tm().loadByKey(historyEntryVKey));
|
||||
|
||||
assertThat(domainHistoryFromDb).isEqualTo(historyEntryFromDb);
|
||||
}
|
||||
@@ -183,13 +183,13 @@ public class DomainHistoryTest extends EntityTestCase {
|
||||
|
||||
// Load the DomainHistory object from the datastore.
|
||||
VKey<DomainHistory> domainHistoryVKey = domainHistory.createVKey();
|
||||
DomainHistory domainHistoryFromDb = tm().transact(() -> tm().load(domainHistoryVKey));
|
||||
DomainHistory domainHistoryFromDb = tm().transact(() -> tm().loadByKey(domainHistoryVKey));
|
||||
|
||||
// attempt to write to SQL.
|
||||
jpaTm().transact(() -> jpaTm().insert(domainHistoryFromDb));
|
||||
|
||||
// Reload and rewrite.
|
||||
DomainHistory domainHistoryFromDb2 = tm().transact(() -> tm().load(domainHistoryVKey));
|
||||
DomainHistory domainHistoryFromDb2 = tm().transact(() -> tm().loadByKey(domainHistoryVKey));
|
||||
jpaTm().transact(() -> jpaTm().put(domainHistoryFromDb2));
|
||||
}
|
||||
|
||||
|
||||
@@ -47,13 +47,13 @@ public class HostHistoryTest extends EntityTestCase {
|
||||
jpaTm().transact(() -> jpaTm().insert(host));
|
||||
VKey<HostResource> hostVKey =
|
||||
VKey.create(HostResource.class, "host1", Key.create(HostResource.class, "host1"));
|
||||
HostResource hostFromDb = jpaTm().transact(() -> jpaTm().load(hostVKey));
|
||||
HostResource hostFromDb = jpaTm().transact(() -> jpaTm().loadByKey(hostVKey));
|
||||
HostHistory hostHistory = createHostHistory(hostFromDb, host.getRepoId());
|
||||
jpaTm().transact(() -> jpaTm().insert(hostHistory));
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
HostHistory fromDatabase = jpaTm().load(hostHistory.createVKey());
|
||||
HostHistory fromDatabase = jpaTm().loadByKey(hostHistory.createVKey());
|
||||
assertHostHistoriesEqual(fromDatabase, hostHistory);
|
||||
assertThat(fromDatabase.getParentVKey()).isEqualTo(hostHistory.getParentVKey());
|
||||
});
|
||||
@@ -65,7 +65,7 @@ public class HostHistoryTest extends EntityTestCase {
|
||||
HostResource host = newHostResourceWithRoid("ns1.example.com", "host1");
|
||||
jpaTm().transact(() -> jpaTm().insert(host));
|
||||
|
||||
HostResource hostFromDb = jpaTm().transact(() -> jpaTm().load(host.createVKey()));
|
||||
HostResource hostFromDb = jpaTm().transact(() -> jpaTm().loadByKey(host.createVKey()));
|
||||
HostHistory hostHistory =
|
||||
createHostHistory(hostFromDb, host.getRepoId()).asBuilder().setHostBase(null).build();
|
||||
jpaTm().transact(() -> jpaTm().insert(hostHistory));
|
||||
@@ -73,7 +73,7 @@ public class HostHistoryTest extends EntityTestCase {
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
HostHistory fromDatabase = jpaTm().load(hostHistory.createVKey());
|
||||
HostHistory fromDatabase = jpaTm().loadByKey(hostHistory.createVKey());
|
||||
assertHostHistoriesEqual(fromDatabase, hostHistory);
|
||||
assertThat(fromDatabase.getParentVKey()).isEqualTo(hostHistory.getParentVKey());
|
||||
});
|
||||
@@ -87,7 +87,7 @@ public class HostHistoryTest extends EntityTestCase {
|
||||
tm().transact(() -> tm().insert(host));
|
||||
VKey<HostResource> hostVKey =
|
||||
VKey.create(HostResource.class, "host1", Key.create(HostResource.class, "host1"));
|
||||
HostResource hostFromDb = tm().transact(() -> tm().load(hostVKey));
|
||||
HostResource hostFromDb = tm().transact(() -> tm().loadByKey(hostVKey));
|
||||
HostHistory hostHistory = createHostHistory(hostFromDb, host.getRepoId());
|
||||
fakeClock.advanceOneMilli();
|
||||
tm().transact(() -> tm().insert(hostHistory));
|
||||
@@ -98,8 +98,8 @@ public class HostHistoryTest extends EntityTestCase {
|
||||
VKey<HostHistory> hostHistoryVKey = hostHistory.createVKey();
|
||||
VKey<HistoryEntry> historyEntryVKey =
|
||||
VKey.createOfy(HistoryEntry.class, Key.create(hostHistory.asHistoryEntry()));
|
||||
HostHistory hostHistoryFromDb = tm().transact(() -> tm().load(hostHistoryVKey));
|
||||
HistoryEntry historyEntryFromDb = tm().transact(() -> tm().load(historyEntryVKey));
|
||||
HostHistory hostHistoryFromDb = tm().transact(() -> tm().loadByKey(hostHistoryVKey));
|
||||
HistoryEntry historyEntryFromDb = tm().transact(() -> tm().loadByKey(historyEntryVKey));
|
||||
|
||||
assertThat(hostHistoryFromDb).isEqualTo(historyEntryFromDb);
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ public class LegacyHistoryObjectTest extends EntityTestCase {
|
||||
.transact(
|
||||
() ->
|
||||
ofyTm()
|
||||
.load(
|
||||
.loadByKey(
|
||||
VKey.create(
|
||||
HistoryEntry.class,
|
||||
historyEntryId,
|
||||
@@ -85,7 +85,7 @@ public class LegacyHistoryObjectTest extends EntityTestCase {
|
||||
jpaTm().insert(legacyContactHistory);
|
||||
});
|
||||
ContactHistory legacyHistoryFromSql =
|
||||
jpaTm().transact(() -> jpaTm().load(legacyContactHistory.createVKey()));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(legacyContactHistory.createVKey()));
|
||||
assertAboutImmutableObjects()
|
||||
.that(legacyContactHistory)
|
||||
.isEqualExceptFields(legacyHistoryFromSql);
|
||||
@@ -109,7 +109,7 @@ public class LegacyHistoryObjectTest extends EntityTestCase {
|
||||
.transact(
|
||||
() ->
|
||||
ofyTm()
|
||||
.load(
|
||||
.loadByKey(
|
||||
VKey.create(
|
||||
HistoryEntry.class,
|
||||
historyEntryId,
|
||||
@@ -130,7 +130,7 @@ public class LegacyHistoryObjectTest extends EntityTestCase {
|
||||
// Next, save that from-Datastore object in SQL and verify we can load it back in
|
||||
jpaTm().transact(() -> jpaTm().insert(legacyDomainHistory));
|
||||
DomainHistory legacyHistoryFromSql =
|
||||
jpaTm().transact(() -> jpaTm().load(legacyDomainHistory.createVKey()));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(legacyDomainHistory.createVKey()));
|
||||
// Don't compare nsHosts directly because one is null and the other is empty
|
||||
assertAboutImmutableObjects()
|
||||
.that(legacyDomainHistory)
|
||||
@@ -161,7 +161,7 @@ public class LegacyHistoryObjectTest extends EntityTestCase {
|
||||
.transact(
|
||||
() ->
|
||||
ofyTm()
|
||||
.load(
|
||||
.loadByKey(
|
||||
VKey.create(
|
||||
HistoryEntry.class,
|
||||
historyEntryId,
|
||||
@@ -181,7 +181,7 @@ public class LegacyHistoryObjectTest extends EntityTestCase {
|
||||
jpaTm().insert(legacyHostHistory);
|
||||
});
|
||||
HostHistory legacyHistoryFromSql =
|
||||
jpaTm().transact(() -> jpaTm().load(legacyHostHistory.createVKey()));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(legacyHostHistory.createVKey()));
|
||||
assertAboutImmutableObjects().that(legacyHostHistory).isEqualExceptFields(legacyHistoryFromSql);
|
||||
// can't compare hostRepoId directly since it doesn't save the ofy key in SQL
|
||||
assertThat(legacyHostHistory.getParentVKey().getSqlKey())
|
||||
|
||||
@@ -93,7 +93,7 @@ class HostResourceTest extends EntityTestCase {
|
||||
void testPersistence() {
|
||||
HostResource newHost = host.asBuilder().setRepoId("NEWHOST").build();
|
||||
tm().transact(() -> tm().insert(newHost));
|
||||
assertThat(ImmutableList.of(tm().transact(() -> tm().load(newHost.createVKey()))))
|
||||
assertThat(ImmutableList.of(tm().transact(() -> tm().loadByKey(newHost.createVKey()))))
|
||||
.comparingElementsUsing(immutableObjectCorrespondence("revisions"))
|
||||
.containsExactly(newHost);
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ class ForeignKeyIndexTest extends EntityTestCase {
|
||||
HostResource host = persistActiveHost("ns1.example.com");
|
||||
ForeignKeyIndex<HostResource> fki =
|
||||
ForeignKeyIndex.load(HostResource.class, "ns1.example.com", fakeClock.nowUtc());
|
||||
assertThat(tm().load(fki.getResourceKey())).isEqualTo(host);
|
||||
assertThat(tm().loadByKey(fki.getResourceKey())).isEqualTo(host);
|
||||
assertThat(fki.getDeletionTime()).isEqualTo(END_OF_TIME);
|
||||
}
|
||||
|
||||
|
||||
@@ -93,13 +93,16 @@ public class PollMessageTest extends EntityTestCase {
|
||||
void testCloudSqlSupportForPolymorphicVKey() {
|
||||
jpaTm().transact(() -> jpaTm().insert(oneTime));
|
||||
PollMessage persistedOneTime =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(PollMessage.class, oneTime.getId())));
|
||||
jpaTm()
|
||||
.transact(() -> jpaTm().loadByKey(VKey.createSql(PollMessage.class, oneTime.getId())));
|
||||
assertThat(persistedOneTime).isInstanceOf(PollMessage.OneTime.class);
|
||||
assertThat(persistedOneTime).isEqualTo(oneTime);
|
||||
|
||||
jpaTm().transact(() -> jpaTm().insert(autoRenew));
|
||||
PollMessage persistedAutoRenew =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(PollMessage.class, autoRenew.getId())));
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> jpaTm().loadByKey(VKey.createSql(PollMessage.class, autoRenew.getId())));
|
||||
assertThat(persistedAutoRenew).isInstanceOf(PollMessage.Autorenew.class);
|
||||
assertThat(persistedAutoRenew).isEqualTo(autoRenew);
|
||||
}
|
||||
@@ -114,7 +117,7 @@ public class PollMessageTest extends EntityTestCase {
|
||||
.setMsg("Test poll message")
|
||||
.setParent(historyEntry)
|
||||
.build());
|
||||
assertThat(tm().transact(() -> tm().load(pollMessage))).isEqualTo(pollMessage);
|
||||
assertThat(tm().transact(() -> tm().loadByEntity(pollMessage))).isEqualTo(pollMessage);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
@@ -129,7 +132,7 @@ public class PollMessageTest extends EntityTestCase {
|
||||
.setAutorenewEndTime(fakeClock.nowUtc().plusDays(365))
|
||||
.setTargetId("foobar.foo")
|
||||
.build());
|
||||
assertThat(tm().transact(() -> tm().load(pollMessage))).isEqualTo(pollMessage);
|
||||
assertThat(tm().transact(() -> tm().loadByEntity(pollMessage))).isEqualTo(pollMessage);
|
||||
}
|
||||
|
||||
@TestOfyOnly
|
||||
|
||||
@@ -131,7 +131,7 @@ class RegistrarTest extends EntityTestCase {
|
||||
|
||||
@TestOfyAndSql
|
||||
void testPersistence() {
|
||||
assertThat(tm().transact(() -> tm().load(registrar.createVKey()))).isEqualTo(registrar);
|
||||
assertThat(tm().transact(() -> tm().loadByKey(registrar.createVKey()))).isEqualTo(registrar);
|
||||
}
|
||||
|
||||
@TestOfyOnly
|
||||
@@ -190,18 +190,18 @@ class RegistrarTest extends EntityTestCase {
|
||||
fakeClock.advanceOneMilli();
|
||||
registrar = registrar.asBuilder().setClientCertificate(SAMPLE_CERT, fakeClock.nowUtc()).build();
|
||||
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
|
||||
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT);
|
||||
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT_HASH);
|
||||
assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT);
|
||||
assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT_HASH);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void testDeleteCertificateHash_alsoDeletesHash() {
|
||||
assertThat(registrar.getClientCertificateHash()).isNotNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isPresent();
|
||||
fakeClock.advanceOneMilli();
|
||||
registrar = registrar.asBuilder().setClientCertificate(null, fakeClock.nowUtc()).build();
|
||||
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getClientCertificateHash()).isEmpty();
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
@@ -213,21 +213,21 @@ class RegistrarTest extends EntityTestCase {
|
||||
.setFailoverClientCertificate(SAMPLE_CERT2, fakeClock.nowUtc())
|
||||
.build();
|
||||
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT2);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT2_HASH);
|
||||
assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT2);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT2_HASH);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void testDeleteFailoverCertificateHash_alsoDeletesHash() {
|
||||
registrar =
|
||||
registrar.asBuilder().setFailoverClientCertificate(SAMPLE_CERT, fakeClock.nowUtc()).build();
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isNotNull();
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isPresent();
|
||||
fakeClock.advanceOneMilli();
|
||||
registrar =
|
||||
registrar.asBuilder().setFailoverClientCertificate(null, fakeClock.nowUtc()).build();
|
||||
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isEmpty();
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
|
||||
@@ -70,14 +70,15 @@ public class RegistryTest extends EntityTestCase {
|
||||
Registry registry =
|
||||
Registry.get("tld").asBuilder().setReservedLists(rl15).setPremiumList(pl).build();
|
||||
tm().transact(() -> tm().put(registry));
|
||||
Registry persisted = tm().transact(() -> tm().load(Registry.createVKey(registry.tldStrId)));
|
||||
Registry persisted =
|
||||
tm().transact(() -> tm().loadByKey(Registry.createVKey(registry.tldStrId)));
|
||||
assertThat(persisted).isEqualTo(registry);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void testPersistence() {
|
||||
assertWithMessage("Registry not found").that(Registry.get("tld")).isNotNull();
|
||||
assertThat(tm().transact(() -> tm().load(Registry.createVKey("tld"))))
|
||||
assertThat(tm().transact(() -> tm().loadByKey(Registry.createVKey("tld"))))
|
||||
.isEqualTo(Registry.get("tld"));
|
||||
}
|
||||
|
||||
@@ -162,7 +163,7 @@ public class RegistryTest extends EntityTestCase {
|
||||
.containsExactlyElementsIn(
|
||||
tm().transact(
|
||||
() ->
|
||||
tm().load(
|
||||
tm().loadByKeys(
|
||||
ImmutableSet.of(
|
||||
Registry.createVKey("foo"), Registry.createVKey("tld"))))
|
||||
.values());
|
||||
|
||||
@@ -118,7 +118,7 @@ public class Spec11ThreatMatchTest extends EntityTestCase {
|
||||
});
|
||||
|
||||
VKey<Spec11ThreatMatch> threatVKey = VKey.createSql(Spec11ThreatMatch.class, threat.getId());
|
||||
Spec11ThreatMatch persistedThreat = jpaTm().transact(() -> jpaTm().load(threatVKey));
|
||||
Spec11ThreatMatch persistedThreat = jpaTm().transact(() -> jpaTm().loadByKey(threatVKey));
|
||||
|
||||
// Threat object saved for the first time doesn't have an ID; it is generated by SQL
|
||||
threat.id = persistedThreat.id;
|
||||
|
||||
@@ -64,7 +64,7 @@ class BillingVKeyTest {
|
||||
|
||||
BillingVKeyTestEntity original = new BillingVKeyTestEntity(oneTimeVKey, recurringVKey);
|
||||
tm().transact(() -> tm().insert(original));
|
||||
BillingVKeyTestEntity persisted = tm().transact(() -> tm().load(original.createVKey()));
|
||||
BillingVKeyTestEntity persisted = tm().transact(() -> tm().loadByKey(original.createVKey()));
|
||||
|
||||
assertThat(persisted).isEqualTo(original);
|
||||
assertThat(persisted.getBillingEventVKey()).isEqualTo(oneTimeVKey);
|
||||
@@ -75,7 +75,7 @@ class BillingVKeyTest {
|
||||
void testHandleNullVKeyCorrectly() {
|
||||
BillingVKeyTestEntity original = new BillingVKeyTestEntity(null, null);
|
||||
tm().transact(() -> tm().insert(original));
|
||||
BillingVKeyTestEntity persisted = tm().transact(() -> tm().load(original.createVKey()));
|
||||
BillingVKeyTestEntity persisted = tm().transact(() -> tm().loadByKey(original.createVKey()));
|
||||
|
||||
assertThat(persisted).isEqualTo(original);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ class DomainHistoryVKeyTest {
|
||||
DomainHistoryVKey domainHistoryVKey = DomainHistoryVKey.create(ofyKey);
|
||||
TestEntity original = new TestEntity(domainHistoryVKey);
|
||||
tm().transact(() -> tm().insert(original));
|
||||
TestEntity persisted = tm().transact(() -> tm().load(original.createVKey()));
|
||||
TestEntity persisted = tm().transact(() -> tm().loadByKey(original.createVKey()));
|
||||
assertThat(persisted).isEqualTo(original);
|
||||
// Double check that the persisted.domainHistoryVKey is a symmetric VKey
|
||||
assertThat(persisted.domainHistoryVKey.createOfyKey())
|
||||
|
||||
@@ -66,14 +66,14 @@ class EntityCallbacksListenerTest {
|
||||
checkAll(updated, 0, 1, 0, 1);
|
||||
|
||||
TestEntity testLoad =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(TestEntity.class, "id")));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(VKey.createSql(TestEntity.class, "id")));
|
||||
checkAll(testLoad, 0, 0, 0, 1);
|
||||
|
||||
TestEntity testRemove =
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> {
|
||||
TestEntity removed = jpaTm().load(VKey.createSql(TestEntity.class, "id"));
|
||||
TestEntity removed = jpaTm().loadByKey(VKey.createSql(TestEntity.class, "id"));
|
||||
jpaTm().getEntityManager().remove(removed);
|
||||
return removed;
|
||||
});
|
||||
|
||||
@@ -15,10 +15,24 @@
|
||||
package google.registry.persistence;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
|
||||
import dagger.Component;
|
||||
import google.registry.beam.initsql.BeamJpaModule;
|
||||
import google.registry.config.CredentialModule;
|
||||
import google.registry.config.RegistryConfig.Config;
|
||||
import google.registry.config.RegistryConfig.ConfigModule;
|
||||
import google.registry.keyring.kms.KmsModule;
|
||||
import google.registry.persistence.PersistenceModule.TransactionIsolationLevel;
|
||||
import google.registry.privileges.secretmanager.SecretManagerModule;
|
||||
import google.registry.testing.DatastoreEntityExtension;
|
||||
import google.registry.util.UtilsModule;
|
||||
import java.util.Optional;
|
||||
import javax.inject.Provider;
|
||||
import javax.inject.Singleton;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import org.hibernate.cfg.Environment;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -29,7 +43,7 @@ import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
/** Unit tests for {@link PersistenceModule}. */
|
||||
@Testcontainers
|
||||
public class PersistenceModuleTest {
|
||||
class PersistenceModuleTest {
|
||||
|
||||
@Container
|
||||
private final PostgreSQLContainer database =
|
||||
@@ -64,4 +78,61 @@ public class PersistenceModuleTest {
|
||||
assertThat(em.isOpen()).isTrue();
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void appengineIsolation() {
|
||||
assertThat(PersistenceModule.provideDefaultDatabaseConfigs().get(Environment.ISOLATION))
|
||||
.isEqualTo(TransactionIsolationLevel.TRANSACTION_SERIALIZABLE.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void beamIsolation_default() {
|
||||
Optional<Provider<TransactionIsolationLevel>> injected =
|
||||
DaggerPersistenceModuleTest_BeamConfigTestComponent.builder()
|
||||
.beamJpaModule(new BeamJpaModule(null, null))
|
||||
.build()
|
||||
.getIsolationOverride();
|
||||
assertThat(injected).isNotNull();
|
||||
assertThat(injected.get().get()).isNull();
|
||||
assertThat(
|
||||
PersistenceModule.provideBeamPipelineCloudSqlConfigs(
|
||||
"", "", PersistenceModule.provideDefaultDatabaseConfigs(), injected)
|
||||
.get(Environment.ISOLATION))
|
||||
.isEqualTo(TransactionIsolationLevel.TRANSACTION_SERIALIZABLE.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void beamIsolation_override() {
|
||||
Optional<Provider<TransactionIsolationLevel>> injected =
|
||||
DaggerPersistenceModuleTest_BeamConfigTestComponent.builder()
|
||||
.beamJpaModule(
|
||||
new BeamJpaModule(
|
||||
null, null, TransactionIsolationLevel.TRANSACTION_READ_UNCOMMITTED))
|
||||
.build()
|
||||
.getIsolationOverride();
|
||||
assertThat(injected).isNotNull();
|
||||
assertThat(injected.get().get())
|
||||
.isEqualTo(TransactionIsolationLevel.TRANSACTION_READ_UNCOMMITTED);
|
||||
assertThat(
|
||||
PersistenceModule.provideBeamPipelineCloudSqlConfigs(
|
||||
"", "", PersistenceModule.provideDefaultDatabaseConfigs(), injected)
|
||||
.get(Environment.ISOLATION))
|
||||
.isEqualTo(TransactionIsolationLevel.TRANSACTION_READ_UNCOMMITTED.name());
|
||||
}
|
||||
|
||||
@Singleton
|
||||
@Component(
|
||||
modules = {
|
||||
BeamJpaModule.class,
|
||||
ConfigModule.class,
|
||||
CredentialModule.class,
|
||||
KmsModule.class,
|
||||
PersistenceModule.class,
|
||||
SecretManagerModule.class,
|
||||
UtilsModule.class
|
||||
})
|
||||
public interface BeamConfigTestComponent {
|
||||
@Config("beamIsolationOverride")
|
||||
Optional<Provider<TransactionIsolationLevel>> getIsolationOverride();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -65,7 +65,9 @@ public class InetAddressSetConverterTest {
|
||||
InetAddressSetTestEntity testEntity = new InetAddressSetTestEntity(inetAddresses);
|
||||
jpaTm().transact(() -> jpaTm().insert(testEntity));
|
||||
InetAddressSetTestEntity persisted =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(InetAddressSetTestEntity.class, "id")));
|
||||
jpaTm()
|
||||
.transact(
|
||||
() -> jpaTm().loadByKey(VKey.createSql(InetAddressSetTestEntity.class, "id")));
|
||||
assertThat(persisted.addresses).isEqualTo(inetAddresses);
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -57,7 +57,8 @@ public class LocalDateConverterTest {
|
||||
jpaTm().transact(() -> jpaTm().insert(entity));
|
||||
LocalDateConverterTestEntity retrievedEntity =
|
||||
jpaTm()
|
||||
.transact(() -> jpaTm().load(VKey.createSql(LocalDateConverterTestEntity.class, "id")));
|
||||
.transact(
|
||||
() -> jpaTm().loadByKey(VKey.createSql(LocalDateConverterTestEntity.class, "id")));
|
||||
return retrievedEntity;
|
||||
}
|
||||
|
||||
|
||||
+36
-33
@@ -136,7 +136,7 @@ class JpaTransactionManagerImplTest {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(theEntity));
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isTrue();
|
||||
assertThat(jpaTm().transact(() -> jpaTm().load(theEntityKey))).isEqualTo(theEntity);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey))).isEqualTo(theEntity);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -200,20 +200,20 @@ class JpaTransactionManagerImplTest {
|
||||
@Test
|
||||
void transactNewReadOnly_retriesJdbcConnectionExceptions() {
|
||||
JpaTransactionManager spyJpaTm = spy(jpaTm());
|
||||
doThrow(JDBCConnectionException.class).when(spyJpaTm).load(any(VKey.class));
|
||||
doThrow(JDBCConnectionException.class).when(spyJpaTm).loadByKey(any(VKey.class));
|
||||
spyJpaTm.transact(() -> spyJpaTm.insert(theEntity));
|
||||
assertThrows(
|
||||
JDBCConnectionException.class,
|
||||
() -> spyJpaTm.transactNewReadOnly(() -> spyJpaTm.load(theEntityKey)));
|
||||
verify(spyJpaTm, times(3)).load(theEntityKey);
|
||||
() -> spyJpaTm.transactNewReadOnly(() -> spyJpaTm.loadByKey(theEntityKey)));
|
||||
verify(spyJpaTm, times(3)).loadByKey(theEntityKey);
|
||||
Supplier<Runnable> supplier =
|
||||
() -> {
|
||||
Runnable work = () -> spyJpaTm.load(theEntityKey);
|
||||
Runnable work = () -> spyJpaTm.loadByKey(theEntityKey);
|
||||
work.run();
|
||||
return null;
|
||||
};
|
||||
assertThrows(JDBCConnectionException.class, () -> spyJpaTm.transactNewReadOnly(supplier));
|
||||
verify(spyJpaTm, times(6)).load(theEntityKey);
|
||||
verify(spyJpaTm, times(6)).loadByKey(theEntityKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -223,31 +223,31 @@ class JpaTransactionManagerImplTest {
|
||||
new RuntimeException()
|
||||
.initCause(new JDBCConnectionException("connection exception", new SQLException())))
|
||||
.when(spyJpaTm)
|
||||
.load(any(VKey.class));
|
||||
.loadByKey(any(VKey.class));
|
||||
spyJpaTm.transact(() -> spyJpaTm.insert(theEntity));
|
||||
assertThrows(
|
||||
RuntimeException.class,
|
||||
() -> spyJpaTm.transactNewReadOnly(() -> spyJpaTm.load(theEntityKey)));
|
||||
verify(spyJpaTm, times(3)).load(theEntityKey);
|
||||
() -> spyJpaTm.transactNewReadOnly(() -> spyJpaTm.loadByKey(theEntityKey)));
|
||||
verify(spyJpaTm, times(3)).loadByKey(theEntityKey);
|
||||
Supplier<Runnable> supplier =
|
||||
() -> {
|
||||
Runnable work = () -> spyJpaTm.load(theEntityKey);
|
||||
Runnable work = () -> spyJpaTm.loadByKey(theEntityKey);
|
||||
work.run();
|
||||
return null;
|
||||
};
|
||||
assertThrows(RuntimeException.class, () -> spyJpaTm.transactNewReadOnly(supplier));
|
||||
verify(spyJpaTm, times(6)).load(theEntityKey);
|
||||
verify(spyJpaTm, times(6)).loadByKey(theEntityKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doTransactionless_retriesJdbcConnectionExceptions() {
|
||||
JpaTransactionManager spyJpaTm = spy(jpaTm());
|
||||
doThrow(JDBCConnectionException.class).when(spyJpaTm).load(any(VKey.class));
|
||||
doThrow(JDBCConnectionException.class).when(spyJpaTm).loadByKey(any(VKey.class));
|
||||
spyJpaTm.transact(() -> spyJpaTm.insert(theEntity));
|
||||
assertThrows(
|
||||
RuntimeException.class,
|
||||
() -> spyJpaTm.doTransactionless(() -> spyJpaTm.load(theEntityKey)));
|
||||
verify(spyJpaTm, times(3)).load(theEntityKey);
|
||||
() -> spyJpaTm.doTransactionless(() -> spyJpaTm.loadByKey(theEntityKey)));
|
||||
verify(spyJpaTm, times(3)).loadByKey(theEntityKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -255,7 +255,7 @@ class JpaTransactionManagerImplTest {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(theEntity));
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isTrue();
|
||||
assertThat(jpaTm().transact(() -> jpaTm().load(theEntityKey))).isEqualTo(theEntity);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey))).isEqualTo(theEntity);
|
||||
assertThrows(RollbackException.class, () -> jpaTm().transact(() -> jpaTm().insert(theEntity)));
|
||||
}
|
||||
|
||||
@@ -264,7 +264,7 @@ class JpaTransactionManagerImplTest {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(compoundIdEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(compoundIdEntity));
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(compoundIdEntity))).isTrue();
|
||||
assertThat(jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey)))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadByKey(compoundIdEntityKey)))
|
||||
.isEqualTo(compoundIdEntity);
|
||||
}
|
||||
|
||||
@@ -275,7 +275,7 @@ class JpaTransactionManagerImplTest {
|
||||
jpaTm().transact(() -> jpaTm().insertAll(moreEntities));
|
||||
moreEntities.forEach(
|
||||
entity -> assertThat(jpaTm().transact(() -> jpaTm().exists(entity))).isTrue());
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class)))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAllOf(TestEntity.class)))
|
||||
.containsExactlyElementsIn(moreEntities);
|
||||
}
|
||||
|
||||
@@ -296,17 +296,17 @@ class JpaTransactionManagerImplTest {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().put(theEntity));
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isTrue();
|
||||
assertThat(jpaTm().transact(() -> jpaTm().load(theEntityKey))).isEqualTo(theEntity);
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey))).isEqualTo(theEntity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void put_updatesExistingEntity() {
|
||||
jpaTm().transact(() -> jpaTm().insert(theEntity));
|
||||
TestEntity persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey));
|
||||
TestEntity persisted = jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey));
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
theEntity.data = "bar";
|
||||
jpaTm().transact(() -> jpaTm().put(theEntity));
|
||||
persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey));
|
||||
persisted = jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey));
|
||||
assertThat(persisted.data).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ class JpaTransactionManagerImplTest {
|
||||
jpaTm().transact(() -> jpaTm().putAll(moreEntities));
|
||||
moreEntities.forEach(
|
||||
entity -> assertThat(jpaTm().transact(() -> jpaTm().exists(entity))).isTrue());
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class)))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAllOf(TestEntity.class)))
|
||||
.containsExactlyElementsIn(moreEntities);
|
||||
}
|
||||
|
||||
@@ -325,22 +325,22 @@ class JpaTransactionManagerImplTest {
|
||||
void update_succeeds() {
|
||||
jpaTm().transact(() -> jpaTm().insert(theEntity));
|
||||
TestEntity persisted =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(TestEntity.class, "theEntity")));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(VKey.createSql(TestEntity.class, "theEntity")));
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
theEntity.data = "bar";
|
||||
jpaTm().transact(() -> jpaTm().update(theEntity));
|
||||
persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey));
|
||||
persisted = jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey));
|
||||
assertThat(persisted.data).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCompoundIdEntity_succeeds() {
|
||||
jpaTm().transact(() -> jpaTm().insert(compoundIdEntity));
|
||||
TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey));
|
||||
TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().loadByKey(compoundIdEntityKey));
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
compoundIdEntity.data = "bar";
|
||||
jpaTm().transact(() -> jpaTm().update(compoundIdEntity));
|
||||
persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey));
|
||||
persisted = jpaTm().transact(() -> jpaTm().loadByKey(compoundIdEntityKey));
|
||||
assertThat(persisted.data).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@@ -361,7 +361,7 @@ class JpaTransactionManagerImplTest {
|
||||
new TestEntity("entity2", "bar_updated"),
|
||||
new TestEntity("entity3", "qux_updated"));
|
||||
jpaTm().transact(() -> jpaTm().updateAll(updated));
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class)))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAllOf(TestEntity.class)))
|
||||
.containsExactlyElementsIn(updated);
|
||||
}
|
||||
|
||||
@@ -376,7 +376,7 @@ class JpaTransactionManagerImplTest {
|
||||
theEntity);
|
||||
assertThrows(
|
||||
IllegalArgumentException.class, () -> jpaTm().transact(() -> jpaTm().updateAll(updated)));
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class)))
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadAllOf(TestEntity.class)))
|
||||
.containsExactlyElementsIn(moreEntities);
|
||||
}
|
||||
|
||||
@@ -384,7 +384,7 @@ class JpaTransactionManagerImplTest {
|
||||
void load_succeeds() {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(theEntity));
|
||||
TestEntity persisted = jpaTm().transact(() -> jpaTm().load(theEntityKey));
|
||||
TestEntity persisted = jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey));
|
||||
assertThat(persisted.name).isEqualTo("theEntity");
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
}
|
||||
@@ -393,14 +393,15 @@ class JpaTransactionManagerImplTest {
|
||||
void load_throwsOnMissingElement() {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
assertThrows(
|
||||
NoSuchElementException.class, () -> jpaTm().transact(() -> jpaTm().load(theEntityKey)));
|
||||
NoSuchElementException.class,
|
||||
() -> jpaTm().transact(() -> jpaTm().loadByKey(theEntityKey)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maybeLoad_succeeds() {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(theEntity));
|
||||
TestEntity persisted = jpaTm().transact(() -> jpaTm().maybeLoad(theEntityKey).get());
|
||||
TestEntity persisted = jpaTm().transact(() -> jpaTm().loadByKeyIfPresent(theEntityKey).get());
|
||||
assertThat(persisted.name).isEqualTo("theEntity");
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
}
|
||||
@@ -408,14 +409,15 @@ class JpaTransactionManagerImplTest {
|
||||
@Test
|
||||
void maybeLoad_nonExistentObject() {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(theEntity))).isFalse();
|
||||
assertThat(jpaTm().transact(() -> jpaTm().maybeLoad(theEntityKey)).isPresent()).isFalse();
|
||||
assertThat(jpaTm().transact(() -> jpaTm().loadByKeyIfPresent(theEntityKey)).isPresent())
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadCompoundIdEntity_succeeds() {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(compoundIdEntity))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(compoundIdEntity));
|
||||
TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().load(compoundIdEntityKey));
|
||||
TestCompoundIdEntity persisted = jpaTm().transact(() -> jpaTm().loadByKey(compoundIdEntityKey));
|
||||
assertThat(persisted.name).isEqualTo("compoundIdEntity");
|
||||
assertThat(persisted.age).isEqualTo(10);
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
@@ -424,7 +426,8 @@ class JpaTransactionManagerImplTest {
|
||||
@Test
|
||||
void loadAll_succeeds() {
|
||||
jpaTm().transact(() -> jpaTm().insertAll(moreEntities));
|
||||
ImmutableList<TestEntity> persisted = jpaTm().transact(() -> jpaTm().loadAll(TestEntity.class));
|
||||
ImmutableList<TestEntity> persisted =
|
||||
jpaTm().transact(() -> jpaTm().loadAllOf(TestEntity.class));
|
||||
assertThat(persisted).containsExactlyElementsIn(moreEntities);
|
||||
}
|
||||
|
||||
|
||||
+65
-15
@@ -133,7 +133,7 @@ public class TransactionManagerTest {
|
||||
assertEntityNotExist(theEntity);
|
||||
tm().transact(() -> tm().insert(theEntity));
|
||||
assertEntityExists(theEntity);
|
||||
TestEntity persisted = tm().transactNewReadOnly(() -> tm().load(theEntity.key()));
|
||||
TestEntity persisted = tm().transactNewReadOnly(() -> tm().loadByKey(theEntity.key()));
|
||||
assertThat(persisted).isEqualTo(theEntity);
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ public class TransactionManagerTest {
|
||||
assertEntityNotExist(theEntity);
|
||||
tm().transact(() -> tm().insert(theEntity));
|
||||
assertEntityExists(theEntity);
|
||||
assertThat(tm().transact(() -> tm().load(theEntity.key()))).isEqualTo(theEntity);
|
||||
assertThat(tm().transact(() -> tm().loadByKey(theEntity.key()))).isEqualTo(theEntity);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
@@ -165,18 +165,18 @@ public class TransactionManagerTest {
|
||||
assertEntityNotExist(theEntity);
|
||||
tm().transact(() -> tm().put(theEntity));
|
||||
assertEntityExists(theEntity);
|
||||
assertThat(tm().transact(() -> tm().load(theEntity.key()))).isEqualTo(theEntity);
|
||||
assertThat(tm().transact(() -> tm().loadByKey(theEntity.key()))).isEqualTo(theEntity);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void saveNewOrUpdate_updatesExistingEntity() {
|
||||
tm().transact(() -> tm().insert(theEntity));
|
||||
TestEntity persisted = tm().transact(() -> tm().load(theEntity.key()));
|
||||
TestEntity persisted = tm().transact(() -> tm().loadByKey(theEntity.key()));
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
theEntity.data = "bar";
|
||||
fakeClock.advanceOneMilli();
|
||||
tm().transact(() -> tm().put(theEntity));
|
||||
persisted = tm().transact(() -> tm().load(theEntity.key()));
|
||||
persisted = tm().transact(() -> tm().loadByKey(theEntity.key()));
|
||||
assertThat(persisted.data).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@@ -193,13 +193,13 @@ public class TransactionManagerTest {
|
||||
TestEntity persisted =
|
||||
tm().transact(
|
||||
() ->
|
||||
tm().load(
|
||||
tm().loadByKey(
|
||||
VKey.create(TestEntity.class, theEntity.name, Key.create(theEntity))));
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
theEntity.data = "bar";
|
||||
fakeClock.advanceOneMilli();
|
||||
tm().transact(() -> tm().update(theEntity));
|
||||
persisted = tm().transact(() -> tm().load(theEntity.key()));
|
||||
persisted = tm().transact(() -> tm().loadByKey(theEntity.key()));
|
||||
assertThat(persisted.data).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ public class TransactionManagerTest {
|
||||
void load_succeeds() {
|
||||
assertEntityNotExist(theEntity);
|
||||
tm().transact(() -> tm().insert(theEntity));
|
||||
TestEntity persisted = tm().transact(() -> tm().load(theEntity.key()));
|
||||
TestEntity persisted = tm().transact(() -> tm().loadByKey(theEntity.key()));
|
||||
assertThat(persisted.name).isEqualTo("theEntity");
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
}
|
||||
@@ -216,14 +216,14 @@ public class TransactionManagerTest {
|
||||
void load_throwsOnMissingElement() {
|
||||
assertEntityNotExist(theEntity);
|
||||
assertThrows(
|
||||
NoSuchElementException.class, () -> tm().transact(() -> tm().load(theEntity.key())));
|
||||
NoSuchElementException.class, () -> tm().transact(() -> tm().loadByKey(theEntity.key())));
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void maybeLoad_succeeds() {
|
||||
assertEntityNotExist(theEntity);
|
||||
tm().transact(() -> tm().insert(theEntity));
|
||||
TestEntity persisted = tm().transact(() -> tm().maybeLoad(theEntity.key()).get());
|
||||
TestEntity persisted = tm().transact(() -> tm().loadByKeyIfPresent(theEntity.key()).get());
|
||||
assertThat(persisted.name).isEqualTo("theEntity");
|
||||
assertThat(persisted.data).isEqualTo("foo");
|
||||
}
|
||||
@@ -231,7 +231,7 @@ public class TransactionManagerTest {
|
||||
@TestOfyAndSql
|
||||
void maybeLoad_nonExistentObject() {
|
||||
assertEntityNotExist(theEntity);
|
||||
assertThat(tm().transact(() -> tm().maybeLoad(theEntity.key())).isPresent()).isFalse();
|
||||
assertThat(tm().transact(() -> tm().loadByKeyIfPresent(theEntity.key())).isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
@@ -292,7 +292,7 @@ public class TransactionManagerTest {
|
||||
tm().transact(() -> tm().insertAll(moreEntities));
|
||||
List<VKey<TestEntity>> keys =
|
||||
moreEntities.stream().map(TestEntity::key).collect(toImmutableList());
|
||||
assertThat(tm().transact(() -> tm().load(keys)))
|
||||
assertThat(tm().transact(() -> tm().loadByKeys(keys)))
|
||||
.isEqualTo(Maps.uniqueIndex(moreEntities, TestEntity::key));
|
||||
}
|
||||
|
||||
@@ -304,7 +304,7 @@ public class TransactionManagerTest {
|
||||
moreEntities.stream().map(TestEntity::key).collect(toImmutableList());
|
||||
ImmutableList<VKey<TestEntity>> doubleKeys =
|
||||
Stream.concat(keys.stream(), keys.stream()).collect(toImmutableList());
|
||||
assertThat(tm().transact(() -> tm().load(doubleKeys)))
|
||||
assertThat(tm().transact(() -> tm().loadByKeys(doubleKeys)))
|
||||
.isEqualTo(Maps.uniqueIndex(moreEntities, TestEntity::key));
|
||||
}
|
||||
|
||||
@@ -316,16 +316,66 @@ public class TransactionManagerTest {
|
||||
Stream.concat(moreEntities.stream(), Stream.of(new TestEntity("dark", "matter")))
|
||||
.map(TestEntity::key)
|
||||
.collect(toImmutableList());
|
||||
assertThat(tm().transact(() -> tm().load(keys)))
|
||||
assertThat(
|
||||
assertThrows(
|
||||
NoSuchElementException.class, () -> tm().transact(() -> tm().loadByKeys(keys))))
|
||||
.hasMessageThat()
|
||||
.contains("dark");
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void loadExisting_missingKeys() {
|
||||
assertAllEntitiesNotExist(moreEntities);
|
||||
tm().transact(() -> tm().insertAll(moreEntities));
|
||||
List<VKey<TestEntity>> keys =
|
||||
Stream.concat(moreEntities.stream(), Stream.of(new TestEntity("dark", "matter")))
|
||||
.map(TestEntity::key)
|
||||
.collect(toImmutableList());
|
||||
assertThat(tm().transact(() -> tm().loadByKeysIfPresent(keys)))
|
||||
.isEqualTo(Maps.uniqueIndex(moreEntities, TestEntity::key));
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void loadAll_success() {
|
||||
tm().transact(() -> tm().insertAll(moreEntities));
|
||||
assertThat(tm().transact(() -> tm().loadByEntities(moreEntities)))
|
||||
.containsExactlyElementsIn(moreEntities);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void loadAll_missingKeys() {
|
||||
assertAllEntitiesNotExist(moreEntities);
|
||||
tm().transact(() -> tm().insertAll(moreEntities));
|
||||
ImmutableList<TestEntity> nonexistent = ImmutableList.of(new TestEntity("dark", "matter"));
|
||||
assertThat(
|
||||
assertThrows(
|
||||
NoSuchElementException.class,
|
||||
() -> tm().transact(() -> tm().loadByEntities(nonexistent))))
|
||||
.hasMessageThat()
|
||||
.contains("dark");
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
void loadAllExisting_missingKeys() {
|
||||
tm().transact(() -> tm().insertAll(moreEntities));
|
||||
tm().transact(() -> tm().delete(new TestEntity("entity1", "foo")));
|
||||
assertThat(
|
||||
tm().transact(
|
||||
() ->
|
||||
tm().loadByEntitiesIfPresent(moreEntities).stream()
|
||||
.map(TestEntity::key)
|
||||
.map(VKey::getSqlKey)
|
||||
.collect(toImmutableList())))
|
||||
.containsExactly("entity2", "entity3");
|
||||
}
|
||||
|
||||
@TestOfyOnly
|
||||
void loadAllForOfyTm_throwsExceptionInTransaction() {
|
||||
assertAllEntitiesNotExist(moreEntities);
|
||||
tm().transact(() -> tm().insertAll(moreEntities));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class, () -> tm().transact(() -> tm().loadAll(TestEntity.class)));
|
||||
IllegalArgumentException.class,
|
||||
() -> tm().transact(() -> tm().loadAllOf(TestEntity.class)));
|
||||
}
|
||||
|
||||
private static void assertEntityExists(TestEntity entity) {
|
||||
|
||||
@@ -60,8 +60,8 @@ class TransactionTest {
|
||||
ofyTm()
|
||||
.transact(
|
||||
() -> {
|
||||
assertThat(ofyTm().load(fooEntity.key())).isEqualTo(fooEntity);
|
||||
assertThat(ofyTm().load(barEntity.key())).isEqualTo(barEntity);
|
||||
assertThat(ofyTm().loadByKey(fooEntity.key())).isEqualTo(fooEntity);
|
||||
assertThat(ofyTm().loadByKey(barEntity.key())).isEqualTo(barEntity);
|
||||
});
|
||||
|
||||
txn = new Transaction.Builder().addDelete(barEntity.key()).build();
|
||||
@@ -82,7 +82,7 @@ class TransactionTest {
|
||||
ofyTm()
|
||||
.transact(
|
||||
() -> {
|
||||
assertThat(ofyTm().load(fooEntity.key())).isEqualTo(fooEntity);
|
||||
assertThat(ofyTm().loadByKey(fooEntity.key())).isEqualTo(fooEntity);
|
||||
assertThat(ofyTm().exists(barEntity.key())).isEqualTo(false);
|
||||
});
|
||||
}
|
||||
@@ -111,14 +111,14 @@ class TransactionTest {
|
||||
jpaTm().insert(barEntity);
|
||||
});
|
||||
TransactionEntity txnEnt =
|
||||
jpaTm().transact(() -> jpaTm().load(VKey.createSql(TransactionEntity.class, 1L)));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(VKey.createSql(TransactionEntity.class, 1L)));
|
||||
Transaction txn = Transaction.deserialize(txnEnt.contents);
|
||||
txn.writeToDatastore();
|
||||
ofyTm()
|
||||
.transact(
|
||||
() -> {
|
||||
assertThat(ofyTm().load(fooEntity.key())).isEqualTo(fooEntity);
|
||||
assertThat(ofyTm().load(barEntity.key())).isEqualTo(barEntity);
|
||||
assertThat(ofyTm().loadByKey(fooEntity.key())).isEqualTo(fooEntity);
|
||||
assertThat(ofyTm().loadByKey(barEntity.key())).isEqualTo(barEntity);
|
||||
});
|
||||
|
||||
// Verify that no transaction was persisted for the load transaction.
|
||||
|
||||
@@ -67,7 +67,7 @@ class RegistrarContactTest {
|
||||
void testPersistence_succeeds() {
|
||||
jpaTm().transact(() -> jpaTm().insert(testRegistrarPoc));
|
||||
RegistrarContact persisted =
|
||||
jpaTm().transact(() -> jpaTm().load(testRegistrarPoc.createVKey()));
|
||||
jpaTm().transact(() -> jpaTm().loadByKey(testRegistrarPoc.createVKey()));
|
||||
assertThat(persisted).isEqualTo(testRegistrarPoc);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ public class RegistrarDaoTest {
|
||||
@Test
|
||||
void update_worksSuccessfully() {
|
||||
jpaTm().transact(() -> jpaTm().insert(testRegistrar));
|
||||
Registrar persisted = jpaTm().transact(() -> jpaTm().load(registrarKey));
|
||||
Registrar persisted = jpaTm().transact(() -> jpaTm().loadByKey(registrarKey));
|
||||
assertThat(persisted.getRegistrarName()).isEqualTo("registrarName");
|
||||
jpaTm()
|
||||
.transact(
|
||||
@@ -86,7 +86,7 @@ public class RegistrarDaoTest {
|
||||
jpaTm()
|
||||
.update(
|
||||
persisted.asBuilder().setRegistrarName("changedRegistrarName").build()));
|
||||
Registrar updated = jpaTm().transact(() -> jpaTm().load(registrarKey));
|
||||
Registrar updated = jpaTm().transact(() -> jpaTm().loadByKey(registrarKey));
|
||||
assertThat(updated.getRegistrarName()).isEqualTo("changedRegistrarName");
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ public class RegistrarDaoTest {
|
||||
void load_worksSuccessfully() {
|
||||
assertThat(jpaTm().transact(() -> jpaTm().exists(testRegistrar))).isFalse();
|
||||
jpaTm().transact(() -> jpaTm().insert(testRegistrar));
|
||||
Registrar persisted = jpaTm().transact(() -> jpaTm().load(registrarKey));
|
||||
Registrar persisted = jpaTm().transact(() -> jpaTm().loadByKey(registrarKey));
|
||||
|
||||
assertThat(persisted.getClientId()).isEqualTo("registrarId");
|
||||
assertThat(persisted.getRegistrarName()).isEqualTo("registrarName");
|
||||
|
||||
@@ -413,7 +413,7 @@ public class DatabaseHelper {
|
||||
// PremiumListUtils.savePremiumListAndEntries(). Clearing the session cache can help make sure
|
||||
// we always get the same list.
|
||||
tm().clearSessionCache();
|
||||
return transactIfJpaTm(() -> tm().load(premiumList));
|
||||
return transactIfJpaTm(() -> tm().loadByEntity(premiumList));
|
||||
}
|
||||
|
||||
/** Creates and persists a tld. */
|
||||
@@ -673,13 +673,13 @@ public class DatabaseHelper {
|
||||
.build());
|
||||
// Modify the existing autorenew event to reflect the pending transfer.
|
||||
persistResource(
|
||||
tm().load(domain.getAutorenewBillingEvent())
|
||||
tm().loadByKey(domain.getAutorenewBillingEvent())
|
||||
.asBuilder()
|
||||
.setRecurrenceEndTime(expirationTime)
|
||||
.build());
|
||||
// Update the end time of the existing autorenew poll message. We must delete it if it has no
|
||||
// events left in it.
|
||||
PollMessage.Autorenew autorenewPollMessage = tm().load(domain.getAutorenewPollMessage());
|
||||
PollMessage.Autorenew autorenewPollMessage = tm().loadByKey(domain.getAutorenewPollMessage());
|
||||
if (autorenewPollMessage.getEventTime().isBefore(expirationTime)) {
|
||||
persistResource(
|
||||
autorenewPollMessage.asBuilder()
|
||||
@@ -768,22 +768,22 @@ public class DatabaseHelper {
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
Iterables.concat(
|
||||
tm().loadAll(BillingEvent.OneTime.class),
|
||||
tm().loadAll(BillingEvent.Recurring.class),
|
||||
tm().loadAll(BillingEvent.Cancellation.class)));
|
||||
tm().loadAllOf(BillingEvent.OneTime.class),
|
||||
tm().loadAllOf(BillingEvent.Recurring.class),
|
||||
tm().loadAllOf(BillingEvent.Cancellation.class)));
|
||||
}
|
||||
|
||||
private static Iterable<BillingEvent> getBillingEvents(EppResource resource) {
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
Iterables.concat(
|
||||
tm().loadAll(BillingEvent.OneTime.class).stream()
|
||||
tm().loadAllOf(BillingEvent.OneTime.class).stream()
|
||||
.filter(oneTime -> oneTime.getDomainRepoId().equals(resource.getRepoId()))
|
||||
.collect(toImmutableList()),
|
||||
tm().loadAll(BillingEvent.Recurring.class).stream()
|
||||
tm().loadAllOf(BillingEvent.Recurring.class).stream()
|
||||
.filter(recurring -> recurring.getDomainRepoId().equals(resource.getRepoId()))
|
||||
.collect(toImmutableList()),
|
||||
tm().loadAll(BillingEvent.Cancellation.class).stream()
|
||||
tm().loadAllOf(BillingEvent.Cancellation.class).stream()
|
||||
.filter(
|
||||
cancellation -> cancellation.getDomainRepoId().equals(resource.getRepoId()))
|
||||
.collect(toImmutableList())));
|
||||
@@ -860,13 +860,13 @@ public class DatabaseHelper {
|
||||
}
|
||||
|
||||
public static ImmutableList<PollMessage> getPollMessages() {
|
||||
return ImmutableList.copyOf(transactIfJpaTm(() -> tm().loadAll(PollMessage.class)));
|
||||
return ImmutableList.copyOf(transactIfJpaTm(() -> tm().loadAllOf(PollMessage.class)));
|
||||
}
|
||||
|
||||
public static ImmutableList<PollMessage> getPollMessages(String clientId) {
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
tm().loadAll(PollMessage.class).stream()
|
||||
tm().loadAllOf(PollMessage.class).stream()
|
||||
.filter(pollMessage -> pollMessage.getClientId().equals(clientId))
|
||||
.collect(toImmutableList()));
|
||||
}
|
||||
@@ -874,7 +874,7 @@ public class DatabaseHelper {
|
||||
public static ImmutableList<PollMessage> getPollMessages(DomainContent domain) {
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
tm().loadAll(PollMessage.class).stream()
|
||||
tm().loadAllOf(PollMessage.class).stream()
|
||||
.filter(
|
||||
pollMessage ->
|
||||
pollMessage.getParentKey().getParent().getName().equals(domain.getRepoId()))
|
||||
@@ -884,7 +884,7 @@ public class DatabaseHelper {
|
||||
public static ImmutableList<PollMessage> getPollMessages(String clientId, DateTime now) {
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
tm().loadAll(PollMessage.class).stream()
|
||||
tm().loadAllOf(PollMessage.class).stream()
|
||||
.filter(pollMessage -> pollMessage.getClientId().equals(clientId))
|
||||
.filter(
|
||||
pollMessage ->
|
||||
@@ -898,7 +898,7 @@ public class DatabaseHelper {
|
||||
EppResource resource, String clientId, DateTime now) {
|
||||
return transactIfJpaTm(
|
||||
() ->
|
||||
tm().loadAll(PollMessage.class).stream()
|
||||
tm().loadAllOf(PollMessage.class).stream()
|
||||
.filter(
|
||||
pollMessage ->
|
||||
pollMessage
|
||||
@@ -942,7 +942,7 @@ public class DatabaseHelper {
|
||||
}
|
||||
|
||||
public static void assertAllocationTokens(AllocationToken... expectedTokens) {
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAll(AllocationToken.class)))
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAllOf(AllocationToken.class)))
|
||||
.comparingElementsUsing(immutableObjectCorrespondence("updateTimestamp", "creationTime"))
|
||||
.containsExactlyElementsIn(expectedTokens);
|
||||
}
|
||||
@@ -1018,7 +1018,7 @@ public class DatabaseHelper {
|
||||
// (unmarshalling entity protos to POJOs, nulling out empty collections, calling @OnLoad
|
||||
// methods, etc.) which is bypassed for entities loaded from the session cache.
|
||||
tm().clearSessionCache();
|
||||
return transactIfJpaTm(() -> tm().load(resource));
|
||||
return transactIfJpaTm(() -> tm().loadByEntity(resource));
|
||||
}
|
||||
|
||||
/** Persists an EPP resource with the {@link EppResourceIndex} always going into bucket one. */
|
||||
@@ -1037,7 +1037,7 @@ public class DatabaseHelper {
|
||||
});
|
||||
maybeAdvanceClock();
|
||||
tm().clearSessionCache();
|
||||
return transactIfJpaTm(() -> tm().load(resource));
|
||||
return transactIfJpaTm(() -> tm().loadByEntity(resource));
|
||||
}
|
||||
|
||||
public static <R> void persistResources(final Iterable<R> resources) {
|
||||
@@ -1059,7 +1059,7 @@ public class DatabaseHelper {
|
||||
// and not from the transaction's session cache.
|
||||
tm().clearSessionCache();
|
||||
for (R resource : resources) {
|
||||
transactIfJpaTm(() -> tm().load(resource));
|
||||
transactIfJpaTm(() -> tm().loadByEntity(resource));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1090,7 +1090,7 @@ public class DatabaseHelper {
|
||||
});
|
||||
maybeAdvanceClock();
|
||||
tm().clearSessionCache();
|
||||
return transactIfJpaTm(() -> tm().load(resource));
|
||||
return transactIfJpaTm(() -> tm().loadByEntity(resource));
|
||||
}
|
||||
|
||||
/** Returns all of the history entries that are parented off the given EppResource. */
|
||||
@@ -1101,11 +1101,11 @@ public class DatabaseHelper {
|
||||
() -> {
|
||||
ImmutableList<? extends HistoryEntry> unsorted = null;
|
||||
if (resource instanceof ContactBase) {
|
||||
unsorted = tm().loadAll(ContactHistory.class);
|
||||
unsorted = tm().loadAllOf(ContactHistory.class);
|
||||
} else if (resource instanceof HostBase) {
|
||||
unsorted = tm().loadAll(HostHistory.class);
|
||||
unsorted = tm().loadAllOf(HostHistory.class);
|
||||
} else if (resource instanceof DomainContent) {
|
||||
unsorted = tm().loadAll(DomainHistory.class);
|
||||
unsorted = tm().loadAllOf(DomainHistory.class);
|
||||
} else {
|
||||
fail("Expected an EppResource instance, but got " + resource.getClass());
|
||||
}
|
||||
@@ -1161,7 +1161,7 @@ public class DatabaseHelper {
|
||||
return Iterables.getOnlyElement(
|
||||
transactIfJpaTm(
|
||||
() ->
|
||||
tm().loadAll(PollMessage.class).stream()
|
||||
tm().loadAllOf(PollMessage.class).stream()
|
||||
.filter(
|
||||
pollMessage -> pollMessage.getParentKey().equals(Key.create(historyEntry)))
|
||||
.collect(toImmutableList())));
|
||||
@@ -1194,7 +1194,7 @@ public class DatabaseHelper {
|
||||
// Force the session to be cleared so that when we read it back, we read from Datastore
|
||||
// and not from the transaction's session cache.
|
||||
tm().clearSessionCache();
|
||||
return transactIfJpaTm(() -> tm().loadAll(resources));
|
||||
return transactIfJpaTm(() -> tm().loadByEntities(resources));
|
||||
}
|
||||
|
||||
public static void deleteResource(final Object resource) {
|
||||
@@ -1219,7 +1219,7 @@ public class DatabaseHelper {
|
||||
// otherwise JPA would just return the input entity instead of actually creating a
|
||||
// clone.
|
||||
tm().transact(() -> tm().put(resource));
|
||||
result = tm().transact(() -> tm().load(resource));
|
||||
result = tm().transact(() -> tm().loadByEntity(resource));
|
||||
}
|
||||
maybeAdvanceClock();
|
||||
return result;
|
||||
|
||||
@@ -63,7 +63,7 @@ public class SqlHelper {
|
||||
public static Registrar saveRegistrar(String clientId) {
|
||||
Registrar registrar = makeRegistrar1().asBuilder().setClientId(clientId).build();
|
||||
jpaTm().transact(() -> jpaTm().insert(registrar));
|
||||
return jpaTm().transact(() -> jpaTm().load(registrar.createVKey()));
|
||||
return jpaTm().transact(() -> jpaTm().loadByKey(registrar.createVKey()));
|
||||
}
|
||||
|
||||
public static void assertThrowForeignKeyViolation(Executable executable) {
|
||||
|
||||
@@ -60,7 +60,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
|
||||
persistPollMessage(123L, DateTime.parse("2015-09-01T22:33:44Z"), "notme");
|
||||
VKey<OneTime> pm4 = futurePollMessage.createVKey();
|
||||
runCommand("-c", "TheRegistrar");
|
||||
assertThat(tm().load(ImmutableList.of(pm1, pm2, pm3, pm4)).values())
|
||||
assertThat(tm().loadByKeysIfPresent(ImmutableList.of(pm1, pm2, pm3, pm4)).values())
|
||||
.containsExactly(futurePollMessage);
|
||||
assertInStdout(
|
||||
"1-FSDGS-TLD-2406-624-2013,2013-05-01T22:33:44.000Z,ninelives",
|
||||
@@ -90,7 +90,8 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
|
||||
autorenew.asBuilder().setEventTime(DateTime.parse("2012-04-15T22:33:44Z")).build();
|
||||
VKey<Autorenew> pm3 = autorenew.createVKey();
|
||||
runCommand("-c", "TheRegistrar");
|
||||
assertThat(tm().load(ImmutableList.of(pm1, pm2, pm3)).values()).containsExactly(resaved);
|
||||
assertThat(tm().loadByKeysIfPresent(ImmutableList.of(pm1, pm2, pm3)).values())
|
||||
.containsExactly(resaved);
|
||||
assertInStdout(
|
||||
"1-AAFSGS-TLD-99406-624-2011,2011-04-15T22:33:44.000Z,autorenew",
|
||||
"1-FSDGS-TLD-2406-624-2013,2013-05-01T22:33:44.000Z,ninelives",
|
||||
@@ -117,7 +118,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
|
||||
.build());
|
||||
VKey<Autorenew> pm3 = autorenew.createVKey();
|
||||
runCommand("-c", "TheRegistrar");
|
||||
assertThat(tm().load(ImmutableList.of(pm1, pm2, pm3))).isEmpty();
|
||||
assertThat(tm().loadByKeysIfPresent(ImmutableList.of(pm1, pm2, pm3))).isEmpty();
|
||||
assertInStdout(
|
||||
"1-AAFSGS-TLD-99406-624-2011,2011-04-15T22:33:44.000Z,autorenew",
|
||||
"1-FSDGS-TLD-2406-624-2013,2013-05-01T22:33:44.000Z,ninelives",
|
||||
@@ -138,7 +139,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
|
||||
persistPollMessage(123L, DateTime.parse("2015-09-01T22:33:44Z"), "time flies");
|
||||
VKey<OneTime> pm4 = notMatched2.createVKey();
|
||||
runCommand("-c", "TheRegistrar", "-m", "food");
|
||||
assertThat(tm().load(ImmutableList.of(pm1, pm2, pm3, pm4)).values())
|
||||
assertThat(tm().loadByKeysIfPresent(ImmutableList.of(pm1, pm2, pm3, pm4)).values())
|
||||
.containsExactly(notMatched1, notMatched2);
|
||||
}
|
||||
|
||||
@@ -163,7 +164,8 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
|
||||
.build());
|
||||
VKey<OneTime> pm3 = notMatched.createVKey();
|
||||
runCommand("-c", "TheRegistrar");
|
||||
assertThat(tm().load(ImmutableList.of(pm1, pm2, pm3)).values()).containsExactly(notMatched);
|
||||
assertThat(tm().loadByKeysIfPresent(ImmutableList.of(pm1, pm2, pm3)).values())
|
||||
.containsExactly(notMatched);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -174,7 +176,7 @@ public class AckPollMessagesCommandTest extends CommandTestCase<AckPollMessagesC
|
||||
OneTime pm4 = persistPollMessage(123L, DateTime.parse("2015-09-01T22:33:44Z"), "notme");
|
||||
runCommand("-c", "TheRegistrar", "-d");
|
||||
assertThat(
|
||||
tm().load(
|
||||
tm().loadByKeys(
|
||||
ImmutableList.of(pm1, pm2, pm3, pm4).stream()
|
||||
.map(OneTime::createVKey)
|
||||
.collect(toImmutableList()))
|
||||
|
||||
@@ -186,12 +186,12 @@ public abstract class CommandTestCase<C extends Command> {
|
||||
|
||||
/** Reloads the given resource from Datastore. */
|
||||
<T> T reloadResource(T resource) {
|
||||
return transactIfJpaTm(() -> tm().load(resource));
|
||||
return transactIfJpaTm(() -> tm().loadByEntity(resource));
|
||||
}
|
||||
|
||||
/** Returns count of all poll messages in Datastore. */
|
||||
int getPollMessageCount() {
|
||||
return transactIfJpaTm(() -> tm().loadAll(PollMessage.class).size());
|
||||
return transactIfJpaTm(() -> tm().loadAllOf(PollMessage.class).size());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -95,7 +95,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
|
||||
assertThat(registrar.getState()).isEqualTo(Registrar.State.ACTIVE);
|
||||
assertThat(registrar.getAllowedTlds()).isEmpty();
|
||||
assertThat(registrar.getIpAddressAllowList()).isEmpty();
|
||||
assertThat(registrar.getClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isEmpty();
|
||||
assertThat(registrar.getPhonePasscode()).isEqualTo("01234");
|
||||
assertThat(registrar.getCreationTime()).isIn(Range.closed(before, after));
|
||||
assertThat(registrar.getLastUpdateTime()).isEqualTo(registrar.getCreationTime());
|
||||
@@ -383,7 +383,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
|
||||
|
||||
Optional<Registrar> registrar = Registrar.loadByClientId("clientz");
|
||||
assertThat(registrar).isPresent();
|
||||
assertThat(registrar.get().getClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH);
|
||||
assertThat(registrar.get().getClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -467,10 +467,10 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
|
||||
Optional<Registrar> registrarOptional = Registrar.loadByClientId("clientz");
|
||||
assertThat(registrarOptional).isPresent();
|
||||
Registrar registrar = registrarOptional.get();
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT3);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH);
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getClientCertificateHash()).isEmpty();
|
||||
assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT3);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -134,9 +134,9 @@ class DeleteAllocationTokensCommandTest extends CommandTestCase<DeleteAllocation
|
||||
for (int i = 0; i < 50; i++) {
|
||||
persistToken(String.format("batch%2d", i), null, i % 2 == 0);
|
||||
}
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAll(AllocationToken.class).size())).isEqualTo(56);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAllOf(AllocationToken.class).size())).isEqualTo(56);
|
||||
runCommandForced("--prefix", "batch");
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAll(AllocationToken.class).size()))
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAllOf(AllocationToken.class).size()))
|
||||
.isEqualTo(56 - 25);
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ class DeleteAllocationTokensCommandTest extends CommandTestCase<DeleteAllocation
|
||||
}
|
||||
|
||||
private static ImmutableList<AllocationToken> reloadTokens(AllocationToken... tokens) {
|
||||
return transactIfJpaTm(() -> tm().loadAll(ImmutableSet.copyOf(tokens)));
|
||||
return transactIfJpaTm(() -> tm().loadByEntities(ImmutableSet.copyOf(tokens)));
|
||||
}
|
||||
|
||||
private static void assertNonexistent(AllocationToken... tokens) {
|
||||
|
||||
@@ -134,7 +134,7 @@ class GenerateAllocationTokensCommandTest extends CommandTestCase<GenerateAlloca
|
||||
runCommand("--prefix", "ooo", "--number", "100", "--length", "16");
|
||||
// The deterministic string generator makes it too much hassle to assert about each token, so
|
||||
// just assert total number.
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAll(AllocationToken.class).size())).isEqualTo(100);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAllOf(AllocationToken.class).size())).isEqualTo(100);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
@@ -199,7 +199,7 @@ class GenerateAllocationTokensCommandTest extends CommandTestCase<GenerateAlloca
|
||||
Collection<String> sampleTokens = command.stringGenerator.createStrings(13, 100);
|
||||
runCommand("--tokens", Joiner.on(",").join(sampleTokens));
|
||||
assertInStdout(Iterables.toArray(sampleTokens, String.class));
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAll(AllocationToken.class).size())).isEqualTo(100);
|
||||
assertThat(transactIfJpaTm(() -> tm().loadAllOf(AllocationToken.class).size())).isEqualTo(100);
|
||||
}
|
||||
|
||||
@TestOfyAndSql
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package google.registry.tools;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
import static google.registry.model.registrar.Registrar.State.ACTIVE;
|
||||
import static google.registry.model.registry.Registry.TldState.GENERAL_AVAILABILITY;
|
||||
import static google.registry.model.registry.Registry.TldState.START_DATE_SUNRISE;
|
||||
@@ -105,7 +106,7 @@ class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
|
||||
assertThat(registrar.getState()).isEqualTo(ACTIVE);
|
||||
assertThat(registrar.verifyPassword(password)).isTrue();
|
||||
assertThat(registrar.getIpAddressAllowList()).isEqualTo(ipAllowList);
|
||||
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT_HASH);
|
||||
assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT_HASH);
|
||||
}
|
||||
|
||||
private void verifyRegistrarContactCreation(String registrarName, String email) {
|
||||
|
||||
@@ -120,7 +120,7 @@ public class UnrenewDomainCommandTest extends CommandTestCase<UnrenewDomainComma
|
||||
HistoryEntry synthetic = getOnlyHistoryEntryOfType(domain, SYNTHETIC);
|
||||
|
||||
assertBillingEventsEqual(
|
||||
tm().load(domain.getAutorenewBillingEvent()),
|
||||
tm().loadByKey(domain.getAutorenewBillingEvent()),
|
||||
new BillingEvent.Recurring.Builder()
|
||||
.setParent(synthetic)
|
||||
.setReason(Reason.RENEW)
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
|
||||
package google.registry.tools;
|
||||
|
||||
import static com.google.common.base.Strings.isNullOrEmpty;
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
|
||||
@@ -68,7 +67,7 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
assertThat(loadRegistrar("NewRegistrar").verifyPassword("some_password")).isTrue();
|
||||
assertThat(
|
||||
jpaTm()
|
||||
.transact(() -> jpaTm().load(VKey.createSql(Registrar.class, "NewRegistrar")))
|
||||
.transact(() -> jpaTm().loadByKey(VKey.createSql(Registrar.class, "NewRegistrar")))
|
||||
.verifyPassword("some_password"))
|
||||
.isTrue();
|
||||
}
|
||||
@@ -250,22 +249,22 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
void testSuccess_certFile() throws Exception {
|
||||
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
|
||||
Registrar registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getClientCertificateHash()).isEmpty();
|
||||
runCommand("--cert_file=" + getCertFilename(SAMPLE_CERT3), "--force", "NewRegistrar");
|
||||
registrar = loadRegistrar("NewRegistrar");
|
||||
// NB: Hash was computed manually using 'openssl x509 -fingerprint -sha256 -in ...' and then
|
||||
// converting the result from a hex string to non-padded base64 encoded string.
|
||||
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT3);
|
||||
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH);
|
||||
assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT3);
|
||||
assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFail_certFileWithViolation() throws Exception {
|
||||
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
|
||||
Registrar registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getClientCertificateHash()).isEmpty();
|
||||
IllegalArgumentException thrown =
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
@@ -274,15 +273,15 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
.isEqualTo(
|
||||
"Certificate validity period is too long; it must be less than or equal to 398"
|
||||
+ " days.");
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFail_certFileWithMultipleViolations() throws Exception {
|
||||
fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z"));
|
||||
Registrar registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getClientCertificateHash()).isEmpty();
|
||||
IllegalArgumentException thrown =
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
@@ -291,14 +290,14 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
.isEqualTo(
|
||||
"Certificate is expired.\nCertificate validity period is too long; it must be less"
|
||||
+ " than or equal to 398 days.");
|
||||
assertThat(registrar.getClientCertificate()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFail_failoverCertFileWithViolation() throws Exception {
|
||||
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
|
||||
Registrar registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
IllegalArgumentException thrown =
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
@@ -308,14 +307,14 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
.isEqualTo(
|
||||
"Certificate validity period is too long; it must be less than or equal to 398"
|
||||
+ " days.");
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFail_failoverCertFileWithMultipleViolations() throws Exception {
|
||||
fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z"));
|
||||
Registrar registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
IllegalArgumentException thrown =
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
@@ -325,17 +324,17 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
.isEqualTo(
|
||||
"Certificate is expired.\nCertificate validity period is too long; it must be less"
|
||||
+ " than or equal to 398 days.");
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSuccess_failoverCertFile() throws Exception {
|
||||
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
|
||||
Registrar registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
runCommand("--failover_cert_file=" + getCertFilename(SAMPLE_CERT3), "--force", "NewRegistrar");
|
||||
registrar = loadRegistrar("NewRegistrar");
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT3);
|
||||
assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -345,9 +344,9 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
|
||||
.asBuilder()
|
||||
.setClientCertificate(SAMPLE_CERT, DateTime.now(UTC))
|
||||
.build());
|
||||
assertThat(isNullOrEmpty(loadRegistrar("NewRegistrar").getClientCertificate())).isFalse();
|
||||
assertThat(loadRegistrar("NewRegistrar").getClientCertificate()).isPresent();
|
||||
runCommand("--cert_file=/dev/null", "--force", "NewRegistrar");
|
||||
assertThat(loadRegistrar("NewRegistrar").getClientCertificate()).isNull();
|
||||
assertThat(loadRegistrar("NewRegistrar").getClientCertificate()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-5
@@ -91,7 +91,7 @@ public class BackfillSpec11ThreatMatchesCommandTest
|
||||
.transact(
|
||||
() -> {
|
||||
ImmutableList<Spec11ThreatMatch> threatMatches =
|
||||
jpaTm().loadAll(Spec11ThreatMatch.class);
|
||||
jpaTm().loadAllOf(Spec11ThreatMatch.class);
|
||||
assertThat(threatMatches).hasSize(6);
|
||||
assertThat(
|
||||
threatMatches.stream()
|
||||
@@ -151,7 +151,7 @@ public class BackfillSpec11ThreatMatchesCommandTest
|
||||
jpaTm()
|
||||
.transact(
|
||||
() ->
|
||||
jpaTm().loadAll(Spec11ThreatMatch.class).stream()
|
||||
jpaTm().loadAllOf(Spec11ThreatMatch.class).stream()
|
||||
.filter((match) -> match.getDomainName().equals("a.com"))
|
||||
.findFirst()
|
||||
.get()
|
||||
@@ -177,7 +177,7 @@ public class BackfillSpec11ThreatMatchesCommandTest
|
||||
|
||||
runCommandForced();
|
||||
ImmutableList<Spec11ThreatMatch> threatMatches =
|
||||
jpaTm().transact(() -> jpaTm().loadAll(Spec11ThreatMatch.class));
|
||||
jpaTm().transact(() -> jpaTm().loadAllOf(Spec11ThreatMatch.class));
|
||||
assertAboutImmutableObjects()
|
||||
.that(Iterables.getOnlyElement(threatMatches))
|
||||
.isEqualExceptFields(previous, "id");
|
||||
@@ -212,7 +212,7 @@ public class BackfillSpec11ThreatMatchesCommandTest
|
||||
assertThrows(RuntimeException.class, this::runCommandForced);
|
||||
assertThat(runtimeException.getCause().getClass()).isEqualTo(IOException.class);
|
||||
assertThat(runtimeException).hasCauseThat().hasMessageThat().isEqualTo("hi");
|
||||
jpaTm().transact(() -> assertThat(jpaTm().loadAll(Spec11ThreatMatch.class)).isEmpty());
|
||||
jpaTm().transact(() -> assertThat(jpaTm().loadAllOf(Spec11ThreatMatch.class)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -249,7 +249,7 @@ public class BackfillSpec11ThreatMatchesCommandTest
|
||||
.transact(
|
||||
() -> {
|
||||
ImmutableList<Spec11ThreatMatch> threatMatches =
|
||||
jpaTm().loadAll(Spec11ThreatMatch.class);
|
||||
jpaTm().loadAllOf(Spec11ThreatMatch.class);
|
||||
assertThat(threatMatches)
|
||||
.comparingElementsUsing(immutableObjectCorrespondence("id", "domainRepoId"))
|
||||
.containsExactly(
|
||||
|
||||
+2
-2
@@ -371,7 +371,7 @@ class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
|
||||
clock.setTo(DateTime.parse("2020-11-02T00:00:00Z"));
|
||||
doTestUpdate(
|
||||
Role.OWNER,
|
||||
Registrar::getClientCertificate,
|
||||
r -> r.getClientCertificate().orElse(null),
|
||||
CertificateSamples.SAMPLE_CERT3,
|
||||
(builder, s) -> builder.setClientCertificate(s, clock.nowUtc()));
|
||||
}
|
||||
@@ -431,7 +431,7 @@ class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
|
||||
clock.setTo(DateTime.parse("2020-11-02T00:00:00Z"));
|
||||
doTestUpdate(
|
||||
Role.OWNER,
|
||||
Registrar::getFailoverClientCertificate,
|
||||
r -> r.getFailoverClientCertificate().orElse(null),
|
||||
CertificateSamples.SAMPLE_CERT3,
|
||||
(builder, s) -> builder.setFailoverClientCertificate(s, clock.nowUtc()));
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package google.registry.ui.server.registrar;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
import static google.registry.testing.CertificateSamples.SAMPLE_CERT;
|
||||
import static google.registry.testing.CertificateSamples.SAMPLE_CERT2;
|
||||
import static google.registry.testing.CertificateSamples.SAMPLE_CERT2_HASH;
|
||||
@@ -121,10 +122,10 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
|
||||
"op", "update", "id", CLIENT_ID, "args", jsonMap));
|
||||
assertThat(response).containsEntry("status", "SUCCESS");
|
||||
Registrar registrar = loadRegistrar(CLIENT_ID);
|
||||
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT3);
|
||||
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH);
|
||||
assertThat(registrar.getFailoverClientCertificate()).isNull();
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isNull();
|
||||
assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT3);
|
||||
assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEmpty();
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isEmpty();
|
||||
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
|
||||
verifyNotificationEmailsSent();
|
||||
}
|
||||
@@ -138,8 +139,8 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
|
||||
"op", "update", "id", CLIENT_ID, "args", jsonMap));
|
||||
assertThat(response).containsEntry("status", "SUCCESS");
|
||||
Registrar registrar = loadRegistrar(CLIENT_ID);
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT3);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH);
|
||||
assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT3);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
|
||||
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
|
||||
verifyNotificationEmailsSent();
|
||||
}
|
||||
@@ -160,10 +161,10 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
|
||||
"op", "update", "id", CLIENT_ID, "args", jsonMap));
|
||||
assertThat(response).containsEntry("status", "SUCCESS");
|
||||
Registrar registrar = loadRegistrar(CLIENT_ID);
|
||||
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT);
|
||||
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT_HASH);
|
||||
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT2);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT2_HASH);
|
||||
assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT);
|
||||
assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT_HASH);
|
||||
assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT2);
|
||||
assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT2_HASH);
|
||||
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user