Remove TransactionManagerFactory.jpaTm() (#1883)

Since JPA is the only TM now, there's no point distinguishing tm() from
jpaTm().
This commit is contained in:
Lai Jiang 2022-12-13 14:37:46 -05:00 committed by GitHub
parent 1242e3d50c
commit 3848771c75
123 changed files with 806 additions and 1181 deletions

View file

@ -14,7 +14,6 @@
package google.registry.batch; package google.registry.batch;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -71,8 +70,7 @@ public class CheckPackagesComplianceAction implements Runnable {
for (PackagePromotion packagePromo : packages) { for (PackagePromotion packagePromo : packages) {
Long creates = Long creates =
(Long) (Long)
jpaTm() tm().query(
.query(
"SELECT COUNT(*) FROM DomainHistory WHERE current_package_token =" "SELECT COUNT(*) FROM DomainHistory WHERE current_package_token ="
+ " :token AND modificationTime >= :lastBilling AND type =" + " :token AND modificationTime >= :lastBilling AND type ="
+ " 'DOMAIN_CREATE'") + " 'DOMAIN_CREATE'")

View file

@ -21,7 +21,6 @@ import static google.registry.batch.BatchModule.PARAM_DRY_RUN;
import static google.registry.config.RegistryEnvironment.PRODUCTION; import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_DELETE; import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_DELETE;
import static google.registry.model.tld.Registries.getTldsOfType; import static google.registry.model.tld.Registries.getTldsOfType;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
import static google.registry.request.RequestParameters.PARAM_TLDS; import static google.registry.request.RequestParameters.PARAM_TLDS;
@ -140,7 +139,7 @@ public class DeleteProberDataAction implements Runnable {
private void runSqlJob(ImmutableSet<String> deletableTlds) { private void runSqlJob(ImmutableSet<String> deletableTlds) {
AtomicInteger softDeletedDomains = new AtomicInteger(); AtomicInteger softDeletedDomains = new AtomicInteger();
AtomicInteger hardDeletedDomains = new AtomicInteger(); AtomicInteger hardDeletedDomains = new AtomicInteger();
jpaTm().transact(() -> processDomains(deletableTlds, softDeletedDomains, hardDeletedDomains)); tm().transact(() -> processDomains(deletableTlds, softDeletedDomains, hardDeletedDomains));
logger.atInfo().log( logger.atInfo().log(
"%s %d domains.", "%s %d domains.",
isDryRun ? "Would have soft-deleted" : "Soft-deleted", softDeletedDomains.get()); isDryRun ? "Would have soft-deleted" : "Soft-deleted", softDeletedDomains.get());
@ -157,8 +156,7 @@ public class DeleteProberDataAction implements Runnable {
// Scroll through domains, soft-deleting as necessary (very few will be soft-deleted) and // Scroll through domains, soft-deleting as necessary (very few will be soft-deleted) and
// keeping track of which domains to hard-delete (there can be many, so we batch them up) // keeping track of which domains to hard-delete (there can be many, so we batch them up)
try (ScrollableResults scrollableResult = try (ScrollableResults scrollableResult =
jpaTm() tm().query(DOMAIN_QUERY_STRING, Domain.class)
.query(DOMAIN_QUERY_STRING, Domain.class)
.setParameter("tlds", deletableTlds) .setParameter("tlds", deletableTlds)
.setParameter( .setParameter(
"creationTimeCutoff", CreateAutoTimestamp.create(now.minus(DOMAIN_USED_DURATION))) "creationTimeCutoff", CreateAutoTimestamp.create(now.minus(DOMAIN_USED_DURATION)))
@ -183,8 +181,8 @@ public class DeleteProberDataAction implements Runnable {
domainRepoIdsToHardDelete.build(), hostNamesToHardDelete.build()); domainRepoIdsToHardDelete.build(), hostNamesToHardDelete.build());
domainRepoIdsToHardDelete = new ImmutableList.Builder<>(); domainRepoIdsToHardDelete = new ImmutableList.Builder<>();
hostNamesToHardDelete = new ImmutableList.Builder<>(); hostNamesToHardDelete = new ImmutableList.Builder<>();
jpaTm().getEntityManager().flush(); tm().getEntityManager().flush();
jpaTm().getEntityManager().clear(); tm().getEntityManager().clear();
} }
} }
// process the remainder // process the remainder
@ -226,32 +224,25 @@ public class DeleteProberDataAction implements Runnable {
private void hardDeleteDomainsAndHosts( private void hardDeleteDomainsAndHosts(
ImmutableList<String> domainRepoIds, ImmutableList<String> hostNames) { ImmutableList<String> domainRepoIds, ImmutableList<String> hostNames) {
jpaTm() tm().query("DELETE FROM Host WHERE hostName IN :hostNames")
.query("DELETE FROM Host WHERE hostName IN :hostNames")
.setParameter("hostNames", hostNames) .setParameter("hostNames", hostNames)
.executeUpdate(); .executeUpdate();
jpaTm() tm().query("DELETE FROM BillingEvent WHERE domainRepoId IN :repoIds")
.query("DELETE FROM BillingEvent WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds) .setParameter("repoIds", domainRepoIds)
.executeUpdate(); .executeUpdate();
jpaTm() tm().query("DELETE FROM BillingRecurrence WHERE domainRepoId IN :repoIds")
.query("DELETE FROM BillingRecurrence WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds) .setParameter("repoIds", domainRepoIds)
.executeUpdate(); .executeUpdate();
jpaTm() tm().query("DELETE FROM BillingCancellation WHERE domainRepoId IN :repoIds")
.query("DELETE FROM BillingCancellation WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds) .setParameter("repoIds", domainRepoIds)
.executeUpdate(); .executeUpdate();
jpaTm() tm().query("DELETE FROM DomainHistory WHERE repoId IN :repoIds")
.query("DELETE FROM DomainHistory WHERE repoId IN :repoIds")
.setParameter("repoIds", domainRepoIds) .setParameter("repoIds", domainRepoIds)
.executeUpdate(); .executeUpdate();
jpaTm() tm().query("DELETE FROM PollMessage WHERE domainRepoId IN :repoIds")
.query("DELETE FROM PollMessage WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds) .setParameter("repoIds", domainRepoIds)
.executeUpdate(); .executeUpdate();
jpaTm() tm().query("DELETE FROM Domain WHERE repoId IN :repoIds")
.query("DELETE FROM Domain WHERE repoId IN :repoIds")
.setParameter("repoIds", domainRepoIds) .setParameter("repoIds", domainRepoIds)
.executeUpdate(); .executeUpdate();
} }

View file

@ -23,7 +23,6 @@ import static google.registry.model.common.Cursor.CursorType.RECURRING_BILLING;
import static google.registry.model.domain.Period.Unit.YEARS; import static google.registry.model.domain.Period.Unit.YEARS;
import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_AUTORENEW; import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_AUTORENEW;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ; import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.union; import static google.registry.util.CollectionUtils.union;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -118,15 +117,13 @@ public class ExpandRecurringBillingEventsAction implements Runnable {
do { do {
final long prevMaxProcessedRecurrenceId = maxProcessedRecurrenceId; final long prevMaxProcessedRecurrenceId = maxProcessedRecurrenceId;
sqlBatchResults = sqlBatchResults =
jpaTm() tm().transact(
.transact(
() -> { () -> {
Set<String> expandedDomains = newHashSet(); Set<String> expandedDomains = newHashSet();
int batchBillingEventsSaved = 0; int batchBillingEventsSaved = 0;
long maxRecurrenceId = prevMaxProcessedRecurrenceId; long maxRecurrenceId = prevMaxProcessedRecurrenceId;
List<Recurring> recurrings = List<Recurring> recurrings =
jpaTm() tm().query(
.query(
"FROM BillingRecurrence " "FROM BillingRecurrence "
+ "WHERE eventTime <= :executeTime " + "WHERE eventTime <= :executeTime "
+ "AND eventTime < recurrenceEndTime " + "AND eventTime < recurrenceEndTime "

View file

@ -16,7 +16,6 @@ package google.registry.batch;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
@ -189,7 +188,7 @@ public class RelockDomainAction implements Runnable {
"Domain %s has a pending delete.", "Domain %s has a pending delete.",
domainName); domainName);
checkArgument( checkArgument(
!DateTimeUtils.isAtOrAfter(jpaTm().getTransactionTime(), domain.getDeletionTime()), !DateTimeUtils.isAtOrAfter(tm().getTransactionTime(), domain.getDeletionTime()),
"Domain %s has been deleted.", "Domain %s has been deleted.",
domainName); domainName);
checkArgument( checkArgument(

View file

@ -14,7 +14,7 @@
package google.registry.batch; package google.registry.batch;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_OK;
@ -77,8 +77,7 @@ public class WipeOutContactHistoryPiiAction implements Runnable {
int numOfWipedEntities = 0; int numOfWipedEntities = 0;
do { do {
numOfWipedEntities = numOfWipedEntities =
jpaTm() tm().transact(
.transact(
() -> () ->
wipeOutContactHistoryData( wipeOutContactHistoryData(
getNextContactHistoryEntitiesWithPiiBatch(wipeOutTime))); getNextContactHistoryEntitiesWithPiiBatch(wipeOutTime)));
@ -113,8 +112,7 @@ public class WipeOutContactHistoryPiiAction implements Runnable {
// email is one of the required fields in EPP, meaning it's initially not null. // email is one of the required fields in EPP, meaning it's initially not null.
// Therefore, checking if it's null is one way to avoid processing contact history entities // Therefore, checking if it's null is one way to avoid processing contact history entities
// that have been processed previously. Refer to RFC 5733 for more information. // that have been processed previously. Refer to RFC 5733 for more information.
return jpaTm() return tm().query(
.query(
"FROM ContactHistory WHERE modificationTime < :wipeOutTime " + "AND email IS NOT NULL", "FROM ContactHistory WHERE modificationTime < :wipeOutTime " + "AND email IS NOT NULL",
ContactHistory.class) ContactHistory.class)
.setParameter("wipeOutTime", wipeOutTime) .setParameter("wipeOutTime", wipeOutTime)
@ -128,7 +126,7 @@ public class WipeOutContactHistoryPiiAction implements Runnable {
AtomicInteger numOfEntities = new AtomicInteger(0); AtomicInteger numOfEntities = new AtomicInteger(0);
contactHistoryEntities.forEach( contactHistoryEntities.forEach(
contactHistoryEntity -> { contactHistoryEntity -> {
jpaTm().update(contactHistoryEntity.asBuilder().wipeOutPii().build()); tm().update(contactHistoryEntity.asBuilder().wipeOutPii().build());
numOfEntities.incrementAndGet(); numOfEntities.incrementAndGet();
}); });
logger.atInfo().log( logger.atInfo().log(

View file

@ -15,7 +15,7 @@
package google.registry.beam.common; package google.registry.beam.common;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import java.util.List; import java.util.List;
@ -52,7 +52,7 @@ public class DatabaseSnapshot implements AutoCloseable {
} }
private DatabaseSnapshot open() { private DatabaseSnapshot open() {
entityManager = jpaTm().getStandaloneEntityManager(); entityManager = tm().getStandaloneEntityManager();
transaction = entityManager.getTransaction(); transaction = entityManager.getTransaction();
transaction.setRollbackOnly(); transaction.setRollbackOnly();
transaction.begin(); transaction.begin();

View file

@ -15,7 +15,7 @@
package google.registry.beam.common; package google.registry.beam.common;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.beam.sdk.values.TypeDescriptors.integers; import static org.apache.beam.sdk.values.TypeDescriptors.integers;
import com.google.auto.value.AutoValue; import com.google.auto.value.AutoValue;
@ -50,8 +50,8 @@ import org.apache.beam.sdk.values.PCollection;
* *
* <p>The {@code JpaTransactionManager} is instantiated once on each pipeline worker VM (through * <p>The {@code JpaTransactionManager} is instantiated once on each pipeline worker VM (through
* {@link RegistryPipelineWorkerInitializer}), made available through the static method {@link * {@link RegistryPipelineWorkerInitializer}), made available through the static method {@link
* TransactionManagerFactory#jpaTm()}, and is shared by all threads on the VM. Configuration is * TransactionManagerFactory#tm()}, and is shared by all threads on the VM. Configuration is through
* through {@link RegistryPipelineOptions}. * {@link RegistryPipelineOptions}.
*/ */
public final class RegistryJpaIO { public final class RegistryJpaIO {
@ -231,11 +231,10 @@ public final class RegistryJpaIO {
@ProcessElement @ProcessElement
public void processElement(OutputReceiver<T> outputReceiver) { public void processElement(OutputReceiver<T> outputReceiver) {
jpaTm() tm().transactNoRetry(
.transactNoRetry(
() -> { () -> {
if (snapshotId != null) { if (snapshotId != null) {
jpaTm().setDatabaseSnapshot(snapshotId); tm().setDatabaseSnapshot(snapshotId);
} }
query.stream().map(resultMapper::apply).forEach(outputReceiver::output); query.stream().map(resultMapper::apply).forEach(outputReceiver::output);
}); });
@ -344,12 +343,11 @@ public final class RegistryJpaIO {
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList()); .collect(ImmutableList.toImmutableList());
try { try {
jpaTm() tm().transact(
.transact(
() -> { () -> {
// Don't modify existing objects as it could lead to race conditions // Don't modify existing objects as it could lead to race conditions
entities.forEach(this::verifyObjectNonexistence); entities.forEach(this::verifyObjectNonexistence);
jpaTm().putAll(entities); tm().putAll(entities);
}); });
counter.inc(entities.size()); counter.inc(entities.size());
} catch (RuntimeException e) { } catch (RuntimeException e) {
@ -364,12 +362,11 @@ public final class RegistryJpaIO {
private void processSingly(ImmutableList<Object> entities) { private void processSingly(ImmutableList<Object> entities) {
for (Object entity : entities) { for (Object entity : entities) {
try { try {
jpaTm() tm().transact(
.transact(
() -> { () -> {
// Don't modify existing objects as it could lead to race conditions // Don't modify existing objects as it could lead to race conditions
verifyObjectNonexistence(entity); verifyObjectNonexistence(entity);
jpaTm().put(entity); tm().put(entity);
}); });
counter.inc(); counter.inc();
} catch (RuntimeException e) { } catch (RuntimeException e) {
@ -381,14 +378,12 @@ public final class RegistryJpaIO {
/** Returns this entity's primary key field(s) in a string. */ /** Returns this entity's primary key field(s) in a string. */
private String toEntityKeyString(Object entity) { private String toEntityKeyString(Object entity) {
try { try {
return jpaTm() return tm().transact(
.transact(
() -> () ->
String.format( String.format(
"%s_%s", "%s_%s",
entity.getClass().getSimpleName(), entity.getClass().getSimpleName(),
jpaTm() tm().getEntityManager()
.getEntityManager()
.getEntityManagerFactory() .getEntityManagerFactory()
.getPersistenceUnitUtil() .getPersistenceUnitUtil()
.getIdentifier(entity))); .getIdentifier(entity)));
@ -404,8 +399,7 @@ public final class RegistryJpaIO {
// updateTimestamp) are reflected in the input object. Beam doesn't allow modification of // updateTimestamp) are reflected in the input object. Beam doesn't allow modification of
// input objects, so this throws an exception. // input objects, so this throws an exception.
// TODO(go/non-datastore-allocateid): also check that all the objects have IDs // TODO(go/non-datastore-allocateid): also check that all the objects have IDs
checkArgument( checkArgument(!tm().exists(obj), "Entities created in SqlBatchWriter must not already exist");
!jpaTm().exists(obj), "Entities created in SqlBatchWriter must not already exist");
} }
} }
} }

View file

@ -14,7 +14,7 @@
package google.registry.beam.common; package google.registry.beam.common;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import google.registry.persistence.transaction.JpaTransactionManager; import google.registry.persistence.transaction.JpaTransactionManager;
import java.io.Serializable; import java.io.Serializable;
@ -53,7 +53,7 @@ public interface RegistryQuery<T> extends Serializable {
static <T> RegistryQuery<T> createQuery( static <T> RegistryQuery<T> createQuery(
String sql, @Nullable Map<String, Object> parameters, boolean nativeQuery) { String sql, @Nullable Map<String, Object> parameters, boolean nativeQuery) {
return () -> { return () -> {
EntityManager entityManager = jpaTm().getEntityManager(); EntityManager entityManager = tm().getEntityManager();
Query query = Query query =
nativeQuery ? entityManager.createNativeQuery(sql) : entityManager.createQuery(sql); nativeQuery ? entityManager.createNativeQuery(sql) : entityManager.createQuery(sql);
if (parameters != null) { if (parameters != null) {
@ -76,7 +76,7 @@ public interface RegistryQuery<T> extends Serializable {
String jpql, @Nullable Map<String, Object> parameters, Class<T> clazz) { String jpql, @Nullable Map<String, Object> parameters, Class<T> clazz) {
return () -> { return () -> {
// TODO(b/193662898): switch to jpaTm().query() when it can properly detach loaded entities. // TODO(b/193662898): switch to jpaTm().query() when it can properly detach loaded entities.
EntityManager entityManager = jpaTm().getEntityManager(); EntityManager entityManager = tm().getEntityManager();
TypedQuery<T> query = entityManager.createQuery(jpql, clazz); TypedQuery<T> query = entityManager.createQuery(jpql, clazz);
if (parameters != null) { if (parameters != null) {
parameters.forEach(query::setParameter); parameters.forEach(query::setParameter);
@ -98,7 +98,7 @@ public interface RegistryQuery<T> extends Serializable {
static <T> RegistryQuery<T> createQuery(CriteriaQuerySupplier<T> criteriaQuery) { static <T> RegistryQuery<T> createQuery(CriteriaQuerySupplier<T> criteriaQuery) {
return () -> { return () -> {
// TODO(b/193662898): switch to jpaTm().query() when it can properly detach loaded entities. // TODO(b/193662898): switch to jpaTm().query() when it can properly detach loaded entities.
EntityManager entityManager = jpaTm().getEntityManager(); EntityManager entityManager = tm().getEntityManager();
TypedQuery<T> query = entityManager.createQuery(criteriaQuery.get()); TypedQuery<T> query = entityManager.createQuery(criteriaQuery.get());
JpaTransactionManager.setQueryFetchSize(query, QUERY_FETCH_SIZE); JpaTransactionManager.setQueryFetchSize(query, QUERY_FETCH_SIZE);
return query.getResultStream().map(e -> detach(entityManager, e)); return query.getResultStream().map(e -> detach(entityManager, e));

View file

@ -26,7 +26,7 @@ import static google.registry.beam.rde.RdePipeline.TupleTags.REFERENCED_HOSTS;
import static google.registry.beam.rde.RdePipeline.TupleTags.REVISION_ID; import static google.registry.beam.rde.RdePipeline.TupleTags.REVISION_ID;
import static google.registry.beam.rde.RdePipeline.TupleTags.SUPERORDINATE_DOMAINS; import static google.registry.beam.rde.RdePipeline.TupleTags.SUPERORDINATE_DOMAINS;
import static google.registry.model.reporting.HistoryEntryDao.RESOURCE_TYPES_TO_HISTORY_TYPES; import static google.registry.model.reporting.HistoryEntryDao.RESOURCE_TYPES_TO_HISTORY_TYPES;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.beam.sdk.values.TypeDescriptors.kvs; import static org.apache.beam.sdk.values.TypeDescriptors.kvs;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -305,7 +305,7 @@ public class RdePipeline implements Serializable {
(String registrarRepoId) -> { (String registrarRepoId) -> {
VKey<Registrar> key = VKey.create(Registrar.class, registrarRepoId); VKey<Registrar> key = VKey.create(Registrar.class, registrarRepoId);
includedRegistrarCounter.inc(); includedRegistrarCounter.inc();
Registrar registrar = jpaTm().transact(() -> jpaTm().loadByKey(key)); Registrar registrar = tm().transact(() -> tm().loadByKey(key));
DepositFragment fragment = marshaller.marshalRegistrar(registrar); DepositFragment fragment = marshaller.marshalRegistrar(registrar);
ImmutableSet<KV<PendingDeposit, DepositFragment>> fragments = ImmutableSet<KV<PendingDeposit, DepositFragment>> fragments =
pendingDeposits.stream() pendingDeposits.stream()
@ -376,11 +376,9 @@ public class RdePipeline implements Serializable {
private <T extends HistoryEntry> EppResource loadResourceByHistoryEntryId( private <T extends HistoryEntry> EppResource loadResourceByHistoryEntryId(
Class<T> historyEntryClazz, String repoId, long revisionId) { Class<T> historyEntryClazz, String repoId, long revisionId) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().loadByKey(
.loadByKey(
VKey.create(historyEntryClazz, new HistoryEntryId(repoId, revisionId)))) VKey.create(historyEntryClazz, new HistoryEntryId(repoId, revisionId))))
.getResourceAtPointInTime() .getResourceAtPointInTime()
.map(resource -> resource.cloneProjectedAtTime(watermark)) .map(resource -> resource.cloneProjectedAtTime(watermark))

View file

@ -15,7 +15,7 @@
package google.registry.beam.resave; package google.registry.beam.resave;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.beam.sdk.values.TypeDescriptors.integers; import static org.apache.beam.sdk.values.TypeDescriptors.integers;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -171,19 +171,18 @@ public class ResaveAllEppResourcesPipeline implements Serializable {
public void processElement( public void processElement(
@Element KV<ShardedKey<Integer>, Iterable<String>> element, @Element KV<ShardedKey<Integer>, Iterable<String>> element,
OutputReceiver<Void> outputReceiver) { OutputReceiver<Void> outputReceiver) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
ImmutableList<VKey<? extends EppResource>> keys = ImmutableList<VKey<? extends EppResource>> keys =
Streams.stream(element.getValue()) Streams.stream(element.getValue())
.map(repoId -> VKey.create(clazz, repoId)) .map(repoId -> VKey.create(clazz, repoId))
.collect(toImmutableList()); .collect(toImmutableList());
ImmutableList<EppResource> mappedResources = ImmutableList<EppResource> mappedResources =
jpaTm().loadByKeys(keys).values().stream() tm().loadByKeys(keys).values().stream()
.map(r -> r.cloneProjectedAtTime(now)) .map(r -> r.cloneProjectedAtTime(now))
.collect(toImmutableList()); .collect(toImmutableList());
jpaTm().putAll(mappedResources); tm().putAll(mappedResources);
}); });
} }
} }

View file

@ -15,7 +15,7 @@
package google.registry.beam.spec11; package google.registry.beam.spec11;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.auto.value.AutoValue; import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -131,9 +131,8 @@ public class Spec11Pipeline implements Serializable {
public void processElement( public void processElement(
@Element KV<String, String> input, OutputReceiver<DomainNameInfo> output) { @Element KV<String, String> input, OutputReceiver<DomainNameInfo> output) {
Domain domain = Domain domain =
jpaTm() tm().transact(
.transact( () -> tm().loadByKey(VKey.create(Domain.class, input.getKey())));
() -> jpaTm().loadByKey(VKey.create(Domain.class, input.getKey())));
String emailAddress = input.getValue(); String emailAddress = input.getValue();
if (emailAddress == null) { if (emailAddress == null) {
emailAddress = ""; emailAddress = "";

View file

@ -16,7 +16,6 @@ package google.registry.export;
import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.base.Verify.verifyNotNull;
import static google.registry.model.tld.Registries.getTldsOfType; import static google.registry.model.tld.Registries.getTldsOfType;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@ -89,8 +88,7 @@ public class ExportDomainListsAction implements Runnable {
// DateTime are persisted as timestamp_z in SQL. It is only the // DateTime are persisted as timestamp_z in SQL. It is only the
// validation that compares the Java types, and only with the first // validation that compares the Java types, and only with the first
// field that compares with the substituted value. // field that compares with the substituted value.
jpaTm() tm().query(
.query(
"SELECT domainName FROM Domain " "SELECT domainName FROM Domain "
+ "WHERE tld = :tld " + "WHERE tld = :tld "
+ "AND deletionTime > :now " + "AND deletionTime > :now "

View file

@ -37,7 +37,6 @@ import static google.registry.model.tld.label.ReservationType.FULLY_BLOCKED;
import static google.registry.model.tld.label.ReservationType.NAME_COLLISION; import static google.registry.model.tld.label.ReservationType.NAME_COLLISION;
import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_ANCHOR_TENANT; import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_ANCHOR_TENANT;
import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_SPECIFIC_USE; import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_SPECIFIC_USE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.pricing.PricingEngineProxy.isDomainPremium; import static google.registry.pricing.PricingEngineProxy.isDomainPremium;
import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.CollectionUtils.nullToEmpty;
@ -1179,8 +1178,7 @@ public class DomainFlowUtils {
private static List<DomainHistory> findRecentHistoryEntries( private static List<DomainHistory> findRecentHistoryEntries(
Domain domain, DateTime now, Duration maxSearchPeriod) { Domain domain, DateTime now, Duration maxSearchPeriod) {
return jpaTm() return tm().query(
.query(
"FROM DomainHistory WHERE modificationTime >= :beginning AND repoId = " "FROM DomainHistory WHERE modificationTime >= :beginning AND repoId = "
+ ":repoId ORDER BY modificationTime ASC", + ":repoId ORDER BY modificationTime ASC",
DomainHistory.class) DomainHistory.class)

View file

@ -15,7 +15,6 @@
package google.registry.flows.domain.token; package google.registry.flows.domain.token;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.base.Strings; import com.google.common.base.Strings;
@ -229,8 +228,8 @@ public class AllocationTokenFlowUtils {
// the Recurring billing event is reloaded later in the renew flow, so we synchronize changed // the Recurring billing event is reloaded later in the renew flow, so we synchronize changed
// RecurringBillingEvent with storage manually // RecurringBillingEvent with storage manually
tm().put(newRecurringBillingEvent); tm().put(newRecurringBillingEvent);
jpaTm().getEntityManager().flush(); tm().getEntityManager().flush();
jpaTm().getEntityManager().clear(); tm().getEntityManager().clear();
// Remove current package token // Remove current package token
return domain return domain

View file

@ -14,7 +14,7 @@
package google.registry.model; package google.registry.model;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.persistence.Column; import javax.persistence.Column;
@ -34,7 +34,7 @@ public class CreateAutoTimestamp extends ImmutableObject implements UnsafeSerial
@PreUpdate @PreUpdate
void setTimestamp() { void setTimestamp() {
if (creationTime == null) { if (creationTime == null) {
creationTime = jpaTm().getTransactionTime(); creationTime = tm().getTransactionTime();
} }
} }

View file

@ -16,7 +16,6 @@ package google.registry.model;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.isAtOrAfter;
@ -349,14 +348,12 @@ public final class EppResourceUtils {
Query query; Query query;
if (isContactKey) { if (isContactKey) {
query = query =
jpaTm() tm().query(CONTACT_LINKED_DOMAIN_QUERY, String.class)
.query(CONTACT_LINKED_DOMAIN_QUERY, String.class)
.setParameter("fkRepoId", key) .setParameter("fkRepoId", key)
.setParameter("now", now); .setParameter("now", now);
} else { } else {
query = query =
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery(HOST_LINKED_DOMAIN_QUERY) .createNativeQuery(HOST_LINKED_DOMAIN_QUERY)
.setParameter("fkRepoId", key.getKey()) .setParameter("fkRepoId", key.getKey())
.setParameter("now", now.toDate()); .setParameter("now", now.toDate());

View file

@ -18,8 +18,8 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static google.registry.config.RegistryConfig.getEppResourceCachingDuration; import static google.registry.config.RegistryConfig.getEppResourceCachingDuration;
import static google.registry.config.RegistryConfig.getEppResourceMaxCachedEntries; import static google.registry.config.RegistryConfig.getEppResourceMaxCachedEntries;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.LoadingCache;
@ -106,12 +106,12 @@ public final class ForeignKeyUtils {
* to duplicate keys. * to duplicate keys.
*/ */
private static <E extends EppResource> ImmutableMap<String, MostRecentResource> load( private static <E extends EppResource> ImmutableMap<String, MostRecentResource> load(
Class<E> clazz, Collection<String> foreignKeys, boolean useReplicaJpaTm) { Class<E> clazz, Collection<String> foreignKeys, boolean useReplicaTm) {
String fkProperty = RESOURCE_TYPE_TO_FK_PROPERTY.get(clazz); String fkProperty = RESOURCE_TYPE_TO_FK_PROPERTY.get(clazz);
JpaTransactionManager jpaTmToUse = useReplicaJpaTm ? replicaJpaTm() : jpaTm(); JpaTransactionManager tmToUse = useReplicaTm ? replicaTm() : tm();
return jpaTmToUse.transact( return tmToUse.transact(
() -> () ->
jpaTmToUse tmToUse
.query( .query(
("SELECT %fkProperty%, repoId, deletionTime FROM %entity% WHERE (%fkProperty%," ("SELECT %fkProperty%, repoId, deletionTime FROM %entity% WHERE (%fkProperty%,"
+ " deletionTime) IN (SELECT %fkProperty%, MAX(deletionTime) FROM" + " deletionTime) IN (SELECT %fkProperty%, MAX(deletionTime) FROM"

View file

@ -15,7 +15,7 @@
package google.registry.model; package google.registry.model;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.DatastoreServiceFactory;
@ -70,12 +70,10 @@ public final class IdService {
* <p>The generated IDs are project-wide unique * <p>The generated IDs are project-wide unique
*/ */
private static Long getSequenceBasedId() { private static Long getSequenceBasedId() {
return jpaTm() return tm().transact(
.transact(
() -> () ->
(BigInteger) (BigInteger)
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery("SELECT nextval('project_wide_unique_id_seq')") .createNativeQuery("SELECT nextval('project_wide_unique_id_seq')")
.getSingleResult()) .getSingleResult())
.longValue(); .longValue();

View file

@ -14,7 +14,7 @@
package google.registry.model; package google.registry.model;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import java.util.Optional; import java.util.Optional;
@ -38,7 +38,7 @@ public class UpdateAutoTimestamp extends ImmutableObject implements UnsafeSerial
@PrePersist @PrePersist
@PreUpdate @PreUpdate
void setTimestamp() { void setTimestamp() {
lastUpdateTime = jpaTm().getTransactionTime(); lastUpdateTime = tm().getTransactionTime();
} }
/** Returns the timestamp, or {@code START_OF_TIME} if it's null. */ /** Returns the timestamp, or {@code START_OF_TIME} if it's null. */

View file

@ -15,7 +15,7 @@
package google.registry.model.common; package google.registry.model.common;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.LoadingCache;
@ -192,7 +192,7 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
/** Sets and persists to SQL the provided migration transition schedule. */ /** Sets and persists to SQL the provided migration transition schedule. */
public static void set(ImmutableSortedMap<DateTime, MigrationState> migrationTransitionMap) { public static void set(ImmutableSortedMap<DateTime, MigrationState> migrationTransitionMap) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
TimedTransitionProperty<MigrationState> transitions = TimedTransitionProperty<MigrationState> transitions =
TimedTransitionProperty.make( TimedTransitionProperty.make(
migrationTransitionMap, migrationTransitionMap,
@ -201,7 +201,7 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
MigrationState.DATASTORE_ONLY, MigrationState.DATASTORE_ONLY,
"migrationTransitionMap must start with DATASTORE_ONLY"); "migrationTransitionMap must start with DATASTORE_ONLY");
validateTransitionAtCurrentTime(transitions); validateTransitionAtCurrentTime(transitions);
jpaTm().put(new DatabaseMigrationStateSchedule(transitions)); tm().put(new DatabaseMigrationStateSchedule(transitions));
CACHE.invalidateAll(); CACHE.invalidateAll();
} }
@ -218,12 +218,10 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
/** Loads the currently-set migration schedule from SQL, or the default if none exists. */ /** Loads the currently-set migration schedule from SQL, or the default if none exists. */
@VisibleForTesting @VisibleForTesting
static TimedTransitionProperty<MigrationState> getUncached() { static TimedTransitionProperty<MigrationState> getUncached() {
return jpaTm() return tm().transactWithoutBackup(
.transactWithoutBackup(
() -> { () -> {
try { try {
return jpaTm() return tm().loadSingleton(DatabaseMigrationStateSchedule.class)
.loadSingleton(DatabaseMigrationStateSchedule.class)
.map(s -> s.migrationTransitions) .map(s -> s.migrationTransitions)
.orElse(DEFAULT_TRANSITION_MAP); .orElse(DEFAULT_TRANSITION_MAP);
} catch (PersistenceException e) { } catch (PersistenceException e) {
@ -245,8 +243,8 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
*/ */
private static void validateTransitionAtCurrentTime( private static void validateTransitionAtCurrentTime(
TimedTransitionProperty<MigrationState> newTransitions) { TimedTransitionProperty<MigrationState> newTransitions) {
MigrationState currentValue = getUncached().getValueAtTime(jpaTm().getTransactionTime()); MigrationState currentValue = getUncached().getValueAtTime(tm().getTransactionTime());
MigrationState nextCurrentValue = newTransitions.getValueAtTime(jpaTm().getTransactionTime()); MigrationState nextCurrentValue = newTransitions.getValueAtTime(tm().getTransactionTime());
checkArgument( checkArgument(
VALID_STATE_TRANSITIONS.get(currentValue).contains(nextCurrentValue), VALID_STATE_TRANSITIONS.get(currentValue).contains(nextCurrentValue),
"Cannot transition from current state-as-of-now %s to new state-as-of-now %s", "Cannot transition from current state-as-of-now %s to new state-as-of-now %s",

View file

@ -15,7 +15,7 @@
package google.registry.model.console; package google.registry.model.console;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import java.util.Optional; import java.util.Optional;
@ -24,11 +24,9 @@ public class UserDao {
/** Retrieves the one user with this email address if it exists. */ /** Retrieves the one user with this email address if it exists. */
public static Optional<User> loadUser(String emailAddress) { public static Optional<User> loadUser(String emailAddress) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query("FROM User WHERE emailAddress = :emailAddress", User.class)
.query("FROM User WHERE emailAddress = :emailAddress", User.class)
.setParameter("emailAddress", emailAddress) .setParameter("emailAddress", emailAddress)
.getResultStream() .getResultStream()
.findFirst()); .findFirst());
@ -36,8 +34,7 @@ public class UserDao {
/** Saves the given user, checking that no existing user already exists with this email. */ /** Saves the given user, checking that no existing user already exists with this email. */
public static void saveUser(User user) { public static void saveUser(User user) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
// Check for an existing user (the unique constraint protects us, but this gives a // Check for an existing user (the unique constraint protects us, but this gives a
// nicer exception) // nicer exception)
@ -51,7 +48,7 @@ public class UserDao {
+ " email already exists with ID %s", + " email already exists with ID %s",
user.getEmailAddress(), user.getId(), savedUser.getId())); user.getEmailAddress(), user.getId(), savedUser.getId()));
} }
jpaTm().put(user); tm().put(user);
}); });
} }
} }

View file

@ -15,7 +15,6 @@
package google.registry.model.domain.token; package google.registry.model.domain.token;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
@ -101,9 +100,8 @@ public class PackagePromotion extends ImmutableObject implements Buildable {
/** Loads and returns a PackagePromotion entity by its token string directly from Cloud SQL. */ /** Loads and returns a PackagePromotion entity by its token string directly from Cloud SQL. */
public static Optional<PackagePromotion> loadByTokenString(String tokenString) { public static Optional<PackagePromotion> loadByTokenString(String tokenString) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
return jpaTm() return tm().query("FROM PackagePromotion WHERE token = :token", PackagePromotion.class)
.query("FROM PackagePromotion WHERE token = :token", PackagePromotion.class)
.setParameter("token", VKey.create(AllocationToken.class, tokenString)) .setParameter("token", VKey.create(AllocationToken.class, tokenString))
.getResultStream() .getResultStream()
.findFirst(); .findFirst();

View file

@ -27,7 +27,6 @@ import static com.google.common.io.BaseEncoding.base64;
import static google.registry.config.RegistryConfig.getDefaultRegistrarWhoisServer; import static google.registry.config.RegistryConfig.getDefaultRegistrarWhoisServer;
import static google.registry.model.CacheUtils.memoizeWithShortExpiration; import static google.registry.model.CacheUtils.memoizeWithShortExpiration;
import static google.registry.model.tld.Registries.assertTldsExist; import static google.registry.model.tld.Registries.assertTldsExist;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy; import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy;
@ -580,8 +579,7 @@ public class Registrar extends UpdateAutoTimestampEntity implements Buildable, J
private Iterable<RegistrarPoc> getContactsIterable() { private Iterable<RegistrarPoc> getContactsIterable() {
return tm().transact( return tm().transact(
() -> () ->
jpaTm() tm().query("FROM RegistrarPoc WHERE registrarId = :registrarId", RegistrarPoc.class)
.query("FROM RegistrarPoc WHERE registrarId = :registrarId", RegistrarPoc.class)
.setParameter("registrarId", registrarId) .setParameter("registrarId", registrarId)
.getResultStream() .getResultStream()
.collect(toImmutableList())); .collect(toImmutableList()));

View file

@ -20,7 +20,6 @@ import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.io.BaseEncoding.base64; import static com.google.common.io.BaseEncoding.base64;
import static google.registry.model.registrar.Registrar.checkValidEmail; import static google.registry.model.registrar.Registrar.checkValidEmail;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy; import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy;
import static google.registry.util.PasswordUtils.SALT_SUPPLIER; import static google.registry.util.PasswordUtils.SALT_SUPPLIER;
@ -185,8 +184,7 @@ public class RegistrarPoc extends ImmutableObject implements Jsonifiable, Unsafe
() -> { () -> {
ImmutableSet<String> emailAddressesToKeep = ImmutableSet<String> emailAddressesToKeep =
contacts.stream().map(RegistrarPoc::getEmailAddress).collect(toImmutableSet()); contacts.stream().map(RegistrarPoc::getEmailAddress).collect(toImmutableSet());
jpaTm() tm().query(
.query(
"DELETE FROM RegistrarPoc WHERE registrarId = :registrarId AND " "DELETE FROM RegistrarPoc WHERE registrarId = :registrarId AND "
+ "emailAddress NOT IN :emailAddressesToKeep") + "emailAddress NOT IN :emailAddressesToKeep")
.setParameter("registrarId", registrar.getRegistrarId()) .setParameter("registrarId", registrar.getRegistrarId())

View file

@ -16,7 +16,7 @@ package google.registry.model.reporting;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -56,8 +56,7 @@ public class HistoryEntryDao {
/** Loads all history objects in the times specified, including all types. */ /** Loads all history objects in the times specified, including all types. */
public static ImmutableList<HistoryEntry> loadAllHistoryObjects( public static ImmutableList<HistoryEntry> loadAllHistoryObjects(
DateTime afterTime, DateTime beforeTime) { DateTime afterTime, DateTime beforeTime) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
new ImmutableList.Builder<HistoryEntry>() new ImmutableList.Builder<HistoryEntry>()
.addAll(loadAllHistoryObjects(ContactHistory.class, afterTime, beforeTime)) .addAll(loadAllHistoryObjects(ContactHistory.class, afterTime, beforeTime))
@ -84,8 +83,8 @@ public class HistoryEntryDao {
/** Loads all history objects in the time period specified for the given {@link EppResource}. */ /** Loads all history objects in the time period specified for the given {@link EppResource}. */
public static ImmutableList<HistoryEntry> loadHistoryObjectsForResource( public static ImmutableList<HistoryEntry> loadHistoryObjectsForResource(
VKey<? extends EppResource> resourceKey, DateTime afterTime, DateTime beforeTime) { VKey<? extends EppResource> resourceKey, DateTime afterTime, DateTime beforeTime) {
return jpaTm() return tm().transact(
.transact(() -> loadHistoryObjectsForResourceInternal(resourceKey, afterTime, beforeTime)); () -> loadHistoryObjectsForResourceInternal(resourceKey, afterTime, beforeTime));
} }
/** /**
@ -119,8 +118,7 @@ public class HistoryEntryDao {
/** Loads all history objects from all time from the given registrars. */ /** Loads all history objects from all time from the given registrars. */
public static Iterable<HistoryEntry> loadHistoryObjectsByRegistrars( public static Iterable<HistoryEntry> loadHistoryObjectsByRegistrars(
ImmutableCollection<String> registrarIds) { ImmutableCollection<String> registrarIds) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
Streams.concat( Streams.concat(
loadHistoryObjectByRegistrarsInternal(ContactHistory.class, registrarIds), loadHistoryObjectByRegistrarsInternal(ContactHistory.class, registrarIds),
@ -132,8 +130,7 @@ public class HistoryEntryDao {
private static <T extends HistoryEntry> Stream<T> loadHistoryObjectByRegistrarsInternal( private static <T extends HistoryEntry> Stream<T> loadHistoryObjectByRegistrarsInternal(
Class<T> historyClass, ImmutableCollection<String> registrarIds) { Class<T> historyClass, ImmutableCollection<String> registrarIds) {
return jpaTm() return tm().criteriaQuery(
.criteriaQuery(
CriteriaQueryBuilder.create(historyClass) CriteriaQueryBuilder.create(historyClass)
.whereFieldIsIn("clientId", registrarIds) .whereFieldIsIn("clientId", registrarIds)
.build()) .build())
@ -144,7 +141,7 @@ public class HistoryEntryDao {
VKey<? extends EppResource> resourceKey, DateTime afterTime, DateTime beforeTime) { VKey<? extends EppResource> resourceKey, DateTime afterTime, DateTime beforeTime) {
// The class we're searching from is based on which resource type (e.g. Domain) we have // The class we're searching from is based on which resource type (e.g. Domain) we have
Class<? extends HistoryEntry> historyClass = getHistoryClassFromParent(resourceKey.getKind()); Class<? extends HistoryEntry> historyClass = getHistoryClassFromParent(resourceKey.getKind());
CriteriaBuilder criteriaBuilder = jpaTm().getEntityManager().getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = tm().getEntityManager().getCriteriaBuilder();
CriteriaQuery<? extends HistoryEntry> criteriaQuery = CriteriaQuery<? extends HistoryEntry> criteriaQuery =
CriteriaQueryBuilder.create(historyClass) CriteriaQueryBuilder.create(historyClass)
.where("modificationTime", criteriaBuilder::greaterThanOrEqualTo, afterTime) .where("modificationTime", criteriaBuilder::greaterThanOrEqualTo, afterTime)
@ -154,7 +151,7 @@ public class HistoryEntryDao {
.orderByAsc("modificationTime") .orderByAsc("modificationTime")
.build(); .build();
return ImmutableList.copyOf(jpaTm().criteriaQuery(criteriaQuery).getResultList()); return ImmutableList.copyOf(tm().criteriaQuery(criteriaQuery).getResultList());
} }
public static Class<? extends HistoryEntry> getHistoryClassFromParent( public static Class<? extends HistoryEntry> getHistoryClassFromParent(
@ -168,9 +165,8 @@ public class HistoryEntryDao {
private static <T extends HistoryEntry> List<T> loadAllHistoryObjects( private static <T extends HistoryEntry> List<T> loadAllHistoryObjects(
Class<T> historyClass, DateTime afterTime, DateTime beforeTime) { Class<T> historyClass, DateTime afterTime, DateTime beforeTime) {
CriteriaBuilder criteriaBuilder = jpaTm().getEntityManager().getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = tm().getEntityManager().getCriteriaBuilder();
return jpaTm() return tm().criteriaQuery(
.criteriaQuery(
CriteriaQueryBuilder.create(historyClass) CriteriaQueryBuilder.create(historyClass)
.where("modificationTime", criteriaBuilder::greaterThanOrEqualTo, afterTime) .where("modificationTime", criteriaBuilder::greaterThanOrEqualTo, afterTime)
.where("modificationTime", criteriaBuilder::lessThanOrEqualTo, beforeTime) .where("modificationTime", criteriaBuilder::lessThanOrEqualTo, beforeTime)

View file

@ -15,7 +15,7 @@
package google.registry.model.server; package google.registry.model.server;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.isAtOrAfter;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
@ -212,12 +212,11 @@ public class Lock extends ImmutableObject implements Serializable {
String scope = tld != null ? tld : GLOBAL; String scope = tld != null ? tld : GLOBAL;
Supplier<AcquireResult> lockAcquirer = Supplier<AcquireResult> lockAcquirer =
() -> { () -> {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
// Checking if an unexpired lock still exists - if so, the lock can't be acquired. // Checking if an unexpired lock still exists - if so, the lock can't be acquired.
Lock lock = Lock lock =
jpaTm() tm().loadByKeyIfPresent(VKey.create(Lock.class, new LockId(resourceName, scope)))
.loadByKeyIfPresent(VKey.create(Lock.class, new LockId(resourceName, scope)))
.orElse(null); .orElse(null);
if (lock != null) { if (lock != null) {
logger.atInfo().log( logger.atInfo().log(
@ -237,11 +236,11 @@ public class Lock extends ImmutableObject implements Serializable {
Lock newLock = Lock newLock =
create(resourceName, scope, requestStatusChecker.getLogId(), now, leaseLength); create(resourceName, scope, requestStatusChecker.getLogId(), now, leaseLength);
jpaTm().put(newLock); tm().put(newLock);
return AcquireResult.create(now, lock, newLock, lockState); return AcquireResult.create(now, lock, newLock, lockState);
}; };
AcquireResult acquireResult = jpaTm().transactWithoutBackup(lockAcquirer); AcquireResult acquireResult = tm().transactWithoutBackup(lockAcquirer);
logAcquireResult(acquireResult); logAcquireResult(acquireResult);
lockMetrics.recordAcquire(resourceName, scope, acquireResult.lockState()); lockMetrics.recordAcquire(resourceName, scope, acquireResult.lockState());
@ -258,15 +257,15 @@ public class Lock extends ImmutableObject implements Serializable {
// this can happen if release() is called around the expiration time and the lock // this can happen if release() is called around the expiration time and the lock
// expires underneath us. // expires underneath us.
VKey<Lock> key = VKey.create(Lock.class, new LockId(resourceName, scope)); VKey<Lock> key = VKey.create(Lock.class, new LockId(resourceName, scope));
Lock loadedLock = jpaTm().loadByKeyIfPresent(key).orElse(null); Lock loadedLock = tm().loadByKeyIfPresent(key).orElse(null);
if (equals(loadedLock)) { if (equals(loadedLock)) {
// Use deleteIgnoringReadOnly() so that we don't create a commit log entry for deleting // Use deleteIgnoringReadOnly() so that we don't create a commit log entry for deleting
// the lock. // the lock.
logger.atInfo().log("Deleting lock: %s", lockId); logger.atInfo().log("Deleting lock: %s", lockId);
jpaTm().delete(key); tm().delete(key);
lockMetrics.recordRelease( lockMetrics.recordRelease(
resourceName, scope, new Duration(acquiredTime, jpaTm().getTransactionTime())); resourceName, scope, new Duration(acquiredTime, tm().getTransactionTime()));
} else { } else {
logger.atSevere().log( logger.atSevere().log(
"The lock we acquired was transferred to someone else before we" "The lock we acquired was transferred to someone else before we"
@ -278,7 +277,7 @@ public class Lock extends ImmutableObject implements Serializable {
} }
return null; return null;
}; };
jpaTm().transactWithoutBackup(lockReleaser); tm().transactWithoutBackup(lockReleaser);
} }
static class LockId extends ImmutableObject implements Serializable { static class LockId extends ImmutableObject implements Serializable {

View file

@ -14,7 +14,7 @@
package google.registry.model.smd; package google.registry.model.smd;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -28,15 +28,12 @@ public class SignedMarkRevocationListDao {
/** Loads the {@link SignedMarkRevocationList}. */ /** Loads the {@link SignedMarkRevocationList}. */
static SignedMarkRevocationList load() { static SignedMarkRevocationList load() {
Optional<SignedMarkRevocationList> smdrl = Optional<SignedMarkRevocationList> smdrl =
jpaTm() tm().transact(
.transact(
() -> { () -> {
Long revisionId = Long revisionId =
jpaTm() tm().query("SELECT MAX(revisionId) FROM SignedMarkRevocationList", Long.class)
.query("SELECT MAX(revisionId) FROM SignedMarkRevocationList", Long.class)
.getSingleResult(); .getSingleResult();
return jpaTm() return tm().query(
.query(
"FROM SignedMarkRevocationList smrl LEFT JOIN FETCH smrl.revokes " "FROM SignedMarkRevocationList smrl LEFT JOIN FETCH smrl.revokes "
+ "WHERE smrl.revisionId = :revisionId", + "WHERE smrl.revisionId = :revisionId",
SignedMarkRevocationList.class) SignedMarkRevocationList.class)
@ -49,7 +46,7 @@ public class SignedMarkRevocationListDao {
/** Save the given {@link SignedMarkRevocationList} */ /** Save the given {@link SignedMarkRevocationList} */
static void save(SignedMarkRevocationList signedMarkRevocationList) { static void save(SignedMarkRevocationList signedMarkRevocationList) {
jpaTm().transact(() -> jpaTm().insert(signedMarkRevocationList)); tm().transact(() -> tm().insert(signedMarkRevocationList));
logger.atInfo().log( logger.atInfo().log(
"Inserted %,d signed mark revocations into Cloud SQL.", "Inserted %,d signed mark revocations into Cloud SQL.",
signedMarkRevocationList.revokes.size()); signedMarkRevocationList.revokes.size());

View file

@ -22,7 +22,6 @@ import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.filterValues; import static com.google.common.collect.Maps.filterValues;
import static google.registry.model.CacheUtils.memoizeWithShortExpiration; import static google.registry.model.CacheUtils.memoizeWithShortExpiration;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.entriesToImmutableMap; import static google.registry.util.CollectionUtils.entriesToImmutableMap;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
@ -59,7 +58,7 @@ public final class Registries {
() -> () ->
tm().transact( tm().transact(
() -> { () -> {
EntityManager entityManager = jpaTm().getEntityManager(); EntityManager entityManager = tm().getEntityManager();
Stream<?> resultStream = Stream<?> resultStream =
entityManager entityManager
.createQuery("SELECT tldStr, tldType FROM Tld") .createQuery("SELECT tldStr, tldType FROM Tld")

View file

@ -15,7 +15,7 @@
package google.registry.model.tld; package google.registry.model.tld;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.domain.RegistryLock; import google.registry.model.domain.RegistryLock;
@ -26,31 +26,29 @@ public final class RegistryLockDao {
/** Returns the {@link RegistryLock} referred to by this revision ID, or empty if none exists. */ /** Returns the {@link RegistryLock} referred to by this revision ID, or empty if none exists. */
public static Optional<RegistryLock> getByRevisionId(long revisionId) { public static Optional<RegistryLock> getByRevisionId(long revisionId) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
return Optional.ofNullable(jpaTm().getEntityManager().find(RegistryLock.class, revisionId)); return Optional.ofNullable(tm().getEntityManager().find(RegistryLock.class, revisionId));
} }
/** Returns the most recent version of the {@link RegistryLock} referred to by the code. */ /** Returns the most recent version of the {@link RegistryLock} referred to by the code. */
public static Optional<RegistryLock> getByVerificationCode(String verificationCode) { public static Optional<RegistryLock> getByVerificationCode(String verificationCode) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
Long revisionId = Long revisionId =
jpaTm() tm().query(
.query(
"SELECT MAX(revisionId) FROM RegistryLock WHERE verificationCode =" "SELECT MAX(revisionId) FROM RegistryLock WHERE verificationCode ="
+ " :verificationCode", + " :verificationCode",
Long.class) Long.class)
.setParameter("verificationCode", verificationCode) .setParameter("verificationCode", verificationCode)
.getSingleResult(); .getSingleResult();
return Optional.ofNullable(revisionId) return Optional.ofNullable(revisionId)
.map(revision -> jpaTm().getEntityManager().find(RegistryLock.class, revision)); .map(revision -> tm().getEntityManager().find(RegistryLock.class, revision));
} }
/** Returns all lock objects that this registrar has created, including pending locks. */ /** Returns all lock objects that this registrar has created, including pending locks. */
public static ImmutableList<RegistryLock> getLocksByRegistrarId(String registrarId) { public static ImmutableList<RegistryLock> getLocksByRegistrarId(String registrarId) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
return ImmutableList.copyOf( return ImmutableList.copyOf(
jpaTm() tm().query(
.query(
"SELECT lock FROM RegistryLock lock WHERE lock.registrarId = :registrarId" "SELECT lock FROM RegistryLock lock WHERE lock.registrarId = :registrarId"
+ " AND lock.unlockCompletionTime IS NULL ORDER BY lock.domainName ASC", + " AND lock.unlockCompletionTime IS NULL ORDER BY lock.domainName ASC",
RegistryLock.class) RegistryLock.class)
@ -64,9 +62,8 @@ public final class RegistryLockDao {
* <p>Returns empty if this domain hasn't been locked before. * <p>Returns empty if this domain hasn't been locked before.
*/ */
public static Optional<RegistryLock> getMostRecentByRepoId(String repoId) { public static Optional<RegistryLock> getMostRecentByRepoId(String repoId) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
return jpaTm() return tm().query(
.query(
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId" "SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId"
+ " ORDER BY lock.revisionId DESC", + " ORDER BY lock.revisionId DESC",
RegistryLock.class) RegistryLock.class)
@ -83,9 +80,8 @@ public final class RegistryLockDao {
* {@link #getMostRecentByRepoId(String)} in that it only returns verified locks. * {@link #getMostRecentByRepoId(String)} in that it only returns verified locks.
*/ */
public static Optional<RegistryLock> getMostRecentVerifiedLockByRepoId(String repoId) { public static Optional<RegistryLock> getMostRecentVerifiedLockByRepoId(String repoId) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
return jpaTm() return tm().query(
.query(
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND" "SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND"
+ " lock.lockCompletionTime IS NOT NULL AND lock.unlockCompletionTime IS NULL" + " lock.lockCompletionTime IS NOT NULL AND lock.unlockCompletionTime IS NULL"
+ " ORDER BY lock.revisionId DESC", + " ORDER BY lock.revisionId DESC",
@ -103,9 +99,8 @@ public final class RegistryLockDao {
* {@link #getMostRecentByRepoId(String)} in that it only returns verified unlocks. * {@link #getMostRecentByRepoId(String)} in that it only returns verified unlocks.
*/ */
public static Optional<RegistryLock> getMostRecentVerifiedUnlockByRepoId(String repoId) { public static Optional<RegistryLock> getMostRecentVerifiedUnlockByRepoId(String repoId) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
return jpaTm() return tm().query(
.query(
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND" "SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND"
+ " lock.unlockCompletionTime IS NOT NULL ORDER BY lock.revisionId DESC", + " lock.unlockCompletionTime IS NOT NULL ORDER BY lock.revisionId DESC",
RegistryLock.class) RegistryLock.class)
@ -116,8 +111,8 @@ public final class RegistryLockDao {
} }
public static RegistryLock save(RegistryLock registryLock) { public static RegistryLock save(RegistryLock registryLock) {
jpaTm().assertInTransaction(); tm().assertInTransaction();
checkNotNull(registryLock, "Null registry lock cannot be saved"); checkNotNull(registryLock, "Null registry lock cannot be saved");
return jpaTm().getEntityManager().merge(registryLock); return tm().getEntityManager().merge(registryLock);
} }
} }

View file

@ -19,7 +19,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration; import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
import static google.registry.config.RegistryConfig.getSingletonCachePersistDuration; import static google.registry.config.RegistryConfig.getSingletonCachePersistDuration;
import static google.registry.config.RegistryConfig.getStaticPremiumListMaxCachedEntries; import static google.registry.config.RegistryConfig.getStaticPremiumListMaxCachedEntries;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.isNullOrEmpty; import static google.registry.util.CollectionUtils.isNullOrEmpty;
import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.LoadingCache;
@ -135,11 +135,10 @@ public class PremiumListDao {
/** Saves the given premium list (and its premium list entries) to Cloud SQL. */ /** Saves the given premium list (and its premium list entries) to Cloud SQL. */
public static PremiumList save(PremiumList premiumList) { public static PremiumList save(PremiumList premiumList) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
jpaTm().insert(premiumList); tm().insert(premiumList);
jpaTm().getEntityManager().flush(); // This populates the revisionId. tm().getEntityManager().flush(); // This populates the revisionId.
long revisionId = premiumList.getRevisionId(); long revisionId = premiumList.getRevisionId();
if (!isNullOrEmpty(premiumList.getLabelsToPrices())) { if (!isNullOrEmpty(premiumList.getLabelsToPrices())) {
@ -148,7 +147,7 @@ public class PremiumListDao {
.getLabelsToPrices() .getLabelsToPrices()
.forEach( .forEach(
(key, value) -> entries.add(PremiumEntry.create(revisionId, value, key))); (key, value) -> entries.add(PremiumEntry.create(revisionId, value, key)));
jpaTm().insertAll(entries.build()); tm().insertAll(entries.build());
} }
}); });
premiumListCache.invalidate(premiumList.getName()); premiumListCache.invalidate(premiumList.getName());
@ -156,27 +155,23 @@ public class PremiumListDao {
} }
public static void delete(PremiumList premiumList) { public static void delete(PremiumList premiumList) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
Optional<PremiumList> persistedList = getLatestRevision(premiumList.getName()); Optional<PremiumList> persistedList = getLatestRevision(premiumList.getName());
if (persistedList.isPresent()) { if (persistedList.isPresent()) {
jpaTm() tm().query("DELETE FROM PremiumEntry WHERE revisionId = :revisionId")
.query("DELETE FROM PremiumEntry WHERE revisionId = :revisionId")
.setParameter("revisionId", persistedList.get().getRevisionId()) .setParameter("revisionId", persistedList.get().getRevisionId())
.executeUpdate(); .executeUpdate();
jpaTm().delete(persistedList.get()); tm().delete(persistedList.get());
} }
}); });
premiumListCache.invalidate(premiumList.getName()); premiumListCache.invalidate(premiumList.getName());
} }
private static Optional<PremiumList> getLatestRevisionUncached(String premiumListName) { private static Optional<PremiumList> getLatestRevisionUncached(String premiumListName) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query(
.query(
"FROM PremiumList WHERE name = :name ORDER BY revisionId DESC", "FROM PremiumList WHERE name = :name ORDER BY revisionId DESC",
PremiumList.class) PremiumList.class)
.setParameter("name", premiumListName) .setParameter("name", premiumListName)
@ -191,11 +186,9 @@ public class PremiumListDao {
* <p>This is an expensive operation and should only be used when the entire list is required. * <p>This is an expensive operation and should only be used when the entire list is required.
*/ */
public static List<PremiumEntry> loadPremiumEntries(PremiumList premiumList) { public static List<PremiumEntry> loadPremiumEntries(PremiumList premiumList) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query(
.query(
"FROM PremiumEntry pe WHERE pe.revisionId = :revisionId", "FROM PremiumEntry pe WHERE pe.revisionId = :revisionId",
PremiumEntry.class) PremiumEntry.class)
.setParameter("revisionId", premiumList.getRevisionId()) .setParameter("revisionId", premiumList.getRevisionId())
@ -207,11 +200,9 @@ public class PremiumListDao {
* retrieval so it should only be done in a cached context. * retrieval so it should only be done in a cached context.
*/ */
static Optional<BigDecimal> getPriceForLabelUncached(RevisionIdAndLabel revisionIdAndLabel) { static Optional<BigDecimal> getPriceForLabelUncached(RevisionIdAndLabel revisionIdAndLabel) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query(
.query(
"SELECT pe.price FROM PremiumEntry pe WHERE pe.revisionId = :revisionId" "SELECT pe.price FROM PremiumEntry pe WHERE pe.revisionId = :revisionId"
+ " AND pe.domainLabel = :label", + " AND pe.domainLabel = :label",
BigDecimal.class) BigDecimal.class)

View file

@ -22,7 +22,7 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration; import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
import static google.registry.model.tld.label.ReservationType.FULLY_BLOCKED; import static google.registry.model.tld.label.ReservationType.FULLY_BLOCKED;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ; import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.CollectionUtils.nullToEmpty;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -78,8 +78,7 @@ public final class ReservedList
@PreRemove @PreRemove
void preRemove() { void preRemove() {
jpaTm() tm().query("DELETE FROM ReservedEntry WHERE revision_id = :revisionId")
.query("DELETE FROM ReservedEntry WHERE revision_id = :revisionId")
.setParameter("revisionId", revisionId) .setParameter("revisionId", revisionId)
.executeUpdate(); .executeUpdate();
} }
@ -101,7 +100,7 @@ public final class ReservedList
entry -> { entry -> {
// We can safely change the revision id since it's "Insignificant". // We can safely change the revision id since it's "Insignificant".
entry.revisionId = revisionId; entry.revisionId = revisionId;
jpaTm().insert(entry); tm().insert(entry);
}); });
} }
} }
@ -200,10 +199,9 @@ public final class ReservedList
public synchronized ImmutableMap<String, ReservedListEntry> getReservedListEntries() { public synchronized ImmutableMap<String, ReservedListEntry> getReservedListEntries() {
if (reservedListMap == null) { if (reservedListMap == null) {
reservedListMap = reservedListMap =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm()
.createQueryComposer(ReservedListEntry.class) .createQueryComposer(ReservedListEntry.class)
.where("revisionId", EQ, revisionId) .where("revisionId", EQ, revisionId)
.stream() .stream()

View file

@ -14,7 +14,7 @@
package google.registry.model.tld.label; package google.registry.model.tld.label;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
@ -31,7 +31,7 @@ public class ReservedListDao {
public static void save(ReservedList reservedList) { public static void save(ReservedList reservedList) {
checkArgumentNotNull(reservedList, "Must specify reservedList"); checkArgumentNotNull(reservedList, "Must specify reservedList");
logger.atInfo().log("Saving reserved list %s to Cloud SQL.", reservedList.getName()); logger.atInfo().log("Saving reserved list %s to Cloud SQL.", reservedList.getName());
jpaTm().transact(() -> jpaTm().insert(reservedList)); tm().transact(() -> tm().insert(reservedList));
logger.atInfo().log( logger.atInfo().log(
"Saved reserved list %s with %d entries to Cloud SQL.", "Saved reserved list %s with %d entries to Cloud SQL.",
reservedList.getName(), reservedList.getReservedListEntries().size()); reservedList.getName(), reservedList.getReservedListEntries().size());
@ -39,7 +39,7 @@ public class ReservedListDao {
/** Deletes a reserved list from Cloud SQL. */ /** Deletes a reserved list from Cloud SQL. */
public static void delete(ReservedList reservedList) { public static void delete(ReservedList reservedList) {
jpaTm().transact(() -> jpaTm().delete(reservedList)); tm().transact(() -> tm().delete(reservedList));
} }
/** /**
@ -47,11 +47,9 @@ public class ReservedListDao {
* exists. * exists.
*/ */
public static Optional<ReservedList> getLatestRevision(String reservedListName) { public static Optional<ReservedList> getLatestRevision(String reservedListName) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query(
.query(
"FROM ReservedList WHERE revisionId IN " "FROM ReservedList WHERE revisionId IN "
+ "(SELECT MAX(revisionId) FROM ReservedList WHERE name = :name)", + "(SELECT MAX(revisionId) FROM ReservedList WHERE name = :name)",
ReservedList.class) ReservedList.class)
@ -66,11 +64,9 @@ public class ReservedListDao {
* <p>This means that at least one reserved list revision must exist for the given name. * <p>This means that at least one reserved list revision must exist for the given name.
*/ */
public static boolean checkExists(String reservedListName) { public static boolean checkExists(String reservedListName) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query("SELECT 1 FROM ReservedList WHERE name = :name", Integer.class)
.query("SELECT 1 FROM ReservedList WHERE name = :name", Integer.class)
.setParameter("name", reservedListName) .setParameter("name", reservedListName)
.setMaxResults(1) .setMaxResults(1)
.getResultList() .getResultList()

View file

@ -18,7 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ; import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -104,8 +104,7 @@ public class ClaimsList extends ImmutableObject {
@PreRemove @PreRemove
void preRemove() { void preRemove() {
jpaTm() tm().query("DELETE FROM ClaimsEntry WHERE revision_id = :revisionId")
.query("DELETE FROM ClaimsEntry WHERE revision_id = :revisionId")
.setParameter("revisionId", revisionId) .setParameter("revisionId", revisionId)
.executeUpdate(); .executeUpdate();
} }
@ -123,7 +122,7 @@ public class ClaimsList extends ImmutableObject {
if (labelsToKeys != null) { if (labelsToKeys != null) {
labelsToKeys.forEach( labelsToKeys.forEach(
(domainLabel, claimKey) -> (domainLabel, claimKey) ->
jpaTm().insert(new ClaimsEntry(revisionId, domainLabel, claimKey))); tm().insert(new ClaimsEntry(revisionId, domainLabel, claimKey)));
} }
} }
@ -169,10 +168,9 @@ public class ClaimsList extends ImmutableObject {
public ImmutableMap<String, String> getLabelsToKeys() { public ImmutableMap<String, String> getLabelsToKeys() {
if (labelsToKeys == null) { if (labelsToKeys == null) {
labelsToKeys = labelsToKeys =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm()
.createQueryComposer(ClaimsEntry.class) .createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId) .where("revisionId", EQ, revisionId)
.stream() .stream()
@ -191,8 +189,7 @@ public class ClaimsList extends ImmutableObject {
*/ */
public long size() { public long size() {
if (labelsToKeys == null) { if (labelsToKeys == null) {
return jpaTm() return tm().createQueryComposer(ClaimsEntry.class)
.createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId) .where("revisionId", EQ, revisionId)
.count(); .count();
} }
@ -209,11 +206,9 @@ public class ClaimsList extends ImmutableObject {
if (labelsToKeys != null) { if (labelsToKeys != null) {
return Optional.ofNullable(labelsToKeys.get(label)); return Optional.ofNullable(labelsToKeys.get(label));
} }
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().createQueryComposer(ClaimsEntry.class)
.createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId) .where("revisionId", EQ, revisionId)
.where("domainLabel", EQ, label) .where("domainLabel", EQ, label)
.first() .first()

View file

@ -16,7 +16,7 @@ package google.registry.model.tmch;
import static google.registry.config.RegistryConfig.getClaimsListCacheDuration; import static google.registry.config.RegistryConfig.getClaimsListCacheDuration;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ; import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.LoadingCache;
@ -51,7 +51,7 @@ public class ClaimsListDao {
/** Saves the given {@link ClaimsList} to Cloud SQL. */ /** Saves the given {@link ClaimsList} to Cloud SQL. */
public static void save(ClaimsList claimsList) { public static void save(ClaimsList claimsList) {
jpaTm().transact(() -> jpaTm().insert(claimsList)); tm().transact(() -> tm().insert(claimsList));
CACHE.put(ClaimsListDao.class, claimsList); CACHE.put(ClaimsListDao.class, claimsList);
} }
@ -65,15 +65,12 @@ public class ClaimsListDao {
* doesn't exist. * doesn't exist.
*/ */
private static ClaimsList getUncached() { private static ClaimsList getUncached() {
return jpaTm() return tm().transact(
.transact(
() -> { () -> {
Long revisionId = Long revisionId =
jpaTm() tm().query("SELECT MAX(revisionId) FROM ClaimsList", Long.class)
.query("SELECT MAX(revisionId) FROM ClaimsList", Long.class)
.getSingleResult(); .getSingleResult();
return jpaTm() return tm().createQueryComposer(ClaimsList.class)
.createQueryComposer(ClaimsList.class)
.where("revisionId", EQ, revisionId) .where("revisionId", EQ, revisionId)
.first(); .first();
}) })

View file

@ -15,7 +15,7 @@
package google.registry.model.tmch; package google.registry.model.tmch;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import google.registry.model.common.CrossTldSingleton; import google.registry.model.common.CrossTldSingleton;
import java.util.Optional; import java.util.Optional;
@ -39,7 +39,7 @@ public final class TmchCrl extends CrossTldSingleton {
/** Returns the singleton instance of this entity, without memoization. */ /** Returns the singleton instance of this entity, without memoization. */
public static Optional<TmchCrl> get() { public static Optional<TmchCrl> get() {
return jpaTm().transact(() -> jpaTm().loadSingleton(TmchCrl.class)); return tm().transact(() -> tm().loadSingleton(TmchCrl.class));
} }
/** /**
@ -49,14 +49,13 @@ public final class TmchCrl extends CrossTldSingleton {
* and actually newer than the one currently in the database. * and actually newer than the one currently in the database.
*/ */
public static void set(final String crl, final String url) { public static void set(final String crl, final String url) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
TmchCrl tmchCrl = new TmchCrl(); TmchCrl tmchCrl = new TmchCrl();
tmchCrl.updated = jpaTm().getTransactionTime(); tmchCrl.updated = tm().getTransactionTime();
tmchCrl.crl = checkNotNull(crl, "crl"); tmchCrl.crl = checkNotNull(crl, "crl");
tmchCrl.url = checkNotNull(url, "url"); tmchCrl.url = checkNotNull(url, "url");
jpaTm().put(tmchCrl); tm().put(tmchCrl);
}); });
} }

View file

@ -14,7 +14,7 @@
package google.registry.persistence.transaction; package google.registry.persistence.transaction;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.util.Collection; import java.util.Collection;
@ -104,7 +104,7 @@ public class CriteriaQueryBuilder<T> {
/** Creates a query builder that will SELECT from the given class. */ /** Creates a query builder that will SELECT from the given class. */
public static <T> CriteriaQueryBuilder<T> create(Class<T> clazz) { public static <T> CriteriaQueryBuilder<T> create(Class<T> clazz) {
return create(jpaTm(), clazz); return create(tm(), clazz);
} }
/** Creates a query builder for the given entity manager. */ /** Creates a query builder for the given entity manager. */

View file

@ -20,8 +20,8 @@ import java.lang.reflect.Proxy;
* A dummy implementation for {@link JpaTransactionManager} which throws exception when any of its * A dummy implementation for {@link JpaTransactionManager} which throws exception when any of its
* method is invoked. * method is invoked.
* *
* <p>This is used to initialize the {@link TransactionManagerFactory#jpaTm()} when running unit * <p>This is used to initialize the {@link TransactionManagerFactory#tm()} when running unit tests,
* tests, because obviously we cannot connect to the actual Cloud SQL backend in a unit test. * because obviously we cannot connect to the actual Cloud SQL backend in a unit test.
* *
* <p>If a unit test needs to access the Cloud SQL database, it must add {@code * <p>If a unit test needs to access the Cloud SQL database, it must add {@code
* JpaTransactionManagerExtension} as a JUnit extension in the test class. * JpaTransactionManagerExtension} as a JUnit extension in the test class.

View file

@ -14,7 +14,7 @@
package google.registry.persistence.transaction; package google.registry.persistence.transaction;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -210,7 +210,7 @@ public abstract class QueryComposer<T> {
} }
public void addToCriteriaQueryBuilder(CriteriaQueryBuilder queryBuilder) { public void addToCriteriaQueryBuilder(CriteriaQueryBuilder queryBuilder) {
CriteriaBuilder criteriaBuilder = jpaTm().getEntityManager().getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = tm().getEntityManager().getCriteriaBuilder();
queryBuilder.where( queryBuilder.where(
fieldName, comparator.getComparisonFactory().apply(criteriaBuilder), value); fieldName, comparator.getComparisonFactory().apply(criteriaBuilder), value);
} }

View file

@ -19,22 +19,16 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.appengine.api.utils.SystemProperty; import com.google.appengine.api.utils.SystemProperty;
import com.google.appengine.api.utils.SystemProperty.Environment.Value; import com.google.appengine.api.utils.SystemProperty.Environment.Value;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import google.registry.config.RegistryEnvironment; import google.registry.config.RegistryEnvironment;
import google.registry.persistence.DaggerPersistenceComponent; import google.registry.persistence.DaggerPersistenceComponent;
import google.registry.tools.RegistryToolEnvironment; import google.registry.tools.RegistryToolEnvironment;
import google.registry.util.NonFinalForTesting; import google.registry.util.NonFinalForTesting;
import java.util.Optional;
import java.util.function.Supplier; import java.util.function.Supplier;
/** Factory class to create {@link TransactionManager} instance. */ /** Factory class to create {@link TransactionManager} instance. */
// TODO: Rename this to PersistenceFactory and move to persistence package.
public final class TransactionManagerFactory { public final class TransactionManagerFactory {
/** Optional override to manually set the transaction manager per-test. */
private static Optional<TransactionManager> tmForTest = Optional.empty();
/** Supplier for jpaTm so that it is initialized only once, upon first usage. */ /** Supplier for jpaTm so that it is initialized only once, upon first usage. */
@NonFinalForTesting @NonFinalForTesting
private static Supplier<JpaTransactionManager> jpaTm = private static Supplier<JpaTransactionManager> jpaTm =
@ -77,42 +71,22 @@ public final class TransactionManagerFactory {
return SystemProperty.environment.value() == Value.Production; return SystemProperty.environment.value() == Value.Production;
} }
/**
* Returns the {@link TransactionManager} instance.
*
* <p>Returns the {@link JpaTransactionManager} or replica based on the possible manually
* specified per-test transaction manager.
*/
public static TransactionManager tm() {
return tmForTest.orElseGet(TransactionManagerFactory::jpaTm);
}
/** /**
* Returns {@link JpaTransactionManager} instance. * Returns {@link JpaTransactionManager} instance.
* *
* <p>Between invocations of {@link TransactionManagerFactory#setJpaTm} every call to this method * <p>Between invocations of {@link TransactionManagerFactory#setJpaTm} every call to this method
* returns the same instance. * returns the same instance.
*/ */
public static JpaTransactionManager jpaTm() { public static JpaTransactionManager tm() {
return jpaTm.get(); return jpaTm.get();
} }
/** Returns a read-only {@link JpaTransactionManager} instance if configured. */ /** Returns a read-only {@link JpaTransactionManager} instance if configured. */
public static JpaTransactionManager replicaJpaTm() { public static JpaTransactionManager replicaTm() {
return replicaJpaTm.get(); return replicaJpaTm.get();
} }
/** /** Sets the return of {@link #tm()} to the given instance of {@link JpaTransactionManager}. */
* Returns a {@link TransactionManager} that uses a replica database if one exists.
*
* <p>In Datastore mode, this is unchanged from the regular transaction manager. In SQL mode,
* however, this will be a reference to the read-only replica database if one is configured.
*/
public static TransactionManager replicaTm() {
return replicaJpaTm();
}
/** Sets the return of {@link #jpaTm()} to the given instance of {@link JpaTransactionManager}. */
public static void setJpaTm(Supplier<JpaTransactionManager> jpaTmSupplier) { public static void setJpaTm(Supplier<JpaTransactionManager> jpaTmSupplier) {
checkArgumentNotNull(jpaTmSupplier, "jpaTmSupplier"); checkArgumentNotNull(jpaTmSupplier, "jpaTmSupplier");
checkState( checkState(
@ -122,7 +96,7 @@ public final class TransactionManagerFactory {
jpaTm = Suppliers.memoize(jpaTmSupplier::get); jpaTm = Suppliers.memoize(jpaTmSupplier::get);
} }
/** Sets the value of {@link #replicaJpaTm()} to the given {@link JpaTransactionManager}. */ /** Sets the value of {@link #replicaTm()} to the given {@link JpaTransactionManager}. */
public static void setReplicaJpaTm(Supplier<JpaTransactionManager> replicaJpaTmSupplier) { public static void setReplicaJpaTm(Supplier<JpaTransactionManager> replicaJpaTmSupplier) {
checkArgumentNotNull(replicaJpaTmSupplier, "replicaJpaTmSupplier"); checkArgumentNotNull(replicaJpaTmSupplier, "replicaJpaTmSupplier");
checkState( checkState(
@ -133,7 +107,7 @@ public final class TransactionManagerFactory {
} }
/** /**
* Makes {@link #jpaTm()} return the {@link JpaTransactionManager} instance provided by {@code * Makes {@link #tm()} return the {@link JpaTransactionManager} instance provided by {@code
* jpaTmSupplier} from now on. This method should only be called by an implementor of {@link * jpaTmSupplier} from now on. This method should only be called by an implementor of {@link
* org.apache.beam.sdk.harness.JvmInitializer}. * org.apache.beam.sdk.harness.JvmInitializer}.
*/ */
@ -141,24 +115,4 @@ public final class TransactionManagerFactory {
checkArgumentNotNull(jpaTmSupplier, "jpaTmSupplier"); checkArgumentNotNull(jpaTmSupplier, "jpaTmSupplier");
jpaTm = Suppliers.memoize(jpaTmSupplier::get); jpaTm = Suppliers.memoize(jpaTmSupplier::get);
} }
/**
* Sets the return of {@link #tm()} to the given instance of {@link TransactionManager}.
*
* <p>DO NOT CALL THIS DIRECTLY IF POSSIBLE. Strongly prefer the use of <code>TmOverrideExtension
* </code> in test code instead.
*
* <p>Used when overriding the per-test transaction manager for dual-database tests. Should be
* matched with a corresponding invocation of {@link #removeTmOverrideForTest()} either at the end
* of the test or in an <code>@AfterEach</code> handler.
*/
@VisibleForTesting
public static void setTmOverrideForTest(TransactionManager newTmOverride) {
tmForTest = Optional.of(newTmOverride);
}
/** Resets the overridden transaction manager post-test. */
public static void removeTmOverrideForTest() {
tmForTest = Optional.empty();
}
} }

View file

@ -16,7 +16,7 @@ package google.registry.rdap;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.model.EppResourceUtils.loadByForeignKeyCached; import static google.registry.model.EppResourceUtils.loadByForeignKeyCached;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD; import static google.registry.request.Action.Method.HEAD;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
@ -203,13 +203,13 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
int querySizeLimit = RESULT_SET_SIZE_SCALING_FACTOR * rdapResultSetMaxSize; int querySizeLimit = RESULT_SET_SIZE_SCALING_FACTOR * rdapResultSetMaxSize;
RdapResultSet<Domain> resultSet; RdapResultSet<Domain> resultSet;
resultSet = resultSet =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> { () -> {
CriteriaBuilder criteriaBuilder = CriteriaBuilder criteriaBuilder =
replicaJpaTm().getEntityManager().getCriteriaBuilder(); replicaTm().getEntityManager().getCriteriaBuilder();
CriteriaQueryBuilder<Domain> queryBuilder = CriteriaQueryBuilder<Domain> queryBuilder =
CriteriaQueryBuilder.create(replicaJpaTm(), Domain.class) CriteriaQueryBuilder.create(replicaTm(), Domain.class)
.where( .where(
"domainName", "domainName",
criteriaBuilder::like, criteriaBuilder::like,
@ -239,7 +239,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
int querySizeLimit = RESULT_SET_SIZE_SCALING_FACTOR * rdapResultSetMaxSize; int querySizeLimit = RESULT_SET_SIZE_SCALING_FACTOR * rdapResultSetMaxSize;
RdapResultSet<Domain> resultSet; RdapResultSet<Domain> resultSet;
resultSet = resultSet =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> { () -> {
CriteriaQueryBuilder<Domain> builder = CriteriaQueryBuilder<Domain> builder =
@ -305,7 +305,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
// incomplete result set if a search asks for something like "ns*", but we need to enforce a // incomplete result set if a search asks for something like "ns*", but we need to enforce a
// limit in order to avoid arbitrarily long-running queries. // limit in order to avoid arbitrarily long-running queries.
Optional<String> desiredRegistrar = getDesiredRegistrar(); Optional<String> desiredRegistrar = getDesiredRegistrar();
return replicaJpaTm() return replicaTm()
.transact( .transact(
() -> { () -> {
CriteriaQueryBuilder<Host> builder = CriteriaQueryBuilder<Host> builder =
@ -319,7 +319,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
builder = builder =
builder.where( builder.where(
"currentSponsorRegistrarId", "currentSponsorRegistrarId",
replicaJpaTm().getEntityManager().getCriteriaBuilder()::equal, replicaTm().getEntityManager().getCriteriaBuilder()::equal,
desiredRegistrar.get()); desiredRegistrar.get());
} }
return getMatchingResources(builder, true, maxNameserversInFirstStage) return getMatchingResources(builder, true, maxNameserversInFirstStage)
@ -438,11 +438,11 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
parameters.put("desiredRegistrar", desiredRegistrar.get()); parameters.put("desiredRegistrar", desiredRegistrar.get());
} }
hostKeys = hostKeys =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> { () -> {
javax.persistence.Query query = javax.persistence.Query query =
replicaJpaTm() replicaTm()
.getEntityManager() .getEntityManager()
.createNativeQuery(queryBuilder.toString()) .createNativeQuery(queryBuilder.toString())
.setMaxResults(maxNameserversInFirstStage); .setMaxResults(maxNameserversInFirstStage);
@ -475,37 +475,37 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
int numHostKeysSearched = 0; int numHostKeysSearched = 0;
for (List<VKey<Host>> chunk : Iterables.partition(hostKeys, 30)) { for (List<VKey<Host>> chunk : Iterables.partition(hostKeys, 30)) {
numHostKeysSearched += chunk.size(); numHostKeysSearched += chunk.size();
replicaJpaTm() replicaTm()
.transact( .transact(
() -> { () -> {
for (VKey<Host> hostKey : hostKeys) { for (VKey<Host> hostKey : hostKeys) {
CriteriaQueryBuilder<Domain> queryBuilder = CriteriaQueryBuilder<Domain> queryBuilder =
CriteriaQueryBuilder.create(replicaJpaTm(), Domain.class) CriteriaQueryBuilder.create(replicaTm(), Domain.class)
.whereFieldContains("nsHosts", hostKey) .whereFieldContains("nsHosts", hostKey)
.orderByAsc("domainName"); .orderByAsc("domainName");
CriteriaBuilder criteriaBuilder = CriteriaBuilder criteriaBuilder =
replicaJpaTm().getEntityManager().getCriteriaBuilder(); replicaTm().getEntityManager().getCriteriaBuilder();
if (!shouldIncludeDeleted()) { if (!shouldIncludeDeleted()) {
queryBuilder = queryBuilder =
queryBuilder.where( queryBuilder.where(
"deletionTime", criteriaBuilder::greaterThan, getRequestTime()); "deletionTime", criteriaBuilder::greaterThan, getRequestTime());
}
if (cursorString.isPresent()) {
queryBuilder =
queryBuilder.where(
"domainName", criteriaBuilder::greaterThan, cursorString.get());
}
replicaJpaTm()
.criteriaQuery(queryBuilder.build())
.getResultStream()
.filter(this::isAuthorized)
.forEach(
(domain) -> {
Hibernate.initialize(domain.getDsData());
domainSetBuilder.add(domain);
});
} }
}); if (cursorString.isPresent()) {
queryBuilder =
queryBuilder.where(
"domainName", criteriaBuilder::greaterThan, cursorString.get());
}
replicaTm()
.criteriaQuery(queryBuilder.build())
.getResultStream()
.filter(this::isAuthorized)
.forEach(
(domain) -> {
Hibernate.initialize(domain.getDsData());
domainSetBuilder.add(domain);
});
}
});
} }
List<Domain> domains = domainSetBuilder.build().asList(); List<Domain> domains = domainSetBuilder.build().asList();
metricInformationBuilder.setNumHostsRetrieved(numHostKeysSearched); metricInformationBuilder.setNumHostsRetrieved(numHostKeysSearched);

View file

@ -14,7 +14,7 @@
package google.registry.rdap; package google.registry.rdap;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier; import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier;
import static google.registry.rdap.RdapUtils.getRegistrarByName; import static google.registry.rdap.RdapUtils.getRegistrarByName;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
@ -71,7 +71,7 @@ public class RdapEntityAction extends RdapActionBase {
if (ROID_PATTERN.matcher(pathSearchString).matches()) { if (ROID_PATTERN.matcher(pathSearchString).matches()) {
VKey<Contact> contactVKey = VKey.create(Contact.class, pathSearchString); VKey<Contact> contactVKey = VKey.create(Contact.class, pathSearchString);
Optional<Contact> contact = Optional<Contact> contact =
replicaJpaTm().transact(() -> replicaJpaTm().loadByKeyIfPresent(contactVKey)); replicaTm().transact(() -> replicaTm().loadByKeyIfPresent(contactVKey));
// As per Andy Newton on the regext mailing list, contacts by themselves have no role, since // As per Andy Newton on the regext mailing list, contacts by themselves have no role, since
// they are global, and might have different roles for different domains. // they are global, and might have different roles for different domains.
if (contact.isPresent() && isAuthorized(contact.get())) { if (contact.isPresent() && isAuthorized(contact.get())) {

View file

@ -15,7 +15,7 @@
package google.registry.rdap; package google.registry.rdap;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier; import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD; import static google.registry.request.Action.Method.HEAD;
@ -260,7 +260,7 @@ public class RdapEntitySearchAction extends RdapSearchActionBase {
resultSet = RdapResultSet.create(ImmutableList.of()); resultSet = RdapResultSet.create(ImmutableList.of());
} else { } else {
resultSet = resultSet =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> { () -> {
CriteriaQueryBuilder<Contact> builder = CriteriaQueryBuilder<Contact> builder =
@ -307,10 +307,10 @@ public class RdapEntitySearchAction extends RdapSearchActionBase {
contactList = ImmutableList.of(); contactList = ImmutableList.of();
} else { } else {
Optional<Contact> contact = Optional<Contact> contact =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> () ->
replicaJpaTm() replicaTm()
.loadByKeyIfPresent( .loadByKeyIfPresent(
VKey.create(Contact.class, partialStringQuery.getInitialString()))); VKey.create(Contact.class, partialStringQuery.getInitialString())));
contactList = contactList =
@ -370,7 +370,7 @@ public class RdapEntitySearchAction extends RdapSearchActionBase {
contactResultSet = RdapResultSet.create(ImmutableList.of()); contactResultSet = RdapResultSet.create(ImmutableList.of());
} else { } else {
contactResultSet = contactResultSet =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> () ->
getMatchingResources( getMatchingResources(

View file

@ -20,7 +20,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap; import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
import static google.registry.model.EppResourceUtils.isLinked; import static google.registry.model.EppResourceUtils.isLinked;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.rdap.RdapIcannStandardInformation.CONTACT_REDACTED_VALUE; import static google.registry.rdap.RdapIcannStandardInformation.CONTACT_REDACTED_VALUE;
import static google.registry.util.CollectionUtils.union; import static google.registry.util.CollectionUtils.union;
@ -366,15 +366,13 @@ public class RdapJsonFormatter {
// Kick off the database loads of the nameservers that we will need, so it can load // Kick off the database loads of the nameservers that we will need, so it can load
// asynchronously while we load and process the contacts. // asynchronously while we load and process the contacts.
ImmutableSet<Host> loadedHosts = ImmutableSet<Host> loadedHosts =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> () ->
ImmutableSet.copyOf( ImmutableSet.copyOf(replicaTm().loadByKeys(domain.getNameservers()).values()));
replicaJpaTm().loadByKeys(domain.getNameservers()).values()));
// Load the registrant and other contacts and add them to the data. // Load the registrant and other contacts and add them to the data.
ImmutableMap<VKey<? extends Contact>, Contact> loadedContacts = ImmutableMap<VKey<? extends Contact>, Contact> loadedContacts =
replicaJpaTm() replicaTm().transact(() -> replicaTm().loadByKeysIfPresent(domain.getReferencedContacts()));
.transact(() -> replicaJpaTm().loadByKeysIfPresent(domain.getReferencedContacts()));
// RDAP Response Profile 2.7.3, A domain MUST have the REGISTRANT, ADMIN, TECH roles and MAY // RDAP Response Profile 2.7.3, A domain MUST have the REGISTRANT, ADMIN, TECH roles and MAY
// have others. We also add the BILLING. // have others. We also add the BILLING.
// //
@ -453,10 +451,10 @@ public class RdapJsonFormatter {
statuses.add(StatusValue.LINKED); statuses.add(StatusValue.LINKED);
} }
if (host.isSubordinate() if (host.isSubordinate()
&& replicaJpaTm() && replicaTm()
.transact( .transact(
() -> () ->
replicaJpaTm() replicaTm()
.loadByKey(host.getSuperordinateDomain()) .loadByKey(host.getSuperordinateDomain())
.cloneProjectedAtTime(getRequestTime()) .cloneProjectedAtTime(getRequestTime())
.getStatusValues() .getStatusValues()
@ -907,10 +905,10 @@ public class RdapJsonFormatter {
.replace("%entityName%", entityName) .replace("%entityName%", entityName)
.replace("%repoIdValue%", resourceVkey.getKey().toString()); .replace("%repoIdValue%", resourceVkey.getKey().toString());
Iterable<HistoryEntry> historyEntries = Iterable<HistoryEntry> historyEntries =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> () ->
replicaJpaTm() replicaTm()
.getEntityManager() .getEntityManager()
.createQuery(jpql, HistoryEntry.class) .createQuery(jpql, HistoryEntry.class)
.getResultList()); .getResultList());

View file

@ -15,7 +15,7 @@
package google.registry.rdap; package google.registry.rdap;
import static google.registry.model.EppResourceUtils.loadByForeignKeyCached; import static google.registry.model.EppResourceUtils.loadByForeignKeyCached;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD; import static google.registry.request.Action.Method.HEAD;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
@ -217,7 +217,7 @@ public class RdapNameserverSearchAction extends RdapSearchActionBase {
private NameserverSearchResponse searchByNameUsingPrefix(RdapSearchPattern partialStringQuery) { private NameserverSearchResponse searchByNameUsingPrefix(RdapSearchPattern partialStringQuery) {
// Add 1 so we can detect truncation. // Add 1 so we can detect truncation.
int querySizeLimit = getStandardQuerySizeLimit(); int querySizeLimit = getStandardQuerySizeLimit();
return replicaJpaTm() return replicaTm()
.transact( .transact(
() -> { () -> {
CriteriaQueryBuilder<Host> queryBuilder = CriteriaQueryBuilder<Host> queryBuilder =
@ -260,20 +260,20 @@ public class RdapNameserverSearchAction extends RdapSearchActionBase {
parameters.put("desiredRegistrar", getDesiredRegistrar().get()); parameters.put("desiredRegistrar", getDesiredRegistrar().get());
} }
queryBuilder.append(" ORDER BY repo_id ASC"); queryBuilder.append(" ORDER BY repo_id ASC");
rdapResultSet = rdapResultSet =
replicaJpaTm() replicaTm()
.transact( .transact(
() -> { () -> {
javax.persistence.Query query = javax.persistence.Query query =
replicaJpaTm() replicaTm()
.getEntityManager() .getEntityManager()
.createNativeQuery(queryBuilder.toString(), Host.class) .createNativeQuery(queryBuilder.toString(), Host.class)
.setMaxResults(querySizeLimit); .setMaxResults(querySizeLimit);
parameters.build().forEach(query::setParameter); parameters.build().forEach(query::setParameter);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Host> resultList = query.getResultList(); List<Host> resultList = query.getResultList();
return filterResourcesByVisibility(resultList, querySizeLimit); return filterResourcesByVisibility(resultList, querySizeLimit);
}); });
return makeSearchResults(rdapResultSet, CursorType.ADDRESS); return makeSearchResults(rdapResultSet, CursorType.ADDRESS);
} }

View file

@ -15,7 +15,7 @@
package google.registry.rdap; package google.registry.rdap;
import static com.google.common.base.Charsets.UTF_8; import static com.google.common.base.Charsets.UTF_8;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -158,17 +158,17 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
*/ */
<T extends EppResource> RdapResultSet<T> getMatchingResources( <T extends EppResource> RdapResultSet<T> getMatchingResources(
CriteriaQueryBuilder<T> builder, boolean checkForVisibility, int querySizeLimit) { CriteriaQueryBuilder<T> builder, boolean checkForVisibility, int querySizeLimit) {
replicaJpaTm().assertInTransaction(); replicaTm().assertInTransaction();
Optional<String> desiredRegistrar = getDesiredRegistrar(); Optional<String> desiredRegistrar = getDesiredRegistrar();
if (desiredRegistrar.isPresent()) { if (desiredRegistrar.isPresent()) {
builder = builder =
builder.where( builder.where(
"currentSponsorRegistrarId", "currentSponsorRegistrarId",
replicaJpaTm().getEntityManager().getCriteriaBuilder()::equal, replicaTm().getEntityManager().getCriteriaBuilder()::equal,
desiredRegistrar.get()); desiredRegistrar.get());
} }
List<T> queryResult = List<T> queryResult =
replicaJpaTm().criteriaQuery(builder.build()).setMaxResults(querySizeLimit).getResultList(); replicaTm().criteriaQuery(builder.build()).setMaxResults(querySizeLimit).getResultList();
if (checkForVisibility) { if (checkForVisibility) {
return filterResourcesByVisibility(queryResult, querySizeLimit); return filterResourcesByVisibility(queryResult, querySizeLimit);
} else { } else {
@ -311,7 +311,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
RdapSearchPattern partialStringQuery, RdapSearchPattern partialStringQuery,
Optional<String> cursorString, Optional<String> cursorString,
DeletedItemHandling deletedItemHandling) { DeletedItemHandling deletedItemHandling) {
replicaJpaTm().assertInTransaction(); replicaTm().assertInTransaction();
if (partialStringQuery.getInitialString().length() if (partialStringQuery.getInitialString().length()
< RdapSearchPattern.MIN_INITIAL_STRING_LENGTH) { < RdapSearchPattern.MIN_INITIAL_STRING_LENGTH) {
throw new UnprocessableEntityException( throw new UnprocessableEntityException(
@ -319,8 +319,8 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
"Initial search string must be at least %d characters", "Initial search string must be at least %d characters",
RdapSearchPattern.MIN_INITIAL_STRING_LENGTH)); RdapSearchPattern.MIN_INITIAL_STRING_LENGTH));
} }
CriteriaBuilder criteriaBuilder = replicaJpaTm().getEntityManager().getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = replicaTm().getEntityManager().getCriteriaBuilder();
CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaJpaTm(), clazz); CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaTm(), clazz);
if (partialStringQuery.getHasWildcard()) { if (partialStringQuery.getHasWildcard()) {
builder = builder =
builder.where( builder.where(
@ -367,9 +367,9 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
"Initial search string must be at least %d characters", "Initial search string must be at least %d characters",
RdapSearchPattern.MIN_INITIAL_STRING_LENGTH)); RdapSearchPattern.MIN_INITIAL_STRING_LENGTH));
} }
replicaJpaTm().assertInTransaction(); replicaTm().assertInTransaction();
CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaJpaTm(), clazz); CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaTm(), clazz);
CriteriaBuilder criteriaBuilder = replicaJpaTm().getEntityManager().getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = replicaTm().getEntityManager().getCriteriaBuilder();
builder = builder.where(filterField, criteriaBuilder::equal, queryString); builder = builder.where(filterField, criteriaBuilder::equal, queryString);
if (cursorString.isPresent()) { if (cursorString.isPresent()) {
if (cursorField.isPresent()) { if (cursorField.isPresent()) {
@ -388,7 +388,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
RdapSearchPattern partialStringQuery, RdapSearchPattern partialStringQuery,
Optional<String> cursorString, Optional<String> cursorString,
DeletedItemHandling deletedItemHandling) { DeletedItemHandling deletedItemHandling) {
replicaJpaTm().assertInTransaction(); replicaTm().assertInTransaction();
return queryItems(clazz, "repoId", partialStringQuery, cursorString, deletedItemHandling); return queryItems(clazz, "repoId", partialStringQuery, cursorString, deletedItemHandling);
} }
@ -398,7 +398,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
builder = builder =
builder.where( builder.where(
"deletionTime", "deletionTime",
replicaJpaTm().getEntityManager().getCriteriaBuilder()::equal, replicaTm().getEntityManager().getCriteriaBuilder()::equal,
END_OF_TIME); END_OF_TIME);
} }
return builder; return builder;

View file

@ -16,7 +16,6 @@ package google.registry.request.auth;
import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.appengine.api.users.User; import com.google.appengine.api.users.User;
@ -311,11 +310,9 @@ public class AuthenticatedRegistrarAccessor {
logger.atInfo().log("Checking registrar contacts for user ID %s.", user.getEmail()); logger.atInfo().log("Checking registrar contacts for user ID %s.", user.getEmail());
// Find all registrars that have a registrar contact with this user's ID. // Find all registrars that have a registrar contact with this user's ID.
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().query(
.query(
"SELECT r FROM Registrar r INNER JOIN RegistrarPoc rp ON r.registrarId =" "SELECT r FROM Registrar r INNER JOIN RegistrarPoc rp ON r.registrarId ="
+ " rp.registrarId WHERE lower(rp.loginEmailAddress) = :email AND" + " rp.registrarId WHERE lower(rp.loginEmailAddress) = :email AND"
+ " r.state != :state", + " r.state != :state",

View file

@ -18,7 +18,7 @@ import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.flows.poll.PollFlowUtils.createPollMessageQuery; import static google.registry.flows.poll.PollFlowUtils.createPollMessageQuery;
import static google.registry.model.poll.PollMessageExternalKeyConverter.makePollMessageExternalId; import static google.registry.model.poll.PollMessageExternalKeyConverter.makePollMessageExternalId;
import static google.registry.persistence.transaction.QueryComposer.Comparator.LIKE; import static google.registry.persistence.transaction.QueryComposer.Comparator.LIKE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
@ -81,8 +81,7 @@ final class AckPollMessagesCommand implements Command {
/** Loads and acks all matching poll messages from SQL in one transaction. */ /** Loads and acks all matching poll messages from SQL in one transaction. */
private void ackPollMessagesSql() { private void ackPollMessagesSql() {
jpaTm() tm().transact(
.transact(
() -> { () -> {
QueryComposer<PollMessage> query = createPollMessageQuery(clientId, clock.nowUtc()); QueryComposer<PollMessage> query = createPollMessageQuery(clientId, clock.nowUtc());
if (!isNullOrEmpty(message)) { if (!isNullOrEmpty(message)) {

View file

@ -15,7 +15,6 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
@ -87,8 +86,7 @@ abstract class CreateOrUpdatePackagePromotionCommand extends MutatingCommand {
@Override @Override
protected final void init() throws Exception { protected final void init() throws Exception {
for (String token : mainParameters) { for (String token : mainParameters) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
PackagePromotion oldPackage = getOldPackagePromotion(token); PackagePromotion oldPackage = getOldPackagePromotion(token);
checkArgument( checkArgument(

View file

@ -17,7 +17,6 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS; import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS;
import static google.registry.model.EppResourceUtils.loadByForeignKeyCached; import static google.registry.model.EppResourceUtils.loadByForeignKeyCached;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
@ -76,8 +75,7 @@ public final class DomainLockUtils {
*/ */
public RegistryLock saveNewRegistryLockRequest( public RegistryLock saveNewRegistryLockRequest(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) { String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
RegistryLockDao.save( RegistryLockDao.save(
createLockBuilder(domainName, registrarId, registrarPocId, isAdmin).build())); createLockBuilder(domainName, registrarId, registrarPocId, isAdmin).build()));
@ -90,8 +88,7 @@ public final class DomainLockUtils {
*/ */
public RegistryLock saveNewRegistryUnlockRequest( public RegistryLock saveNewRegistryUnlockRequest(
String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) { String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
RegistryLockDao.save( RegistryLockDao.save(
createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration).build())); createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration).build()));
@ -99,10 +96,9 @@ public final class DomainLockUtils {
/** Verifies and applies the lock request previously requested by a user. */ /** Verifies and applies the lock request previously requested by a user. */
public RegistryLock verifyAndApplyLock(String verificationCode, boolean isAdmin) { public RegistryLock verifyAndApplyLock(String verificationCode, boolean isAdmin) {
return jpaTm() return tm().transact(
.transact(
() -> { () -> {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
RegistryLock lock = getByVerificationCode(verificationCode); RegistryLock lock = getByVerificationCode(verificationCode);
checkArgument( checkArgument(
@ -128,10 +124,9 @@ public final class DomainLockUtils {
/** Verifies and applies the unlock request previously requested by a user. */ /** Verifies and applies the unlock request previously requested by a user. */
public RegistryLock verifyAndApplyUnlock(String verificationCode, boolean isAdmin) { public RegistryLock verifyAndApplyUnlock(String verificationCode, boolean isAdmin) {
RegistryLock lock = RegistryLock lock =
jpaTm() tm().transact(
.transact(
() -> { () -> {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
RegistryLock previousLock = getByVerificationCode(verificationCode); RegistryLock previousLock = getByVerificationCode(verificationCode);
checkArgument( checkArgument(
!previousLock.getUnlockCompletionTime().isPresent(), !previousLock.getUnlockCompletionTime().isPresent(),
@ -165,10 +160,9 @@ public final class DomainLockUtils {
*/ */
public RegistryLock administrativelyApplyLock( public RegistryLock administrativelyApplyLock(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) { String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
return jpaTm() return tm().transact(
.transact(
() -> { () -> {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
RegistryLock newLock = RegistryLock newLock =
RegistryLockDao.save( RegistryLockDao.save(
createLockBuilder(domainName, registrarId, registrarPocId, isAdmin) createLockBuilder(domainName, registrarId, registrarPocId, isAdmin)
@ -188,10 +182,9 @@ public final class DomainLockUtils {
public RegistryLock administrativelyApplyUnlock( public RegistryLock administrativelyApplyUnlock(
String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) { String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) {
RegistryLock lock = RegistryLock lock =
jpaTm() tm().transact(
.transact(
() -> { () -> {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
RegistryLock result = RegistryLock result =
RegistryLockDao.save( RegistryLockDao.save(
createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration) createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration)
@ -240,8 +233,7 @@ public final class DomainLockUtils {
} }
private void setAsRelock(RegistryLock newLock) { private void setAsRelock(RegistryLock newLock) {
jpaTm() tm().transact(
.transact(
() -> () ->
RegistryLockDao.getMostRecentVerifiedUnlockByRepoId(newLock.getRepoId()) RegistryLockDao.getMostRecentVerifiedUnlockByRepoId(newLock.getRepoId())
.ifPresent( .ifPresent(
@ -251,7 +243,7 @@ public final class DomainLockUtils {
private RegistryLock.Builder createLockBuilder( private RegistryLock.Builder createLockBuilder(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) { String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
Domain domain = getDomain(domainName, registrarId, now); Domain domain = getDomain(domainName, registrarId, now);
verifyDomainNotLocked(domain, isAdmin); verifyDomainNotLocked(domain, isAdmin);
@ -276,7 +268,7 @@ public final class DomainLockUtils {
private RegistryLock.Builder createUnlockBuilder( private RegistryLock.Builder createUnlockBuilder(
String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) { String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
Domain domain = getDomain(domainName, registrarId, now); Domain domain = getDomain(domainName, registrarId, now);
Optional<RegistryLock> lockOptional = Optional<RegistryLock> lockOptional =
RegistryLockDao.getMostRecentVerifiedLockByRepoId(domain.getRepoId()); RegistryLockDao.getMostRecentVerifiedLockByRepoId(domain.getRepoId());

View file

@ -14,7 +14,7 @@
package google.registry.tools; package google.registry.tools;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent; import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
@ -32,8 +32,7 @@ public class GetPackagePromotionCommand extends GetEppResourceCommand {
@Override @Override
void runAndPrint() { void runAndPrint() {
for (String token : mainParameters) { for (String token : mainParameters) {
jpaTm() tm().transact(
.transact(
() -> { () -> {
PackagePromotion packagePromotion = PackagePromotion packagePromotion =
checkArgumentPresent( checkArgumentPresent(

View file

@ -20,7 +20,6 @@ import static com.google.common.collect.Iterables.partition;
import static google.registry.model.eppcommon.StatusValue.SERVER_DELETE_PROHIBITED; import static google.registry.model.eppcommon.StatusValue.SERVER_DELETE_PROHIBITED;
import static google.registry.model.eppcommon.StatusValue.SERVER_TRANSFER_PROHIBITED; import static google.registry.model.eppcommon.StatusValue.SERVER_TRANSFER_PROHIBITED;
import static google.registry.model.eppcommon.StatusValue.SERVER_UPDATE_PROHIBITED; import static google.registry.model.eppcommon.StatusValue.SERVER_UPDATE_PROHIBITED;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.findDuplicates; import static google.registry.util.CollectionUtils.findDuplicates;
@ -84,8 +83,7 @@ public abstract class LockOrUnlockDomainCommand extends ConfirmingCommand {
.forEach( .forEach(
batch -> batch ->
// we require that the jpaTm is the outer transaction in DomainLockUtils // we require that the jpaTm is the outer transaction in DomainLockUtils
jpaTm() tm().transact(
.transact(
() -> () ->
tm().transact( tm().transact(
() -> { () -> {

View file

@ -15,7 +15,7 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.tools.Injector.injectReflectively; import static google.registry.tools.Injector.injectReflectively;
import com.beust.jcommander.JCommander; import com.beust.jcommander.JCommander;
@ -218,7 +218,7 @@ final class RegistryCli implements CommandRunner {
// Reset the JPA transaction manager after every command to avoid a situation where a test can // Reset the JPA transaction manager after every command to avoid a situation where a test can
// interfere with other tests // interfere with other tests
JpaTransactionManager cachedJpaTm = jpaTm(); JpaTransactionManager cachedJpaTm = tm();
TransactionManagerFactory.setJpaTm(() -> component.nomulusToolJpaTransactionManager().get()); TransactionManagerFactory.setJpaTm(() -> component.nomulusToolJpaTransactionManager().get());
TransactionManagerFactory.setReplicaJpaTm( TransactionManagerFactory.setReplicaJpaTm(
() -> component.nomulusToolReplicaJpaTransactionManager().get()); () -> component.nomulusToolReplicaJpaTransactionManager().get());

View file

@ -14,7 +14,7 @@
package google.registry.tools; package google.registry.tools;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
@ -48,11 +48,10 @@ public class SetDatabaseMigrationStateCommand extends ConfirmingCommand {
@Override @Override
protected String prompt() { protected String prompt() {
return jpaTm() return tm().transact(
.transact(
() -> { () -> {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
DateTime nextTransition = transitionSchedule.ceilingKey(now); DateTime nextTransition = transitionSchedule.ceilingKey(now);
if (nextTransition != null && nextTransition.isBefore(now.plusMinutes(10))) { if (nextTransition != null && nextTransition.isBefore(now.plusMinutes(10))) {
result.append(WARNING_MESSAGE); result.append(WARNING_MESSAGE);
@ -65,7 +64,7 @@ public class SetDatabaseMigrationStateCommand extends ConfirmingCommand {
@Override @Override
protected String execute() { protected String execute() {
jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(transitionSchedule)); tm().transact(() -> DatabaseMigrationStateSchedule.set(transitionSchedule));
return String.format("Successfully set new migration state schedule %s", transitionSchedule); return String.format("Successfully set new migration state schedule %s", transitionSchedule);
} }
} }

View file

@ -17,7 +17,6 @@ package google.registry.tools.server;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.io.BaseEncoding.base16; import static com.google.common.io.BaseEncoding.base16;
import static google.registry.model.EppResourceUtils.loadAtPointInTime; import static google.registry.model.EppResourceUtils.loadAtPointInTime;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@ -144,7 +143,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
} }
private void generateForTld(String tld, DateTime exportTime) { private void generateForTld(String tld, DateTime exportTime) {
ImmutableList<String> stanzas = jpaTm().transact(() -> getStanzasForTld(tld, exportTime)); ImmutableList<String> stanzas = tm().transact(() -> getStanzasForTld(tld, exportTime));
BlobId outputBlobId = BlobId.of(bucket, String.format(FILENAME_FORMAT, tld, exportTime)); BlobId outputBlobId = BlobId.of(bucket, String.format(FILENAME_FORMAT, tld, exportTime));
try (OutputStream gcsOutput = gcsUtils.openOutputStream(outputBlobId); try (OutputStream gcsOutput = gcsUtils.openOutputStream(outputBlobId);
Writer osWriter = new OutputStreamWriter(gcsOutput, UTF_8); Writer osWriter = new OutputStreamWriter(gcsOutput, UTF_8);
@ -160,8 +159,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
private ImmutableList<String> getStanzasForTld(String tld, DateTime exportTime) { private ImmutableList<String> getStanzasForTld(String tld, DateTime exportTime) {
ImmutableList.Builder<String> result = new ImmutableList.Builder<>(); ImmutableList.Builder<String> result = new ImmutableList.Builder<>();
ScrollableResults scrollableResults = ScrollableResults scrollableResults =
jpaTm() tm().query("FROM Domain WHERE tld = :tld AND deletionTime > :exportTime")
.query("FROM Domain WHERE tld = :tld AND deletionTime > :exportTime")
.setParameter("tld", tld) .setParameter("tld", tld)
.setParameter("exportTime", exportTime) .setParameter("exportTime", exportTime)
.unwrap(Query.class) .unwrap(Query.class)
@ -171,8 +169,8 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
Domain domain = (Domain) scrollableResults.get(0); Domain domain = (Domain) scrollableResults.get(0);
populateStanzasForDomain(domain, exportTime, result); populateStanzasForDomain(domain, exportTime, result);
if (i == 0) { if (i == 0) {
jpaTm().getEntityManager().flush(); tm().getEntityManager().flush();
jpaTm().getEntityManager().clear(); tm().getEntityManager().clear();
} }
} }
return result.build(); return result.build();

View file

@ -17,7 +17,7 @@ package google.registry.tools.server;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.model.tld.Registries.assertTldsExist; import static google.registry.model.tld.Registries.assertTldsExist;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
import static google.registry.request.RequestParameters.PARAM_TLDS; import static google.registry.request.RequestParameters.PARAM_TLDS;
@ -74,18 +74,16 @@ public final class ListDomainsAction extends ListObjectsAction<Domain> {
} }
private ImmutableList<Domain> loadDomains() { private ImmutableList<Domain> loadDomains() {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm() tm().query(
.query(
"FROM Domain WHERE tld IN (:tlds) AND deletionTime > " "FROM Domain WHERE tld IN (:tlds) AND deletionTime > "
+ "current_timestamp() ORDER BY creationTime DESC", + "current_timestamp() ORDER BY creationTime DESC",
Domain.class) Domain.class)
.setParameter("tlds", tlds) .setParameter("tlds", tlds)
.setMaxResults(limit) .setMaxResults(limit)
.getResultStream() .getResultStream()
.map(EppResourceUtils.transformAtTime(jpaTm().getTransactionTime())) .map(EppResourceUtils.transformAtTime(tm().getTransactionTime()))
.collect(toImmutableList())); .collect(toImmutableList()));
} }
} }

View file

@ -15,7 +15,7 @@
package google.registry.tools.server; package google.registry.tools.server;
import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
@ -49,10 +49,9 @@ public final class ListPremiumListsAction extends ListObjectsAction<PremiumList>
@Override @Override
public ImmutableSet<PremiumList> loadObjects() { public ImmutableSet<PremiumList> loadObjects() {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm().loadAllOf(PremiumList.class).stream() tm().loadAllOf(PremiumList.class).stream()
.map(PremiumList::getName) .map(PremiumList::getName)
.map(PremiumListDao::getLatestRevision) .map(PremiumListDao::getLatestRevision)
.filter(Optional::isPresent) .filter(Optional::isPresent)

View file

@ -15,7 +15,7 @@
package google.registry.tools.server; package google.registry.tools.server;
import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.POST; import static google.registry.request.Action.Method.POST;
@ -47,10 +47,9 @@ public final class ListReservedListsAction extends ListObjectsAction<ReservedLis
@Override @Override
public ImmutableSet<ReservedList> loadObjects() { public ImmutableSet<ReservedList> loadObjects() {
return jpaTm() return tm().transact(
.transact(
() -> () ->
jpaTm().loadAllOf(ReservedList.class).stream() tm().loadAllOf(ReservedList.class).stream()
.map(ReservedList::getName) .map(ReservedList::getName)
.map(ReservedListDao::getLatestRevision) .map(ReservedListDao::getLatestRevision)
.filter(Optional::isPresent) .filter(Optional::isPresent)

View file

@ -16,7 +16,6 @@ package google.registry.tools.server;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.model.tld.Registries.assertTldsExist; import static google.registry.model.tld.Registries.assertTldsExist;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.RequestParameters.PARAM_TLDS; import static google.registry.request.RequestParameters.PARAM_TLDS;
@ -80,8 +79,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable {
checkArgument(smearMinutes > 0, "Must specify a positive number of smear minutes"); checkArgument(smearMinutes > 0, "Must specify a positive number of smear minutes");
tm().transact( tm().transact(
() -> () ->
jpaTm() tm().query(
.query(
"SELECT domainName FROM Domain " "SELECT domainName FROM Domain "
+ "WHERE tld IN (:tlds) " + "WHERE tld IN (:tlds) "
+ "AND deletionTime > :now", + "AND deletionTime > :now",

View file

@ -19,7 +19,6 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.difference;
import static google.registry.config.RegistryEnvironment.PRODUCTION; import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.security.JsonResponseHelper.Status.ERROR; import static google.registry.security.JsonResponseHelper.Status.ERROR;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
@ -243,7 +242,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
Registrar registrar = loadRegistrarUnchecked(registrarId); Registrar registrar = loadRegistrarUnchecked(registrarId);
// Detach the registrar to avoid Hibernate object-updates, since we wish to email // Detach the registrar to avoid Hibernate object-updates, since we wish to email
// out the diffs between the existing and updated registrar objects // out the diffs between the existing and updated registrar objects
jpaTm().getEntityManager().detach(registrar); tm().getEntityManager().detach(registrar);
// Verify that the registrar hasn't been changed. // Verify that the registrar hasn't been changed.
// To do that - we find the latest update time (or null if the registrar has been // To do that - we find the latest update time (or null if the registrar has been
// deleted) and compare to the update time from the args. The update time in the args // deleted) and compare to the update time from the args. The update time in the args

View file

@ -16,7 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
import static google.registry.ui.server.registrar.RegistrarConsoleModule.PARAM_CLIENT_ID; import static google.registry.ui.server.registrar.RegistrarConsoleModule.PARAM_CLIENT_ID;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
@ -196,17 +196,16 @@ public final class RegistryLockGetAction implements JsonGetAction {
private static ImmutableList<ImmutableMap<String, ?>> getLockedDomains( private static ImmutableList<ImmutableMap<String, ?>> getLockedDomains(
String registrarId, boolean isAdmin) { String registrarId, boolean isAdmin) {
return jpaTm() return tm().transact(
.transact(
() -> () ->
RegistryLockDao.getLocksByRegistrarId(registrarId).stream() RegistryLockDao.getLocksByRegistrarId(registrarId).stream()
.filter(lock -> !lock.isLockRequestExpired(jpaTm().getTransactionTime())) .filter(lock -> !lock.isLockRequestExpired(tm().getTransactionTime()))
.map(lock -> lockToMap(lock, isAdmin)) .map(lock -> lockToMap(lock, isAdmin))
.collect(toImmutableList())); .collect(toImmutableList()));
} }
private static ImmutableMap<String, ?> lockToMap(RegistryLock lock, boolean isAdmin) { private static ImmutableMap<String, ?> lockToMap(RegistryLock lock, boolean isAdmin) {
DateTime now = jpaTm().getTransactionTime(); DateTime now = tm().getTransactionTime();
return new ImmutableMap.Builder<String, Object>() return new ImmutableMap.Builder<String, Object>()
.put(DOMAIN_NAME_PARAM, lock.getDomainName()) .put(DOMAIN_NAME_PARAM, lock.getDomainName())
.put(LOCKED_TIME_PARAM, lock.getLockCompletionTime().map(DateTime::toString).orElse("")) .put(LOCKED_TIME_PARAM, lock.getLockCompletionTime().map(DateTime::toString).orElse(""))

View file

@ -16,7 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.security.JsonResponseHelper.Status.ERROR; import static google.registry.security.JsonResponseHelper.Status.ERROR;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
import static google.registry.ui.server.registrar.RegistryLockGetAction.getContactMatchingLogin; import static google.registry.ui.server.registrar.RegistryLockGetAction.getContactMatchingLogin;
@ -127,8 +127,7 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc
.orElseThrow(() -> new ForbiddenException("User is not logged in")); .orElseThrow(() -> new ForbiddenException("User is not logged in"));
String userEmail = verifyPasswordAndGetEmail(userAuthInfo, postInput); String userEmail = verifyPasswordAndGetEmail(userAuthInfo, postInput);
jpaTm() tm().transact(
.transact(
() -> { () -> {
RegistryLock registryLock = RegistryLock registryLock =
postInput.isLock postInput.isLock

View file

@ -16,7 +16,7 @@ package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -51,12 +51,10 @@ final class NameserverLookupByIpCommand implements WhoisCommand {
public WhoisResponse executeQuery(DateTime now) throws WhoisException { public WhoisResponse executeQuery(DateTime now) throws WhoisException {
Iterable<Host> hostsFromDb; Iterable<Host> hostsFromDb;
hostsFromDb = hostsFromDb =
jpaTm() tm().transact(
.transact(
() -> () ->
// We cannot query @Convert-ed fields in HQL, so we must use native Postgres. // We cannot query @Convert-ed fields in HQL, so we must use native Postgres.
jpaTm() tm().getEntityManager()
.getEntityManager()
/* /*
* Using array_operator <@ (contained-by) with gin index on inet_address. * Using array_operator <@ (contained-by) with gin index on inet_address.
* Without gin index, this is slightly slower than the alternative form of * Without gin index, this is slightly slower than the alternative form of

View file

@ -17,7 +17,7 @@ package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -53,13 +53,13 @@ final class NameserverWhoisResponse extends WhoisResponseImpl {
ImmutableMap<Host, String> hostRegistrars = ImmutableMap<Host, String> hostRegistrars =
subordinateHosts.isEmpty() subordinateHosts.isEmpty()
? ImmutableMap.of() ? ImmutableMap.of()
: replicaJpaTm() : replicaTm()
.transact( .transact(
() -> () ->
Maps.toMap( Maps.toMap(
subordinateHosts.iterator(), subordinateHosts.iterator(),
host -> host ->
replicaJpaTm() replicaTm()
.loadByKey(host.getSuperordinateDomain()) .loadByKey(host.getSuperordinateDomain())
.cloneProjectedAtTime(getTimestamp()) .cloneProjectedAtTime(getTimestamp())
.getCurrentSponsorRegistrarId())); .getCurrentSponsorRegistrarId()));

View file

@ -14,7 +14,7 @@
package google.registry.batch; package google.registry.batch;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistActiveContact; import static google.registry.testing.DatabaseHelper.persistActiveContact;
import static google.registry.testing.DatabaseHelper.persistEppResource; import static google.registry.testing.DatabaseHelper.persistEppResource;
@ -110,7 +110,7 @@ public class CheckPackagesComplianceActionTest {
.setLastNotificationSent(DateTime.parse("2010-11-12T05:00:00Z")) .setLastNotificationSent(DateTime.parse("2010-11-12T05:00:00Z"))
.build(); .build();
jpaTm().transact(() -> jpaTm().put(packagePromotion)); tm().transact(() -> tm().put(packagePromotion));
contact = persistActiveContact("contact1234"); contact = persistActiveContact("contact1234");
} }
@ -199,7 +199,7 @@ public class CheckPackagesComplianceActionTest {
.setPackagePrice(Money.of(CurrencyUnit.USD, 1000)) .setPackagePrice(Money.of(CurrencyUnit.USD, 1000))
.setNextBillingDate(DateTime.parse("2012-11-12T05:00:00Z")) .setNextBillingDate(DateTime.parse("2012-11-12T05:00:00Z"))
.build(); .build();
jpaTm().transact(() -> jpaTm().put(packagePromotion2)); tm().transact(() -> tm().put(packagePromotion2));
persistEppResource( persistEppResource(
DatabaseHelper.newDomain("foo2.tld", contact) DatabaseHelper.newDomain("foo2.tld", contact)
@ -253,7 +253,7 @@ public class CheckPackagesComplianceActionTest {
.setPackagePrice(Money.of(CurrencyUnit.USD, 1000)) .setPackagePrice(Money.of(CurrencyUnit.USD, 1000))
.setNextBillingDate(DateTime.parse("2015-11-12T05:00:00Z")) .setNextBillingDate(DateTime.parse("2015-11-12T05:00:00Z"))
.build(); .build();
jpaTm().transact(() -> jpaTm().put(packagePromotion2)); tm().transact(() -> tm().put(packagePromotion2));
// Create limit is 1, creating 2 domains to go over the limit // Create limit is 1, creating 2 domains to go over the limit
persistEppResource( persistEppResource(

View file

@ -17,7 +17,7 @@ package google.registry.batch;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResource;
import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_OK;
@ -118,8 +118,7 @@ class WipeOutContactHistoryPiiActionTest {
void getAllHistoryEntitiesOlderThan_returnsAllPersistedEntities() { void getAllHistoryEntitiesOlderThan_returnsAllPersistedEntities() {
ImmutableList<ContactHistory> expectedToBeWipedOut = ImmutableList<ContactHistory> expectedToBeWipedOut =
persistLotsOfContactHistoryEntities(20, MIN_MONTHS_BEFORE_WIPE_OUT + 1, 0, DEFAULT_CONTACT); persistLotsOfContactHistoryEntities(20, MIN_MONTHS_BEFORE_WIPE_OUT + 1, 0, DEFAULT_CONTACT);
jpaTm() tm().transact(
.transact(
() -> () ->
assertThat( assertThat(
action.getNextContactHistoryEntitiesWithPiiBatch( action.getNextContactHistoryEntitiesWithPiiBatch(
@ -135,8 +134,7 @@ class WipeOutContactHistoryPiiActionTest {
// persisted entities that should not be part of the actual result // persisted entities that should not be part of the actual result
persistLotsOfContactHistoryEntities(15, 17, MIN_MONTHS_BEFORE_WIPE_OUT - 1, DEFAULT_CONTACT); persistLotsOfContactHistoryEntities(15, 17, MIN_MONTHS_BEFORE_WIPE_OUT - 1, DEFAULT_CONTACT);
jpaTm() tm().transact(
.transact(
() -> () ->
assertThat( assertThat(
action.getNextContactHistoryEntitiesWithPiiBatch( action.getNextContactHistoryEntitiesWithPiiBatch(
@ -147,8 +145,7 @@ class WipeOutContactHistoryPiiActionTest {
@Test @Test
void run_withNoEntitiesToWipeOut_success() { void run_withNoEntitiesToWipeOut_success() {
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -158,8 +155,7 @@ class WipeOutContactHistoryPiiActionTest {
action.run(); action.run();
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -180,8 +176,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return a stream of all persisted entities. // The query should return a stream of all persisted entities.
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -197,8 +192,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return an empty stream after the wipe out action. // The query should return an empty stream after the wipe out action.
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -217,8 +211,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return a subset of all persisted data. // The query should return a subset of all persisted data.
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -233,8 +226,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return an empty stream after the wipe out action. // The query should return an empty stream after the wipe out action.
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -254,8 +246,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return a subset of all persisted data. // The query should return a subset of all persisted data.
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -270,8 +261,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return an empty stream after the wipe out action. // The query should return an empty stream after the wipe out action.
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
action action
.getNextContactHistoryEntitiesWithPiiBatch( .getNextContactHistoryEntitiesWithPiiBatch(
@ -284,8 +274,7 @@ class WipeOutContactHistoryPiiActionTest {
@Test @Test
void wipeOutContactHistoryData_wipesOutNoEntity() { void wipeOutContactHistoryData_wipesOutNoEntity() {
jpaTm() tm().transact(
.transact(
() -> () ->
assertThat( assertThat(
action.wipeOutContactHistoryData( action.wipeOutContactHistoryData(
@ -302,8 +291,7 @@ class WipeOutContactHistoryPiiActionTest {
assertAllEntitiesContainPii(DatabaseHelper.loadByEntitiesIfPresent(expectedToBeWipedOut)); assertAllEntitiesContainPii(DatabaseHelper.loadByEntitiesIfPresent(expectedToBeWipedOut));
jpaTm() tm().transact(
.transact(
() -> { () -> {
action.wipeOutContactHistoryData( action.wipeOutContactHistoryData(
action.getNextContactHistoryEntitiesWithPiiBatch( action.getNextContactHistoryEntitiesWithPiiBatch(

View file

@ -14,7 +14,7 @@
package google.registry.beam.common; package google.registry.beam.common;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.truth.Truth; import com.google.common.truth.Truth;
@ -81,12 +81,12 @@ public class DatabaseSnapshotTest {
jpa = jpa =
new JpaTransactionManagerImpl( new JpaTransactionManagerImpl(
Persistence.createEntityManagerFactory("nomulus", jpaProperties), new FakeClock()); Persistence.createEntityManagerFactory("nomulus", jpaProperties), new FakeClock());
origJpa = jpaTm(); origJpa = tm();
TransactionManagerFactory.setJpaTm(() -> jpa); TransactionManagerFactory.setJpaTm(() -> jpa);
Registry tld = DatabaseHelper.newRegistry("tld", "TLD"); Registry tld = DatabaseHelper.newRegistry("tld", "TLD");
jpaTm().transact(() -> jpaTm().put(tld)); tm().transact(() -> tm().put(tld));
registry = jpaTm().transact(() -> jpaTm().loadByEntity(tld)); registry = tm().transact(() -> tm().loadByEntity(tld));
} }
@AfterAll @AfterAll
@ -113,11 +113,9 @@ public class DatabaseSnapshotTest {
void readSnapshot() { void readSnapshot() {
try (DatabaseSnapshot databaseSnapshot = DatabaseSnapshot.createSnapshot()) { try (DatabaseSnapshot databaseSnapshot = DatabaseSnapshot.createSnapshot()) {
Registry snapshotRegistry = Registry snapshotRegistry =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
.setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
.loadByEntity(registry)); .loadByEntity(registry));
Truth.assertThat(snapshotRegistry).isEqualTo(registry); Truth.assertThat(snapshotRegistry).isEqualTo(registry);
} }
@ -131,22 +129,20 @@ public class DatabaseSnapshotTest {
.asBuilder() .asBuilder()
.setCreateBillingCost(registry.getStandardCreateCost().plus(1)) .setCreateBillingCost(registry.getStandardCreateCost().plus(1))
.build(); .build();
jpaTm().transact(() -> jpaTm().put(updated)); tm().transact(() -> tm().put(updated));
Registry persistedUpdate = jpaTm().transact(() -> jpaTm().loadByEntity(registry)); Registry persistedUpdate = tm().transact(() -> tm().loadByEntity(registry));
Truth.assertThat(persistedUpdate).isNotEqualTo(registry); Truth.assertThat(persistedUpdate).isNotEqualTo(registry);
Registry snapshotRegistry = Registry snapshotRegistry =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
.setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
.loadByEntity(registry)); .loadByEntity(registry));
Truth.assertThat(snapshotRegistry).isEqualTo(registry); Truth.assertThat(snapshotRegistry).isEqualTo(registry);
} finally { } finally {
// Revert change to registry in DB, which is shared by all test methods. // Revert change to registry in DB, which is shared by all test methods.
jpaTm().transact(() -> jpaTm().put(registry)); tm().transact(() -> tm().put(registry));
} }
} }
@ -158,7 +154,7 @@ public class DatabaseSnapshotTest {
.asBuilder() .asBuilder()
.setCreateBillingCost(registry.getStandardCreateCost().plus(1)) .setCreateBillingCost(registry.getStandardCreateCost().plus(1))
.build(); .build();
jpaTm().transact(() -> jpaTm().put(updated)); tm().transact(() -> tm().put(updated));
Read<Registry, Registry> read = Read<Registry, Registry> read =
RegistryJpaIO.read(() -> CriteriaQueryBuilder.create(Registry.class).build(), x -> x) RegistryJpaIO.read(() -> CriteriaQueryBuilder.create(Registry.class).build(), x -> x)
@ -172,7 +168,7 @@ public class DatabaseSnapshotTest {
testPipeline.run(); testPipeline.run();
} finally { } finally {
// Revert change to registry in DB, which is shared by all test methods. // Revert change to registry in DB, which is shared by all test methods.
jpaTm().transact(() -> jpaTm().put(registry)); tm().transact(() -> tm().put(registry));
} }
} }
} }

View file

@ -16,7 +16,7 @@ package google.registry.beam.common;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence; import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.loadAllOf; import static google.registry.testing.DatabaseHelper.loadAllOf;
import static google.registry.testing.DatabaseHelper.newContact; import static google.registry.testing.DatabaseHelper.newContact;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -51,7 +51,7 @@ class RegistryJpaWriteTest implements Serializable {
@Test @Test
void writeToSql_twoWriters() { void writeToSql_twoWriters() {
jpaTm().transact(() -> jpaTm().put(AppEngineExtension.makeRegistrar2())); tm().transact(() -> tm().put(AppEngineExtension.makeRegistrar2()));
ImmutableList.Builder<Contact> contactsBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<Contact> contactsBuilder = new ImmutableList.Builder<>();
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
contactsBuilder.add(newContact("contact_" + i)); contactsBuilder.add(newContact("contact_" + i));
@ -72,11 +72,10 @@ class RegistryJpaWriteTest implements Serializable {
// RegistryJpaIO.Write actions should not write existing objects to the database because the // RegistryJpaIO.Write actions should not write existing objects to the database because the
// object could have been mutated in between creation and when the Write actually occurs, // object could have been mutated in between creation and when the Write actually occurs,
// causing a race condition // causing a race condition
jpaTm() tm().transact(
.transact(
() -> { () -> {
jpaTm().put(AppEngineExtension.makeRegistrar2()); tm().put(AppEngineExtension.makeRegistrar2());
jpaTm().put(newContact("contact")); tm().put(newContact("contact"));
}); });
Contact contact = Iterables.getOnlyElement(loadAllOf(Contact.class)); Contact contact = Iterables.getOnlyElement(loadAllOf(Contact.class));
testPipeline testPipeline

View file

@ -16,7 +16,7 @@ package google.registry.beam.resave;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.loadAllOf; import static google.registry.testing.DatabaseHelper.loadAllOf;
import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.loadByEntity;
@ -151,7 +151,7 @@ public class ResaveAllEppResourcesPipelineTest {
persistDomainWithDependentResources("renewed", "tld", contact, now, now, now.plusYears(1)); persistDomainWithDependentResources("renewed", "tld", contact, now, now, now.plusYears(1));
persistActiveDomain("nonrenewed.tld", now, now.plusYears(20)); persistActiveDomain("nonrenewed.tld", now, now.plusYears(20));
// Spy the transaction manager so we can be sure we're only saving the renewed domain // Spy the transaction manager so we can be sure we're only saving the renewed domain
JpaTransactionManager spy = spy(jpaTm()); JpaTransactionManager spy = spy(tm());
TransactionManagerFactory.setJpaTm(() -> spy); TransactionManagerFactory.setJpaTm(() -> spy);
ArgumentCaptor<Domain> domainPutCaptor = ArgumentCaptor.forClass(Domain.class); ArgumentCaptor<Domain> domainPutCaptor = ArgumentCaptor.forClass(Domain.class);
runPipeline(); runPipeline();
@ -171,7 +171,7 @@ public class ResaveAllEppResourcesPipelineTest {
persistDomainWithDependentResources( persistDomainWithDependentResources(
"nonrenewed", "tld", contact, now, now, now.plusYears(20)); "nonrenewed", "tld", contact, now, now, now.plusYears(20));
// Spy the transaction manager so we can be sure we're attempting to save everything // Spy the transaction manager so we can be sure we're attempting to save everything
JpaTransactionManager spy = spy(jpaTm()); JpaTransactionManager spy = spy(tm());
TransactionManagerFactory.setJpaTm(() -> spy); TransactionManagerFactory.setJpaTm(() -> spy);
ArgumentCaptor<EppResource> eppResourcePutCaptor = ArgumentCaptor.forClass(EppResource.class); ArgumentCaptor<EppResource> eppResourcePutCaptor = ArgumentCaptor.forClass(EppResource.class);
runPipeline(); runPipeline();

View file

@ -17,7 +17,7 @@ package google.registry.beam.spec11;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence; import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.AppEngineExtension.makeRegistrar1; import static google.registry.testing.AppEngineExtension.makeRegistrar1;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistActiveContact; import static google.registry.testing.DatabaseHelper.persistActiveContact;
@ -278,11 +278,10 @@ class Spec11PipelineTest {
} }
private void verifySaveToCloudSql() { private void verifySaveToCloudSql() {
jpaTm() tm().transact(
.transact(
() -> { () -> {
ImmutableList<Spec11ThreatMatch> sqlThreatMatches = ImmutableList<Spec11ThreatMatch> sqlThreatMatches =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), new LocalDate(2020, 1, 27)); Spec11ThreatMatchDao.loadEntriesByDate(tm(), new LocalDate(2020, 1, 27));
assertThat(sqlThreatMatches) assertThat(sqlThreatMatches)
.comparingElementsUsing(immutableObjectCorrespondence("id")) .comparingElementsUsing(immutableObjectCorrespondence("id"))
.containsExactlyElementsIn(sqlThreatMatches); .containsExactlyElementsIn(sqlThreatMatches);

View file

@ -22,7 +22,7 @@ import static google.registry.model.common.DatabaseMigrationStateSchedule.Migrat
import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_ONLY; import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_ONLY;
import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_PRIMARY; import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_PRIMARY;
import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_PRIMARY_READ_ONLY; import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_PRIMARY_READ_ONLY;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
@ -128,7 +128,7 @@ public class DatabaseMigrationStateScheduleTest extends EntityTestCase {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(nowInvalidMap))); () -> tm().transact(() -> DatabaseMigrationStateSchedule.set(nowInvalidMap)));
assertThat(thrown) assertThat(thrown)
.hasMessageThat() .hasMessageThat()
.isEqualTo( .isEqualTo(
@ -150,7 +150,7 @@ public class DatabaseMigrationStateScheduleTest extends EntityTestCase {
private void runValidTransition(MigrationState from, MigrationState to) { private void runValidTransition(MigrationState from, MigrationState to) {
ImmutableSortedMap<DateTime, MigrationState> transitions = ImmutableSortedMap<DateTime, MigrationState> transitions =
createMapEndingWithTransition(from, to); createMapEndingWithTransition(from, to);
jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(transitions)); tm().transact(() -> DatabaseMigrationStateSchedule.set(transitions));
assertThat(DatabaseMigrationStateSchedule.getUncached().toValueMap()) assertThat(DatabaseMigrationStateSchedule.getUncached().toValueMap())
.containsExactlyEntriesIn(transitions); .containsExactlyEntriesIn(transitions);
} }
@ -161,7 +161,7 @@ public class DatabaseMigrationStateScheduleTest extends EntityTestCase {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(transitions))); () -> tm().transact(() -> DatabaseMigrationStateSchedule.set(transitions)));
assertThat(thrown) assertThat(thrown)
.hasMessageThat() .hasMessageThat()
.isEqualTo( .isEqualTo(

View file

@ -15,7 +15,7 @@
package google.registry.model.console; package google.registry.model.console;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.truth.Truth8; import com.google.common.truth.Truth8;
@ -62,7 +62,7 @@ public class UserDaoTest extends EntityTestCase {
// nonexistent one should never exist // nonexistent one should never exist
Truth8.assertThat(UserDao.loadUser("nonexistent@email.com")).isEmpty(); Truth8.assertThat(UserDao.loadUser("nonexistent@email.com")).isEmpty();
// now try deleting the one that does exist // now try deleting the one that does exist
jpaTm().transact(() -> jpaTm().delete(fromDb)); tm().transact(() -> tm().delete(fromDb));
Truth8.assertThat(UserDao.loadUser("email@email.com")).isEmpty(); Truth8.assertThat(UserDao.loadUser("email@email.com")).isEmpty();
} }

View file

@ -16,7 +16,7 @@ package google.registry.model.console;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import google.registry.model.EntityTestCase; import google.registry.model.EntityTestCase;
@ -38,19 +38,15 @@ public class UserTest extends EntityTestCase {
.setUserRoles( .setUserRoles(
new UserRoles.Builder().setGlobalRole(GlobalRole.FTE).setIsAdmin(true).build()) new UserRoles.Builder().setGlobalRole(GlobalRole.FTE).setIsAdmin(true).build())
.build(); .build();
jpaTm().transact(() -> jpaTm().put(user)); tm().transact(() -> tm().put(user));
jpaTm() tm().transact(
.transact(
() -> { () -> {
assertAboutImmutableObjects() assertAboutImmutableObjects()
.that( .that(
jpaTm() tm().query("FROM User WHERE gaiaId = 'gaiaId'", User.class).getSingleResult())
.query("FROM User WHERE gaiaId = 'gaiaId'", User.class)
.getSingleResult())
.isEqualExceptFields(user, "id", "updateTimestamp"); .isEqualExceptFields(user, "id", "updateTimestamp");
assertThat( assertThat(
jpaTm() tm().query("FROM User WHERE gaiaId = 'badGaiaId'", User.class)
.query("FROM User WHERE gaiaId = 'badGaiaId'", User.class)
.getResultList()) .getResultList())
.isEmpty(); .isEmpty();
}); });

View file

@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT_STARTED; import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT_STARTED;
import static google.registry.model.domain.token.AllocationToken.TokenType.PACKAGE; import static google.registry.model.domain.token.AllocationToken.TokenType.PACKAGE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.loadByEntity;
@ -177,11 +177,10 @@ public class DomainSqlTest {
@Test @Test
void testResaveDomain_succeeds() { void testResaveDomain_succeeds() {
persistDomain(); persistDomain();
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
jpaTm().put(persisted.asBuilder().build()); tm().put(persisted.asBuilder().build());
}); });
// Load the domain in its entirety. // Load the domain in its entirety.
assertEqualDomainExcept(loadByKey(domain.createVKey())); assertEqualDomainExcept(loadByKey(domain.createVKey()));
@ -190,18 +189,16 @@ public class DomainSqlTest {
@Test @Test
void testModifyGracePeriod_setEmptyCollectionSuccessfully() { void testModifyGracePeriod_setEmptyCollectionSuccessfully() {
persistDomain(); persistDomain();
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build(); Domain modified = persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build();
jpaTm().put(modified); tm().put(modified);
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()).isEmpty(); assertThat(persisted.getGracePeriods()).isEmpty();
}); });
} }
@ -209,18 +206,16 @@ public class DomainSqlTest {
@Test @Test
void testModifyGracePeriod_setNullCollectionSuccessfully() { void testModifyGracePeriod_setNullCollectionSuccessfully() {
persistDomain(); persistDomain();
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = persisted.asBuilder().setGracePeriods(null).build(); Domain modified = persisted.asBuilder().setGracePeriods(null).build();
jpaTm().put(modified); tm().put(modified);
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()).isEmpty(); assertThat(persisted.getGracePeriods()).isEmpty();
}); });
} }
@ -228,10 +223,9 @@ public class DomainSqlTest {
@Test @Test
void testModifyGracePeriod_addThenRemoveSuccessfully() { void testModifyGracePeriod_addThenRemoveSuccessfully() {
persistDomain(); persistDomain();
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = Domain modified =
persisted persisted
.asBuilder() .asBuilder()
@ -244,13 +238,12 @@ public class DomainSqlTest {
null, null,
200L)) 200L))
.build(); .build();
jpaTm().put(modified); tm().put(modified);
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()) assertThat(persisted.getGracePeriods())
.containsExactly( .containsExactly(
GracePeriod.create( GracePeriod.create(
@ -260,23 +253,21 @@ public class DomainSqlTest {
assertEqualDomainExcept(persisted, "gracePeriods"); assertEqualDomainExcept(persisted, "gracePeriods");
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
Domain.Builder builder = persisted.asBuilder(); Domain.Builder builder = persisted.asBuilder();
for (GracePeriod gracePeriod : persisted.getGracePeriods()) { for (GracePeriod gracePeriod : persisted.getGracePeriods()) {
if (gracePeriod.getType() == GracePeriodStatus.RENEW) { if (gracePeriod.getType() == GracePeriodStatus.RENEW) {
builder.removeGracePeriod(gracePeriod); builder.removeGracePeriod(gracePeriod);
} }
} }
jpaTm().put(builder.build()); tm().put(builder.build());
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertEqualDomainExcept(persisted); assertEqualDomainExcept(persisted);
}); });
} }
@ -284,18 +275,16 @@ public class DomainSqlTest {
@Test @Test
void testModifyGracePeriod_removeThenAddSuccessfully() { void testModifyGracePeriod_removeThenAddSuccessfully() {
persistDomain(); persistDomain();
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build(); Domain modified = persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build();
jpaTm().put(modified); tm().put(modified);
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()).isEmpty(); assertThat(persisted.getGracePeriods()).isEmpty();
Domain modified = Domain modified =
persisted persisted
@ -309,13 +298,12 @@ public class DomainSqlTest {
null, null,
100L)) 100L))
.build(); .build();
jpaTm().put(modified); tm().put(modified);
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()) assertThat(persisted.getGracePeriods())
.containsExactly( .containsExactly(
GracePeriod.create( GracePeriod.create(
@ -332,37 +320,33 @@ public class DomainSqlTest {
Sets.union(domain.getDsData(), ImmutableSet.of(extraDsData)).immutableCopy(); Sets.union(domain.getDsData(), ImmutableSet.of(extraDsData)).immutableCopy();
// Add an extra DomainDsData to dsData set. // Add an extra DomainDsData to dsData set.
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getDsData()).containsExactlyElementsIn(domain.getDsData()); assertThat(persisted.getDsData()).containsExactlyElementsIn(domain.getDsData());
Domain modified = persisted.asBuilder().setDsData(unionDsData).build(); Domain modified = persisted.asBuilder().setDsData(unionDsData).build();
jpaTm().put(modified); tm().put(modified);
}); });
// Verify that the persisted domain entity contains both DomainDsData records. // Verify that the persisted domain entity contains both DomainDsData records.
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getDsData()).containsExactlyElementsIn(unionDsData); assertThat(persisted.getDsData()).containsExactlyElementsIn(unionDsData);
assertEqualDomainExcept(persisted, "dsData"); assertEqualDomainExcept(persisted, "dsData");
}); });
// Remove the extra DomainDsData record from dsData set. // Remove the extra DomainDsData record from dsData set.
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
jpaTm().put(persisted.asBuilder().setDsData(domain.getDsData()).build()); tm().put(persisted.asBuilder().setDsData(domain.getDsData()).build());
}); });
// Verify that the persisted domain is equal to the original domain. // Verify that the persisted domain is equal to the original domain.
jpaTm() tm().transact(
.transact(
() -> { () -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey()); Domain persisted = tm().loadByKey(domain.createVKey());
assertEqualDomainExcept(persisted); assertEqualDomainExcept(persisted);
}); });
} }
@ -371,7 +355,7 @@ public class DomainSqlTest {
void testSerializable() { void testSerializable() {
createTld("com"); createTld("com");
insertInDb(contact, contact2, domain, host); insertInDb(contact, contact2, domain, host);
Domain persisted = jpaTm().transact(() -> jpaTm().loadByEntity(domain)); Domain persisted = tm().transact(() -> tm().loadByEntity(domain));
assertThat(SerializeUtils.serializeDeserialize(persisted)).isEqualTo(persisted); assertThat(SerializeUtils.serializeDeserialize(persisted)).isEqualTo(persisted);
} }
@ -427,8 +411,7 @@ public class DomainSqlTest {
DateTime originalUpdateTime = persisted.getUpdateTimestamp().getTimestamp(); DateTime originalUpdateTime = persisted.getUpdateTimestamp().getTimestamp();
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
DateTime transactionTime = DateTime transactionTime =
jpaTm() tm().transact(
.transact(
() -> { () -> {
Host host2 = Host host2 =
new Host.Builder() new Host.Builder()
@ -440,7 +423,7 @@ public class DomainSqlTest {
insertInDb(host2); insertInDb(host2);
domain = persisted.asBuilder().addNameserver(host2.createVKey()).build(); domain = persisted.asBuilder().addNameserver(host2.createVKey()).build();
updateInDb(domain); updateInDb(domain);
return jpaTm().getTransactionTime(); return tm().getTransactionTime();
}); });
domain = loadByKey(domain.createVKey()); domain = loadByKey(domain.createVKey());
assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(transactionTime); assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(transactionTime);
@ -454,8 +437,7 @@ public class DomainSqlTest {
DateTime originalUpdateTime = persisted.getUpdateTimestamp().getTimestamp(); DateTime originalUpdateTime = persisted.getUpdateTimestamp().getTimestamp();
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
DateTime transactionTime = DateTime transactionTime =
jpaTm() tm().transact(
.transact(
() -> { () -> {
domain = domain =
persisted persisted
@ -464,7 +446,7 @@ public class DomainSqlTest {
ImmutableSet.of(DomainDsData.create(1, 2, 3, new byte[] {0, 1, 2}))) ImmutableSet.of(DomainDsData.create(1, 2, 3, new byte[] {0, 1, 2})))
.build(); .build();
updateInDb(domain); updateInDb(domain);
return jpaTm().getTransactionTime(); return tm().getTransactionTime();
}); });
domain = loadByKey(domain.createVKey()); domain = loadByKey(domain.createVKey());
assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(transactionTime); assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(transactionTime);

View file

@ -16,7 +16,7 @@ package google.registry.model.domain.token;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResource;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -66,9 +66,9 @@ public class PackagePromotionTest extends EntityTestCase {
.setNextBillingDate(DateTime.parse("2011-11-12T05:00:00Z")) .setNextBillingDate(DateTime.parse("2011-11-12T05:00:00Z"))
.build(); .build();
jpaTm().transact(() -> jpaTm().put(packagePromotion)); tm().transact(() -> tm().put(packagePromotion));
assertAboutImmutableObjects() assertAboutImmutableObjects()
.that(jpaTm().transact(() -> PackagePromotion.loadByTokenString("abc123")).get()) .that(tm().transact(() -> PackagePromotion.loadByTokenString("abc123")).get())
.isEqualExceptFields(packagePromotion, "packagePromotionId"); .isEqualExceptFields(packagePromotion, "packagePromotionId");
} }

View file

@ -15,7 +15,7 @@
package google.registry.model.eppcommon; package google.registry.model.eppcommon;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.loadByEntity;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -83,7 +83,7 @@ class AddressTest {
/** Test the merge behavior. */ /** Test the merge behavior. */
@Test @Test
void testSuccess_putAndLoadStreetLines() { void testSuccess_putAndLoadStreetLines() {
jpaTm().transact(() -> jpaTm().put(entity)); tm().transact(() -> tm().put(entity));
assertAddress(loadByEntity(entity).address, "123 W 14th St", "8th Fl", "Rm 8"); assertAddress(loadByEntity(entity).address, "123 W 14th St", "8th Fl", "Rm 8");
} }

View file

@ -16,7 +16,7 @@ package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.loadByEntity;
import static google.registry.testing.DatabaseHelper.newContactWithRoid; import static google.registry.testing.DatabaseHelper.newContactWithRoid;
@ -49,10 +49,9 @@ public class ContactHistoryTest extends EntityTestCase {
Contact contactFromDb = loadByEntity(contact); Contact contactFromDb = loadByEntity(contact);
ContactHistory contactHistory = createContactHistory(contactFromDb); ContactHistory contactHistory = createContactHistory(contactFromDb);
insertInDb(contactHistory); insertInDb(contactHistory);
jpaTm() tm().transact(
.transact(
() -> { () -> {
ContactHistory fromDatabase = jpaTm().loadByKey(contactHistory.createVKey()); ContactHistory fromDatabase = tm().loadByKey(contactHistory.createVKey());
assertContactHistoriesEqual(fromDatabase, contactHistory); assertContactHistoriesEqual(fromDatabase, contactHistory);
assertThat(fromDatabase.getRepoId()).isEqualTo(contactHistory.getRepoId()); assertThat(fromDatabase.getRepoId()).isEqualTo(contactHistory.getRepoId());
}); });
@ -65,8 +64,7 @@ public class ContactHistoryTest extends EntityTestCase {
Contact contactFromDb = loadByEntity(contact); Contact contactFromDb = loadByEntity(contact);
ContactHistory contactHistory = createContactHistory(contactFromDb); ContactHistory contactHistory = createContactHistory(contactFromDb);
insertInDb(contactHistory); insertInDb(contactHistory);
ContactHistory fromDatabase = ContactHistory fromDatabase = tm().transact(() -> tm().loadByKey(contactHistory.createVKey()));
jpaTm().transact(() -> jpaTm().loadByKey(contactHistory.createVKey()));
assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase); assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase);
} }

View file

@ -16,7 +16,7 @@ package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.newContactWithRoid; import static google.registry.testing.DatabaseHelper.newContactWithRoid;
@ -64,10 +64,9 @@ public class DomainHistoryTest extends EntityTestCase {
DomainHistory domainHistory = createDomainHistory(domain); DomainHistory domainHistory = createDomainHistory(domain);
insertInDb(domainHistory); insertInDb(domainHistory);
jpaTm() tm().transact(
.transact(
() -> { () -> {
DomainHistory fromDatabase = jpaTm().loadByKey(domainHistory.createVKey()); DomainHistory fromDatabase = tm().loadByKey(domainHistory.createVKey());
assertDomainHistoriesEqual(fromDatabase, domainHistory); assertDomainHistoriesEqual(fromDatabase, domainHistory);
assertThat(fromDatabase.getRepoId()).isEqualTo(domainHistory.getRepoId()); assertThat(fromDatabase.getRepoId()).isEqualTo(domainHistory.getRepoId());
}); });
@ -78,8 +77,7 @@ public class DomainHistoryTest extends EntityTestCase {
Domain domain = addGracePeriodForSql(createDomainWithContactsAndHosts()); Domain domain = addGracePeriodForSql(createDomainWithContactsAndHosts());
DomainHistory domainHistory = createDomainHistory(domain); DomainHistory domainHistory = createDomainHistory(domain);
insertInDb(domainHistory); insertInDb(domainHistory);
DomainHistory fromDatabase = DomainHistory fromDatabase = tm().transact(() -> tm().loadByKey(domainHistory.createVKey()));
jpaTm().transact(() -> jpaTm().loadByKey(domainHistory.createVKey()));
assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase); assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase);
} }
@ -88,11 +86,10 @@ public class DomainHistoryTest extends EntityTestCase {
Host host = newHostWithRoid("ns1.example.com", "host1"); Host host = newHostWithRoid("ns1.example.com", "host1");
Contact contact = newContactWithRoid("contactId", "contact1"); Contact contact = newContactWithRoid("contactId", "contact1");
jpaTm() tm().transact(
.transact(
() -> { () -> {
jpaTm().insert(host); tm().insert(host);
jpaTm().insert(contact); tm().insert(contact);
}); });
Domain domain = Domain domain =

View file

@ -16,7 +16,7 @@ package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects; import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.loadByEntity;
import static google.registry.testing.DatabaseHelper.newHostWithRoid; import static google.registry.testing.DatabaseHelper.newHostWithRoid;
@ -45,10 +45,9 @@ public class HostHistoryTest extends EntityTestCase {
Host hostFromDb = loadByEntity(host); Host hostFromDb = loadByEntity(host);
HostHistory hostHistory = createHostHistory(hostFromDb); HostHistory hostHistory = createHostHistory(hostFromDb);
insertInDb(hostHistory); insertInDb(hostHistory);
jpaTm() tm().transact(
.transact(
() -> { () -> {
HostHistory fromDatabase = jpaTm().loadByKey(hostHistory.createVKey()); HostHistory fromDatabase = tm().loadByKey(hostHistory.createVKey());
assertHostHistoriesEqual(fromDatabase, hostHistory); assertHostHistoriesEqual(fromDatabase, hostHistory);
assertThat(fromDatabase.getRepoId()).isEqualTo(hostHistory.getRepoId()); assertThat(fromDatabase.getRepoId()).isEqualTo(hostHistory.getRepoId());
}); });
@ -61,7 +60,7 @@ public class HostHistoryTest extends EntityTestCase {
Host hostFromDb = loadByEntity(host); Host hostFromDb = loadByEntity(host);
HostHistory hostHistory = createHostHistory(hostFromDb); HostHistory hostHistory = createHostHistory(hostFromDb);
insertInDb(hostHistory); insertInDb(hostHistory);
HostHistory fromDatabase = jpaTm().transact(() -> jpaTm().loadByKey(hostHistory.createVKey())); HostHistory fromDatabase = tm().transact(() -> tm().loadByKey(hostHistory.createVKey()));
assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase); assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase);
} }

View file

@ -16,7 +16,7 @@ package google.registry.model.reporting;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence; import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTlds; import static google.registry.testing.DatabaseHelper.createTlds;
import static google.registry.testing.DatabaseHelper.persistActiveContact; import static google.registry.testing.DatabaseHelper.persistActiveContact;
import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResource;
@ -51,32 +51,29 @@ class Spec11ThreatMatchDaoTest extends EntityTestCase {
todayOrgDomain = persistResource(DatabaseHelper.newDomain("today.org", contact)); todayOrgDomain = persistResource(DatabaseHelper.newDomain("today.org", contact));
yesterdayComDomain = persistResource(DatabaseHelper.newDomain("yesterday.com", contact)); yesterdayComDomain = persistResource(DatabaseHelper.newDomain("yesterday.com", contact));
yesterdayOrgDomain = persistResource(DatabaseHelper.newDomain("yesterday.org", contact)); yesterdayOrgDomain = persistResource(DatabaseHelper.newDomain("yesterday.org", contact));
jpaTm() tm().transact(
.transact(
() -> { () -> {
jpaTm().insertAll(getThreatMatchesToday()); tm().insertAll(getThreatMatchesToday());
jpaTm().insertAll(getThreatMatchesYesterday()); tm().insertAll(getThreatMatchesYesterday());
}); });
} }
@Test @Test
void testDeleteEntriesByDate() { void testDeleteEntriesByDate() {
// Verify that all entries with the date TODAY were removed // Verify that all entries with the date TODAY were removed
jpaTm() tm().transact(
.transact(
() -> { () -> {
Spec11ThreatMatchDao.deleteEntriesByDate(jpaTm(), TODAY); Spec11ThreatMatchDao.deleteEntriesByDate(tm(), TODAY);
ImmutableList<Spec11ThreatMatch> persistedToday = ImmutableList<Spec11ThreatMatch> persistedToday =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), TODAY); Spec11ThreatMatchDao.loadEntriesByDate(tm(), TODAY);
assertThat(persistedToday).isEmpty(); assertThat(persistedToday).isEmpty();
}); });
// Verify that all other entries were not removed // Verify that all other entries were not removed
jpaTm() tm().transact(
.transact(
() -> { () -> {
ImmutableList<Spec11ThreatMatch> persistedYesterday = ImmutableList<Spec11ThreatMatch> persistedYesterday =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), YESTERDAY); Spec11ThreatMatchDao.loadEntriesByDate(tm(), YESTERDAY);
assertThat(persistedYesterday) assertThat(persistedYesterday)
.comparingElementsUsing(immutableObjectCorrespondence("id")) .comparingElementsUsing(immutableObjectCorrespondence("id"))
.containsExactlyElementsIn(getThreatMatchesYesterday()); .containsExactlyElementsIn(getThreatMatchesYesterday());
@ -85,11 +82,10 @@ class Spec11ThreatMatchDaoTest extends EntityTestCase {
@Test @Test
void testLoadEntriesByDate() { void testLoadEntriesByDate() {
jpaTm() tm().transact(
.transact(
() -> { () -> {
ImmutableList<Spec11ThreatMatch> persisted = ImmutableList<Spec11ThreatMatch> persisted =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), TODAY); Spec11ThreatMatchDao.loadEntriesByDate(tm(), TODAY);
assertThat(persisted) assertThat(persisted)
.comparingElementsUsing(immutableObjectCorrespondence("id")) .comparingElementsUsing(immutableObjectCorrespondence("id"))

View file

@ -17,7 +17,7 @@ package google.registry.model.tld;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId; import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getMostRecentUnlockedRegistryLockByRepoId; import static google.registry.testing.SqlHelper.getMostRecentUnlockedRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getMostRecentVerifiedRegistryLockByRepoId; import static google.registry.testing.SqlHelper.getMostRecentVerifiedRegistryLockByRepoId;
@ -55,16 +55,14 @@ public final class RegistryLockDaoTest extends EntityTestCase {
RegistryLock lock = createLock(); RegistryLock lock = createLock();
saveRegistryLock(lock); saveRegistryLock(lock);
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
jpaTm() tm().transact(
.transact(
() -> { () -> {
RegistryLock updatedLock = RegistryLock updatedLock =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get(); RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
RegistryLockDao.save( RegistryLockDao.save(
updatedLock.asBuilder().setLockCompletionTime(fakeClock.nowUtc()).build()); updatedLock.asBuilder().setLockCompletionTime(fakeClock.nowUtc()).build());
}); });
jpaTm() tm().transact(
.transact(
() -> { () -> {
RegistryLock fromDatabase = RegistryLock fromDatabase =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get(); RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
@ -97,8 +95,7 @@ public final class RegistryLockDaoTest extends EntityTestCase {
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
RegistryLock updatedLock = lock.asBuilder().setLockCompletionTime(fakeClock.nowUtc()).build(); RegistryLock updatedLock = lock.asBuilder().setLockCompletionTime(fakeClock.nowUtc()).build();
saveRegistryLock(updatedLock); saveRegistryLock(updatedLock);
jpaTm() tm().transact(
.transact(
() -> { () -> {
RegistryLock fromDatabase = RegistryLock fromDatabase =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get(); RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();

View file

@ -17,7 +17,7 @@ package google.registry.model.tld.label;
import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.newRegistry; import static google.registry.testing.DatabaseHelper.newRegistry;
import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResource;
import static org.joda.money.CurrencyUnit.JPY; import static org.joda.money.CurrencyUnit.JPY;
@ -28,7 +28,6 @@ import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import google.registry.persistence.transaction.TransactionManagerFactory;
import google.registry.testing.AppEngineExtension; import google.registry.testing.AppEngineExtension;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.TestCacheExtension; import google.registry.testing.TestCacheExtension;
@ -88,8 +87,7 @@ public class PremiumListDaoTest {
@Test @Test
void saveNew_worksSuccessfully() { void saveNew_worksSuccessfully() {
PremiumListDao.save(testList); PremiumListDao.save(testList);
jpaTm() tm().transact(
.transact(
() -> { () -> {
Optional<PremiumList> persistedListOpt = PremiumListDao.getLatestRevision("testname"); Optional<PremiumList> persistedListOpt = PremiumListDao.getLatestRevision("testname");
assertThat(persistedListOpt).isPresent(); assertThat(persistedListOpt).isPresent();
@ -119,8 +117,7 @@ public class PremiumListDaoTest {
BigDecimal.valueOf(30.03))) BigDecimal.valueOf(30.03)))
.setCreationTimestamp(fakeClock.nowUtc()) .setCreationTimestamp(fakeClock.nowUtc())
.build()); .build());
jpaTm() tm().transact(
.transact(
() -> { () -> {
Optional<PremiumList> savedListOpt = PremiumListDao.getLatestRevision("testname"); Optional<PremiumList> savedListOpt = PremiumListDao.getLatestRevision("testname");
assertThat(savedListOpt).isPresent(); assertThat(savedListOpt).isPresent();
@ -167,8 +164,7 @@ public class PremiumListDaoTest {
.setLabelsToPrices(TEST_PRICES) .setLabelsToPrices(TEST_PRICES)
.setCreationTimestamp(fakeClock.nowUtc()) .setCreationTimestamp(fakeClock.nowUtc())
.build()); .build());
jpaTm() tm().transact(
.transact(
() -> { () -> {
Optional<PremiumList> persistedList = PremiumListDao.getLatestRevision("list1"); Optional<PremiumList> persistedList = PremiumListDao.getLatestRevision("list1");
assertThat(persistedList).isPresent(); assertThat(persistedList).isPresent();
@ -188,8 +184,7 @@ public class PremiumListDaoTest {
.setLabelsToPrices(TEST_PRICES) .setLabelsToPrices(TEST_PRICES)
.setCreationTimestamp(fakeClock.nowUtc()) .setCreationTimestamp(fakeClock.nowUtc())
.build()); .build());
jpaTm() tm().transact(
.transact(
() -> { () -> {
PremiumList premiumList = PremiumListDao.getLatestRevision("list1").get(); PremiumList premiumList = PremiumListDao.getLatestRevision("list1").get();
assertThat(premiumList.getLabelsToPrices()) assertThat(premiumList.getLabelsToPrices())
@ -260,8 +255,7 @@ public class PremiumListDaoTest {
PremiumListDao.save(testList); PremiumListDao.save(testList);
PremiumList pl = PremiumListDao.getLatestRevision("testname").get(); PremiumList pl = PremiumListDao.getLatestRevision("testname").get();
assertThat(PremiumListDao.premiumListCache.getIfPresent("testname")).hasValue(pl); assertThat(PremiumListDao.premiumListCache.getIfPresent("testname")).hasValue(pl);
TransactionManagerFactory.tm() tm().transact(() -> PremiumListDao.save("testname", USD, ImmutableList.of("test,USD 1")));
.transact(() -> PremiumListDao.save("testname", USD, ImmutableList.of("test,USD 1")));
assertThat(PremiumListDao.premiumListCache.getIfPresent("testname")).isNull(); assertThat(PremiumListDao.premiumListCache.getIfPresent("testname")).isNull();
} }

View file

@ -15,7 +15,7 @@
package google.registry.model.tld.label; package google.registry.model.tld.label;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import google.registry.model.tld.label.ReservedList.ReservedListEntry; import google.registry.model.tld.label.ReservedList.ReservedListEntry;
@ -60,12 +60,10 @@ public class ReservedListDaoTest {
@Test @Test
void save_worksSuccessfully() { void save_worksSuccessfully() {
ReservedListDao.save(testReservedList); ReservedListDao.save(testReservedList);
jpaTm() tm().transact(
.transact(
() -> { () -> {
ReservedList persistedList = ReservedList persistedList =
jpaTm() tm().query("FROM ReservedList WHERE name = :name", ReservedList.class)
.query("FROM ReservedList WHERE name = :name", ReservedList.class)
.setParameter("name", "testlist") .setParameter("name", "testlist")
.getSingleResult(); .getSingleResult();
assertThat(persistedList.getReservedListEntries()) assertThat(persistedList.getReservedListEntries())

View file

@ -15,7 +15,7 @@
package google.registry.model.tmch; package google.registry.model.tmch;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -110,7 +110,7 @@ public class ClaimsListDaoTest {
ClaimsList claimsList = ClaimsList claimsList =
ClaimsList.create(fakeClock.nowUtc(), ImmutableMap.of("label1", "key1", "label2", "key2")); ClaimsList.create(fakeClock.nowUtc(), ImmutableMap.of("label1", "key1", "label2", "key2"));
// Bypass the DAO to avoid the cache // Bypass the DAO to avoid the cache
jpaTm().transact(() -> jpaTm().insert(claimsList)); tm().transact(() -> tm().insert(claimsList));
ClaimsList fromDatabase = ClaimsListDao.get(); ClaimsList fromDatabase = ClaimsListDao.get();
// At first, we haven't loaded any entries // At first, we haven't loaded any entries
assertThat(fromDatabase.claimKeyCache.getIfPresent("label1")).isNull(); assertThat(fromDatabase.claimKeyCache.getIfPresent("label1")).isNull();

View file

@ -17,7 +17,7 @@ package google.registry.persistence;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -56,27 +56,24 @@ class EntityCallbacksListenerTest {
TestEntity testUpdate = new TestEntity(); TestEntity testUpdate = new TestEntity();
TestEntity updated = TestEntity updated =
jpaTm() tm().transact(
.transact(
() -> { () -> {
TestEntity merged = jpaTm().getEntityManager().merge(testUpdate); TestEntity merged = tm().getEntityManager().merge(testUpdate);
merged.nonTransientField++; merged.nonTransientField++;
jpaTm().getEntityManager().flush(); tm().getEntityManager().flush();
return merged; return merged;
}); });
// Note that when we get the merged entity, its @PostLoad callbacks are also invoked // Note that when we get the merged entity, its @PostLoad callbacks are also invoked
checkAll(updated, 0, 1, 0, 1); checkAll(updated, 0, 1, 0, 1);
TestEntity testLoad = TestEntity testLoad = tm().transact(() -> tm().loadByKey(VKey.create(TestEntity.class, "id")));
jpaTm().transact(() -> jpaTm().loadByKey(VKey.create(TestEntity.class, "id")));
checkAll(testLoad, 0, 0, 0, 1); checkAll(testLoad, 0, 0, 0, 1);
TestEntity testRemove = TestEntity testRemove =
jpaTm() tm().transact(
.transact(
() -> { () -> {
TestEntity removed = jpaTm().loadByKey(VKey.create(TestEntity.class, "id")); TestEntity removed = tm().loadByKey(VKey.create(TestEntity.class, "id"));
return jpaTm().delete(removed); return tm().delete(removed);
}); });
checkAll(testRemove, 0, 0, 1, 1); checkAll(testRemove, 0, 0, 1, 1);
} }
@ -104,11 +101,10 @@ class EntityCallbacksListenerTest {
void verifyCallbacksNotCalledOnCommit() { void verifyCallbacksNotCalledOnCommit() {
insertInDb(new TestEntity()); insertInDb(new TestEntity());
TestEntity testLoad = TestEntity testLoad = tm().transact(() -> tm().loadByKey(VKey.create(TestEntity.class, "id")));
jpaTm().transact(() -> jpaTm().loadByKey(VKey.create(TestEntity.class, "id")));
assertThat(testLoad.entityPreUpdate).isEqualTo(0); assertThat(testLoad.entityPreUpdate).isEqualTo(0);
testLoad = jpaTm().transact(() -> jpaTm().loadByKey(VKey.create(TestEntity.class, "id"))); testLoad = tm().transact(() -> tm().loadByKey(VKey.create(TestEntity.class, "id")));
// Verify that post-load happened but pre-update didn't. // Verify that post-load happened but pre-update didn't.
assertThat(testLoad.entityPostLoad).isEqualTo(1); assertThat(testLoad.entityPostLoad).isEqualTo(1);

View file

@ -17,7 +17,7 @@ package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.domain.token.AllocationToken.TokenType.SINGLE_USE; import static google.registry.model.domain.token.AllocationToken.TokenType.SINGLE_USE;
import static google.registry.model.domain.token.AllocationToken.TokenType.UNLIMITED_USE; import static google.registry.model.domain.token.AllocationToken.TokenType.UNLIMITED_USE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -52,9 +52,7 @@ public class AllocationTokenListConverterTest {
new TestAllocationTokenVKeyList(tokens); new TestAllocationTokenVKeyList(tokens);
insertInDb(testAllocationTokenVKeyList); insertInDb(testAllocationTokenVKeyList);
TestAllocationTokenVKeyList persisted = TestAllocationTokenVKeyList persisted =
jpaTm() tm().transact(() -> tm().getEntityManager().find(TestAllocationTokenVKeyList.class, "id"));
.transact(
() -> jpaTm().getEntityManager().find(TestAllocationTokenVKeyList.class, "id"));
assertThat(persisted.tokenList).isEqualTo(tokens); assertThat(persisted.tokenList).isEqualTo(tokens);
} }

View file

@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.ENDED; import static google.registry.model.domain.token.AllocationToken.TokenStatus.ENDED;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT_STARTED; import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT_STARTED;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.VALID; import static google.registry.model.domain.token.AllocationToken.TokenStatus.VALID;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -60,11 +60,9 @@ public class AllocationTokenStatusTransitionConverterTest {
new AllocationTokenStatusTransitionConverterTestEntity(timedTransitionProperty); new AllocationTokenStatusTransitionConverterTestEntity(timedTransitionProperty);
insertInDb(testEntity); insertInDb(testEntity);
AllocationTokenStatusTransitionConverterTestEntity persisted = AllocationTokenStatusTransitionConverterTestEntity persisted =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.find(AllocationTokenStatusTransitionConverterTestEntity.class, "id")); .find(AllocationTokenStatusTransitionConverterTestEntity.class, "id"));
assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty); assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty);
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
@ -53,7 +53,7 @@ public class BillingCostTransitionConverterTest {
TestEntity testEntity = new TestEntity(timedTransitionProperty); TestEntity testEntity = new TestEntity(timedTransitionProperty);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty); assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty);
} }

View file

@ -16,7 +16,7 @@ package google.registry.persistence.converter;
import static com.google.common.base.Charsets.US_ASCII; import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.hash.Funnels.stringFunnel; import static com.google.common.hash.Funnels.stringFunnel;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -43,7 +43,7 @@ class BloomFilterConverterTest {
TestEntity entity = new TestEntity(bloomFilter); TestEntity entity = new TestEntity(bloomFilter);
insertInDb(entity); insertInDb(entity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.bloomFilter).isEqualTo(bloomFilter); assertThat(persisted.bloomFilter).isEqualTo(bloomFilter);
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -48,7 +48,7 @@ public class CidrAddressBlockListConverterTest {
TestEntity testEntity = new TestEntity(addresses); TestEntity testEntity = new TestEntity(addresses);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.addresses).isEqualTo(addresses); assertThat(persisted.addresses).isEqualTo(addresses);
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -45,7 +45,7 @@ public class CurrencyToBillingConverterTest {
TestEntity testEntity = new TestEntity(currencyToBilling); TestEntity testEntity = new TestEntity(currencyToBilling);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.currencyToBilling).containsExactlyEntriesIn(currencyToBilling); assertThat(persisted.currencyToBilling).containsExactlyEntriesIn(currencyToBilling);
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -41,27 +41,23 @@ public class CurrencyUnitConverterTest {
TestEntity entity = new TestEntity(CurrencyUnit.EUR); TestEntity entity = new TestEntity(CurrencyUnit.EUR);
insertInDb(entity); insertInDb(entity);
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT currency FROM \"TestEntity\" WHERE name = 'id'") "SELECT currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList())) .getResultList()))
.containsExactly("EUR"); .containsExactly("EUR");
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.currency).isEqualTo(CurrencyUnit.EUR); assertThat(persisted.currency).isEqualTo(CurrencyUnit.EUR);
} }
@Test @Test
void invalidCurrency() { void invalidCurrency() {
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"INSERT INTO \"TestEntity\" (name, currency) VALUES('id', 'XXXX')") "INSERT INTO \"TestEntity\" (name, currency) VALUES('id', 'XXXX')")
.executeUpdate()); .executeUpdate());
@ -69,9 +65,7 @@ public class CurrencyUnitConverterTest {
assertThrows( assertThrows(
PersistenceException.class, PersistenceException.class,
() -> () ->
jpaTm() tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id").currency));
.transact(
() -> jpaTm().getEntityManager().find(TestEntity.class, "id").currency));
assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("Unknown currency 'XXXX'"); assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("Unknown currency 'XXXX'");
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -63,11 +63,9 @@ public class DatabaseMigrationScheduleTransitionConverterTest {
new DatabaseMigrationScheduleTransitionConverterTestEntity(timedTransitionProperty); new DatabaseMigrationScheduleTransitionConverterTestEntity(timedTransitionProperty);
insertInDb(testEntity); insertInDb(testEntity);
DatabaseMigrationScheduleTransitionConverterTestEntity persisted = DatabaseMigrationScheduleTransitionConverterTestEntity persisted =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.find(DatabaseMigrationScheduleTransitionConverterTestEntity.class, "id")); .find(DatabaseMigrationScheduleTransitionConverterTestEntity.class, "id"));
assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty); assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty);
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
@ -72,9 +72,7 @@ public class DateTimeConverterTest {
TestEntity entity = new TestEntity("normalized_utc_time", dt); TestEntity entity = new TestEntity("normalized_utc_time", dt);
insertInDb(entity); insertInDb(entity);
TestEntity retrievedEntity = TestEntity retrievedEntity =
jpaTm() tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "normalized_utc_time"));
.transact(
() -> jpaTm().getEntityManager().find(TestEntity.class, "normalized_utc_time"));
assertThat(retrievedEntity.dt.toString()).isEqualTo("2019-09-01T01:01:01.000Z"); assertThat(retrievedEntity.dt.toString()).isEqualTo("2019-09-01T01:01:01.000Z");
} }
@ -85,7 +83,7 @@ public class DateTimeConverterTest {
insertInDb(entity); insertInDb(entity);
TestEntity retrievedEntity = TestEntity retrievedEntity =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "new_york_time")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "new_york_time"));
assertThat(retrievedEntity.dt.toString()).isEqualTo("2019-09-01T06:01:01.000Z"); assertThat(retrievedEntity.dt.toString()).isEqualTo("2019-09-01T06:01:01.000Z");
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
@ -82,7 +82,7 @@ public class DurationConverterTest {
DurationTestEntity entity = new DurationTestEntity(duration); DurationTestEntity entity = new DurationTestEntity(duration);
insertInDb(entity); insertInDb(entity);
DurationTestEntity persisted = DurationTestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(DurationTestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(DurationTestEntity.class, "id"));
assertThat(persisted.duration.getMillis()).isEqualTo(duration.getMillis()); assertThat(persisted.duration.getMillis()).isEqualTo(duration.getMillis());
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -65,8 +65,7 @@ public class InetAddressSetConverterTest {
InetAddressSetTestEntity testEntity = new InetAddressSetTestEntity(inetAddresses); InetAddressSetTestEntity testEntity = new InetAddressSetTestEntity(inetAddresses);
insertInDb(testEntity); insertInDb(testEntity);
InetAddressSetTestEntity persisted = InetAddressSetTestEntity persisted =
jpaTm() tm().transact(() -> tm().loadByKey(VKey.create(InetAddressSetTestEntity.class, "id")));
.transact(() -> jpaTm().loadByKey(VKey.create(InetAddressSetTestEntity.class, "id")));
assertThat(persisted.addresses).isEqualTo(inetAddresses); assertThat(persisted.addresses).isEqualTo(inetAddresses);
} }

View file

@ -14,7 +14,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -60,11 +60,9 @@ public class JodaMoneyConverterTest {
TestEntity entity = new TestEntity(money); TestEntity entity = new TestEntity(money);
insertInDb(entity); insertInDb(entity);
List<?> result = List<?> result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'") "SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList()); .getResultList());
@ -75,7 +73,7 @@ public class JodaMoneyConverterTest {
.containsExactly(BigDecimal.valueOf(100.12).setScale(2), "USD") .containsExactly(BigDecimal.valueOf(100.12).setScale(2), "USD")
.inOrder(); .inOrder();
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.money).isEqualTo(money); assertThat(persisted.money).isEqualTo(money);
} }
@ -86,11 +84,9 @@ public class JodaMoneyConverterTest {
TestEntity entity = new TestEntity(money); TestEntity entity = new TestEntity(money);
insertInDb(entity); insertInDb(entity);
List<?> result = List<?> result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'") "SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList()); .getResultList());
@ -102,11 +98,9 @@ public class JodaMoneyConverterTest {
.inOrder(); .inOrder();
result = result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name" + " = 'id'") .createQuery("SELECT money FROM TestEntity WHERE name" + " = 'id'")
.getResultList()); .getResultList());
@ -114,7 +108,7 @@ public class JodaMoneyConverterTest {
assertThat(result.get(0)).isEqualTo(money); assertThat(result.get(0)).isEqualTo(money);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.money).isEqualTo(money); assertThat(persisted.money).isEqualTo(money);
} }
@ -130,11 +124,9 @@ public class JodaMoneyConverterTest {
ComplexTestEntity entity = new ComplexTestEntity(moneyMap, myMoney, yourMoney); ComplexTestEntity entity = new ComplexTestEntity(moneyMap, myMoney, yourMoney);
insertInDb(entity); insertInDb(entity);
List<?> result = List<?> result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT my_amount, my_currency, your_amount, your_currency FROM" "SELECT my_amount, my_currency, your_amount, your_currency FROM"
+ " \"ComplexTestEntity\" WHERE name = 'id'") + " \"ComplexTestEntity\" WHERE name = 'id'")
@ -145,17 +137,15 @@ public class JodaMoneyConverterTest {
BigDecimal.valueOf(100).setScale(2), "USD", BigDecimal.valueOf(80).setScale(2), "GBP") BigDecimal.valueOf(100).setScale(2), "USD", BigDecimal.valueOf(80).setScale(2), "GBP")
.inOrder(); .inOrder();
result = result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT map_amount, map_currency FROM \"MoneyMap\"" "SELECT map_amount, map_currency FROM \"MoneyMap\""
+ " WHERE entity_name = 'id' AND map_key = 'dos'") + " WHERE entity_name = 'id' AND map_key = 'dos'")
.getResultList()); .getResultList());
ComplexTestEntity persisted = ComplexTestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(ComplexTestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(ComplexTestEntity.class, "id"));
assertThat(result).hasSize(1); assertThat(result).hasSize(1);
assertThat(Arrays.asList((Object[]) result.get(0))) assertThat(Arrays.asList((Object[]) result.get(0)))
@ -173,32 +163,26 @@ public class JodaMoneyConverterTest {
*/ */
@Test @Test
void testNullSafeGet_nullAmountNullCurrency_returnsNull() throws SQLException { void testNullSafeGet_nullAmountNullCurrency_returnsNull() throws SQLException {
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', null," "INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', null,"
+ " null)") + " null)")
.executeUpdate()); .executeUpdate());
List<?> result = List<?> result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'") "SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList()); .getResultList());
assertThat(result).hasSize(1); assertThat(result).hasSize(1);
assertThat(Arrays.asList((Object[]) result.get(0))).containsExactly(null, null).inOrder(); assertThat(Arrays.asList((Object[]) result.get(0))).containsExactly(null, null).inOrder();
assertThat( assertThat(
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name = 'id'") .createQuery("SELECT money FROM TestEntity WHERE name = 'id'")
.getResultList()) .getResultList())
.get(0)) .get(0))
@ -207,21 +191,17 @@ public class JodaMoneyConverterTest {
@Test @Test
void testNullSafeGet_nullAMountValidCurrency_throwsHibernateException() throws SQLException { void testNullSafeGet_nullAMountValidCurrency_throwsHibernateException() throws SQLException {
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', null," "INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', null,"
+ " 'USD')") + " 'USD')")
.executeUpdate()); .executeUpdate());
List<?> result = List<?> result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'") "SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList()); .getResultList());
@ -232,11 +212,9 @@ public class JodaMoneyConverterTest {
assertThrows( assertThrows(
PersistenceException.class, PersistenceException.class,
() -> () ->
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name = 'id'") .createQuery("SELECT money FROM TestEntity WHERE name = 'id'")
.getResultList())); .getResultList()));
assertThat(thrown) assertThat(thrown)
@ -249,21 +227,17 @@ public class JodaMoneyConverterTest {
@Test @Test
void testNullSafeGet_nullAMountInValidCurrency_throwsIllegalCurrencyException() void testNullSafeGet_nullAMountInValidCurrency_throwsIllegalCurrencyException()
throws SQLException { throws SQLException {
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', 100," "INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', 100,"
+ " 'INVALIDCURRENCY')") + " 'INVALIDCURRENCY')")
.executeUpdate()); .executeUpdate());
List<?> result = List<?> result =
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createNativeQuery( .createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'") "SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList()); .getResultList());
@ -275,11 +249,9 @@ public class JodaMoneyConverterTest {
assertThrows( assertThrows(
IllegalCurrencyException.class, IllegalCurrencyException.class,
() -> () ->
jpaTm() tm().transact(
.transact(
() -> () ->
jpaTm() tm().getEntityManager()
.getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name = 'id'") .createQuery("SELECT money FROM TestEntity WHERE name = 'id'")
.getResultList())); .getResultList()));
assertThat(thrown).hasMessageThat().isEqualTo("Unknown currency 'INVALIDCURRENCY'"); assertThat(thrown).hasMessageThat().isEqualTo("Unknown currency 'INVALIDCURRENCY'");

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
@ -55,8 +55,8 @@ public class LocalDateConverterTest {
private LocalDateConverterTestEntity persistAndLoadTestEntity(LocalDate date) { private LocalDateConverterTestEntity persistAndLoadTestEntity(LocalDate date) {
LocalDateConverterTestEntity entity = new LocalDateConverterTestEntity(date); LocalDateConverterTestEntity entity = new LocalDateConverterTestEntity(date);
insertInDb(entity); insertInDb(entity);
return jpaTm() return tm().transact(
.transact(() -> jpaTm().loadByKey(VKey.create(LocalDateConverterTestEntity.class, "id"))); () -> tm().loadByKey(VKey.create(LocalDateConverterTestEntity.class, "id")));
} }
/** Override entity name to avoid the nested class reference. */ /** Override entity name to avoid the nested class reference. */

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -43,7 +43,7 @@ public class StatusValueSetConverterTest {
insertInDb(obj); insertInDb(obj);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "foo")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "foo"));
assertThat(persisted.data).isEqualTo(enums); assertThat(persisted.data).isEqualTo(enums);
} }

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -43,7 +43,7 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(tlds); TestEntity testEntity = new TestEntity(tlds);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.tlds).containsExactly("app", "dev", "how"); assertThat(persisted.tlds).containsExactly("app", "dev", "how");
} }
@ -53,11 +53,10 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(tlds); TestEntity testEntity = new TestEntity(tlds);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
persisted.tlds = ImmutableList.of("com", "gov"); persisted.tlds = ImmutableList.of("com", "gov");
jpaTm().transact(() -> jpaTm().getEntityManager().merge(persisted)); tm().transact(() -> tm().getEntityManager().merge(persisted));
TestEntity updated = TestEntity updated = tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
assertThat(updated.tlds).containsExactly("com", "gov"); assertThat(updated.tlds).containsExactly("com", "gov");
} }
@ -66,7 +65,7 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(null); TestEntity testEntity = new TestEntity(null);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.tlds).isNull(); assertThat(persisted.tlds).isNull();
} }
@ -75,7 +74,7 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(ImmutableList.of()); TestEntity testEntity = new TestEntity(ImmutableList.of());
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.tlds).isEmpty(); assertThat(persisted.tlds).isEmpty();
} }
@ -107,13 +106,11 @@ public class StringListConverterTest {
} }
private static Object getSingleResultFromNativeQuery(String sql) { private static Object getSingleResultFromNativeQuery(String sql) {
return jpaTm() return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).getSingleResult());
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).getSingleResult());
} }
private static Object executeNativeQuery(String sql) { private static Object executeNativeQuery(String sql) {
return jpaTm() return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).executeUpdate());
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).executeUpdate());
} }
@Entity(name = "TestEntity") // Override entity name to avoid the nested class reference. @Entity(name = "TestEntity") // Override entity name to avoid the nested class reference.

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter; package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb; import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -51,7 +51,7 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(MAP); TestEntity testEntity = new TestEntity(MAP);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).containsExactlyEntriesIn(MAP); assertThat(persisted.map).containsExactlyEntriesIn(MAP);
} }
@ -60,12 +60,11 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(MAP); TestEntity testEntity = new TestEntity(MAP);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).containsExactlyEntriesIn(MAP); assertThat(persisted.map).containsExactlyEntriesIn(MAP);
persisted.map = ImmutableMap.of(new Key("key4"), new Value("value4")); persisted.map = ImmutableMap.of(new Key("key4"), new Value("value4"));
jpaTm().transact(() -> jpaTm().getEntityManager().merge(persisted)); tm().transact(() -> tm().getEntityManager().merge(persisted));
TestEntity updated = TestEntity updated = tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
assertThat(updated.map).containsExactly(new Key("key4"), new Value("value4")); assertThat(updated.map).containsExactly(new Key("key4"), new Value("value4"));
} }
@ -74,7 +73,7 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(null); TestEntity testEntity = new TestEntity(null);
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).isNull(); assertThat(persisted.map).isNull();
} }
@ -83,7 +82,7 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(ImmutableMap.of()); TestEntity testEntity = new TestEntity(ImmutableMap.of());
insertInDb(testEntity); insertInDb(testEntity);
TestEntity persisted = TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id")); tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).isEmpty(); assertThat(persisted.map).isEmpty();
} }
@ -117,13 +116,11 @@ public class StringMapConverterBaseTest {
} }
private static Object getSingleResultFromNativeQuery(String sql) { private static Object getSingleResultFromNativeQuery(String sql) {
return jpaTm() return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).getSingleResult());
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).getSingleResult());
} }
private static Object executeNativeQuery(String sql) { private static Object executeNativeQuery(String sql) {
return jpaTm() return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).executeUpdate());
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).executeUpdate());
} }
private static class Key extends ImmutableObject { private static class Key extends ImmutableObject {

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