Replace com.google.common.base.Function with java.util.function.Function

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=179249159
This commit is contained in:
guyben 2017-12-15 15:41:05 -08:00 committed by Ben McIlwain
parent d538dca2e0
commit 8157928a35
53 changed files with 424 additions and 399 deletions

View file

@ -15,6 +15,7 @@
package google.registry.backup; package google.registry.backup;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterators.peekingIterator; import static com.google.common.collect.Iterators.peekingIterator;
import static google.registry.backup.BackupUtils.createDeserializingIterator; import static google.registry.backup.BackupUtils.createDeserializingIterator;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
@ -25,8 +26,6 @@ import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityTranslator; import com.google.appengine.api.datastore.EntityTranslator;
import com.google.appengine.tools.cloudstorage.GcsFileMetadata; import com.google.appengine.tools.cloudstorage.GcsFileMetadata;
import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.PeekingIterator; import com.google.common.collect.PeekingIterator;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -50,8 +49,8 @@ import java.nio.channels.Channels;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream;
import javax.inject.Inject; import javax.inject.Inject;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -117,15 +116,18 @@ public class RestoreCommitLogsAction implements Runnable {
} }
// Restore the CommitLogCheckpointRoot and CommitLogBuckets. // Restore the CommitLogCheckpointRoot and CommitLogBuckets.
saveOfy( saveOfy(
FluentIterable.from(bucketTimestamps.entrySet()) Stream.concat(
.transform( bucketTimestamps
(Function<Entry<Integer, DateTime>, ImmutableObject>) .entrySet()
entry -> .stream()
new CommitLogBucket.Builder() .map(
.setBucketNum(entry.getKey()) entry ->
.setLastWrittenTime(entry.getValue()) new CommitLogBucket.Builder()
.build()) .setBucketNum(entry.getKey())
.append(CommitLogCheckpointRoot.create(lastCheckpoint.getCheckpointTime()))); .setLastWrittenTime(entry.getValue())
.build()),
Stream.of(CommitLogCheckpointRoot.create(lastCheckpoint.getCheckpointTime())))
.collect(toImmutableList()));
logger.info("Restore complete"); logger.info("Restore complete");
} }

View file

@ -51,7 +51,6 @@ import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.ViewDefinition; import com.google.api.services.bigquery.model.ViewDefinition;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableTable; import com.google.common.collect.ImmutableTable;
import com.google.common.io.BaseEncoding; import com.google.common.io.BaseEncoding;
@ -359,36 +358,33 @@ public class BigqueryConnection implements AutoCloseable {
} }
/** /**
* A function that updates the specified Bigquery table to reflect the metadata from the input * Updates the specified Bigquery table to reflect the metadata from the input.
* DestinationTable, passing the same DestinationTable through as the output. If the specified *
* table does not already exist, it will be inserted into the dataset. * <p>Returns the input DestinationTable. If the specified table does not already exist, it will
* be inserted into the dataset.
* *
* <p>Clients can call this function directly to update a table on demand, or can pass it to * <p>Clients can call this function directly to update a table on demand, or can pass it to
* Futures.transform() to update a table produced as the asynchronous result of a load or query * Futures.transform() to update a table produced as the asynchronous result of a load or query
* job (e.g. to add a description to it). * job (e.g. to add a description to it).
*/ */
private class UpdateTableFunction implements Function<DestinationTable, DestinationTable> { private DestinationTable updateTable(final DestinationTable destinationTable) {
@Override Table table = destinationTable.getTable();
public DestinationTable apply(final DestinationTable destinationTable) { TableReference ref = table.getTableReference();
Table table = destinationTable.getTable(); try {
TableReference ref = table.getTableReference(); if (checkTableExists(ref.getDatasetId(), ref.getTableId())) {
try { // Make sure to use patch() rather than update(). The former changes only those properties
if (checkTableExists(ref.getDatasetId(), ref.getTableId())) { // which are specified, while the latter would change everything, blanking out unspecified
// Make sure to use patch() rather than update(). The former changes only those properties // properties.
// which are specified, while the latter would change everything, blanking out unspecified bigquery
// properties. .tables()
bigquery.tables() .patch(ref.getProjectId(), ref.getDatasetId(), ref.getTableId(), table)
.patch(ref.getProjectId(), ref.getDatasetId(), ref.getTableId(), table) .execute();
.execute(); } else {
} else { bigquery.tables().insert(ref.getProjectId(), ref.getDatasetId(), table).execute();
bigquery.tables()
.insert(ref.getProjectId(), ref.getDatasetId(), table)
.execute();
}
return destinationTable;
} catch (IOException e) {
throw BigqueryJobFailureException.create(e);
} }
return destinationTable;
} catch (IOException e) {
throw BigqueryJobFailureException.create(e);
} }
} }
@ -408,7 +404,7 @@ public class BigqueryConnection implements AutoCloseable {
.setSourceFormat(sourceFormat.toString()) .setSourceFormat(sourceFormat.toString())
.setSourceUris(ImmutableList.copyOf(sourceUris)) .setSourceUris(ImmutableList.copyOf(sourceUris))
.setDestinationTable(dest.getTableReference()))); .setDestinationTable(dest.getTableReference())));
return transform(runJobToCompletion(job, dest), new UpdateTableFunction(), directExecutor()); return transform(runJobToCompletion(job, dest), this::updateTable, directExecutor());
} }
/** /**
@ -421,11 +417,9 @@ public class BigqueryConnection implements AutoCloseable {
DestinationTable dest) { DestinationTable dest) {
if (dest.type == TableType.VIEW) { if (dest.type == TableType.VIEW) {
// Use Futures.transform() rather than calling apply() directly so that any exceptions thrown // Use Futures.transform() rather than calling apply() directly so that any exceptions thrown
// by calling UpdateTableFunction will be propagated on the get() call, not from here. // by calling updateTable will be propagated on the get() call, not from here.
return transform( return transform(
Futures.immediateFuture(dest.withQuery(querySql)), Futures.immediateFuture(dest.withQuery(querySql)), this::updateTable, directExecutor());
new UpdateTableFunction(),
directExecutor());
} else { } else {
Job job = new Job() Job job = new Job()
.setConfiguration(new JobConfiguration() .setConfiguration(new JobConfiguration()
@ -434,7 +428,7 @@ public class BigqueryConnection implements AutoCloseable {
.setDefaultDataset(getDataset()) .setDefaultDataset(getDataset())
.setWriteDisposition(dest.getWriteDisposition().toString()) .setWriteDisposition(dest.getWriteDisposition().toString())
.setDestinationTable(dest.getTableReference()))); .setDestinationTable(dest.getTableReference())));
return transform(runJobToCompletion(job, dest), new UpdateTableFunction(), directExecutor()); return transform(runJobToCompletion(job, dest), this::updateTable, directExecutor());
} }
} }

View file

@ -20,7 +20,6 @@ import com.google.api.client.json.JsonFactory;
import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryScopes; import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
@ -28,6 +27,7 @@ import dagger.multibindings.Multibinds;
import google.registry.config.RegistryConfig.Config; import google.registry.config.RegistryConfig.Config;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
/** Dagger module for Google {@link Bigquery} connection objects. */ /** Dagger module for Google {@link Bigquery} connection objects. */
@Module @Module

View file

@ -18,12 +18,12 @@ import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIden
import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonFactory;
import com.google.api.services.dataflow.Dataflow; import com.google.api.services.dataflow.Dataflow;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
import google.registry.config.RegistryConfig.Config; import google.registry.config.RegistryConfig.Config;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
/** Module for dependencies required by monthly billing actions. */ /** Module for dependencies required by monthly billing actions. */
@Module @Module

View file

@ -19,7 +19,6 @@ import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonFactory;
import com.google.api.services.dns.Dns; import com.google.api.services.dns.Dns;
import com.google.api.services.dns.DnsScopes; import com.google.api.services.dns.DnsScopes;
import com.google.common.base.Function;
import com.google.common.util.concurrent.RateLimiter; import com.google.common.util.concurrent.RateLimiter;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
@ -30,6 +29,7 @@ import google.registry.config.RegistryConfig.Config;
import google.registry.dns.writer.DnsWriter; import google.registry.dns.writer.DnsWriter;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import javax.inject.Named; import javax.inject.Named;
/** Dagger module for Google Cloud DNS service connection objects. */ /** Dagger module for Google Cloud DNS service connection objects. */

View file

@ -19,11 +19,11 @@ import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonFactory;
import com.google.api.services.drive.Drive; import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.DriveScopes;
import com.google.common.base.Function;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
import google.registry.config.RegistryConfig.Config; import google.registry.config.RegistryConfig.Config;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
/** Dagger module for Google {@link Drive} service connection objects. */ /** Dagger module for Google {@link Drive} service connection objects. */
@Module @Module

View file

@ -24,7 +24,6 @@ import static google.registry.model.domain.DomainResource.extendRegistrationWith
import static google.registry.model.index.ForeignKeyIndex.loadAndGetKey; import static google.registry.model.index.ForeignKeyIndex.loadAndGetKey;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -67,6 +66,7 @@ import google.registry.model.transfer.TransferStatus;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import org.joda.time.DateTime; import org.joda.time.DateTime;
/** Static utility functions for resource flows. */ /** Static utility functions for resource flows. */

View file

@ -19,12 +19,12 @@ import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonFactory;
import com.google.api.services.cloudkms.v1.CloudKMS; import com.google.api.services.cloudkms.v1.CloudKMS;
import com.google.api.services.cloudkms.v1.CloudKMSScopes; import com.google.api.services.cloudkms.v1.CloudKMSScopes;
import com.google.common.base.Function;
import dagger.Binds; import dagger.Binds;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
import google.registry.config.RegistryConfig.Config; import google.registry.config.RegistryConfig.Config;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
/** Dagger module for Cloud KMS connection objects. */ /** Dagger module for Cloud KMS connection objects. */
@Module @Module

View file

@ -19,7 +19,6 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Lists.partition; 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; import static google.registry.security.XsrfTokenManager.X_CSRF_TOKEN;
import static google.registry.util.FormattingLogger.getLoggerForCallerClass; import static google.registry.util.FormattingLogger.getLoggerForCallerClass;
import static google.registry.util.ResourceUtils.readResourceUtf8; import static google.registry.util.ResourceUtils.readResourceUtf8;
@ -27,7 +26,6 @@ import static java.util.Arrays.asList;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators; import com.google.common.collect.Iterators;
import google.registry.config.RegistryEnvironment; import google.registry.config.RegistryEnvironment;
@ -41,6 +39,7 @@ import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.function.Function;
import javax.inject.Inject; import javax.inject.Inject;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -235,15 +234,17 @@ public class LoadTestAction implements Runnable {
// Do successful creates on random names // Do successful creates on random names
tasks.addAll( tasks.addAll(
createTasks( createTasks(
transform( createNumCopies(xmlContactCreateTmpl, successfulContactCreatesPerSecond)
createNumCopies(xmlContactCreateTmpl, successfulContactCreatesPerSecond), .stream()
randomNameReplacer("%contact%", MAX_CONTACT_LENGTH)), .map(randomNameReplacer("%contact%", MAX_CONTACT_LENGTH))
.collect(toImmutableList()),
startSecond)); startSecond));
tasks.addAll( tasks.addAll(
createTasks( createTasks(
transform( createNumCopies(xmlHostCreateTmpl, successfulHostCreatesPerSecond)
createNumCopies(xmlHostCreateTmpl, successfulHostCreatesPerSecond), .stream()
randomNameReplacer("%host%", ARBITRARY_VALID_HOST_LENGTH)), .map(randomNameReplacer("%host%", ARBITRARY_VALID_HOST_LENGTH))
.collect(toImmutableList()),
startSecond)); startSecond));
tasks.addAll( tasks.addAll(
createTasks( createTasks(

View file

@ -21,7 +21,6 @@ import static google.registry.util.DateTimeUtils.isAtOrAfter;
import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static google.registry.util.DateTimeUtils.isBeforeOrAt;
import static google.registry.util.DateTimeUtils.latestOf; import static google.registry.util.DateTimeUtils.latestOf;
import com.google.common.base.Function;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
import com.googlecode.objectify.Result; import com.googlecode.objectify.Result;
import com.googlecode.objectify.cmd.Query; import com.googlecode.objectify.cmd.Query;
@ -44,6 +43,7 @@ import google.registry.util.FormattingLogger;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Interval; import org.joda.time.Interval;

View file

@ -14,15 +14,14 @@
package google.registry.model; 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.Iterables.transform;
import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.Maps.transformValues;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -34,6 +33,7 @@ import java.lang.reflect.Field;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.NavigableMap; import java.util.NavigableMap;
@ -125,8 +125,7 @@ public abstract class ImmutableObject implements Cloneable {
Field field = entry.getKey(); Field field = entry.getKey();
Object value = entry.getValue(); Object value = entry.getValue();
sortedFields.put( sortedFields.put(
field.getName(), field.getName(), field.isAnnotationPresent(DoNotHydrate.class) ? value : hydrate(value));
field.isAnnotationPresent(DoNotHydrate.class) ? value : HYDRATOR.apply(value));
} }
return toStringHelper(sortedFields); return toStringHelper(sortedFields);
} }
@ -141,54 +140,60 @@ public abstract class ImmutableObject implements Cloneable {
} }
/** Helper function to recursively hydrate an ImmutableObject. */ /** Helper function to recursively hydrate an ImmutableObject. */
private static final Function<Object, Object> HYDRATOR = private static final Object hydrate(Object value) {
new Function<Object, Object>() { if (value instanceof Key) {
@Override return hydrate(ofy().load().key((Key<?>) value).now());
public Object apply(Object value) { } else if (value instanceof Map) {
if (value instanceof Key) { return transformValues((Map<?, ?>) value, ImmutableObject::hydrate);
return apply(ofy().load().key((Key<?>) value).now()); } else if (value instanceof Collection) {
} else if (value instanceof Map) { return transform((Collection<?>) value, ImmutableObject::hydrate);
return transformValues((Map<?, ?>) value, this); } else if (value instanceof ImmutableObject) {
} else if (value instanceof Collection) { return ((ImmutableObject) value).toHydratedString();
return transform((Collection<?>) value, this); }
} else if (value instanceof ImmutableObject) { return value;
return ((ImmutableObject) value).toHydratedString(); }
}
return value;
}};
/** Helper function to recursively convert a ImmutableObject to a Map of generic objects. */ /** Helper function to recursively convert a ImmutableObject to a Map of generic objects. */
private static final Function<Object, Object> TO_MAP_HELPER = private static Object toMapRecursive(Object o) {
new Function<Object, Object>() { if (o == null) {
@Override return null;
public Object apply(Object o) { } else if (o instanceof ImmutableObject) {
if (o == null) { // LinkedHashMap to preserve field ordering and because ImmutableMap forbids null
return null; // values.
} else if (o instanceof ImmutableObject) { Map<String, Object> result = new LinkedHashMap<>();
// LinkedHashMap to preserve field ordering and because ImmutableMap forbids null for (Entry<Field, Object> entry : ModelUtils.getFieldValues(o).entrySet()) {
// values. result.put(entry.getKey().getName(), toMapRecursive(entry.getValue()));
Map<String, Object> result = new LinkedHashMap<>(); }
for (Entry<Field, Object> entry : ModelUtils.getFieldValues(o).entrySet()) { return result;
result.put(entry.getKey().getName(), apply(entry.getValue())); } else if (o instanceof Map) {
} return Maps.transformValues((Map<?, ?>) o, ImmutableObject::toMapRecursive);
return result; } else if (o instanceof Set) {
} else if (o instanceof Map) { return ((Set<?>) o)
return Maps.transformValues((Map<?, ?>) o, this); .stream()
} else if (o instanceof Set) { .map(ImmutableObject::toMapRecursive)
return ((Set<?>) o).stream().map(this).collect(toImmutableSet()); // We can't use toImmutableSet here, because values can be null (especially since the
} else if (o instanceof Collection) { // original ImmutableObject might have been the result of a cloneEmptyToNull call).
return ((Collection<?>) o).stream().map(this).collect(toImmutableList()); //
} else if (o instanceof Number || o instanceof Boolean) { // We can't use toSet either, because we want to preserve order. So we use LinkedHashSet
return o; // instead.
} else { .collect(toCollection(LinkedHashSet::new));
return o.toString(); } else if (o instanceof Collection) {
} return ((Collection<?>) o)
} .stream()
}; .map(ImmutableObject::toMapRecursive)
// We can't use toImmutableList here, because values can be null (especially since the
// original ImmutableObject might have been the result of a cloneEmptyToNull call).
.collect(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. */ /** Returns a map of all object fields (including sensitive data) that's used to produce diffs. */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Map<String, Object> toDiffableFieldMap() { public Map<String, Object> toDiffableFieldMap() {
return (Map<String, Object>) TO_MAP_HELPER.apply(this); return (Map<String, Object>) toMapRecursive(this);
} }
} }

View file

@ -16,7 +16,6 @@ package google.registry.model;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.base.Functions;
import com.google.common.collect.Streams; import com.google.common.collect.Streams;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -67,7 +66,7 @@ public final class JsonMapBuilder {
name, name,
value == null value == null
? Collections.EMPTY_LIST ? Collections.EMPTY_LIST
: Streams.stream(value).map(Functions.toStringFunction()).collect(toImmutableList())); : Streams.stream(value).map(Object::toString).collect(toImmutableList()));
return this; return this;
} }

View file

@ -17,12 +17,11 @@ package google.registry.model;
import static com.google.common.base.Predicates.instanceOf; import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.base.Predicates.isNull; import static com.google.common.base.Predicates.isNull;
import static com.google.common.base.Predicates.or; import static com.google.common.base.Predicates.or;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.Maps.transformValues;
import static com.google.common.collect.Sets.newLinkedHashSet; import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
@ -44,42 +43,48 @@ import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.AbstractList; import java.util.AbstractList;
import java.util.ArrayDeque;
import java.util.Collection; import java.util.Collection;
import java.util.Deque; import java.util.Deque;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedList; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream;
/** A collection of static methods that deal with reflection on model classes. */ /** A collection of static methods that deal with reflection on model classes. */
public class ModelUtils { public class ModelUtils {
/** Caches all instance fields on an object, including non-public and inherited fields. */ /** Caches all instance fields on an object, including non-public and inherited fields. */
private static final LoadingCache<Class<?>, ImmutableMap<String, Field>> ALL_FIELDS_CACHE = private static final LoadingCache<Class<?>, ImmutableMap<String, Field>> ALL_FIELDS_CACHE =
CacheBuilder.newBuilder().build(new CacheLoader<Class<?>, ImmutableMap<String, Field>>() { CacheBuilder.newBuilder()
@Override .build(
public ImmutableMap<String, Field> load(Class<?> clazz) { new CacheLoader<Class<?>, ImmutableMap<String, Field>>() {
Deque<Class<?>> hierarchy = new LinkedList<>(); @Override
// Walk the hierarchy up to but not including ImmutableObject (to ignore hashCode). public ImmutableMap<String, Field> load(Class<?> clazz) {
for (; clazz != ImmutableObject.class; clazz = clazz.getSuperclass()) { Deque<Class<?>> hierarchy = new ArrayDeque<>();
// Add to the front, so that shadowed fields show up later in the list. // Walk the hierarchy up to but not including ImmutableObject (to ignore
// This will mean that getFieldValues will show the most derived value. // hashCode).
hierarchy.addFirst(clazz); for (; clazz != ImmutableObject.class; clazz = clazz.getSuperclass()) {
} // Add to the front, so that shadowed fields show up later in the list.
Map<String, Field> fields = new LinkedHashMap<>(); // This will mean that getFieldValues will show the most derived value.
for (Class<?> hierarchyClass : hierarchy) { hierarchy.addFirst(clazz);
// Don't use hierarchyClass.getFields() because it only picks up public fields. }
for (Field field : hierarchyClass.getDeclaredFields()) { Map<String, Field> fields = new LinkedHashMap<>();
if (!Modifier.isStatic(field.getModifiers())) { for (Class<?> hierarchyClass : hierarchy) {
field.setAccessible(true); // Don't use hierarchyClass.getFields() because it only picks up public fields.
fields.put(field.getName(), field); for (Field field : hierarchyClass.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
field.setAccessible(true);
fields.put(field.getName(), field);
}
}
}
return ImmutableMap.copyOf(fields);
} }
} });
}
return ImmutableMap.copyOf(fields);
}});
/** Lists all instance fields on an object, including non-public and inherited fields. */ /** Lists all instance fields on an object, including non-public and inherited fields. */
static Map<String, Field> getAllFields(Class<?> clazz) { static Map<String, Field> getAllFields(Class<?> clazz) {
@ -208,53 +213,55 @@ public class ModelUtils {
} }
/** Functional helper for {@link #cloneEmptyToNull}. */ /** Functional helper for {@link #cloneEmptyToNull}. */
private static final Function<Object, ?> CLONE_EMPTY_TO_NULL = private static Object cloneEmptyToNullRecursive(Object obj) {
new Function<Object, Object>() { if (obj instanceof ImmutableSortedMap) {
@Override // ImmutableSortedMapTranslatorFactory handles empty for us. If the object is null, then
public Object apply(Object obj) { // its on-save hook can't run.
if (obj instanceof ImmutableSortedMap) { return obj;
// ImmutableSortedMapTranslatorFactory handles empty for us. If the object is null, then }
// its on-save hook can't run. if (obj == null
return obj; || obj.equals("")
} || (obj instanceof Collection && ((Collection<?>) obj).isEmpty())
if ("".equals(obj) || (obj instanceof Map && ((Map<?, ?>) obj).isEmpty())
|| (obj instanceof Collection && ((Collection<?>) obj).isEmpty()) || (obj.getClass().isArray() && Array.getLength(obj) == 0)) {
|| (obj instanceof Map && ((Map<?, ?>) obj).isEmpty()) return null;
|| (obj != null && obj.getClass().isArray() && Array.getLength(obj) == 0)) { }
return null; Predicate<Object> immutableObjectOrNull = or(isNull(), instanceOf(ImmutableObject.class));
} if ((obj instanceof Set || obj instanceof List)
Predicate<Object> immutableObjectOrNull = or(isNull(), instanceOf(ImmutableObject.class)); && Streams.stream((Iterable<?>) obj).allMatch(immutableObjectOrNull)) {
if ((obj instanceof Set || obj instanceof List) // Recurse into sets and lists, but only if they contain ImmutableObjects.
&& Streams.stream((Iterable<?>) obj).allMatch(immutableObjectOrNull)) { Stream<?> stream =
// Recurse into sets and lists, but only if they contain ImmutableObjects. Streams.stream((Iterable<?>) obj).map(ModelUtils::cloneEmptyToNullRecursive);
FluentIterable<?> fluent = FluentIterable.from((Iterable<?>) obj).transform(this); // We can't use toImmutable(List/Set) because the values can be null.
return (obj instanceof List) ? newArrayList(fluent) : newLinkedHashSet(fluent); // We can't use toSet because we have to preserve order in the Set.
} // So we use toList (accepts null) and LinkedHashSet (preserves order and accepts null)
if (obj instanceof Map return (obj instanceof List)
&& ((Map<?, ?>) obj).values().stream().allMatch(immutableObjectOrNull)) { ? stream.collect(toList())
// Recurse into maps with ImmutableObject values. : stream.collect(toCollection(LinkedHashSet::new));
return transformValues((Map<?, ?>) obj, this); }
} if (obj instanceof Map && ((Map<?, ?>) obj).values().stream().allMatch(immutableObjectOrNull)) {
if (obj instanceof ImmutableObject) { // Recurse into maps with ImmutableObject values.
// Recurse on the fields of an ImmutableObject. return transformValues((Map<?, ?>) obj, ModelUtils::cloneEmptyToNullRecursive);
ImmutableObject copy = ImmutableObject.clone((ImmutableObject) obj); }
for (Field field : getAllFields(obj.getClass()).values()) { if (obj instanceof ImmutableObject) {
Object oldValue = getFieldValue(obj, field); // Recurse on the fields of an ImmutableObject.
Object newValue = apply(oldValue); ImmutableObject copy = ImmutableObject.clone((ImmutableObject) obj);
if (!Objects.equals(oldValue, newValue)) { for (Field field : getAllFields(obj.getClass()).values()) {
setFieldValue(copy, field, newValue); Object oldValue = getFieldValue(obj, field);
} Object newValue = cloneEmptyToNullRecursive(oldValue);
} if (!Objects.equals(oldValue, newValue)) {
return copy; setFieldValue(copy, field, newValue);
}
return obj;
} }
}; }
return copy;
}
return obj;
}
/** Returns a clone of the object and sets empty collections, arrays, maps and strings to null. */ /** Returns a clone of the object and sets empty collections, arrays, maps and strings to null. */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected static <T extends ImmutableObject> T cloneEmptyToNull(T obj) { protected static <T extends ImmutableObject> T cloneEmptyToNull(T obj) {
return (T) CLONE_EMPTY_TO_NULL.apply(obj); return (T) cloneEmptyToNullRecursive(obj);
} }
@VisibleForTesting @VisibleForTesting

View file

@ -15,10 +15,9 @@
package google.registry.model.ofy; package google.registry.model.ofy;
import static com.googlecode.objectify.ObjectifyService.ofy; import static com.googlecode.objectify.ObjectifyService.ofy;
import static google.registry.util.ObjectifyUtils.OBJECTS_TO_KEYS;
import com.google.common.base.Functions;
import com.google.common.collect.FluentIterable; import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
import com.googlecode.objectify.Result; import com.googlecode.objectify.Result;
@ -38,13 +37,13 @@ abstract class AugmentedDeleter implements Deleter {
@Override @Override
public Result<Void> entities(Iterable<?> entities) { public Result<Void> entities(Iterable<?> entities) {
handleDeletion(Iterables.transform(entities, OBJECTS_TO_KEYS)); handleDeletion(Iterables.transform(entities, Key::create));
return delegate.entities(entities); return delegate.entities(entities);
} }
@Override @Override
public Result<Void> entities(Object... entities) { public Result<Void> entities(Object... entities) {
handleDeletion(FluentIterable.from(entities).transform(OBJECTS_TO_KEYS)); handleDeletion(FluentIterable.from(entities).transform(Key::create));
return delegate.entities(entities); return delegate.entities(entities);
} }
@ -65,11 +64,8 @@ abstract class AugmentedDeleter implements Deleter {
// Magic to convert the type Iterable<? extends Key<?>> (a family of types which allows for // Magic to convert the type Iterable<? extends Key<?>> (a family of types which allows for
// homogeneous iterables of a fixed Key<T> type, e.g. List<Key<Lock>>, and is convenient for // homogeneous iterables of a fixed Key<T> type, e.g. List<Key<Lock>>, and is convenient for
// callers) into the type Iterable<Key<?>> (a concrete type of heterogeneous keys, which is // callers) into the type Iterable<Key<?>> (a concrete type of heterogeneous keys, which is
// convenient for users). We do this by passing each key through the identity function // convenient for users).
// parameterized for Key<?>, which erases any homogeneous typing on the iterable. handleDeletion(ImmutableList.<Key<?>>copyOf(keys));
// See: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ104
Iterable<Key<?>> retypedKeys = Iterables.transform(keys, Functions.<Key<?>>identity());
handleDeletion(retypedKeys);
return delegate.keys(keys); return delegate.keys(keys);
} }

View file

@ -25,7 +25,6 @@ import static google.registry.model.ofy.CommitLogBucket.loadBucket;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static google.registry.util.DateTimeUtils.isBeforeOrAt;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -153,9 +152,7 @@ class CommitLoggedWork<R> extends VoidWork {
mutations = mutations =
union(info.getSaves(), untouchedRootsWithTouchedChildren) union(info.getSaves(), untouchedRootsWithTouchedChildren)
.stream() .stream()
.map( .map(entity -> (ImmutableObject) CommitLogMutation.create(manifestKey, entity))
(Function<Object, ImmutableObject>)
(Object saveEntity) -> CommitLogMutation.create(manifestKey, saveEntity))
.collect(toImmutableSet()); .collect(toImmutableSet());
ofy().saveWithoutBackup() ofy().saveWithoutBackup()
.entities(new ImmutableSet.Builder<>() .entities(new ImmutableSet.Builder<>()

View file

@ -21,7 +21,6 @@ import static com.google.common.collect.Maps.uniqueIndex;
import static com.googlecode.objectify.ObjectifyService.ofy; import static com.googlecode.objectify.ObjectifyService.ofy;
import static google.registry.config.RegistryConfig.getBaseOfyRetryDuration; import static google.registry.config.RegistryConfig.getBaseOfyRetryDuration;
import static google.registry.util.CollectionUtils.union; import static google.registry.util.CollectionUtils.union;
import static google.registry.util.ObjectifyUtils.OBJECTS_TO_KEYS;
import com.google.appengine.api.datastore.DatastoreFailureException; import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreTimeoutException; import com.google.appengine.api.datastore.DatastoreTimeoutException;
@ -170,7 +169,7 @@ public class Ofy {
assertInTransaction(); assertInTransaction();
checkState(Streams.stream(entities).allMatch(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); checkProhibitedAnnotations(entities, NotBackedUp.class, VirtualEntity.class);
ImmutableMap<Key<?>, ?> keysToEntities = uniqueIndex(entities, OBJECTS_TO_KEYS); ImmutableMap<Key<?>, ?> keysToEntities = uniqueIndex(entities, Key::create);
TRANSACTION_INFO.get().putSaves(keysToEntities); TRANSACTION_INFO.get().putSaves(keysToEntities);
} }
}; };

View file

@ -14,7 +14,6 @@
package google.registry.model.ofy; 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.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.filterValues; import static com.google.common.collect.Maps.filterValues;
@ -76,7 +75,7 @@ class TransactionInfo {
void putDeletes(Iterable<Key<?>> keys) { void putDeletes(Iterable<Key<?>> keys) {
assertNotReadOnly(); assertNotReadOnly();
changesBuilder.putAll(toMap(keys, constant(TransactionInfo.Delete.SENTINEL))); changesBuilder.putAll(toMap(keys, k -> TransactionInfo.Delete.SENTINEL));
} }
ImmutableSet<Key<?>> getTouchedKeys() { ImmutableSet<Key<?>> getTouchedKeys() {

View file

@ -14,13 +14,11 @@
package google.registry.model.registrar; 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.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.difference;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy; import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy;
import static google.registry.util.ObjectifyUtils.OBJECTS_TO_KEYS;
import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.joining;
import com.google.common.base.Enums; import com.google.common.base.Enums;
@ -171,7 +169,7 @@ public class RegistrarContact extends ImmutableObject implements Jsonifiable {
.type(RegistrarContact.class) .type(RegistrarContact.class)
.ancestor(registrar) .ancestor(registrar)
.keys()), .keys()),
contacts.stream().map(OBJECTS_TO_KEYS).collect(toImmutableSet()))); contacts.stream().map(Key::create).collect(toImmutableSet())));
ofy().save().entities(contacts); ofy().save().entities(contacts);
} }
}); });
@ -272,7 +270,7 @@ public class RegistrarContact extends ImmutableObject implements Jsonifiable {
.put("emailAddress", emailAddress) .put("emailAddress", emailAddress)
.put("phoneNumber", phoneNumber) .put("phoneNumber", phoneNumber)
.put("faxNumber", faxNumber) .put("faxNumber", faxNumber)
.put("types", getTypes().stream().map(toStringFunction()).collect(joining(","))) .put("types", getTypes().stream().map(Object::toString).collect(joining(",")))
.put("visibleInWhoisAsAdmin", visibleInWhoisAsAdmin) .put("visibleInWhoisAsAdmin", visibleInWhoisAsAdmin)
.put("visibleInWhoisAsTech", visibleInWhoisAsTech) .put("visibleInWhoisAsTech", visibleInWhoisAsTech)
.put("visibleInDomainWhoisAsAbuse", visibleInDomainWhoisAsAbuse) .put("visibleInDomainWhoisAsAbuse", visibleInDomainWhoisAsAbuse)

View file

@ -15,11 +15,10 @@
package google.registry.monitoring.metrics.contrib; package google.registry.monitoring.metrics.contrib;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject; import com.google.common.truth.Subject;
@ -63,15 +62,13 @@ abstract class AbstractMetricSubject<T, S extends AbstractMetricSubject<T, S>>
*/ */
protected final Set<ImmutableList<String>> expectedNondefaultLabelTuples = new HashSet<>(); protected final Set<ImmutableList<String>> expectedNondefaultLabelTuples = new HashSet<>();
/** /** Converts a metric point to a nice string representation for use in error messages. */
* Function to convert a metric point to a nice string representation for use in error messages. protected String convertMetricPoint(MetricPoint<T> metricPoint) {
*/ return String.format(
protected final Function<MetricPoint<T>, String> metricPointConverter = "%s => %s",
metricPoint -> Joiner.on(':').join(metricPoint.labelValues()),
String.format( getMessageRepresentation(metricPoint.value()));
"%s => %s", }
Joiner.on(':').join(metricPoint.labelValues()),
getMessageRepresentation(metricPoint.value()));
protected AbstractMetricSubject(FailureMetadata metadata, Metric<T> actual) { protected AbstractMetricSubject(FailureMetadata metadata, Metric<T> actual) {
super(metadata, checkNotNull(actual)); super(metadata, checkNotNull(actual));
@ -101,9 +98,11 @@ abstract class AbstractMetricSubject<T, S extends AbstractMetricSubject<T, S>>
"has a value for labels", "has a value for labels",
Joiner.on(':').join(labels), Joiner.on(':').join(labels),
"has labeled values", "has labeled values",
Lists.transform( Ordering.<MetricPoint<T>>natural()
Ordering.<MetricPoint<T>>natural().sortedCopy(actual().getTimestampedValues()), .sortedCopy(actual().getTimestampedValues())
metricPointConverter)); .stream()
.map(this::convertMetricPoint)
.collect(toImmutableList()));
} }
if (!metricPoint.value().equals(value)) { if (!metricPoint.value().equals(value)) {
failWithBadResults( failWithBadResults(
@ -129,9 +128,11 @@ abstract class AbstractMetricSubject<T, S extends AbstractMetricSubject<T, S>>
"has a value for labels", "has a value for labels",
Joiner.on(':').join(labels), Joiner.on(':').join(labels),
"has labeled values", "has labeled values",
Lists.transform( Ordering.<MetricPoint<T>>natural()
Ordering.<MetricPoint<T>>natural().sortedCopy(actual().getTimestampedValues()), .sortedCopy(actual().getTimestampedValues())
metricPointConverter)); .stream()
.map(this::convertMetricPoint)
.collect(toImmutableList()));
} }
if (hasDefaultValue(metricPoint)) { if (hasDefaultValue(metricPoint)) {
failWithBadResults( failWithBadResults(
@ -169,9 +170,11 @@ abstract class AbstractMetricSubject<T, S extends AbstractMetricSubject<T, S>>
"has", "has",
"no other nondefault values", "no other nondefault values",
"has labeled values", "has labeled values",
Lists.transform( Ordering.<MetricPoint<T>>natural()
Ordering.<MetricPoint<T>>natural().sortedCopy(actual().getTimestampedValues()), .sortedCopy(actual().getTimestampedValues())
metricPointConverter)); .stream()
.map(this::convertMetricPoint)
.collect(toImmutableList()));
} }
return andChainer(); return andChainer();
} }

View file

@ -21,7 +21,6 @@ import com.google.api.services.monitoring.v3.Monitoring;
import com.google.api.services.monitoring.v3.MonitoringScopes; import com.google.api.services.monitoring.v3.MonitoringScopes;
import com.google.api.services.monitoring.v3.model.MonitoredResource; import com.google.api.services.monitoring.v3.model.MonitoredResource;
import com.google.appengine.api.modules.ModulesService; import com.google.appengine.api.modules.ModulesService;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import dagger.Module; import dagger.Module;
@ -31,6 +30,7 @@ import google.registry.monitoring.metrics.MetricReporter;
import google.registry.monitoring.metrics.MetricWriter; import google.registry.monitoring.metrics.MetricWriter;
import google.registry.monitoring.metrics.stackdriver.StackdriverWriter; import google.registry.monitoring.metrics.stackdriver.StackdriverWriter;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import org.joda.time.Duration; import org.joda.time.Duration;
/** Dagger module for Google Stackdriver service connection objects. */ /** Dagger module for Google Stackdriver service connection objects. */

View file

@ -21,15 +21,12 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.CollectionUtils.union; import static google.registry.util.CollectionUtils.union;
import static google.registry.util.DomainNameUtils.ACE_PREFIX; import static google.registry.util.DomainNameUtils.ACE_PREFIX;
import com.google.common.base.Functions;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable; import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import com.google.common.collect.Streams;
import com.google.common.net.InetAddresses; import com.google.common.net.InetAddresses;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
import google.registry.config.RdapNoticeDescriptor; import google.registry.config.RdapNoticeDescriptor;
@ -59,7 +56,9 @@ import java.net.URI;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -1091,16 +1090,17 @@ public class RdapJsonFormatter {
*/ */
private static ImmutableList<String> makeStatusValueList( private static ImmutableList<String> makeStatusValueList(
ImmutableSet<StatusValue> statusValues, boolean isDeleted) { ImmutableSet<StatusValue> statusValues, boolean isDeleted) {
FluentIterable<RdapStatus> iterable = Stream<RdapStatus> stream =
FluentIterable.from(statusValues) statusValues
.transform(Functions.forMap(statusToRdapStatusMap, RdapStatus.OBSCURED)); .stream()
.map(status -> statusToRdapStatusMap.getOrDefault(status, RdapStatus.OBSCURED));
if (isDeleted) { if (isDeleted) {
iterable = stream =
iterable Stream.concat(
.filter(Predicates.not(Predicates.equalTo(RdapStatus.ACTIVE))) stream.filter(rdapStatus -> !Objects.equals(rdapStatus, RdapStatus.ACTIVE)),
.append(RdapStatus.REMOVED); Stream.of(RdapStatus.REMOVED));
} }
return Streams.stream(iterable) return stream
.map(RdapStatus::getDisplayName) .map(RdapStatus::getDisplayName)
.collect(toImmutableSortedSet(Ordering.natural())) .collect(toImmutableSortedSet(Ordering.natural()))
.asList(); .asList();

View file

@ -22,7 +22,6 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.google.common.base.Ascii; import com.google.common.base.Ascii;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.net.InternetDomainName; import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -59,6 +58,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.ProviderException; import java.security.ProviderException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Random; import java.util.Random;
import java.util.function.Function;
import org.joda.time.DateTime; import org.joda.time.DateTime;
/** Utility class that converts an {@link XjcRdeDomainElement} into a {@link DomainResource}. */ /** Utility class that converts an {@link XjcRdeDomainElement} into a {@link DomainResource}. */

View file

@ -16,6 +16,7 @@ package google.registry.reporting;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.reporting.IcannReportingModule.MANIFEST_FILE_NAME; import static google.registry.reporting.IcannReportingModule.MANIFEST_FILE_NAME;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
@ -119,7 +120,7 @@ public class IcannReportingStager {
return fields return fields
.stream() .stream()
.map((schema) -> schema.getName().replace('_', '-')) .map((schema) -> schema.getName().replace('_', '-'))
.collect(ImmutableList.toImmutableList()); .collect(toImmutableList());
} }
/** Creates and stores activity reports on GCS, returns a list of files stored. */ /** Creates and stores activity reports on GCS, returns a list of files stored. */
@ -183,7 +184,7 @@ public class IcannReportingStager {
// Ignore TLD, Registrar name and IANA id // Ignore TLD, Registrar name and IANA id
.skip(3) .skip(3)
.map((Object o) -> Integer.parseInt(o.toString())) .map((Object o) -> Integer.parseInt(o.toString()))
.collect(Collectors.toList()); .collect(toImmutableList());
checkState( checkState(
rowVals.size() == totals.size(), rowVals.size() == totals.size(),
"Number of elements in totals not equal to number of elements in row!"); "Number of elements in totals not equal to number of elements in row!");

View file

@ -33,7 +33,6 @@ import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory; import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory; import com.google.appengine.api.users.UserServiceFactory;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import dagger.Binds; import dagger.Binds;
import dagger.Module; import dagger.Module;
@ -43,6 +42,7 @@ import google.registry.keyring.api.KeyModule.Key;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Provider; import javax.inject.Provider;
import javax.inject.Singleton; import javax.inject.Singleton;

View file

@ -15,7 +15,7 @@
package google.registry.request; package google.registry.request;
import com.google.auto.value.AutoValue; import com.google.auto.value.AutoValue;
import com.google.common.base.Function; import java.util.function.Function;
/** /**
* Mapping of an {@link Action} to a {@link Runnable} instantiator for request handling. * Mapping of an {@link Action} to a {@link Runnable} instantiator for request handling.

View file

@ -17,7 +17,6 @@ package google.registry.request;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Throwables.throwIfUnchecked; import static com.google.common.base.Throwables.throwIfUnchecked;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -25,6 +24,7 @@ import java.lang.reflect.Method;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.function.Function;
/** /**
* Path prefix request router. * Path prefix request router.

View file

@ -24,7 +24,6 @@ import static org.joda.time.DateTimeZone.UTC;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import com.google.common.base.Function;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -43,6 +42,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.joda.money.BigMoney; import org.joda.money.BigMoney;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;

View file

@ -15,9 +15,9 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.model.EppResourceUtils.loadByForeignKey; import static google.registry.model.EppResourceUtils.loadByForeignKey;
import static google.registry.util.FormattingLogger.getLoggerForCallerClass; import static google.registry.util.FormattingLogger.getLoggerForCallerClass;
import static java.util.stream.Collectors.toList;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
@ -64,7 +64,8 @@ public class LockDomainCommand extends LockOrUnlockDomainCommand {
"addNameservers", ImmutableList.of(), "addNameservers", ImmutableList.of(),
"addAdmins", ImmutableList.of(), "addAdmins", ImmutableList.of(),
"addTechs", ImmutableList.of(), "addTechs", ImmutableList.of(),
"addStatuses", statusesToAdd.stream().map(StatusValue::getXmlName).collect(toList()), "addStatuses",
statusesToAdd.stream().map(StatusValue::getXmlName).collect(toImmutableList()),
"remove", false, "remove", false,
"removeNameservers", ImmutableList.of(), "removeNameservers", ImmutableList.of(),
"removeAdmins", ImmutableList.of(), "removeAdmins", ImmutableList.of(),

View file

@ -16,7 +16,6 @@ package google.registry.tools;
import static com.google.common.base.CaseFormat.UPPER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.base.Functions.toStringFunction;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
@ -227,6 +226,6 @@ public abstract class MutatingCommand extends ConfirmingCommand implements Remot
protected String prompt() { protected String prompt() {
return changedEntitiesMap.isEmpty() return changedEntitiesMap.isEmpty()
? "No entity changes to apply." ? "No entity changes to apply."
: changedEntitiesMap.values().stream().map(toStringFunction()).collect(joining("\n")); : changedEntitiesMap.values().stream().map(Object::toString).collect(joining("\n"));
} }
} }

View file

@ -17,7 +17,6 @@ package google.registry.tools;
import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.joining;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import com.google.common.base.Functions;
import com.google.common.collect.ComparisonChain; import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import google.registry.rde.PendingDeposit; import google.registry.rde.PendingDeposit;
@ -49,7 +48,7 @@ final class PendingEscrowCommand implements RemoteApiCommand {
SORTER SORTER
.sortedCopy(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda().values()) .sortedCopy(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda().values())
.stream() .stream()
.map(Functions.toStringFunction()) .map(Object::toString)
.collect(joining("\n"))); .collect(joining("\n")));
} }
} }

View file

@ -15,9 +15,9 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.model.EppResourceUtils.loadByForeignKey; import static google.registry.model.EppResourceUtils.loadByForeignKey;
import static google.registry.util.FormattingLogger.getLoggerForCallerClass; import static google.registry.util.FormattingLogger.getLoggerForCallerClass;
import static java.util.stream.Collectors.toList;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
@ -71,7 +71,7 @@ public class UnlockDomainCommand extends LockOrUnlockDomainCommand {
"removeAdmins", ImmutableList.of(), "removeAdmins", ImmutableList.of(),
"removeTechs", ImmutableList.of(), "removeTechs", ImmutableList.of(),
"removeStatuses", "removeStatuses",
statusesToRemove.stream().map(StatusValue::getXmlName).collect(toList()), statusesToRemove.stream().map(StatusValue::getXmlName).collect(toImmutableList()),
"change", false)); "change", false));
} }
} }

View file

@ -18,8 +18,6 @@ import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Strings; import com.google.common.base.Strings;
@ -42,6 +40,7 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream; import java.util.stream.Stream;
import javax.inject.Inject; import javax.inject.Inject;
@ -187,7 +186,7 @@ public abstract class ListObjectsAction<T extends ImmutableObject> implements Ru
// Next, add to the mapping all the aliases, with their values defined as whatever was in the // Next, add to the mapping all the aliases, with their values defined as whatever was in the
// map under the aliased field's original name. // map under the aliased field's original name.
fieldMap.putAll( fieldMap.putAll(
Maps.transformValues(getFieldAliases(), Functions.forMap(new HashMap<>(fieldMap)))); new HashMap<>(Maps.transformValues(getFieldAliases(), value -> fieldMap.get(value))));
Set<String> expectedFields = ImmutableSortedSet.copyOf(fieldMap.keySet()); Set<String> expectedFields = ImmutableSortedSet.copyOf(fieldMap.keySet());
for (String field : fields) { for (String field : fields) {
checkArgument(fieldMap.containsKey(field), checkArgument(fieldMap.containsKey(field),
@ -235,8 +234,7 @@ public abstract class ListObjectsAction<T extends ImmutableObject> implements Ru
if (isHeaderRowInUse(data)) { if (isHeaderRowInUse(data)) {
// Add a row of headers (column names mapping to themselves). // Add a row of headers (column names mapping to themselves).
Map<String, String> headerRow = Map<String, String> headerRow = Maps.asMap(data.columnKeySet(), key -> key);
Maps.asMap(data.columnKeySet(), Functions.identity());
lines.add(rowFormatter.apply(headerRow)); lines.add(rowFormatter.apply(headerRow));
// Add a row of separator lines (column names mapping to '-' * column width). // Add a row of separator lines (column names mapping to '-' * column width).

View file

@ -22,8 +22,6 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet;
import com.google.common.base.Ascii; import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -36,6 +34,7 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import javax.annotation.Detainted; import javax.annotation.Detainted;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.annotation.Tainted; import javax.annotation.Tainted;
@ -137,7 +136,7 @@ public final class FormField<I, O> {
/** Returns an optional form field named {@code name} with a specific {@code inputType}. */ /** Returns an optional form field named {@code name} with a specific {@code inputType}. */
public static <T> Builder<T, T> named(String name, Class<T> typeIn) { public static <T> Builder<T, T> named(String name, Class<T> typeIn) {
checkArgument(!name.isEmpty()); checkArgument(!name.isEmpty());
return new Builder<>(name, checkNotNull(typeIn), typeIn, Functions.identity()); return new Builder<>(name, checkNotNull(typeIn), typeIn, x -> x);
} }
/** /**
@ -445,8 +444,8 @@ public final class FormField<I, O> {
* @see #transform(Function) * @see #transform(Function)
*/ */
public <T> Builder<I, T> transform(Class<T> newType, Function<O, T> transform) { public <T> Builder<I, T> transform(Class<T> newType, Function<O, T> transform) {
return new Builder<>(name, typeIn, checkNotNull(newType), return new Builder<>(
Functions.compose(checkNotNull(transform), converter)); name, typeIn, checkNotNull(newType), this.converter.andThen(checkNotNull(transform)));
} }
/** /**
@ -456,7 +455,7 @@ public final class FormField<I, O> {
* which {@code transform} is expected to conform. * which {@code transform} is expected to conform.
*/ */
public Builder<I, O> transform(Function<O, O> transform) { public Builder<I, O> transform(Function<O, O> transform) {
this.converter = Functions.compose(checkNotNull(transform), converter); this.converter = this.converter.andThen(checkNotNull(transform));
return this; return this;
} }

View file

@ -20,7 +20,6 @@ import static com.google.common.collect.Range.closed;
import static google.registry.util.DomainNameUtils.canonicalizeDomainName; import static google.registry.util.DomainNameUtils.canonicalizeDomainName;
import com.google.common.base.Ascii; import com.google.common.base.Ascii;
import com.google.common.base.Function;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.net.InternetDomainName; import com.google.common.net.InternetDomainName;
@ -38,6 +37,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
/** Form fields for validating input for the {@code Registrar} class. */ /** Form fields for validating input for the {@code Registrar} class. */
public final class RegistrarFormFields { public final class RegistrarFormFields {

View file

@ -14,7 +14,6 @@
package google.registry.ui.server.registrar; package google.registry.ui.server.registrar;
import static com.google.common.base.Functions.toStringFunction;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.security.JsonResponseHelper.Status.ERROR; import static google.registry.security.JsonResponseHelper.Status.ERROR;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
@ -118,7 +117,7 @@ public final class RegistrarPaymentSetupAction implements Runnable, JsonAction {
accountIds accountIds
.keySet() .keySet()
.stream() .stream()
.map(toStringFunction()) .map(Object::toString)
.collect(toImmutableList())))); .collect(toImmutableList()))));
} }
} }

View file

@ -21,7 +21,6 @@ import static java.lang.Math.max;
import static java.lang.Math.min; import static java.lang.Math.min;
import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.Executors.newFixedThreadPool;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.Uninterruptibles; import com.google.common.util.concurrent.Uninterruptibles;
@ -32,6 +31,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.function.Function;
/** Utilities for multithreaded operations in App Engine requests. */ /** Utilities for multithreaded operations in App Engine requests. */
public final class Concurrent { public final class Concurrent {

View file

@ -1,24 +0,0 @@
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.util;
import com.google.common.base.Function;
import com.googlecode.objectify.Key;
/** Utilities for working with Objectify. */
public class ObjectifyUtils {
public static final Function<Object, Key<?>> OBJECTS_TO_KEYS = Key::create;
}

View file

@ -19,7 +19,6 @@ import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.html.HtmlEscapers.htmlEscaper; 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.Joiner;
import google.registry.model.eppcommon.Address; import google.registry.model.eppcommon.Address;
import google.registry.util.Idn; import google.registry.util.Idn;
@ -27,6 +26,7 @@ import google.registry.xml.UtcDateTimeAdapter;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.joda.time.DateTime; import org.joda.time.DateTime;

View file

@ -15,7 +15,6 @@
package google.registry.backup; package google.registry.backup;
import static com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService; import static com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService;
import static com.google.common.base.Functions.constant;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Maps.toMap; import static com.google.common.collect.Maps.toMap;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@ -247,7 +246,7 @@ public class RestoreCommitLogsActionTest {
} }
private CommitLogCheckpoint createCheckpoint(DateTime now) { private CommitLogCheckpoint createCheckpoint(DateTime now) {
return CommitLogCheckpoint.create(now, toMap(getBucketIds(), constant(now))); return CommitLogCheckpoint.create(now, toMap(getBucketIds(), x -> now));
} }
private Iterable<ImmutableObject> saveDiffFile( private Iterable<ImmutableObject> saveDiffFile(

View file

@ -16,23 +16,24 @@ package google.registry.flows;
import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.difference;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.EppXmlTransformer.marshal; import static google.registry.flows.EppXmlTransformer.marshal;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.BILLING_EVENT_ID_STRIPPER; import static google.registry.testing.DatastoreHelper.BILLING_EVENT_ID_STRIPPER;
import static google.registry.testing.DatastoreHelper.POLL_MESSAGE_ID_STRIPPER;
import static google.registry.testing.DatastoreHelper.getPollMessages; import static google.registry.testing.DatastoreHelper.getPollMessages;
import static google.registry.xml.XmlTestUtils.assertXmlEquals; import static google.registry.xml.XmlTestUtils.assertXmlEquals;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays; import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Streams;
import google.registry.config.RegistryConfig.ConfigModule.TmchCaMode; import google.registry.config.RegistryConfig.ConfigModule.TmchCaMode;
import google.registry.flows.EppTestComponent.FakesAndMocksModule; import google.registry.flows.EppTestComponent.FakesAndMocksModule;
import google.registry.flows.picker.FlowPicker; import google.registry.flows.picker.FlowPicker;
@ -58,8 +59,10 @@ import google.registry.tmch.TmchCertificateAuthority;
import google.registry.tmch.TmchXmlSignature; import google.registry.tmch.TmchXmlSignature;
import google.registry.util.TypeUtils.TypeInstantiator; import google.registry.util.TypeUtils.TypeInstantiator;
import google.registry.xml.ValidationMode; import google.registry.xml.ValidationMode;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
@ -217,6 +220,18 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
return builder.build(); return builder.build();
} }
private static BillingEvent expandGracePeriod(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();
}
/** /**
* Assert that the actual grace periods and the corresponding billing events referenced from * Assert that the actual grace periods and the corresponding billing events referenced from
* their keys match the expected map of grace periods to billing events. For the expected map, * their keys match the expected map of grace periods to billing events. For the expected map,
@ -225,19 +240,7 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
public void assertGracePeriods( public void assertGracePeriods(
Iterable<GracePeriod> actual, Iterable<GracePeriod> actual,
ImmutableMap<GracePeriod, ? extends BillingEvent> expected) { ImmutableMap<GracePeriod, ? extends BillingEvent> expected) {
Function<GracePeriod, BillingEvent> gracePeriodExpander = assertThat(canonicalizeGracePeriods(Maps.toMap(actual, FlowTestCase::expandGracePeriod)))
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)); .isEqualTo(canonicalizeGracePeriods(expected));
} }
@ -261,12 +264,11 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
/** Assert that the list matches all the poll messages in the fake Datastore. */ /** Assert that the list matches all the poll messages in the fake Datastore. */
public void assertPollMessagesHelper(Iterable<PollMessage> pollMessages, PollMessage... expected) public void assertPollMessagesHelper(Iterable<PollMessage> pollMessages, PollMessage... expected)
throws Exception { throws Exception {
// To facilitate comparison, remove the ids.
Function<PollMessage, PollMessage> idStripper =
pollMessage -> pollMessage.asBuilder().setId(1L).build();
// Ordering is irrelevant but duplicates should be considered independently. // Ordering is irrelevant but duplicates should be considered independently.
assertThat(FluentIterable.from(pollMessages).transform(idStripper)) assertThat(
.containsExactlyElementsIn(FluentIterable.from(expected).transform(idStripper)); Streams.stream(pollMessages).map(POLL_MESSAGE_ID_STRIPPER).collect(toImmutableList()))
.containsExactlyElementsIn(
Arrays.stream(expected).map(POLL_MESSAGE_ID_STRIPPER).collect(toImmutableList()));
} }
private EppOutput runFlowInternal(CommitMode commitMode, UserPrivileges userPrivileges) private EppOutput runFlowInternal(CommitMode commitMode, UserPrivileges userPrivileges)

View file

@ -37,8 +37,6 @@ import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMap;
@ -72,6 +70,8 @@ import google.registry.model.reporting.HistoryEntry;
import google.registry.model.transfer.TransferData; import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferResponse.DomainTransferResponse; import google.registry.model.transfer.TransferResponse.DomainTransferResponse;
import google.registry.model.transfer.TransferStatus; import google.registry.model.transfer.TransferStatus;
import java.util.Arrays;
import java.util.stream.Stream;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Duration; import org.joda.time.Duration;
@ -262,22 +262,21 @@ public class DomainTransferApproveFlowTest
.build(); .build();
assertBillingEventsForResource( assertBillingEventsForResource(
domain, domain,
FluentIterable.from(expectedCancellationBillingEvents) Stream.concat(
.transform( Arrays.stream(expectedCancellationBillingEvents)
(Function<BillingEvent.Cancellation.Builder, BillingEvent>) .map(builder -> builder.setParent(historyEntryTransferApproved).build()),
builder -> builder.setParent(historyEntryTransferApproved).build()) Stream.of(
.append( transferBillingEvent,
transferBillingEvent, getLosingClientAutorenewEvent()
getLosingClientAutorenewEvent() .asBuilder()
.asBuilder() .setRecurrenceEndTime(clock.nowUtc())
.setRecurrenceEndTime(clock.nowUtc()) .build(),
.build(), getGainingClientAutorenewEvent()
getGainingClientAutorenewEvent() .asBuilder()
.asBuilder() .setEventTime(domain.getRegistrationExpirationTime())
.setEventTime(domain.getRegistrationExpirationTime()) .setParent(historyEntryTransferApproved)
.setParent(historyEntryTransferApproved) .build()))
.build()) .toArray(size -> new BillingEvent[size]));
.toArray(BillingEvent.class));
// There should be a grace period for the new transfer billing event. // There should be a grace period for the new transfer billing event.
assertGracePeriods( assertGracePeriods(
domain.getGracePeriods(), domain.getGracePeriods(),
@ -299,21 +298,20 @@ public class DomainTransferApproveFlowTest
// for the gaining client that begins at the new expiration time. // for the gaining client that begins at the new expiration time.
assertBillingEventsForResource( assertBillingEventsForResource(
domain, domain,
FluentIterable.from(expectedCancellationBillingEvents) Stream.concat(
.transform( Arrays.stream(expectedCancellationBillingEvents)
(Function<BillingEvent.Cancellation.Builder, BillingEvent>) .map(builder -> builder.setParent(historyEntryTransferApproved).build()),
builder -> builder.setParent(historyEntryTransferApproved).build()) Stream.of(
.append( getLosingClientAutorenewEvent()
getLosingClientAutorenewEvent() .asBuilder()
.asBuilder() .setRecurrenceEndTime(clock.nowUtc())
.setRecurrenceEndTime(clock.nowUtc()) .build(),
.build(), getGainingClientAutorenewEvent()
getGainingClientAutorenewEvent() .asBuilder()
.asBuilder() .setEventTime(domain.getRegistrationExpirationTime())
.setEventTime(domain.getRegistrationExpirationTime()) .setParent(historyEntryTransferApproved)
.setParent(historyEntryTransferApproved) .build()))
.build()) .toArray(size -> new BillingEvent[size]));
.toArray(BillingEvent.class));
// There should be no grace period. // There should be no grace period.
assertGracePeriods(domain.getGracePeriods(), ImmutableMap.of()); assertGracePeriods(domain.getGracePeriods(), ImmutableMap.of());
} }

View file

@ -14,6 +14,7 @@
package google.registry.flows.domain; package google.registry.flows.domain;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
@ -37,12 +38,10 @@ import static google.registry.testing.HostResourceSubject.assertAboutHosts;
import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.JUnitBackports.expectThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.stream.Collectors.toSet;
import static org.joda.money.CurrencyUnit.EUR; import static org.joda.money.CurrencyUnit.EUR;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
import com.google.appengine.repackaged.com.google.common.collect.Sets; import com.google.appengine.repackaged.com.google.common.collect.Sets;
import com.google.common.base.Function;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -91,7 +90,6 @@ import google.registry.model.transfer.TransferResponse;
import google.registry.model.transfer.TransferStatus; import google.registry.model.transfer.TransferStatus;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -257,6 +255,11 @@ public class DomainTransferRequestFlowTest
expectedExpirationTime, implicitTransferTime, Period.create(1, Unit.YEARS)); expectedExpirationTime, implicitTransferTime, Period.create(1, Unit.YEARS));
} }
/** Implements the missing Optional.stream function that is added in Java 9. */
private static <T> Stream<T> optionalToStream(Optional<T> optional) {
return optional.map(Stream::of).orElseGet(Stream::empty);
}
private void assertHistoryEntriesContainBillingEventsAndGracePeriods( private void assertHistoryEntriesContainBillingEventsAndGracePeriods(
DateTime expectedExpirationTime, DateTime expectedExpirationTime,
DateTime implicitTransferTime, DateTime implicitTransferTime,
@ -304,16 +307,16 @@ public class DomainTransferRequestFlowTest
BillingEvent.Recurring gainingClientAutorenew = BillingEvent.Recurring gainingClientAutorenew =
getGainingClientAutorenewEvent().asBuilder().setEventTime(expectedExpirationTime).build(); getGainingClientAutorenewEvent().asBuilder().setEventTime(expectedExpirationTime).build();
// Construct extra billing events expected by the specific test. // Construct extra billing events expected by the specific test.
Set<BillingEvent> extraBillingEvents = ImmutableSet<BillingEvent> extraBillingEvents =
Stream.of(extraExpectedBillingEvents) Stream.of(extraExpectedBillingEvents)
.map( .map(builder -> builder.setParent(historyEntryTransferRequest).build())
(Function<BillingEvent.Cancellation.Builder, BillingEvent>) .collect(toImmutableSet());
builder -> builder.setParent(historyEntryTransferRequest).build())
.collect(toSet());
// Assert that the billing events we constructed above actually exist in Datastore. // Assert that the billing events we constructed above actually exist in Datastore.
Set<BillingEvent> expectedBillingEvents = ImmutableSet<BillingEvent> expectedBillingEvents =
Sets.newHashSet(losingClientAutorenew, gainingClientAutorenew); Stream.concat(
optionalTransferBillingEvent.ifPresent(expectedBillingEvents::add); Stream.of(losingClientAutorenew, gainingClientAutorenew),
optionalToStream(optionalTransferBillingEvent))
.collect(toImmutableSet());
assertBillingEvents(Sets.union(expectedBillingEvents, extraBillingEvents)); assertBillingEvents(Sets.union(expectedBillingEvents, extraBillingEvents));
// Assert that the domain's TransferData server-approve billing events match the above. // Assert that the domain's TransferData server-approve billing events match the above.
if (expectTransferBillingEvent) { if (expectTransferBillingEvent) {
@ -328,8 +331,10 @@ public class DomainTransferRequestFlowTest
gainingClientAutorenew); gainingClientAutorenew);
// Assert that the full set of server-approve billing events is exactly the extra ones plus // Assert that the full set of server-approve billing events is exactly the extra ones plus
// the transfer billing event (if present) and the gaining client autorenew. // the transfer billing event (if present) and the gaining client autorenew.
Set<BillingEvent> expectedServeApproveBillingEvents = Sets.newHashSet(gainingClientAutorenew); ImmutableSet<BillingEvent> expectedServeApproveBillingEvents =
optionalTransferBillingEvent.ifPresent(expectedServeApproveBillingEvents::add); Stream.concat(
Stream.of(gainingClientAutorenew), optionalToStream(optionalTransferBillingEvent))
.collect(toImmutableSet());
assertBillingEventsEqual( assertBillingEventsEqual(
Iterables.filter( Iterables.filter(
ofy() ofy()

View file

@ -18,7 +18,6 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.EntityClasses.ALL_CLASSES; import static google.registry.model.EntityClasses.ALL_CLASSES;
import static google.registry.util.TypeUtils.hasAnnotation; import static google.registry.util.TypeUtils.hasAnnotation;
import static java.util.stream.Collectors.toSet;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
@ -63,13 +62,13 @@ public class EntityClassesTest {
.stream() .stream()
.filter(hasAnnotation(Entity.class)) .filter(hasAnnotation(Entity.class))
.map(Key::getKind) .map(Key::getKind)
.collect(toSet()); .collect(toImmutableSet());
Set<String> entitySubclassKinds = Set<String> entitySubclassKinds =
ALL_CLASSES ALL_CLASSES
.stream() .stream()
.filter(hasAnnotation(EntitySubclass.class)) .filter(hasAnnotation(EntitySubclass.class))
.map(Key::getKind) .map(Key::getKind)
.collect(toSet()); .collect(toImmutableSet());
assertThat(baseEntityKinds).named("base entity kinds").containsAllIn(entitySubclassKinds); assertThat(baseEntityKinds).named("base entity kinds").containsAllIn(entitySubclassKinds);
} }

View file

@ -251,6 +251,27 @@ public class ImmutableObjectTest {
assertThat(cloned.heterogenousMap).containsEntry("b", ""); assertThat(cloned.heterogenousMap).containsEntry("b", "");
} }
/** Subclass of ImmutableObject with fields that are containers containing null values. */
public static class NullInContainersObject extends ImmutableObject {
Object[] array = new Object[] {null};
List<?> list = newArrayList((Object) null);
Set<?> set = newHashSet((Object) null);
Map<String, ?> map = newHashMap();
public NullInContainersObject() {
map.put("a", null);
}
}
@Test
public void testToDiffableFieldMap_withEmptyAndNulls() {
Map<String, Object> diffableFieldMap = new NullInContainersObject().toDiffableFieldMap();
assertThat((List<?>) diffableFieldMap.get("array")).containsExactly((Object) null);
assertThat((List<?>) diffableFieldMap.get("list")).containsExactly((Object) null);
assertThat((Set<?>) diffableFieldMap.get("set")).containsExactly((Object) null);
assertThat((Map<?, ?>) diffableFieldMap.get("map")).containsExactly("a", (Object) null);
}
/** Subclass of ImmutableObject with keys to other objects. */ /** Subclass of ImmutableObject with keys to other objects. */
public static class RootObject extends ImmutableObject { public static class RootObject extends ImmutableObject {

View file

@ -14,12 +14,11 @@
package google.registry.model.registry; package google.registry.model.registry;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.registry.label.ReservedListTest.GET_NAME_FUNCTION;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.newRegistry; import static google.registry.testing.DatastoreHelper.newRegistry;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
@ -142,7 +141,7 @@ public class RegistryTest extends EntityTestCase {
"mouse,FULLY_BLOCKED"); "mouse,FULLY_BLOCKED");
Registry r = Registry.get("tld") Registry r = Registry.get("tld")
.asBuilder().setReservedLists(ImmutableSet.of(rl5, rl6)).build(); .asBuilder().setReservedLists(ImmutableSet.of(rl5, rl6)).build();
assertThat(transform(r.getReservedLists(), GET_NAME_FUNCTION)) assertThat(r.getReservedLists().stream().map(Key::getName).collect(toImmutableList()))
.containsExactly("tld-reserved5", "tld-reserved6"); .containsExactly("tld-reserved5", "tld-reserved6");
r = Registry.get("tld").asBuilder().setReservedLists(ImmutableSet.<ReservedList> of()).build(); r = Registry.get("tld").asBuilder().setReservedLists(ImmutableSet.<ReservedList> of()).build();
assertThat(r.getReservedLists()).isEmpty(); assertThat(r.getReservedLists()).isEmpty();
@ -163,7 +162,7 @@ public class RegistryTest extends EntityTestCase {
.asBuilder() .asBuilder()
.setReservedListsByName(ImmutableSet.of("tld-reserved24", "tld-reserved25")) .setReservedListsByName(ImmutableSet.of("tld-reserved24", "tld-reserved25"))
.build(); .build();
assertThat(transform(r.getReservedLists(), GET_NAME_FUNCTION)) assertThat(r.getReservedLists().stream().map(Key::getName).collect(toImmutableList()))
.containsExactly("tld-reserved24", "tld-reserved25"); .containsExactly("tld-reserved24", "tld-reserved25");
r = Registry.get("tld").asBuilder().setReservedListsByName(ImmutableSet.<String> of()).build(); r = Registry.get("tld").asBuilder().setReservedListsByName(ImmutableSet.<String> of()).build();
assertThat(r.getReservedLists()).isEmpty(); assertThat(r.getReservedLists()).isEmpty();

View file

@ -36,11 +36,9 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.net.InternetDomainName; import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key;
import google.registry.model.ofy.Ofy; import google.registry.model.ofy.Ofy;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import google.registry.model.registry.label.ReservedList.ReservedListEntry; import google.registry.model.registry.label.ReservedList.ReservedListEntry;
@ -585,7 +583,4 @@ public class ReservedListTest {
.contains( .contains(
"List 'blah' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); "List 'blah' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]");
} }
/** Gets the name of a reserved list. */
public static final Function<Key<ReservedList>, String> GET_NAME_FUNCTION = Key::getName;
} }

View file

@ -19,9 +19,9 @@ import static com.google.common.truth.Truth8.assertThat;
import static google.registry.request.auth.Auth.AUTH_INTERNAL_ONLY; import static google.registry.request.auth.Auth.AUTH_INTERNAL_ONLY;
import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.Function;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.function.Function;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;

View file

@ -43,10 +43,8 @@ import static java.util.Arrays.asList;
import static org.joda.money.CurrencyUnit.USD; import static org.joda.money.CurrencyUnit.USD;
import com.google.common.base.Ascii; import com.google.common.base.Ascii;
import com.google.common.base.Function;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -103,6 +101,7 @@ import google.registry.tmch.LordnTask;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.joda.money.Money; import org.joda.money.Money;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -669,8 +668,9 @@ public class DatastoreHelper {
/** Assert that the actual billing events match the expected ones, ignoring IDs and order. */ /** Assert that the actual billing events match the expected ones, ignoring IDs and order. */
public static void assertBillingEventsEqual( public static void assertBillingEventsEqual(
Iterable<BillingEvent> actual, Iterable<BillingEvent> expected) { Iterable<BillingEvent> actual, Iterable<BillingEvent> expected) {
assertThat(Iterables.transform(actual, BILLING_EVENT_ID_STRIPPER)) assertThat(Streams.stream(actual).map(BILLING_EVENT_ID_STRIPPER).collect(toImmutableList()))
.containsExactlyElementsIn(Iterables.transform(expected, BILLING_EVENT_ID_STRIPPER)); .containsExactlyElementsIn(
Streams.stream(expected).map(BILLING_EVENT_ID_STRIPPER).collect(toImmutableList()));
} }
/** Assert that the expected billing events are exactly the ones found in the fake Datastore. */ /** Assert that the expected billing events are exactly the ones found in the fake Datastore. */
@ -688,9 +688,12 @@ public class DatastoreHelper {
*/ */
public static void assertBillingEventsForResource( public static void assertBillingEventsForResource(
EppResource resource, BillingEvent... expected) throws Exception { EppResource resource, BillingEvent... expected) throws Exception {
assertThat(FluentIterable.from(getBillingEvents(resource)).transform(BILLING_EVENT_ID_STRIPPER)) assertThat(
Streams.stream(getBillingEvents(resource))
.map(BILLING_EVENT_ID_STRIPPER)
.collect(toImmutableList()))
.containsExactlyElementsIn( .containsExactlyElementsIn(
FluentIterable.from(expected).transform(BILLING_EVENT_ID_STRIPPER)); Arrays.stream(expected).map(BILLING_EVENT_ID_STRIPPER).collect(toImmutableList()));
} }
/** Assert that there are no billing events. */ /** Assert that there are no billing events. */
@ -711,15 +714,20 @@ public class DatastoreHelper {
/** Assert that the actual poll messages match the expected ones, ignoring IDs and order. */ /** Assert that the actual poll messages match the expected ones, ignoring IDs and order. */
public static void assertPollMessagesEqual( public static void assertPollMessagesEqual(
Iterable<PollMessage> actual, Iterable<PollMessage> expected) { Iterable<PollMessage> actual, Iterable<PollMessage> expected) {
assertThat(Iterables.transform(actual, POLL_MESSAGE_ID_STRIPPER)) assertThat(Streams.stream(actual).map(POLL_MESSAGE_ID_STRIPPER).collect(toImmutableList()))
.containsExactlyElementsIn(Iterables.transform(expected, POLL_MESSAGE_ID_STRIPPER)); .containsExactlyElementsIn(
Streams.stream(expected).map(POLL_MESSAGE_ID_STRIPPER).collect(toImmutableList()));
} }
public static void assertPollMessagesForResource(EppResource resource, PollMessage... expected) public static void assertPollMessagesForResource(EppResource resource, PollMessage... expected)
throws Exception { throws Exception {
assertThat(FluentIterable.from(getPollMessages(resource)).transform(POLL_MESSAGE_ID_STRIPPER)) assertThat(
getPollMessages(resource)
.stream()
.map(POLL_MESSAGE_ID_STRIPPER)
.collect(toImmutableList()))
.containsExactlyElementsIn( .containsExactlyElementsIn(
FluentIterable.from(expected).transform(POLL_MESSAGE_ID_STRIPPER)); Arrays.stream(expected).map(POLL_MESSAGE_ID_STRIPPER).collect(toImmutableList()));
} }
/** Helper to effectively erase the poll message ID to facilitate comparison. */ /** Helper to effectively erase the poll message ID to facilitate comparison. */

View file

@ -18,8 +18,8 @@ import static com.google.appengine.tools.development.testing.LocalTaskQueueTestC
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not; import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getFirst; import static com.google.common.collect.Iterables.getFirst;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Multisets.containsOccurrences; import static com.google.common.collect.Multisets.containsOccurrences;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_; import static com.google.common.truth.Truth.assert_;
@ -32,7 +32,6 @@ import com.google.appengine.api.taskqueue.dev.QueueStateInfo;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo.HeaderWrapper; import com.google.appengine.api.taskqueue.dev.QueueStateInfo.HeaderWrapper;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo.TaskStateInfo; import com.google.appengine.api.taskqueue.dev.QueueStateInfo.TaskStateInfo;
import com.google.common.base.Ascii; import com.google.common.base.Ascii;
import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ArrayListMultimap;
@ -55,6 +54,7 @@ import java.util.LinkedList;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import java.util.function.Function;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import org.joda.time.Duration; import org.joda.time.Duration;
@ -196,7 +196,12 @@ public class TaskQueueHelper {
Function<TaskStateInfo, String> propertyGetter, Function<TaskStateInfo, String> propertyGetter,
String... expectedTaskProperties) throws Exception { String... expectedTaskProperties) throws Exception {
// Ordering is irrelevant but duplicates should be considered independently. // Ordering is irrelevant but duplicates should be considered independently.
assertThat(transform(getQueueInfo(queueName).getTaskInfo(), propertyGetter)) assertThat(
getQueueInfo(queueName)
.getTaskInfo()
.stream()
.map(propertyGetter)
.collect(toImmutableList()))
.containsExactly((Object[]) expectedTaskProperties); .containsExactly((Object[]) expectedTaskProperties);
} }

View file

@ -14,9 +14,8 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.registry.label.ReservedListTest.GET_NAME_FUNCTION;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistReservedList; import static google.registry.testing.DatastoreHelper.persistReservedList;
@ -31,6 +30,7 @@ import static org.joda.time.Duration.standardMinutes;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import com.googlecode.objectify.Key;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import google.registry.model.registry.Registry.TldState; import google.registry.model.registry.Registry.TldState;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -283,7 +283,12 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
"--roid_suffix=Q9JYB4C", "--roid_suffix=Q9JYB4C",
"--dns_writers=VoidDnsWriter", "--dns_writers=VoidDnsWriter",
"xn--q9jyb4c"); "xn--q9jyb4c");
assertThat(transform(Registry.get("xn--q9jyb4c").getReservedLists(), GET_NAME_FUNCTION)) assertThat(
Registry.get("xn--q9jyb4c")
.getReservedLists()
.stream()
.map(Key::getName)
.collect(toImmutableList()))
.containsExactly("xn--q9jyb4c_abuse", "common_abuse"); .containsExactly("xn--q9jyb4c_abuse", "common_abuse");
} }

View file

@ -14,9 +14,8 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.registry.label.ReservedListTest.GET_NAME_FUNCTION;
import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistReservedList; import static google.registry.testing.DatastoreHelper.persistReservedList;
@ -282,7 +281,12 @@ public class UpdateTldCommandTest extends CommandTestCase<UpdateTldCommand> {
public void testSuccess_setReservedLists() throws Exception { public void testSuccess_setReservedLists() throws Exception {
runCommandForced("--reserved_lists=xn--q9jyb4c_r1,xn--q9jyb4c_r2", "xn--q9jyb4c"); runCommandForced("--reserved_lists=xn--q9jyb4c_r1,xn--q9jyb4c_r2", "xn--q9jyb4c");
assertThat(transform(Registry.get("xn--q9jyb4c").getReservedLists(), GET_NAME_FUNCTION)) assertThat(
Registry.get("xn--q9jyb4c")
.getReservedLists()
.stream()
.map(Key::getName)
.collect(toImmutableList()))
.containsExactly("xn--q9jyb4c_r1", "xn--q9jyb4c_r2"); .containsExactly("xn--q9jyb4c_r1", "xn--q9jyb4c_r2");
} }
@ -292,7 +296,12 @@ public class UpdateTldCommandTest extends CommandTestCase<UpdateTldCommand> {
.setReservedListsByName(ImmutableSet.of("xn--q9jyb4c_r1", "xn--q9jyb4c_r2")) .setReservedListsByName(ImmutableSet.of("xn--q9jyb4c_r1", "xn--q9jyb4c_r2"))
.build()); .build());
runCommandForced("--reserved_lists=xn--q9jyb4c_r2", "xn--q9jyb4c"); runCommandForced("--reserved_lists=xn--q9jyb4c_r2", "xn--q9jyb4c");
assertThat(transform(Registry.get("xn--q9jyb4c").getReservedLists(), GET_NAME_FUNCTION)) assertThat(
Registry.get("xn--q9jyb4c")
.getReservedLists()
.stream()
.map(Key::getName)
.collect(toImmutableList()))
.containsExactly("xn--q9jyb4c_r2"); .containsExactly("xn--q9jyb4c_r2");
} }
@ -302,7 +311,12 @@ public class UpdateTldCommandTest extends CommandTestCase<UpdateTldCommand> {
.setReservedListsByName(ImmutableSet.of("xn--q9jyb4c_r1")) .setReservedListsByName(ImmutableSet.of("xn--q9jyb4c_r1"))
.build()); .build());
runCommandForced("--add_reserved_lists=xn--q9jyb4c_r2", "xn--q9jyb4c"); runCommandForced("--add_reserved_lists=xn--q9jyb4c_r2", "xn--q9jyb4c");
assertThat(transform(Registry.get("xn--q9jyb4c").getReservedLists(), GET_NAME_FUNCTION)) assertThat(
Registry.get("xn--q9jyb4c")
.getReservedLists()
.stream()
.map(Key::getName)
.collect(toImmutableList()))
.containsExactly("xn--q9jyb4c_r1", "xn--q9jyb4c_r2"); .containsExactly("xn--q9jyb4c_r1", "xn--q9jyb4c_r2");
} }
@ -321,7 +335,12 @@ public class UpdateTldCommandTest extends CommandTestCase<UpdateTldCommand> {
.setReservedListsByName(ImmutableSet.of("xn--q9jyb4c_r1", "xn--q9jyb4c_r2")) .setReservedListsByName(ImmutableSet.of("xn--q9jyb4c_r1", "xn--q9jyb4c_r2"))
.build()); .build());
runCommandForced("--remove_reserved_lists=xn--q9jyb4c_r1", "xn--q9jyb4c"); runCommandForced("--remove_reserved_lists=xn--q9jyb4c_r1", "xn--q9jyb4c");
assertThat(transform(Registry.get("xn--q9jyb4c").getReservedLists(), GET_NAME_FUNCTION)) assertThat(
Registry.get("xn--q9jyb4c")
.getReservedLists()
.stream()
.map(Key::getName)
.collect(toImmutableList()))
.containsExactly("xn--q9jyb4c_r2"); .containsExactly("xn--q9jyb4c_r2");
} }

View file

@ -25,8 +25,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -36,6 +34,7 @@ import com.google.common.testing.NullPointerTester;
import com.google.re2j.Pattern; import com.google.re2j.Pattern;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -241,7 +240,7 @@ public class FormFieldTest {
assertThat( assertThat(
FormField.named("lol") FormField.named("lol")
.transform(Object.class, Integer::parseInt) .transform(Object.class, Integer::parseInt)
.transform(String.class, Functions.toStringFunction()) .transform(String.class, Object::toString)
.build() .build()
.convert("123")) .convert("123"))
.hasValue("123"); .hasValue("123");
@ -484,11 +483,12 @@ public class FormFieldTest {
@Test @Test
public void testNullness() { public void testNullness() {
NullPointerTester tester = new NullPointerTester() NullPointerTester tester =
.setDefault(Class.class, Object.class) new NullPointerTester()
.setDefault(Function.class, Functions.identity()) .setDefault(Class.class, Object.class)
.setDefault(Pattern.class, Pattern.compile(".")) .setDefault(Function.class, x -> x)
.setDefault(String.class, "hello.com"); .setDefault(Pattern.class, Pattern.compile("."))
.setDefault(String.class, "hello.com");
tester.testAllPublicStaticMethods(FormField.class); tester.testAllPublicStaticMethods(FormField.class);
tester.testAllPublicInstanceMethods(FormField.named("lol")); tester.testAllPublicInstanceMethods(FormField.named("lol"));
tester.testAllPublicInstanceMethods(FormField.named("lol").build()); tester.testAllPublicInstanceMethods(FormField.named("lol").build());

View file

@ -17,12 +17,11 @@ package google.registry.util;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.testing.NullPointerTester; import com.google.common.testing.NullPointerTester;
import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.common.util.concurrent.UncheckedExecutionException;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import java.util.function.Function;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -39,7 +38,7 @@ public class ConcurrentTest {
@Test @Test
public void testTransform_emptyList_returnsEmptyList() throws Exception { public void testTransform_emptyList_returnsEmptyList() throws Exception {
assertThat(Concurrent.transform(ImmutableList.of(), Functions.identity())).isEmpty(); assertThat(Concurrent.transform(ImmutableList.of(), x -> x)).isEmpty();
} }
@Test @Test
@ -66,8 +65,7 @@ public class ConcurrentTest {
@Test @Test
public void testNullness() throws Exception { public void testNullness() throws Exception {
NullPointerTester tester = new NullPointerTester() NullPointerTester tester = new NullPointerTester().setDefault(Function.class, x -> x);
.setDefault(Function.class, Functions.identity());
tester.testAllPublicStaticMethods(Concurrent.class); tester.testAllPublicStaticMethods(Concurrent.class);
} }
} }