Run automatic Java 8 conversion over codebase

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=171174380
This commit is contained in:
mcilwain 2017-10-05 10:48:38 -07:00 committed by Ben McIlwain
parent 44df5da771
commit 5edb7935ed
190 changed files with 2312 additions and 3096 deletions

View file

@ -30,7 +30,6 @@ import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.appengine.tools.cloudstorage.ListItem;
import com.google.appengine.tools.cloudstorage.ListResult;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.testing.TestLogHandler;
import google.registry.testing.AppEngineRule;
@ -85,12 +84,9 @@ public class GcsDiffFileListerTest {
private Iterable<DateTime> extractTimesFromDiffFiles(List<GcsFileMetadata> diffFiles) {
return transform(
diffFiles,
new Function<GcsFileMetadata, DateTime>() {
@Override
public DateTime apply(GcsFileMetadata metadata) {
return DateTime.parse(
metadata.getFilename().getObjectName().substring(DIFF_FILE_PREFIX.length()));
}});
metadata ->
DateTime.parse(
metadata.getFilename().getObjectName().substring(DIFF_FILE_PREFIX.length())));
}
private Iterable<DateTime> listDiffFiles(DateTime fromTime, DateTime toTime) {

View file

@ -33,7 +33,6 @@ import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
@ -278,13 +277,8 @@ public class RestoreCommitLogsActionTest {
}
private void assertExpectedIds(String... ids) {
assertThat(transform(
ofy().load().type(TestObject.class),
new Function<TestObject, String>() {
@Override
public String apply(TestObject test) {
return test.getId();
}})).containsExactly((Object[]) ids);
assertThat(transform(ofy().load().type(TestObject.class), TestObject::getId))
.containsExactly((Object[]) ids);
}
private void assertInDatastore(Iterable<? extends ImmutableObject> entities) {

View file

@ -13,8 +13,9 @@
// limitations under the License.
package google.registry.batch;
import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.async.AsyncFlowEnqueuer.QUEUE_ASYNC_DELETE;
import static google.registry.flows.async.AsyncFlowEnqueuer.QUEUE_ASYNC_HOST_RENAME;
@ -57,7 +58,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@ -292,15 +292,21 @@ public class DeleteContactsAndHostsActionTest
Iterables.getOnlyElement(getPollMessages("NewRegistrar", clock.nowUtc()));
assertThat(gainingPollMessage.getEventTime()).isLessThan(clock.nowUtc());
assertThat(
Iterables.getOnlyElement(
FluentIterable.from(gainingPollMessage.getResponseData())
.filter(TransferResponse.class))
gainingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.SERVER_CANCELLED);
PendingActionNotificationResponse panData =
getOnlyElement(
FluentIterable.from(gainingPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
gainingPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid())
.isEqualTo(Trid.create("transferClient-trid", "transferServer-trid"));
assertThat(panData.getActionResult()).isFalse();

View file

@ -25,7 +25,6 @@ import static java.util.Arrays.asList;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo.TaskStateInfo;
import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
@ -106,14 +105,13 @@ public class TldFanoutActionTest {
private static void assertTasks(String... tasks) throws Exception {
assertTasksEnqueued(
QUEUE,
transform(asList(tasks), new Function<String, TaskMatcher>() {
@Override
public TaskMatcher apply(String namespace) {
return new TaskMatcher()
.url(ENDPOINT)
.header("content-type", "application/x-www-form-urlencoded")
.param("tld", namespace);
}}));
transform(
asList(tasks),
(String namespace) ->
new TaskMatcher()
.url(ENDPOINT)
.header("content-type", "application/x-www-form-urlencoded")
.param("tld", namespace)));
}
@Test

View file

@ -29,7 +29,6 @@ import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo.TaskStateInfo;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
@ -129,16 +128,12 @@ public class ReadDnsQueueActionTest {
DNS_PUBLISH_PUSH_QUEUE_NAME,
transform(
tldsToDnsWriters.entries().asList(),
new Function<Entry<String, String>, TaskMatcher>() {
@Override
public TaskMatcher apply(Entry<String, String> tldToDnsWriter) {
return new TaskMatcher()
(Entry<String, String> tldToDnsWriter) ->
new TaskMatcher()
.url(PublishDnsUpdatesAction.PATH)
.param("tld", tldToDnsWriter.getKey())
.param("dnsWriter", tldToDnsWriter.getValue())
.header("content-type", "application/x-www-form-urlencoded");
}
}));
.header("content-type", "application/x-www-form-urlencoded")));
}
@Test

View file

@ -14,6 +14,7 @@
package google.registry.dns.writer.clouddns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld;
@ -30,8 +31,6 @@ import com.google.api.services.dns.Dns;
import com.google.api.services.dns.model.Change;
import com.google.api.services.dns.model.ResourceRecordSet;
import com.google.api.services.dns.model.ResourceRecordSetsListResponse;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -54,7 +53,6 @@ import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
@ -128,21 +126,18 @@ public class CloudDnsWriterTest {
throws Throwable {
return new ResourceRecordSetsListResponse()
.setRrsets(
FluentIterable.from(stubZone)
stubZone
.stream()
.filter(
new Predicate<ResourceRecordSet>() {
@Override
public boolean apply(
@Nullable ResourceRecordSet resourceRecordSet) {
if (resourceRecordSet == null) {
return false;
}
return resourceRecordSet
.getName()
.equals(recordNameCaptor.getValue());
resourceRecordSet -> {
if (resourceRecordSet == null) {
return false;
}
return resourceRecordSet
.getName()
.equals(recordNameCaptor.getValue());
})
.toList());
.collect(toImmutableList()));
}
});

View file

@ -23,7 +23,6 @@ import static org.mockito.Mockito.when;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.modules.ModulesService;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import google.registry.testing.AppEngineRule;
@ -98,30 +97,24 @@ public class DatastoreBackupServiceTest {
.param("kind", "bar"));
}
private static final Function<DatastoreBackupInfo, String> BACKUP_NAME_GETTER =
new Function<DatastoreBackupInfo, String>() {
@Override
public String apply(DatastoreBackupInfo backup) {
return backup.getName();
}};
@Test
public void testSuccess_findAllByNamePrefix() throws Exception {
assertThat(transform(backupService.findAllByNamePrefix("backupA"), BACKUP_NAME_GETTER))
assertThat(
transform(backupService.findAllByNamePrefix("backupA"), DatastoreBackupInfo::getName))
.containsExactly("backupA1", "backupA2", "backupA3");
assertThat(transform(backupService.findAllByNamePrefix("backupB"), BACKUP_NAME_GETTER))
assertThat(
transform(backupService.findAllByNamePrefix("backupB"), DatastoreBackupInfo::getName))
.containsExactly("backupB1", "backupB42");
assertThat(transform(backupService.findAllByNamePrefix("backupB4"), BACKUP_NAME_GETTER))
assertThat(
transform(backupService.findAllByNamePrefix("backupB4"), DatastoreBackupInfo::getName))
.containsExactly("backupB42");
assertThat(backupService.findAllByNamePrefix("backupX")).isEmpty();
}
@Test
public void testSuccess_findByName() throws Exception {
assertThat(BACKUP_NAME_GETTER.apply(backupService.findByName("backupA1")))
.isEqualTo("backupA1");
assertThat(BACKUP_NAME_GETTER.apply(backupService.findByName("backupB4")))
.isEqualTo("backupB42");
assertThat(backupService.findByName("backupA1").getName()).isEqualTo("backupA1");
assertThat(backupService.findByName("backupB4").getName()).isEqualTo("backupB42");
}
@Test

View file

@ -15,6 +15,7 @@
package google.registry.export;
import static com.google.common.base.Strings.repeat;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.io.Resources.getResource;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
@ -22,14 +23,12 @@ import static google.registry.export.ExportConstants.getBackupKinds;
import static google.registry.export.ExportConstants.getReportingKinds;
import static google.registry.util.ResourceUtils.readResourceUtf8;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.re2j.Pattern;
import javax.annotation.Nullable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@ -91,15 +90,8 @@ public class ExportConstantsTest {
private static ImmutableList<String> extractListFromFile(String filename) {
String fileContents = readResourceUtf8(ExportConstantsTest.class, filename);
final Pattern stripComments = Pattern.compile("\\s*#.*$");
return FluentIterable.from(Splitter.on('\n').split(fileContents.trim()))
.transform(
new Function<String, String>() {
@Override
@Nullable
public String apply(@Nullable String line) {
return stripComments.matcher(line).replaceFirst("");
}
})
.toList();
return Streams.stream(Splitter.on('\n').split(fileContents.trim()))
.map(line -> stripComments.matcher(line).replaceFirst(""))
.collect(toImmutableList());
}
}

View file

@ -37,7 +37,6 @@ import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobConfigurationLoad;
import com.google.api.services.bigquery.model.JobReference;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import google.registry.bigquery.BigqueryFactory;
@ -138,31 +137,27 @@ public class LoadSnapshotActionTest {
}
// Check the job IDs for each load job.
assertThat(transform(jobs, new Function<Job, String>() {
@Override
public String apply(Job job) {
return job.getJobReference().getJobId();
}})).containsExactly(
assertThat(transform(jobs, job -> job.getJobReference().getJobId()))
.containsExactly(
"load-snapshot-id12345-one-1391096117045",
"load-snapshot-id12345-two-1391096117045",
"load-snapshot-id12345-three-1391096117045");
// Check the source URI for each load job.
assertThat(transform(jobs, new Function<Job, String>() {
@Override
public String apply(Job job) {
return Iterables.getOnlyElement(job.getConfiguration().getLoad().getSourceUris());
}})).containsExactly(
assertThat(
transform(
jobs,
job -> Iterables.getOnlyElement(job.getConfiguration().getLoad().getSourceUris())))
.containsExactly(
"gs://bucket/snapshot.one.backup_info",
"gs://bucket/snapshot.two.backup_info",
"gs://bucket/snapshot.three.backup_info");
// Check the destination table ID for each load job.
assertThat(transform(jobs, new Function<Job, String>() {
@Override
public String apply(Job job) {
return job.getConfiguration().getLoad().getDestinationTable().getTableId();
}})).containsExactly("id12345_one", "id12345_two", "id12345_three");
assertThat(
transform(
jobs, job -> job.getConfiguration().getLoad().getDestinationTable().getTableId()))
.containsExactly("id12345_one", "id12345_two", "id12345_three");
// Check that we executed the inserted jobs.
verify(bigqueryJobsInsert, times(3)).execute();

View file

@ -32,7 +32,6 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import google.registry.groups.DirectoryGroupsConnection;
@ -198,11 +197,8 @@ public class SyncGroupMembersActionTest {
"hexadecimal@snow.fall",
Role.MEMBER);
verify(response).setStatus(SC_OK);
assertThat(Iterables.filter(Registrar.loadAll(), new Predicate<Registrar>() {
@Override
public boolean apply(Registrar registrar) {
return registrar.getContactsRequireSyncing();
}})).isEmpty();
assertThat(Iterables.filter(Registrar.loadAll(), Registrar::getContactsRequireSyncing))
.isEmpty();
}
@Test

View file

@ -32,7 +32,6 @@ import static org.mockito.Mockito.when;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.model.Dataset;
import com.google.api.services.bigquery.model.Table;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import google.registry.bigquery.BigqueryFactory;
import google.registry.request.HttpException.InternalServerErrorException;
@ -118,14 +117,7 @@ public class UpdateSnapshotViewActionTest {
tableOrder.verify(bigqueryTables)
.update(eq("myproject"), eq("latest_datastore_export"), eq("fookind"), tableArg.capture());
Iterable<String> actualQueries =
Iterables.transform(
tableArg.getAllValues(),
new Function<Table, String>() {
@Override
public String apply(Table table) {
return table.getView().getQuery();
}
});
Iterables.transform(tableArg.getAllValues(), table -> table.getView().getQuery());
assertThat(actualQueries).containsExactly(
"#legacySQL\nSELECT * FROM [myproject:some_dataset.12345_fookind]",
"#standardSQL\nSELECT * FROM `myproject.some_dataset.12345_fookind`");

View file

@ -178,19 +178,6 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
}
/** Helper to remove the grace period's billing event key to facilitate comparison. */
private static final Function<GracePeriod, GracePeriod> GRACE_PERIOD_KEY_STRIPPER =
new Function<GracePeriod, GracePeriod>() {
@Override
public GracePeriod apply(GracePeriod gracePeriod) {
return GracePeriod.create(
gracePeriod.isSunrushAddGracePeriod()
? GracePeriodStatus.SUNRUSH_ADD
: gracePeriod.getType(),
gracePeriod.getExpirationTime(),
gracePeriod.getClientId(),
null);
}};
/** A helper class that sets the billing event parent history entry to facilitate comparison. */
public static class BillingEventParentSetter implements Function<BillingEvent, BillingEvent> {
private HistoryEntry historyEntry;
@ -220,7 +207,16 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
ImmutableMap.Builder<GracePeriod, BillingEvent> builder = new ImmutableMap.Builder<>();
for (Map.Entry<GracePeriod, ? extends BillingEvent> entry : gracePeriods.entrySet()) {
builder.put(
GRACE_PERIOD_KEY_STRIPPER.apply(entry.getKey()),
((Function<GracePeriod, GracePeriod>)
gracePeriod ->
GracePeriod.create(
gracePeriod.isSunrushAddGracePeriod()
? GracePeriodStatus.SUNRUSH_ADD
: gracePeriod.getType(),
gracePeriod.getExpirationTime(),
gracePeriod.getClientId(),
null))
.apply(entry.getKey()),
BILLING_EVENT_ID_STRIPPER.apply(entry.getValue()));
}
return builder.build();
@ -235,18 +231,17 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
Iterable<GracePeriod> actual,
ImmutableMap<GracePeriod, ? extends BillingEvent> expected) {
Function<GracePeriod, BillingEvent> gracePeriodExpander =
new Function<GracePeriod, BillingEvent>() {
@Override
public BillingEvent apply(GracePeriod gracePeriod) {
assertThat(gracePeriod.hasBillingEvent())
.named("Billing event is present for grace period: " + gracePeriod)
.isTrue();
return ofy().load()
.key(firstNonNull(
gracePeriod.getOneTimeBillingEvent(),
gracePeriod.getRecurringBillingEvent()))
.now();
}};
gracePeriod -> {
assertThat(gracePeriod.hasBillingEvent())
.named("Billing event is present for grace period: " + gracePeriod)
.isTrue();
return ofy()
.load()
.key(
firstNonNull(
gracePeriod.getOneTimeBillingEvent(), gracePeriod.getRecurringBillingEvent()))
.now();
};
assertThat(canonicalizeGracePeriods(Maps.toMap(actual, gracePeriodExpander)))
.isEqualTo(canonicalizeGracePeriods(expected));
}
@ -273,11 +268,7 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
throws Exception {
// To facilitate comparison, remove the ids.
Function<PollMessage, PollMessage> idStripper =
new Function<PollMessage, PollMessage>() {
@Override
public PollMessage apply(PollMessage pollMessage) {
return pollMessage.asBuilder().setId(1L).build();
}};
pollMessage -> pollMessage.asBuilder().setId(1L).build();
// Ordering is irrelevant but duplicates should be considered independently.
assertThat(FluentIterable.from(pollMessages).transform(idStripper))
.containsExactlyElementsIn(FluentIterable.from(expected).transform(idStripper));

View file

@ -14,6 +14,7 @@
package google.registry.flows;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.EppResourceUtils.loadByForeignKey;
import static google.registry.model.ofy.ObjectifyService.ofy;
@ -21,10 +22,9 @@ import static google.registry.model.tmch.ClaimsListShardTest.createTestClaimsLis
import static google.registry.testing.LogsSubject.assertAboutLogs;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Streams;
import com.google.common.testing.TestLogHandler;
import com.googlecode.objectify.Key;
import google.registry.flows.FlowUtils.NotLoggedInException;
@ -139,17 +139,17 @@ public abstract class ResourceFlowTestCase<F extends Flow, R extends EppResource
* Confirms that an EppResourceIndex entity exists in Datastore for a given resource.
*/
protected static <T extends EppResource> void assertEppResourceIndexEntityFor(final T resource) {
ImmutableList<EppResourceIndex> indices = FluentIterable
.from(ofy().load()
.type(EppResourceIndex.class)
.filter("kind", Key.getKind(resource.getClass())))
.filter(new Predicate<EppResourceIndex>() {
@Override
public boolean apply(EppResourceIndex index) {
return Key.create(resource).equals(index.getKey())
&& ofy().load().key(index.getKey()).now().equals(resource);
}})
.toList();
ImmutableList<EppResourceIndex> indices =
Streams.stream(
ofy()
.load()
.type(EppResourceIndex.class)
.filter("kind", Key.getKind(resource.getClass())))
.filter(
index ->
Key.create(resource).equals(index.getKey())
&& ofy().load().key(index.getKey()).now().equals(resource))
.collect(toImmutableList());
assertThat(indices).hasSize(1);
assertThat(indices.get(0).getBucket())
.isEqualTo(EppResourceIndexBucket.getBucketKey(Key.create(resource)));

View file

@ -14,6 +14,7 @@
package google.registry.flows.contact;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.ContactResourceSubject.assertAboutContacts;
import static google.registry.testing.DatastoreHelper.assertNoBillingEvents;
@ -23,8 +24,6 @@ import static google.registry.testing.DatastoreHelper.getOnlyPollMessage;
import static google.registry.testing.DatastoreHelper.getPollMessages;
import static google.registry.testing.DatastoreHelper.persistResource;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import google.registry.flows.ResourceFlowUtils.BadAuthInfoForResourceException;
import google.registry.flows.ResourceFlowUtils.ResourceDoesNotExistException;
import google.registry.flows.ResourceFlowUtils.ResourceNotOwnedException;
@ -92,14 +91,21 @@ public class ContactTransferApproveFlowTest
PollMessage gainingPollMessage = getOnlyPollMessage("NewRegistrar");
assertThat(gainingPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(TransferResponse.class))
gainingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.CLIENT_APPROVED);
PendingActionNotificationResponse panData = Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
.isEqualTo(TransferStatus.CLIENT_APPROVED);
PendingActionNotificationResponse panData =
gainingPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid())
.isEqualTo(Trid.create("transferClient-trid", "transferServer-trid"));
assertThat(panData.getActionResult()).isTrue();

View file

@ -14,6 +14,7 @@
package google.registry.flows.contact;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.ContactResourceSubject.assertAboutContacts;
import static google.registry.testing.DatastoreHelper.assertNoBillingEvents;
@ -22,8 +23,6 @@ import static google.registry.testing.DatastoreHelper.getOnlyPollMessage;
import static google.registry.testing.DatastoreHelper.getPollMessages;
import static google.registry.testing.DatastoreHelper.persistResource;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import google.registry.flows.ResourceFlowUtils.BadAuthInfoForResourceException;
import google.registry.flows.ResourceFlowUtils.ResourceDoesNotExistException;
import google.registry.flows.exceptions.NotPendingTransferException;
@ -86,11 +85,14 @@ public class ContactTransferCancelFlowTest
PollMessage losingPollMessage = getOnlyPollMessage("TheRegistrar");
assertThat(losingPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(losingPollMessage.getResponseData())
.filter(TransferResponse.class))
losingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.CLIENT_CANCELLED);
.isEqualTo(TransferStatus.CLIENT_CANCELLED);
}
private void doFailingTest(String commandFilename) throws Exception {

View file

@ -14,6 +14,7 @@
package google.registry.flows.contact;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.ContactResourceSubject.assertAboutContacts;
import static google.registry.testing.DatastoreHelper.assertNoBillingEvents;
@ -22,8 +23,6 @@ import static google.registry.testing.DatastoreHelper.getOnlyPollMessage;
import static google.registry.testing.DatastoreHelper.getPollMessages;
import static google.registry.testing.DatastoreHelper.persistResource;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import google.registry.flows.ResourceFlowUtils.BadAuthInfoForResourceException;
import google.registry.flows.ResourceFlowUtils.ResourceDoesNotExistException;
import google.registry.flows.ResourceFlowUtils.ResourceNotOwnedException;
@ -90,14 +89,21 @@ public class ContactTransferRejectFlowTest
PollMessage gainingPollMessage = getOnlyPollMessage("NewRegistrar");
assertThat(gainingPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(TransferResponse.class))
gainingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.CLIENT_REJECTED);
PendingActionNotificationResponse panData = Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
.isEqualTo(TransferStatus.CLIENT_REJECTED);
PendingActionNotificationResponse panData =
gainingPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid())
.isEqualTo(Trid.create("transferClient-trid", "transferServer-trid"));
assertThat(panData.getActionResult()).isFalse();

View file

@ -17,6 +17,7 @@ package google.registry.flows.contact;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.config.RegistryConfig.getContactAutomaticTransferLength;
import static google.registry.model.ofy.ObjectifyService.ofy;
@ -116,10 +117,10 @@ public class ContactTransferRequestFlowTest
PollMessage gainingApproveMessage =
getOnlyElement(getPollMessages("NewRegistrar", afterTransfer));
PollMessage losingApproveMessage =
getOnlyElement(
Iterables.filter(
getPollMessages("TheRegistrar", afterTransfer),
not(equalTo(losingRequestMessage))));
getPollMessages("TheRegistrar", afterTransfer)
.stream()
.filter(not(equalTo(losingRequestMessage)))
.collect(onlyElement());
// Check for TransferData server-approve entities containing what we expect: only
// poll messages, the approval notice ones for gaining and losing registrars.

View file

@ -34,6 +34,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DomainApplicationSubject.assertAboutApplications;
import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.Comparator.comparing;
import static org.joda.money.CurrencyUnit.EUR;
import static org.joda.money.CurrencyUnit.USD;
@ -124,7 +125,6 @@ import google.registry.tmch.TmchCertificateAuthority;
import google.registry.tmch.TmchXmlSignature;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
@ -205,11 +205,7 @@ public class DomainApplicationCreateFlowTest
// Check that the domain application was created and persisted with a history entry.
// We want the one with the newest creation time, but lacking an index we need this code.
List<DomainApplication> applications = ofy().load().type(DomainApplication.class).list();
Collections.sort(applications, new Comparator<DomainApplication>() {
@Override
public int compare(DomainApplication a, DomainApplication b) {
return a.getCreationTime().compareTo(b.getCreationTime());
}});
Collections.sort(applications, comparing(DomainApplication::getCreationTime));
assertAboutApplications().that(getLast(applications))
.hasFullyQualifiedDomainName(getUniqueIdFromCommand()).and()
.hasNumEncodedSignedMarks(sunriseApplication ? 1 : 0).and()

View file

@ -26,9 +26,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.TestDataHelper.loadFileWithSubstitutions;
import static google.registry.util.DatastoreServiceUtils.KEY_TO_KIND_FUNCTION;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -56,7 +54,6 @@ import google.registry.model.registry.Registry.TldState;
import google.registry.model.smd.EncodedSignedMark;
import google.registry.testing.AppEngineRule;
import google.registry.testing.EppLoader;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
@ -336,20 +333,20 @@ public class DomainApplicationInfoFlowTest
int numPreviousReads = RequestCapturingAsyncDatastoreService.getReads().size();
doSuccessfulTest("domain_info_sunrise_response.xml", HostsState.HOSTS_EXIST);
// Get all of the keys loaded in the flow, with each distinct load() call as a list of keys.
int numReadsWithContactsOrHosts = FluentIterable
.from(RequestCapturingAsyncDatastoreService.getReads())
.skip(numPreviousReads)
.filter(
new Predicate<List<com.google.appengine.api.datastore.Key>>() {
@Override
public boolean apply(List<com.google.appengine.api.datastore.Key> keys) {
return FluentIterable.from(keys)
.transform(KEY_TO_KIND_FUNCTION)
.anyMatch(Predicates.or(
equalTo(Key.getKind(ContactResource.class)),
equalTo(Key.getKind(HostResource.class))));
}})
.size();
int numReadsWithContactsOrHosts =
(int)
RequestCapturingAsyncDatastoreService.getReads()
.stream()
.skip(numPreviousReads)
.filter(
keys ->
keys.stream()
.map(KEY_TO_KIND_FUNCTION)
.anyMatch(
Predicates.or(
equalTo(Key.getKind(ContactResource.class)),
equalTo(Key.getKind(HostResource.class)))))
.count();
assertThat(numReadsWithContactsOrHosts).isEqualTo(1);
}

View file

@ -14,6 +14,7 @@
package google.registry.flows.domain;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.domain.DomainTransferFlowTestCase.persistWithPendingTransfer;
import static google.registry.model.EppResourceUtils.loadByForeignKey;
@ -46,11 +47,9 @@ import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.googlecode.objectify.Key;
import google.registry.flows.EppRequestSource;
import google.registry.flows.ResourceFlowTestCase;
@ -543,14 +542,21 @@ public class DomainDeleteFlowTest extends ResourceFlowTestCase<DomainDeleteFlow,
PollMessage gainingPollMessage = getOnlyPollMessage("NewRegistrar");
assertThat(gainingPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(TransferResponse.class))
gainingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.SERVER_CANCELLED);
PendingActionNotificationResponse panData = Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
.isEqualTo(TransferStatus.SERVER_CANCELLED);
PendingActionNotificationResponse panData =
gainingPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid())
.isEqualTo(Trid.create("transferClient-trid", "transferServer-trid"));
assertThat(panData.getActionResult()).isFalse();

View file

@ -27,9 +27,7 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.TestDataHelper.loadFileWithSubstitutions;
import static google.registry.util.DatastoreServiceUtils.KEY_TO_KIND_FUNCTION;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
@ -56,7 +54,6 @@ import google.registry.model.eppcommon.StatusValue;
import google.registry.model.host.HostResource;
import google.registry.model.ofy.RequestCapturingAsyncDatastoreService;
import google.registry.testing.AppEngineRule;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
@ -641,20 +638,20 @@ public class DomainInfoFlowTest extends ResourceFlowTestCase<DomainInfoFlow, Dom
int numPreviousReads = RequestCapturingAsyncDatastoreService.getReads().size();
doSuccessfulTest("domain_info_response.xml", false);
// Get all of the keys loaded in the flow, with each distinct load() call as a list of keys.
int numReadsWithContactsOrHosts = FluentIterable
.from(RequestCapturingAsyncDatastoreService.getReads())
.skip(numPreviousReads)
.filter(
new Predicate<List<com.google.appengine.api.datastore.Key>>() {
@Override
public boolean apply(List<com.google.appengine.api.datastore.Key> keys) {
return FluentIterable.from(keys)
.transform(KEY_TO_KIND_FUNCTION)
.anyMatch(Predicates.or(
equalTo(Key.getKind(ContactResource.class)),
equalTo(Key.getKind(HostResource.class))));
}})
.size();
int numReadsWithContactsOrHosts =
(int)
RequestCapturingAsyncDatastoreService.getReads()
.stream()
.skip(numPreviousReads)
.filter(
keys ->
keys.stream()
.map(KEY_TO_KIND_FUNCTION)
.anyMatch(
Predicates.or(
equalTo(Key.getKind(ContactResource.class)),
equalTo(Key.getKind(HostResource.class)))))
.count();
assertThat(numReadsWithContactsOrHosts).isEqualTo(1);
}

View file

@ -14,7 +14,7 @@
package google.registry.flows.domain;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.reporting.DomainTransactionRecord.TransactionReportField.NET_ADDS_4_YR;
@ -40,7 +40,6 @@ import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.googlecode.objectify.Key;
import google.registry.flows.ResourceFlowUtils.BadAuthInfoForResourceException;
@ -49,8 +48,6 @@ import google.registry.flows.ResourceFlowUtils.ResourceNotOwnedException;
import google.registry.flows.domain.DomainFlowUtils.NotAuthorizedForTldException;
import google.registry.flows.exceptions.NotPendingTransferException;
import google.registry.model.billing.BillingEvent;
import google.registry.model.billing.BillingEvent.Cancellation;
import google.registry.model.billing.BillingEvent.Cancellation.Builder;
import google.registry.model.billing.BillingEvent.OneTime;
import google.registry.model.billing.BillingEvent.Reason;
import google.registry.model.billing.BillingEvent.Recurring;
@ -205,15 +202,23 @@ public class DomainTransferApproveFlowTest
assertThat(gainingTransferPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(gainingAutorenewPollMessage.getEventTime())
.isEqualTo(domain.getRegistrationExpirationTime());
DomainTransferResponse transferResponse = getOnlyElement(FluentIterable
.from(gainingTransferPollMessage.getResponseData())
.filter(DomainTransferResponse.class));
DomainTransferResponse transferResponse =
gainingTransferPollMessage
.getResponseData()
.stream()
.filter(DomainTransferResponse.class::isInstance)
.map(DomainTransferResponse.class::cast)
.collect(onlyElement());
assertThat(transferResponse.getTransferStatus()).isEqualTo(TransferStatus.CLIENT_APPROVED);
assertThat(transferResponse.getExtendedRegistrationExpirationTime())
.isEqualTo(domain.getRegistrationExpirationTime());
PendingActionNotificationResponse panData = Iterables.getOnlyElement(FluentIterable
.from(gainingTransferPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
PendingActionNotificationResponse panData =
gainingTransferPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid())
.isEqualTo(Trid.create("transferClient-trid", "transferServer-trid"));
assertThat(panData.getActionResult()).isTrue();
@ -250,12 +255,8 @@ public class DomainTransferApproveFlowTest
domain,
FluentIterable.from(expectedCancellationBillingEvents)
.transform(
new Function<BillingEvent.Cancellation.Builder, BillingEvent>() {
@Override
public Cancellation apply(Builder builder) {
return builder.setParent(historyEntryTransferApproved).build();
}
})
(Function<BillingEvent.Cancellation.Builder, BillingEvent>)
builder -> builder.setParent(historyEntryTransferApproved).build())
.append(
transferBillingEvent,
getLosingClientAutorenewEvent()
@ -292,12 +293,8 @@ public class DomainTransferApproveFlowTest
domain,
FluentIterable.from(expectedCancellationBillingEvents)
.transform(
new Function<BillingEvent.Cancellation.Builder, BillingEvent>() {
@Override
public Cancellation apply(Builder builder) {
return builder.setParent(historyEntryTransferApproved).build();
}
})
(Function<BillingEvent.Cancellation.Builder, BillingEvent>)
builder -> builder.setParent(historyEntryTransferApproved).build())
.append(
getLosingClientAutorenewEvent()
.asBuilder()

View file

@ -14,6 +14,7 @@
package google.registry.flows.domain;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.reporting.DomainTransactionRecord.TransactionReportField.NET_RENEWS_3_YR;
import static google.registry.model.reporting.DomainTransactionRecord.TransactionReportField.TRANSFER_NACKED;
@ -32,9 +33,7 @@ import static google.registry.testing.DomainResourceSubject.assertAboutDomains;
import static google.registry.testing.HistoryEntrySubject.assertAboutHistoryEntries;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import google.registry.flows.ResourceFlowUtils.BadAuthInfoForResourceException;
import google.registry.flows.ResourceFlowUtils.ResourceDoesNotExistException;
import google.registry.flows.ResourceFlowUtils.ResourceNotOwnedException;
@ -116,14 +115,21 @@ public class DomainTransferRejectFlowTest
PollMessage gainingPollMessage = getOnlyPollMessage("NewRegistrar");
assertThat(gainingPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(TransferResponse.class))
gainingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.CLIENT_REJECTED);
PendingActionNotificationResponse panData = Iterables.getOnlyElement(FluentIterable
.from(gainingPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
.isEqualTo(TransferStatus.CLIENT_REJECTED);
PendingActionNotificationResponse panData =
gainingPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid())
.isEqualTo(Trid.create("transferClient-trid", "transferServer-trid"));
assertThat(panData.getActionResult()).isFalse();

View file

@ -14,6 +14,8 @@
package google.registry.flows.domain;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.reporting.DomainTransactionRecord.TransactionReportField.TRANSFER_SUCCESSFUL;
@ -38,7 +40,6 @@ import static org.joda.money.CurrencyUnit.USD;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
@ -66,7 +67,6 @@ import google.registry.flows.exceptions.ResourceStatusProhibitsOperationExceptio
import google.registry.flows.exceptions.TransferPeriodMustBeOneYearException;
import google.registry.flows.exceptions.TransferPeriodZeroAndFeeTransferExtensionException;
import google.registry.model.billing.BillingEvent;
import google.registry.model.billing.BillingEvent.Cancellation.Builder;
import google.registry.model.billing.BillingEvent.Reason;
import google.registry.model.contact.ContactAuthInfo;
import google.registry.model.domain.DomainAuthInfo;
@ -87,6 +87,7 @@ import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferResponse;
import google.registry.model.transfer.TransferStatus;
import java.util.Map;
import java.util.stream.Stream;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
@ -285,14 +286,11 @@ public class DomainTransferRequestFlowTest
.build();
// Construct extra billing events expected by the specific test.
ImmutableList<BillingEvent> extraBillingEvents =
FluentIterable.from(extraExpectedBillingEvents)
.transform(
new Function<BillingEvent.Cancellation.Builder, BillingEvent>() {
@Override
public BillingEvent apply(Builder builder) {
return builder.setParent(historyEntryTransferRequest).build();
}})
.toList();
Stream.of(extraExpectedBillingEvents)
.map(
(Function<BillingEvent.Cancellation.Builder, BillingEvent>)
builder -> builder.setParent(historyEntryTransferRequest).build())
.collect(toImmutableList());
// Assert that the billing events we constructed above actually exist in datastore.
assertBillingEvents(FluentIterable.from(extraBillingEvents)
.append(optionalTransferBillingEvent.asSet())
@ -367,46 +365,57 @@ public class DomainTransferRequestFlowTest
assertThat(transferApprovedPollMessage.getEventTime()).isEqualTo(implicitTransferTime);
assertThat(autorenewPollMessage.getEventTime()).isEqualTo(expectedExpirationTime);
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(transferApprovedPollMessage.getResponseData())
.filter(TransferResponse.class))
transferApprovedPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.SERVER_APPROVED);
PendingActionNotificationResponse panData = Iterables.getOnlyElement(FluentIterable
.from(transferApprovedPollMessage.getResponseData())
.filter(PendingActionNotificationResponse.class));
.isEqualTo(TransferStatus.SERVER_APPROVED);
PendingActionNotificationResponse panData =
transferApprovedPollMessage
.getResponseData()
.stream()
.filter(PendingActionNotificationResponse.class::isInstance)
.map(PendingActionNotificationResponse.class::cast)
.collect(onlyElement());
assertThat(panData.getTrid().getClientTransactionId()).isEqualTo("ABC-12345");
assertThat(panData.getActionResult()).isTrue();
// Two poll messages on the losing registrar's side at the implicit transfer time: a
// transfer pending message, and a transfer approved message (both OneTime messages).
assertThat(getPollMessages("TheRegistrar", implicitTransferTime)).hasSize(2);
PollMessage losingTransferPendingPollMessage = Iterables.getOnlyElement(
FluentIterable.from(getPollMessages("TheRegistrar", clock.nowUtc()))
.filter(
new Predicate<PollMessage>() {
@Override
public boolean apply(PollMessage pollMessage) {
return TransferStatus.PENDING.getMessage().equals(pollMessage.getMsg());
}
}));
PollMessage losingTransferApprovedPollMessage = Iterables.getOnlyElement(FluentIterable
.from(getPollMessages("TheRegistrar", implicitTransferTime))
.filter(Predicates.not(Predicates.equalTo(losingTransferPendingPollMessage))));
PollMessage losingTransferPendingPollMessage =
getPollMessages("TheRegistrar", clock.nowUtc())
.stream()
.filter(pollMessage -> TransferStatus.PENDING.getMessage().equals(pollMessage.getMsg()))
.collect(onlyElement());
PollMessage losingTransferApprovedPollMessage =
getPollMessages("TheRegistrar", implicitTransferTime)
.stream()
.filter(Predicates.not(Predicates.equalTo(losingTransferPendingPollMessage)))
.collect(onlyElement());
assertThat(losingTransferPendingPollMessage.getEventTime()).isEqualTo(clock.nowUtc());
assertThat(losingTransferApprovedPollMessage.getEventTime()).isEqualTo(implicitTransferTime);
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(losingTransferPendingPollMessage.getResponseData())
.filter(TransferResponse.class))
losingTransferPendingPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.PENDING);
.isEqualTo(TransferStatus.PENDING);
assertThat(
Iterables.getOnlyElement(FluentIterable
.from(losingTransferApprovedPollMessage.getResponseData())
.filter(TransferResponse.class))
losingTransferApprovedPollMessage
.getResponseData()
.stream()
.filter(TransferResponse.class::isInstance)
.map(TransferResponse.class::cast)
.collect(onlyElement())
.getTransferStatus())
.isEqualTo(TransferStatus.SERVER_APPROVED);
.isEqualTo(TransferStatus.SERVER_APPROVED);
// Assert that the poll messages show up in the TransferData server approve entities.
assertPollMessagesEqual(

View file

@ -20,8 +20,6 @@ import static com.google.common.truth.Truth.assert_;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static org.joda.time.DateTimeZone.UTC;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.googlecode.objectify.annotation.Id;
@ -157,14 +155,11 @@ public class EntityTestCase {
}
// Descend into persisted ImmutableObject classes, but not anything else.
if (ImmutableObject.class.isAssignableFrom(fieldClass)) {
fields.addAll(FluentIterable
.from(getAllPotentiallyIndexedFieldPaths(fieldClass))
.transform(new Function<String, String>(){
@Override
public String apply(String subfield) {
return field.getName() + "." + subfield;
}})
.toSet());
getAllPotentiallyIndexedFieldPaths(fieldClass)
.stream()
.map(subfield -> field.getName() + "." + subfield)
.distinct()
.forEachOrdered(fields::add);
} else {
fields.add(field.getName());
}

View file

@ -14,6 +14,7 @@
package google.registry.model.domain;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.EppResourceUtils.loadByForeignKey;
@ -26,7 +27,6 @@ import static google.registry.testing.DomainResourceSubject.assertAboutDomains;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
@ -52,6 +52,7 @@ import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferData.TransferServerApproveEntity;
import google.registry.model.transfer.TransferStatus;
import google.registry.testing.ExceptionRule;
import java.util.stream.Stream;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.junit.Before;
@ -363,9 +364,13 @@ public class DomainResourceTest extends EntityTestCase {
ImmutableSet<GracePeriod> renewGracePeriods = ImmutableSet.of(
GracePeriod.create(GracePeriodStatus.RENEW, clock.nowUtc().plusDays(3), "foo", null),
GracePeriod.create(GracePeriodStatus.RENEW, clock.nowUtc().plusDays(1), "baz", null));
domain = domain.asBuilder()
.setGracePeriods(FluentIterable.from(addGracePeriods).append(renewGracePeriods).toSet())
.build();
domain =
domain
.asBuilder()
.setGracePeriods(
Stream.concat(addGracePeriods.stream(), renewGracePeriods.stream())
.collect(toImmutableSet()))
.build();
assertThat(domain.getGracePeriodsOfType(GracePeriodStatus.ADD)).isEqualTo(addGracePeriods);
assertThat(domain.getGracePeriodsOfType(GracePeriodStatus.RENEW)).isEqualTo(renewGracePeriods);
assertThat(domain.getGracePeriodsOfType(GracePeriodStatus.TRANSFER)).isEmpty();

View file

@ -95,9 +95,5 @@ public class PremiumListTest {
/** Gets the label of a premium list entry. */
public static final Function<Key<PremiumListEntry>, String> GET_ENTRY_NAME_FUNCTION =
new Function<Key<PremiumListEntry>, String>() {
@Override
public String apply(final Key<PremiumListEntry> input) {
return input.getName();
}};
Key::getName;
}

View file

@ -551,10 +551,5 @@ public class ReservedListTest {
}
/** Gets the name of a reserved list. */
public static final Function<Key<ReservedList>, String> GET_NAME_FUNCTION =
new Function<Key<ReservedList>, String>() {
@Override
public String apply(final Key<ReservedList> input) {
return input.getName();
}};
public static final Function<Key<ReservedList>, String> GET_NAME_FUNCTION = Key::getName;
}

View file

@ -17,7 +17,6 @@ package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -76,12 +75,7 @@ public class MetricRegistryImplTest {
"test_description",
"test_valuedisplayname",
ImmutableSet.of(label),
new Supplier<ImmutableMap<ImmutableList<String>, Long>>() {
@Override
public ImmutableMap<ImmutableList<String>, Long> get() {
return ImmutableMap.of(ImmutableList.of("foo"), 1L);
}
},
() -> ImmutableMap.of(ImmutableList.of("foo"), 1L),
Long.class);
assertThat(testGauge.getValueClass()).isSameAs(Long.class);

View file

@ -22,7 +22,6 @@ import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.monitoring.v3.Monitoring;
import com.google.api.services.monitoring.v3.MonitoringScopes;
import com.google.api.services.monitoring.v3.model.MonitoredResource;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -130,12 +129,7 @@ public final class SheepCounterExample {
"Quality of the sleep.",
"Quality",
ImmutableSet.<LabelDescriptor>of(),
new Supplier<ImmutableMap<ImmutableList<String>, Double>>() {
@Override
public ImmutableMap<ImmutableList<String>, Double> get() {
return ImmutableMap.of(ImmutableList.<String>of(), new Random().nextDouble());
}
},
() -> ImmutableMap.of(ImmutableList.<String>of(), new Random().nextDouble()),
Double.class);
/**
@ -210,13 +204,10 @@ public final class SheepCounterExample {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
new Runnable() {
@Override
public void run() {
reporter.stopAsync().awaitTerminated();
// Allow the LogManager to cleanup the loggers.
DelayedShutdownLogManager.resetFinally();
}
() -> {
reporter.stopAsync().awaitTerminated();
// Allow the LogManager to cleanup the loggers.
DelayedShutdownLogManager.resetFinally();
}));
System.err.println("Send SIGINT (Ctrl+C) to stop sleeping.");

View file

@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTld;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@ -88,14 +87,7 @@ public class ContactResourceToXjcConverterTest {
// o One or more <status> elements that describe the status of the
// contact object.
assertThat(
FluentIterable
.from(bean.getStatuses())
.transform(new Function<XjcContactStatusType, XjcContactStatusValueType>() {
@Override
public XjcContactStatusValueType apply(XjcContactStatusType status) {
return status.getS();
}}))
assertThat(FluentIterable.from(bean.getStatuses()).transform(XjcContactStatusType::getS))
.containsExactly(
XjcContactStatusValueType.CLIENT_DELETE_PROHIBITED,
XjcContactStatusValueType.SERVER_UPDATE_PROHIBITED);

View file

@ -26,7 +26,6 @@ import static google.registry.xjc.rgp.XjcRgpStatusValueType.TRANSFER_PERIOD;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@ -59,7 +58,6 @@ import google.registry.model.transfer.TransferStatus;
import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock;
import google.registry.util.Idn;
import google.registry.xjc.domain.XjcDomainContactType;
import google.registry.xjc.domain.XjcDomainStatusType;
import google.registry.xjc.domain.XjcDomainStatusValueType;
import google.registry.xjc.rde.XjcRdeContentsType;
@ -69,7 +67,6 @@ import google.registry.xjc.rde.XjcRdeMenuType;
import google.registry.xjc.rdedomain.XjcRdeDomain;
import google.registry.xjc.rdedomain.XjcRdeDomainElement;
import google.registry.xjc.rgp.XjcRgpStatusType;
import google.registry.xjc.rgp.XjcRgpStatusValueType;
import google.registry.xjc.secdns.XjcSecdnsDsDataType;
import java.io.ByteArrayOutputStream;
import org.joda.money.Money;
@ -109,13 +106,11 @@ public class DomainResourceToXjcConverterTest {
assertThat(bean.getClID()).isEqualTo("GetTheeBack");
assertThat(FluentIterable
.from(bean.getContacts())
.transform(new Function<XjcDomainContactType, String>() {
@Override
public String apply(XjcDomainContactType input) {
return String.format("%s %s", input.getType().toString(), input.getValue());
}})).containsExactly("ADMIN 5372808-IRL", "TECH 5372808-TRL");
assertThat(
FluentIterable.from(bean.getContacts())
.transform(
input -> String.format("%s %s", input.getType().toString(), input.getValue())))
.containsExactly("ADMIN 5372808-IRL", "TECH 5372808-TRL");
assertThat(bean.getCrDate()).isEqualTo(DateTime.parse("1900-01-01T00:00:00Z"));
@ -150,13 +145,8 @@ public class DomainResourceToXjcConverterTest {
// "pendingDelete" sub-statuses, including "redemptionPeriod",
// "pendingRestore", and "pendingDelete", that a domain name can be
// in as a result of grace period processing as specified in [RFC3915].
assertThat(FluentIterable
.from(bean.getRgpStatuses())
.transform(new Function<XjcRgpStatusType, XjcRgpStatusValueType>() {
@Override
public XjcRgpStatusValueType apply(XjcRgpStatusType status) {
return status.getS();
}})).containsExactly(TRANSFER_PERIOD, RENEW_PERIOD);
assertThat(FluentIterable.from(bean.getRgpStatuses()).transform(XjcRgpStatusType::getS))
.containsExactly(TRANSFER_PERIOD, RENEW_PERIOD);
assertThat(bean.getSecDNS()).named("secdns").isNotNull();
assertThat(bean.getSecDNS().getDsDatas()).named("secdns dsdata").isNotNull();
@ -170,19 +160,12 @@ public class DomainResourceToXjcConverterTest {
assertThat(bean.getRoid()).isEqualTo("2-Q9JYB4C");
assertThat(
FluentIterable
.from(bean.getStatuses())
.transform(new Function<XjcDomainStatusType, XjcDomainStatusValueType>() {
@Override
public XjcDomainStatusValueType apply(XjcDomainStatusType status) {
return status.getS();
}})
).containsExactly(
XjcDomainStatusValueType.CLIENT_DELETE_PROHIBITED,
XjcDomainStatusValueType.CLIENT_RENEW_PROHIBITED,
XjcDomainStatusValueType.CLIENT_TRANSFER_PROHIBITED,
XjcDomainStatusValueType.SERVER_UPDATE_PROHIBITED);
assertThat(FluentIterable.from(bean.getStatuses()).transform(XjcDomainStatusType::getS))
.containsExactly(
XjcDomainStatusValueType.CLIENT_DELETE_PROHIBITED,
XjcDomainStatusValueType.CLIENT_RENEW_PROHIBITED,
XjcDomainStatusValueType.CLIENT_TRANSFER_PROHIBITED,
XjcDomainStatusValueType.SERVER_UPDATE_PROHIBITED);
assertThat(bean.getTrDate()).isEqualTo(DateTime.parse("1910-01-01T00:00:00Z"));

View file

@ -14,6 +14,7 @@
package google.registry.rde;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.common.Cursor.CursorType.BRDA;
import static google.registry.model.common.Cursor.CursorType.RDE_STAGING;
@ -39,9 +40,7 @@ import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.appengine.tools.cloudstorage.ListItem;
import com.google.appengine.tools.cloudstorage.ListOptions;
import com.google.appengine.tools.cloudstorage.ListResult;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -782,15 +781,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
ListResult listResult =
gcsService.list("rde-bucket", new ListOptions.Builder().setPrefix("manual/test").build());
ImmutableSet<String> filenames =
FluentIterable.from(ImmutableList.copyOf(listResult))
.transform(
new Function<ListItem, String>() {
@Override
public String apply(ListItem listItem) {
return listItem.getName();
}
})
.toSet();
ImmutableList.copyOf(listResult).stream().map(ListItem::getName).collect(toImmutableSet());
for (String tld : tlds) {
assertThat(filenames)
.containsAllOf(

View file

@ -14,6 +14,7 @@
package google.registry.rde.imports;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld;
@ -28,10 +29,9 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.common.io.ByteSource;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
@ -375,16 +375,14 @@ public class RdeImportUtilsTest extends ShardableTestCase {
/** Confirms that an EppResourceIndex entity exists in Datastore for a given resource. */
private static <T extends EppResource> void assertEppResourceIndexEntityFor(final T resource) {
ImmutableList<EppResourceIndex> indices = FluentIterable
.from(ofy().load()
.type(EppResourceIndex.class)
.filter("kind", Key.getKind(resource.getClass())))
.filter(new Predicate<EppResourceIndex>() {
@Override
public boolean apply(EppResourceIndex index) {
return ofy().load().key(index.getKey()).now().equals(resource);
}})
.toList();
ImmutableList<EppResourceIndex> indices =
Streams.stream(
ofy()
.load()
.type(EppResourceIndex.class)
.filter("kind", Key.getKind(resource.getClass())))
.filter(index -> ofy().load().key(index.getKey()).now().equals(resource))
.collect(toImmutableList());
assertThat(indices).hasSize(1);
assertThat(indices.get(0).getBucket())
.isEqualTo(EppResourceIndexBucket.getBucketKey(Key.create(resource)));

View file

@ -80,10 +80,6 @@ public final class JsonHttpTestUtils {
*/
public static Supplier<Map<String, Object>> createJsonResponseSupplier(
final StringWriter writer) {
return memoize(new Supplier<Map<String, Object>>() {
@Override
public Map<String, Object> get() {
return getJsonResponse(writer);
}});
return memoize(() -> getJsonResponse(writer));
}
}

View file

@ -14,7 +14,6 @@
package google.registry.server;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
@ -133,9 +132,8 @@ public final class StaticResourceServlet extends HttpServlet {
return Optional.absent();
}
rsp.setContentType(
firstNonNull(
MIMES_BY_EXTENSION.get(getExtension(file.getFileName().toString())),
DEFAULT_MIME_TYPE)
MIMES_BY_EXTENSION
.getOrDefault(getExtension(file.getFileName().toString()), DEFAULT_MIME_TYPE)
.toString());
rsp.setContentLength(Ints.checkedCast(Files.size(file)));
return Optional.of(file);

View file

@ -29,11 +29,9 @@ import java.net.URL;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.servlet.Filter;
import javax.servlet.http.HttpServlet;
import org.mortbay.jetty.Connector;
@ -129,15 +127,11 @@ public final class TestServer {
/** Stops the HTTP server. */
public void stop() {
try {
SimpleTimeLimiter.create(newCachedThreadPool())
Void unusedReturnValue = SimpleTimeLimiter.create(newCachedThreadPool())
.callWithTimeout(
new Callable<Void>() {
@Nullable
@Override
public Void call() throws Exception {
server.stop();
return null;
}
() -> {
server.stop();
return null;
},
SHUTDOWN_TIMEOUT_MS,
TimeUnit.MILLISECONDS);

View file

@ -21,9 +21,7 @@ import com.google.common.util.concurrent.SimpleTimeLimiter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
final class UrlChecker {
@ -33,19 +31,19 @@ final class UrlChecker {
/** Probes {@code url} until it becomes available. */
static void waitUntilAvailable(final URL url, int timeoutMs) {
try {
SimpleTimeLimiter.create(newCachedThreadPool()).callWithTimeout(new Callable<Void>() {
@Nullable
@Override
public Void call() throws InterruptedException, IOException {
int exponentialBackoffMs = 1;
while (true) {
if (isAvailable(url)) {
return null;
}
Thread.sleep(exponentialBackoffMs *= 2);
}
}
}, timeoutMs, TimeUnit.MILLISECONDS);
Void unusedReturnValue = SimpleTimeLimiter.create(newCachedThreadPool())
.callWithTimeout(
() -> {
int exponentialBackoffMs = 1;
while (true) {
if (isAvailable(url)) {
return null;
}
Thread.sleep(exponentialBackoffMs *= 2);
}
},
timeoutMs,
TimeUnit.MILLISECONDS);
} catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);

View file

@ -17,7 +17,9 @@ package google.registry.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Suppliers.memoize;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.toArray;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.config.RegistryConfig.getContactAndHostRoidSuffix;
@ -42,7 +44,6 @@ import static org.joda.money.CurrencyUnit.USD;
import com.google.common.base.Ascii;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.collect.FluentIterable;
@ -51,6 +52,7 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.common.net.InetAddresses;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
@ -108,14 +110,14 @@ import org.joda.time.DateTime;
public class DatastoreHelper {
private static final Supplier<String[]> DEFAULT_PREMIUM_LIST_CONTENTS =
memoize(new Supplier<String[]>() {
@Override
public String[] get() {
return toArray(
Splitter.on('\n').split(
readResourceUtf8(DatastoreHelper.class, "default_premium_list_testdata.csv")),
String.class);
}});
memoize(
() ->
toArray(
Splitter.on('\n')
.split(
readResourceUtf8(
DatastoreHelper.class, "default_premium_list_testdata.csv")),
String.class));
public static HostResource newHostResource(String hostName) {
return new HostResource.Builder()
@ -689,12 +691,7 @@ public class DatastoreHelper {
/** Helper to effectively erase the billing event ID to facilitate comparison. */
public static final Function<BillingEvent, BillingEvent> BILLING_EVENT_ID_STRIPPER =
new Function<BillingEvent, BillingEvent>() {
@Override
public BillingEvent apply(BillingEvent billingEvent) {
// Can't use id=0 because that causes the builder to generate a new id.
return billingEvent.asBuilder().setId(1L).build();
}};
billingEvent -> billingEvent.asBuilder().setId(1L).build();
/** Assert that the actual poll message matches the expected one, ignoring IDs. */
public static void assertPollMessagesEqual(PollMessage actual, PollMessage expected) {
@ -718,48 +715,43 @@ public class DatastoreHelper {
/** Helper to effectively erase the poll message ID to facilitate comparison. */
public static final Function<PollMessage, PollMessage> POLL_MESSAGE_ID_STRIPPER =
new Function<PollMessage, PollMessage>() {
@Override
public PollMessage apply(PollMessage pollMessage) {
// Can't use id=0 because that causes the builder to generate a new id.
return pollMessage.asBuilder().setId(1L).build();
}};
pollMessage -> pollMessage.asBuilder().setId(1L).build();
public static ImmutableList<PollMessage> getPollMessages() {
return FluentIterable.from(ofy().load().type(PollMessage.class)).toList();
return Streams.stream(ofy().load().type(PollMessage.class)).collect(toImmutableList());
}
public static ImmutableList<PollMessage> getPollMessages(String clientId) {
return FluentIterable
.from(ofy().load().type(PollMessage.class).filter("clientId", clientId))
.toList();
return Streams.stream(ofy().load().type(PollMessage.class).filter("clientId", clientId))
.collect(toImmutableList());
}
public static ImmutableList<PollMessage> getPollMessages(EppResource resource) {
return FluentIterable.from(ofy().load().type(PollMessage.class).ancestor(resource)).toList();
return Streams.stream(ofy().load().type(PollMessage.class).ancestor(resource))
.collect(toImmutableList());
}
public static ImmutableList<PollMessage> getPollMessages(String clientId, DateTime now) {
return FluentIterable
.from(ofy()
.load()
.type(PollMessage.class)
.filter("clientId", clientId)
.filter("eventTime <=", now.toDate()))
.toList();
return Streams.stream(
ofy()
.load()
.type(PollMessage.class)
.filter("clientId", clientId)
.filter("eventTime <=", now.toDate()))
.collect(toImmutableList());
}
/** Gets all PollMessages associated with the given EppResource. */
public static ImmutableList<PollMessage> getPollMessages(
EppResource resource, String clientId, DateTime now) {
return FluentIterable
.from(ofy()
.load()
.type(PollMessage.class)
.ancestor(resource)
.filter("clientId", clientId)
.filter("eventTime <=", now.toDate()))
.toList();
return Streams.stream(
ofy()
.load()
.type(PollMessage.class)
.ancestor(resource)
.filter("clientId", clientId)
.filter("eventTime <=", now.toDate()))
.collect(toImmutableList());
}
public static PollMessage getOnlyPollMessage(String clientId) {
@ -774,7 +766,11 @@ public class DatastoreHelper {
String clientId,
DateTime now,
Class<? extends PollMessage> subType) {
return Iterables.getOnlyElement(Iterables.filter(getPollMessages(clientId, now), subType));
return getPollMessages(clientId, now)
.stream()
.filter(subType::isInstance)
.map(subType::cast)
.collect(onlyElement());
}
public static PollMessage getOnlyPollMessage(
@ -782,8 +778,11 @@ public class DatastoreHelper {
String clientId,
DateTime now,
Class<? extends PollMessage> subType) {
return Iterables.getOnlyElement(
Iterables.filter(getPollMessages(resource, clientId, now), subType));
return getPollMessages(resource, clientId, now)
.stream()
.filter(subType::isInstance)
.map(subType::cast)
.collect(onlyElement());
}
/** Returns a newly allocated, globally unique domain repoId of the format HEX-TLD. */
@ -948,13 +947,10 @@ public class DatastoreHelper {
*/
public static List<HistoryEntry> getHistoryEntriesOfType(
EppResource resource, final HistoryEntry.Type type) {
return FluentIterable.from(getHistoryEntries(resource))
.filter(new Predicate<HistoryEntry>() {
@Override
public boolean apply(HistoryEntry entry) {
return entry.getType() == type;
}})
.toList();
return getHistoryEntries(resource)
.stream()
.filter(entry -> entry.getType() == type)
.collect(toImmutableList());
}
/**

View file

@ -64,9 +64,8 @@ public final class SystemPropertyRule extends ExternalResource {
* @see java.lang.System#setProperty(String, String)
*/
public SystemPropertyRule override(String key, @Nullable String value) {
if (!originals.containsKey(key)) {
originals.put(key, new Property(key, Optional.fromNullable(System.getProperty(key))));
}
originals.computeIfAbsent(
key, k -> new Property(k, Optional.fromNullable(System.getProperty(k))));
Property property = new Property(key, Optional.fromNullable(value));
if (isRunning) {
property.set();

View file

@ -26,6 +26,7 @@ import static com.google.common.truth.Truth.assert_;
import static google.registry.util.DiffUtils.prettyPrintEntityDeepDiff;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.joining;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo.HeaderWrapper;
@ -35,7 +36,6 @@ import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
@ -178,12 +178,7 @@ public class TaskQueueHelper {
.join(
Maps.transformValues(
expected.toMap(),
new Function<Object, String>() {
@Override
public String apply(Object input) {
return "\t" + String.valueOf(input).replaceAll("\n", "\n\t");
}
}));
input -> "\t" + String.valueOf(input).replaceAll("\n", "\n\t")));
}
}
@ -208,12 +203,7 @@ public class TaskQueueHelper {
/** Ensures that the tasks in the named queue are exactly those with the expected names. */
public static void assertTasksEnqueued(String queueName, String... expectedTaskNames)
throws Exception {
Function<TaskStateInfo, String> nameGetter = new Function<TaskStateInfo, String>() {
@Nonnull
@Override
public String apply(@Nonnull TaskStateInfo taskStateInfo) {
return taskStateInfo.getTaskName();
}};
Function<TaskStateInfo, String> nameGetter = TaskStateInfo::getTaskName;
assertTasksEnqueuedWithProperty(queueName, nameGetter, expectedTaskNames);
}
@ -249,21 +239,21 @@ public class TaskQueueHelper {
taskInfos.remove(Iterables.find(taskInfos, taskMatcher));
} catch (NoSuchElementException e) {
final Map<String, Object> taskMatcherMap = taskMatcher.expected.toMap();
assert_().fail(
"Task not found in queue %s:\n\n%s\n\nPotential candidate match diffs:\n\n%s",
queueName,
taskMatcher,
FluentIterable.from(taskInfos)
.transform(new Function<TaskStateInfo, String>() {
@Override
public String apply(TaskStateInfo input) {
return prettyPrintEntityDeepDiff(
taskMatcherMap,
Maps.filterKeys(
new MatchableTaskInfo(input).toMap(),
in(taskMatcherMap.keySet())));
}})
.join(Joiner.on('\n')));
assert_()
.fail(
"Task not found in queue %s:\n\n%s\n\nPotential candidate match diffs:\n\n%s",
queueName,
taskMatcher,
taskInfos
.stream()
.map(
input ->
prettyPrintEntityDeepDiff(
taskMatcherMap,
Maps.filterKeys(
new MatchableTaskInfo(input).toMap(),
in(taskMatcherMap.keySet()))))
.collect(joining("\n")));
}
}
}
@ -294,12 +284,7 @@ public class TaskQueueHelper {
public static void assertDnsTasksEnqueued(String... expectedTaskTargetNames) throws Exception {
assertTasksEnqueuedWithProperty(
DnsConstants.DNS_PULL_QUEUE_NAME,
new Function<TaskStateInfo, String>() {
@Nonnull
@Override
public String apply(@Nonnull TaskStateInfo taskStateInfo) {
return getParamFromTaskInfo(taskStateInfo, DnsConstants.DNS_TARGET_NAME_PARAM);
}},
taskStateInfo -> getParamFromTaskInfo(taskStateInfo, DnsConstants.DNS_TARGET_NAME_PARAM),
expectedTaskTargetNames);
}

View file

@ -14,7 +14,6 @@
package google.registry.testing;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.testing.TestLogHandler;
import java.util.logging.LogRecord;
@ -37,12 +36,6 @@ public final class TestLogHandlerUtils {
public static LogRecord findFirstLogRecordWithMessagePrefix(
TestLogHandler handler, final String prefix) {
return Iterables.find(
handler.getStoredLogRecords(),
new Predicate<LogRecord>() {
@Override
public boolean apply(LogRecord logRecord) {
return logRecord.getMessage().startsWith(prefix);
}
});
handler.getStoredLogRecords(), logRecord -> logRecord.getMessage().startsWith(prefix));
}
}

View file

@ -20,7 +20,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.persistActiveContact;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.common.base.Function;
import com.googlecode.objectify.Key;
import google.registry.model.ImmutableObject;
import google.registry.model.contact.ContactResource;
@ -46,12 +45,7 @@ public class ResaveEntitiesCommandTest extends CommandTestCase<ResaveEntitiesCom
Iterable<ImmutableObject> savedEntities =
transform(
ofy().load().type(CommitLogMutation.class).list(),
new Function<CommitLogMutation, ImmutableObject>() {
@Override
public ImmutableObject apply(CommitLogMutation mutation) {
return ofy().load().fromEntity(mutation.getEntity());
}
});
mutation -> ofy().load().fromEntity(mutation.getEntity()));
// Reload the contacts before asserting, since their update times will have changed.
ofy().clearSessionCache();
assertThat(savedEntities)

View file

@ -21,7 +21,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import com.google.common.base.Function;
import google.registry.model.ImmutableObject;
import google.registry.model.ofy.CommitLogManifest;
import google.registry.model.ofy.CommitLogMutation;
@ -62,12 +61,7 @@ public class ResaveEnvironmentEntitiesCommandTest
Iterable<ImmutableObject> savedEntities =
transform(
ofy().load().type(CommitLogMutation.class).list(),
new Function<CommitLogMutation, ImmutableObject>() {
@Override
public ImmutableObject apply(CommitLogMutation mutation) {
return ofy().load().fromEntity(mutation.getEntity());
}
});
mutation -> ofy().load().fromEntity(mutation.getEntity()));
assertThat(savedEntities)
.containsExactly(
// The Registrars and RegistrarContacts are created by AppEngineRule.

View file

@ -30,7 +30,6 @@ import static google.registry.testing.HistoryEntrySubject.assertAboutHistoryEntr
import static org.joda.time.DateTimeZone.UTC;
import static org.junit.Assert.fail;
import com.google.common.collect.FluentIterable;
import google.registry.model.domain.DomainApplication;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.eppcommon.Trid;
@ -123,8 +122,9 @@ public class UpdateApplicationStatusCommandTest
PollMessage pollMessage = getFirstPollMessage();
assertThat(pollMessage.getMsg()).isEqualTo("Application rejected");
DomainPendingActionNotificationResponse response = (DomainPendingActionNotificationResponse)
FluentIterable.from(pollMessage.getResponseData()).first().get();
DomainPendingActionNotificationResponse response =
(DomainPendingActionNotificationResponse)
pollMessage.getResponseData().stream().findFirst().get();
assertThat(response.getTrid()).isEqualTo(creationTrid);
assertThat(response.getActionResult()).isFalse();
}
@ -161,8 +161,9 @@ public class UpdateApplicationStatusCommandTest
PollMessage pollMessage = getFirstPollMessage();
assertThat(pollMessage.getMsg()).isEqualTo("Application allocated");
DomainPendingActionNotificationResponse response = (DomainPendingActionNotificationResponse)
FluentIterable.from(pollMessage.getResponseData()).first().get();
DomainPendingActionNotificationResponse response =
(DomainPendingActionNotificationResponse)
pollMessage.getResponseData().stream().findFirst().get();
assertThat(response.getTrid()).isEqualTo(creationTrid);
assertThat(response.getActionResult()).isTrue();
}
@ -225,8 +226,9 @@ public class UpdateApplicationStatusCommandTest
assertThat(getPollMessageCount()).isEqualTo(1);
PollMessage pollMessage = getFirstPollMessage();
DomainPendingActionNotificationResponse response = (DomainPendingActionNotificationResponse)
FluentIterable.from(pollMessage.getResponseData()).first().get();
DomainPendingActionNotificationResponse response =
(DomainPendingActionNotificationResponse)
pollMessage.getResponseData().stream().findFirst().get();
assertThat(response.getTrid()).isEqualTo(Trid.create("ABC123", "server-trid"));
}

View file

@ -16,6 +16,7 @@ package google.registry.tools.server;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
@ -27,10 +28,9 @@ import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.Arrays.asList;
import com.google.appengine.api.datastore.Entity;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Streams;
import google.registry.model.ImmutableObject;
import google.registry.model.ofy.CommitLogBucket;
import google.registry.model.ofy.CommitLogCheckpoint;
@ -81,13 +81,10 @@ public class KillAllCommitLogsActionTest extends MapreduceTestCase<KillAllCommit
for (Class<?> clazz : AFFECTED_TYPES) {
assertThat(ofy().load().type(clazz)).named("entities of type " + clazz).isNotEmpty();
}
ImmutableList<?> otherStuff = FluentIterable.from(ofy().load())
.filter(new Predicate<Object>() {
@Override
public boolean apply(Object obj) {
return !AFFECTED_TYPES.contains(obj.getClass());
}})
.toList();
ImmutableList<?> otherStuff =
Streams.stream(ofy().load())
.filter(obj -> !AFFECTED_TYPES.contains(obj.getClass()))
.collect(toImmutableList());
assertThat(otherStuff).isNotEmpty();
runMapreduce();
for (Class<?> clazz : AFFECTED_TYPES) {

View file

@ -17,6 +17,7 @@ package google.registry.tools.server;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Multimaps.filterKeys;
import static com.google.common.collect.Sets.difference;
import static com.google.common.truth.Truth.assertThat;
@ -32,7 +33,6 @@ import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.Arrays.asList;
import com.google.appengine.api.datastore.Entity;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@ -53,6 +53,7 @@ import google.registry.model.poll.PollMessage;
import google.registry.model.reporting.HistoryEntry;
import google.registry.testing.FakeResponse;
import google.registry.testing.mapreduce.MapreduceTestCase;
import java.util.stream.Stream;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.Test;
@ -64,22 +65,21 @@ import org.junit.runners.JUnit4;
public class KillAllEppResourcesActionTest extends MapreduceTestCase<KillAllEppResourcesAction> {
static final ImmutableSet<String> AFFECTED_KINDS =
FluentIterable.from(
asList(
EppResourceIndex.class,
ForeignKeyContactIndex.class,
ForeignKeyDomainIndex.class,
ForeignKeyHostIndex.class,
DomainApplicationIndex.class,
DomainBase.class,
ContactResource.class,
HostResource.class,
HistoryEntry.class,
PollMessage.class,
BillingEvent.OneTime.class,
BillingEvent.Recurring.class))
.transform(CLASS_TO_KIND_FUNCTION)
.toSet();
Stream.of(
EppResourceIndex.class,
ForeignKeyContactIndex.class,
ForeignKeyDomainIndex.class,
ForeignKeyHostIndex.class,
DomainApplicationIndex.class,
DomainBase.class,
ContactResource.class,
HostResource.class,
HistoryEntry.class,
PollMessage.class,
BillingEvent.OneTime.class,
BillingEvent.Recurring.class)
.map(CLASS_TO_KIND_FUNCTION)
.collect(toImmutableSet());
private void runMapreduce() throws Exception {
action = new KillAllEppResourcesAction();

View file

@ -216,14 +216,7 @@ public class FormFieldTest {
public void testCast() {
assertThat(
FormField.named("lol")
.transform(
Integer.class,
new Function<String, Integer>() {
@Override
public Integer apply(String input) {
return Integer.parseInt(input);
}
})
.transform(Integer.class, Integer::parseInt)
.build()
.convert("123"))
.hasValue(123);
@ -233,14 +226,7 @@ public class FormFieldTest {
public void testCast_twice() {
assertThat(
FormField.named("lol")
.transform(
Object.class,
new Function<String, Object>() {
@Override
public Integer apply(String input) {
return Integer.parseInt(input);
}
})
.transform(Object.class, Integer::parseInt)
.transform(String.class, Functions.toStringFunction())
.build()
.convert("123"))
@ -384,20 +370,13 @@ public class FormFieldTest {
.propagate(0)
.propagate("lol")));
FormField.mapNamed("lol")
.transform(String.class, new Function<Map<String, ?>, String>() {
@Override
public String apply(Map<String, ?> input) {
return FormField.named("cat")
.emptyToNull()
.required()
.build()
.extractUntyped(input)
.get();
}})
.transform(
String.class,
input ->
FormField.named("cat").emptyToNull().required().build().extractUntyped(input).get())
.asList()
.build()
.convert(ImmutableList.<Map<String, ?>>of(
ImmutableMap.of("cat", "")));
.convert(ImmutableList.<Map<String, ?>>of(ImmutableMap.of("cat", "")));
}
@Test
@ -410,24 +389,21 @@ public class FormFieldTest {
@Test
public void testAsMatrix() {
assertThat(
FormField.named("lol", Integer.class)
.transform(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input * 2;
}})
.asList()
.asList()
.build()
.convert(Lists.cartesianProduct(ImmutableList.of(
ImmutableList.of(1, 2),
ImmutableList.of(3, 4))))
.get())
.containsExactly(
ImmutableList.of(2, 6),
ImmutableList.of(2, 8),
ImmutableList.of(4, 6),
ImmutableList.of(4, 8)).inOrder();
FormField.named("lol", Integer.class)
.transform(input -> input * 2)
.asList()
.asList()
.build()
.convert(
Lists.cartesianProduct(
ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of(3, 4))))
.get())
.containsExactly(
ImmutableList.of(2, 6),
ImmutableList.of(2, 8),
ImmutableList.of(4, 6),
ImmutableList.of(4, 8))
.inOrder();
}
@Test

View file

@ -44,21 +44,19 @@ public class ConcurrentTest {
@Test
public void testTransform_addIntegers() throws Exception {
assertThat(Concurrent.transform(ImmutableList.of(1, 2, 3), new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input + 1;
}})).containsExactly(2, 3, 4).inOrder();
assertThat(Concurrent.transform(ImmutableList.of(1, 2, 3), input -> input + 1))
.containsExactly(2, 3, 4)
.inOrder();
}
@Test
public void testTransform_throwsException_isSinglyWrappedByUee() throws Exception {
try {
Concurrent.transform(ImmutableList.of(1, 2, 3), new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
throw new RuntimeException("hello");
}});
Concurrent.transform(
ImmutableList.of(1, 2, 3),
input -> {
throw new RuntimeException("hello");
});
fail("Didn't throw!");
} catch (UncheckedExecutionException e) {
// We can't use ExpectedException because root cause must be one level of indirection away.