diff --git a/java/google/registry/backup/CommitLogCheckpointStrategy.java b/java/google/registry/backup/CommitLogCheckpointStrategy.java index eda8638b7..e3e1a97a9 100644 --- a/java/google/registry/backup/CommitLogCheckpointStrategy.java +++ b/java/google/registry/backup/CommitLogCheckpointStrategy.java @@ -21,7 +21,6 @@ import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.earliestOf; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.googlecode.objectify.Key; import com.googlecode.objectify.Work; @@ -167,10 +166,7 @@ class CommitLogCheckpointStrategy { ImmutableMap computeBucketCheckpointTimes( ImmutableMap firstPassTimes, final DateTime threshold) { - return ImmutableMap.copyOf(transformValues(firstPassTimes, new Function() { - @Override - public DateTime apply(DateTime firstPassTime) { - return earliestOf(firstPassTime, threshold); - }})); + return ImmutableMap.copyOf( + transformValues(firstPassTimes, firstPassTime -> earliestOf(firstPassTime, threshold))); } } diff --git a/java/google/registry/backup/ExportCommitLogDiffAction.java b/java/google/registry/backup/ExportCommitLogDiffAction.java index 147abfe76..9163e3f1a 100644 --- a/java/google/registry/backup/ExportCommitLogDiffAction.java +++ b/java/google/registry/backup/ExportCommitLogDiffAction.java @@ -16,6 +16,7 @@ package google.registry.backup; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verifyNotNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Lists.partition; import static google.registry.backup.BackupUtils.GcsMetadataKeys.LOWER_BOUND_CHECKPOINT; @@ -29,15 +30,14 @@ import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.FormattingLogger.getLoggerForCallerClass; import static java.nio.channels.Channels.newOutputStream; import static java.util.Arrays.asList; +import static java.util.Comparator.comparingLong; 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.ComparisonChain; -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.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.model.ImmutableObject; @@ -52,7 +52,6 @@ import google.registry.util.FormattingLogger; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; -import java.util.Comparator; import java.util.List; import java.util.Map; import javax.annotation.Nullable; @@ -152,21 +151,17 @@ public final class ExportCommitLogDiffAction implements Runnable { // transaction-consistent by virtue of our checkpoint strategy and our customized Ofy; see // CommitLogCheckpointStrategy for the proof. We break ties by sorting on bucket ID to ensure // a deterministic order. - return FluentIterable.from(upperCheckpoint.getBucketTimestamps().keySet()) - .transformAndConcat(new Function>>() { - @Override - public Iterable> apply(Integer bucketNum) { - return loadDiffKeysFromBucket(lowerCheckpoint, upperCheckpoint, bucketNum); - }}) - .toSortedList(new Comparator>() { - @Override - public int compare(Key a, Key b) { - // Compare keys by timestamp (which is encoded in the id as millis), then by bucket id. - return ComparisonChain.start() - .compare(a.getId(), b.getId()) - .compare(a.getParent().getId(), b.getParent().getId()) - .result(); - }}); + return upperCheckpoint + .getBucketTimestamps() + .keySet() + .stream() + .flatMap( + bucketNum -> + Streams.stream(loadDiffKeysFromBucket(lowerCheckpoint, upperCheckpoint, bucketNum))) + .sorted( + comparingLong(Key::getId) + .thenComparingLong(a -> a.getParent().getId())) + .collect(toImmutableList()); } /** diff --git a/java/google/registry/backup/GcsDiffFileLister.java b/java/google/registry/backup/GcsDiffFileLister.java index 1b352244d..b8f272e44 100644 --- a/java/google/registry/backup/GcsDiffFileLister.java +++ b/java/google/registry/backup/GcsDiffFileLister.java @@ -37,7 +37,6 @@ import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; -import java.util.concurrent.Callable; import javax.annotation.Nullable; import javax.inject.Inject; import org.joda.time.DateTime; @@ -113,12 +112,7 @@ class GcsDiffFileLister { final String filename = listItems.next().getName(); DateTime upperBoundTime = DateTime.parse(filename.substring(DIFF_FILE_PREFIX.length())); if (isInRange(upperBoundTime, fromTime, toTime)) { - upperBoundTimesToMetadata.put(upperBoundTime, executor.submit( - new Callable() { - @Override - public GcsFileMetadata call() throws Exception { - return getMetadata(filename); - }})); + upperBoundTimesToMetadata.put(upperBoundTime, executor.submit(() -> getMetadata(filename))); lastUpperBoundTime = latestOf(upperBoundTime, lastUpperBoundTime); } } diff --git a/java/google/registry/backup/RestoreCommitLogsAction.java b/java/google/registry/backup/RestoreCommitLogsAction.java index b2c8065e7..6d8bc9698 100644 --- a/java/google/registry/backup/RestoreCommitLogsAction.java +++ b/java/google/registry/backup/RestoreCommitLogsAction.java @@ -52,7 +52,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.concurrent.Callable; import javax.inject.Inject; import org.joda.time.DateTime; @@ -117,16 +116,16 @@ public class RestoreCommitLogsAction implements Runnable { } } // Restore the CommitLogCheckpointRoot and CommitLogBuckets. - saveOfy(FluentIterable.from(bucketTimestamps.entrySet()) - .transform(new Function, ImmutableObject> () { - @Override - public ImmutableObject apply(Entry entry) { - return new CommitLogBucket.Builder() - .setBucketNum(entry.getKey()) - .setLastWrittenTime(entry.getValue()) - .build(); - }}) - .append(CommitLogCheckpointRoot.create(lastCheckpoint.getCheckpointTime()))); + saveOfy( + FluentIterable.from(bucketTimestamps.entrySet()) + .transform( + (Function, ImmutableObject>) + entry -> + new CommitLogBucket.Builder() + .setBucketNum(entry.getKey()) + .setLastWrittenTime(entry.getValue()) + .build()) + .append(CommitLogCheckpointRoot.create(lastCheckpoint.getCheckpointTime()))); } /** @@ -153,11 +152,7 @@ public class RestoreCommitLogsAction implements Runnable { try { deleteResult.now(); } catch (Exception e) { - retry(new Runnable() { - @Override - public void run() { - deleteAsync(manifest.getDeletions()).now(); - }}); + retry(() -> deleteAsync(manifest.getDeletions()).now()); } return manifest; } @@ -167,11 +162,7 @@ public class RestoreCommitLogsAction implements Runnable { logger.info("Would have saved " + entitiesToSave); return; } - retry(new Runnable() { - @Override - public void run() { - datastoreService.put(entitiesToSave); - }}); + retry(() -> datastoreService.put(entitiesToSave)); } private void saveOfy(final Iterable objectsToSave) { @@ -179,11 +170,7 @@ public class RestoreCommitLogsAction implements Runnable { logger.info("Would have saved " + asList(objectsToSave)); return; } - retry(new Runnable() { - @Override - public void run() { - ofy().saveWithoutBackup().entities(objectsToSave).now(); - }}); + retry(() -> ofy().saveWithoutBackup().entities(objectsToSave).now()); } private Result deleteAsync(Set> keysToDelete) { @@ -198,12 +185,10 @@ public class RestoreCommitLogsAction implements Runnable { /** Retrier for saves and deletes, since we can't proceed with any failures. */ private void retry(final Runnable runnable) { retrier.callWithRetry( - new Callable() { - @Override - public Void call() throws Exception { - runnable.run(); - return null; - }}, + () -> { + runnable.run(); + return null; + }, RuntimeException.class); } } diff --git a/java/google/registry/batch/DeleteContactsAndHostsAction.java b/java/google/registry/batch/DeleteContactsAndHostsAction.java index 11b27b761..e96395ec5 100644 --- a/java/google/registry/batch/DeleteContactsAndHostsAction.java +++ b/java/google/registry/batch/DeleteContactsAndHostsAction.java @@ -18,6 +18,7 @@ import static com.google.appengine.api.taskqueue.QueueConstants.maxLeaseCount; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.math.IntMath.divide; import static com.googlecode.objectify.Key.getKind; import static google.registry.flows.ResourceFlowUtils.denyPendingTransfer; @@ -52,8 +53,6 @@ import com.google.appengine.tools.mapreduce.Mapper; import com.google.appengine.tools.mapreduce.Reducer; import com.google.appengine.tools.mapreduce.ReducerInput; import com.google.auto.value.AutoValue; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -94,7 +93,6 @@ import google.registry.util.SystemClock; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import javax.inject.Inject; import javax.inject.Named; import org.joda.time.DateTime; @@ -180,22 +178,11 @@ public class DeleteContactsAndHostsAction implements Runnable { return; } final List tasks = - FluentIterable.from(deletionRequests) - .transform( - new Function() { - @Override - public TaskHandle apply(DeletionRequest deletionRequest) { - return deletionRequest.task(); - } - }) - .toList(); + deletionRequests.stream().map(DeletionRequest::task).collect(toImmutableList()); retrier.callWithRetry( - new Callable() { - @Override - public Void call() throws Exception { - queue.deleteTask(tasks); - return null; - } + () -> { + queue.deleteTask(tasks); + return null; }, TransientFailureException.class); for (DeletionRequest deletionRequest : deletionRequests) { diff --git a/java/google/registry/batch/DeleteProberDataAction.java b/java/google/registry/batch/DeleteProberDataAction.java index ffadb3b72..a62206b73 100644 --- a/java/google/registry/batch/DeleteProberDataAction.java +++ b/java/google/registry/batch/DeleteProberDataAction.java @@ -15,6 +15,7 @@ package google.registry.batch; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.flows.ResourceFlowUtils.updateForeignKeyIndexDeletionTime; import static google.registry.mapreduce.MapreduceRunner.PARAM_DRY_RUN; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -24,11 +25,8 @@ import static google.registry.request.Action.Method.POST; import static org.joda.time.DateTimeZone.UTC; import com.google.appengine.tools.mapreduce.Mapper; -import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Strings; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -94,21 +92,11 @@ public class DeleteProberDataAction implements Runnable { } private static ImmutableSet getProberRoidSuffixes() { - return FluentIterable.from(getTldsOfType(TldType.TEST)) - .filter(new Predicate() { - @Override - public boolean apply(String tld) { - // Extra sanity check to prevent us from nuking prod data if a real TLD accidentally - // gets set to type TEST. - return tld.endsWith(".test"); - }}) - .transform( - new Function() { - @Override - public String apply(String tld) { - return Registry.get(tld).getRoidSuffix(); - }}) - .toSet(); + return getTldsOfType(TldType.TEST) + .stream() + .filter(tld -> tld.endsWith(".test")) + .map(tld -> Registry.get(tld).getRoidSuffix()) + .collect(toImmutableSet()); } /** Provides the map method that runs for each existing DomainBase entity. */ diff --git a/java/google/registry/batch/ExpandRecurringBillingEventsAction.java b/java/google/registry/batch/ExpandRecurringBillingEventsAction.java index b3ce51257..a47bb7f19 100644 --- a/java/google/registry/batch/ExpandRecurringBillingEventsAction.java +++ b/java/google/registry/batch/ExpandRecurringBillingEventsAction.java @@ -15,6 +15,7 @@ package google.registry.batch; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Sets.difference; import static google.registry.mapreduce.MapreduceRunner.PARAM_DRY_RUN; import static google.registry.mapreduce.inputs.EppResourceInputs.createChildEntityInput; @@ -32,13 +33,11 @@ import static google.registry.util.PipelineUtils.createJobPath; import com.google.appengine.tools.mapreduce.Mapper; import com.google.appengine.tools.mapreduce.Reducer; import com.google.appengine.tools.mapreduce.ReducerInput; -import com.google.common.base.Function; import com.google.common.base.Optional; -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.Range; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.Work; @@ -262,14 +261,10 @@ public class ExpandRecurringBillingEventsAction implements Runnable { DateTime cursorTime, DateTime executeTime, final Registry tld) { - return FluentIterable.from(eventTimes) - .transform(new Function() { - @Override - public DateTime apply(DateTime eventTime) { - return eventTime.plus(tld.getAutoRenewGracePeriodLength()); - }}) + return Streams.stream(eventTimes) + .map(eventTime -> eventTime.plus(tld.getAutoRenewGracePeriodLength())) .filter(Range.closedOpen(cursorTime, executeTime)) - .toSet(); + .collect(toImmutableSet()); } /** @@ -279,19 +274,13 @@ public class ExpandRecurringBillingEventsAction implements Runnable { private ImmutableSet getExistingBillingTimes( Iterable oneTimesForDomain, final BillingEvent.Recurring recurringEvent) { - return FluentIterable.from(oneTimesForDomain) - .filter(new Predicate() { - @Override - public boolean apply(OneTime billingEvent) { - return Key.create(recurringEvent) - .equals(billingEvent.getCancellationMatchingBillingEvent()); - }}) - .transform(new Function() { - @Override - public DateTime apply(OneTime billingEvent) { - return billingEvent.getBillingTime(); - }}) - .toSet(); + return Streams.stream(oneTimesForDomain) + .filter( + billingEvent -> + Key.create(recurringEvent) + .equals(billingEvent.getCancellationMatchingBillingEvent())) + .map(OneTime::getBillingTime) + .collect(toImmutableSet()); } } diff --git a/java/google/registry/batch/RefreshDnsOnHostRenameAction.java b/java/google/registry/batch/RefreshDnsOnHostRenameAction.java index 14639c332..580928459 100644 --- a/java/google/registry/batch/RefreshDnsOnHostRenameAction.java +++ b/java/google/registry/batch/RefreshDnsOnHostRenameAction.java @@ -17,6 +17,7 @@ package google.registry.batch; import static com.google.appengine.api.taskqueue.QueueConstants.maxLeaseCount; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.flows.async.AsyncFlowEnqueuer.PARAM_HOST_KEY; import static google.registry.flows.async.AsyncFlowEnqueuer.PARAM_REQUESTED_TIME; import static google.registry.flows.async.AsyncFlowEnqueuer.QUEUE_ASYNC_HOST_RENAME; @@ -38,8 +39,6 @@ import com.google.appengine.tools.mapreduce.Mapper; import com.google.appengine.tools.mapreduce.Reducer; import com.google.appengine.tools.mapreduce.ReducerInput; import com.google.auto.value.AutoValue; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.googlecode.objectify.Key; @@ -61,7 +60,6 @@ import google.registry.util.SystemClock; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; @@ -180,12 +178,11 @@ public class RefreshDnsOnHostRenameAction implements Runnable { } if (referencingHostKey != null) { retrier.callWithRetry( - new Callable() { - @Override - public Void call() throws Exception { - dnsQueue.addDomainRefreshTask(domain.getFullyQualifiedDomainName()); - return null; - }}, TransientFailureException.class); + () -> { + dnsQueue.addDomainRefreshTask(domain.getFullyQualifiedDomainName()); + return null; + }, + TransientFailureException.class); logger.infofmt( "Enqueued DNS refresh for domain %s referenced by host %s.", domain.getFullyQualifiedDomainName(), referencingHostKey); @@ -244,22 +241,13 @@ public class RefreshDnsOnHostRenameAction implements Runnable { return; } final List tasks = - FluentIterable.from(refreshRequests) - .transform( - new Function() { - @Override - public TaskHandle apply(DnsRefreshRequest refreshRequest) { - return refreshRequest.task(); - } - }) - .toList(); + refreshRequests.stream().map(DnsRefreshRequest::task).collect(toImmutableList()); retrier.callWithRetry( - new Callable() { - @Override - public Void call() throws Exception { - queue.deleteTask(tasks); - return null; - }}, TransientFailureException.class); + () -> { + queue.deleteTask(tasks); + return null; + }, + TransientFailureException.class); for (DnsRefreshRequest refreshRequest : refreshRequests) { asyncFlowMetrics.recordAsyncFlowResult(DNS_REFRESH, result, refreshRequest.requestedTime()); } diff --git a/java/google/registry/batch/VerifyEntityIntegrityAction.java b/java/google/registry/batch/VerifyEntityIntegrityAction.java index 52b069842..8e58dddc1 100644 --- a/java/google/registry/batch/VerifyEntityIntegrityAction.java +++ b/java/google/registry/batch/VerifyEntityIntegrityAction.java @@ -15,6 +15,7 @@ package google.registry.batch; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static com.googlecode.objectify.Key.getKind; import static google.registry.model.EppResourceUtils.isActive; @@ -36,7 +37,6 @@ import com.google.appengine.tools.mapreduce.ReducerInput; import com.google.appengine.tools.mapreduce.inputs.DatastoreKeyInput; import com.google.common.annotations.VisibleForTesting; 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.Key; @@ -259,18 +259,24 @@ public class VerifyEntityIntegrityAction implements Runnable { verifyExistence(key, domain.getTransferData().getServerApproveAutorenewEvent()); verifyExistence(key, domain.getTransferData().getServerApproveAutorenewPollMessage()); verifyExistence(key, domain.getTransferData().getServerApproveBillingEvent()); - verifyExistence(key, FluentIterable - .from(domain.getTransferData().getServerApproveEntities()) - .transform( - new Function, - Key>() { - @SuppressWarnings("unchecked") - @Override - public Key apply( - Key key) { - return (Key) key; - }}) - .toSet()); + verifyExistence( + key, + domain + .getTransferData() + .getServerApproveEntities() + .stream() + .map( + new Function< + Key, + Key>() { + @SuppressWarnings("unchecked") + @Override + public Key apply( + Key key) { + return (Key) key; + } + }) + .collect(toImmutableSet())); verifyExistence(key, domain.getApplication()); verifyExistence(key, domain.getAutorenewBillingEvent()); for (GracePeriod gracePeriod : domain.getGracePeriods()) { diff --git a/java/google/registry/batch/VerifyEntityIntegrityStreamer.java b/java/google/registry/batch/VerifyEntityIntegrityStreamer.java index 73d1613ba..74936e649 100644 --- a/java/google/registry/batch/VerifyEntityIntegrityStreamer.java +++ b/java/google/registry/batch/VerifyEntityIntegrityStreamer.java @@ -21,19 +21,16 @@ import static google.registry.batch.EntityIntegrityAlertsSchema.FIELD_SCANTIME; import static google.registry.batch.EntityIntegrityAlertsSchema.FIELD_SOURCE; import static google.registry.batch.EntityIntegrityAlertsSchema.FIELD_TARGET; import static google.registry.batch.EntityIntegrityAlertsSchema.TABLE_ID; +import static java.util.stream.Collectors.joining; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.Bigquery.Tabledata.InsertAll; import com.google.api.services.bigquery.model.TableDataInsertAllRequest; import com.google.api.services.bigquery.model.TableDataInsertAllRequest.Rows; import com.google.api.services.bigquery.model.TableDataInsertAllResponse; -import com.google.api.services.bigquery.model.TableDataInsertAllResponse.InsertErrors; import com.google.auto.factory.AutoFactory; import com.google.auto.factory.Provided; -import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import google.registry.bigquery.BigqueryFactory; @@ -183,30 +180,26 @@ public class VerifyEntityIntegrityStreamer { new TableDataInsertAllRequest().setRows(rows)); Callable callable = - new Callable() { - @Override - public Void call() throws Exception { - TableDataInsertAllResponse response = request.execute(); - // Turn errors on the response object into RuntimeExceptions that the retrier will - // retry. - if (response.getInsertErrors() != null && !response.getInsertErrors().isEmpty()) { - throw new RuntimeException( - FluentIterable.from(response.getInsertErrors()) - .transform( - new Function() { - @Override - public String apply(InsertErrors error) { - try { - return error.toPrettyString(); - } catch (IOException e) { - return error.toString(); - } - } - }) - .join(Joiner.on('\n'))); - } - return null; + () -> { + TableDataInsertAllResponse response = request.execute(); + // Turn errors on the response object into RuntimeExceptions that the retrier will + // retry. + if (response.getInsertErrors() != null && !response.getInsertErrors().isEmpty()) { + throw new RuntimeException( + response + .getInsertErrors() + .stream() + .map( + error -> { + try { + return error.toPrettyString(); + } catch (IOException e) { + return error.toString(); + } + }) + .collect(joining("\n"))); } + return null; }; retrier.callWithRetry(callable, RuntimeException.class); } catch (IOException e) { diff --git a/java/google/registry/bigquery/BigqueryConnection.java b/java/google/registry/bigquery/BigqueryConnection.java index 38ef5e9ef..5c2a5b30e 100644 --- a/java/google/registry/bigquery/BigqueryConnection.java +++ b/java/google/registry/bigquery/BigqueryConnection.java @@ -73,7 +73,6 @@ import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Random; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import javax.annotation.Nullable; import org.joda.time.DateTime; @@ -693,20 +692,15 @@ public class BigqueryConnection implements AutoCloseable { final Job job, final T result, @Nullable final AbstractInputStreamContent data) { - return service.submit(new Callable() { - @Override - public T call() { - runJob(job, data); - return result; - }}); + return service.submit( + () -> { + runJob(job, data); + return result; + }); } private ListenableFuture runJobToCompletion(final Job job) { - return service.submit(new Callable() { - @Override - public Job call() { - return runJob(job, null); - }}); + return service.submit(() -> runJob(job, null)); } /** Helper that returns true if a dataset with this name exists. */ diff --git a/java/google/registry/config/RegistryConfig.java b/java/google/registry/config/RegistryConfig.java index f87bd12ca..8b170220b 100644 --- a/java/google/registry/config/RegistryConfig.java +++ b/java/google/registry/config/RegistryConfig.java @@ -16,7 +16,6 @@ package google.registry.config; import static com.google.common.base.Suppliers.memoize; import static google.registry.config.ConfigUtils.makeUrl; -import static google.registry.config.YamlUtils.getConfigSettings; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.common.annotations.VisibleForTesting; @@ -1270,11 +1269,7 @@ public final class RegistryConfig { * change the contents of the YAML config files. */ private static final Supplier CONFIG_SETTINGS = - memoize(new Supplier() { - @Override - public RegistryConfigSettings get() { - return getConfigSettings(); - }}); + memoize(YamlUtils::getConfigSettings); private RegistryConfig() {} } diff --git a/java/google/registry/cron/TldFanoutAction.java b/java/google/registry/cron/TldFanoutAction.java index f25222f34..eba54030c 100644 --- a/java/google/registry/cron/TldFanoutAction.java +++ b/java/google/registry/cron/TldFanoutAction.java @@ -19,7 +19,7 @@ import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.base.Strings.nullToEmpty; -import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getFirst; import static com.google.common.collect.Multimaps.filterKeys; import static com.google.common.collect.Sets.difference; @@ -36,6 +36,7 @@ import com.google.common.base.Optional; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; +import com.google.common.collect.Streams; import google.registry.request.Action; import google.registry.request.Parameter; import google.registry.request.ParameterMap; @@ -116,11 +117,13 @@ public final class TldFanoutAction implements Runnable { public void run() { Set tlds = difference( - ImmutableSet.copyOf( - concat( - runInEmpty ? ImmutableSet.of("") : ImmutableSet.of(), - forEachRealTld ? getTldsOfType(REAL) : ImmutableSet.of(), - forEachTestTld ? getTldsOfType(TEST) : ImmutableSet.of())), + Streams.concat( + Streams.stream(runInEmpty ? ImmutableSet.of("") : ImmutableSet.of()), + Streams.stream( + forEachRealTld ? getTldsOfType(REAL) : ImmutableSet.of()), + Streams.stream( + forEachTestTld ? getTldsOfType(TEST) : ImmutableSet.of())) + .collect(toImmutableSet()), excludes); Multimap flowThruParams = filterKeys(params, not(in(CONTROL_PARAMS))); Queue taskQueue = getQueue(queue); diff --git a/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java b/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java index 3afa3ea92..745d02a82 100644 --- a/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java +++ b/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java @@ -284,39 +284,35 @@ public class CloudDnsWriter extends BaseDnsWriter { @VisibleForTesting Callable getMutateZoneCallback( final ImmutableMap> desiredRecords) { - return new Callable() { - @Override - public Void call() throws IOException, ZoneStateException { - // Fetch all existing records for names that this writer is trying to modify - Builder existingRecords = new Builder<>(); - for (String domainName : desiredRecords.keySet()) { - List existingRecordsForDomain = - getResourceRecordsForDomain(domainName); - existingRecords.addAll(existingRecordsForDomain); + return () -> { + // Fetch all existing records for names that this writer is trying to modify + Builder existingRecords = new Builder<>(); + for (String domainName : desiredRecords.keySet()) { + List existingRecordsForDomain = getResourceRecordsForDomain(domainName); + existingRecords.addAll(existingRecordsForDomain); - // Fetch glue records for in-bailiwick nameservers - for (ResourceRecordSet record : existingRecordsForDomain) { - if (!record.getType().equals("NS")) { - continue; - } - for (String hostName : record.getRrdatas()) { - if (hostName.endsWith(domainName) && !hostName.equals(domainName)) { - existingRecords.addAll(getResourceRecordsForDomain(hostName)); - } + // Fetch glue records for in-bailiwick nameservers + for (ResourceRecordSet record : existingRecordsForDomain) { + if (!record.getType().equals("NS")) { + continue; + } + for (String hostName : record.getRrdatas()) { + if (hostName.endsWith(domainName) && !hostName.equals(domainName)) { + existingRecords.addAll(getResourceRecordsForDomain(hostName)); } } } - - // Flatten the desired records into one set. - Builder flattenedDesiredRecords = new Builder<>(); - for (ImmutableSet records : desiredRecords.values()) { - flattenedDesiredRecords.addAll(records); - } - - // Delete all existing records and add back the desired records - updateResourceRecords(flattenedDesiredRecords.build(), existingRecords.build()); - return null; } + + // Flatten the desired records into one set. + Builder flattenedDesiredRecords = new Builder<>(); + for (ImmutableSet records : desiredRecords.values()) { + flattenedDesiredRecords.addAll(records); + } + + // Delete all existing records and add back the desired records + updateResourceRecords(flattenedDesiredRecords.build(), existingRecords.build()); + return null; }; } diff --git a/java/google/registry/export/DatastoreBackupService.java b/java/google/registry/export/DatastoreBackupService.java index 3d8566837..d0ba87ef3 100644 --- a/java/google/registry/export/DatastoreBackupService.java +++ b/java/google/registry/export/DatastoreBackupService.java @@ -18,15 +18,12 @@ import static com.google.appengine.api.datastore.DatastoreServiceFactory.getData import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.Strings.nullToEmpty; -import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.modules.ModulesService; import com.google.appengine.api.modules.ModulesServiceFactory; import com.google.appengine.api.taskqueue.TaskHandle; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -91,18 +88,10 @@ public class DatastoreBackupService { public Iterable findAllByNamePrefix(final String namePrefix) { // Need the raw DatastoreService to access the internal _AE_Backup_Information entities. // TODO(b/19081037): make an Objectify entity class for these raw Datastore entities instead. - return FluentIterable - .from(getDatastoreService().prepare(new Query(BACKUP_INFO_KIND)).asIterable()) - .filter(new Predicate() { - @Override - public boolean apply(Entity entity) { - return nullToEmpty((String) entity.getProperty("name")).startsWith(namePrefix); - }}) - .transform(new Function() { - @Override - public DatastoreBackupInfo apply(Entity entity) { - return new DatastoreBackupInfo(entity); - }}); + return FluentIterable.from( + getDatastoreService().prepare(new Query(BACKUP_INFO_KIND)).asIterable()) + .filter(entity -> nullToEmpty((String) entity.getProperty("name")).startsWith(namePrefix)) + .transform(DatastoreBackupInfo::new); } /** diff --git a/java/google/registry/export/SyncGroupMembersAction.java b/java/google/registry/export/SyncGroupMembersAction.java index b81e2d730..b8275bd71 100644 --- a/java/google/registry/export/SyncGroupMembersAction.java +++ b/java/google/registry/export/SyncGroupMembersAction.java @@ -14,6 +14,8 @@ package google.registry.export; +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.request.Action.Method.POST; import static google.registry.util.CollectionUtils.nullToEmpty; @@ -21,13 +23,11 @@ import static google.registry.util.RegistrarUtils.normalizeClientId; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_OK; -import com.google.common.base.Function; import com.google.common.base.Optional; -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.Sets; +import com.google.common.collect.Streams; import com.googlecode.objectify.VoidWork; import google.registry.config.RegistryConfig.Config; import google.registry.groups.GroupsConnection; @@ -44,7 +44,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.Callable; import javax.annotation.Nullable; import javax.inject.Inject; @@ -118,16 +117,14 @@ public final class SyncGroupMembersAction implements Runnable { */ @Override public void run() { - List dirtyRegistrars = FluentIterable.from(Registrar.loadAllCached()) - .filter(new Predicate() { - @Override - public boolean apply(Registrar registrar) { - // Only grab active registrars that require syncing and are of the correct type. - return registrar.isLive() - && registrar.getContactsRequireSyncing() - && registrar.getType() == Registrar.Type.REAL; - }}) - .toList(); + List dirtyRegistrars = + Streams.stream(Registrar.loadAllCached()) + .filter( + registrar -> + registrar.isLive() + && registrar.getContactsRequireSyncing() + && registrar.getType() == Registrar.Type.REAL) + .collect(toImmutableList()); if (dirtyRegistrars.isEmpty()) { sendResponse(Result.NOT_MODIFIED, null); return; @@ -137,12 +134,12 @@ public final class SyncGroupMembersAction implements Runnable { new ImmutableMap.Builder<>(); for (final Registrar registrar : dirtyRegistrars) { try { - retrier.callWithRetry(new Callable() { - @Override - public Void call() throws Exception { - syncRegistrarContacts(registrar); - return null; - }}, RuntimeException.class); + retrier.callWithRetry( + () -> { + syncRegistrarContacts(registrar); + return null; + }, + RuntimeException.class); resultsBuilder.put(registrar, Optional.absent()); } catch (Throwable e) { logger.severe(e, e.getMessage()); @@ -193,18 +190,12 @@ public final class SyncGroupMembersAction implements Runnable { groupKey = getGroupEmailAddressForContactType( registrar.getClientId(), type, gSuiteDomainName); Set currentMembers = groupsConnection.getMembersOfGroup(groupKey); - Set desiredMembers = FluentIterable.from(registrarContacts) - .filter(new Predicate() { - @Override - public boolean apply(RegistrarContact contact) { - return contact.getTypes().contains(type); - }}) - .transform(new Function() { - @Override - public String apply(RegistrarContact contact) { - return contact.getEmailAddress(); - }}) - .toSet(); + Set desiredMembers = + registrarContacts + .stream() + .filter(contact -> contact.getTypes().contains(type)) + .map(RegistrarContact::getEmailAddress) + .collect(toImmutableSet()); for (String email : Sets.difference(desiredMembers, currentMembers)) { groupsConnection.addMemberToGroup(groupKey, email, Role.MEMBER); totalAdded++; diff --git a/java/google/registry/export/sheet/SyncRegistrarsSheet.java b/java/google/registry/export/sheet/SyncRegistrarsSheet.java index d4242095c..0dce56976 100644 --- a/java/google/registry/export/sheet/SyncRegistrarsSheet.java +++ b/java/google/registry/export/sheet/SyncRegistrarsSheet.java @@ -15,6 +15,7 @@ package google.registry.export.sheet; import static com.google.common.base.MoreObjects.firstNonNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.common.Cursor.CursorType.SYNC_REGISTRAR_SHEET; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registrar.RegistrarContact.Type.ABUSE; @@ -26,10 +27,8 @@ import static google.registry.model.registrar.RegistrarContact.Type.TECH; import static google.registry.model.registrar.RegistrarContact.Type.WHOIS; import static google.registry.util.DateTimeUtils.START_OF_TIME; -import com.google.common.base.Function; import com.google.common.base.Joiner; 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.ImmutableSortedSet; @@ -77,104 +76,83 @@ class SyncRegistrarsSheet { final DateTime executionTime = clock.nowUtc(); sheetSynchronizer.synchronize( spreadsheetId, - FluentIterable.from( - new Ordering() { - @Override - public int compare(Registrar left, Registrar right) { - return left.getClientId().compareTo(right.getClientId()); - } - }.immutableSortedCopy(Registrar.loadAllCached())) + new Ordering() { + @Override + public int compare(Registrar left, Registrar right) { + return left.getClientId().compareTo(right.getClientId()); + } + }.immutableSortedCopy(Registrar.loadAllCached()) + .stream() .filter( - new Predicate() { - @Override - public boolean apply(Registrar registrar) { - return registrar.getType() == Registrar.Type.REAL - || registrar.getType() == Registrar.Type.OTE; - } + registrar -> + registrar.getType() == Registrar.Type.REAL + || registrar.getType() == Registrar.Type.OTE) + .map( + registrar -> { + ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); + ImmutableSortedSet contacts = registrar.getContacts(); + RegistrarAddress address = + firstNonNull( + registrar.getLocalizedAddress(), + firstNonNull( + registrar.getInternationalizedAddress(), + new RegistrarAddress.Builder() + .setStreet(ImmutableList.of("UNKNOWN")) + .setCity("UNKNOWN") + .setCountryCode("US") + .build())); + // + // (╯°□°)╯ WARNING WARNING WARNING + // + // Do not change these mappings simply because the Registrar model changed. Only + // change these mappings if the people who use the spreadsheet requested it be + // changed. + // + // These values are hard-coded because they correspond to actual spreadsheet + // columns. If you change this dictionary, then you'll need to manually add new + // columns to the registrar spreadsheets for all environments before deployment, + // and you'll need to remove deleted columns probably like a week after + // deployment. + // + builder.put("clientIdentifier", convert(registrar.getClientId())); + builder.put("registrarName", convert(registrar.getRegistrarName())); + builder.put("state", convert(registrar.getState())); + builder.put("ianaIdentifier", convert(registrar.getIanaIdentifier())); + builder.put("billingIdentifier", convert(registrar.getBillingIdentifier())); + builder.put("billingAccountMap", convert(registrar.getBillingAccountMap())); + builder.put("primaryContacts", convertContacts(contacts, byType(ADMIN))); + builder.put("techContacts", convertContacts(contacts, byType(TECH))); + builder.put("marketingContacts", convertContacts(contacts, byType(MARKETING))); + builder.put("abuseContacts", convertContacts(contacts, byType(ABUSE))); + builder.put("whoisInquiryContacts", convertContacts(contacts, byType(WHOIS))); + builder.put("legalContacts", convertContacts(contacts, byType(LEGAL))); + builder.put("billingContacts", convertContacts(contacts, byType(BILLING))); + builder.put( + "contactsMarkedAsWhoisAdmin", + convertContacts(contacts, RegistrarContact::getVisibleInWhoisAsAdmin)); + builder.put( + "contactsMarkedAsWhoisTech", + convertContacts(contacts, RegistrarContact::getVisibleInWhoisAsTech)); + builder.put("emailAddress", convert(registrar.getEmailAddress())); + builder.put("address.street", convert(address.getStreet())); + builder.put("address.city", convert(address.getCity())); + builder.put("address.state", convert(address.getState())); + builder.put("address.zip", convert(address.getZip())); + builder.put("address.countryCode", convert(address.getCountryCode())); + builder.put("phoneNumber", convert(registrar.getPhoneNumber())); + builder.put("faxNumber", convert(registrar.getFaxNumber())); + builder.put("creationTime", convert(registrar.getCreationTime())); + builder.put("lastUpdateTime", convert(registrar.getLastUpdateTime())); + builder.put("allowedTlds", convert(registrar.getAllowedTlds())); + builder.put("whoisServer", convert(registrar.getWhoisServer())); + builder.put("blockPremiumNames", convert(registrar.getBlockPremiumNames())); + builder.put("ipAddressWhitelist", convert(registrar.getIpAddressWhitelist())); + builder.put("url", convert(registrar.getUrl())); + builder.put("referralUrl", convert(registrar.getReferralUrl())); + builder.put("icannReferralEmail", convert(registrar.getIcannReferralEmail())); + return builder.build(); }) - .transform( - new Function>() { - @Override - public ImmutableMap apply(Registrar registrar) { - ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); - ImmutableSortedSet contacts = registrar.getContacts(); - RegistrarAddress address = - firstNonNull( - registrar.getLocalizedAddress(), - firstNonNull( - registrar.getInternationalizedAddress(), - new RegistrarAddress.Builder() - .setStreet(ImmutableList.of("UNKNOWN")) - .setCity("UNKNOWN") - .setCountryCode("US") - .build())); - // - // (╯°□°)╯ WARNING WARNING WARNING - // - // Do not change these mappings simply because the Registrar model changed. Only - // change these mappings if the people who use the spreadsheet requested it be - // changed. - // - // These values are hard-coded because they correspond to actual spreadsheet - // columns. If you change this dictionary, then you'll need to manually add new - // columns to the registrar spreadsheets for all environments before deployment, - // and you'll need to remove deleted columns probably like a week after - // deployment. - // - builder.put("clientIdentifier", convert(registrar.getClientId())); - builder.put("registrarName", convert(registrar.getRegistrarName())); - builder.put("state", convert(registrar.getState())); - builder.put("ianaIdentifier", convert(registrar.getIanaIdentifier())); - builder.put("billingIdentifier", convert(registrar.getBillingIdentifier())); - builder.put("billingAccountMap", convert(registrar.getBillingAccountMap())); - builder.put("primaryContacts", convertContacts(contacts, byType(ADMIN))); - builder.put("techContacts", convertContacts(contacts, byType(TECH))); - builder.put("marketingContacts", convertContacts(contacts, byType(MARKETING))); - builder.put("abuseContacts", convertContacts(contacts, byType(ABUSE))); - builder.put("whoisInquiryContacts", convertContacts(contacts, byType(WHOIS))); - builder.put("legalContacts", convertContacts(contacts, byType(LEGAL))); - builder.put("billingContacts", convertContacts(contacts, byType(BILLING))); - builder.put( - "contactsMarkedAsWhoisAdmin", - convertContacts( - contacts, - new Predicate() { - @Override - public boolean apply(RegistrarContact contact) { - return contact.getVisibleInWhoisAsAdmin(); - } - })); - builder.put( - "contactsMarkedAsWhoisTech", - convertContacts( - contacts, - new Predicate() { - @Override - public boolean apply(RegistrarContact contact) { - return contact.getVisibleInWhoisAsTech(); - } - })); - builder.put("emailAddress", convert(registrar.getEmailAddress())); - builder.put("address.street", convert(address.getStreet())); - builder.put("address.city", convert(address.getCity())); - builder.put("address.state", convert(address.getState())); - builder.put("address.zip", convert(address.getZip())); - builder.put("address.countryCode", convert(address.getCountryCode())); - builder.put("phoneNumber", convert(registrar.getPhoneNumber())); - builder.put("faxNumber", convert(registrar.getFaxNumber())); - builder.put("creationTime", convert(registrar.getCreationTime())); - builder.put("lastUpdateTime", convert(registrar.getLastUpdateTime())); - builder.put("allowedTlds", convert(registrar.getAllowedTlds())); - builder.put("whoisServer", convert(registrar.getWhoisServer())); - builder.put("blockPremiumNames", convert(registrar.getBlockPremiumNames())); - builder.put("ipAddressWhitelist", convert(registrar.getIpAddressWhitelist())); - builder.put("url", convert(registrar.getUrl())); - builder.put("referralUrl", convert(registrar.getReferralUrl())); - builder.put("icannReferralEmail", convert(registrar.getIcannReferralEmail())); - return builder.build(); - } - }) - .toList()); + .collect(toImmutableList())); ofy().transact(new VoidWork() { @Override public void vrun() { @@ -201,11 +179,7 @@ class SyncRegistrarsSheet { } private static Predicate byType(final RegistrarContact.Type type) { - return new Predicate() { - @Override - public boolean apply(RegistrarContact contact) { - return contact.getTypes().contains(type); - }}; + return contact -> contact.getTypes().contains(type); } /** Converts a value to a string representation that can be stored in a spreadsheet cell. */ diff --git a/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java b/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java index d391d4e3c..a74b49565 100644 --- a/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java +++ b/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java @@ -134,19 +134,16 @@ public class SyncRegistrarsSheetAction implements Runnable { } String sheetLockName = String.format("%s: %s", LOCK_NAME, sheetId.get()); - Callable runner = new Callable() { - @Nullable - @Override - public Void call() throws IOException { - try { - syncRegistrarsSheet.run(sheetId.get()); - Result.OK.send(response, null); - } catch (IOException e) { - Result.FAILED.send(response, e); - } - return null; - } - }; + Callable runner = + () -> { + try { + syncRegistrarsSheet.run(sheetId.get()); + Result.OK.send(response, null); + } catch (IOException e) { + Result.FAILED.send(response, e); + } + return null; + }; if (!lockHandler.executeWithLocks(runner, null, timeout, sheetLockName)) { // If we fail to acquire the lock, it probably means lots of updates are happening at once, in // which case it should be safe to not bother. The task queue definition should *not* specify diff --git a/java/google/registry/flows/ExtensionManager.java b/java/google/registry/flows/ExtensionManager.java index 159d7d440..b76c5d265 100644 --- a/java/google/registry/flows/ExtensionManager.java +++ b/java/google/registry/flows/ExtensionManager.java @@ -14,15 +14,12 @@ package google.registry.flows; -import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.intersection; import static google.registry.model.domain.fee.Fee.FEE_EXTENSION_URIS; import static google.registry.model.eppcommon.ProtocolDefinition.ServiceExtension.getCommandExtensionUri; import com.google.common.base.Joiner; -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 google.registry.flows.EppException.CommandUseErrorException; @@ -130,7 +127,13 @@ public final class ExtensionManager { ImmutableSet> implementedExtensions) throws UnsupportedRepeatedExtensionException { for (Class implemented : implementedExtensions) { - if (FluentIterable.from(suppliedExtensionInstances).filter(implemented).size() > 1) { + if ((int) + suppliedExtensionInstances + .stream() + .filter(implemented::isInstance) + .map(implemented::cast) + .count() + > 1) { throw new UnsupportedRepeatedExtensionException(); } } @@ -143,13 +146,9 @@ public final class ExtensionManager { ImmutableSet.Builder> unimplementedExtensionsBuilder = new ImmutableSet.Builder<>(); for (final CommandExtension instance : suppliedExtensionInstances) { - if (!any( - implementedExtensionClasses, - new Predicate>() { - @Override - public boolean apply(Class implementedExtensionClass) { - return implementedExtensionClass.isInstance(instance); - }})) { + if (implementedExtensionClasses + .stream() + .noneMatch(implementedExtensionClass -> implementedExtensionClass.isInstance(instance))) { unimplementedExtensionsBuilder.add(instance.getClass()); } } diff --git a/java/google/registry/flows/ResourceFlowUtils.java b/java/google/registry/flows/ResourceFlowUtils.java index 5bd9cdce4..a640eaef6 100644 --- a/java/google/registry/flows/ResourceFlowUtils.java +++ b/java/google/registry/flows/ResourceFlowUtils.java @@ -30,7 +30,6 @@ import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.googlecode.objectify.Key; import com.googlecode.objectify.Work; @@ -178,29 +177,35 @@ public final class ResourceFlowUtils { final Class resourceClass, final Function> getPotentialReferences) throws EppException { // Enter a transactionless context briefly. - EppException failfastException = ofy().doTransactionless(new Work() { - @Override - public EppException run() { - final ForeignKeyIndex fki = ForeignKeyIndex.load(resourceClass, targetId, now); - if (fki == null) { - return new ResourceDoesNotExistException(resourceClass, targetId); - } - // Query for the first few linked domains, and if found, actually load them. The query is - // eventually consistent and so might be very stale, but the direct load will not be stale, - // just non-transactional. If we find at least one actual reference then we can reliably - // fail. If we don't find any, we can't trust the query and need to do the full mapreduce. - Iterable> keys = - queryForLinkedDomains(fki.getResourceKey(), now).limit(FAILFAST_CHECK_COUNT).keys(); - Predicate predicate = new Predicate() { - @Override - public boolean apply(DomainBase domain) { - return getPotentialReferences.apply(domain).contains(fki.getResourceKey()); - }}; - return Iterables.any(ofy().load().keys(keys).values(), predicate) - ? new ResourceToDeleteIsReferencedException() - : null; - } - }); + EppException failfastException = + ofy() + .doTransactionless( + new Work() { + @Override + public EppException run() { + final ForeignKeyIndex fki = + ForeignKeyIndex.load(resourceClass, targetId, now); + if (fki == null) { + return new ResourceDoesNotExistException(resourceClass, targetId); + } + /* Query for the first few linked domains, and if found, actually load them. The + * query is eventually consistent and so might be very stale, but the direct + * load will not be stale, just non-transactional. If we find at least one + * actual reference then we can reliably fail. If we don't find any, we can't + * trust the query and need to do the full mapreduce. + */ + Iterable> keys = + queryForLinkedDomains(fki.getResourceKey(), now) + .limit(FAILFAST_CHECK_COUNT) + .keys(); + Predicate predicate = + domain -> + getPotentialReferences.apply(domain).contains(fki.getResourceKey()); + return ofy().load().keys(keys).values().stream().anyMatch(predicate) + ? new ResourceToDeleteIsReferencedException() + : null; + } + }); if (failfastException != null) { throw failfastException; } @@ -339,13 +344,8 @@ public final class ResourceFlowUtils { return; } // The roid should match one of the contacts. - Optional> foundContact = tryFind( - domain.getReferencedContacts(), - new Predicate>() { - @Override - public boolean apply(Key key) { - return key.getName().equals(authRepoId); - }}); + Optional> foundContact = + tryFind(domain.getReferencedContacts(), key -> key.getName().equals(authRepoId)); if (!foundContact.isPresent()) { throw new BadAuthInfoForResourceException(); } diff --git a/java/google/registry/flows/async/AsyncFlowEnqueuer.java b/java/google/registry/flows/async/AsyncFlowEnqueuer.java index 594c39e73..7b592b0c9 100644 --- a/java/google/registry/flows/async/AsyncFlowEnqueuer.java +++ b/java/google/registry/flows/async/AsyncFlowEnqueuer.java @@ -26,7 +26,6 @@ import google.registry.model.eppcommon.Trid; import google.registry.model.host.HostResource; import google.registry.util.FormattingLogger; import google.registry.util.Retrier; -import java.util.concurrent.Callable; import javax.inject.Inject; import javax.inject.Named; import org.joda.time.DateTime; @@ -107,11 +106,11 @@ public final class AsyncFlowEnqueuer { * enqueuing a task. */ private void addTaskToQueueWithRetry(final Queue queue, final TaskOptions task) { - retrier.callWithRetry(new Callable() { - @Override - public Void call() throws Exception { - queue.add(task); - return null; - }}, TransientFailureException.class); + retrier.callWithRetry( + () -> { + queue.add(task); + return null; + }, + TransientFailureException.class); } } diff --git a/java/google/registry/flows/contact/ContactDeleteFlow.java b/java/google/registry/flows/contact/ContactDeleteFlow.java index 9b1c9a659..0134bc65d 100644 --- a/java/google/registry/flows/contact/ContactDeleteFlow.java +++ b/java/google/registry/flows/contact/ContactDeleteFlow.java @@ -23,7 +23,6 @@ import static google.registry.flows.ResourceFlowUtils.verifyResourceOwnership; import static google.registry.model.eppoutput.Result.Code.SUCCESS_WITH_ACTION_PENDING; import static google.registry.model.ofy.ObjectifyService.ofy; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.googlecode.objectify.Key; @@ -69,13 +68,6 @@ public final class ContactDeleteFlow implements TransactionalFlow { StatusValue.PENDING_DELETE, StatusValue.SERVER_DELETE_PROHIBITED); - private static final Function> GET_REFERENCED_CONTACTS = - new Function>() { - @Override - public ImmutableSet apply(DomainBase domain) { - return domain.getReferencedContacts(); - }}; - @Inject ExtensionManager extensionManager; @Inject @ClientId String clientId; @Inject @TargetId String targetId; @@ -93,7 +85,7 @@ public final class ContactDeleteFlow implements TransactionalFlow { extensionManager.validate(); validateClientIsLoggedIn(clientId); DateTime now = ofy().getTransactionTime(); - failfastForAsyncDelete(targetId, now, ContactResource.class, GET_REFERENCED_CONTACTS); + failfastForAsyncDelete(targetId, now, ContactResource.class, DomainBase::getReferencedContacts); ContactResource existingContact = loadAndVerifyExistence(ContactResource.class, targetId, now); verifyNoDisallowedStatuses(existingContact, DISALLOWED_STATUSES); verifyOptionalAuthInfo(authInfo, existingContact); diff --git a/java/google/registry/flows/domain/DomainAllocateFlow.java b/java/google/registry/flows/domain/DomainAllocateFlow.java index 19a744a5b..b58073083 100644 --- a/java/google/registry/flows/domain/DomainAllocateFlow.java +++ b/java/google/registry/flows/domain/DomainAllocateFlow.java @@ -14,8 +14,7 @@ package google.registry.flows.domain; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.getOnlyElement; +import static com.google.common.collect.MoreCollectors.onlyElement; import static google.registry.flows.FlowUtils.validateClientIsLoggedIn; import static google.registry.flows.ResourceFlowUtils.verifyResourceDoesNotExist; import static google.registry.flows.domain.DomainFlowUtils.cloneAndLinkReferences; @@ -39,6 +38,7 @@ import static google.registry.util.DateTimeUtils.leapSafeAddYears; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Streams; import com.google.common.net.InternetDomainName; import com.googlecode.objectify.Key; import dagger.Lazy; @@ -212,7 +212,10 @@ public class DomainAllocateFlow implements TransactionalFlow { private T getOnly( Iterable objects, Class clazz) { - return getOnlyElement(filter(objects, clazz)); + return Streams.stream(objects) + .filter(clazz::isInstance) + .map(clazz::cast) + .collect(onlyElement()); } private void verifyIsSuperuser() throws OnlySuperuserCanAllocateException { diff --git a/java/google/registry/flows/domain/DomainApplicationCreateFlow.java b/java/google/registry/flows/domain/DomainApplicationCreateFlow.java index 25147280d..858822694 100644 --- a/java/google/registry/flows/domain/DomainApplicationCreateFlow.java +++ b/java/google/registry/flows/domain/DomainApplicationCreateFlow.java @@ -14,6 +14,7 @@ package google.registry.flows.domain; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static google.registry.flows.FlowUtils.persistEntityChanges; import static google.registry.flows.FlowUtils.validateClientIsLoggedIn; @@ -43,8 +44,6 @@ import static google.registry.model.index.DomainApplicationIndex.loadActiveAppli import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registry.label.ReservedList.matchesAnchorTenantReservation; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.net.InternetDomainName; @@ -94,7 +93,6 @@ import google.registry.model.registry.Registry; import google.registry.model.registry.Registry.TldState; import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.IcannReportingTypes.ActivityReportField; -import google.registry.model.smd.AbstractSignedMark; import google.registry.model.smd.EncodedSignedMark; import javax.inject.Inject; import org.joda.time.DateTime; @@ -244,32 +242,31 @@ public final class DomainApplicationCreateFlow implements TransactionalFlow { .setDomainName(domainName) .setYears(years) .build()); - DomainApplication newApplication = new DomainApplication.Builder() - .setCreationTrid(trid) - .setCreationClientId(clientId) - .setPersistedCurrentSponsorClientId(clientId) - .setRepoId(createDomainRepoId(ObjectifyService.allocateId(), tld)) - .setLaunchNotice(launchCreate == null ? null : launchCreate.getNotice()) - .setIdnTableName(idnTableName) - .setPhase(launchCreate.getPhase()) - .setPeriod(command.getPeriod()) - .setApplicationStatus(ApplicationStatus.VALIDATED) - .addStatusValue(StatusValue.PENDING_CREATE) - .setDsData(secDnsCreate == null ? null : secDnsCreate.getDsData()) - .setRegistrant(command.getRegistrant()) - .setAuthInfo(command.getAuthInfo()) - .setFullyQualifiedDomainName(targetId) - .setNameservers(command.getNameservers()) - .setContacts(command.getContacts()) - .setEncodedSignedMarks(FluentIterable - .from(launchCreate.getSignedMarks()) - .transform(new Function() { - @Override - public EncodedSignedMark apply(AbstractSignedMark abstractSignedMark) { - return (EncodedSignedMark) abstractSignedMark; - }}) - .toList()) - .build(); + DomainApplication newApplication = + new DomainApplication.Builder() + .setCreationTrid(trid) + .setCreationClientId(clientId) + .setPersistedCurrentSponsorClientId(clientId) + .setRepoId(createDomainRepoId(ObjectifyService.allocateId(), tld)) + .setLaunchNotice(launchCreate == null ? null : launchCreate.getNotice()) + .setIdnTableName(idnTableName) + .setPhase(launchCreate.getPhase()) + .setPeriod(command.getPeriod()) + .setApplicationStatus(ApplicationStatus.VALIDATED) + .addStatusValue(StatusValue.PENDING_CREATE) + .setDsData(secDnsCreate == null ? null : secDnsCreate.getDsData()) + .setRegistrant(command.getRegistrant()) + .setAuthInfo(command.getAuthInfo()) + .setFullyQualifiedDomainName(targetId) + .setNameservers(command.getNameservers()) + .setContacts(command.getContacts()) + .setEncodedSignedMarks( + launchCreate + .getSignedMarks() + .stream() + .map(abstractSignedMark -> (EncodedSignedMark) abstractSignedMark) + .collect(toImmutableList())) + .build(); HistoryEntry historyEntry = buildHistoryEntry(newApplication.getRepoId(), command.getPeriod(), now); ImmutableSet.Builder entitiesToSave = new ImmutableSet.Builder<>(); diff --git a/java/google/registry/flows/domain/DomainCheckFlow.java b/java/google/registry/flows/domain/DomainCheckFlow.java index 167c5ff55..87e410eef 100644 --- a/java/google/registry/flows/domain/DomainCheckFlow.java +++ b/java/google/registry/flows/domain/DomainCheckFlow.java @@ -28,8 +28,6 @@ import static google.registry.model.registry.label.ReservationType.getTypeOfHigh import static google.registry.pricing.PricingEngineProxy.isDomainPremium; import com.google.common.base.Optional; -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; @@ -46,7 +44,6 @@ import google.registry.flows.annotations.ReportingSpec; import google.registry.flows.custom.DomainCheckFlowCustomLogic; import google.registry.flows.custom.DomainCheckFlowCustomLogic.BeforeResponseParameters; import google.registry.flows.custom.DomainCheckFlowCustomLogic.BeforeResponseReturnData; -import google.registry.model.domain.DomainApplication; import google.registry.model.domain.DomainCommand.Check; import google.registry.model.domain.DomainResource; import google.registry.model.domain.fee.FeeCheckCommandExtension; @@ -176,12 +173,9 @@ public final class DomainCheckFlow implements Flow { } Registry registry = Registry.get(domainName.parent().toString()); if (PENDING_ALLOCATION_TLD_STATES.contains(registry.getTldState(now)) - && FluentIterable.from(loadActiveApplicationsByDomainName(domainName.toString(), now)) - .anyMatch(new Predicate() { - @Override - public boolean apply(DomainApplication input) { - return !input.getApplicationStatus().isFinalStatus(); - }})) { + && loadActiveApplicationsByDomainName(domainName.toString(), now) + .stream() + .anyMatch(input -> !input.getApplicationStatus().isFinalStatus())) { return Optional.of("Pending allocation"); } ImmutableSet reservationTypes = getReservationTypes(domainName); diff --git a/java/google/registry/flows/domain/DomainFlowUtils.java b/java/google/registry/flows/domain/DomainFlowUtils.java index bc21e9f45..e78ddd1c0 100644 --- a/java/google/registry/flows/domain/DomainFlowUtils.java +++ b/java/google/registry/flows/domain/DomainFlowUtils.java @@ -41,13 +41,12 @@ import static google.registry.util.DomainNameUtils.ACE_PREFIX; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.base.Splitter; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; +import com.google.common.collect.Streams; import com.google.common.net.InternetDomainName; import com.googlecode.objectify.Key; import google.registry.flows.EppException; @@ -940,24 +939,22 @@ public class DomainFlowUtils { .order("modificationTime") .list(); Optional entryToCancel = - FluentIterable.from(recentHistoryEntries) - .filter( - new Predicate() { - @Override - public boolean apply(HistoryEntry historyEntry) { - // Look for add and renew transaction records that have yet to be reported - for (DomainTransactionRecord record : - historyEntry.getDomainTransactionRecords()) { - if (cancelableFields.contains(record.getReportField()) - && record.getReportingTime().isAfter(now)) { - return true; - } - } - return false; - } - }) - // We only want to cancel out the most recent add or renewal - .last(); + Optional.fromJavaUtil( + Streams.findLast( + recentHistoryEntries + .stream() + .filter( + historyEntry -> { + // Look for add and renew transaction records that have yet to be reported + for (DomainTransactionRecord record : + historyEntry.getDomainTransactionRecords()) { + if (cancelableFields.contains(record.getReportField()) + && record.getReportingTime().isAfter(now)) { + return true; + } + } + return false; + }))); ImmutableSet.Builder recordsBuilder = new ImmutableSet.Builder<>(); if (entryToCancel.isPresent()) { for (DomainTransactionRecord record : entryToCancel.get().getDomainTransactionRecords()) { diff --git a/java/google/registry/flows/domain/DomainTransferUtils.java b/java/google/registry/flows/domain/DomainTransferUtils.java index 98c2ad430..9b977055a 100644 --- a/java/google/registry/flows/domain/DomainTransferUtils.java +++ b/java/google/registry/flows/domain/DomainTransferUtils.java @@ -14,8 +14,8 @@ package google.registry.flows.domain; -import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.getOnlyElement; +import static com.google.common.collect.MoreCollectors.onlyElement; import static google.registry.util.DateTimeUtils.END_OF_TIME; import com.google.common.base.Optional; @@ -61,14 +61,29 @@ public final class DomainTransferUtils { if (transferPeriod.getValue() != 0) { // Unless superuser sets period to 0, add a transfer billing event. transferDataBuilder.setServerApproveBillingEvent( - Key.create(getOnlyElement(filter(serverApproveEntities, BillingEvent.OneTime.class)))); + Key.create( + serverApproveEntities + .stream() + .filter(BillingEvent.OneTime.class::isInstance) + .map(BillingEvent.OneTime.class::cast) + .collect(onlyElement()))); } return transferDataBuilder .setTransferStatus(TransferStatus.PENDING) - .setServerApproveAutorenewEvent(Key.create( - getOnlyElement(filter(serverApproveEntities, BillingEvent.Recurring.class)))) - .setServerApproveAutorenewPollMessage(Key.create( - getOnlyElement(filter(serverApproveEntities, PollMessage.Autorenew.class)))) + .setServerApproveAutorenewEvent( + Key.create( + serverApproveEntities + .stream() + .filter(BillingEvent.Recurring.class::isInstance) + .map(BillingEvent.Recurring.class::cast) + .collect(onlyElement()))) + .setServerApproveAutorenewPollMessage( + Key.create( + serverApproveEntities + .stream() + .filter(PollMessage.Autorenew.class::isInstance) + .map(PollMessage.Autorenew.class::cast) + .collect(onlyElement()))) .setServerApproveEntities(serverApproveEntityKeys.build()) .setTransferPeriod(transferPeriod) .build(); diff --git a/java/google/registry/flows/domain/FeesAndCredits.java b/java/google/registry/flows/domain/FeesAndCredits.java index 8c052afde..e9daa7d84 100644 --- a/java/google/registry/flows/domain/FeesAndCredits.java +++ b/java/google/registry/flows/domain/FeesAndCredits.java @@ -14,7 +14,7 @@ package google.registry.flows.domain; -import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; @@ -26,6 +26,7 @@ import google.registry.model.domain.fee.BaseFee; import google.registry.model.domain.fee.BaseFee.FeeType; import google.registry.model.domain.fee.Credit; import google.registry.model.domain.fee.Fee; +import java.util.stream.Stream; import org.joda.money.CurrencyUnit; import org.joda.money.Money; @@ -102,7 +103,7 @@ public class FeesAndCredits extends ImmutableObject implements Buildable { /** Returns all fees and credits for the event. */ public ImmutableList getFeesAndCredits() { - return ImmutableList.copyOf(concat(getFees(), getCredits())); + return Stream.concat(getFees().stream(), getCredits().stream()).collect(toImmutableList()); } @Override diff --git a/java/google/registry/flows/host/HostDeleteFlow.java b/java/google/registry/flows/host/HostDeleteFlow.java index 88337b5e0..efecca560 100644 --- a/java/google/registry/flows/host/HostDeleteFlow.java +++ b/java/google/registry/flows/host/HostDeleteFlow.java @@ -23,7 +23,6 @@ import static google.registry.flows.host.HostFlowUtils.validateHostName; import static google.registry.model.eppoutput.Result.Code.SUCCESS_WITH_ACTION_PENDING; import static google.registry.model.ofy.ObjectifyService.ofy; -import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.googlecode.objectify.Key; import google.registry.flows.EppException; @@ -71,13 +70,6 @@ public final class HostDeleteFlow implements TransactionalFlow { StatusValue.PENDING_DELETE, StatusValue.SERVER_DELETE_PROHIBITED); - private static final Function> GET_NAMESERVERS = - new Function>() { - @Override - public ImmutableSet apply(DomainBase domain) { - return domain.getNameservers(); - }}; - @Inject ExtensionManager extensionManager; @Inject @ClientId String clientId; @Inject @TargetId String targetId; @@ -95,7 +87,7 @@ public final class HostDeleteFlow implements TransactionalFlow { validateClientIsLoggedIn(clientId); DateTime now = ofy().getTransactionTime(); validateHostName(targetId); - failfastForAsyncDelete(targetId, now, HostResource.class, GET_NAMESERVERS); + failfastForAsyncDelete(targetId, now, HostResource.class, DomainBase::getNameservers); HostResource existingHost = loadAndVerifyExistence(HostResource.class, targetId, now); verifyNoDisallowedStatuses(existingHost, DISALLOWED_STATUSES); if (!isSuperuser) { diff --git a/java/google/registry/flows/host/HostFlowUtils.java b/java/google/registry/flows/host/HostFlowUtils.java index 37a2befa9..1a358f3e7 100644 --- a/java/google/registry/flows/host/HostFlowUtils.java +++ b/java/google/registry/flows/host/HostFlowUtils.java @@ -18,11 +18,10 @@ import static google.registry.model.EppResourceUtils.isActive; import static google.registry.model.EppResourceUtils.loadByForeignKey; import static google.registry.model.registry.Registries.findTldForName; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; +import static java.util.stream.Collectors.joining; import com.google.common.base.Ascii; -import com.google.common.base.Joiner; import com.google.common.base.Optional; -import com.google.common.collect.Iterables; import com.google.common.net.InternetDomainName; import google.registry.flows.EppException; import google.registry.flows.EppException.AuthorizationErrorException; @@ -98,8 +97,12 @@ public class HostFlowUtils { return Optional.absent(); } // This is a subordinate host - String domainName = Joiner.on('.').join(Iterables.skip( - hostName.parts(), hostName.parts().size() - (tld.get().parts().size() + 1))); + String domainName = + hostName + .parts() + .stream() + .skip(hostName.parts().size() - (tld.get().parts().size() + 1)) + .collect(joining(".")); DomainResource superordinateDomain = loadByForeignKey(DomainResource.class, domainName, now); if (superordinateDomain == null || !isActive(superordinateDomain, now)) { throw new SuperordinateDomainDoesNotExistException(domainName); diff --git a/java/google/registry/keyring/kms/KmsConnectionImpl.java b/java/google/registry/keyring/kms/KmsConnectionImpl.java index 480e02ee1..e51d409f8 100644 --- a/java/google/registry/keyring/kms/KmsConnectionImpl.java +++ b/java/google/registry/keyring/kms/KmsConnectionImpl.java @@ -29,7 +29,6 @@ import google.registry.config.RegistryConfig.Config; import google.registry.keyring.api.KeyringException; import google.registry.util.Retrier; import java.io.IOException; -import java.util.concurrent.Callable; import javax.inject.Inject; /** The {@link KmsConnection} which talks to Cloud KMS. */ @@ -137,13 +136,7 @@ class KmsConnectionImpl implements KmsConnection { public byte[] decrypt(final String cryptoKeyName, final String encodedCiphertext) { try { return retrier.callWithRetry( - new Callable() { - @Override - public byte[] call() throws IOException { - return attemptDecrypt(cryptoKeyName, encodedCiphertext); - } - }, - IOException.class); + () -> attemptDecrypt(cryptoKeyName, encodedCiphertext), IOException.class); } catch (RuntimeException e) { throw new KeyringException( String.format("CloudKMS decrypt operation failed for secret %s", cryptoKeyName), e); diff --git a/java/google/registry/loadtest/LoadTestAction.java b/java/google/registry/loadtest/LoadTestAction.java index e0765c954..6af3bbeb3 100644 --- a/java/google/registry/loadtest/LoadTestAction.java +++ b/java/google/registry/loadtest/LoadTestAction.java @@ -17,6 +17,7 @@ package google.registry.loadtest; import static com.google.appengine.api.taskqueue.QueueConstants.maxTasksPerAdd; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Lists.partition; import static com.google.common.collect.Lists.transform; import static google.registry.security.XsrfTokenManager.X_CSRF_TOKEN; @@ -27,7 +28,6 @@ import static org.joda.time.DateTimeZone.UTC; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import google.registry.config.RegistryEnvironment; @@ -247,12 +247,12 @@ public class LoadTestAction implements Runnable { startSecond)); tasks.addAll( createTasks( - FluentIterable.from( - createNumCopies(xmlDomainCreateTmpl, successfulDomainCreatesPerSecond)) - .transform(randomNameReplacer("%domain%", MAX_DOMAIN_LABEL_LENGTH)) - .transform(listNameReplacer("%contact%", contactNames)) - .transform(listNameReplacer("%host%", hostPrefixes)) - .toList(), + createNumCopies(xmlDomainCreateTmpl, successfulDomainCreatesPerSecond) + .stream() + .map(randomNameReplacer("%domain%", MAX_DOMAIN_LABEL_LENGTH)) + .map(listNameReplacer("%contact%", contactNames)) + .map(listNameReplacer("%host%", hostPrefixes)) + .collect(toImmutableList()), startSecond)); } ImmutableList taskOptions = tasks.build(); @@ -308,19 +308,11 @@ public class LoadTestAction implements Runnable { private Function listNameReplacer(final String toReplace, List choices) { final Iterator iterator = Iterators.cycle(choices); - return new Function() { - @Override - public String apply(String xml) { - return xml.replace(toReplace, iterator.next()); - }}; + return xml -> xml.replace(toReplace, iterator.next()); } private Function randomNameReplacer(final String toReplace, final int numChars) { - return new Function() { - @Override - public String apply(String xml) { - return xml.replace(toReplace, getRandomLabel(numChars)); - }}; + return xml -> xml.replace(toReplace, getRandomLabel(numChars)); } private String getRandomLabel(int numChars) { diff --git a/java/google/registry/mapreduce/inputs/CommitLogManifestReader.java b/java/google/registry/mapreduce/inputs/CommitLogManifestReader.java index a968277e6..bc440e93f 100644 --- a/java/google/registry/mapreduce/inputs/CommitLogManifestReader.java +++ b/java/google/registry/mapreduce/inputs/CommitLogManifestReader.java @@ -30,7 +30,6 @@ import google.registry.util.FormattingLogger; import google.registry.util.Retrier; import google.registry.util.SystemSleeper; import java.util.NoSuchElementException; -import java.util.concurrent.Callable; import org.joda.time.DateTime; /** {@link InputReader} that maps over {@link CommitLogManifest}. */ @@ -138,12 +137,7 @@ class CommitLogManifestReader extends InputReader> { final Cursor currentCursor = queryIterator.getCursor(); try { return retrier.callWithRetry( - new Callable>() { - @Override - public Key call() { - return queryIterator.next(); - } - }, + () -> queryIterator.next(), new Retrier.FailureReporter() { @Override public void beforeRetry(Throwable thrown, int failures, int maxAttempts) { @@ -155,8 +149,7 @@ class CommitLogManifestReader extends InputReader> { public void afterFinalFailure(Throwable thrown, int failures) { logger.severefmt( "Max retry attempts reached trying to read item %d/%d. Giving up.", - loaded, - total); + loaded, total); } }, DatastoreTimeoutException.class); diff --git a/java/google/registry/mapreduce/inputs/EppResourceBaseReader.java b/java/google/registry/mapreduce/inputs/EppResourceBaseReader.java index 1274adcbb..8862a2a3e 100644 --- a/java/google/registry/mapreduce/inputs/EppResourceBaseReader.java +++ b/java/google/registry/mapreduce/inputs/EppResourceBaseReader.java @@ -14,13 +14,13 @@ package google.registry.mapreduce.inputs; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.EntityClasses.CLASS_TO_KIND_FUNCTION; import static google.registry.model.ofy.ObjectifyService.ofy; import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.datastore.QueryResultIterator; import com.google.appengine.tools.mapreduce.InputReader; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.googlecode.objectify.Key; import com.googlecode.objectify.cmd.Query; @@ -137,7 +137,7 @@ abstract class EppResourceBaseReader extends InputReader { ImmutableSet> resourceClasses) { // Ignore EppResource when finding kinds, since it doesn't have one and doesn't imply filtering. return resourceClasses.contains(EppResource.class) - ? ImmutableSet.of() - : FluentIterable.from(resourceClasses).transform(CLASS_TO_KIND_FUNCTION).toSet(); + ? ImmutableSet.of() + : resourceClasses.stream().map(CLASS_TO_KIND_FUNCTION).collect(toImmutableSet()); } } diff --git a/java/google/registry/model/EntityClasses.java b/java/google/registry/model/EntityClasses.java index bfaf77eae..f15a9ebdb 100644 --- a/java/google/registry/model/EntityClasses.java +++ b/java/google/registry/model/EntityClasses.java @@ -116,17 +116,12 @@ public final class EntityClasses { /** * Function that converts an Objectify-registered class to its Datastore kind name. * - *

Note that this mapping is not one-to-one, since polymorphic subclasses of an entity all - * have the same Datastore kind. (In theory, two distinct top-level entities could also map to - * the same kind since it's just {@code class.getSimpleName()}, but we test against that.) + *

Note that this mapping is not one-to-one, since polymorphic subclasses of an entity all have + * the same Datastore kind. (In theory, two distinct top-level entities could also map to the same + * kind since it's just {@code class.getSimpleName()}, but we test against that.) */ public static final Function, String> CLASS_TO_KIND_FUNCTION = - new Function, String>() { - @Override - public String apply(Class clazz) { - return Key.getKind(clazz); - } - }; + (Class clazz) -> Key.getKind(clazz); private EntityClasses() {} } diff --git a/java/google/registry/model/EppResourceUtils.java b/java/google/registry/model/EppResourceUtils.java index 50f515107..b2a856419 100644 --- a/java/google/registry/model/EppResourceUtils.java +++ b/java/google/registry/model/EppResourceUtils.java @@ -172,11 +172,7 @@ public final class EppResourceUtils { * Iterables.transform() over a collection of EppResources. */ public static Function transformAtTime(final DateTime now) { - return new Function() { - @Override - public T apply(T resource) { - return cloneProjectedAtTime(resource, now); - }}; + return (T resource) -> cloneProjectedAtTime(resource, now); } /** diff --git a/java/google/registry/model/ImmutableObject.java b/java/google/registry/model/ImmutableObject.java index 5c83bb9ca..ca0b91683 100644 --- a/java/google/registry/model/ImmutableObject.java +++ b/java/google/registry/model/ImmutableObject.java @@ -14,6 +14,8 @@ package google.registry.model; +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Maps.transformValues; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -22,7 +24,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.common.base.Function; import com.google.common.base.Joiner; -import com.google.common.collect.FluentIterable; import com.google.common.collect.Maps; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Ignore; @@ -157,30 +158,33 @@ public abstract class ImmutableObject implements Cloneable { }}; /** Helper function to recursively convert a ImmutableObject to a Map of generic objects. */ - private static final Function TO_MAP_HELPER = new Function() { - @Override - public Object apply(Object o) { - if (o == null) { - return null; - } else if (o instanceof ImmutableObject) { - // LinkedHashMap to preserve field ordering and because ImmutableMap forbids null values. - Map result = new LinkedHashMap<>(); - for (Entry entry : ModelUtils.getFieldValues(o).entrySet()) { - result.put(entry.getKey().getName(), apply(entry.getValue())); + private static final Function TO_MAP_HELPER = + new Function() { + @Override + public Object apply(Object o) { + if (o == null) { + return null; + } else if (o instanceof ImmutableObject) { + // LinkedHashMap to preserve field ordering and because ImmutableMap forbids null + // values. + Map result = new LinkedHashMap<>(); + for (Entry entry : ModelUtils.getFieldValues(o).entrySet()) { + result.put(entry.getKey().getName(), apply(entry.getValue())); + } + return result; + } else if (o instanceof Map) { + return Maps.transformValues((Map) o, this); + } else if (o instanceof Set) { + return ((Set) o).stream().map(this).collect(toImmutableSet()); + } else if (o instanceof Collection) { + return ((Collection) o).stream().map(this).collect(toImmutableList()); + } else if (o instanceof Number || o instanceof Boolean) { + return o; + } else { + return o.toString(); + } } - return result; - } else if (o instanceof Map) { - return Maps.transformValues((Map) o, this); - } else if (o instanceof Set) { - return FluentIterable.from((Set) o).transform(this).toSet(); - } else if (o instanceof Collection) { - return FluentIterable.from((Collection) o).transform(this).toList(); - } else if (o instanceof Number || o instanceof Boolean) { - return o; - } else { - return o.toString(); - } - }}; + }; /** Returns a map of all object fields (including sensitive data) that's used to produce diffs. */ @SuppressWarnings("unchecked") diff --git a/java/google/registry/model/JsonMapBuilder.java b/java/google/registry/model/JsonMapBuilder.java index 16f2a599f..7424ccb58 100644 --- a/java/google/registry/model/JsonMapBuilder.java +++ b/java/google/registry/model/JsonMapBuilder.java @@ -14,9 +14,10 @@ package google.registry.model; -import com.google.common.base.Function; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.google.common.base.Functions; -import com.google.common.collect.FluentIterable; +import com.google.common.collect.Streams; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -29,14 +30,6 @@ import javax.annotation.Nullable; * list is passed as {@code null}, it'll be substituted with empty list. Lists are not mutable. */ public final class JsonMapBuilder { - - private static final Function> TO_JSON_OBJECT = - new Function>() { - @Override - public Map apply(Jsonifiable input) { - return input.toJsonMap(); - }}; - private final Map map = new LinkedHashMap<>(); public JsonMapBuilder put(String name, @Nullable Boolean value) { @@ -70,15 +63,21 @@ public final class JsonMapBuilder { } public JsonMapBuilder putListOfStrings(String name, @Nullable Iterable value) { - map.put(name, value == null ? Collections.EMPTY_LIST - : FluentIterable.from(value).transform(Functions.toStringFunction()).toList()); + map.put( + name, + value == null + ? Collections.EMPTY_LIST + : Streams.stream(value).map(Functions.toStringFunction()).collect(toImmutableList())); return this; } public JsonMapBuilder putListOfJsonObjects( String name, @Nullable Iterable value) { - map.put(name, value == null ? Collections.EMPTY_LIST - : FluentIterable.from(value).transform(TO_JSON_OBJECT).toList()); + map.put( + name, + value == null + ? Collections.EMPTY_LIST + : Streams.stream(value).map(Jsonifiable::toJsonMap).collect(toImmutableList())); return this; } diff --git a/java/google/registry/model/ModelUtils.java b/java/google/registry/model/ModelUtils.java index 7a7b1e5f4..fef76d030 100644 --- a/java/google/registry/model/ModelUtils.java +++ b/java/google/registry/model/ModelUtils.java @@ -17,7 +17,6 @@ package google.registry.model; import static com.google.common.base.Predicates.instanceOf; import static com.google.common.base.Predicates.isNull; import static com.google.common.base.Predicates.or; -import static com.google.common.collect.Iterables.all; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.Sets.newLinkedHashSet; @@ -34,6 +33,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Ordering; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Ignore; @@ -95,25 +95,21 @@ public class ModelUtils { body = FluentIterable.from(clazz.getEnumConstants()); } else { stringBuilder.append("class "); - body = FluentIterable.from(getAllFields(clazz).values()) - .filter(new Predicate() { - @Override - public boolean apply(Field field) { - return !field.isAnnotationPresent(Ignore.class); - }}) - .transform(new Function() { - @Override - public Object apply(Field field) { - String annotation = field.isAnnotationPresent(Id.class) - ? "@Id " - : field.isAnnotationPresent(Parent.class) - ? "@Parent " - : ""; - String type = field.getType().isArray() - ? field.getType().getComponentType().getName() + "[]" - : field.getGenericType().toString().replaceFirst("class ", ""); - return String.format("%s%s %s", annotation, type, field.getName()); - }}); + body = + FluentIterable.from(getAllFields(clazz).values()) + .filter((Field field) -> !field.isAnnotationPresent(Ignore.class)) + .transform( + (Field field) -> { + String annotation = + field.isAnnotationPresent(Id.class) + ? "@Id " + : field.isAnnotationPresent(Parent.class) ? "@Parent " : ""; + String type = + field.getType().isArray() + ? field.getType().getComponentType().getName() + "[]" + : field.getGenericType().toString().replaceFirst("class ", ""); + return String.format("%s%s %s", annotation, type, field.getName()); + }); } return stringBuilder .append(clazz.getName()).append(" {\n ") @@ -212,45 +208,48 @@ public class ModelUtils { } /** Functional helper for {@link #cloneEmptyToNull}. */ - private static final Function CLONE_EMPTY_TO_NULL = new Function() { - @Override - public Object apply(Object obj) { - if (obj instanceof ImmutableSortedMap) { - // ImmutableSortedMapTranslatorFactory handles empty for us. If the object is null, then - // its on-save hook can't run. + private static final Function CLONE_EMPTY_TO_NULL = + new Function() { + @Override + public Object apply(Object obj) { + if (obj instanceof ImmutableSortedMap) { + // ImmutableSortedMapTranslatorFactory handles empty for us. If the object is null, then + // its on-save hook can't run. + return obj; + } + if ("".equals(obj) + || (obj instanceof Collection && ((Collection) obj).isEmpty()) + || (obj instanceof Map && ((Map) obj).isEmpty()) + || (obj != null && obj.getClass().isArray() && Array.getLength(obj) == 0)) { + return null; + } + Predicate immutableObjectOrNull = or(isNull(), instanceOf(ImmutableObject.class)); + if ((obj instanceof Set || obj instanceof List) + && Streams.stream((Iterable) obj).allMatch(immutableObjectOrNull)) { + // Recurse into sets and lists, but only if they contain ImmutableObjects. + FluentIterable fluent = FluentIterable.from((Iterable) obj).transform(this); + return (obj instanceof List) ? newArrayList(fluent) : newLinkedHashSet(fluent); + } + if (obj instanceof Map + && ((Map) obj).values().stream().allMatch(immutableObjectOrNull)) { + // Recurse into maps with ImmutableObject values. + return transformValues((Map) obj, this); + } + if (obj instanceof ImmutableObject) { + // Recurse on the fields of an ImmutableObject. + ImmutableObject copy = ImmutableObject.clone((ImmutableObject) obj); + for (Field field : getAllFields(obj.getClass()).values()) { + Object oldValue = getFieldValue(obj, field); + Object newValue = apply(oldValue); + if (!Objects.equals(oldValue, newValue)) { + setFieldValue(copy, field, newValue); + } + } + return copy; + } return obj; } - if ("".equals(obj) - || (obj instanceof Collection && ((Collection) obj).isEmpty()) - || (obj instanceof Map && ((Map) obj).isEmpty()) - || (obj != null && obj.getClass().isArray() && Array.getLength(obj) == 0)) { - return null; - } - Predicate immutableObjectOrNull = or(isNull(), instanceOf(ImmutableObject.class)); - if ((obj instanceof Set || obj instanceof List) - && all((Iterable) obj, immutableObjectOrNull)) { - // Recurse into sets and lists, but only if they contain ImmutableObjects. - FluentIterable fluent = FluentIterable.from((Iterable) obj).transform(this); - return (obj instanceof List) ? newArrayList(fluent) : newLinkedHashSet(fluent); - } - if (obj instanceof Map && all(((Map) obj).values(), immutableObjectOrNull)) { - // Recurse into maps with ImmutableObject values. - return transformValues((Map) obj, this); - } - if (obj instanceof ImmutableObject) { - // Recurse on the fields of an ImmutableObject. - ImmutableObject copy = ImmutableObject.clone((ImmutableObject) obj); - for (Field field : getAllFields(obj.getClass()).values()) { - Object oldValue = getFieldValue(obj, field); - Object newValue = apply(oldValue); - if (!Objects.equals(oldValue, newValue)) { - setFieldValue(copy, field, newValue); - } - } - return copy; - } - return obj; - }}; + }; /** Returns a clone of the object and sets empty collections, arrays, maps and strings to null. */ @SuppressWarnings("unchecked") diff --git a/java/google/registry/model/SchemaVersion.java b/java/google/registry/model/SchemaVersion.java index 2facdc083..44c4ba4fa 100644 --- a/java/google/registry/model/SchemaVersion.java +++ b/java/google/registry/model/SchemaVersion.java @@ -16,10 +16,8 @@ package google.registry.model; import static com.google.common.base.Predicates.or; import static com.google.common.base.Predicates.subtypeOf; +import static java.util.stream.Collectors.joining; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.collect.FluentIterable; import com.google.common.collect.Ordering; import java.util.ArrayDeque; import java.util.Queue; @@ -60,14 +58,11 @@ public final class SchemaVersion { * types (for classes), or else a list of all possible values (for enums). */ public static String getSchema() { - return FluentIterable.from(getAllPersistedTypes()) + return getAllPersistedTypes() + .stream() .filter(or(subtypeOf(Enum.class), subtypeOf(ImmutableObject.class))) - .transform(new Function, String>() { - @Override - public String apply(Class clazz) { - return ModelUtils.getSchema(clazz); - }}) - .join(Joiner.on('\n')); + .map(ModelUtils::getSchema) + .collect(joining("\n")); } private SchemaVersion() {} diff --git a/java/google/registry/model/billing/RegistrarBillingUtils.java b/java/google/registry/model/billing/RegistrarBillingUtils.java index ec9296512..0e8d22400 100644 --- a/java/google/registry/model/billing/RegistrarBillingUtils.java +++ b/java/google/registry/model/billing/RegistrarBillingUtils.java @@ -14,15 +14,13 @@ package google.registry.model.billing; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static google.registry.model.ofy.ObjectifyService.ofy; -import com.google.common.base.Function; import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Maps; -import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.Ordering; import com.googlecode.objectify.cmd.Query; import google.registry.model.CacheUtils; @@ -38,19 +36,11 @@ public final class RegistrarBillingUtils { private static final Supplier> CURRENCIES_CACHE = CacheUtils.memoizeWithShortExpiration( - new Supplier>() { - @Override - public ImmutableSortedSet get() { - return FluentIterable - .from(Registries.getTlds()) - .transform(new Function() { - @Override - public CurrencyUnit apply(String tld) { - return Registry.get(tld).getCurrency(); - }}) - .toSortedSet(Ordering.natural()); - } - }); + () -> + Registries.getTlds() + .stream() + .map((String tld) -> Registry.get(tld).getCurrency()) + .collect(toImmutableSortedSet(Ordering.natural()))); /** * Returns set of currencies in which registrars may be billed. @@ -69,28 +59,25 @@ public final class RegistrarBillingUtils { */ public static ImmutableMap> getBillingEntryQueries( final Registrar registrar) { - return Maps.toMap(getCurrencies(), - new Function>() { - @Override - public Query apply(CurrencyUnit currency) { - return ofy().load() + return Maps.toMap( + getCurrencies(), + (CurrencyUnit currency) -> + ofy() + .load() .type(RegistrarBillingEntry.class) .ancestor(registrar) .filter("currency", currency) - .order("-created"); - }}); + .order("-created")); } /** Returns amount of money registrar currently owes registry in each currency. */ public static Map loadBalance(Registrar registrar) { - return Maps.transformEntries(getBillingEntryQueries(registrar), - new EntryTransformer, Money>() { - @Override - public Money transformEntry( - CurrencyUnit currency, Query query) { - RegistrarBillingEntry entry = query.first().now(); - return entry != null ? entry.getBalance() : Money.zero(currency); - }}); + return Maps.transformEntries( + getBillingEntryQueries(registrar), + (CurrencyUnit currency, Query query) -> { + RegistrarBillingEntry entry = query.first().now(); + return entry != null ? entry.getBalance() : Money.zero(currency); + }); } private RegistrarBillingUtils() {} diff --git a/java/google/registry/model/billing/RegistrarCredit.java b/java/google/registry/model/billing/RegistrarCredit.java index e97704d7e..f2dbf9a79 100644 --- a/java/google/registry/model/billing/RegistrarCredit.java +++ b/java/google/registry/model/billing/RegistrarCredit.java @@ -16,15 +16,16 @@ package google.registry.model.billing; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registry.Registries.assertTldExists; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.ComparisonChain; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; @@ -216,7 +217,8 @@ public final class RegistrarCredit extends ImmutableObject implements Buildable *

The resulting list sorts the credits first by type and then by creation time. */ public static ImmutableList loadAllForRegistrar(Registrar registrar) { - return FluentIterable.from(ofy().load().type(RegistrarCredit.class).ancestor(registrar)) - .toSortedList(CREDIT_PRIORITY_ORDERING); + return Streams.stream(ofy().load().type(RegistrarCredit.class).ancestor(registrar)) + .sorted(CREDIT_PRIORITY_ORDERING) + .collect(toImmutableList()); } } diff --git a/java/google/registry/model/billing/RegistrarCreditBalance.java b/java/google/registry/model/billing/RegistrarCreditBalance.java index 09f3a4c1c..7920e79b6 100644 --- a/java/google/registry/model/billing/RegistrarCreditBalance.java +++ b/java/google/registry/model/billing/RegistrarCreditBalance.java @@ -20,7 +20,6 @@ import static com.google.common.base.Preconditions.checkState; import static google.registry.model.ofy.ObjectifyService.ofy; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.ForwardingNavigableMap; import com.google.common.collect.ImmutableSortedMap; @@ -193,16 +192,12 @@ public final class RegistrarCreditBalance extends ImmutableObject implements Bui */ @VisibleForTesting BalanceMap(Map> data) { - delegate = ImmutableSortedMap.copyOf( - Maps.transformValues( - data, - new Function, ImmutableSortedMap>() { - @Override - public ImmutableSortedMap apply(Map map) { - return ImmutableSortedMap.copyOf(map, Ordering.natural()); - } - }), - Ordering.natural()); + delegate = + ImmutableSortedMap.copyOf( + Maps.transformValues( + data, + (Map map) -> ImmutableSortedMap.copyOf(map, Ordering.natural())), + Ordering.natural()); } @Override diff --git a/java/google/registry/model/common/TimeOfYear.java b/java/google/registry/model/common/TimeOfYear.java index 60b57a74f..f08a80908 100644 --- a/java/google/registry/model/common/TimeOfYear.java +++ b/java/google/registry/model/common/TimeOfYear.java @@ -21,7 +21,6 @@ import static google.registry.util.DateTimeUtils.isAtOrAfter; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static org.joda.time.DateTimeZone.UTC; -import com.google.common.base.Function; import com.google.common.base.Splitter; import com.google.common.collect.ContiguousSet; import com.google.common.collect.FluentIterable; @@ -85,11 +84,7 @@ public class TimeOfYear extends ImmutableObject { normalizedRange.lowerEndpoint().getYear(), normalizedRange.upperEndpoint().getYear()); return FluentIterable.from(ContiguousSet.create(yearRange, integers())) - .transform(new Function() { - @Override - public DateTime apply(Integer year) { - return getDateTimeWithYear(year); - }}) + .transform(this::getDateTimeWithYear) .filter(normalizedRange); } diff --git a/java/google/registry/model/common/TimedTransitionProperty.java b/java/google/registry/model/common/TimedTransitionProperty.java index e82ac5669..c25f4602e 100644 --- a/java/google/registry/model/common/TimedTransitionProperty.java +++ b/java/google/registry/model/common/TimedTransitionProperty.java @@ -20,7 +20,6 @@ import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.latestOf; -import com.google.common.base.Function; import com.google.common.collect.ForwardingMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSortedMap; @@ -103,18 +102,17 @@ public class TimedTransitionProperty() { - // For each entry in the input value map, make the output map have an entry at the - // corresponding time that points to a transition containing that time and that value. - @Override - public T transformEntry(DateTime transitionTime, V value) { - checkArgument(!transitionTime.isBefore(START_OF_TIME), + return Maps.transformEntries( + valueMap, + (DateTime transitionTime, V value) -> { + checkArgument( + !transitionTime.isBefore(START_OF_TIME), "Timed transition times cannot be earlier than START_OF_TIME / Unix Epoch"); T subclass = TypeUtils.instantiate(timedTransitionSubclass); ((TimedTransition) subclass).transitionTime = transitionTime; subclass.setValue(value); return subclass; - }}); + }); } /** @@ -288,13 +286,7 @@ public class TimedTransitionProperty toValueMap() { - return ImmutableSortedMap.copyOfSorted(Maps.transformValues( - backingMap, - new Function() { - @Override - public V apply(T timedTransition) { - return timedTransition.getValue(); - }})); + return ImmutableSortedMap.copyOfSorted(Maps.transformValues(backingMap, T::getValue)); } /** diff --git a/java/google/registry/model/contact/ContactCommand.java b/java/google/registry/model/contact/ContactCommand.java index d7640434b..aa9853595 100644 --- a/java/google/registry/model/contact/ContactCommand.java +++ b/java/google/registry/model/contact/ContactCommand.java @@ -17,7 +17,6 @@ package google.registry.model.contact; import static com.google.common.base.Preconditions.checkState; import static google.registry.util.CollectionUtils.nullToEmpty; -import com.google.common.base.Function; import com.google.common.collect.Maps; import google.registry.model.ImmutableObject; import google.registry.model.contact.PostalInfo.Type; @@ -67,11 +66,7 @@ public class ContactCommand { // There can be no more than 2 postalInfos (enforced by the schema), and if there are 2 they // must be of different types (not enforced). If the type is repeated, uniqueIndex will throw. checkState(nullToEmpty(postalInfo).size() <= 2); - return Maps.uniqueIndex(nullToEmpty(postalInfo), new Function() { - @Override - public Type apply(PostalInfo info) { - return info.getType(); - }}); + return Maps.uniqueIndex(nullToEmpty(postalInfo), PostalInfo::getType); } public ContactPhoneNumber getVoice() { diff --git a/java/google/registry/model/contact/ContactResource.java b/java/google/registry/model/contact/ContactResource.java index 7885a4854..de9e36d9c 100644 --- a/java/google/registry/model/contact/ContactResource.java +++ b/java/google/registry/model/contact/ContactResource.java @@ -15,13 +15,12 @@ package google.registry.model.contact; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.EppResourceUtils.projectResourceOntoBuilderAtTime; import com.google.common.base.Optional; import com.google.common.base.Predicates; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.IgnoreSave; import com.googlecode.objectify.annotation.Index; @@ -33,6 +32,7 @@ import google.registry.model.annotations.ExternalMessagingName; import google.registry.model.annotations.ReportedOn; import google.registry.model.contact.PostalInfo.Type; import google.registry.model.transfer.TransferData; +import java.util.stream.Stream; import javax.xml.bind.annotation.XmlElement; import org.joda.time.DateTime; @@ -170,10 +170,9 @@ public class ContactResource extends EppResource implements */ @XmlElement(name = "postalInfo") public ImmutableList getPostalInfosAsList() { - return FluentIterable - .from(Lists.newArrayList(localizedPostalInfo, internationalizedPostalInfo)) + return Stream.of(localizedPostalInfo, internationalizedPostalInfo) .filter(Predicates.notNull()) - .toList(); + .collect(toImmutableList()); } @Override diff --git a/java/google/registry/model/domain/DomainBase.java b/java/google/registry/model/domain/DomainBase.java index d96bbcc6b..4270da027 100644 --- a/java/google/registry/model/domain/DomainBase.java +++ b/java/google/registry/model/domain/DomainBase.java @@ -17,8 +17,8 @@ package google.registry.model.domain; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Predicates.not; import static com.google.common.base.Strings.emptyToNull; -import static com.google.common.collect.Iterables.all; -import static com.google.common.collect.Iterables.any; +import static com.google.common.collect.ImmutableSet.toImmutableSet; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.union; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -30,9 +30,7 @@ import static google.registry.util.DomainNameUtils.canonicalizeDomainName; import static google.registry.util.DomainNameUtils.getTldFromDomainName; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; -import com.google.common.base.Function; import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; @@ -49,6 +47,7 @@ import google.registry.model.domain.launch.LaunchNotice; import google.registry.model.domain.secdns.DelegationSignerData; import google.registry.model.host.HostResource; import java.util.Set; +import java.util.stream.Stream; /** Shared base class for {@link DomainResource} and {@link DomainApplication}. */ @ReportedOn @@ -134,33 +133,28 @@ public abstract class DomainBase extends EppResource { /** Loads and returns the fully qualified host names of all linked nameservers. */ public ImmutableSortedSet loadNameserverFullyQualifiedHostNames() { - return FluentIterable.from(ofy().load().keys(getNameservers()).values()) - .transform( - new Function() { - @Override - public String apply(HostResource host) { - return host.getFullyQualifiedHostName(); - } - }) - .toSortedSet(Ordering.natural()); + return ofy() + .load() + .keys(getNameservers()) + .values() + .stream() + .map(HostResource::getFullyQualifiedHostName) + .collect(toImmutableSortedSet(Ordering.natural())); } /** A key to the registrant who registered this domain. */ public Key getRegistrant() { - return FluentIterable - .from(nullToEmpty(allContacts)) + return nullToEmpty(allContacts) + .stream() .filter(IS_REGISTRANT) - .first() + .findFirst() .get() .getContactKey(); } /** Associated contacts for the domain (other than registrant). */ public ImmutableSet getContacts() { - return FluentIterable - .from(nullToEmpty(allContacts)) - .filter(not(IS_REGISTRANT)) - .toSet(); + return nullToEmpty(allContacts).stream().filter(not(IS_REGISTRANT)).collect(toImmutableSet()); } public DomainAuthInfo getAuthInfo() { @@ -183,11 +177,7 @@ public abstract class DomainBase extends EppResource { /** Predicate to determine if a given {@link DesignatedContact} is the registrant. */ private static final Predicate IS_REGISTRANT = - new Predicate() { - @Override - public boolean apply(DesignatedContact contact) { - return DesignatedContact.Type.REGISTRANT.equals(contact.type); - }}; + (DesignatedContact contact) -> DesignatedContact.Type.REGISTRANT.equals(contact.type); /** An override of {@link EppResource#asBuilder} with tighter typing. */ @Override @@ -208,7 +198,7 @@ public abstract class DomainBase extends EppResource { T instance = getInstance(); checkArgumentNotNull( emptyToNull(instance.fullyQualifiedDomainName), "Missing fullyQualifiedDomainName"); - checkArgument(any(instance.allContacts, IS_REGISTRANT), "Missing registrant"); + checkArgument(instance.allContacts.stream().anyMatch(IS_REGISTRANT), "Missing registrant"); instance.tld = getTldFromDomainName(instance.fullyQualifiedDomainName); return super.build(); } @@ -255,13 +245,13 @@ public abstract class DomainBase extends EppResource { } public B setContacts(ImmutableSet contacts) { - checkArgument(all(contacts, not(IS_REGISTRANT)), "Registrant cannot be a contact"); + checkArgument(contacts.stream().noneMatch(IS_REGISTRANT), "Registrant cannot be a contact"); // Replace the non-registrant contacts inside allContacts. - getInstance().allContacts = FluentIterable - .from(nullToEmpty(getInstance().allContacts)) - .filter(IS_REGISTRANT) - .append(contacts) - .toSet(); + getInstance().allContacts = + Stream.concat( + nullToEmpty(getInstance().allContacts).stream().filter(IS_REGISTRANT), + contacts.stream()) + .collect(toImmutableSet()); return thisCastToDerived(); } diff --git a/java/google/registry/model/domain/DomainCommand.java b/java/google/registry/model/domain/DomainCommand.java index 33b6db8f4..0a63eb9ec 100644 --- a/java/google/registry/model/domain/DomainCommand.java +++ b/java/google/registry/model/domain/DomainCommand.java @@ -27,7 +27,6 @@ import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; import static google.registry.util.CollectionUtils.union; -import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -458,13 +457,7 @@ public class DomainCommand { throw new InvalidReferencesException( clazz, ImmutableSet.copyOf(difference(foreignKeys, fkis.keySet()))); } - return ImmutableMap.copyOf(transformValues( - fkis, - new Function, Key>() { - @Override - public Key apply(ForeignKeyIndex fki) { - return fki.getResourceKey(); - }})); + return ImmutableMap.copyOf(transformValues(fkis, ForeignKeyIndex::getResourceKey)); } /** Exception to throw when referenced objects don't exist. */ diff --git a/java/google/registry/model/domain/rgp/GracePeriodStatus.java b/java/google/registry/model/domain/rgp/GracePeriodStatus.java index ab0c85a6f..91aae76ba 100644 --- a/java/google/registry/model/domain/rgp/GracePeriodStatus.java +++ b/java/google/registry/model/domain/rgp/GracePeriodStatus.java @@ -16,14 +16,12 @@ package google.registry.model.domain.rgp; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.not; -import static java.util.Arrays.asList; +import static com.google.common.collect.ImmutableMap.toImmutableMap; -import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; import google.registry.model.translators.EnumToAttributeAdapter; import google.registry.model.translators.EnumToAttributeAdapter.EppEnum; +import java.util.stream.Stream; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @@ -101,15 +99,12 @@ public enum GracePeriodStatus implements EppEnum { /** Provide a quick lookup of GracePeriodStatus from XML name. */ private static final ImmutableMap XML_NAME_TO_GRACE_PERIOD_STATUS = - Maps.uniqueIndex( - // SUNRUSH_ADD isn't a real grace period type visible in EPP XML, so exclude it. - Iterables.filter(asList(GracePeriodStatus.values()), not(equalTo(SUNRUSH_ADD))), - new Function() { - @Override - public String apply(GracePeriodStatus gracePeriodStatus) { - return gracePeriodStatus.xmlName; - } - }); + Stream.of(GracePeriodStatus.values()) + .filter(not(equalTo(SUNRUSH_ADD))) + .collect( + toImmutableMap( + (GracePeriodStatus gracePeriodStatus) -> gracePeriodStatus.xmlName, + value -> value)); @XmlAttribute(name = "s") private final String xmlName; diff --git a/java/google/registry/model/eppcommon/ProtocolDefinition.java b/java/google/registry/model/eppcommon/ProtocolDefinition.java index cc1fb9933..5e8484275 100644 --- a/java/google/registry/model/eppcommon/ProtocolDefinition.java +++ b/java/google/registry/model/eppcommon/ProtocolDefinition.java @@ -14,11 +14,9 @@ package google.registry.model.eppcommon; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Maps.uniqueIndex; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import google.registry.model.domain.allocate.AllocateCreateExtension; @@ -98,16 +96,9 @@ public class ProtocolDefinition { } /** Converts a service extension enum to its URI. */ - private static final Function TO_URI_FUNCTION = - new Function() { - @Override - public String apply(ServiceExtension serviceExtension) { - return serviceExtension.getUri(); - }}; - /** This stores a map from URI back to the service extension enum. */ private static final ImmutableMap serviceExtensionByUri = - uniqueIndex(EnumSet.allOf(ServiceExtension.class), TO_URI_FUNCTION); + uniqueIndex(EnumSet.allOf(ServiceExtension.class), ServiceExtension::getUri); /** Returns the service extension enum associated with a URI, or null if none are associated. */ public static ServiceExtension getServiceExtensionFromUri(String uri) { @@ -116,16 +107,11 @@ public class ProtocolDefinition { /** A set of all the visible extension URIs. */ private static final ImmutableSet visibleServiceExtensionUris = - FluentIterable.from(EnumSet.allOf(ServiceExtension.class)) - .filter( - new Predicate() { - @Override - public boolean apply(ServiceExtension serviceExtension) { - return serviceExtension.getVisible(); - } - }) - .transform(TO_URI_FUNCTION) - .toSet(); + EnumSet.allOf(ServiceExtension.class) + .stream() + .filter(ServiceExtension::getVisible) + .map(ServiceExtension::getUri) + .collect(toImmutableSet()); /** Return the set of all visible service extension URIs. */ public static ImmutableSet getVisibleServiceExtensionUris() { diff --git a/java/google/registry/model/eppinput/EppInput.java b/java/google/registry/model/eppinput/EppInput.java index 7b7330900..c958b5275 100644 --- a/java/google/registry/model/eppinput/EppInput.java +++ b/java/google/registry/model/eppinput/EppInput.java @@ -19,7 +19,6 @@ import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; import com.google.common.base.Ascii; import com.google.common.base.Optional; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import google.registry.model.ImmutableObject; @@ -153,7 +152,13 @@ public class EppInput extends ImmutableObject { /** Get the extension based on type, or null. If there are multiple, it chooses the first. */ @Nullable public E getSingleExtension(Class clazz) { - return FluentIterable.from(getCommandWrapper().getExtensions()).filter(clazz).first().orNull(); + return getCommandWrapper() + .getExtensions() + .stream() + .filter(clazz::isInstance) + .map(clazz::cast) + .findFirst() + .orElse(null); } /** A tag that goes inside of an EPP {@literal }. */ diff --git a/java/google/registry/model/eppoutput/EppResponse.java b/java/google/registry/model/eppoutput/EppResponse.java index 2d0c38530..9524cbf47 100644 --- a/java/google/registry/model/eppoutput/EppResponse.java +++ b/java/google/registry/model/eppoutput/EppResponse.java @@ -17,7 +17,7 @@ package google.registry.model.eppoutput; import static google.registry.util.CollectionUtils.forceEmptyToNull; import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; -import com.google.common.collect.FluentIterable; +import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import google.registry.model.Buildable; import google.registry.model.ImmutableObject; @@ -157,7 +157,9 @@ public class EppResponse extends ImmutableObject implements ResponseOrGreeting { @Nullable public ResponseExtension getFirstExtensionOfType(Class clazz) { - return FluentIterable.from(extensions).filter(clazz).first().orNull(); + return Optional.fromJavaUtil( + extensions.stream().filter(clazz::isInstance).map(clazz::cast).findFirst()) + .orNull(); } @Nullable diff --git a/java/google/registry/model/index/ForeignKeyIndex.java b/java/google/registry/model/index/ForeignKeyIndex.java index 89e340c3a..4533aed2e 100644 --- a/java/google/registry/model/index/ForeignKeyIndex.java +++ b/java/google/registry/model/index/ForeignKeyIndex.java @@ -18,7 +18,6 @@ import static com.google.common.collect.Maps.filterValues; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.TypeUtils.instantiate; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.googlecode.objectify.Key; @@ -166,10 +165,6 @@ public abstract class ForeignKeyIndex extends BackupGroup Class clazz, Iterable foreignKeys, final DateTime now) { return filterValues( ofy().load().type(mapToFkiClass(clazz)).ids(foreignKeys), - new Predicate>() { - @Override - public boolean apply(ForeignKeyIndex fki) { - return now.isBefore(fki.deletionTime); - }}); + (ForeignKeyIndex fki) -> now.isBefore(fki.deletionTime)); } } diff --git a/java/google/registry/model/ofy/CommitLogBucket.java b/java/google/registry/model/ofy/CommitLogBucket.java index f9c737206..467b296b7 100644 --- a/java/google/registry/model/ofy/CommitLogBucket.java +++ b/java/google/registry/model/ofy/CommitLogBucket.java @@ -16,14 +16,13 @@ package google.registry.model.ofy; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.DiscreteDomain.integers; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.config.RegistryConfig.getCommitLogBucketCount; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.DateTimeUtils.START_OF_TIME; -import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.ContiguousSet; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Range; @@ -137,13 +136,10 @@ public class CommitLogBucket extends ImmutableObject implements Buildable { /** Returns all commit log bucket keys, in ascending order by bucket ID. */ public static ImmutableSet> getAllBucketKeys() { - return FluentIterable.from(getBucketIds()) - .transform(new Function>() { - @Override - public Key apply(Integer bucketId) { - return getBucketKeyUnsafe(bucketId); - }}) - .toSet(); + return getBucketIds() + .stream() + .map(CommitLogBucket::getBucketKeyUnsafe) + .collect(toImmutableSet()); } @Override diff --git a/java/google/registry/model/ofy/CommitLoggedWork.java b/java/google/registry/model/ofy/CommitLoggedWork.java index 7ff445846..1fcf50467 100644 --- a/java/google/registry/model/ofy/CommitLoggedWork.java +++ b/java/google/registry/model/ofy/CommitLoggedWork.java @@ -17,6 +17,7 @@ package google.registry.model.ofy; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Maps.filterKeys; import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.union; @@ -25,7 +26,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.googlecode.objectify.Key; @@ -150,14 +150,13 @@ class CommitLoggedWork extends VoidWork { ImmutableSet.copyOf(filterKeys(rootsForTouchedKeys, not(in(touchedKeys))).values()); manifest = CommitLogManifest.create(info.bucketKey, info.transactionTime, info.getDeletes()); final Key manifestKey = Key.create(manifest); - mutations = FluentIterable - .from(union(info.getSaves(), untouchedRootsWithTouchedChildren)) - .transform(new Function() { - @Override - public CommitLogMutation apply(Object saveEntity) { - return CommitLogMutation.create(manifestKey, saveEntity); - }}) - .toSet(); + mutations = + union(info.getSaves(), untouchedRootsWithTouchedChildren) + .stream() + .map( + (Function) + (Object saveEntity) -> CommitLogMutation.create(manifestKey, saveEntity)) + .collect(toImmutableSet()); ofy().saveWithoutBackup() .entities(new ImmutableSet.Builder<>() .add(manifest) diff --git a/java/google/registry/model/ofy/Ofy.java b/java/google/registry/model/ofy/Ofy.java index 77ff577eb..a071cdb66 100644 --- a/java/google/registry/model/ofy/Ofy.java +++ b/java/google/registry/model/ofy/Ofy.java @@ -29,7 +29,7 @@ import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; @@ -136,7 +136,7 @@ public class Ofy { @Override protected void handleDeletion(Iterable> keys) { assertInTransaction(); - checkState(Iterables.all(keys, notNull()), "Can't delete a null key."); + checkState(Streams.stream(keys).allMatch(notNull()), "Can't delete a null key."); checkProhibitedAnnotations(keys, NotBackedUp.class, VirtualEntity.class); TRANSACTION_INFO.get().putDeletes(keys); } @@ -168,7 +168,7 @@ public class Ofy { @Override protected void handleSave(Iterable entities) { assertInTransaction(); - checkState(Iterables.all(entities, notNull()), "Can't save a null entity."); + checkState(Streams.stream(entities).allMatch(notNull()), "Can't save a null entity."); checkProhibitedAnnotations(entities, NotBackedUp.class, VirtualEntity.class); ImmutableMap, ?> keysToEntities = uniqueIndex(entities, OBJECTS_TO_KEYS); TRANSACTION_INFO.get().putSaves(keysToEntities); diff --git a/java/google/registry/model/ofy/TimestampInversionException.java b/java/google/registry/model/ofy/TimestampInversionException.java index eb3679acd..acc39ccbe 100644 --- a/java/google/registry/model/ofy/TimestampInversionException.java +++ b/java/google/registry/model/ofy/TimestampInversionException.java @@ -15,7 +15,6 @@ package google.registry.model.ofy; import com.google.common.base.Joiner; -import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.googlecode.objectify.Key; import com.googlecode.objectify.Objectify; @@ -43,17 +42,20 @@ class TimestampInversionException extends RuntimeException { } private TimestampInversionException(DateTime transactionTime, String problem) { - super(Joiner.on('\n').join( - String.format( - "Timestamp inversion between transaction time (%s) and %s", - transactionTime, - problem), - getFileAndLine(FluentIterable.from(new Exception().getStackTrace()) - .firstMatch(new Predicate() { - @Override - public boolean apply(StackTraceElement element) { - return !element.getClassName().startsWith(Objectify.class.getPackage().getName()) - && !element.getClassName().startsWith(Ofy.class.getName()); - }}).get()))); + super( + Joiner.on('\n') + .join( + String.format( + "Timestamp inversion between transaction time (%s) and %s", + transactionTime, problem), + getFileAndLine( + FluentIterable.from(new Exception().getStackTrace()) + .firstMatch( + (StackTraceElement element) -> + !element + .getClassName() + .startsWith(Objectify.class.getPackage().getName()) + && !element.getClassName().startsWith(Ofy.class.getName())) + .get()))); } } diff --git a/java/google/registry/model/ofy/TransactionInfo.java b/java/google/registry/model/ofy/TransactionInfo.java index 50ab4c610..e241dbccd 100644 --- a/java/google/registry/model/ofy/TransactionInfo.java +++ b/java/google/registry/model/ofy/TransactionInfo.java @@ -16,6 +16,7 @@ package google.registry.model.ofy; import static com.google.common.base.Functions.constant; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Maps.filterValues; import static com.google.common.collect.Maps.toMap; import static google.registry.model.ofy.CommitLogBucket.getArbitraryBucketId; @@ -23,7 +24,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy; 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; @@ -88,9 +88,11 @@ class TransactionInfo { } ImmutableSet getSaves() { - return FluentIterable - .from(changesBuilder.build().values()) + return changesBuilder + .build() + .values() + .stream() .filter(Predicates.not(IS_DELETE)) - .toSet(); + .collect(toImmutableSet()); } } diff --git a/java/google/registry/model/poll/PollMessage.java b/java/google/registry/model/poll/PollMessage.java index 2e0782a2f..fed697c55 100644 --- a/java/google/registry/model/poll/PollMessage.java +++ b/java/google/registry/model/poll/PollMessage.java @@ -14,6 +14,7 @@ package google.registry.model.poll; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.util.CollectionUtils.forceEmptyToNull; import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.DateTimeUtils.END_OF_TIME; @@ -24,6 +25,7 @@ import com.google.common.base.Converter; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.EntitySubclass; @@ -235,26 +237,48 @@ public abstract class PollMessage extends ImmutableObject public Builder setResponseData(ImmutableList responseData) { FluentIterable iterable = FluentIterable.from(responseData); - getInstance().contactPendingActionNotificationResponses = forceEmptyToNull( - iterable.filter(ContactPendingActionNotificationResponse.class).toList()); - getInstance().contactTransferResponses = forceEmptyToNull( - iterable.filter(ContactTransferResponse.class).toList()); - getInstance().domainPendingActionNotificationResponses = forceEmptyToNull( - iterable.filter(DomainPendingActionNotificationResponse.class).toList()); - getInstance().domainTransferResponses = forceEmptyToNull( - iterable.filter(DomainTransferResponse.class).toList()); - getInstance().hostPendingActionNotificationResponses = forceEmptyToNull( - iterable.filter(HostPendingActionNotificationResponse.class).toList()); + getInstance().contactPendingActionNotificationResponses = + forceEmptyToNull( + Streams.stream(iterable) + .filter(ContactPendingActionNotificationResponse.class::isInstance) + .map(ContactPendingActionNotificationResponse.class::cast) + .collect(toImmutableList())); + getInstance().contactTransferResponses = + forceEmptyToNull( + Streams.stream(iterable) + .filter(ContactTransferResponse.class::isInstance) + .map(ContactTransferResponse.class::cast) + .collect(toImmutableList())); + getInstance().domainPendingActionNotificationResponses = + forceEmptyToNull( + Streams.stream(iterable) + .filter(DomainPendingActionNotificationResponse.class::isInstance) + .map(DomainPendingActionNotificationResponse.class::cast) + .collect(toImmutableList())); + getInstance().domainTransferResponses = + forceEmptyToNull( + Streams.stream(iterable) + .filter(DomainTransferResponse.class::isInstance) + .map(DomainTransferResponse.class::cast) + .collect(toImmutableList())); + getInstance().hostPendingActionNotificationResponses = + forceEmptyToNull( + Streams.stream(iterable) + .filter(HostPendingActionNotificationResponse.class::isInstance) + .map(HostPendingActionNotificationResponse.class::cast) + .collect(toImmutableList())); return this; } public Builder setResponseExtensions( ImmutableList responseExtensions) { - getInstance().launchInfoResponseExtension = FluentIterable - .from(responseExtensions) - .filter(LaunchInfoResponseExtension.class) - .first() - .orNull(); + getInstance().launchInfoResponseExtension = + responseExtensions + .stream() + .filter(LaunchInfoResponseExtension.class::isInstance) + .map(LaunchInfoResponseExtension.class::cast) + .findFirst() + .orElse(null); return this; } } diff --git a/java/google/registry/model/registrar/Registrar.java b/java/google/registry/model/registrar/Registrar.java index 4d27b3a59..2728801a0 100644 --- a/java/google/registry/model/registrar/Registrar.java +++ b/java/google/registry/model/registrar/Registrar.java @@ -21,6 +21,7 @@ import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.notNull; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Strings.nullToEmpty; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static com.google.common.collect.Sets.immutableEnumSet; import static com.google.common.io.BaseEncoding.base64; import static google.registry.config.RegistryConfig.getDefaultRegistrarReferralUrl; @@ -35,13 +36,13 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.X509Utils.getCertificateHash; import static google.registry.util.X509Utils.loadCertificate; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Comparator.comparing; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Strings; import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -50,6 +51,7 @@ import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.collect.Range; import com.google.common.collect.Sets; +import com.google.common.collect.Streams; import com.google.re2j.Pattern; import com.googlecode.objectify.Key; import com.googlecode.objectify.Work; @@ -193,12 +195,9 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable * Compare two instances of {@link RegistrarContact} by their email addresses lexicographically. */ private static final Comparator CONTACT_EMAIL_COMPARATOR = - new Comparator() { - @Override - public int compare(RegistrarContact rc1, RegistrarContact rc2) { - return rc1.getEmailAddress().compareTo(rc2.getEmailAddress()); - } - }; + comparing( + (RegistrarContact arg) -> arg.getEmailAddress(), + (String leftProperty, String rightProperty) -> leftProperty.compareTo(rightProperty)); /** * A caching {@link Supplier} of a clientId to {@link Registrar} map. @@ -207,19 +206,21 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable * query inside an unrelated client-affecting transaction. */ private static final Supplier> CACHE_BY_CLIENT_ID = - memoizeWithShortExpiration(new Supplier>() { - @Override - public ImmutableMap get() { - return ofy().doTransactionless(new Work>() { - @Override - public ImmutableMap run() { - ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); - for (Registrar registrar : loadAll()) { - builder.put(registrar.getClientId(), registrar); - } - return builder.build(); - }}); - }}); + memoizeWithShortExpiration( + () -> + ofy() + .doTransactionless( + new Work>() { + @Override + public ImmutableMap run() { + ImmutableMap.Builder builder = + new ImmutableMap.Builder<>(); + for (Registrar registrar : loadAll()) { + builder.put(registrar.getClientId(), registrar); + } + return builder.build(); + } + })); @Parent Key parent = getCrossTldKey(); @@ -421,14 +422,13 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable BillingMethod billingMethod; @NonFinalForTesting - private static Supplier saltSupplier = new Supplier() { - @Override - public byte[] get() { - // There are 32 bytes in a sha-256 hash, and the salt should generally be the same size. - byte[] salt = new byte[32]; - new SecureRandom().nextBytes(salt); - return salt; - }}; + private static Supplier saltSupplier = + () -> { + // There are 32 bytes in a sha-256 hash, and the salt should generally be the same size. + byte[] salt = new byte[32]; + new SecureRandom().nextBytes(salt); + return salt; + }; public String getClientId() { return clientIdentifier; @@ -576,9 +576,9 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable * address. */ public ImmutableSortedSet getContacts() { - return FluentIterable.from(getContactsIterable()) + return Streams.stream(getContactsIterable()) .filter(notNull()) - .toSortedSet(CONTACT_EMAIL_COMPARATOR); + .collect(toImmutableSortedSet(CONTACT_EMAIL_COMPARATOR)); } /** @@ -586,16 +586,10 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable * their email address. */ public ImmutableSortedSet getContactsOfType(final RegistrarContact.Type type) { - return FluentIterable.from(getContactsIterable()) + return Streams.stream(getContactsIterable()) .filter(notNull()) - .filter( - new Predicate() { - @Override - public boolean apply(@Nullable RegistrarContact contact) { - return contact.getTypes().contains(type); - } - }) - .toSortedSet(CONTACT_EMAIL_COMPARATOR); + .filter((@Nullable RegistrarContact contact) -> contact.getTypes().contains(type)) + .collect(toImmutableSortedSet(CONTACT_EMAIL_COMPARATOR)); } private Iterable getContactsIterable() { diff --git a/java/google/registry/model/registrar/RegistrarContact.java b/java/google/registry/model/registrar/RegistrarContact.java index eac42299c..7b98efc7a 100644 --- a/java/google/registry/model/registrar/RegistrarContact.java +++ b/java/google/registry/model/registrar/RegistrarContact.java @@ -16,17 +16,17 @@ package google.registry.model.registrar; import static com.google.common.base.Functions.toStringFunction; import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.transform; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Sets.difference; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy; import static google.registry.util.ObjectifyUtils.OBJECTS_TO_KEYS; +import static java.util.stream.Collectors.joining; import com.google.common.base.Enums; -import com.google.common.base.Joiner; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.annotation.Entity; @@ -141,7 +141,9 @@ public class RegistrarContact extends ImmutableObject implements Jsonifiable { } public static ImmutableSet typesFromStrings(Iterable typeNames) { - return FluentIterable.from(typeNames).transform(Enums.stringConverter(Type.class)).toSet(); + return Streams.stream(typeNames) + .map(Enums.stringConverter(Type.class)) + .collect(toImmutableSet()); } /** @@ -154,15 +156,25 @@ public class RegistrarContact extends ImmutableObject implements Jsonifiable { */ public static void updateContacts( final Registrar registrar, final Set contacts) { - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().delete().keys(difference( - ImmutableSet.copyOf( - ofy().load().type(RegistrarContact.class).ancestor(registrar).keys()), - FluentIterable.from(contacts).transform(OBJECTS_TO_KEYS).toSet())); - ofy().save().entities(contacts); - }}); + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy() + .delete() + .keys( + difference( + ImmutableSet.copyOf( + ofy() + .load() + .type(RegistrarContact.class) + .ancestor(registrar) + .keys()), + contacts.stream().map(OBJECTS_TO_KEYS).collect(toImmutableSet()))); + ofy().save().entities(contacts); + } + }); } public Key getParent() { @@ -260,7 +272,7 @@ public class RegistrarContact extends ImmutableObject implements Jsonifiable { .put("emailAddress", emailAddress) .put("phoneNumber", phoneNumber) .put("faxNumber", faxNumber) - .put("types", Joiner.on(',').join(transform(getTypes(), toStringFunction()))) + .put("types", getTypes().stream().map(toStringFunction()).collect(joining(","))) .put("visibleInWhoisAsAdmin", visibleInWhoisAsAdmin) .put("visibleInWhoisAsTech", visibleInWhoisAsTech) .put("visibleInDomainWhoisAsAbuse", visibleInDomainWhoisAsAbuse) diff --git a/java/google/registry/model/registry/Registries.java b/java/google/registry/model/registry/Registries.java index 20beb3ab7..0488aac36 100644 --- a/java/google/registry/model/registry/Registries.java +++ b/java/google/registry/model/registry/Registries.java @@ -19,6 +19,7 @@ import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.base.Strings.emptyToNull; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Maps.filterValues; import static google.registry.model.CacheUtils.memoizeWithShortExpiration; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; @@ -28,9 +29,9 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Streams; import com.google.common.net.InternetDomainName; import com.googlecode.objectify.Work; import google.registry.model.registry.Registry.TldType; @@ -50,19 +51,22 @@ public final class Registries { * query inside an unrelated client-affecting transaction. */ private static Supplier> createFreshCache() { - return memoizeWithShortExpiration(new Supplier>() { - @Override - public ImmutableMap get() { - return ofy().doTransactionless(new Work>() { - @Override - public ImmutableMap run() { - ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); - for (Registry registry : ofy().load().type(Registry.class).ancestor(getCrossTldKey())) { - builder.put(registry.getTldStr(), registry.getTldType()); - } - return builder.build(); - }}); - }}); + return memoizeWithShortExpiration( + () -> + ofy() + .doTransactionless( + new Work>() { + @Override + public ImmutableMap run() { + ImmutableMap.Builder builder = + new ImmutableMap.Builder<>(); + for (Registry registry : + ofy().load().type(Registry.class).ancestor(getCrossTldKey())) { + builder.put(registry.getTldStr(), registry.getTldType()); + } + return builder.build(); + } + })); } /** Manually reset the static cache backing the methods on this class. */ @@ -93,7 +97,8 @@ public final class Registries { for (String tld : tlds) { checkArgumentNotNull(emptyToNull(tld), "Null or empty TLD specified"); } - ImmutableSet badTlds = FluentIterable.from(tlds).filter(not(in(getTlds()))).toSet(); + ImmutableSet badTlds = + Streams.stream(tlds).filter(not(in(getTlds()))).collect(toImmutableSet()); checkArgument(badTlds.isEmpty(), "TLDs do not exist: %s", Joiner.on(", ").join(badTlds)); return tlds; } diff --git a/java/google/registry/model/registry/Registry.java b/java/google/registry/model/registry/Registry.java index 8f2fe4f10..5552e826b 100644 --- a/java/google/registry/model/registry/Registry.java +++ b/java/google/registry/model/registry/Registry.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.not; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -34,7 +35,6 @@ import com.google.common.base.Predicate; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Iterables; @@ -799,15 +799,12 @@ public class Registry extends ImmutableObject implements Buildable { } } ImmutableSet>> conflicts = - FluentIterable.from(allAuthCodes.asMap().entrySet()) - .filter( - new Predicate>>() { - @Override - public boolean apply(Entry> entry) { - return entry.getValue().size() > 1; - } - }) - .toSet(); + allAuthCodes + .asMap() + .entrySet() + .stream() + .filter((Entry> entry) -> entry.getValue().size() > 1) + .collect(toImmutableSet()); checkArgument( conflicts.isEmpty(), "Cannot set reserved lists because of auth code conflicts for labels: %s", @@ -837,14 +834,7 @@ public class Registry extends ImmutableObject implements Buildable { ImmutableSortedMap renewCostsMap) { checkArgumentNotNull(renewCostsMap, "Renew billing costs map cannot be null"); checkArgument( - Iterables.all( - renewCostsMap.values(), - new Predicate() { - @Override - public boolean apply(Money amount) { - return amount.isPositiveOrZero(); - } - }), + renewCostsMap.values().stream().allMatch(Money::isPositiveOrZero), "Renew billing cost cannot be negative"); getInstance().renewBillingCostTransitions = TimedTransitionProperty.fromValueMap(renewCostsMap, BillingCostTransition.class); @@ -855,14 +845,7 @@ public class Registry extends ImmutableObject implements Buildable { public Builder setEapFeeSchedule(ImmutableSortedMap eapFeeSchedule) { checkArgumentNotNull(eapFeeSchedule, "EAP schedule map cannot be null"); checkArgument( - Iterables.all( - eapFeeSchedule.values(), - new Predicate() { - @Override - public boolean apply(Money amount) { - return amount.isPositiveOrZero(); - } - }), + eapFeeSchedule.values().stream().allMatch(Money::isPositiveOrZero), "EAP fee cannot be negative"); getInstance().eapFeeSchedule = TimedTransitionProperty.fromValueMap(eapFeeSchedule, BillingCostTransition.class); @@ -939,17 +922,12 @@ public class Registry extends ImmutableObject implements Buildable { instance.getServerStatusChangeCost().getCurrencyUnit().equals(instance.currency), "Server status change cost must be in the registry's currency"); Predicate currencyCheck = - new Predicate() { - @Override - public boolean apply(Money money) { - return money.getCurrencyUnit().equals(instance.currency); - } - }; + (Money money) -> money.getCurrencyUnit().equals(instance.currency); checkArgument( - Iterables.all(instance.getRenewBillingCostTransitions().values(), currencyCheck), + instance.getRenewBillingCostTransitions().values().stream().allMatch(currencyCheck), "Renew cost must be in the registry's currency"); checkArgument( - Iterables.all(instance.eapFeeSchedule.toValueMap().values(), currencyCheck), + instance.eapFeeSchedule.toValueMap().values().stream().allMatch(currencyCheck), "All EAP fees must be in the registry's currency"); checkArgumentNotNull( instance.pricingEngineClassName, "All registries must have a configured pricing engine"); diff --git a/java/google/registry/model/registry/label/PremiumListUtils.java b/java/google/registry/model/registry/label/PremiumListUtils.java index 4346d70d3..ed79cf5a1 100644 --- a/java/google/registry/model/registry/label/PremiumListUtils.java +++ b/java/google/registry/model/registry/label/PremiumListUtils.java @@ -15,6 +15,7 @@ package google.registry.model.registry.label; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.partition; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -30,12 +31,11 @@ import static org.joda.time.DateTimeZone.UTC; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.cache.CacheLoader.InvalidCacheLoadException; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Streams; import com.googlecode.objectify.Key; import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.Work; @@ -202,15 +202,9 @@ public final class PremiumListUtils { @VisibleForTesting public static ImmutableSet parentPremiumListEntriesOnRevision( Iterable entries, final Key revisionKey) { - return FluentIterable.from(entries) - .transform( - new Function() { - @Override - public PremiumListEntry apply(PremiumListEntry entry) { - return entry.asBuilder().setParent(revisionKey).build(); - } - }) - .toSet(); + return Streams.stream(entries) + .map((PremiumListEntry entry) -> entry.asBuilder().setParent(revisionKey).build()) + .collect(toImmutableSet()); } /** Deletes the PremiumList and all of its child entities. */ diff --git a/java/google/registry/model/registry/label/ReservedList.java b/java/google/registry/model/registry/label/ReservedList.java index fc7843d32..201e9bf7f 100644 --- a/java/google/registry/model/registry/label/ReservedList.java +++ b/java/google/registry/model/registry/label/ReservedList.java @@ -17,6 +17,7 @@ package google.registry.model.registry.label; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; @@ -28,14 +29,12 @@ import static google.registry.util.CollectionUtils.nullToEmpty; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.joda.time.DateTimeZone.UTC; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.net.InternetDomainName; @@ -217,15 +216,10 @@ public final class ReservedList if (label.length() == 0) { return ImmutableSet.of(FULLY_BLOCKED); } - return FluentIterable.from(getReservedListEntries(label, tld)) - .transform( - new Function() { - @Override - public ReservationType apply(ReservedListEntry reservedListEntry) { - return reservedListEntry.reservationType; - } - }) - .toSet(); + return getReservedListEntries(label, tld) + .stream() + .map((ReservedListEntry reservedListEntry) -> reservedListEntry.reservationType) + .collect(toImmutableSet()); } /** diff --git a/java/google/registry/model/smd/SignedMarkRevocationList.java b/java/google/registry/model/smd/SignedMarkRevocationList.java index 1d0f8e422..05cc80af9 100644 --- a/java/google/registry/model/smd/SignedMarkRevocationList.java +++ b/java/google/registry/model/smd/SignedMarkRevocationList.java @@ -25,7 +25,6 @@ import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.isBeforeOrAt; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; @@ -93,31 +92,36 @@ public class SignedMarkRevocationList extends ImmutableObject { * single {@link SignedMarkRevocationList} object. */ private static final Supplier CACHE = - memoizeWithShortExpiration(new Supplier() { - @Override - public SignedMarkRevocationList get() { - // Open a new transactional read even if we are in a transaction currently. - return ofy().transactNewReadOnly(new Work() { - @Override - public SignedMarkRevocationList run() { - Iterable shards = ofy() - .load() - .type(SignedMarkRevocationList.class) - .ancestor(getCrossTldKey()); - DateTime creationTime = - isEmpty(shards) - ? START_OF_TIME - : checkNotNull(Iterables.get(shards, 0).creationTime, "creationTime"); - ImmutableMap.Builder revokes = new ImmutableMap.Builder<>(); - for (SignedMarkRevocationList shard : shards) { - revokes.putAll(shard.revokes); - checkState( - creationTime.equals(shard.creationTime), - "Inconsistent creation times: %s vs. %s", creationTime, shard.creationTime); - } - return create(creationTime, revokes.build()); - }}); - }}); + memoizeWithShortExpiration( + () -> + ofy() + .transactNewReadOnly( + new Work() { + @Override + public SignedMarkRevocationList run() { + Iterable shards = + ofy() + .load() + .type(SignedMarkRevocationList.class) + .ancestor(getCrossTldKey()); + DateTime creationTime = + isEmpty(shards) + ? START_OF_TIME + : checkNotNull( + Iterables.get(shards, 0).creationTime, "creationTime"); + ImmutableMap.Builder revokes = + new ImmutableMap.Builder<>(); + for (SignedMarkRevocationList shard : shards) { + revokes.putAll(shard.revokes); + checkState( + creationTime.equals(shard.creationTime), + "Inconsistent creation times: %s vs. %s", + creationTime, + shard.creationTime); + } + return create(creationTime, revokes.build()); + } + })); /** Return a single logical instance that combines all Datastore shards. */ public static SignedMarkRevocationList get() { @@ -154,25 +158,34 @@ public class SignedMarkRevocationList extends ImmutableObject { /** Save this list to Datastore in sharded form. Returns {@code this}. */ public SignedMarkRevocationList save() { - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().deleteWithoutBackup().keys(ofy() - .load() - .type(SignedMarkRevocationList.class) - .ancestor(getCrossTldKey()) - .keys()); - ofy().saveWithoutBackup().entities(FluentIterable - .from(CollectionUtils.partitionMap(revokes, SHARD_SIZE)) - .transform(new Function, SignedMarkRevocationList>() { + ofy() + .transact( + new VoidWork() { @Override - public SignedMarkRevocationList apply(ImmutableMap shardRevokes) { - SignedMarkRevocationList shard = create(creationTime, shardRevokes); - shard.id = allocateId(); - shard.isShard = true; // Avoid the exception in disallowUnshardedSaves(). - return shard; - }})); - }}); + public void vrun() { + ofy() + .deleteWithoutBackup() + .keys( + ofy() + .load() + .type(SignedMarkRevocationList.class) + .ancestor(getCrossTldKey()) + .keys()); + ofy() + .saveWithoutBackup() + .entities( + FluentIterable.from(CollectionUtils.partitionMap(revokes, SHARD_SIZE)) + .transform( + (ImmutableMap shardRevokes) -> { + SignedMarkRevocationList shard = + create(creationTime, shardRevokes); + shard.id = allocateId(); + shard.isShard = + true; // Avoid the exception in disallowUnshardedSaves(). + return shard; + })); + } + }); return this; } diff --git a/java/google/registry/model/tmch/ClaimsListShard.java b/java/google/registry/model/tmch/ClaimsListShard.java index b6c431c05..fad132865 100644 --- a/java/google/registry/model/tmch/ClaimsListShard.java +++ b/java/google/registry/model/tmch/ClaimsListShard.java @@ -23,7 +23,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.DateTimeUtils.START_OF_TIME; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; import com.googlecode.objectify.Key; @@ -96,54 +95,47 @@ public class ClaimsListShard extends ImmutableObject { private static final Retrier LOADER_RETRIER = new Retrier(new SystemSleeper(), 2); private static final Callable LOADER_CALLABLE = - new Callable() { - @Override - public ClaimsListShard call() throws Exception { - // Find the most recent revision. - Key revisionKey = getCurrentRevision(); + () -> { + // Find the most recent revision. + Key revisionKey = getCurrentRevision(); - Map combinedLabelsToKeys = new HashMap<>(); - DateTime creationTime = START_OF_TIME; - if (revisionKey != null) { - // Grab all of the keys for the shards that belong to the current revision. - final List> shardKeys = - ofy().load().type(ClaimsListShard.class).ancestor(revisionKey).keys().list(); + Map combinedLabelsToKeys = new HashMap<>(); + DateTime creationTime = START_OF_TIME; + if (revisionKey != null) { + // Grab all of the keys for the shards that belong to the current revision. + final List> shardKeys = + ofy().load().type(ClaimsListShard.class).ancestor(revisionKey).keys().list(); - // Load all of the shards concurrently, each in a separate transaction. - List shards = - Concurrent.transform( - shardKeys, - new Function, ClaimsListShard>() { - @Override - public ClaimsListShard apply(final Key key) { - return ofy() - .transactNewReadOnly( - new Work() { - @Override - public ClaimsListShard run() { - ClaimsListShard claimsListShard = ofy().load().key(key).now(); - checkState( - claimsListShard != null, - "Key not found when loading claims list shards."); - return claimsListShard; - } - }); - } - }); + // Load all of the shards concurrently, each in a separate transaction. + List shards = + Concurrent.transform( + shardKeys, + (final Key key) -> + ofy() + .transactNewReadOnly( + new Work() { + @Override + public ClaimsListShard run() { + ClaimsListShard claimsListShard = ofy().load().key(key).now(); + checkState( + claimsListShard != null, + "Key not found when loading claims list shards."); + return claimsListShard; + } + })); - // Combine the shards together and return the concatenated ClaimsList. - if (!shards.isEmpty()) { - creationTime = shards.get(0).creationTime; - for (ClaimsListShard shard : shards) { - combinedLabelsToKeys.putAll(shard.labelsToKeys); - checkState( - creationTime.equals(shard.creationTime), - "Inconsistent claims list shard creation times."); - } + // Combine the shards together and return the concatenated ClaimsList. + if (!shards.isEmpty()) { + creationTime = shards.get(0).creationTime; + for (ClaimsListShard shard : shards) { + combinedLabelsToKeys.putAll(shard.labelsToKeys); + checkState( + creationTime.equals(shard.creationTime), + "Inconsistent claims list shard creation times."); } } - return create(creationTime, ImmutableMap.copyOf(combinedLabelsToKeys)); } + return create(creationTime, ImmutableMap.copyOf(combinedLabelsToKeys)); }; /** @@ -152,12 +144,7 @@ public class ClaimsListShard extends ImmutableObject { */ private static final Supplier CACHE = memoizeWithShortExpiration( - new Supplier() { - @Override - public ClaimsListShard get() { - return LOADER_RETRIER.callWithRetry(LOADER_CALLABLE, IllegalStateException.class); - } - }); + () -> LOADER_RETRIER.callWithRetry(LOADER_CALLABLE, IllegalStateException.class)); public DateTime getCreationTime() { return creationTime; @@ -186,20 +173,21 @@ public class ClaimsListShard extends ImmutableObject { final Key parentKey = ClaimsListRevision.createKey(); // Save the ClaimsList shards in separate transactions. - Concurrent.transform(CollectionUtils.partitionMap(labelsToKeys, shardSize), - new Function, ClaimsListShard>() { - @Override - public ClaimsListShard apply(final ImmutableMap labelsToKeysShard) { - return ofy().transactNew(new Work() { - @Override - public ClaimsListShard run() { - ClaimsListShard shard = create(creationTime, labelsToKeysShard); - shard.isShard = true; - shard.parent = parentKey; - ofy().saveWithoutBackup().entity(shard); - return shard; - }}); - }}); + Concurrent.transform( + CollectionUtils.partitionMap(labelsToKeys, shardSize), + (final ImmutableMap labelsToKeysShard) -> + ofy() + .transactNew( + new Work() { + @Override + public ClaimsListShard run() { + ClaimsListShard shard = create(creationTime, labelsToKeysShard); + shard.isShard = true; + shard.parent = parentKey; + ofy().saveWithoutBackup().entity(shard); + return shard; + } + })); // Persist the new revision, thus causing the newly created shards to go live. ofy().transactNew(new VoidWork() { diff --git a/java/google/registry/monitoring/metrics/EventMetric.java b/java/google/registry/monitoring/metrics/EventMetric.java index 36214b9cd..b3dab9a31 100644 --- a/java/google/registry/monitoring/metrics/EventMetric.java +++ b/java/google/registry/monitoring/metrics/EventMetric.java @@ -153,9 +153,7 @@ public class EventMetric extends AbstractMetric { lock.lock(); try { - if (!values.containsKey(labelValues)) { - values.put(labelValues, new MutableDistribution(distributionFitter)); - } + values.computeIfAbsent(labelValues, k -> new MutableDistribution(distributionFitter)); values.get(labelValues).add(sample, count); valueStartTimestamps.putIfAbsent(labelValues, startTimestamp); diff --git a/java/google/registry/monitoring/metrics/MetricMetrics.java b/java/google/registry/monitoring/metrics/MetricMetrics.java index cdec974d6..a58caff8f 100644 --- a/java/google/registry/monitoring/metrics/MetricMetrics.java +++ b/java/google/registry/monitoring/metrics/MetricMetrics.java @@ -14,7 +14,6 @@ package google.registry.monitoring.metrics; -import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -57,27 +56,24 @@ final class MetricMetrics { "Count of Timeseries being pushed to Monitoring API", "Timeseries Count", LABELS, - new Supplier, Long>>() { - @Override - public ImmutableMap, Long> get() { - HashMap, Long> timeseriesCount = new HashMap<>(); + () -> { + HashMap, Long> timeseriesCount = new HashMap<>(); - for (Metric metric : MetricRegistryImpl.getDefault().getRegisteredMetrics()) { - ImmutableList key = - ImmutableList.of( - metric.getMetricSchema().kind().toString(), - metric.getValueClass().toString()); + for (Metric metric : MetricRegistryImpl.getDefault().getRegisteredMetrics()) { + ImmutableList key = + ImmutableList.of( + metric.getMetricSchema().kind().toString(), + metric.getValueClass().toString()); - int cardinality = metric.getCardinality(); - if (!timeseriesCount.containsKey(key)) { - timeseriesCount.put(key, (long) cardinality); - } else { - timeseriesCount.put(key, timeseriesCount.get(key) + cardinality); - } + int cardinality = metric.getCardinality(); + if (!timeseriesCount.containsKey(key)) { + timeseriesCount.put(key, (long) cardinality); + } else { + timeseriesCount.put(key, timeseriesCount.get(key) + cardinality); } - - return ImmutableMap.copyOf(timeseriesCount); } + + return ImmutableMap.copyOf(timeseriesCount); }, Long.class); diff --git a/java/google/registry/monitoring/metrics/contrib/AbstractMetricSubject.java b/java/google/registry/monitoring/metrics/contrib/AbstractMetricSubject.java index 562c0bdae..d54d53539 100644 --- a/java/google/registry/monitoring/metrics/contrib/AbstractMetricSubject.java +++ b/java/google/registry/monitoring/metrics/contrib/AbstractMetricSubject.java @@ -67,15 +67,11 @@ abstract class AbstractMetricSubject> * Function to convert a metric point to a nice string representation for use in error messages. */ protected final Function, String> metricPointConverter = - new Function, String>() { - @Override - public String apply(MetricPoint metricPoint) { - return String.format( + metricPoint -> + String.format( "%s => %s", Joiner.on(':').join(metricPoint.labelValues()), getMessageRepresentation(metricPoint.value())); - } - }; protected AbstractMetricSubject(FailureMetadata metadata, Metric actual) { super(metadata, checkNotNull(actual)); diff --git a/java/google/registry/monitoring/metrics/contrib/DistributionMetricSubject.java b/java/google/registry/monitoring/metrics/contrib/DistributionMetricSubject.java index 69c86bfb1..95609f111 100644 --- a/java/google/registry/monitoring/metrics/contrib/DistributionMetricSubject.java +++ b/java/google/registry/monitoring/metrics/contrib/DistributionMetricSubject.java @@ -19,7 +19,6 @@ import static com.google.common.truth.Truth.assertAbout; import com.google.common.collect.BoundType; import com.google.common.collect.Range; import com.google.common.truth.FailureMetadata; -import com.google.common.truth.Subject; import google.registry.monitoring.metrics.Distribution; import google.registry.monitoring.metrics.Metric; import google.registry.monitoring.metrics.MetricPoint; @@ -48,15 +47,9 @@ public final class DistributionMetricSubject extends AbstractMetricSubject { /** {@link Subject.Factory} for assertions about {@link Metric} objects. */ - private static final Subject.Factory> - SUBJECT_FACTORY = - // The Truth extensibility documentation indicates that the target should be nullable. - (FailureMetadata failureMetadata, @Nullable Metric target) -> - new DistributionMetricSubject(failureMetadata, target); - /** Static assertThat({@link Metric}) shortcut method. */ public static DistributionMetricSubject assertThat(@Nullable Metric metric) { - return assertAbout(SUBJECT_FACTORY).that(metric); + return assertAbout(DistributionMetricSubject::new).that(metric); } private DistributionMetricSubject(FailureMetadata metadata, Metric actual) { diff --git a/java/google/registry/monitoring/metrics/contrib/LongMetricSubject.java b/java/google/registry/monitoring/metrics/contrib/LongMetricSubject.java index 148ffad13..d9f179222 100644 --- a/java/google/registry/monitoring/metrics/contrib/LongMetricSubject.java +++ b/java/google/registry/monitoring/metrics/contrib/LongMetricSubject.java @@ -17,7 +17,6 @@ package google.registry.monitoring.metrics.contrib; import static com.google.common.truth.Truth.assertAbout; import com.google.common.truth.FailureMetadata; -import com.google.common.truth.Subject; import google.registry.monitoring.metrics.Metric; import google.registry.monitoring.metrics.MetricPoint; import javax.annotation.Nullable; @@ -45,14 +44,9 @@ import javax.annotation.Nullable; public final class LongMetricSubject extends AbstractMetricSubject { /** {@link Subject.Factory} for assertions about {@link Metric} objects. */ - private static final Subject.Factory> SUBJECT_FACTORY = - // The Truth extensibility documentation indicates that the target should be nullable. - (FailureMetadata failureMetadata, @Nullable Metric target) -> - new LongMetricSubject(failureMetadata, target); - /** Static assertThat({@link Metric}) shortcut method. */ public static LongMetricSubject assertThat(@Nullable Metric metric) { - return assertAbout(SUBJECT_FACTORY).that(metric); + return assertAbout(LongMetricSubject::new).that(metric); } private LongMetricSubject(FailureMetadata metadata, Metric actual) { diff --git a/java/google/registry/monitoring/whitebox/MetricsExportAction.java b/java/google/registry/monitoring/whitebox/MetricsExportAction.java index 36f4f2bb5..12a6a3c46 100644 --- a/java/google/registry/monitoring/whitebox/MetricsExportAction.java +++ b/java/google/registry/monitoring/whitebox/MetricsExportAction.java @@ -19,14 +19,11 @@ import static com.google.common.base.Predicates.not; import static com.google.common.collect.Multimaps.filterKeys; import static google.registry.request.Action.Method.POST; import static google.registry.util.FormattingLogger.getLoggerForCallerClass; +import static java.util.stream.Collectors.joining; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.TableDataInsertAllRequest; import com.google.api.services.bigquery.model.TableDataInsertAllResponse; -import com.google.api.services.bigquery.model.TableDataInsertAllResponse.InsertErrors; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; @@ -85,18 +82,19 @@ public class MetricsExportAction implements Runnable { .execute(); if (response.getInsertErrors() != null && !response.getInsertErrors().isEmpty()) { - throw new RuntimeException(FluentIterable - .from(response.getInsertErrors()) - .transform(new Function() { - @Override - public String apply(InsertErrors error) { - try { - return error.toPrettyString(); - } catch (IOException e) { - return error.toString(); - } - }}) - .join(Joiner.on('\n'))); + throw new RuntimeException( + response + .getInsertErrors() + .stream() + .map( + error -> { + try { + return error.toPrettyString(); + } catch (IOException e) { + return error.toString(); + } + }) + .collect(joining("\n"))); } } catch (Throwable e) { logger.warningfmt("Caught Unknown Exception: %s", e); diff --git a/java/google/registry/monitoring/whitebox/WhiteboxModule.java b/java/google/registry/monitoring/whitebox/WhiteboxModule.java index 9655b7c7e..769e3923e 100644 --- a/java/google/registry/monitoring/whitebox/WhiteboxModule.java +++ b/java/google/registry/monitoring/whitebox/WhiteboxModule.java @@ -61,12 +61,7 @@ public class WhiteboxModule { @Provides @Named("insertIdGenerator") static Supplier provideInsertIdGenerator() { - return new Supplier() { - @Override - public String get() { - return UUID.randomUUID().toString(); - } - }; + return () -> UUID.randomUUID().toString(); } /** Provides an EppMetric builder with the request ID and startTimestamp already initialized. */ diff --git a/java/google/registry/rdap/RdapEntitySearchAction.java b/java/google/registry/rdap/RdapEntitySearchAction.java index e2e7bdfd3..57d5f9a1d 100644 --- a/java/google/registry/rdap/RdapEntitySearchAction.java +++ b/java/google/registry/rdap/RdapEntitySearchAction.java @@ -14,16 +14,16 @@ package google.registry.rdap; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier; import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.HEAD; import com.google.common.base.Optional; -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.primitives.Booleans; import com.google.common.primitives.Longs; import com.googlecode.objectify.cmd.Query; @@ -156,17 +156,13 @@ public class RdapEntitySearchAction extends RdapActionBase { } // Get the registrar matches. ImmutableList registrars = - FluentIterable.from(Registrar.loadAllCached()) + Streams.stream(Registrar.loadAllCached()) .filter( - new Predicate() { - @Override - public boolean apply(Registrar registrar) { - return partialStringQuery.matches(registrar.getRegistrarName()) - && shouldBeVisible(registrar); - } - }) + registrar -> + partialStringQuery.matches(registrar.getRegistrarName()) + && shouldBeVisible(registrar)) .limit(rdapResultSetMaxSize + 1) - .toList(); + .collect(toImmutableList()); // Get the contact matches and return the results, fetching an additional contact to detect // truncation. If we are including deleted entries, we must fetch more entries, in case some // get excluded due to permissioning. diff --git a/java/google/registry/rdap/RdapJsonFormatter.java b/java/google/registry/rdap/RdapJsonFormatter.java index 9a5972162..88a16a68a 100644 --- a/java/google/registry/rdap/RdapJsonFormatter.java +++ b/java/google/registry/rdap/RdapJsonFormatter.java @@ -15,12 +15,12 @@ package google.registry.rdap; import static com.google.common.base.Strings.nullToEmpty; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static google.registry.model.EppResourceUtils.isLinked; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.CollectionUtils.union; import static google.registry.util.DomainNameUtils.ACE_PREFIX; -import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.base.Predicates; @@ -30,6 +30,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; +import com.google.common.collect.Streams; import com.google.common.net.InetAddresses; import com.googlecode.objectify.Key; import google.registry.config.RdapNoticeDescriptor; @@ -282,19 +283,11 @@ public class RdapJsonFormatter { /** Sets the ordering for hosts; just use the fully qualified host name. */ private static final Ordering HOST_RESOURCE_ORDERING = - Ordering.natural().onResultOf(new Function() { - @Override - public String apply(HostResource host) { - return host.getFullyQualifiedHostName(); - }}); + Ordering.natural().onResultOf(HostResource::getFullyQualifiedHostName); /** Sets the ordering for designated contacts; order them in a fixed order by contact type. */ private static final Ordering DESIGNATED_CONTACT_ORDERING = - Ordering.natural().onResultOf(new Function() { - @Override - public DesignatedContact.Type apply(DesignatedContact designatedContact) { - return designatedContact.getType(); - }}); + Ordering.natural().onResultOf(DesignatedContact::getType); ImmutableMap getJsonTosNotice(String rdapLinkBase) { return getJsonHelpNotice(rdapTosPath, rdapLinkBase); @@ -1076,15 +1069,9 @@ public class RdapJsonFormatter { .filter(Predicates.not(Predicates.equalTo(RdapStatus.ACTIVE))) .append(RdapStatus.REMOVED); } - return iterable - .transform( - new Function() { - @Override - public String apply(RdapStatus status) { - return status.getDisplayName(); - } - }) - .toSortedSet(Ordering.natural()) + return Streams.stream(iterable) + .map(RdapStatus::getDisplayName) + .collect(toImmutableSortedSet(Ordering.natural())) .asList(); } diff --git a/java/google/registry/rdap/RdapUtils.java b/java/google/registry/rdap/RdapUtils.java index 54bc0c389..3b057e1e2 100644 --- a/java/google/registry/rdap/RdapUtils.java +++ b/java/google/registry/rdap/RdapUtils.java @@ -17,7 +17,6 @@ package google.registry.rdap; import static com.google.common.collect.Iterables.tryFind; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import google.registry.model.registrar.Registrar; /** Utility functions for RDAP. */ @@ -29,11 +28,9 @@ public final class RdapUtils { static Optional getRegistrarByIanaIdentifier(final long ianaIdentifier) { return tryFind( Registrar.loadAllCached(), - new Predicate() { - @Override - public boolean apply(Registrar registrar) { - Long registrarIanaIdentifier = registrar.getIanaIdentifier(); - return (registrarIanaIdentifier != null) && (registrarIanaIdentifier == ianaIdentifier); - }}); + registrar -> { + Long registrarIanaIdentifier = registrar.getIanaIdentifier(); + return (registrarIanaIdentifier != null) && (registrarIanaIdentifier == ianaIdentifier); + }); } } diff --git a/java/google/registry/rde/EscrowTaskRunner.java b/java/google/registry/rde/EscrowTaskRunner.java index 24ca4d536..62725f2ee 100644 --- a/java/google/registry/rde/EscrowTaskRunner.java +++ b/java/google/registry/rde/EscrowTaskRunner.java @@ -89,26 +89,30 @@ class EscrowTaskRunner { Duration timeout, final CursorType cursorType, final Duration interval) { - Callable lockRunner = new Callable() { - @Override - public Void call() throws Exception { - logger.info("tld=" + registry.getTld()); - DateTime startOfToday = clock.nowUtc().withTimeAtStartOfDay(); - Cursor cursor = ofy().load().key(Cursor.createKey(cursorType, registry)).now(); - final DateTime nextRequiredRun = (cursor == null ? startOfToday : cursor.getCursorTime()); - if (nextRequiredRun.isAfter(startOfToday)) { - throw new NoContentException("Already completed"); - } - logger.info("cursor=" + nextRequiredRun); - task.runWithLock(nextRequiredRun); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().save().entity( - Cursor.create(cursorType, nextRequiredRun.plus(interval), registry)); - }}); - return null; - }}; + Callable lockRunner = + () -> { + logger.info("tld=" + registry.getTld()); + DateTime startOfToday = clock.nowUtc().withTimeAtStartOfDay(); + Cursor cursor = ofy().load().key(Cursor.createKey(cursorType, registry)).now(); + final DateTime nextRequiredRun = (cursor == null ? startOfToday : cursor.getCursorTime()); + if (nextRequiredRun.isAfter(startOfToday)) { + throw new NoContentException("Already completed"); + } + logger.info("cursor=" + nextRequiredRun); + task.runWithLock(nextRequiredRun); + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy() + .save() + .entity( + Cursor.create(cursorType, nextRequiredRun.plus(interval), registry)); + } + }); + return null; + }; String lockName = String.format("%s %s", task.getClass().getSimpleName(), registry.getTld()); if (!lockHandler.executeWithLocks(lockRunner, tld, timeout, lockName)) { // This will happen if either: a) the task is double-executed; b) the task takes a long time diff --git a/java/google/registry/rde/RdeStagingAction.java b/java/google/registry/rde/RdeStagingAction.java index 9b7708816..7061a6219 100644 --- a/java/google/registry/rde/RdeStagingAction.java +++ b/java/google/registry/rde/RdeStagingAction.java @@ -23,7 +23,6 @@ import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; import com.google.common.base.Ascii; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; @@ -262,16 +261,14 @@ public final class RdeStagingAction implements Runnable { return ImmutableSetMultimap.copyOf( Multimaps.filterValues( pendingDepositChecker.getTldsAndWatermarksPendingDepositForRdeAndBrda(), - new Predicate() { - @Override - public boolean apply(PendingDeposit pending) { - if (clock.nowUtc().isBefore(pending.watermark().plus(transactionCooldown))) { - logger.infofmt("Ignoring within %s cooldown: %s", transactionCooldown, pending); - return false; - } else { - return true; - } - }})); + pending -> { + if (clock.nowUtc().isBefore(pending.watermark().plus(transactionCooldown))) { + logger.infofmt("Ignoring within %s cooldown: %s", transactionCooldown, pending); + return false; + } else { + return true; + } + })); } private ImmutableSetMultimap getManualPendingDeposits() { diff --git a/java/google/registry/rde/RdeStagingMapper.java b/java/google/registry/rde/RdeStagingMapper.java index 6eee05a06..b04f3ac6f 100644 --- a/java/google/registry/rde/RdeStagingMapper.java +++ b/java/google/registry/rde/RdeStagingMapper.java @@ -15,18 +15,18 @@ package google.registry.rde; import static com.google.common.base.Strings.nullToEmpty; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.EppResourceUtils.loadAtPointInTime; import static google.registry.model.ofy.ObjectifyService.ofy; import com.google.appengine.tools.mapreduce.Mapper; import com.google.auto.value.AutoValue; -import com.google.common.base.Function; import com.google.common.base.Optional; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Maps; +import com.google.common.collect.Streams; import com.googlecode.objectify.Result; import google.registry.model.EppResource; import google.registry.model.contact.ContactResource; @@ -96,25 +96,16 @@ public final class RdeStagingMapper extends Mapper dates = - FluentIterable - .from(shouldEmitOnAllTlds - ? pendings.values() - : pendings.get(((DomainResource) resource).getTld())) - .transform(new Function() { - @Override - public DateTime apply(PendingDeposit pending) { - return pending.watermark(); - }}) - .toSet(); + Streams.stream( + shouldEmitOnAllTlds + ? pendings.values() + : pendings.get(((DomainResource) resource).getTld())) + .map(PendingDeposit::watermark) + .collect(toImmutableSet()); // Launch asynchronous fetches of point-in-time representations of resource. ImmutableMap> resourceAtTimes = - ImmutableMap.copyOf(Maps.asMap(dates, - new Function>() { - @Override - public Result apply(DateTime input) { - return loadAtPointInTime(resource, input); - }})); + ImmutableMap.copyOf(Maps.asMap(dates, input -> loadAtPointInTime(resource, input))); // Convert resource to an XML fragment for each watermark/mode pair lazily and cache the result. Fragmenter fragmenter = new Fragmenter(resourceAtTimes); diff --git a/java/google/registry/rde/RdeStagingReducer.java b/java/google/registry/rde/RdeStagingReducer.java index 0f963594c..21c74b711 100644 --- a/java/google/registry/rde/RdeStagingReducer.java +++ b/java/google/registry/rde/RdeStagingReducer.java @@ -101,12 +101,11 @@ public final class RdeStagingReducer extends Reducer fragments) { - Callable lockRunner = new Callable() { - @Override - public Void call() throws Exception { - reduceWithLock(key, fragments); - return null; - }}; + Callable lockRunner = + () -> { + reduceWithLock(key, fragments); + return null; + }; String lockName = String.format("RdeStaging %s %s", key.tld(), key.mode()); if (!lockHandler.executeWithLocks(lockRunner, null, lockTimeout, lockName)) { logger.warningfmt("Lock in use: %s", lockName); diff --git a/java/google/registry/rde/RdeUploadAction.java b/java/google/registry/rde/RdeUploadAction.java index b2dda593d..ac0ea67f9 100644 --- a/java/google/registry/rde/RdeUploadAction.java +++ b/java/google/registry/rde/RdeUploadAction.java @@ -59,7 +59,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; -import java.util.concurrent.Callable; import javax.inject.Inject; import javax.inject.Named; import org.bouncycastle.openpgp.PGPKeyPair; @@ -157,12 +156,10 @@ public final class RdeUploadAction implements Runnable, EscrowTask { verifyFileExists(reportFilename); final long xmlLength = readXmlLength(xmlLengthFilename); retrier.callWithRetry( - new Callable() { - @Override - public Void call() throws Exception { - upload(xmlFilename, xmlLength, watermark, name); - return null; - }}, + () -> { + upload(xmlFilename, xmlLength, watermark, name); + return null; + }, JSchException.class); ofy().transact(new VoidWork() { @Override diff --git a/java/google/registry/rde/imports/RdeHostLinkAction.java b/java/google/registry/rde/imports/RdeHostLinkAction.java index 85c784b2d..3ea717b55 100644 --- a/java/google/registry/rde/imports/RdeHostLinkAction.java +++ b/java/google/registry/rde/imports/RdeHostLinkAction.java @@ -20,12 +20,11 @@ import static google.registry.model.EppResourceUtils.loadByForeignKey; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registry.Registries.findTldForName; import static google.registry.util.PipelineUtils.createJobPath; +import static java.util.stream.Collectors.joining; import com.google.appengine.tools.mapreduce.Mapper; -import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.google.common.net.InternetDomainName; import com.googlecode.objectify.Key; import com.googlecode.objectify.Work; @@ -196,10 +195,11 @@ public class RdeHostLinkAction implements Runnable { } // This is a subordinate host String domainName = - Joiner.on('.') - .join( - Iterables.skip( - hostName.parts(), hostName.parts().size() - (tld.get().parts().size() + 1))); + hostName + .parts() + .stream() + .skip(hostName.parts().size() - (tld.get().parts().size() + 1)) + .collect(joining(".")); DomainResource superordinateDomain = loadByForeignKey(DomainResource.class, domainName, now); // Hosts can't be linked if domains import hasn't been run checkState( diff --git a/java/google/registry/rde/imports/XjcToContactResourceConverter.java b/java/google/registry/rde/imports/XjcToContactResourceConverter.java index 3047b8e3c..f37ce80df 100644 --- a/java/google/registry/rde/imports/XjcToContactResourceConverter.java +++ b/java/google/registry/rde/imports/XjcToContactResourceConverter.java @@ -16,13 +16,12 @@ package google.registry.rde.imports; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.not; +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.rde.imports.RdeImportUtils.generateTridForImport; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; import com.googlecode.objectify.Key; import google.registry.model.contact.ContactAddress; import google.registry.model.contact.ContactPhoneNumber; @@ -54,23 +53,6 @@ final class XjcToContactResourceConverter extends XjcToEppResourceConverter { XmlToEnumMapper.create(PostalInfo.Type.values()); private static final XmlToEnumMapper TRANSFER_STATUS_MAPPER = XmlToEnumMapper.create(TransferStatus.values()); - - private static final Function choiceConverter = - new Function() { - @Override - public PostalInfoChoice apply(XjcContactIntLocType choice) { - return convertPostalInfoChoice(choice); - } - }; - - private static final Function STATUS_VALUE_CONVERTER = - new Function() { - @Override - public StatusValue apply(XjcContactStatusType status) { - return convertStatusValue(status); - } - }; - /** Converts {@link XjcRdeContact} to {@link ContactResource}. */ static ContactResource convertContact(XjcRdeContact contact) { ofy().save().entity( @@ -88,11 +70,12 @@ final class XjcToContactResourceConverter extends XjcToEppResourceConverter { return new ContactResource.Builder() .setRepoId(contact.getRoid()) .setStatusValues( - FluentIterable.from(contact.getStatuses()) - .transform(STATUS_VALUE_CONVERTER) - // LINKED is implicit and should not be imported onto the new contact. + contact + .getStatuses() + .stream() + .map(XjcToContactResourceConverter::convertStatusValue) .filter(not(equalTo(StatusValue.LINKED))) - .toSet()) + .collect(toImmutableSet())) .setLocalizedPostalInfo( getPostalInfoOfType(contact.getPostalInfos(), XjcContactPostalInfoEnumType.LOC)) .setInternationalizedPostalInfo( @@ -160,9 +143,24 @@ final class XjcToContactResourceConverter extends XjcToEppResourceConverter { } return new Disclose.Builder() .setFlag(disclose.isFlag()) - .setNames(ImmutableList.copyOf(Lists.transform(disclose.getNames(), choiceConverter))) - .setOrgs(ImmutableList.copyOf(Lists.transform(disclose.getOrgs(), choiceConverter))) - .setAddrs(ImmutableList.copyOf(Lists.transform(disclose.getAddrs(), choiceConverter))) + .setNames( + disclose + .getNames() + .stream() + .map(XjcToContactResourceConverter::convertPostalInfoChoice) + .collect(toImmutableList())) + .setOrgs( + disclose + .getOrgs() + .stream() + .map(XjcToContactResourceConverter::convertPostalInfoChoice) + .collect(toImmutableList())) + .setAddrs( + disclose + .getAddrs() + .stream() + .map(XjcToContactResourceConverter::convertPostalInfoChoice) + .collect(toImmutableList())) .build(); } diff --git a/java/google/registry/rde/imports/XjcToDomainResourceConverter.java b/java/google/registry/rde/imports/XjcToDomainResourceConverter.java index fd8f5fc5c..7838df602 100644 --- a/java/google/registry/rde/imports/XjcToDomainResourceConverter.java +++ b/java/google/registry/rde/imports/XjcToDomainResourceConverter.java @@ -16,7 +16,7 @@ package google.registry.rde.imports; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; -import static com.google.common.collect.Iterables.transform; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.util.DomainNameUtils.canonicalizeDomainName; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static org.joda.time.DateTimeZone.UTC; @@ -24,7 +24,6 @@ import static org.joda.time.DateTimeZone.UTC; import com.google.common.base.Ascii; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.net.InternetDomainName; import com.googlecode.objectify.Key; import google.registry.model.billing.BillingEvent; @@ -80,44 +79,17 @@ final class XjcToDomainResourceConverter extends XjcToEppResourceConverter { private static final XmlToEnumMapper TRANSFER_STATUS_MAPPER = XmlToEnumMapper.create(TransferStatus.values()); - private static final Function STATUS_CONVERTER = - new Function() { - @Override - public StatusValue apply(XjcDomainStatusType status) { - return convertStatusType(status); - } - }; - private static final Function> HOST_OBJ_CONVERTER = - new Function>() { - @Override - public Key apply(String fullyQualifiedHostName) { - // host names are always lower case - fullyQualifiedHostName = canonicalizeDomainName(fullyQualifiedHostName); - Key key = - ForeignKeyIndex.loadAndGetKey( - HostResource.class, fullyQualifiedHostName, DateTime.now(UTC)); - checkState( - key != null, - String.format("HostResource not found with name '%s'", fullyQualifiedHostName)); - return key; - } - }; - - private static final Function CONTACT_CONVERTER = - new Function() { - @Override - public DesignatedContact apply(XjcDomainContactType contact) { - return convertContactType(contact); - } - }; - - private static final Function SECDNS_CONVERTER = - new Function() { - @Override - public DelegationSignerData apply(XjcSecdnsDsDataType secdns) { - return convertSecdnsDsDataType(secdns); - } + fullyQualifiedHostName -> { + // host names are always lower case + fullyQualifiedHostName = canonicalizeDomainName(fullyQualifiedHostName); + Key key = + ForeignKeyIndex.loadAndGetKey( + HostResource.class, fullyQualifiedHostName, DateTime.now(UTC)); + checkState( + key != null, + String.format("HostResource not found with name '%s'", fullyQualifiedHostName)); + return key; }; /** Converts {@link XjcRgpStatusType} to {@link GracePeriod} */ @@ -198,21 +170,40 @@ final class XjcToDomainResourceConverter extends XjcToEppResourceConverter { .setLastEppUpdateTime(domain.getUpDate()) .setLastEppUpdateClientId(domain.getUpRr() == null ? null : domain.getUpRr().getValue()) .setLastTransferTime(domain.getTrDate()) - .setStatusValues(ImmutableSet.copyOf(transform(domain.getStatuses(), STATUS_CONVERTER))) + .setStatusValues( + domain + .getStatuses() + .stream() + .map(XjcToDomainResourceConverter::convertStatusType) + .collect(toImmutableSet())) .setNameservers(convertNameservers(domain.getNs())) .setGracePeriods( - ImmutableSet.copyOf(transform(domain.getRgpStatuses(), gracePeriodConverter))) - .setContacts(ImmutableSet.copyOf(transform(domain.getContacts(), CONTACT_CONVERTER))) + domain + .getRgpStatuses() + .stream() + .map(gracePeriodConverter) + .collect(toImmutableSet())) + .setContacts( + domain + .getContacts() + .stream() + .map(XjcToDomainResourceConverter::convertContactType) + .collect(toImmutableSet())) .setDsData( domain.getSecDNS() == null ? ImmutableSet.of() - : ImmutableSet.copyOf( - transform(domain.getSecDNS().getDsDatas(), SECDNS_CONVERTER))) + : domain + .getSecDNS() + .getDsDatas() + .stream() + .map(XjcToDomainResourceConverter::convertSecdnsDsDataType) + .collect(toImmutableSet())) .setTransferData(convertDomainTransferData(domain.getTrnData())) // authInfo pw must be a token between 6 and 16 characters in length // generate a token of 16 characters as the default authInfo pw - .setAuthInfo(DomainAuthInfo - .create(PasswordAuth.create(stringGenerator.createString(16), domain.getRoid()))); + .setAuthInfo( + DomainAuthInfo.create( + PasswordAuth.create(stringGenerator.createString(16), domain.getRoid()))); checkArgumentNotNull( domain.getRegistrant(), "Registrant is missing for domain '%s'", domain.getName()); builder = builder.setRegistrant(convertRegistrant(domain.getRegistrant())); @@ -237,7 +228,7 @@ final class XjcToDomainResourceConverter extends XjcToEppResourceConverter { checkArgument( ns.getHostAttrs() == null || ns.getHostAttrs().isEmpty(), "Host attributes are not yet supported"); - return ImmutableSet.copyOf(Iterables.transform(ns.getHostObjs(), HOST_OBJ_CONVERTER)); + return ns.getHostObjs().stream().map(HOST_OBJ_CONVERTER).collect(toImmutableSet()); } /** Converts {@link XjcRdeDomainTransferDataType} to {@link TransferData}. */ diff --git a/java/google/registry/rde/imports/XjcToHostResourceConverter.java b/java/google/registry/rde/imports/XjcToHostResourceConverter.java index aa85f3323..26eefeda8 100644 --- a/java/google/registry/rde/imports/XjcToHostResourceConverter.java +++ b/java/google/registry/rde/imports/XjcToHostResourceConverter.java @@ -16,14 +16,12 @@ package google.registry.rde.imports; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.rde.imports.RdeImportUtils.generateTridForImport; import static google.registry.util.DomainNameUtils.canonicalizeDomainName; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; import com.google.common.net.InetAddresses; import com.googlecode.objectify.Key; import google.registry.model.eppcommon.StatusValue; @@ -37,23 +35,6 @@ import java.net.InetAddress; /** Utility class that converts an {@link XjcRdeHost} into a {@link HostResource}. */ public class XjcToHostResourceConverter extends XjcToEppResourceConverter { - - private static final Function STATUS_VALUE_CONVERTER = - new Function() { - @Override - public StatusValue apply(XjcHostStatusType status) { - return convertStatusType(status); - } - }; - - private static final Function ADDR_CONVERTER = - new Function() { - @Override - public InetAddress apply(XjcHostAddrType addr) { - return convertAddrType(addr); - } - }; - static HostResource convert(XjcRdeHost host) { // TODO(b/35384052): Handle subordinate hosts correctly by setting superordinateDomaina and // lastSuperordinateChange fields. @@ -81,13 +62,16 @@ public class XjcToHostResourceConverter extends XjcToEppResourceConverter { .setCreationClientId(host.getCrRr().getValue()) .setLastEppUpdateClientId(host.getUpRr() == null ? null : host.getUpRr().getValue()) .setStatusValues( - FluentIterable.from(host.getStatuses()) - .transform(STATUS_VALUE_CONVERTER) - // LINKED is implicit and should not be imported onto the new host. - // PENDING_TRANSFER is a property of the superordinate host. + host.getStatuses() + .stream() + .map(XjcToHostResourceConverter::convertStatusType) .filter(not(in(ImmutableSet.of(StatusValue.LINKED, StatusValue.PENDING_TRANSFER)))) - .toSet()) - .setInetAddresses(ImmutableSet.copyOf(Lists.transform(host.getAddrs(), ADDR_CONVERTER))) + .collect(toImmutableSet())) + .setInetAddresses( + host.getAddrs() + .stream() + .map(XjcToHostResourceConverter::convertAddrType) + .collect(toImmutableSet())) .build(); } diff --git a/java/google/registry/reporting/IcannReportingStagingAction.java b/java/google/registry/reporting/IcannReportingStagingAction.java index d195862d1..d4516088e 100644 --- a/java/google/registry/reporting/IcannReportingStagingAction.java +++ b/java/google/registry/reporting/IcannReportingStagingAction.java @@ -22,7 +22,6 @@ import static javax.servlet.http.HttpServletResponse.SC_OK; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.appengine.tools.cloudstorage.GcsFilename; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; @@ -130,16 +129,7 @@ public final class IcannReportingStagingAction implements Runnable { } private Iterable getHeaders(ImmutableSet fields) { - return Iterables.transform( - fields, - new Function() { - @Override - public String apply(TableFieldSchema schema) { - // Change from '_' delimiters (Bigquery-compatible) to '-' (ICANN specification) - return schema.getName().replace('_', '-'); - } - } - ); + return Iterables.transform(fields, schema -> schema.getName().replace('_', '-')); } private void stageActivityReports ( diff --git a/java/google/registry/reporting/IcannReportingUploadAction.java b/java/google/registry/reporting/IcannReportingUploadAction.java index fcdf5f530..0136545a8 100644 --- a/java/google/registry/reporting/IcannReportingUploadAction.java +++ b/java/google/registry/reporting/IcannReportingUploadAction.java @@ -32,11 +32,9 @@ import google.registry.request.Response; import google.registry.request.auth.Auth; import google.registry.util.FormattingLogger; import google.registry.util.Retrier; -import google.registry.xml.XmlException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.concurrent.Callable; import javax.inject.Inject; /** @@ -82,16 +80,16 @@ public final class IcannReportingUploadAction implements Runnable { gcsFilename.getObjectName(), gcsFilename.getBucketName()); - retrier.callWithRetry(new Callable() { - @Override - public Void call() throws IOException, XmlException { - final byte[] payload = readReportFromGcs(gcsFilename); - icannReporter.send(payload, tld, yearMonth, reportType); - response.setContentType(PLAIN_TEXT_UTF_8); - response.setPayload( - String.format("OK, sending: %s", new String(payload, StandardCharsets.UTF_8))); - return null; - }}, IOException.class); + retrier.callWithRetry( + () -> { + final byte[] payload = readReportFromGcs(gcsFilename); + icannReporter.send(payload, tld, yearMonth, reportType); + response.setContentType(PLAIN_TEXT_UTF_8); + response.setPayload( + String.format("OK, sending: %s", new String(payload, StandardCharsets.UTF_8))); + return null; + }, + IOException.class); } private byte[] readReportFromGcs(GcsFilename reportFilename) throws IOException { diff --git a/java/google/registry/request/Modules.java b/java/google/registry/request/Modules.java index fcd3278e1..01fe2514e 100644 --- a/java/google/registry/request/Modules.java +++ b/java/google/registry/request/Modules.java @@ -128,12 +128,7 @@ public final class Modules { public static final class AppIdentityCredentialModule { @Provides static Function, AppIdentityCredential> provideAppIdentityCredential() { - return new Function, AppIdentityCredential>() { - @Override - public AppIdentityCredential apply(Set scopes) { - return new AppIdentityCredential(scopes); - } - }; + return AppIdentityCredential::new; } } @@ -200,12 +195,7 @@ public final class Modules { @Provides static Function, GoogleCredential> provideScopedGoogleCredential( final Provider googleCredentialProvider) { - return new Function, GoogleCredential>() { - @Override - public GoogleCredential apply(Set scopes) { - return googleCredentialProvider.get().createScoped(scopes); - } - }; + return scopes -> googleCredentialProvider.get().createScoped(scopes); } /** diff --git a/java/google/registry/request/Router.java b/java/google/registry/request/Router.java index 910d6a66e..4c05fd5a1 100644 --- a/java/google/registry/request/Router.java +++ b/java/google/registry/request/Router.java @@ -95,21 +95,19 @@ final class Router { } private static Function newInstantiator(final Method method) { - return new Function() { - @Override - public Object apply(Object component) { - try { - return method.invoke(component); - } catch (IllegalAccessException e) { - throw new RuntimeException( - "Error reflectively accessing component's @Action factory method", e); - } catch (InvocationTargetException e) { - // This means an exception was thrown during the injection process while instantiating - // the @Action class; we should propagate that underlying exception. - throwIfUnchecked(e.getCause()); - throw new AssertionError( - "Component's @Action factory method somehow threw checked exception", e); - } - }}; + return component -> { + try { + return method.invoke(component); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "Error reflectively accessing component's @Action factory method", e); + } catch (InvocationTargetException e) { + // This means an exception was thrown during the injection process while instantiating + // the @Action class; we should propagate that underlying exception. + throwIfUnchecked(e.getCause()); + throw new AssertionError( + "Component's @Action factory method somehow threw checked exception", e); + } + }; } } diff --git a/java/google/registry/request/RouterDisplayHelper.java b/java/google/registry/request/RouterDisplayHelper.java index 519f29ce3..9684f0aa3 100644 --- a/java/google/registry/request/RouterDisplayHelper.java +++ b/java/google/registry/request/RouterDisplayHelper.java @@ -14,10 +14,11 @@ package google.registry.request; -import com.google.common.base.Function; +import static java.util.stream.Collectors.joining; + import com.google.common.base.Joiner; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Streams; import java.util.Map; /** @@ -139,14 +140,8 @@ public class RouterDisplayHelper { .build()); return headerToString(formatString) + String.format("%n") - + FluentIterable.from(routes) - .transform( - new Function() { - @Override - public String apply(Route route) { - return routeToString(route, formatString); - } - }) - .join(Joiner.on(String.format("%n"))); + + Streams.stream(routes) + .map(route -> routeToString(route, formatString)) + .collect(joining(String.format("%n"))); } } diff --git a/java/google/registry/tools/AllocateDomainCommand.java b/java/google/registry/tools/AllocateDomainCommand.java index 59a3db6f2..cc045ea8c 100644 --- a/java/google/registry/tools/AllocateDomainCommand.java +++ b/java/google/registry/tools/AllocateDomainCommand.java @@ -18,19 +18,18 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.emptyToNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.transform; import static com.google.common.io.BaseEncoding.base16; import static google.registry.flows.EppXmlTransformer.unmarshal; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.tools.CommandUtilities.addHeader; +import static java.util.stream.Collectors.joining; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Ascii; -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.ImmutableMap; import com.google.template.soy.data.SoyMapData; import com.googlecode.objectify.Key; @@ -43,7 +42,6 @@ import google.registry.model.domain.DomainCommand; import google.registry.model.domain.Period; import google.registry.model.domain.launch.ApplicationStatus; import google.registry.model.domain.launch.LaunchNotice; -import google.registry.model.domain.secdns.DelegationSignerData; import google.registry.model.eppinput.EppInput; import google.registry.model.eppinput.EppInput.ResourceCommandWrapper; import google.registry.model.reporting.HistoryEntry; @@ -51,6 +49,7 @@ import google.registry.model.smd.SignedMark; import google.registry.tools.soy.DomainAllocateSoyInfo; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** Command to allocated a domain from a domain application. */ @Parameters(separators = " =", commandDescription = "Allocate a domain application") @@ -68,20 +67,33 @@ final class AllocateDomainCommand extends MutatingEppToolCommand { protected String postExecute() throws Exception { StringBuilder builder = new StringBuilder(); // Check to see that we allocated everything. - return builder.append(ofy().transactNewReadOnly(new Work() { - @Override - public String run() { - String failureMessage = FluentIterable - .from(ofy().load().keys(applicationKeys).values()) - .transform(new Function() { - @Override - public String apply(DomainApplication application) { - return application.getApplicationStatus() == ApplicationStatus.ALLOCATED - ? null : application.getFullyQualifiedDomainName(); - }}) - .join(Joiner.on('\n').skipNulls()); - return failureMessage.isEmpty() ? "ALL SUCCEEDED" : addHeader("FAILURES", failureMessage); - }})).toString(); + return builder + .append( + ofy() + .transactNewReadOnly( + new Work() { + @Override + public String run() { + String failureMessage = + ofy() + .load() + .keys(applicationKeys) + .values() + .stream() + .map( + application -> + application.getApplicationStatus() + == ApplicationStatus.ALLOCATED + ? null + : application.getFullyQualifiedDomainName()) + .filter(Objects::nonNull) + .collect(joining("\n")); + return failureMessage.isEmpty() + ? "ALL SUCCEEDED" + : addHeader("FAILURES", failureMessage); + } + })) + .toString(); } /** Extract the registration period from the XML used to create the domain application. */ @@ -96,85 +108,98 @@ final class AllocateDomainCommand extends MutatingEppToolCommand { protected void initMutatingEppToolCommand() { checkArgument(superuser, "This command MUST be run as --superuser."); setSoyTemplate(DomainAllocateSoyInfo.getInstance(), DomainAllocateSoyInfo.CREATE); - ofy().transactNewReadOnly(new VoidWork() { - @Override - public void vrun() { - Iterable> keys = transform( - Splitter.on(',').split(ids), - new Function>() { + ofy() + .transactNewReadOnly( + new VoidWork() { @Override - public Key apply(String applicationId) { - return Key.create(DomainApplication.class, applicationId); - }}); - for (DomainApplication application : ofy().load().keys(keys).values()) { - // If the application is already allocated print a warning but do not fail. - if (application.getApplicationStatus() == ApplicationStatus.ALLOCATED) { - System.err.printf( - "Application %s has already been allocated\n", application.getRepoId()); - continue; - } - // Ensure domain doesn't already have a final status which it shouldn't be updated from. - checkState( - !application.getApplicationStatus().isFinalStatus(), - "Application has final status %s", - application.getApplicationStatus()); - try { - HistoryEntry history = checkNotNull( - ofy().load() - .type(HistoryEntry.class) - .ancestor(checkNotNull(application)) - .order("modificationTime") - .first() - .now(), - "Could not find any history entries for domain application %s", - application.getRepoId()); - String clientTransactionId = - emptyToNull(history.getTrid().getClientTransactionId()); - Period period = checkNotNull(extractPeriodFromXml(history.getXmlBytes())); - checkArgument(period.getUnit() == Period.Unit.YEARS); - ImmutableMap.Builder contactsMapBuilder = new ImmutableMap.Builder<>(); - for (DesignatedContact contact : application.getContacts()) { - contactsMapBuilder.put( - Ascii.toLowerCase(contact.getType().toString()), - ofy().load().key(contact.getContactKey()).now().getForeignKey()); - } - LaunchNotice launchNotice = application.getLaunchNotice(); - addSoyRecord(application.getCurrentSponsorClientId(), new SoyMapData( - "name", application.getFullyQualifiedDomainName(), - "period", period.getValue(), - "nameservers", application.loadNameserverFullyQualifiedHostNames(), - "registrant", ofy().load().key(application.getRegistrant()).now().getForeignKey(), - "contacts", contactsMapBuilder.build(), - "authInfo", application.getAuthInfo().getPw().getValue(), - "smdId", application.getEncodedSignedMarks().isEmpty() - ? null - : unmarshal( - SignedMark.class, - application.getEncodedSignedMarks().get(0).getBytes()).getId(), - "applicationRoid", application.getRepoId(), - "applicationTime", application.getCreationTime().toString(), - "launchNotice", launchNotice == null ? null : ImmutableMap.of( - "noticeId", launchNotice.getNoticeId().getTcnId(), - "expirationTime", launchNotice.getExpirationTime().toString(), - "acceptedTime", launchNotice.getAcceptedTime().toString()), - "dsRecords", FluentIterable.from(application.getDsData()) - .transform(new Function>() { - @Override - public ImmutableMap apply(DelegationSignerData dsData) { - return ImmutableMap.of( - "keyTag", dsData.getKeyTag(), - "algorithm", dsData.getAlgorithm(), - "digestType", dsData.getDigestType(), - "digest", base16().encode(dsData.getDigest())); - }}) - .toList(), - "clTrid", clientTransactionId)); - applicationKeys.add(Key.create(application)); - } catch (EppException e) { - throw new RuntimeException(e); - } - } - } - }); + public void vrun() { + Iterable> keys = + transform( + Splitter.on(',').split(ids), + applicationId -> Key.create(DomainApplication.class, applicationId)); + for (DomainApplication application : ofy().load().keys(keys).values()) { + // If the application is already allocated print a warning but do not fail. + if (application.getApplicationStatus() == ApplicationStatus.ALLOCATED) { + System.err.printf( + "Application %s has already been allocated\n", application.getRepoId()); + continue; + } + // Ensure domain doesn't already have a final status which it shouldn't be updated + // from. + checkState( + !application.getApplicationStatus().isFinalStatus(), + "Application has final status %s", + application.getApplicationStatus()); + try { + HistoryEntry history = + checkNotNull( + ofy() + .load() + .type(HistoryEntry.class) + .ancestor(checkNotNull(application)) + .order("modificationTime") + .first() + .now(), + "Could not find any history entries for domain application %s", + application.getRepoId()); + String clientTransactionId = + emptyToNull(history.getTrid().getClientTransactionId()); + Period period = checkNotNull(extractPeriodFromXml(history.getXmlBytes())); + checkArgument(period.getUnit() == Period.Unit.YEARS); + ImmutableMap.Builder contactsMapBuilder = + new ImmutableMap.Builder<>(); + for (DesignatedContact contact : application.getContacts()) { + contactsMapBuilder.put( + Ascii.toLowerCase(contact.getType().toString()), + ofy().load().key(contact.getContactKey()).now().getForeignKey()); + } + LaunchNotice launchNotice = application.getLaunchNotice(); + addSoyRecord( + application.getCurrentSponsorClientId(), + new SoyMapData( + "name", application.getFullyQualifiedDomainName(), + "period", period.getValue(), + "nameservers", application.loadNameserverFullyQualifiedHostNames(), + "registrant", + ofy().load().key(application.getRegistrant()).now().getForeignKey(), + "contacts", contactsMapBuilder.build(), + "authInfo", application.getAuthInfo().getPw().getValue(), + "smdId", + application.getEncodedSignedMarks().isEmpty() + ? null + : unmarshal( + SignedMark.class, + application.getEncodedSignedMarks().get(0).getBytes()) + .getId(), + "applicationRoid", application.getRepoId(), + "applicationTime", application.getCreationTime().toString(), + "launchNotice", + launchNotice == null + ? null + : ImmutableMap.of( + "noticeId", launchNotice.getNoticeId().getTcnId(), + "expirationTime", + launchNotice.getExpirationTime().toString(), + "acceptedTime", launchNotice.getAcceptedTime().toString()), + "dsRecords", + application + .getDsData() + .stream() + .map( + dsData -> + ImmutableMap.of( + "keyTag", dsData.getKeyTag(), + "algorithm", dsData.getAlgorithm(), + "digestType", dsData.getDigestType(), + "digest", base16().encode(dsData.getDigest()))) + .collect(toImmutableList()), + "clTrid", clientTransactionId)); + applicationKeys.add(Key.create(application)); + } catch (EppException e) { + throw new RuntimeException(e); + } + } + } + }); } } diff --git a/java/google/registry/tools/AppEngineConnection.java b/java/google/registry/tools/AppEngineConnection.java index 144fb3385..89f16a757 100644 --- a/java/google/registry/tools/AppEngineConnection.java +++ b/java/google/registry/tools/AppEngineConnection.java @@ -63,11 +63,7 @@ class AppEngineConnection implements Connection { *

Computing this is expensive since it needs to load {@code ServerSecret} so do it once. */ private final Supplier xsrfToken = - memoize(new Supplier() { - @Override - public String get() { - return xsrfTokenManager.generateToken(getUserId()); - }}); + memoize(() -> xsrfTokenManager.generateToken(getUserId())); @Override public void prefetchXsrfToken() throws IOException { diff --git a/java/google/registry/tools/AuctionStatusCommand.java b/java/google/registry/tools/AuctionStatusCommand.java index 622de3e39..ed17573cf 100644 --- a/java/google/registry/tools/AuctionStatusCommand.java +++ b/java/google/registry/tools/AuctionStatusCommand.java @@ -60,28 +60,34 @@ final class AuctionStatusCommand implements RemoteApiCommand { @Override public void run() throws Exception { final ImmutableSet domains = ImmutableSet.copyOf(mainArguments); - Files.write(output, FluentIterable - .from(domains) - .transformAndConcat(new Function>() { - @Override - public Iterable apply(String fullyQualifiedDomainName) { - checkState( - findTldForName(InternetDomainName.from(fullyQualifiedDomainName)).isPresent(), - "No tld found for %s", fullyQualifiedDomainName); - return ofy().transactNewReadOnly(new Work>() { - @Override - public Iterable run() { - ImmutableList.Builder applications = - new ImmutableList.Builder<>(); - for (String domain : domains) { - applications.addAll( - loadActiveApplicationsByDomainName(domain, ofy().getTransactionTime())); - } - return Lists.transform( - FluentIterable.from(applications.build()).toSortedList(ORDERING), - APPLICATION_FORMATTER); - }}); - }}), UTF_8); + Files.write( + output, + FluentIterable.from(domains) + .transformAndConcat( + fullyQualifiedDomainName -> { + checkState( + findTldForName(InternetDomainName.from(fullyQualifiedDomainName)).isPresent(), + "No tld found for %s", + fullyQualifiedDomainName); + return ofy() + .transactNewReadOnly( + new Work>() { + @Override + public Iterable run() { + ImmutableList.Builder applications = + new ImmutableList.Builder<>(); + for (String domain : domains) { + applications.addAll( + loadActiveApplicationsByDomainName( + domain, ofy().getTransactionTime())); + } + return Lists.transform( + ImmutableList.sortedCopyOf(ORDERING, applications.build()), + APPLICATION_FORMATTER); + } + }); + }), + UTF_8); } private static final Ordering ORDERING = new Ordering() { @@ -97,11 +103,10 @@ final class AuctionStatusCommand implements RemoteApiCommand { }}; private static final Function APPLICATION_FORMATTER = - new Function() { - @Override - public String apply(DomainApplication app) { - ContactResource registrant = checkNotNull(ofy().load().key(app.getRegistrant()).now()); - Object[] keysAndValues = new Object[] { + app -> { + ContactResource registrant = checkNotNull(ofy().load().key(app.getRegistrant()).now()); + Object[] keysAndValues = + new Object[] { "Domain", app.getFullyQualifiedDomainName(), "Type", app.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise", "Application Status", app.getApplicationStatus(), @@ -111,8 +116,8 @@ final class AuctionStatusCommand implements RemoteApiCommand { "Registrar Name", app.getCurrentSponsorClientId(), "Registrant Email", registrant.getEmailAddress(), "Registrant Phone", registrant.getVoiceNumber().getPhoneNumber() - }; - return String.format( - Strings.repeat("%-25s= %s\n", keysAndValues.length / 2), keysAndValues); - }}; + }; + return String.format( + Strings.repeat("%-25s= %s\n", keysAndValues.length / 2), keysAndValues); + }; } diff --git a/java/google/registry/tools/CreateAuctionCreditsCommand.java b/java/google/registry/tools/CreateAuctionCreditsCommand.java index c83aa3ab7..b6fba4c8b 100644 --- a/java/google/registry/tools/CreateAuctionCreditsCommand.java +++ b/java/google/registry/tools/CreateAuctionCreditsCommand.java @@ -17,6 +17,7 @@ package google.registry.tools; import static com.google.common.base.CaseFormat.UPPER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.registry.Registries.assertTldExists; import static google.registry.util.PreconditionsUtils.checkArgumentPresent; import static org.joda.time.DateTimeZone.UTC; @@ -25,9 +26,9 @@ import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Function; import com.google.common.base.Splitter; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; +import com.google.common.collect.Streams; import com.google.re2j.Matcher; import com.google.re2j.Pattern; import google.registry.model.billing.RegistrarCredit; @@ -42,6 +43,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.stream.Stream; import org.joda.money.BigMoney; import org.joda.money.CurrencyUnit; import org.joda.money.Money; @@ -107,31 +109,25 @@ final class CreateAuctionCreditsCommand extends MutatingCommand { CURRENCY_CODE; public static List getHeaders() { - return FluentIterable.from(values()) - .transform(new Function() { - @Override - public String apply(CsvHeader header) { - // Returns the name of the header as it appears in the CSV file. - return UPPER_UNDERSCORE.to(UPPER_CAMEL, header.name()); - }}) - .toList(); + return Stream.of(values()) + .map(header -> UPPER_UNDERSCORE.to(UPPER_CAMEL, header.name())) + .collect(toImmutableList()); } } private static final Pattern QUOTED_STRING = Pattern.compile("\"(.*)\""); /** Helper function to unwrap a quoted string, failing if the string is not quoted. */ - private static final Function UNQUOTER = new Function() { - @Override - public String apply(String input) { - Matcher matcher = QUOTED_STRING.matcher(input); - checkArgument(matcher.matches(), "Input not quoted"); - return matcher.group(1); - }}; + private static final Function UNQUOTER = + input -> { + Matcher matcher = QUOTED_STRING.matcher(input); + checkArgument(matcher.matches(), "Input not quoted"); + return matcher.group(1); + }; /** Returns the input string of quoted CSV values split into the list of unquoted values. */ private static List splitCsvLine(String line) { - return FluentIterable.from(Splitter.on(',').split(line)).transform(UNQUOTER).toList(); + return Streams.stream(Splitter.on(',').split(line)).map(UNQUOTER).collect(toImmutableList()); } @Override diff --git a/java/google/registry/tools/CreateLrpTokensCommand.java b/java/google/registry/tools/CreateLrpTokensCommand.java index 0e0c5d466..88c3d9240 100644 --- a/java/google/registry/tools/CreateLrpTokensCommand.java +++ b/java/google/registry/tools/CreateLrpTokensCommand.java @@ -16,6 +16,7 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Sets.difference; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registry.Registries.assertTldsExist; @@ -27,9 +28,7 @@ import com.beust.jcommander.Parameters; import com.google.appengine.tools.remoteapi.RemoteApiException; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; -import com.google.common.base.Function; import com.google.common.base.Splitter; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -50,7 +49,6 @@ import java.io.StringReader; import java.nio.file.Path; import java.util.Collection; import java.util.List; -import java.util.concurrent.Callable; import javax.inject.Inject; /** @@ -164,12 +162,12 @@ public class CreateLrpTokensCommand implements RemoteApiCommand { } final ImmutableSet tokensToSave = tokensToSaveBuilder.build(); // Wrap in a retrier to deal with transient 404 errors (thrown as RemoteApiExceptions). - retrier.callWithRetry(new Callable() { - @Override - public Void call() throws Exception { - saveTokens(tokensToSave); - return null; - }}, RemoteApiException.class); + retrier.callWithRetry( + () -> { + saveTokens(tokensToSave); + return null; + }, + RemoteApiException.class); } while (line != null); } @@ -196,21 +194,19 @@ public class CreateLrpTokensCommand implements RemoteApiCommand { private ImmutableSet generateTokens(int count) { final ImmutableSet candidates = ImmutableSet.copyOf(TokenUtils.createTokens(LRP, stringGenerator, count)); - ImmutableSet> existingTokenKeys = FluentIterable.from(candidates) - .transform(new Function>() { - @Override - public Key apply(String input) { - return Key.create(LrpTokenEntity.class, input); - }}) - .toSet(); - ImmutableSet existingTokenStrings = FluentIterable - .from(ofy().load().keys(existingTokenKeys).values()) - .transform(new Function() { - @Override - public String apply(LrpTokenEntity input) { - return input.getToken(); - }}) - .toSet(); + ImmutableSet> existingTokenKeys = + candidates + .stream() + .map(input -> Key.create(LrpTokenEntity.class, input)) + .collect(toImmutableSet()); + ImmutableSet existingTokenStrings = + ofy() + .load() + .keys(existingTokenKeys) + .values() + .stream() + .map(LrpTokenEntity::getToken) + .collect(toImmutableSet()); return ImmutableSet.copyOf(difference(candidates, existingTokenStrings)); } } diff --git a/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java b/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java index 3c88eca62..ef527129f 100644 --- a/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java +++ b/java/google/registry/tools/CreateOrUpdateRegistrarCommand.java @@ -18,19 +18,17 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.isNull; import static com.google.common.base.Strings.isNullOrEmpty; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.util.DomainNameUtils.canonicalizeDomainName; import static google.registry.util.RegistrarUtils.normalizeRegistrarName; import static java.nio.charset.StandardCharsets.US_ASCII; import static org.joda.time.DateTimeZone.UTC; import com.beust.jcommander.Parameter; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import google.registry.model.billing.RegistrarBillingUtils; import google.registry.model.registrar.Registrar; @@ -376,8 +374,9 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { builder.setBillingMethod(billingMethod); } List streetAddressFields = Arrays.asList(street, city, state, zip, countryCode); - checkArgument(Iterables.any(streetAddressFields, isNull()) - == Iterables.all(streetAddressFields, isNull()), + checkArgument( + streetAddressFields.stream().anyMatch(isNull()) + == streetAddressFields.stream().allMatch(isNull()), "Must specify all fields of address"); if (street != null) { // We always set the localized address for now. That should be safe to do since it supports @@ -432,15 +431,11 @@ abstract class CreateOrUpdateRegistrarCommand extends MutatingCommand { // Check if registrar has billing account IDs for the currency of the TLDs that it is // allowed to register. ImmutableSet tldCurrencies = - FluentIterable.from(newRegistrar.getAllowedTlds()) - .transform( - new Function() { - @Override - public CurrencyUnit apply(String tld) { - return Registry.get(tld).getCurrency(); - } - }) - .toSet(); + newRegistrar + .getAllowedTlds() + .stream() + .map(tld -> Registry.get(tld).getCurrency()) + .collect(toImmutableSet()); Set currenciesWithoutBillingAccountId = newRegistrar.getBillingAccountMap() == null ? tldCurrencies diff --git a/java/google/registry/tools/CreateRegistrarCommand.java b/java/google/registry/tools/CreateRegistrarCommand.java index 0e9db1195..7c68f2638 100644 --- a/java/google/registry/tools/CreateRegistrarCommand.java +++ b/java/google/registry/tools/CreateRegistrarCommand.java @@ -17,22 +17,22 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.emptyToNull; -import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.getOnlyElement; -import static com.google.common.collect.Lists.newArrayList; import static google.registry.model.registrar.Registrar.State.ACTIVE; import static google.registry.tools.RegistryToolEnvironment.PRODUCTION; import static google.registry.tools.RegistryToolEnvironment.SANDBOX; import static google.registry.tools.RegistryToolEnvironment.UNITTEST; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.RegistrarUtils.normalizeClientId; +import static java.util.stream.Collectors.toCollection; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Streams; import google.registry.model.registrar.Registrar; +import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; @@ -82,15 +82,9 @@ final class CreateRegistrarCommand extends CreateOrUpdateRegistrarCommand checkState( !Registrar.loadByClientId(clientId).isPresent(), "Registrar %s already exists", clientId); List collisions = - newArrayList( - filter( - Registrar.loadAll(), - new Predicate() { - @Override - public boolean apply(Registrar registrar) { - return normalizeClientId(registrar.getClientId()).equals(clientId); - } - })); + Streams.stream(Registrar.loadAll()) + .filter(registrar -> normalizeClientId(registrar.getClientId()).equals(clientId)) + .collect(toCollection(ArrayList::new)); if (!collisions.isEmpty()) { throw new IllegalArgumentException(String.format( "The registrar client identifier %s normalizes identically to existing registrar %s", diff --git a/java/google/registry/tools/CreateRegistrarGroupsCommand.java b/java/google/registry/tools/CreateRegistrarGroupsCommand.java index 09623345b..c40ad6dac 100644 --- a/java/google/registry/tools/CreateRegistrarGroupsCommand.java +++ b/java/google/registry/tools/CreateRegistrarGroupsCommand.java @@ -14,13 +14,11 @@ package google.registry.tools; -import static com.google.common.collect.Iterables.transform; import static google.registry.util.PreconditionsUtils.checkArgumentPresent; +import static java.util.stream.Collectors.joining; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; -import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.net.MediaType; import google.registry.model.registrar.Registrar; @@ -64,11 +62,7 @@ public class CreateRegistrarGroupsCommand extends ConfirmingCommand protected String prompt() { return String.format( "Create registrar contact groups for registrar(s) %s?", - Joiner.on(", ").join(transform(registrars, new Function() { - @Override - public String apply(Registrar registrar) { - return registrar.getRegistrarName(); - }}))); + registrars.stream().map(Registrar::getRegistrarName).collect(joining(", "))); } /** Calls the server endpoint to create groups for the specified registrar client id. */ diff --git a/java/google/registry/tools/GenerateAuctionDataCommand.java b/java/google/registry/tools/GenerateAuctionDataCommand.java index 7384c8471..830653758 100644 --- a/java/google/registry/tools/GenerateAuctionDataCommand.java +++ b/java/google/registry/tools/GenerateAuctionDataCommand.java @@ -24,6 +24,8 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registry.Registries.assertTldExists; import static google.registry.util.DateTimeUtils.isAtOrAfter; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.joining; import static org.joda.time.DateTimeZone.UTC; import com.beust.jcommander.Parameter; @@ -51,10 +53,10 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeSet; import org.joda.time.DateTime; @@ -143,12 +145,8 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand { /** Return a map of all fully-qualified domain names mapped to the applications for that name. */ private static Multimap getDomainApplicationMap(final String tld) { DateTime now = DateTime.now(UTC); - Multimap domainApplicationMap = TreeMultimap.create( - Ordering.natural(), new Comparator() { - @Override - public int compare(DomainApplication o1, DomainApplication o2) { - return o1.getForeignKey().compareTo(o2.getForeignKey()); - }}); + Multimap domainApplicationMap = + TreeMultimap.create(Ordering.natural(), comparing(DomainApplication::getForeignKey)); Iterable domainApplications = ofy().load().type(DomainApplication.class).filter("tld", tld); for (DomainApplication domainApplication : domainApplications) { @@ -202,25 +200,28 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand { // Registrant Name|Registrant Company|Registrant Address 1|Registrant Address 2| // Registrant City|Registrant Province|Registrant Postal Code|Registrant Country| // Registrant Email|Registrant Telephone|Reserve|Application Type - return Joiner.on('|').join(ImmutableList.of( - domainApplication.getFullyQualifiedDomainName(), - domainApplication.getForeignKey(), - formatter.print(domainApplication.getCreationTime()), - domainApplication.getLastEppUpdateTime() != null - ? formatter.print(domainApplication.getLastEppUpdateTime()) : "", - domainApplication.getCurrentSponsorClientId(), - nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getName() : ""), - nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getOrg() : ""), - Iterables.getFirst(street, ""), - Joiner.on(' ').skipNulls().join(Iterables.skip(street, 1)), - nullToEmpty(address.isPresent() ? address.get().getCity() : ""), - nullToEmpty(address.isPresent() ? address.get().getState() : ""), - nullToEmpty(address.isPresent() ? address.get().getZip() : ""), - nullToEmpty(address.isPresent() ? address.get().getCountryCode() : ""), - nullToEmpty(registrant.getEmailAddress()), - nullToEmpty(phoneNumber.isPresent() ? phoneNumber.get().toPhoneString() : ""), - "", - domainApplication.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise")); + return Joiner.on('|') + .join( + ImmutableList.of( + domainApplication.getFullyQualifiedDomainName(), + domainApplication.getForeignKey(), + formatter.print(domainApplication.getCreationTime()), + domainApplication.getLastEppUpdateTime() != null + ? formatter.print(domainApplication.getLastEppUpdateTime()) + : "", + domainApplication.getCurrentSponsorClientId(), + nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getName() : ""), + nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getOrg() : ""), + Iterables.getFirst(street, ""), + street.stream().skip(1).filter(Objects::nonNull).collect(joining(" ")), + nullToEmpty(address.isPresent() ? address.get().getCity() : ""), + nullToEmpty(address.isPresent() ? address.get().getState() : ""), + nullToEmpty(address.isPresent() ? address.get().getZip() : ""), + nullToEmpty(address.isPresent() ? address.get().getCountryCode() : ""), + nullToEmpty(registrant.getEmailAddress()), + nullToEmpty(phoneNumber.isPresent() ? phoneNumber.get().toPhoneString() : ""), + "", + domainApplication.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise")); } /** Return a record line for the given registrar. */ diff --git a/java/google/registry/tools/GenerateDnsReportCommand.java b/java/google/registry/tools/GenerateDnsReportCommand.java index a1a195999..1beef3d5e 100644 --- a/java/google/registry/tools/GenerateDnsReportCommand.java +++ b/java/google/registry/tools/GenerateDnsReportCommand.java @@ -14,6 +14,7 @@ package google.registry.tools; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.io.BaseEncoding.base16; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.registry.Registries.assertTldExists; @@ -23,10 +24,8 @@ import static java.nio.charset.StandardCharsets.US_ASCII; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Ordering; import google.registry.model.domain.DomainResource; import google.registry.model.domain.secdns.DelegationSignerData; import google.registry.model.host.HostResource; @@ -98,20 +97,24 @@ final class GenerateDnsReportCommand implements RemoteApiCommand { } private void write(DomainResource domain) { - ImmutableList nameservers = FluentIterable - .from(domain.loadNameserverFullyQualifiedHostNames()) - .toSortedList(Ordering.natural()); - ImmutableList> dsData = FluentIterable.from(domain.getDsData()) - .transform(new Function>() { - @Override - public Map apply(DelegationSignerData dsData) { - return ImmutableMap.of( - "keyTag", dsData.getKeyTag(), - "algorithm", dsData.getAlgorithm(), - "digestType", dsData.getDigestType(), - "digest", base16().encode(dsData.getDigest())); - }}) - .toList(); + ImmutableList nameservers = + ImmutableList.sortedCopyOf(domain.loadNameserverFullyQualifiedHostNames()); + ImmutableList> dsData = + domain + .getDsData() + .stream() + .map( + new Function>() { + @Override + public Map apply(DelegationSignerData dsData) { + return ImmutableMap.of( + "keyTag", dsData.getKeyTag(), + "algorithm", dsData.getAlgorithm(), + "digestType", dsData.getDigestType(), + "digest", base16().encode(dsData.getDigest())); + } + }) + .collect(toImmutableList()); ImmutableMap.Builder mapBuilder = new ImmutableMap.Builder<>(); mapBuilder.put("domain", domain.getFullyQualifiedDomainName()); if (!nameservers.isEmpty()) { @@ -124,13 +127,13 @@ final class GenerateDnsReportCommand implements RemoteApiCommand { } private void write(HostResource nameserver) { - ImmutableList ipAddresses = FluentIterable.from(nameserver.getInetAddresses()) - .transform(new Function() { - @Override - public String apply(InetAddress inetAddress) { - return inetAddress.getHostAddress(); - }}) - .toSortedList(Ordering.natural()); + ImmutableList ipAddresses = + nameserver + .getInetAddresses() + .stream() + .map(InetAddress::getHostAddress) + .sorted() + .collect(toImmutableList()); ImmutableMap map = ImmutableMap.of( "host", nameserver.getFullyQualifiedHostName(), "ips", ipAddresses); diff --git a/java/google/registry/tools/LoadSnapshotCommand.java b/java/google/registry/tools/LoadSnapshotCommand.java index e852d3b0d..115aac29a 100644 --- a/java/google/registry/tools/LoadSnapshotCommand.java +++ b/java/google/registry/tools/LoadSnapshotCommand.java @@ -20,7 +20,6 @@ import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.FutureCallback; @@ -121,7 +120,7 @@ final class LoadSnapshotCommand extends BigqueryCommand { } // Block on the completion of all the load jobs. List results = Futures.successfulAsList(loadJobs.values()).get(); - int numSucceeded = FluentIterable.from(results).filter(notNull()).size(); + int numSucceeded = (int) results.stream().filter(notNull()).count(); System.err.printf( "All load jobs have terminated: %d/%d successful.\n", numSucceeded, loadJobs.size()); diff --git a/java/google/registry/tools/MutatingCommand.java b/java/google/registry/tools/MutatingCommand.java index f97597f01..9685f47ad 100644 --- a/java/google/registry/tools/MutatingCommand.java +++ b/java/google/registry/tools/MutatingCommand.java @@ -24,11 +24,10 @@ import static com.google.common.base.Strings.emptyToNull; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.DatastoreServiceUtils.getNameOrId; import static google.registry.util.DiffUtils.prettyPrintEntityDeepDiff; +import static java.util.stream.Collectors.joining; -import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; 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; @@ -228,8 +227,6 @@ public abstract class MutatingCommand extends ConfirmingCommand implements Remot protected String prompt() { return changedEntitiesMap.isEmpty() ? "No entity changes to apply." - : Joiner.on("\n").join(FluentIterable - .from(changedEntitiesMap.values()) - .transform(toStringFunction())); + : changedEntitiesMap.values().stream().map(toStringFunction()).collect(joining("\n")); } } diff --git a/java/google/registry/tools/PendingEscrowCommand.java b/java/google/registry/tools/PendingEscrowCommand.java index 1e51ff947..d2ab3dbc4 100644 --- a/java/google/registry/tools/PendingEscrowCommand.java +++ b/java/google/registry/tools/PendingEscrowCommand.java @@ -14,11 +14,11 @@ package google.registry.tools; +import static java.util.stream.Collectors.joining; + import com.beust.jcommander.Parameters; import com.google.common.base.Functions; -import com.google.common.base.Joiner; import com.google.common.collect.ComparisonChain; -import com.google.common.collect.FluentIterable; import com.google.common.collect.Ordering; import google.registry.rde.PendingDeposit; import google.registry.rde.PendingDepositChecker; @@ -45,9 +45,11 @@ final class PendingEscrowCommand implements RemoteApiCommand { @Override public void run() throws Exception { - System.out.println(FluentIterable - .from(SORTER.sortedCopy(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda().values())) - .transform(Functions.toStringFunction()) - .join(Joiner.on('\n'))); + System.out.println( + SORTER + .sortedCopy(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda().values()) + .stream() + .map(Functions.toStringFunction()) + .collect(joining("\n"))); } } diff --git a/java/google/registry/tools/RegistrarContactCommand.java b/java/google/registry/tools/RegistrarContactCommand.java index 3d72efdb4..8372c17e5 100644 --- a/java/google/registry/tools/RegistrarContactCommand.java +++ b/java/google/registry/tools/RegistrarContactCommand.java @@ -17,7 +17,7 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; -import static com.google.common.collect.Iterables.transform; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import static google.registry.util.PreconditionsUtils.checkArgumentPresent; @@ -166,8 +166,11 @@ final class RegistrarContactCommand extends MutatingCommand { || ((contactTypeNames.size() == 1) && contactTypeNames.get(0).isEmpty())) { contactTypes = ImmutableSet.of(); } else { - contactTypes = ImmutableSet.copyOf( - transform(contactTypeNames, Enums.stringConverter(RegistrarContact.Type.class))); + contactTypes = + contactTypeNames + .stream() + .map(Enums.stringConverter(RegistrarContact.Type.class)) + .collect(toImmutableSet()); } ImmutableSet contacts = registrar.getContacts(); Map contactsMap = new LinkedHashMap<>(); diff --git a/java/google/registry/tools/UpdateDomainCommand.java b/java/google/registry/tools/UpdateDomainCommand.java index 15c98dbbd..8661c033a 100644 --- a/java/google/registry/tools/UpdateDomainCommand.java +++ b/java/google/registry/tools/UpdateDomainCommand.java @@ -15,15 +15,13 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.EppResourceUtils.loadByForeignKey; import static google.registry.model.ofy.ObjectifyService.ofy; import static org.joda.time.DateTimeZone.UTC; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; @@ -215,21 +213,11 @@ final class UpdateDomainCommand extends CreateOrUpdateDomainCommand { ImmutableSet getContactsOfType( DomainResource domainResource, final DesignatedContact.Type contactType) { - return FluentIterable.from(domainResource.getContacts()) - .filter( - new Predicate() { - @Override - public boolean apply(DesignatedContact contact) { - return contact.getType().equals(contactType); - } - }) - .transform( - new Function() { - @Override - public String apply(DesignatedContact contact) { - return ofy().load().key(contact.getContactKey()).now().getContactId(); - } - }) - .toSet(); + return domainResource + .getContacts() + .stream() + .filter(contact -> contact.getType().equals(contactType)) + .map(contact -> ofy().load().key(contact.getContactKey()).now().getContactId()) + .collect(toImmutableSet()); } } diff --git a/java/google/registry/tools/UpdateTldCommand.java b/java/google/registry/tools/UpdateTldCommand.java index 4a1e5f2ae..a7c2a66ff 100644 --- a/java/google/registry/tools/UpdateTldCommand.java +++ b/java/google/registry/tools/UpdateTldCommand.java @@ -15,6 +15,7 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.intersection; import static com.google.common.collect.Sets.union; @@ -23,16 +24,13 @@ import static google.registry.util.CollectionUtils.nullToEmpty; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; -import com.google.common.base.Function; import com.google.common.base.Optional; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.googlecode.objectify.Key; import google.registry.config.RegistryEnvironment; import google.registry.model.registry.Registry; import google.registry.model.registry.Registry.TldState; -import google.registry.model.registry.label.ReservedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -115,15 +113,7 @@ class UpdateTldCommand extends CreateOrUpdateTldCommand { ImmutableSet getReservedLists(Registry oldRegistry) { return formUpdatedList( "reserved lists", - FluentIterable - .from(oldRegistry.getReservedLists()) - .transform( - new Function, String>() { - @Override - public String apply(Key key) { - return key.getName(); - }}) - .toSet(), + oldRegistry.getReservedLists().stream().map(Key::getName).collect(toImmutableSet()), reservedListNames, reservedListsAdd, reservedListsRemove); diff --git a/java/google/registry/tools/ValidateEscrowDepositCommand.java b/java/google/registry/tools/ValidateEscrowDepositCommand.java index dbba80c5f..b9ae4be0b 100644 --- a/java/google/registry/tools/ValidateEscrowDepositCommand.java +++ b/java/google/registry/tools/ValidateEscrowDepositCommand.java @@ -14,7 +14,6 @@ package google.registry.tools; -import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.Sets.difference; @@ -100,7 +99,7 @@ final class ValidateEscrowDepositCommand implements Command { SortedMap counts = new TreeMap<>(); for (JAXBElement item : deposit.getContents().getContents()) { String name = item.getDeclaredType().getSimpleName(); - counts.put(name, firstNonNull(counts.get(name), 0L) + 1L); + counts.put(name, counts.getOrDefault(name, 0L) + 1L); if (XjcRdeHost.class.isAssignableFrom(item.getDeclaredType())) { XjcRdeHost host = (XjcRdeHost) item.getValue(); hostnames.add(checkNotNull(host.getName())); diff --git a/java/google/registry/tools/VerifyOteCommand.java b/java/google/registry/tools/VerifyOteCommand.java index 3e258dd7b..0baa2203d 100644 --- a/java/google/registry/tools/VerifyOteCommand.java +++ b/java/google/registry/tools/VerifyOteCommand.java @@ -16,16 +16,16 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Predicates.notNull; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.registrar.Registrar.loadByClientId; import static google.registry.util.PreconditionsUtils.checkArgumentPresent; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; -import com.google.common.base.Function; import com.google.common.base.Strings; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Streams; import google.registry.config.RegistryEnvironment; import google.registry.model.registrar.Registrar; import google.registry.tools.server.VerifyOteAction; @@ -105,21 +105,20 @@ final class VerifyOteCommand implements ServerSideCommand { * prefixes of those accounts (in this case, regname). */ private ImmutableSet getAllRegistrarNames() { - return FluentIterable.from(Registrar.loadAll()) - .transform(new Function() { - @Override - public String apply(Registrar registrar) { - if (!registrar.isLive()) { - return null; - } - String name = registrar.getClientId(); - // Look for names of the form "regname-1", "regname-2", etc. and strip the -# suffix. - String replacedName = name.replaceFirst("^(.*)-[1234]$", "$1"); - // Check if any replacement happened, and thus whether the name matches the format. - // If it matches, provide the shortened name, and otherwise return null. - return name.equals(replacedName) ? null : replacedName; - }}) - .filter(notNull()) - .toSet(); + return Streams.stream(Registrar.loadAll()) + .map( + registrar -> { + if (!registrar.isLive()) { + return null; + } + String name = registrar.getClientId(); + // Look for names of the form "regname-1", "regname-2", etc. and strip the -# suffix. + String replacedName = name.replaceFirst("^(.*)-[1234]$", "$1"); + // Check if any replacement happened, and thus whether the name matches the format. + // If it matches, provide the shortened name, and otherwise return null. + return name.equals(replacedName) ? null : replacedName; + }) + .filter(notNull()) + .collect(toImmutableSet()); } } diff --git a/java/google/registry/tools/server/CreateGroupsAction.java b/java/google/registry/tools/server/CreateGroupsAction.java index 07c0e1681..77fa416d9 100644 --- a/java/google/registry/tools/server/CreateGroupsAction.java +++ b/java/google/registry/tools/server/CreateGroupsAction.java @@ -19,14 +19,12 @@ import static google.registry.request.Action.Method.POST; import static java.util.Arrays.asList; import static javax.servlet.http.HttpServletResponse.SC_OK; -import com.google.common.base.Function; import com.google.common.base.Optional; import google.registry.config.RegistryConfig.Config; import google.registry.groups.GroupsConnection; import google.registry.groups.GroupsConnection.Role; import google.registry.model.registrar.Registrar; import google.registry.model.registrar.RegistrarContact; -import google.registry.model.registrar.RegistrarContact.Type; import google.registry.request.Action; import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.InternalServerErrorException; @@ -70,26 +68,26 @@ public class CreateGroupsAction implements Runnable { List types = asList(RegistrarContact.Type.values()); // Concurrently create the groups for each RegistrarContact.Type, collecting the results from // each call (which are either an Exception if it failed, or absent() if it succeeded). - List> results = Concurrent.transform( - types, - NUM_SIMULTANEOUS_CONNECTIONS, - new Function>() { - @Override - public Optional apply(Type type) { - try { - String groupKey = getGroupEmailAddressForContactType( - registrar.getClientId(), type, gSuiteDomainName); - String parentGroup = - getGroupEmailAddressForContactType("registrar", type, gSuiteDomainName); - // Creates the group, then adds it as a member to the global registrar group for - // that type. - groupsConnection.createGroup(groupKey); - groupsConnection.addMemberToGroup(parentGroup, groupKey, Role.MEMBER); - return Optional. absent(); - } catch (Exception e) { - return Optional.of(e); - } - }}); + List> results = + Concurrent.transform( + types, + NUM_SIMULTANEOUS_CONNECTIONS, + type -> { + try { + String groupKey = + getGroupEmailAddressForContactType( + registrar.getClientId(), type, gSuiteDomainName); + String parentGroup = + getGroupEmailAddressForContactType("registrar", type, gSuiteDomainName); + // Creates the group, then adds it as a member to the global registrar group for + // that type. + groupsConnection.createGroup(groupKey); + groupsConnection.addMemberToGroup(parentGroup, groupKey, Role.MEMBER); + return Optional.absent(); + } catch (Exception e) { + return Optional.of(e); + } + }); // Return the correct server response based on the results of the group creations. if (Optional.presentInstances(results).iterator().hasNext()) { StringWriter responseString = new StringWriter(); diff --git a/java/google/registry/tools/server/GenerateZoneFilesAction.java b/java/google/registry/tools/server/GenerateZoneFilesAction.java index d2c2842b5..0e99acd21 100644 --- a/java/google/registry/tools/server/GenerateZoneFilesAction.java +++ b/java/google/registry/tools/server/GenerateZoneFilesAction.java @@ -16,6 +16,7 @@ package google.registry.tools.server; import static com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService; import static com.google.common.base.Predicates.notNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterators.filter; import static com.google.common.io.BaseEncoding.base16; import static google.registry.mapreduce.inputs.EppResourceInputs.createEntityInput; @@ -31,8 +32,6 @@ import com.google.appengine.tools.cloudstorage.RetryParams; import com.google.appengine.tools.mapreduce.Mapper; import com.google.appengine.tools.mapreduce.Reducer; import com.google.appengine.tools.mapreduce.ReducerInput; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -144,17 +143,13 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA ImmutableList.of( new NullInput(), createEntityInput(DomainResource.class))); - ImmutableList filenames = FluentIterable.from(tlds) - .transform( - new Function() { - @Override - public String apply(String tld) { - return String.format( - GCS_PATH_FORMAT, - bucket, - String.format(FILENAME_FORMAT, tld, exportTime)); - }}) - .toList(); + ImmutableList filenames = + tlds.stream() + .map( + tld -> + String.format( + GCS_PATH_FORMAT, bucket, String.format(FILENAME_FORMAT, tld, exportTime))) + .collect(toImmutableList()); return ImmutableMap.of( "jobPath", createJobPath(jobId), "filenames", filenames); diff --git a/java/google/registry/tools/server/KillAllCommitLogsAction.java b/java/google/registry/tools/server/KillAllCommitLogsAction.java index 7f7decb82..82262c8d1 100644 --- a/java/google/registry/tools/server/KillAllCommitLogsAction.java +++ b/java/google/registry/tools/server/KillAllCommitLogsAction.java @@ -15,6 +15,7 @@ package google.registry.tools.server; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.request.Action.Method.POST; import static google.registry.util.PipelineUtils.createJobPath; @@ -22,7 +23,6 @@ import static google.registry.util.PipelineUtils.createJobPath; import com.google.appengine.tools.mapreduce.Input; import com.google.appengine.tools.mapreduce.Mapper; import com.google.appengine.tools.mapreduce.inputs.InMemoryInput; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.googlecode.objectify.Key; @@ -33,7 +33,7 @@ import google.registry.model.ofy.CommitLogCheckpointRoot; import google.registry.request.Action; import google.registry.request.Response; import google.registry.request.auth.Auth; -import java.util.Arrays; +import java.util.stream.Stream; import javax.inject.Inject; /** @@ -63,13 +63,14 @@ public class KillAllCommitLogsAction implements Runnable { "DO NOT RUN ANYWHERE ELSE EXCEPT CRASH OR TESTS."); // Create a in-memory input, assigning each bucket to its own shard for maximum parallelization, // with one extra shard for the CommitLogCheckpointRoot. - Input> input = new InMemoryInput<>( - Lists.partition( - FluentIterable - .from(Arrays.>asList(CommitLogCheckpointRoot.getKey())) - .append(CommitLogBucket.getAllBucketKeys()) - .toList(), - 1)); + Input> input = + new InMemoryInput<>( + Lists.partition( + Stream.concat( + Stream.of(CommitLogCheckpointRoot.getKey()), + CommitLogBucket.getAllBucketKeys().stream()) + .collect(toImmutableList()), + 1)); response.sendJavaScriptRedirect(createJobPath(mrRunner .setJobName("Delete all commit logs") .setModuleName("tools") diff --git a/java/google/registry/tools/server/ListDomainsAction.java b/java/google/registry/tools/server/ListDomainsAction.java index f35c08a41..e37c6f55e 100644 --- a/java/google/registry/tools/server/ListDomainsAction.java +++ b/java/google/registry/tools/server/ListDomainsAction.java @@ -19,6 +19,7 @@ import static google.registry.model.EppResourceUtils.queryNotDeleted; import static google.registry.model.registry.Registries.assertTldsExist; import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.POST; +import static java.util.Comparator.comparing; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; @@ -28,7 +29,6 @@ import google.registry.request.Action; import google.registry.request.Parameter; import google.registry.request.auth.Auth; import google.registry.util.Clock; -import java.util.Comparator; import java.util.List; import javax.inject.Inject; @@ -42,12 +42,6 @@ public final class ListDomainsAction extends ListObjectsAction { /** An App Engine limitation on how many subqueries can be used in a single query. */ private static final int MAX_NUM_SUBQUERIES = 30; - private static final Comparator COMPARATOR = - new Comparator() { - @Override - public int compare(DomainResource a, DomainResource b) { - return a.getFullyQualifiedDomainName().compareTo(b.getFullyQualifiedDomainName()); - }}; public static final String PATH = "/_dr/admin/list/domains"; @Inject @Parameter("tlds") ImmutableSet tlds; @@ -64,7 +58,8 @@ public final class ListDomainsAction extends ListObjectsAction { checkArgument(!tlds.isEmpty(), "Must specify TLDs to query"); assertTldsExist(tlds); ImmutableSortedSet.Builder builder = - new ImmutableSortedSet.Builder(COMPARATOR); + new ImmutableSortedSet.Builder( + comparing(DomainResource::getFullyQualifiedDomainName)); for (List batch : Lists.partition(tlds.asList(), MAX_NUM_SUBQUERIES)) { builder.addAll(queryNotDeleted(DomainResource.class, clock.nowUtc(), "tld in", batch)); } diff --git a/java/google/registry/tools/server/ListHostsAction.java b/java/google/registry/tools/server/ListHostsAction.java index 3e904abdb..0c5f4dd52 100644 --- a/java/google/registry/tools/server/ListHostsAction.java +++ b/java/google/registry/tools/server/ListHostsAction.java @@ -14,19 +14,19 @@ package google.registry.tools.server; +import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.POST; +import static java.util.Comparator.comparing; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Streams; import google.registry.model.EppResourceUtils; import google.registry.model.host.HostResource; import google.registry.request.Action; import google.registry.request.auth.Auth; import google.registry.util.Clock; -import java.util.Comparator; import javax.inject.Inject; import org.joda.time.DateTime; @@ -40,14 +40,6 @@ public final class ListHostsAction extends ListObjectsAction { public static final String PATH = "/_dr/admin/list/hosts"; - private static final Comparator comparator = - new Comparator() { - @Override - public int compare(HostResource host1, HostResource host2) { - return host1.getFullyQualifiedHostName() - .compareTo(host2.getFullyQualifiedHostName()); - }}; - @Inject Clock clock; @Inject ListHostsAction() {} @@ -59,13 +51,8 @@ public final class ListHostsAction extends ListObjectsAction { @Override public ImmutableSet loadObjects() { final DateTime now = clock.nowUtc(); - return FluentIterable - .from(ofy().load().type(HostResource.class)) - .filter(new Predicate() { - @Override - public boolean apply(HostResource host) { - return EppResourceUtils.isActive(host, now); - }}) - .toSortedSet(comparator); + return Streams.stream(ofy().load().type(HostResource.class)) + .filter(host -> EppResourceUtils.isActive(host, now)) + .collect(toImmutableSortedSet(comparing(HostResource::getFullyQualifiedHostName))); } } diff --git a/java/google/registry/tools/server/ListObjectsAction.java b/java/google/registry/tools/server/ListObjectsAction.java index 904718213..3577393ba 100644 --- a/java/google/registry/tools/server/ListObjectsAction.java +++ b/java/google/registry/tools/server/ListObjectsAction.java @@ -16,6 +16,7 @@ package google.registry.tools.server; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -29,7 +30,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import google.registry.model.ImmutableObject; @@ -42,6 +42,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.stream.Stream; import javax.inject.Inject; /** @@ -150,14 +151,9 @@ public abstract class ListObjectsAction implements Ru final ImmutableMap nameMapping = ((fullFieldNames != null) && fullFieldNames.isPresent() && fullFieldNames.get()) ? getFieldAliases() : getFieldAliases().inverse(); - return ImmutableSet.copyOf(Iterables.transform( - Iterables.concat(getPrimaryKeyFields(), fieldsToUse), - new Function() { - @Override - public String apply(String field) { - // Rename fields that are in the map according to the map, and leave the others as is. - return nameMapping.containsKey(field) ? nameMapping.get(field) : field; - }})); + return Stream.concat(getPrimaryKeyFields().stream(), fieldsToUse.stream()) + .map(field -> nameMapping.getOrDefault(field, field)) + .collect(toImmutableSet()); } /** @@ -209,22 +205,16 @@ public abstract class ListObjectsAction implements Ru */ private static ImmutableMap computeColumnWidths( ImmutableTable data, final boolean includingHeader) { - return ImmutableMap.copyOf(Maps.transformEntries( - data.columnMap(), - new Maps.EntryTransformer, Integer>() { - @Override - public Integer transformEntry(String columnName, Map columnValues) { - // Return the length of the longest string in this column (including the column name). - return Ordering.natural().max(Iterables.transform( - Iterables.concat( - ImmutableList.of(includingHeader ? columnName : ""), - columnValues.values()), - new Function() { - @Override - public Integer apply(String value) { - return value.length(); - }})); - }})); + return ImmutableMap.copyOf( + Maps.transformEntries( + data.columnMap(), + (columnName, columnValues) -> + Stream.concat( + Stream.of(includingHeader ? columnName : ""), + columnValues.values().stream()) + .map(String::length) + .max(Ordering.natural()) + .get())); } /** @@ -250,12 +240,8 @@ public abstract class ListObjectsAction implements Ru lines.add(rowFormatter.apply(headerRow)); // Add a row of separator lines (column names mapping to '-' * column width). - Map separatorRow = Maps.transformValues(columnWidths, - new Function() { - @Override - public String apply(Integer width) { - return Strings.repeat("-", width); - }}); + Map separatorRow = + Maps.transformValues(columnWidths, width -> Strings.repeat("-", width)); lines.add(rowFormatter.apply(separatorRow)); } @@ -275,14 +261,12 @@ public abstract class ListObjectsAction implements Ru */ private static Function, String> makeRowFormatter( final Map columnWidths) { - return new Function, String>() { - @Override - public String apply(Map rowByColumns) { - List paddedFields = new ArrayList<>(); - for (Map.Entry cell : rowByColumns.entrySet()) { - paddedFields.add(Strings.padEnd(cell.getValue(), columnWidths.get(cell.getKey()), ' ')); - } - return Joiner.on(" ").join(paddedFields); - }}; + return rowByColumns -> { + List paddedFields = new ArrayList<>(); + for (Map.Entry cell : rowByColumns.entrySet()) { + paddedFields.add(Strings.padEnd(cell.getValue(), columnWidths.get(cell.getKey()), ' ')); + } + return Joiner.on(" ").join(paddedFields); + }; } } diff --git a/java/google/registry/tools/server/ListTldsAction.java b/java/google/registry/tools/server/ListTldsAction.java index 4c85c4ec3..01a4658a9 100644 --- a/java/google/registry/tools/server/ListTldsAction.java +++ b/java/google/registry/tools/server/ListTldsAction.java @@ -14,12 +14,11 @@ package google.registry.tools.server; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static google.registry.model.registry.Registries.getTlds; import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.POST; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -50,13 +49,7 @@ public final class ListTldsAction extends ListObjectsAction { @Override public ImmutableSet loadObjects() { - return FluentIterable.from(getTlds()) - .transform(new Function() { - @Override - public Registry apply(String tldString) { - return Registry.get(tldString); - }}) - .toSet(); + return getTlds().stream().map(Registry::get).collect(toImmutableSet()); } @Override diff --git a/java/google/registry/tools/server/VerifyOteAction.java b/java/google/registry/tools/server/VerifyOteAction.java index 9e4eb27a6..e66cd7e69 100644 --- a/java/google/registry/tools/server/VerifyOteAction.java +++ b/java/google/registry/tools/server/VerifyOteAction.java @@ -16,6 +16,7 @@ package google.registry.tools.server; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.not; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Maps.toMap; import static google.registry.flows.EppXmlTransformer.unmarshal; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -23,7 +24,6 @@ import static google.registry.util.CollectionUtils.isNullOrEmpty; import static google.registry.util.DomainNameUtils.ACE_PREFIX; import com.google.common.base.Ascii; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; @@ -51,7 +51,7 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; -import javax.annotation.Nonnull; +import java.util.stream.Stream; import javax.inject.Inject; /** @@ -82,14 +82,7 @@ public class VerifyOteAction implements Runnable, JsonAction { public Map handleJsonRequest(Map json) { final boolean summarize = Boolean.parseBoolean((String) json.get("summarize")); return toMap( - (List) json.get("registrars"), - new Function() { - @Nonnull - @Override - public Object apply(@Nonnull String registrar) { - return checkRegistrar(registrar, summarize); - } - }); + (List) json.get("registrars"), registrar -> checkRegistrar(registrar, summarize)); } /** Checks whether the provided registrar has passed OT&E and returns relevant information. */ @@ -112,66 +105,37 @@ public class VerifyOteAction implements Runnable, JsonAction { } private static final Predicate HAS_CLAIMS_NOTICE = - new Predicate() { - @Override - public boolean apply(@Nonnull EppInput eppInput) { - LaunchCreateExtension launchCreate = - eppInput.getSingleExtension(LaunchCreateExtension.class); - return launchCreate != null && launchCreate.getNotice() != null; - } - }; - - private static final Predicate HAS_FEE = - new Predicate() { - @Override - public boolean apply(@Nonnull EppInput eppInput) { - return eppInput.getSingleExtension(FeeCreateCommandExtension.class) != null; - } + eppInput -> { + LaunchCreateExtension launchCreate = + eppInput.getSingleExtension(LaunchCreateExtension.class); + return launchCreate != null && launchCreate.getNotice() != null; }; private static final Predicate HAS_SEC_DNS = - new Predicate() { - @Override - public boolean apply(@Nonnull EppInput eppInput) { - return (eppInput.getSingleExtension(SecDnsCreateExtension.class) != null) + eppInput -> + (eppInput.getSingleExtension(SecDnsCreateExtension.class) != null) || (eppInput.getSingleExtension(SecDnsUpdateExtension.class) != null); - } - }; - private static final Predicate IS_SUNRISE = - new Predicate() { - @Override - public boolean apply(@Nonnull EppInput eppInput) { - LaunchCreateExtension launchCreate = - eppInput.getSingleExtension(LaunchCreateExtension.class); - return launchCreate != null && !isNullOrEmpty(launchCreate.getSignedMarks()); - } + eppInput -> { + LaunchCreateExtension launchCreate = + eppInput.getSingleExtension(LaunchCreateExtension.class); + return launchCreate != null && !isNullOrEmpty(launchCreate.getSignedMarks()); }; private static final Predicate IS_IDN = - new Predicate() { - @Override - public boolean apply(@Nonnull EppInput eppInput) { - return ((DomainCommand.Create) + eppInput -> + ((DomainCommand.Create) ((ResourceCommandWrapper) eppInput.getCommandWrapper().getCommand()) .getResourceCommand()) .getFullyQualifiedDomainName() .startsWith(ACE_PREFIX); - } - }; - private static final Predicate IS_SUBORDINATE = - new Predicate() { - @Override - public boolean apply(@Nonnull EppInput eppInput) { - return !isNullOrEmpty( + eppInput -> + !isNullOrEmpty( ((HostCommand.Create) ((ResourceCommandWrapper) eppInput.getCommandWrapper().getCommand()) .getResourceCommand()) .getInetAddresses()); - } - }; - /** Enum defining the distinct statistics (types of registrar actions) to record. */ public enum StatType { CONTACT_CREATES(0, equalTo(Type.CONTACT_CREATE)), @@ -192,7 +156,10 @@ public class VerifyOteAction implements Runnable, JsonAction { DOMAIN_CREATES_ASCII(1, equalTo(Type.DOMAIN_CREATE), not(IS_IDN)), DOMAIN_CREATES_IDN(1, equalTo(Type.DOMAIN_CREATE), IS_IDN), DOMAIN_CREATES_WITH_CLAIMS_NOTICE(1, equalTo(Type.DOMAIN_CREATE), HAS_CLAIMS_NOTICE), - DOMAIN_CREATES_WITH_FEE(1, equalTo(Type.DOMAIN_CREATE), HAS_FEE), + DOMAIN_CREATES_WITH_FEE( + 1, + equalTo(Type.DOMAIN_CREATE), + eppInput -> eppInput.getSingleExtension(FeeCreateCommandExtension.class) != null), DOMAIN_CREATES_WITH_SEC_DNS(1, equalTo(Type.DOMAIN_CREATE), HAS_SEC_DNS), DOMAIN_CREATES_WITHOUT_SEC_DNS(0, equalTo(Type.DOMAIN_CREATE), not(HAS_SEC_DNS)), DOMAIN_DELETES(2, equalTo(Type.DOMAIN_DELETE)), @@ -214,15 +181,7 @@ public class VerifyOteAction implements Runnable, JsonAction { /** The number of StatTypes with a non-zero requirement. */ private static final int NUM_REQUIREMENTS = - FluentIterable.from(values()) - .filter( - new Predicate() { - @Override - public boolean apply(@Nonnull StatType statType) { - return statType.requirement > 0; - } - }) - .size(); + (int) Stream.of(values()).filter(statType -> statType.requirement > 0).count(); /** Required number of times registrars must complete this action. */ final int requirement; @@ -304,15 +263,10 @@ public class VerifyOteAction implements Runnable, JsonAction { ? Optional.absent() : Optional.of(unmarshal(EppInput.class, xmlBytes)); if (!statCounts.addAll( - FluentIterable.from(EnumSet.allOf(StatType.class)) - .filter( - new Predicate() { - @Override - public boolean apply(@Nonnull StatType statType) { - return statType.matches(historyEntry.getType(), eppInput); - } - }) - .toList())) { + EnumSet.allOf(StatType.class) + .stream() + .filter(statType -> statType.matches(historyEntry.getType(), eppInput)) + .collect(toImmutableList()))) { statCounts.add(StatType.UNCLASSIFIED_FLOWS); } } @@ -339,14 +293,8 @@ public class VerifyOteAction implements Runnable, JsonAction { public String toString() { return FluentIterable.from(EnumSet.allOf(StatType.class)) .transform( - new Function() { - @Nonnull - @Override - public String apply(@Nonnull StatType statType) { - return String.format( - "%s: %d", statType.description(), statCounts.count(statType)); - } - }) + statType -> + String.format("%s: %d", statType.description(), statCounts.count(statType))) .append(String.format("TOTAL: %d", statCounts.size())) .join(Joiner.on("\n")); } diff --git a/java/google/registry/ui/forms/FormField.java b/java/google/registry/ui/forms/FormField.java index e6af39184..e6c026388 100644 --- a/java/google/registry/ui/forms/FormField.java +++ b/java/google/registry/ui/forms/FormField.java @@ -17,6 +17,8 @@ package google.registry.ui.forms; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; @@ -24,10 +26,10 @@ import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; 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.Range; +import com.google.common.collect.Streams; import com.google.re2j.Pattern; import java.util.Collection; import java.util.List; @@ -35,7 +37,6 @@ import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.Detainted; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.Tainted; import javax.annotation.concurrent.Immutable; @@ -281,7 +282,15 @@ public final class FormField { checkState(CharSequence.class.isAssignableFrom(typeOut) || Collection.class.isAssignableFrom(typeOut)); @SuppressWarnings("unchecked") - Function emptyToNullFunction = (Function) EMPTY_TO_NULL_FUNCTION; + Function emptyToNullFunction = + (Function) + ((Function) + input -> + ((input instanceof CharSequence) && (((CharSequence) input).length() == 0)) + || ((input instanceof Collection) + && ((Collection) input).isEmpty()) + ? null + : input); return transform(emptyToNullFunction); } @@ -295,7 +304,9 @@ public final class FormField { public Builder trimmed() { checkState(String.class.isAssignableFrom(typeOut)); @SuppressWarnings("unchecked") - Function trimFunction = (Function) TRIM_FUNCTION; + Function trimFunction = + (Function) + ((Function) input -> input != null ? input.trim() : null); return transform(String.class, trimFunction); } @@ -309,7 +320,10 @@ public final class FormField { public Builder uppercased() { checkState(String.class.isAssignableFrom(typeOut)); @SuppressWarnings("unchecked") - Function funk = (Function) UPPERCASE_FUNCTION; + Function funk = + (Function) + ((Function) + input -> input != null ? input.toUpperCase(Locale.ENGLISH) : null); return transform(String.class, funk); } @@ -323,7 +337,10 @@ public final class FormField { public Builder lowercased() { checkState(String.class.isAssignableFrom(typeOut)); @SuppressWarnings("unchecked") - Function funk = (Function) LOWERCASE_FUNCTION; + Function funk = + (Function) + ((Function) + input -> input != null ? input.toLowerCase(Locale.ENGLISH) : null); return transform(String.class, funk); } @@ -519,7 +536,10 @@ public final class FormField { Class> setOut = (Class>) (Class) Set.class; @SuppressWarnings("unchecked") Function, Set> toSetFunction = - (Function, Set>) (Function) TO_SET_FUNCTION; + (Function, Set>) + (Function) + ((Function, Set>) + input -> input != null ? ImmutableSet.copyOf(input) : null); return asList().transform(setOut, toSetFunction); } @@ -541,58 +561,13 @@ public final class FormField { return new FormField<>(name, typeIn, typeOut, converter); } - private static final Function, Set> TO_SET_FUNCTION = - new Function, Set>() { - @Nullable - @Override - public Set apply(@Nullable List input) { - return input != null ? ImmutableSet.copyOf(input) : null; - }}; - - private static final Function TRIM_FUNCTION = - new Function() { - @Nullable - @Override - public String apply(@Nullable String input) { - return input != null ? input.trim() : null; - }}; - - private static final Function UPPERCASE_FUNCTION = - new Function() { - @Nullable - @Override - public String apply(@Nullable String input) { - return input != null ? input.toUpperCase(Locale.ENGLISH) : null; - }}; - - private static final Function LOWERCASE_FUNCTION = - new Function() { - @Nullable - @Override - public String apply(@Nullable String input) { - return input != null ? input.toLowerCase(Locale.ENGLISH) : null; - }}; - private static final Function REQUIRED_FUNCTION = - new Function() { - @Nonnull - @Override - public Object apply(@Nullable Object input) { - if (input == null) { - throw new FormFieldException("This field is required."); - } - return input; - }}; - - private static final Function EMPTY_TO_NULL_FUNCTION = - new Function() { - @Nullable - @Override - public Object apply(@Nullable Object input) { - return ((input instanceof CharSequence) && (((CharSequence) input).length() == 0)) - || ((input instanceof Collection) && ((Collection) input).isEmpty()) - ? null : input; - }}; + input -> { + if (input == null) { + throw new FormFieldException("This field is required."); + } + return input; + }; private static final class DefaultFunction implements Function { private final O defaultValue; @@ -761,10 +736,11 @@ public final class FormField { @Nullable @Override public List apply(@Nullable String input) { - return input == null ? null : FluentIterable - .from(splitter.split(input)) - .transform(itemField.converter) - .toList(); + return input == null + ? null + : Streams.stream(splitter.split(input)) + .map(itemField.converter) + .collect(toImmutableList()); } } @@ -780,10 +756,11 @@ public final class FormField { @Nullable @Override public Set apply(@Nullable String input) { - return input == null ? null : FluentIterable - .from(splitter.split(input)) - .transform(itemField.converter) - .toSet(); + return input == null + ? null + : Streams.stream(splitter.split(input)) + .map(itemField.converter) + .collect(toImmutableSet()); } } } diff --git a/java/google/registry/ui/forms/FormFields.java b/java/google/registry/ui/forms/FormFields.java index 2b51e7760..612c03093 100644 --- a/java/google/registry/ui/forms/FormFields.java +++ b/java/google/registry/ui/forms/FormFields.java @@ -19,23 +19,13 @@ import static com.google.common.collect.Range.closed; import static com.google.common.collect.Range.singleton; import static java.util.Locale.getISOCountries; -import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.re2j.Pattern; -import javax.annotation.Nullable; /** Utility class of {@link FormField} objects for validating EPP related things. */ public final class FormFields { private static final Pattern WHITESPACE = Pattern.compile("[ \\t\\r\\n]+"); - private static final Function COLLAPSE_WHITESPACE = - new Function() { - @Nullable - @Override - public String apply(@Nullable String input) { - return input != null ? WHITESPACE.matcher(input).replaceAll(" ") : null; - }}; - /** * Form field that applies XML Schema Token cleanup to input. * @@ -43,11 +33,12 @@ public final class FormFields { * * @see XSD Datatypes - token */ - public static final FormField XS_TOKEN = FormField.named("xsToken") - .emptyToNull() - .trimmed() - .transform(COLLAPSE_WHITESPACE) - .build(); + public static final FormField XS_TOKEN = + FormField.named("xsToken") + .emptyToNull() + .trimmed() + .transform(input -> input != null ? WHITESPACE.matcher(input).replaceAll(" ") : null) + .build(); /** * Form field that ensures input does not contain tabs, line feeds, or carriage returns. diff --git a/java/google/registry/ui/server/RegistrarFormFields.java b/java/google/registry/ui/server/RegistrarFormFields.java index 22d670d0b..c423b68b9 100644 --- a/java/google/registry/ui/server/RegistrarFormFields.java +++ b/java/google/registry/ui/server/RegistrarFormFields.java @@ -37,7 +37,6 @@ import java.security.cert.CertificateParsingException; import java.util.List; import java.util.Map; import java.util.Set; -import javax.annotation.Nullable; /** Form fields for validating input for the {@code Registrar} class. */ public final class RegistrarFormFields { @@ -47,30 +46,24 @@ public final class RegistrarFormFields { public static final String ASCII_ERROR = "Please only use ASCII-US characters."; private static final Function CIDR_TRANSFORM = - new Function() { - @Nullable - @Override - public CidrAddressBlock apply(@Nullable String input) { - try { - return input != null ? CidrAddressBlock.create(input) : null; - } catch (IllegalArgumentException e) { - throw new FormFieldException("Not a valid CIDR notation IP-address block.", e); - } - }}; + input -> { + try { + return input != null ? CidrAddressBlock.create(input) : null; + } catch (IllegalArgumentException e) { + throw new FormFieldException("Not a valid CIDR notation IP-address block.", e); + } + }; private static final Function HOSTNAME_TRANSFORM = - new Function() { - @Nullable - @Override - public String apply(@Nullable String input) { - if (input == null) { - return null; - } - if (!InternetDomainName.isValid(input)) { - throw new FormFieldException("Not a valid hostname."); - } - return canonicalizeDomainName(input); - }}; + input -> { + if (input == null) { + return null; + } + if (!InternetDomainName.isValid(input)) { + throw new FormFieldException("Not a valid hostname."); + } + return canonicalizeDomainName(input); + }; public static final FormField NAME_FIELD = FormFields.NAME.asBuilderNamed("registrarName") @@ -133,20 +126,18 @@ public final class RegistrarFormFields { private static final FormField X509_PEM_CERTIFICATE = FormField.named("certificate") .emptyToNull() - .transform(new Function() { - @Nullable - @Override - public String apply(@Nullable String input) { - if (input == null) { - return null; - } - try { - X509Utils.loadCertificate(input); - } catch (CertificateParsingException e) { - throw new FormFieldException("Invalid X.509 PEM certificate"); - } - return input; - }}) + .transform( + input -> { + if (input == null) { + return null; + } + try { + X509Utils.loadCertificate(input); + } catch (CertificateParsingException e) { + throw new FormFieldException("Invalid X.509 PEM certificate"); + } + return input; + }) .build(); public static final FormField CLIENT_CERTIFICATE_FIELD = @@ -233,48 +224,44 @@ public final class RegistrarFormFields { public static final Function, RegistrarContact.Builder> REGISTRAR_CONTACT_TRANSFORM = - new Function, RegistrarContact.Builder>() { - @Nullable - @Override - public RegistrarContact.Builder apply(@Nullable Map args) { - if (args == null) { - return null; - } - RegistrarContact.Builder builder = new RegistrarContact.Builder(); - for (String name : CONTACT_NAME_FIELD.extractUntyped(args).asSet()) { - builder.setName(name); - } - for (String emailAddress : CONTACT_EMAIL_ADDRESS_FIELD.extractUntyped(args).asSet()) { - builder.setEmailAddress(emailAddress); - } - for (Boolean visible : - CONTACT_VISIBLE_IN_WHOIS_AS_ADMIN_FIELD.extractUntyped(args).asSet()) { - builder.setVisibleInWhoisAsAdmin(visible); - } - for (Boolean visible : - CONTACT_VISIBLE_IN_WHOIS_AS_TECH_FIELD.extractUntyped(args).asSet()) { - builder.setVisibleInWhoisAsTech(visible); - } - for (Boolean visible : - PHONE_AND_EMAIL_VISIBLE_IN_DOMAIN_WHOIS_AS_ABUSE_FIELD - .extractUntyped(args) - .asSet()) { - builder.setVisibleInDomainWhoisAsAbuse(visible); - } - for (String phoneNumber : CONTACT_PHONE_NUMBER_FIELD.extractUntyped(args).asSet()) { - builder.setPhoneNumber(phoneNumber); - } - for (String faxNumber : CONTACT_FAX_NUMBER_FIELD.extractUntyped(args).asSet()) { - builder.setFaxNumber(faxNumber); - } - for (Set types : CONTACT_TYPES.extractUntyped(args).asSet()) { - builder.setTypes(types); - } - for (String gaeUserId : CONTACT_GAE_USER_ID_FIELD.extractUntyped(args).asSet()) { - builder.setGaeUserId(gaeUserId); - } - return builder; + args -> { + if (args == null) { + return null; } + RegistrarContact.Builder builder = new RegistrarContact.Builder(); + for (String name : CONTACT_NAME_FIELD.extractUntyped(args).asSet()) { + builder.setName(name); + } + for (String emailAddress : CONTACT_EMAIL_ADDRESS_FIELD.extractUntyped(args).asSet()) { + builder.setEmailAddress(emailAddress); + } + for (Boolean visible : + CONTACT_VISIBLE_IN_WHOIS_AS_ADMIN_FIELD.extractUntyped(args).asSet()) { + builder.setVisibleInWhoisAsAdmin(visible); + } + for (Boolean visible : + CONTACT_VISIBLE_IN_WHOIS_AS_TECH_FIELD.extractUntyped(args).asSet()) { + builder.setVisibleInWhoisAsTech(visible); + } + for (Boolean visible : + PHONE_AND_EMAIL_VISIBLE_IN_DOMAIN_WHOIS_AS_ABUSE_FIELD + .extractUntyped(args) + .asSet()) { + builder.setVisibleInDomainWhoisAsAbuse(visible); + } + for (String phoneNumber : CONTACT_PHONE_NUMBER_FIELD.extractUntyped(args).asSet()) { + builder.setPhoneNumber(phoneNumber); + } + for (String faxNumber : CONTACT_FAX_NUMBER_FIELD.extractUntyped(args).asSet()) { + builder.setFaxNumber(faxNumber); + } + for (Set types : CONTACT_TYPES.extractUntyped(args).asSet()) { + builder.setTypes(types); + } + for (String gaeUserId : CONTACT_GAE_USER_ID_FIELD.extractUntyped(args).asSet()) { + builder.setGaeUserId(gaeUserId); + } + return builder; }; public static final FormField>, List> @@ -349,36 +336,32 @@ public final class RegistrarFormFields { final FormField cityField, final FormField stateField, final FormField zipField) { - return new Function, RegistrarAddress>() { - @Nullable - @Override - public RegistrarAddress apply(@Nullable Map args) { - if (args == null) { - return null; - } - RegistrarAddress.Builder builder = new RegistrarAddress.Builder(); - String countryCode = COUNTRY_CODE_FIELD.extractUntyped(args).get(); - builder.setCountryCode(countryCode); - for (List streets : streetField.extractUntyped(args).asSet()) { - builder.setStreet(ImmutableList.copyOf(streets)); - } - for (String city : cityField.extractUntyped(args).asSet()) { - builder.setCity(city); - } - for (String state : stateField.extractUntyped(args).asSet()) { - if ("US".equals(countryCode)) { - state = Ascii.toUpperCase(state); - if (!StateCode.US_MAP.containsKey(state)) { - throw new FormFieldException(stateField, "Unknown US state code."); - } - } - builder.setState(state); - } - for (String zip : zipField.extractUntyped(args).asSet()) { - builder.setZip(zip); - } - return builder.build(); + return args -> { + if (args == null) { + return null; } + RegistrarAddress.Builder builder = new RegistrarAddress.Builder(); + String countryCode = COUNTRY_CODE_FIELD.extractUntyped(args).get(); + builder.setCountryCode(countryCode); + for (List streets : streetField.extractUntyped(args).asSet()) { + builder.setStreet(ImmutableList.copyOf(streets)); + } + for (String city : cityField.extractUntyped(args).asSet()) { + builder.setCity(city); + } + for (String state : stateField.extractUntyped(args).asSet()) { + if ("US".equals(countryCode)) { + state = Ascii.toUpperCase(state); + if (!StateCode.US_MAP.containsKey(state)) { + throw new FormFieldException(stateField, "Unknown US state code."); + } + } + builder.setState(state); + } + for (String zip : zipField.extractUntyped(args).asSet()) { + builder.setZip(zip); + } + return builder.build(); }; } } diff --git a/java/google/registry/ui/server/SoyTemplateUtils.java b/java/google/registry/ui/server/SoyTemplateUtils.java index 4c5e36400..c886e6da6 100644 --- a/java/google/registry/ui/server/SoyTemplateUtils.java +++ b/java/google/registry/ui/server/SoyTemplateUtils.java @@ -14,7 +14,6 @@ package google.registry.ui.server; -import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Suppliers.memoize; import static com.google.common.io.Resources.asCharSource; import static com.google.common.io.Resources.getResource; @@ -46,44 +45,43 @@ public final class SoyTemplateUtils { /** Returns a memoized supplier containing compiled tofu. */ public static Supplier createTofuSupplier(final SoyFileInfo... soyInfos) { - return memoize(new Supplier() { - @Override - public SoyTofu get() { - ConsoleDebug debugMode = ConsoleDebug.get(); - SoyFileSet.Builder builder = SoyFileSet.builder(); - for (SoyFileInfo soyInfo : soyInfos) { - builder.add(getResource(soyInfo.getClass(), soyInfo.getFileName())); - } - Map globals = new HashMap<>(); - try { - globals.putAll(SoyUtils.parseCompileTimeGlobals(asCharSource(SOY_GLOBALS, UTF_8))); - } catch (SoySyntaxException | IOException e) { - throw new RuntimeException("Failed to load soy globals", e); - } - globals.put("DEBUG", debugMode.ordinal()); - builder.setCompileTimeGlobals(globals); - return builder.build().compileToTofu(); - }}); + return memoize( + () -> { + ConsoleDebug debugMode = ConsoleDebug.get(); + SoyFileSet.Builder builder = SoyFileSet.builder(); + for (SoyFileInfo soyInfo : soyInfos) { + builder.add(getResource(soyInfo.getClass(), soyInfo.getFileName())); + } + Map globals = new HashMap<>(); + try { + globals.putAll(SoyUtils.parseCompileTimeGlobals(asCharSource(SOY_GLOBALS, UTF_8))); + } catch (SoySyntaxException | IOException e) { + throw new RuntimeException("Failed to load soy globals", e); + } + globals.put("DEBUG", debugMode.ordinal()); + builder.setCompileTimeGlobals(globals); + return builder.build().compileToTofu(); + }); } /** Returns a memoized supplier of the thing you pass to {@code setCssRenamingMap()}. */ public static Supplier createCssRenamingMapSupplier( final URL cssMap, final URL cssMapDebug) { - return memoize(new Supplier() { - @Override - public SoyCssRenamingMap get() { - final ImmutableMap renames = getCssRenames(cssMap, cssMapDebug); - return new SoyCssRenamingMap() { - @Override - public String get(String cssClassName) { - List result = new ArrayList<>(); - for (String part : CSS_CLASS_SPLITTER.split(cssClassName)) { - result.add(firstNonNull(renames.get(part), part)); + return memoize( + () -> { + final ImmutableMap renames = getCssRenames(cssMap, cssMapDebug); + return new SoyCssRenamingMap() { + @Override + public String get(String cssClassName) { + List result = new ArrayList<>(); + for (String part : CSS_CLASS_SPLITTER.split(cssClassName)) { + result.add(renames.getOrDefault(part, part)); + } + return CSS_CLASS_JOINER.join(result); } - return CSS_CLASS_JOINER.join(result); - }}; - }}); + }; + }); } private static ImmutableMap getCssRenames(URL cssMap, URL cssMapDebug) { diff --git a/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java b/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java index a7becab86..93618ee28 100644 --- a/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java +++ b/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java @@ -27,7 +27,6 @@ import com.braintreegateway.Transaction; import com.braintreegateway.TransactionRequest; import com.braintreegateway.ValidationError; import com.braintreegateway.ValidationErrors; -import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.re2j.Pattern; import google.registry.config.RegistryConfig.Config; @@ -108,15 +107,15 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { .emptyToNull() .required() .matches(Pattern.compile("-?\\d+(?:\\.\\d+)?"), "Invalid number.") - .transform(BigDecimal.class, new Function() { - @Override - public BigDecimal apply(String value) { - BigDecimal result = new BigDecimal(value); - if (result.signum() != 1) { - throw new FormFieldException("Must be a positive number."); - } - return result; - }}) + .transform( + BigDecimal.class, + value -> { + BigDecimal result = new BigDecimal(value); + if (result.signum() != 1) { + throw new FormFieldException("Must be a positive number."); + } + return result; + }) .build(); private static final FormField CURRENCY_FIELD = @@ -125,15 +124,15 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { .emptyToNull() .required() .matches(Pattern.compile("[A-Z]{3}"), "Invalid currency code.") - .transform(CurrencyUnit.class, new Function() { - @Override - public CurrencyUnit apply(String value) { - try { - return CurrencyUnit.of(value); - } catch (IllegalCurrencyException ignored) { - throw new FormFieldException("Unknown ISO currency code."); - } - }}) + .transform( + CurrencyUnit.class, + value -> { + try { + return CurrencyUnit.of(value); + } catch (IllegalCurrencyException ignored) { + throw new FormFieldException("Unknown ISO currency code."); + } + }) .build(); private static final FormField PAYMENT_METHOD_NONCE_FIELD = diff --git a/java/google/registry/ui/server/registrar/RegistrarPaymentSetupAction.java b/java/google/registry/ui/server/registrar/RegistrarPaymentSetupAction.java index a3dda2ad9..61ffdb23d 100644 --- a/java/google/registry/ui/server/registrar/RegistrarPaymentSetupAction.java +++ b/java/google/registry/ui/server/registrar/RegistrarPaymentSetupAction.java @@ -15,12 +15,12 @@ package google.registry.ui.server.registrar; import static com.google.common.base.Functions.toStringFunction; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.security.JsonResponseHelper.Status.ERROR; import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static java.util.Arrays.asList; import com.braintreegateway.BraintreeGateway; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import google.registry.braintree.BraintreeRegistrarSyncer; import google.registry.config.RegistryConfig.Config; @@ -107,14 +107,18 @@ public final class RegistrarPaymentSetupAction implements Runnable, JsonAction { // In order to set the customerId field on the payment, the customer must exist. customerSyncer.sync(registrar); - return JsonResponseHelper - .create(SUCCESS, "Success", asList( + return JsonResponseHelper.create( + SUCCESS, + "Success", + asList( ImmutableMap.of( "brainframe", brainframe, "token", braintreeGateway.clientToken().generate(), "currencies", - FluentIterable.from(accountIds.keySet()) - .transform(toStringFunction()) - .toList()))); + accountIds + .keySet() + .stream() + .map(toStringFunction()) + .collect(toImmutableList())))); } } diff --git a/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java b/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java index c9ab29529..2eaf24dc4 100644 --- a/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java +++ b/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java @@ -14,23 +14,22 @@ package google.registry.ui.server.registrar; -import static com.google.common.collect.Iterables.any; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Sets.difference; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.security.JsonResponseHelper.Status.ERROR; import static google.registry.security.JsonResponseHelper.Status.SUCCESS; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; +import com.google.common.collect.Streams; import com.googlecode.objectify.Work; import google.registry.config.RegistryConfig.Config; import google.registry.export.sheet.SyncRegistrarsSheetAction; @@ -53,7 +52,6 @@ import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; -import javax.annotation.Nullable; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @@ -82,11 +80,8 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA registrarChangesNotificationEmailAddresses; @Inject RegistrarSettingsAction() {} - private static final Predicate HAS_PHONE = new Predicate() { - @Override - public boolean apply(RegistrarContact contact) { - return contact.getPhoneNumber() != null; - }}; + private static final Predicate HAS_PHONE = + contact -> contact.getPhoneNumber() != null; @Override public void run() { @@ -160,13 +155,10 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA private Map expandRegistrarWithContacts(Iterable contacts, Registrar registrar) { - ImmutableSet> expandedContacts = FluentIterable.from(contacts) - .transform(new Function>() { - @Override - public Map apply(RegistrarContact contact) { - return contact.toDiffableFieldMap(); - }}) - .toSet(); + ImmutableSet> expandedContacts = + Streams.stream(contacts) + .map(RegistrarContact::toDiffableFieldMap) + .collect(toImmutableSet()); // Use LinkedHashMap here to preserve ordering; null values mean we can't use ImmutableMap. LinkedHashMap result = new LinkedHashMap<>(); result.putAll(registrar.toDiffableFieldMap()); @@ -286,8 +278,8 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA Multimap newContactsByType, RegistrarContact.Type... types) { for (RegistrarContact.Type type : types) { - if (any(oldContactsByType.get(type), HAS_PHONE) - && !any(newContactsByType.get(type), HAS_PHONE)) { + if (oldContactsByType.get(type).stream().anyMatch(HAS_PHONE) + && newContactsByType.get(type).stream().noneMatch(HAS_PHONE)) { throw new ContactRequirementException( String.format( "Please provide a phone number for at least one %s contact", @@ -306,12 +298,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA */ private static Optional getDomainWhoisVisibleAbuseContact( Set contacts) { - return Iterables.tryFind(contacts, new Predicate() { - @Override - public boolean apply(@Nullable RegistrarContact contact) { - return contact.getVisibleInDomainWhoisAsAbuse(); - } - }); + return Iterables.tryFind(contacts, RegistrarContact::getVisibleInDomainWhoisAsAbuse); } /** diff --git a/java/google/registry/ui/server/registrar/SendEmailUtils.java b/java/google/registry/ui/server/registrar/SendEmailUtils.java index 04a8e06d1..b8adf2430 100644 --- a/java/google/registry/ui/server/registrar/SendEmailUtils.java +++ b/java/google/registry/ui/server/registrar/SendEmailUtils.java @@ -14,12 +14,12 @@ package google.registry.ui.server.registrar; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.toArray; -import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicates; -import com.google.common.collect.FluentIterable; +import com.google.common.collect.Streams; import google.registry.config.RegistryConfig.Config; import google.registry.util.FormattingLogger; import google.registry.util.NonFinalForTesting; @@ -60,25 +60,25 @@ public class SendEmailUtils { Message msg = emailService.createMessage(); msg.setFrom( new InternetAddress(gSuiteOutgoingEmailAddress, gSuiteOutoingEmailDisplayName)); - List emails = FluentIterable - .from(addresses) - .transform(new Function() { - @Override - public InternetAddress apply(String emailAddress) { - try { - return new InternetAddress(emailAddress, true); - } catch (AddressException e) { - logger.severefmt( - e, - "Could not send email to %s with subject '%s'.", - emailAddress, - subject); - // Returning null excludes this address from the list of recipients on the email. - return null; - } - }}) - .filter(Predicates.notNull()) - .toList(); + List emails = + Streams.stream(addresses) + .map( + emailAddress -> { + try { + return new InternetAddress(emailAddress, true); + } catch (AddressException e) { + logger.severefmt( + e, + "Could not send email to %s with subject '%s'.", + emailAddress, + subject); + // Returning null excludes this address from the list of recipients on the + // email. + return null; + } + }) + .filter(Predicates.notNull()) + .collect(toImmutableList()); if (emails.isEmpty()) { return false; } diff --git a/java/google/registry/ui/server/registrar/SessionUtils.java b/java/google/registry/ui/server/registrar/SessionUtils.java index 34637f616..d8e7f88bf 100644 --- a/java/google/registry/ui/server/registrar/SessionUtils.java +++ b/java/google/registry/ui/server/registrar/SessionUtils.java @@ -21,9 +21,7 @@ import static google.registry.util.PreconditionsUtils.checkArgumentPresent; import com.google.appengine.api.users.User; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.base.Strings; -import com.google.common.collect.FluentIterable; import com.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.model.registrar.Registrar; @@ -33,7 +31,6 @@ import google.registry.request.auth.AuthResult; import google.registry.request.auth.UserAuthInfo; import google.registry.util.FormattingLogger; import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @@ -193,12 +190,9 @@ public class SessionUtils { /** Returns {@code true} if {@code gaeUserId} is listed in contacts. */ private static boolean hasAccessToRegistrar(Registrar registrar, final String gaeUserId) { - return FluentIterable - .from(registrar.getContacts()) - .anyMatch(new Predicate() { - @Override - public boolean apply(@Nonnull RegistrarContact contact) { - return gaeUserId.equals(contact.getGaeUserId()); - }}); + return registrar + .getContacts() + .stream() + .anyMatch(contact -> gaeUserId.equals(contact.getGaeUserId())); } } diff --git a/java/google/registry/util/Concurrent.java b/java/google/registry/util/Concurrent.java index e9e7358e8..256881bf0 100644 --- a/java/google/registry/util/Concurrent.java +++ b/java/google/registry/util/Concurrent.java @@ -16,19 +16,18 @@ package google.registry.util; import static com.google.appengine.api.ThreadManager.currentRequestThreadFactory; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.concurrent.Executors.newFixedThreadPool; import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.common.util.concurrent.Uninterruptibles; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; @@ -71,17 +70,13 @@ public final class Concurrent { // are not compatible with code that needs to interact with App Engine (such as Objectify), // which we often have in funk when calling Concurrent.transform(). // For more info see: http://stackoverflow.com/questions/15976406 - return FluentIterable.from(items).transform(funk).toList(); + return items.stream().map(funk).collect(toImmutableList()); } ExecutorService executor = newFixedThreadPool(threadCount, threadFactory); try { List> futures = new ArrayList<>(); for (final A item : items) { - futures.add(executor.submit(new Callable() { - @Override - public B call() { - return funk.apply(item); - }})); + futures.add(executor.submit(() -> funk.apply(item))); } ImmutableList.Builder results = new ImmutableList.Builder<>(); for (Future future : futures) { diff --git a/java/google/registry/util/DatastoreServiceUtils.java b/java/google/registry/util/DatastoreServiceUtils.java index 77d413ce3..8ae2976ac 100644 --- a/java/google/registry/util/DatastoreServiceUtils.java +++ b/java/google/registry/util/DatastoreServiceUtils.java @@ -22,11 +22,7 @@ import com.google.common.base.Optional; public class DatastoreServiceUtils { /** Helper function that extracts the kind from a regular Datastore entity key. */ - public static final Function KEY_TO_KIND_FUNCTION = new Function() { - @Override - public String apply(Key key) { - return key.getKind(); - }}; + public static final Function KEY_TO_KIND_FUNCTION = Key::getKind; /** Returns the name or id of a key, which may be a string or a long. */ public static Object getNameOrId(Key key) { diff --git a/java/google/registry/util/FormattingLogger.java b/java/google/registry/util/FormattingLogger.java index 48f046246..452e01c41 100644 --- a/java/google/registry/util/FormattingLogger.java +++ b/java/google/registry/util/FormattingLogger.java @@ -14,7 +14,6 @@ package google.registry.util; -import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import java.util.logging.Handler; import java.util.logging.Level; @@ -44,13 +43,10 @@ public class FormattingLogger { } private void log(Level level, @Nullable Throwable cause, String msg) { - StackTraceElement callerFrame = FluentIterable - .from(new Exception().getStackTrace()) - .firstMatch(new Predicate() { - @Override - public boolean apply(StackTraceElement frame) { - return !frame.getClassName().equals(FormattingLogger.class.getName()); - }}).get(); + StackTraceElement callerFrame = + FluentIterable.from(new Exception().getStackTrace()) + .firstMatch(frame -> !frame.getClassName().equals(FormattingLogger.class.getName())) + .get(); if (cause == null) { logger.logp(level, callerFrame.getClassName(), callerFrame.getMethodName(), msg); } else { diff --git a/java/google/registry/util/ObjectifyUtils.java b/java/google/registry/util/ObjectifyUtils.java index c19c6179d..7b99749da 100644 --- a/java/google/registry/util/ObjectifyUtils.java +++ b/java/google/registry/util/ObjectifyUtils.java @@ -20,9 +20,5 @@ import com.googlecode.objectify.Key; /** Utilities for working with Objectify. */ public class ObjectifyUtils { - public static final Function> OBJECTS_TO_KEYS = new Function>() { - @Override - public Key apply(Object obj) { - return Key.create(obj); - }}; + public static final Function> OBJECTS_TO_KEYS = Key::create; } diff --git a/java/google/registry/util/Retrier.java b/java/google/registry/util/Retrier.java index 5299f4cac..1ddea1f9a 100644 --- a/java/google/registry/util/Retrier.java +++ b/java/google/registry/util/Retrier.java @@ -16,7 +16,6 @@ package google.registry.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Throwables.throwIfUnchecked; -import static com.google.common.collect.Iterables.any; import static com.google.common.math.IntMath.pow; import static google.registry.util.PredicateUtils.supertypeOf; @@ -163,10 +162,7 @@ public class Retrier implements Serializable { Class... moreRetryableErrors) { final Set> retryables = new ImmutableSet.Builder>().add(retryableError).add(moreRetryableErrors).build(); - return callWithRetry(callable, failureReporter, new Predicate() { - @Override - public boolean apply(Throwable e) { - return any(retryables, supertypeOf(e.getClass())); - }}); + return callWithRetry( + callable, failureReporter, e -> retryables.stream().anyMatch(supertypeOf(e.getClass()))); } } diff --git a/java/google/registry/util/TaskEnqueuer.java b/java/google/registry/util/TaskEnqueuer.java index 076918b72..47f5b2466 100644 --- a/java/google/registry/util/TaskEnqueuer.java +++ b/java/google/registry/util/TaskEnqueuer.java @@ -22,7 +22,6 @@ import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TransientFailureException; import java.io.Serializable; import java.util.List; -import java.util.concurrent.Callable; import javax.inject.Inject; /** Utilities for dealing with App Engine task queues. */ @@ -65,15 +64,13 @@ public class TaskEnqueuer implements Serializable { */ public List enqueue(final Queue queue, final Iterable tasks) { return retrier.callWithRetry( - new Callable>() { - @Override - public List call() { - for (TaskOptions task : tasks) { - logger.infofmt( - "Enqueuing queue='%s' endpoint='%s'", queue.getQueueName(), task.getUrl()); - } - return queue.add(tasks); - }}, + () -> { + for (TaskOptions task : tasks) { + logger.infofmt( + "Enqueuing queue='%s' endpoint='%s'", queue.getQueueName(), task.getUrl()); + } + return queue.add(tasks); + }, TransientFailureException.class); } } diff --git a/java/google/registry/util/TokenUtils.java b/java/google/registry/util/TokenUtils.java index dcafc5390..64dd9b729 100644 --- a/java/google/registry/util/TokenUtils.java +++ b/java/google/registry/util/TokenUtils.java @@ -14,8 +14,8 @@ package google.registry.util; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; +import static com.google.common.collect.ImmutableSet.toImmutableSet; + import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -59,13 +59,11 @@ public final class TokenUtils { final TokenType type, StringGenerator generator, int count) { - return FluentIterable.from(generator.createStrings(type.getLength(), count)) - .transform(new Function() { - @Override - public String apply(String token) { - return String.format("%s_%s", type.getPrefix(), token); - }}) - .toSet(); + return generator + .createStrings(type.getLength(), count) + .stream() + .map(token -> String.format("%s_%s", type.getPrefix(), token)) + .collect(toImmutableSet()); } private TokenUtils() {} diff --git a/java/google/registry/util/TypeUtils.java b/java/google/registry/util/TypeUtils.java index b06b4dd25..1796928bb 100644 --- a/java/google/registry/util/TypeUtils.java +++ b/java/google/registry/util/TypeUtils.java @@ -103,7 +103,7 @@ public class TypeUtils { /** Returns a predicate that tests whether classes are annotated with the given annotation. */ public static final Predicate> hasAnnotation( final Class annotation) { - return (Class clazz) -> clazz.isAnnotationPresent(annotation); + return clazz -> clazz.isAnnotationPresent(annotation); } public static void checkNoInheritanceRelationships(ImmutableSet> resourceClasses) { diff --git a/java/google/registry/util/X509Utils.java b/java/google/registry/util/X509Utils.java index e77c897a9..0a3ea1ffd 100644 --- a/java/google/registry/util/X509Utils.java +++ b/java/google/registry/util/X509Utils.java @@ -17,12 +17,11 @@ package google.registry.util; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.throwIfInstanceOf; +import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.common.io.BaseEncoding.base64; import static java.nio.charset.StandardCharsets.US_ASCII; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -72,9 +71,12 @@ public final class X509Utils { public static X509Certificate loadCertificate(InputStream input) throws CertificateParsingException { try { - return Iterables.getOnlyElement(FluentIterable - .from(CertificateFactory.getInstance("X.509").generateCertificates(input)) - .filter(X509Certificate.class)); + return CertificateFactory.getInstance("X.509") + .generateCertificates(input) + .stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .collect(onlyElement()); } catch (CertificateException e) { // CertificateParsingException by specification. throwIfInstanceOf(e, CertificateParsingException.class); throw new CertificateParsingException(e); @@ -114,9 +116,12 @@ public final class X509Utils { public static X509CRL loadCrl(String asciiCrl) throws GeneralSecurityException { ByteArrayInputStream input = new ByteArrayInputStream(asciiCrl.getBytes(US_ASCII)); try { - return Iterables.getOnlyElement(FluentIterable - .from(CertificateFactory.getInstance("X.509").generateCRLs(input)) - .filter(X509CRL.class)); + return CertificateFactory.getInstance("X.509") + .generateCRLs(input) + .stream() + .filter(X509CRL.class::isInstance) + .map(X509CRL.class::cast) + .collect(onlyElement()); } catch (NoSuchElementException e) { throw new CRLException("No X509CRL found."); } catch (IllegalArgumentException e) { diff --git a/java/google/registry/whois/DomainWhoisResponse.java b/java/google/registry/whois/DomainWhoisResponse.java index 140c8ceea..d6587a391 100644 --- a/java/google/registry/whois/DomainWhoisResponse.java +++ b/java/google/registry/whois/DomainWhoisResponse.java @@ -21,9 +21,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.CollectionUtils.isNullOrEmpty; import static google.registry.xml.UtcDateTimeAdapter.getFormattedString; -import com.google.common.base.Function; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -77,13 +75,7 @@ final class DomainWhoisResponse extends WhoisResponseImpl { Registrar registrar = registrarOptional.get(); Optional abuseContact = Iterables.tryFind( - registrar.getContacts(), - new Predicate() { - @Override - public boolean apply(@Nullable RegistrarContact contact) { - return contact.getVisibleInDomainWhoisAsAbuse(); - } - }); + registrar.getContacts(), RegistrarContact::getVisibleInDomainWhoisAsAbuse); String plaintext = new DomainEmitter() .emitField( @@ -97,9 +89,7 @@ final class DomainWhoisResponse extends WhoisResponseImpl { .emitField( "Registry Expiry Date", getFormattedString(domain.getRegistrationExpirationTime())) .emitField("Registrar", registrar.getRegistrarName()) - .emitField( - "Registrar IANA ID", - Objects.toString(registrar.getIanaIdentifier(), "")) + .emitField("Registrar IANA ID", Objects.toString(registrar.getIanaIdentifier(), "")) // Email address is a required field for registrar contacts. Therefore as long as there // is an abuse contact, we can get an email address from it. .emitFieldIfDefined( @@ -116,12 +106,7 @@ final class DomainWhoisResponse extends WhoisResponseImpl { .emitSet( "Name Server", domain.loadNameserverFullyQualifiedHostNames(), - new Function() { - @Override - public String apply(String hostName) { - return maybeFormatHostname(hostName, preferUnicode); - } - }) + hostName -> maybeFormatHostname(hostName, preferUnicode)) .emitField( "DNSSEC", isNullOrEmpty(domain.getDsData()) ? "unsigned" : "signedDelegation") .emitWicfLink() @@ -135,12 +120,8 @@ final class DomainWhoisResponse extends WhoisResponseImpl { /** Returns the contact of the given type, or null if it does not exist. */ @Nullable private Key getContactReference(final Type type) { - Optional contactOfType = tryFind(domain.getContacts(), - new Predicate() { - @Override - public boolean apply(DesignatedContact d) { - return d.getType() == type; - }}); + Optional contactOfType = + tryFind(domain.getContacts(), d -> d.getType() == type); return contactOfType.isPresent() ? contactOfType.get().getContactKey() : null; } @@ -200,12 +181,10 @@ final class DomainWhoisResponse extends WhoisResponseImpl { return emitSet( "Domain Status", combinedStatuses.build(), - new Function() { - @Override - public String apply(EppEnum status) { - String xmlName = status.getXmlName(); - return String.format("%s %s%s", xmlName, ICANN_STATUS_URL_PREFIX, xmlName); - }}); + status -> { + String xmlName = status.getXmlName(); + return String.format("%s %s%s", xmlName, ICANN_STATUS_URL_PREFIX, xmlName); + }); } /** Emits the message that AWIP requires accompany all domain WHOIS responses. */ diff --git a/java/google/registry/whois/NameserverLookupByIpCommand.java b/java/google/registry/whois/NameserverLookupByIpCommand.java index b0c7da108..e15f446f3 100644 --- a/java/google/registry/whois/NameserverLookupByIpCommand.java +++ b/java/google/registry/whois/NameserverLookupByIpCommand.java @@ -15,13 +15,13 @@ package google.registry.whois; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ImmutableList.toImmutableList; import static google.registry.model.EppResourceUtils.queryNotDeleted; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Streams; import com.google.common.net.InternetDomainName; import google.registry.model.host.HostResource; import google.registry.model.registry.Registries; @@ -47,16 +47,14 @@ final class NameserverLookupByIpCommand implements WhoisCommand { @Override public WhoisResponse executeQuery(DateTime now) throws WhoisException { - ImmutableList hosts = FluentIterable - .from(queryNotDeleted(HostResource.class, now, "inetAddresses", ipAddress)) - .filter(new Predicate() { - @Override - public boolean apply(final HostResource host) { - return Registries - .findTldForName(InternetDomainName.from(host.getFullyQualifiedHostName())) - .isPresent(); - }}) - .toList(); + ImmutableList hosts = + Streams.stream(queryNotDeleted(HostResource.class, now, "inetAddresses", ipAddress)) + .filter( + host -> + Registries.findTldForName( + InternetDomainName.from(host.getFullyQualifiedHostName())) + .isPresent()) + .collect(toImmutableList()); if (hosts.isEmpty()) { throw new WhoisException(now, SC_NOT_FOUND, "No nameservers found."); } diff --git a/java/google/registry/whois/NameserverWhoisResponse.java b/java/google/registry/whois/NameserverWhoisResponse.java index c626984e2..57362fc9f 100644 --- a/java/google/registry/whois/NameserverWhoisResponse.java +++ b/java/google/registry/whois/NameserverWhoisResponse.java @@ -18,13 +18,11 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static google.registry.model.ofy.ObjectifyService.ofy; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.net.InetAddresses; import google.registry.model.host.HostResource; import google.registry.model.registrar.Registrar; -import java.net.InetAddress; import org.joda.time.DateTime; /** Container for WHOIS responses to a nameserver lookup queries. */ @@ -60,15 +58,7 @@ final class NameserverWhoisResponse extends WhoisResponseImpl { emitter .emitField( "Server Name", maybeFormatHostname(host.getFullyQualifiedHostName(), preferUnicode)) - .emitSet( - "IP Address", - host.getInetAddresses(), - new Function() { - @Override - public String apply(InetAddress addr) { - return InetAddresses.toAddrString(addr); - } - }) + .emitSet("IP Address", host.getInetAddresses(), InetAddresses::toAddrString) .emitField("Registrar", registrar.get().getRegistrarName()) .emitField("Registrar WHOIS Server", registrar.get().getWhoisServer()) .emitField("Registrar URL", registrar.get().getReferralUrl()); diff --git a/java/google/registry/whois/RegistrarLookupCommand.java b/java/google/registry/whois/RegistrarLookupCommand.java index 65e4fa930..0fe2b7eb1 100644 --- a/java/google/registry/whois/RegistrarLookupCommand.java +++ b/java/google/registry/whois/RegistrarLookupCommand.java @@ -45,42 +45,42 @@ final class RegistrarLookupCommand implements WhoisCommand { * WHOIS. */ private static final Supplier> REGISTRAR_BY_NORMALIZED_NAME_CACHE = - memoizeWithShortExpiration(new Supplier>() { - @Override - public Map get() { - Map map = new HashMap<>(); - // Use the normalized registrar name as a key, and ignore inactive and hidden registrars. - for (Registrar registrar : Registrar.loadAllCached()) { - if (!registrar.isLiveAndPubliclyVisible() || registrar.getRegistrarName() == null) { - continue; - } - String normalized = normalizeRegistrarName(registrar.getRegistrarName()); - if (map.put(normalized, registrar) != null) { - logger.warning(normalized - + " appeared as a normalized registrar name for more than one registrar"); - } - } - // Use the normalized registrar name without its last word as a key, assuming there are - // multiple words in the name. This allows searches without LLC or INC, etc. Only insert - // if there isn't already a mapping for this string, so that if there's a registrar with a - // two word name (Go Daddy) and no business-type suffix and another registrar with just - // that first word as its name (Go), the latter will win. - for (Registrar registrar : ImmutableList.copyOf(map.values())) { - if (registrar.getRegistrarName() == null) { - continue; - } - List words = - Splitter.on(CharMatcher.whitespace()).splitToList(registrar.getRegistrarName()); - if (words.size() > 1) { - String normalized = - normalizeRegistrarName(Joiner.on("").join(words.subList(0, words.size() - 1))); - if (!map.containsKey(normalized)) { - map.put(normalized, registrar); + memoizeWithShortExpiration( + () -> { + Map map = new HashMap<>(); + // Use the normalized registrar name as a key, and ignore inactive and hidden + // registrars. + for (Registrar registrar : Registrar.loadAllCached()) { + if (!registrar.isLiveAndPubliclyVisible() || registrar.getRegistrarName() == null) { + continue; + } + String normalized = normalizeRegistrarName(registrar.getRegistrarName()); + if (map.put(normalized, registrar) != null) { + logger.warning( + normalized + + " appeared as a normalized registrar name for more than one registrar"); } } - } - return ImmutableMap.copyOf(map); - }}); + // Use the normalized registrar name without its last word as a key, assuming there are + // multiple words in the name. This allows searches without LLC or INC, etc. Only insert + // if there isn't already a mapping for this string, so that if there's a registrar with + // a + // two word name (Go Daddy) and no business-type suffix and another registrar with just + // that first word as its name (Go), the latter will win. + for (Registrar registrar : ImmutableList.copyOf(map.values())) { + if (registrar.getRegistrarName() == null) { + continue; + } + List words = + Splitter.on(CharMatcher.whitespace()).splitToList(registrar.getRegistrarName()); + if (words.size() > 1) { + String normalized = + normalizeRegistrarName(Joiner.on("").join(words.subList(0, words.size() - 1))); + map.putIfAbsent(normalized, registrar); + } + } + return ImmutableMap.copyOf(map); + }); @VisibleForTesting final String registrarName; diff --git a/java/google/registry/whois/WhoisResponseImpl.java b/java/google/registry/whois/WhoisResponseImpl.java index 153197d9c..a440c10d2 100644 --- a/java/google/registry/whois/WhoisResponseImpl.java +++ b/java/google/registry/whois/WhoisResponseImpl.java @@ -16,13 +16,12 @@ package google.registry.whois; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.html.HtmlEscapers.htmlEscaper; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Ordering; import google.registry.model.eppcommon.Address; import google.registry.util.Idn; import google.registry.xml.UtcDateTimeAdapter; @@ -93,10 +92,7 @@ abstract class WhoisResponseImpl implements WhoisResponse { * be to use {@link java.util.SortedSet} but that would require reworking the models. */ E emitSet(String title, Set values, Function transform) { - return emitList(title, FluentIterable - .from(values) - .transform(transform) - .toSortedList(Ordering.natural())); + return emitList(title, values.stream().map(transform).sorted().collect(toImmutableList())); } /** Helper method that loops over a list of values and calls {@link #emitField}. */ diff --git a/javatests/google/registry/backup/GcsDiffFileListerTest.java b/javatests/google/registry/backup/GcsDiffFileListerTest.java index 3d78875df..6649298ee 100644 --- a/javatests/google/registry/backup/GcsDiffFileListerTest.java +++ b/javatests/google/registry/backup/GcsDiffFileListerTest.java @@ -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 extractTimesFromDiffFiles(List diffFiles) { return transform( diffFiles, - new Function() { - @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 listDiffFiles(DateTime fromTime, DateTime toTime) { diff --git a/javatests/google/registry/backup/RestoreCommitLogsActionTest.java b/javatests/google/registry/backup/RestoreCommitLogsActionTest.java index 397f4fbf2..3274b0598 100644 --- a/javatests/google/registry/backup/RestoreCommitLogsActionTest.java +++ b/javatests/google/registry/backup/RestoreCommitLogsActionTest.java @@ -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() { - @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 entities) { diff --git a/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java b/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java index 37ef608ae..fba1ffb5f 100644 --- a/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java +++ b/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java @@ -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(); diff --git a/javatests/google/registry/cron/TldFanoutActionTest.java b/javatests/google/registry/cron/TldFanoutActionTest.java index 641f46254..7cd50e8b7 100644 --- a/javatests/google/registry/cron/TldFanoutActionTest.java +++ b/javatests/google/registry/cron/TldFanoutActionTest.java @@ -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() { - @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 diff --git a/javatests/google/registry/dns/ReadDnsQueueActionTest.java b/javatests/google/registry/dns/ReadDnsQueueActionTest.java index be3d4dc20..93d3cd38f 100644 --- a/javatests/google/registry/dns/ReadDnsQueueActionTest.java +++ b/javatests/google/registry/dns/ReadDnsQueueActionTest.java @@ -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, TaskMatcher>() { - @Override - public TaskMatcher apply(Entry tldToDnsWriter) { - return new TaskMatcher() + (Entry 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 diff --git a/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java b/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java index f1317bbed..e48673ea5 100644 --- a/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java +++ b/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java @@ -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() { - @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())); } }); diff --git a/javatests/google/registry/export/DatastoreBackupServiceTest.java b/javatests/google/registry/export/DatastoreBackupServiceTest.java index 46c210e99..0bdffbae5 100644 --- a/javatests/google/registry/export/DatastoreBackupServiceTest.java +++ b/javatests/google/registry/export/DatastoreBackupServiceTest.java @@ -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 BACKUP_NAME_GETTER = - new Function() { - @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 diff --git a/javatests/google/registry/export/ExportConstantsTest.java b/javatests/google/registry/export/ExportConstantsTest.java index 11ec840f4..aaccc9639 100644 --- a/javatests/google/registry/export/ExportConstantsTest.java +++ b/javatests/google/registry/export/ExportConstantsTest.java @@ -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 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() { - @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()); } } diff --git a/javatests/google/registry/export/LoadSnapshotActionTest.java b/javatests/google/registry/export/LoadSnapshotActionTest.java index dacdc3967..a2eb35f6a 100644 --- a/javatests/google/registry/export/LoadSnapshotActionTest.java +++ b/javatests/google/registry/export/LoadSnapshotActionTest.java @@ -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() { - @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() { - @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() { - @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(); diff --git a/javatests/google/registry/export/SyncGroupMembersActionTest.java b/javatests/google/registry/export/SyncGroupMembersActionTest.java index 764e3cd6c..13aa2e08e 100644 --- a/javatests/google/registry/export/SyncGroupMembersActionTest.java +++ b/javatests/google/registry/export/SyncGroupMembersActionTest.java @@ -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() { - @Override - public boolean apply(Registrar registrar) { - return registrar.getContactsRequireSyncing(); - }})).isEmpty(); + assertThat(Iterables.filter(Registrar.loadAll(), Registrar::getContactsRequireSyncing)) + .isEmpty(); } @Test diff --git a/javatests/google/registry/export/UpdateSnapshotViewActionTest.java b/javatests/google/registry/export/UpdateSnapshotViewActionTest.java index 02af935dc..a28be2a92 100644 --- a/javatests/google/registry/export/UpdateSnapshotViewActionTest.java +++ b/javatests/google/registry/export/UpdateSnapshotViewActionTest.java @@ -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 actualQueries = - Iterables.transform( - tableArg.getAllValues(), - new Function() { - @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`"); diff --git a/javatests/google/registry/flows/FlowTestCase.java b/javatests/google/registry/flows/FlowTestCase.java index 0dea8af89..7ccfca824 100644 --- a/javatests/google/registry/flows/FlowTestCase.java +++ b/javatests/google/registry/flows/FlowTestCase.java @@ -178,19 +178,6 @@ public abstract class FlowTestCase extends ShardableTestCase { } /** Helper to remove the grace period's billing event key to facilitate comparison. */ - private static final Function GRACE_PERIOD_KEY_STRIPPER = - new Function() { - @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 { private HistoryEntry historyEntry; @@ -220,7 +207,16 @@ public abstract class FlowTestCase extends ShardableTestCase { ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); for (Map.Entry entry : gracePeriods.entrySet()) { builder.put( - GRACE_PERIOD_KEY_STRIPPER.apply(entry.getKey()), + ((Function) + 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 extends ShardableTestCase { Iterable actual, ImmutableMap expected) { Function gracePeriodExpander = - new Function() { - @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 extends ShardableTestCase { throws Exception { // To facilitate comparison, remove the ids. Function idStripper = - new Function() { - @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)); diff --git a/javatests/google/registry/flows/ResourceFlowTestCase.java b/javatests/google/registry/flows/ResourceFlowTestCase.java index ca0424a46..83a4e0740 100644 --- a/javatests/google/registry/flows/ResourceFlowTestCase.java +++ b/javatests/google/registry/flows/ResourceFlowTestCase.java @@ -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 void assertEppResourceIndexEntityFor(final T resource) { - ImmutableList indices = FluentIterable - .from(ofy().load() - .type(EppResourceIndex.class) - .filter("kind", Key.getKind(resource.getClass()))) - .filter(new Predicate() { - @Override - public boolean apply(EppResourceIndex index) { - return Key.create(resource).equals(index.getKey()) - && ofy().load().key(index.getKey()).now().equals(resource); - }}) - .toList(); + ImmutableList 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))); diff --git a/javatests/google/registry/flows/contact/ContactTransferApproveFlowTest.java b/javatests/google/registry/flows/contact/ContactTransferApproveFlowTest.java index d41bc6803..a841d62b9 100644 --- a/javatests/google/registry/flows/contact/ContactTransferApproveFlowTest.java +++ b/javatests/google/registry/flows/contact/ContactTransferApproveFlowTest.java @@ -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(); diff --git a/javatests/google/registry/flows/contact/ContactTransferCancelFlowTest.java b/javatests/google/registry/flows/contact/ContactTransferCancelFlowTest.java index 57b33d3ca..563cfe246 100644 --- a/javatests/google/registry/flows/contact/ContactTransferCancelFlowTest.java +++ b/javatests/google/registry/flows/contact/ContactTransferCancelFlowTest.java @@ -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 { diff --git a/javatests/google/registry/flows/contact/ContactTransferRejectFlowTest.java b/javatests/google/registry/flows/contact/ContactTransferRejectFlowTest.java index 7213ad424..00d767cbb 100644 --- a/javatests/google/registry/flows/contact/ContactTransferRejectFlowTest.java +++ b/javatests/google/registry/flows/contact/ContactTransferRejectFlowTest.java @@ -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(); diff --git a/javatests/google/registry/flows/contact/ContactTransferRequestFlowTest.java b/javatests/google/registry/flows/contact/ContactTransferRequestFlowTest.java index 12b4a9d78..d68d84c7f 100644 --- a/javatests/google/registry/flows/contact/ContactTransferRequestFlowTest.java +++ b/javatests/google/registry/flows/contact/ContactTransferRequestFlowTest.java @@ -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. diff --git a/javatests/google/registry/flows/domain/DomainApplicationCreateFlowTest.java b/javatests/google/registry/flows/domain/DomainApplicationCreateFlowTest.java index f9c2d7b0f..9a071c23e 100644 --- a/javatests/google/registry/flows/domain/DomainApplicationCreateFlowTest.java +++ b/javatests/google/registry/flows/domain/DomainApplicationCreateFlowTest.java @@ -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 applications = ofy().load().type(DomainApplication.class).list(); - Collections.sort(applications, new Comparator() { - @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() diff --git a/javatests/google/registry/flows/domain/DomainApplicationInfoFlowTest.java b/javatests/google/registry/flows/domain/DomainApplicationInfoFlowTest.java index 90d13a039..317111e3f 100644 --- a/javatests/google/registry/flows/domain/DomainApplicationInfoFlowTest.java +++ b/javatests/google/registry/flows/domain/DomainApplicationInfoFlowTest.java @@ -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>() { - @Override - public boolean apply(List 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); } diff --git a/javatests/google/registry/flows/domain/DomainDeleteFlowTest.java b/javatests/google/registry/flows/domain/DomainDeleteFlowTest.java index 959b1b5fc..fc670efad 100644 --- a/javatests/google/registry/flows/domain/DomainDeleteFlowTest.java +++ b/javatests/google/registry/flows/domain/DomainDeleteFlowTest.java @@ -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>() { - @Override - public boolean apply(List 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); } diff --git a/javatests/google/registry/flows/domain/DomainTransferApproveFlowTest.java b/javatests/google/registry/flows/domain/DomainTransferApproveFlowTest.java index 9011d0f58..8cf5211c4 100644 --- a/javatests/google/registry/flows/domain/DomainTransferApproveFlowTest.java +++ b/javatests/google/registry/flows/domain/DomainTransferApproveFlowTest.java @@ -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() { - @Override - public Cancellation apply(Builder builder) { - return builder.setParent(historyEntryTransferApproved).build(); - } - }) + (Function) + builder -> builder.setParent(historyEntryTransferApproved).build()) .append( transferBillingEvent, getLosingClientAutorenewEvent() @@ -292,12 +293,8 @@ public class DomainTransferApproveFlowTest domain, FluentIterable.from(expectedCancellationBillingEvents) .transform( - new Function() { - @Override - public Cancellation apply(Builder builder) { - return builder.setParent(historyEntryTransferApproved).build(); - } - }) + (Function) + builder -> builder.setParent(historyEntryTransferApproved).build()) .append( getLosingClientAutorenewEvent() .asBuilder() diff --git a/javatests/google/registry/flows/domain/DomainTransferRejectFlowTest.java b/javatests/google/registry/flows/domain/DomainTransferRejectFlowTest.java index 4c3431818..6d413e21f 100644 --- a/javatests/google/registry/flows/domain/DomainTransferRejectFlowTest.java +++ b/javatests/google/registry/flows/domain/DomainTransferRejectFlowTest.java @@ -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(); diff --git a/javatests/google/registry/flows/domain/DomainTransferRequestFlowTest.java b/javatests/google/registry/flows/domain/DomainTransferRequestFlowTest.java index 13890ce6e..8378f2851 100644 --- a/javatests/google/registry/flows/domain/DomainTransferRequestFlowTest.java +++ b/javatests/google/registry/flows/domain/DomainTransferRequestFlowTest.java @@ -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 extraBillingEvents = - FluentIterable.from(extraExpectedBillingEvents) - .transform( - new Function() { - @Override - public BillingEvent apply(Builder builder) { - return builder.setParent(historyEntryTransferRequest).build(); - }}) - .toList(); + Stream.of(extraExpectedBillingEvents) + .map( + (Function) + 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() { - @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( diff --git a/javatests/google/registry/model/EntityTestCase.java b/javatests/google/registry/model/EntityTestCase.java index d86e85a63..494e97e2a 100644 --- a/javatests/google/registry/model/EntityTestCase.java +++ b/javatests/google/registry/model/EntityTestCase.java @@ -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(){ - @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()); } diff --git a/javatests/google/registry/model/domain/DomainResourceTest.java b/javatests/google/registry/model/domain/DomainResourceTest.java index 0ab68a05a..031b8ea8f 100644 --- a/javatests/google/registry/model/domain/DomainResourceTest.java +++ b/javatests/google/registry/model/domain/DomainResourceTest.java @@ -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 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(); diff --git a/javatests/google/registry/model/registry/label/PremiumListTest.java b/javatests/google/registry/model/registry/label/PremiumListTest.java index eb0aac57e..731674848 100644 --- a/javatests/google/registry/model/registry/label/PremiumListTest.java +++ b/javatests/google/registry/model/registry/label/PremiumListTest.java @@ -95,9 +95,5 @@ public class PremiumListTest { /** Gets the label of a premium list entry. */ public static final Function, String> GET_ENTRY_NAME_FUNCTION = - new Function, String>() { - @Override - public String apply(final Key input) { - return input.getName(); - }}; + Key::getName; } diff --git a/javatests/google/registry/model/registry/label/ReservedListTest.java b/javatests/google/registry/model/registry/label/ReservedListTest.java index 493cc2be4..d112361ec 100644 --- a/javatests/google/registry/model/registry/label/ReservedListTest.java +++ b/javatests/google/registry/model/registry/label/ReservedListTest.java @@ -551,10 +551,5 @@ public class ReservedListTest { } /** Gets the name of a reserved list. */ - public static final Function, String> GET_NAME_FUNCTION = - new Function, String>() { - @Override - public String apply(final Key input) { - return input.getName(); - }}; + public static final Function, String> GET_NAME_FUNCTION = Key::getName; } diff --git a/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java b/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java index 92f3f431b..f3d8542e6 100644 --- a/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java +++ b/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java @@ -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, Long>>() { - @Override - public ImmutableMap, Long> get() { - return ImmutableMap.of(ImmutableList.of("foo"), 1L); - } - }, + () -> ImmutableMap.of(ImmutableList.of("foo"), 1L), Long.class); assertThat(testGauge.getValueClass()).isSameAs(Long.class); diff --git a/javatests/google/registry/monitoring/metrics/example/SheepCounterExample.java b/javatests/google/registry/monitoring/metrics/example/SheepCounterExample.java index 8bc814546..40b771ae6 100644 --- a/javatests/google/registry/monitoring/metrics/example/SheepCounterExample.java +++ b/javatests/google/registry/monitoring/metrics/example/SheepCounterExample.java @@ -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.of(), - new Supplier, Double>>() { - @Override - public ImmutableMap, Double> get() { - return ImmutableMap.of(ImmutableList.of(), new Random().nextDouble()); - } - }, + () -> ImmutableMap.of(ImmutableList.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."); diff --git a/javatests/google/registry/rde/ContactResourceToXjcConverterTest.java b/javatests/google/registry/rde/ContactResourceToXjcConverterTest.java index 224f79f81..3e4d13e79 100644 --- a/javatests/google/registry/rde/ContactResourceToXjcConverterTest.java +++ b/javatests/google/registry/rde/ContactResourceToXjcConverterTest.java @@ -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 elements that describe the status of the // contact object. - assertThat( - FluentIterable - .from(bean.getStatuses()) - .transform(new Function() { - @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); diff --git a/javatests/google/registry/rde/DomainResourceToXjcConverterTest.java b/javatests/google/registry/rde/DomainResourceToXjcConverterTest.java index d527a7505..e5f8eb54d 100644 --- a/javatests/google/registry/rde/DomainResourceToXjcConverterTest.java +++ b/javatests/google/registry/rde/DomainResourceToXjcConverterTest.java @@ -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() { - @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() { - @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() { - @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")); diff --git a/javatests/google/registry/rde/RdeStagingActionTest.java b/javatests/google/registry/rde/RdeStagingActionTest.java index f966acbe4..a1d4270ae 100644 --- a/javatests/google/registry/rde/RdeStagingActionTest.java +++ b/javatests/google/registry/rde/RdeStagingActionTest.java @@ -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 { ListResult listResult = gcsService.list("rde-bucket", new ListOptions.Builder().setPrefix("manual/test").build()); ImmutableSet filenames = - FluentIterable.from(ImmutableList.copyOf(listResult)) - .transform( - new Function() { - @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( diff --git a/javatests/google/registry/rde/imports/RdeImportUtilsTest.java b/javatests/google/registry/rde/imports/RdeImportUtilsTest.java index 935401865..bc5a8a41b 100644 --- a/javatests/google/registry/rde/imports/RdeImportUtilsTest.java +++ b/javatests/google/registry/rde/imports/RdeImportUtilsTest.java @@ -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 void assertEppResourceIndexEntityFor(final T resource) { - ImmutableList indices = FluentIterable - .from(ofy().load() - .type(EppResourceIndex.class) - .filter("kind", Key.getKind(resource.getClass()))) - .filter(new Predicate() { - @Override - public boolean apply(EppResourceIndex index) { - return ofy().load().key(index.getKey()).now().equals(resource); - }}) - .toList(); + ImmutableList 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))); diff --git a/javatests/google/registry/security/JsonHttpTestUtils.java b/javatests/google/registry/security/JsonHttpTestUtils.java index f1f0b1332..1b33c3868 100644 --- a/javatests/google/registry/security/JsonHttpTestUtils.java +++ b/javatests/google/registry/security/JsonHttpTestUtils.java @@ -80,10 +80,6 @@ public final class JsonHttpTestUtils { */ public static Supplier> createJsonResponseSupplier( final StringWriter writer) { - return memoize(new Supplier>() { - @Override - public Map get() { - return getJsonResponse(writer); - }}); + return memoize(() -> getJsonResponse(writer)); } } diff --git a/javatests/google/registry/server/StaticResourceServlet.java b/javatests/google/registry/server/StaticResourceServlet.java index 2762bc224..d934fa789 100644 --- a/javatests/google/registry/server/StaticResourceServlet.java +++ b/javatests/google/registry/server/StaticResourceServlet.java @@ -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); diff --git a/javatests/google/registry/server/TestServer.java b/javatests/google/registry/server/TestServer.java index daa9ce5bc..12e4c7eff 100644 --- a/javatests/google/registry/server/TestServer.java +++ b/javatests/google/registry/server/TestServer.java @@ -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() { - @Nullable - @Override - public Void call() throws Exception { - server.stop(); - return null; - } + () -> { + server.stop(); + return null; }, SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS); diff --git a/javatests/google/registry/server/UrlChecker.java b/javatests/google/registry/server/UrlChecker.java index bda4d5a4d..d6ff64824 100644 --- a/javatests/google/registry/server/UrlChecker.java +++ b/javatests/google/registry/server/UrlChecker.java @@ -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() { - @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); diff --git a/javatests/google/registry/testing/DatastoreHelper.java b/javatests/google/registry/testing/DatastoreHelper.java index 676e17b55..87e0fc468 100644 --- a/javatests/google/registry/testing/DatastoreHelper.java +++ b/javatests/google/registry/testing/DatastoreHelper.java @@ -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 DEFAULT_PREMIUM_LIST_CONTENTS = - memoize(new Supplier() { - @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 BILLING_EVENT_ID_STRIPPER = - new Function() { - @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 POLL_MESSAGE_ID_STRIPPER = - new Function() { - @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 getPollMessages() { - return FluentIterable.from(ofy().load().type(PollMessage.class)).toList(); + return Streams.stream(ofy().load().type(PollMessage.class)).collect(toImmutableList()); } public static ImmutableList 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 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 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 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 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 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 getHistoryEntriesOfType( EppResource resource, final HistoryEntry.Type type) { - return FluentIterable.from(getHistoryEntries(resource)) - .filter(new Predicate() { - @Override - public boolean apply(HistoryEntry entry) { - return entry.getType() == type; - }}) - .toList(); + return getHistoryEntries(resource) + .stream() + .filter(entry -> entry.getType() == type) + .collect(toImmutableList()); } /** diff --git a/javatests/google/registry/testing/SystemPropertyRule.java b/javatests/google/registry/testing/SystemPropertyRule.java index 1c5696cf4..79f0c0f7a 100644 --- a/javatests/google/registry/testing/SystemPropertyRule.java +++ b/javatests/google/registry/testing/SystemPropertyRule.java @@ -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(); diff --git a/javatests/google/registry/testing/TaskQueueHelper.java b/javatests/google/registry/testing/TaskQueueHelper.java index 0f3d83924..8d59e1785 100644 --- a/javatests/google/registry/testing/TaskQueueHelper.java +++ b/javatests/google/registry/testing/TaskQueueHelper.java @@ -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() { - @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 nameGetter = new Function() { - @Nonnull - @Override - public String apply(@Nonnull TaskStateInfo taskStateInfo) { - return taskStateInfo.getTaskName(); - }}; + Function 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 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() { - @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() { - @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); } diff --git a/javatests/google/registry/testing/TestLogHandlerUtils.java b/javatests/google/registry/testing/TestLogHandlerUtils.java index c9e5d286f..702619b29 100644 --- a/javatests/google/registry/testing/TestLogHandlerUtils.java +++ b/javatests/google/registry/testing/TestLogHandlerUtils.java @@ -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() { - @Override - public boolean apply(LogRecord logRecord) { - return logRecord.getMessage().startsWith(prefix); - } - }); + handler.getStoredLogRecords(), logRecord -> logRecord.getMessage().startsWith(prefix)); } } diff --git a/javatests/google/registry/tools/ResaveEntitiesCommandTest.java b/javatests/google/registry/tools/ResaveEntitiesCommandTest.java index 694db437b..dd5076a3f 100644 --- a/javatests/google/registry/tools/ResaveEntitiesCommandTest.java +++ b/javatests/google/registry/tools/ResaveEntitiesCommandTest.java @@ -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 savedEntities = transform( ofy().load().type(CommitLogMutation.class).list(), - new Function() { - @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) diff --git a/javatests/google/registry/tools/ResaveEnvironmentEntitiesCommandTest.java b/javatests/google/registry/tools/ResaveEnvironmentEntitiesCommandTest.java index 897e15372..7b754cd7e 100644 --- a/javatests/google/registry/tools/ResaveEnvironmentEntitiesCommandTest.java +++ b/javatests/google/registry/tools/ResaveEnvironmentEntitiesCommandTest.java @@ -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 savedEntities = transform( ofy().load().type(CommitLogMutation.class).list(), - new Function() { - @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. diff --git a/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java b/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java index 9b3ee9c7e..eef15bdc4 100644 --- a/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java +++ b/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java @@ -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")); } diff --git a/javatests/google/registry/tools/server/KillAllCommitLogsActionTest.java b/javatests/google/registry/tools/server/KillAllCommitLogsActionTest.java index 1d68b960c..1c86efe7c 100644 --- a/javatests/google/registry/tools/server/KillAllCommitLogsActionTest.java +++ b/javatests/google/registry/tools/server/KillAllCommitLogsActionTest.java @@ -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 clazz : AFFECTED_TYPES) { assertThat(ofy().load().type(clazz)).named("entities of type " + clazz).isNotEmpty(); } - ImmutableList otherStuff = FluentIterable.from(ofy().load()) - .filter(new Predicate() { - @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) { diff --git a/javatests/google/registry/tools/server/KillAllEppResourcesActionTest.java b/javatests/google/registry/tools/server/KillAllEppResourcesActionTest.java index 013ed4aee..e51b875d3 100644 --- a/javatests/google/registry/tools/server/KillAllEppResourcesActionTest.java +++ b/javatests/google/registry/tools/server/KillAllEppResourcesActionTest.java @@ -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 { static final ImmutableSet 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(); diff --git a/javatests/google/registry/ui/forms/FormFieldTest.java b/javatests/google/registry/ui/forms/FormFieldTest.java index 512956974..c2e859d1e 100644 --- a/javatests/google/registry/ui/forms/FormFieldTest.java +++ b/javatests/google/registry/ui/forms/FormFieldTest.java @@ -216,14 +216,7 @@ public class FormFieldTest { public void testCast() { assertThat( FormField.named("lol") - .transform( - Integer.class, - new Function() { - @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() { - @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, String>() { - @Override - public String apply(Map 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.>of( - ImmutableMap.of("cat", ""))); + .convert(ImmutableList.>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() { - @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 diff --git a/javatests/google/registry/util/ConcurrentTest.java b/javatests/google/registry/util/ConcurrentTest.java index 83e0fa4c0..f2b2159bf 100644 --- a/javatests/google/registry/util/ConcurrentTest.java +++ b/javatests/google/registry/util/ConcurrentTest.java @@ -44,21 +44,19 @@ public class ConcurrentTest { @Test public void testTransform_addIntegers() throws Exception { - assertThat(Concurrent.transform(ImmutableList.of(1, 2, 3), new Function() { - @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() { - @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.