Deprecate more fields in RegistryConfig

This primarily addresses issues with TMCH testing mode and email sending utils.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=143710550
This commit is contained in:
mcilwain 2017-01-05 14:38:38 -08:00 committed by Ben McIlwain
parent c05424b947
commit 25a8bbe890
23 changed files with 203 additions and 265 deletions

View file

@ -16,6 +16,7 @@ package google.registry.config;
import static google.registry.config.ConfigUtils.makeUrl; import static google.registry.config.ConfigUtils.makeUrl;
import com.google.appengine.api.utils.SystemProperty;
import com.google.common.base.Optional; import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -214,8 +215,8 @@ public final class ConfigModule {
/** @see RegistryConfig#getCommitLogDatastoreRetention() */ /** @see RegistryConfig#getCommitLogDatastoreRetention() */
@Provides @Provides
@Config("commitLogDatastoreRetention") @Config("commitLogDatastoreRetention")
public static Duration provideCommitLogDatastoreRetention(RegistryConfig config) { public static Duration provideCommitLogDatastoreRetention() {
return config.getCommitLogDatastoreRetention(); return RegistryConfig.getCommitLogDatastoreRetention();
} }
/** /**
@ -423,8 +424,8 @@ public final class ConfigModule {
*/ */
@Provides @Provides
@Config("tmchCaTestingMode") @Config("tmchCaTestingMode")
public static boolean provideTmchCaTestingMode(RegistryConfig config) { public static boolean provideTmchCaTestingMode() {
return config.getTmchCaTestingMode(); return RegistryConfig.getTmchCaTestingMode();
} }
/** /**
@ -467,6 +468,29 @@ public final class ConfigModule {
} }
} }
/**
* The email address that outgoing emails from the app are sent from.
*
* @see google.registry.util.SendEmailUtils
*/
@Provides
@Config("googleAppsSendFromEmailAddress")
public static String provideGoogleAppsSendFromEmailAddress() {
return String.format("noreply@%s.appspotmail.com", SystemProperty.applicationId.get());
}
/**
* The display name that is used on outgoing emails sent by Nomulus.
*
* @see google.registry.util.SendEmailUtils
*/
@Provides
@Config("googleAppsAdminEmailDisplayName")
public static String provideGoogleAppsAdminEmailDisplayName() {
// Production example: "Example Registry"
return "Google Domain Registry";
}
/** /**
* Returns the Google Cloud Storage bucket for staging escrow deposits pending upload. * Returns the Google Cloud Storage bucket for staging escrow deposits pending upload.
* *
@ -1025,5 +1049,9 @@ public final class ConfigModule {
public static class LocalTestConfig { public static class LocalTestConfig {
public static final String CONTACT_AND_HOST_ROID_SUFFIX = "ROID"; public static final String CONTACT_AND_HOST_ROID_SUFFIX = "ROID";
public static final String GOOGLE_APPS_SEND_FROM_EMAIL_ADDRESS = "noreply@testing.example";
public static final String GOOGLE_APPS_ADMIN_EMAIL_DISPLAY_NAME = "Testing Nomulus";
} }
} }

View file

@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.config.ConfigUtils.makeUrl; import static google.registry.config.ConfigUtils.makeUrl;
import static org.joda.time.Duration.standardDays; import static org.joda.time.Duration.standardDays;
import com.google.appengine.api.utils.SystemProperty;
import com.google.common.base.Optional; import com.google.common.base.Optional;
import com.google.common.net.HostAndPort; import com.google.common.net.HostAndPort;
import java.net.URL; import java.net.URL;
@ -48,33 +47,6 @@ public final class ProductionRegistryConfigExample extends RegistryConfig {
this.environment = checkNotNull(environment); this.environment = checkNotNull(environment);
} }
/**
* {@inheritDoc}
*
* <p>Thirty days makes a sane default, because it's highly unlikely we'll ever need to generate a
* deposit older than that. And if we do, we could always bring up a separate App Engine instance
* and replay the commit logs off GCS.
*/
@Override
public Duration getCommitLogDatastoreRetention() {
return Duration.standardDays(30);
}
@Override
public String getSnapshotsBucket() {
return RegistryConfig.getProjectId() + "-snapshots";
}
@Override
public boolean getTmchCaTestingMode() {
switch (environment) {
case PRODUCTION:
return false;
default:
return true;
}
}
@Override @Override
public Optional<String> getECatcherAddress() { public Optional<String> getECatcherAddress() {
throw new UnsupportedOperationException(); // n/a throw new UnsupportedOperationException(); // n/a
@ -91,36 +63,11 @@ public final class ProductionRegistryConfigExample extends RegistryConfig {
} }
} }
@Override
public Duration getSingletonCacheRefreshDuration() {
return Duration.standardMinutes(10);
}
@Override
public Duration getDomainLabelListCacheDuration() {
return Duration.standardHours(1);
}
@Override
public Duration getSingletonCachePersistDuration() {
return Duration.standardDays(365);
}
@Override @Override
public String getReservedTermsExportDisclaimer() { public String getReservedTermsExportDisclaimer() {
return RESERVED_TERMS_EXPORT_DISCLAIMER; return RESERVED_TERMS_EXPORT_DISCLAIMER;
} }
@Override
public String getGoogleAppsAdminEmailDisplayName() {
return "Example Registry";
}
@Override
public String getGoogleAppsSendFromEmailAddress() {
return String.format("noreply@%s.appspotmail.com", SystemProperty.applicationId.get());
}
@Override @Override
public String getRegistrarDefaultWhoisServer() { public String getRegistrarDefaultWhoisServer() {
return "whois.nic.registry.example"; return "whois.nic.registry.example";

View file

@ -49,7 +49,9 @@ public abstract class RegistryConfig {
* *
* @see google.registry.export.ExportSnapshotServlet * @see google.registry.export.ExportSnapshotServlet
*/ */
public abstract String getSnapshotsBucket(); public static String getSnapshotsBucket() {
return getProjectId() + "-snapshots";
}
/** /**
* Number of sharded commit log buckets. * Number of sharded commit log buckets.
@ -82,14 +84,23 @@ public abstract class RegistryConfig {
* @see google.registry.backup.DeleteOldCommitLogsAction * @see google.registry.backup.DeleteOldCommitLogsAction
* @see google.registry.model.translators.CommitLogRevisionsTranslatorFactory * @see google.registry.model.translators.CommitLogRevisionsTranslatorFactory
*/ */
public abstract Duration getCommitLogDatastoreRetention(); public static Duration getCommitLogDatastoreRetention() {
return Duration.standardDays(30);
}
/** /**
* Returns {@code true} if TMCH certificate authority should be in testing mode. * Returns {@code true} if TMCH certificate authority should be in testing mode.
* *
* @see google.registry.tmch.TmchCertificateAuthority * @see google.registry.tmch.TmchCertificateAuthority
*/ */
public abstract boolean getTmchCaTestingMode(); public static boolean getTmchCaTestingMode() {
switch (RegistryEnvironment.get()) {
case PRODUCTION:
return false;
default:
return true;
}
}
public abstract Optional<String> getECatcherAddress(); public abstract Optional<String> getECatcherAddress();
@ -101,7 +112,16 @@ public abstract class RegistryConfig {
public abstract HostAndPort getServer(); public abstract HostAndPort getServer();
/** Returns the amount of time a singleton should be cached, before expiring. */ /** Returns the amount of time a singleton should be cached, before expiring. */
public abstract Duration getSingletonCacheRefreshDuration(); public static Duration getSingletonCacheRefreshDuration() {
switch (RegistryEnvironment.get()) {
case UNITTEST:
// All cache durations are set to zero so that unit tests can update and then retrieve data
// immediately without failure.
return Duration.ZERO;
default:
return Duration.standardMinutes(10);
}
}
/** /**
* Returns the amount of time a domain label list should be cached in memory before expiring. * Returns the amount of time a domain label list should be cached in memory before expiring.
@ -109,10 +129,24 @@ public abstract class RegistryConfig {
* @see google.registry.model.registry.label.ReservedList * @see google.registry.model.registry.label.ReservedList
* @see google.registry.model.registry.label.PremiumList * @see google.registry.model.registry.label.PremiumList
*/ */
public abstract Duration getDomainLabelListCacheDuration(); public static Duration getDomainLabelListCacheDuration() {
switch (RegistryEnvironment.get()) {
case UNITTEST:
return Duration.ZERO;
default:
return Duration.standardHours(1);
}
}
/** Returns the amount of time a singleton should be cached in persist mode, before expiring. */ /** Returns the amount of time a singleton should be cached in persist mode, before expiring. */
public abstract Duration getSingletonCachePersistDuration(); public static Duration getSingletonCachePersistDuration() {
switch (RegistryEnvironment.get()) {
case UNITTEST:
return Duration.ZERO;
default:
return Duration.standardDays(365);
}
}
/** /**
* Returns the header text at the top of the reserved terms exported list. * Returns the header text at the top of the reserved terms exported list.
@ -121,20 +155,6 @@ public abstract class RegistryConfig {
*/ */
public abstract String getReservedTermsExportDisclaimer(); public abstract String getReservedTermsExportDisclaimer();
/**
* Returns a display name that is used on outgoing emails sent by Nomulus.
*
* @see google.registry.util.SendEmailUtils
*/
public abstract String getGoogleAppsAdminEmailDisplayName();
/**
* Returns the email address that outgoing emails from the app are sent from.
*
* @see google.registry.util.SendEmailUtils
*/
public abstract String getGoogleAppsSendFromEmailAddress();
/** /**
* Returns default WHOIS server to use when {@code Registrar#getWhoisServer()} is {@code null}. * Returns default WHOIS server to use when {@code Registrar#getWhoisServer()} is {@code null}.
* *

View file

@ -28,6 +28,7 @@ import javax.annotation.concurrent.ThreadSafe;
* passing the {@link RegistryEnvironment} as a single parameter. * passing the {@link RegistryEnvironment} as a single parameter.
*/ */
@ThreadSafe @ThreadSafe
@Deprecated // will be replaced by YAML config; see b/33386530 for details
public final class RegistryConfigLoader { public final class RegistryConfigLoader {
public static final String REGISTRY_CONFIG_PROPERTY = "google.registry.config"; public static final String REGISTRY_CONFIG_PROPERTY = "google.registry.config";

View file

@ -72,14 +72,19 @@ public enum RegistryEnvironment {
/** Globally override registry configuration from within a unit test. */ /** Globally override registry configuration from within a unit test. */
@VisibleForTesting @VisibleForTesting
@Deprecated
public static void overrideConfigurationForTesting(@Nullable RegistryConfig newConfig) { public static void overrideConfigurationForTesting(@Nullable RegistryConfig newConfig) {
configOverride = newConfig; configOverride = newConfig;
} }
@Nullable @Nullable
@Deprecated
private static RegistryConfig configOverride; private static RegistryConfig configOverride;
@Deprecated
private static final RegistryConfig testingConfig = new TestRegistryConfig(); private static final RegistryConfig testingConfig = new TestRegistryConfig();
@Deprecated
private final RegistryConfig config = RegistryConfigLoader.load(this); private final RegistryConfig config = RegistryConfigLoader.load(this);
/** System property for configuring which environment we should use. */ /** System property for configuring which environment we should use. */

View file

@ -29,21 +29,6 @@ public class TestRegistryConfig extends RegistryConfig {
public TestRegistryConfig() {} public TestRegistryConfig() {}
@Override
public Duration getCommitLogDatastoreRetention() {
return Duration.standardDays(30);
}
@Override
public String getSnapshotsBucket() {
return RegistryConfig.getProjectId() + "-snapshots";
}
@Override
public boolean getTmchCaTestingMode() {
return true;
}
@Override @Override
public Optional<String> getECatcherAddress() { public Optional<String> getECatcherAddress() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -54,38 +39,11 @@ public class TestRegistryConfig extends RegistryConfig {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override
public Duration getSingletonCacheRefreshDuration() {
// All cache durations are set to zero so that unit tests can update and then retrieve data
// immediately without failure.
return Duration.ZERO;
}
@Override
public Duration getDomainLabelListCacheDuration() {
return Duration.ZERO;
}
@Override
public Duration getSingletonCachePersistDuration() {
return Duration.ZERO;
}
@Override @Override
public String getReservedTermsExportDisclaimer() { public String getReservedTermsExportDisclaimer() {
return "This is a disclaimer.\n"; return "This is a disclaimer.\n";
} }
@Override
public String getGoogleAppsAdminEmailDisplayName() {
return "Testing Nomulus";
}
@Override
public String getGoogleAppsSendFromEmailAddress() {
return "noreply@testing.example";
}
@Override @Override
public String getRegistrarDefaultWhoisServer() { public String getRegistrarDefaultWhoisServer() {
return "whois.nic.fakewhois.example"; return "whois.nic.fakewhois.example";

View file

@ -21,7 +21,7 @@ import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_OK;
import com.google.common.net.MediaType; import com.google.common.net.MediaType;
import google.registry.config.RegistryEnvironment; import google.registry.config.RegistryConfig;
import google.registry.util.Clock; import google.registry.util.Clock;
import google.registry.util.FormattingLogger; import google.registry.util.FormattingLogger;
import google.registry.util.NonFinalForTesting; import google.registry.util.NonFinalForTesting;
@ -44,8 +44,6 @@ import javax.servlet.http.HttpServletResponse;
*/ */
public class ExportSnapshotServlet extends HttpServlet { public class ExportSnapshotServlet extends HttpServlet {
private static final RegistryEnvironment ENVIRONMENT = RegistryEnvironment.get();
/** Queue to use for enqueuing the task that will actually launch the backup. */ /** Queue to use for enqueuing the task that will actually launch the backup. */
static final String QUEUE = "export-snapshot"; // See queue.xml. static final String QUEUE = "export-snapshot"; // See queue.xml.
@ -71,7 +69,7 @@ public class ExportSnapshotServlet extends HttpServlet {
backupService.launchNewBackup( backupService.launchNewBackup(
QUEUE, QUEUE,
snapshotName, snapshotName,
ENVIRONMENT.config().getSnapshotsBucket(), RegistryConfig.getSnapshotsBucket(),
ExportConstants.getBackupKinds()); ExportConstants.getBackupKinds());
// Enqueue a poll task to monitor the backup and load reporting-related kinds into bigquery. // Enqueue a poll task to monitor the backup and load reporting-related kinds into bigquery.
checkSnapshotServlet.enqueuePollTask(snapshotName, ExportConstants.getReportingKinds()); checkSnapshotServlet.enqueuePollTask(snapshotName, ExportConstants.getReportingKinds());

View file

@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not; import static com.google.common.base.Predicates.not;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
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.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION; import static google.registry.model.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION;
@ -49,7 +50,6 @@ import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Mapify; import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.annotation.OnSave; import com.googlecode.objectify.annotation.OnSave;
import com.googlecode.objectify.annotation.Parent; import com.googlecode.objectify.annotation.Parent;
import google.registry.config.RegistryEnvironment;
import google.registry.model.Buildable; import google.registry.model.Buildable;
import google.registry.model.CreateAutoTimestamp; import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
@ -211,24 +211,23 @@ public class Registry extends ImmutableObject implements Buildable {
} }
/** A cache that loads the {@link Registry} for a given tld. */ /** A cache that loads the {@link Registry} for a given tld. */
private static final LoadingCache<String, Optional<Registry>> CACHE = CacheBuilder.newBuilder() private static final LoadingCache<String, Optional<Registry>> CACHE =
.expireAfterWrite( CacheBuilder.newBuilder()
RegistryEnvironment.get().config().getSingletonCacheRefreshDuration().getMillis(), .expireAfterWrite(getSingletonCacheRefreshDuration().getMillis(), MILLISECONDS)
MILLISECONDS) .build(new CacheLoader<String, Optional<Registry>>() {
.build(new CacheLoader<String, Optional<Registry>>() { @Override
@Override public Optional<Registry> load(final String tld) {
public Optional<Registry> load(final String tld) { // Enter a transactionless context briefly; we don't want to enroll every TLD in a
// Enter a transactionless context briefly; we don't want to enroll every TLD in a // transaction that might be wrapping this call, and memcached results are fine here
// transaction that might be wrapping this call, and memcached results are fine here. return Optional.fromNullable(ofy().doTransactionless(new Work<Registry>() {
return Optional.fromNullable(ofy().doTransactionless(new Work<Registry>() { @Override
@Override public Registry run() {
public Registry run() { return ofy()
return ofy() .load()
.load() .key(Key.create(getCrossTldKey(), Registry.class, tld))
.key(Key.create(getCrossTldKey(), Registry.class, tld)) .now();
.now(); }}));
}})); }});
}});
/** Returns the registry for a given TLD, throwing if none exists. */ /** Returns the registry for a given TLD, throwing if none exists. */
public static Registry get(String tld) { public static Registry get(String tld) {

View file

@ -19,6 +19,7 @@ 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;
import static com.google.common.collect.Iterables.partition; import static com.google.common.collect.Iterables.partition;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.model.ofy.ObjectifyService.allocateId; import static google.registry.model.ofy.ObjectifyService.allocateId;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
@ -48,7 +49,6 @@ import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.OnLoad; import com.googlecode.objectify.annotation.OnLoad;
import com.googlecode.objectify.annotation.Parent; import com.googlecode.objectify.annotation.Parent;
import com.googlecode.objectify.cmd.Query; import com.googlecode.objectify.cmd.Query;
import google.registry.config.RegistryEnvironment;
import google.registry.model.Buildable; import google.registry.model.Buildable;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.annotations.ReportedOn; import google.registry.model.annotations.ReportedOn;
@ -97,24 +97,22 @@ public final class PremiumList extends BaseDomainLabelList<Money, PremiumList.Pr
} }
} }
private static LoadingCache<String, PremiumList> cache = CacheBuilder private static LoadingCache<String, PremiumList> cache =
.newBuilder() CacheBuilder.newBuilder()
.expireAfterWrite( .expireAfterWrite(getDomainLabelListCacheDuration().getMillis(), MILLISECONDS)
RegistryEnvironment.get().config().getDomainLabelListCacheDuration().getMillis(), .build(new CacheLoader<String, PremiumList>() {
MILLISECONDS)
.build(new CacheLoader<String, PremiumList>() {
@Override
public PremiumList load(final String listName) {
return ofy().doTransactionless(new Work<PremiumList>() {
@Override @Override
public PremiumList run() { public PremiumList load(final String listName) {
return ofy().load() return ofy().doTransactionless(new Work<PremiumList>() {
.type(PremiumList.class) @Override
.parent(getCrossTldKey()) public PremiumList run() {
.id(listName) return ofy().load()
.now(); .type(PremiumList.class)
.parent(getCrossTldKey())
.id(listName)
.now();
}});
}}); }});
}});
/** /**
* Gets the premium price for the specified label on the specified tld, or returns Optional.absent * Gets the premium price for the specified label on the specified tld, or returns Optional.absent

View file

@ -16,6 +16,7 @@ package google.registry.model.registry.label;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
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.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION; import static google.registry.model.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION;
@ -40,7 +41,6 @@ import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Mapify; import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.mapper.Mapper; import com.googlecode.objectify.mapper.Mapper;
import google.registry.config.RegistryEnvironment;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -221,16 +221,20 @@ public final class ReservedList
return builder.build(); return builder.build();
} }
private static LoadingCache<String, ReservedList> cache = CacheBuilder private static LoadingCache<String, ReservedList> cache =
.newBuilder() CacheBuilder.newBuilder()
.expireAfterWrite( .expireAfterWrite(getDomainLabelListCacheDuration().getMillis(), MILLISECONDS)
RegistryEnvironment.get().config().getDomainLabelListCacheDuration().getMillis(), .build(
MILLISECONDS) new CacheLoader<String, ReservedList>() {
.build(new CacheLoader<String, ReservedList>() { @Override
@Override public ReservedList load(String listName) {
public ReservedList load(String listName) { return ofy()
return ofy().load().type(ReservedList.class).parent(getCrossTldKey()).id(listName).now(); .load()
}}); .type(ReservedList.class)
.parent(getCrossTldKey())
.id(listName)
.now();
}});
/** /**
* Gets the {@link ReservationType} of a label in a single ReservedList, or returns an absent * Gets the {@link ReservationType} of a label in a single ReservedList, or returns an absent

View file

@ -15,13 +15,13 @@
package google.registry.model.translators; package google.registry.model.translators;
import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.MoreObjects.firstNonNull;
import static google.registry.config.RegistryConfig.getCommitLogDatastoreRetention;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
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 com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
import google.registry.config.RegistryEnvironment;
import google.registry.model.ofy.CommitLogManifest; import google.registry.model.ofy.CommitLogManifest;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -47,8 +47,6 @@ import org.joda.time.DateTime;
public final class CommitLogRevisionsTranslatorFactory public final class CommitLogRevisionsTranslatorFactory
extends ImmutableSortedMapTranslatorFactory<DateTime, Key<CommitLogManifest>> { extends ImmutableSortedMapTranslatorFactory<DateTime, Key<CommitLogManifest>> {
private static final RegistryEnvironment ENVIRONMENT = RegistryEnvironment.get();
/** /**
* Add a reference to the current commit log to the resource's revisions map. * Add a reference to the current commit log to the resource's revisions map.
* *
@ -65,7 +63,7 @@ public final class CommitLogRevisionsTranslatorFactory
ImmutableSortedMap<DateTime, Key<CommitLogManifest>> transformBeforeSave( ImmutableSortedMap<DateTime, Key<CommitLogManifest>> transformBeforeSave(
ImmutableSortedMap<DateTime, Key<CommitLogManifest>> revisions) { ImmutableSortedMap<DateTime, Key<CommitLogManifest>> revisions) {
DateTime now = ofy().getTransactionTime(); DateTime now = ofy().getTransactionTime();
DateTime threshold = now.minus(ENVIRONMENT.config().getCommitLogDatastoreRetention()); DateTime threshold = now.minus(getCommitLogDatastoreRetention());
DateTime preThresholdTime = firstNonNull(revisions.floorKey(threshold), START_OF_TIME); DateTime preThresholdTime = firstNonNull(revisions.floorKey(threshold), START_OF_TIME);
return new ImmutableSortedMap.Builder<DateTime, Key<CommitLogManifest>>(Ordering.natural()) return new ImmutableSortedMap.Builder<DateTime, Key<CommitLogManifest>>(Ordering.natural())
.putAll(revisions.subMap(preThresholdTime, true, now.withTimeAtStartOfDay(), false)) .putAll(revisions.subMap(preThresholdTime, true, now.withTimeAtStartOfDay(), false))

View file

@ -14,6 +14,8 @@
package google.registry.tmch; package google.registry.tmch;
import static google.registry.config.RegistryConfig.getSingletonCachePersistDuration;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
import static google.registry.util.ResourceUtils.readResourceUtf8; import static google.registry.util.ResourceUtils.readResourceUtf8;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
@ -21,7 +23,6 @@ import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
import google.registry.config.ConfigModule.Config; import google.registry.config.ConfigModule.Config;
import google.registry.config.RegistryEnvironment;
import google.registry.model.tmch.TmchCrl; import google.registry.model.tmch.TmchCrl;
import google.registry.util.Clock; import google.registry.util.Clock;
import google.registry.util.NonFinalForTesting; import google.registry.util.NonFinalForTesting;
@ -46,8 +47,6 @@ import javax.inject.Inject;
@ThreadSafe @ThreadSafe
public final class TmchCertificateAuthority { public final class TmchCertificateAuthority {
private static final RegistryEnvironment ENVIRONMENT = RegistryEnvironment.get();
private static final String ROOT_CRT_FILE = "icann-tmch.crt"; private static final String ROOT_CRT_FILE = "icann-tmch.crt";
private static final String TEST_ROOT_CRT_FILE = "icann-tmch-test.crt"; private static final String TEST_ROOT_CRT_FILE = "icann-tmch-test.crt";
private static final String CRL_FILE = "icann-tmch.crl"; private static final String CRL_FILE = "icann-tmch.crl";
@ -71,8 +70,7 @@ public final class TmchCertificateAuthority {
*/ */
private static final LoadingCache<Boolean, X509CRL> CRL_CACHE = private static final LoadingCache<Boolean, X509CRL> CRL_CACHE =
CacheBuilder.newBuilder() CacheBuilder.newBuilder()
.expireAfterWrite( .expireAfterWrite(getSingletonCacheRefreshDuration().getMillis(), MILLISECONDS)
ENVIRONMENT.config().getSingletonCacheRefreshDuration().getMillis(), MILLISECONDS)
.build( .build(
new CacheLoader<Boolean, X509CRL>() { new CacheLoader<Boolean, X509CRL>() {
@Override @Override
@ -102,8 +100,7 @@ public final class TmchCertificateAuthority {
/** A cached function that loads the CRT from a jar resource. */ /** A cached function that loads the CRT from a jar resource. */
private static final LoadingCache<Boolean, X509Certificate> ROOT_CACHE = private static final LoadingCache<Boolean, X509Certificate> ROOT_CACHE =
CacheBuilder.newBuilder() CacheBuilder.newBuilder()
.expireAfterWrite( .expireAfterWrite(getSingletonCachePersistDuration().getMillis(), MILLISECONDS)
ENVIRONMENT.config().getSingletonCachePersistDuration().getMillis(), MILLISECONDS)
.build( .build(
new CacheLoader<Boolean, X509Certificate>() { new CacheLoader<Boolean, X509Certificate>() {
@Override @Override

View file

@ -71,9 +71,10 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
private static final String ARGS_PARAM = "args"; private static final String ARGS_PARAM = "args";
@Inject HttpServletRequest request; @Inject HttpServletRequest request;
@Inject SessionUtils sessionUtils;
@Inject JsonActionRunner jsonActionRunner; @Inject JsonActionRunner jsonActionRunner;
@Inject Registrar initialRegistrar; @Inject Registrar initialRegistrar;
@Inject SendEmailUtils sendEmailUtils;
@Inject SessionUtils sessionUtils;
@Inject @Config("registrarChangesNotificationEmailAddresses") ImmutableList<String> @Inject @Config("registrarChangesNotificationEmailAddresses") ImmutableList<String>
registrarChangesNotificationEmailAddresses; registrarChangesNotificationEmailAddresses;
@Inject RegistrarSettingsAction() {} @Inject RegistrarSettingsAction() {}
@ -285,7 +286,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
} }
SyncRegistrarsSheetAction.enqueueBackendTask(); SyncRegistrarsSheetAction.enqueueBackendTask();
if (!registrarChangesNotificationEmailAddresses.isEmpty()) { if (!registrarChangesNotificationEmailAddresses.isEmpty()) {
SendEmailUtils.sendEmail( sendEmailUtils.sendEmail(
registrarChangesNotificationEmailAddresses, registrarChangesNotificationEmailAddresses,
String.format("Registrar %s updated", registrarName), String.format("Registrar %s updated", registrarName),
"The following changes were made to the registrar:\n" "The following changes were made to the registrar:\n"

View file

@ -15,18 +15,17 @@
package google.registry.util; package google.registry.util;
import static com.google.common.base.Suppliers.memoizeWithExpiration; import static com.google.common.base.Suppliers.memoizeWithExpiration;
import static google.registry.config.RegistryConfig.getSingletonCachePersistDuration;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.joda.time.Duration.ZERO; import static org.joda.time.Duration.ZERO;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import google.registry.config.RegistryEnvironment;
import org.joda.time.Duration; import org.joda.time.Duration;
/** Utility methods related to caching. */ /** Utility methods related to caching. */
public class CacheUtils { public class CacheUtils {
private static final RegistryEnvironment ENVIRONMENT = RegistryEnvironment.get();
/** /**
* Memoize a supplier, with a short expiration specified in the environment config. * Memoize a supplier, with a short expiration specified in the environment config.
* *
@ -34,7 +33,7 @@ public class CacheUtils {
* lists downloaded from the TMCH get updated in datastore and the caches need to be refreshed.) * lists downloaded from the TMCH get updated in datastore and the caches need to be refreshed.)
*/ */
public static <T> Supplier<T> memoizeWithShortExpiration(Supplier<T> original) { public static <T> Supplier<T> memoizeWithShortExpiration(Supplier<T> original) {
return memoizeForDuration(original, ENVIRONMENT.config().getSingletonCacheRefreshDuration()); return memoizeForDuration(original, getSingletonCacheRefreshDuration());
} }
/** /**
@ -45,7 +44,7 @@ public class CacheUtils {
* while allowing the production config to set the expiration to forever. * while allowing the production config to set the expiration to forever.
*/ */
public static <T> Supplier<T> memoizeWithLongExpiration(Supplier<T> original) { public static <T> Supplier<T> memoizeWithLongExpiration(Supplier<T> original) {
return memoizeForDuration(original, ENVIRONMENT.config().getSingletonCachePersistDuration()); return memoizeForDuration(original, getSingletonCachePersistDuration());
} }
/** Memoize a supplier, with a given expiration. */ /** Memoize a supplier, with a given expiration. */

View file

@ -20,10 +20,9 @@ import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Predicates; 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 google.registry.config.ConfigModule.Config;
import google.registry.config.RegistryConfig;
import google.registry.config.RegistryEnvironment;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import javax.mail.Message; import javax.mail.Message;
import javax.mail.internet.AddressException; import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
@ -33,30 +32,31 @@ import javax.mail.internet.InternetAddress;
*/ */
public class SendEmailUtils { public class SendEmailUtils {
private static final RegistryConfig CONFIG = RegistryEnvironment.get().config();
private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();
private final String googleAppsSendFromEmailAddress;
private final String googleAppsAdminEmailDisplayName;
@Inject
public SendEmailUtils(
@Config("googleAppsSendFromEmailAddress") String googleAppsSendFromEmailAddress,
@Config("googleAppsAdminEmailDisplayName") String googleAppsAdminEmailDisplayName) {
this.googleAppsSendFromEmailAddress = googleAppsSendFromEmailAddress;
this.googleAppsAdminEmailDisplayName = googleAppsAdminEmailDisplayName;
}
@NonFinalForTesting @NonFinalForTesting
private static SendEmailService emailService = new SendEmailService(); private static SendEmailService emailService = new SendEmailService();
/** /**
* Sends an email from Nomulus to the specified recipient. Returns true iff sending was * Sends an email from Nomulus to the specified recipient(s). Returns true iff sending was
* successful. * successful.
*/ */
public static boolean sendEmail(String address, String subject, String body) { public boolean sendEmail(Iterable<String> addresses, final String subject, String body) {
return sendEmail(ImmutableList.of(address), subject, body);
}
/**
* Sends an email from Nomulus to the specified recipients. Returns true iff sending was
* successful.
*/
public static boolean sendEmail(Iterable<String> addresses, final String subject, String body) {
try { try {
Message msg = emailService.createMessage(); Message msg = emailService.createMessage();
msg.setFrom(new InternetAddress( msg.setFrom(
CONFIG.getGoogleAppsSendFromEmailAddress(), new InternetAddress(googleAppsSendFromEmailAddress, googleAppsAdminEmailDisplayName));
CONFIG.getGoogleAppsAdminEmailDisplayName()));
List<InternetAddress> emails = FluentIterable List<InternetAddress> emails = FluentIterable
.from(addresses) .from(addresses)
.transform(new Function<String, InternetAddress>() { .transform(new Function<String, InternetAddress>() {

View file

@ -14,8 +14,6 @@
package google.registry.config; package google.registry.config;
import static com.google.common.truth.Truth.assertThat;
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;
@ -28,14 +26,4 @@ public class RegistryEnvironmentTest {
public void testGet() throws Exception { public void testGet() throws Exception {
RegistryEnvironment.get(); RegistryEnvironment.get();
} }
@Test
public void testOverride() throws Exception {
RegistryEnvironment.overrideConfigurationForTesting(new TestRegistryConfig() {
@Override
public String getSnapshotsBucket() {
return "black velvet";
}});
assertThat(RegistryEnvironment.get().config().getSnapshotsBucket()).isEqualTo("black velvet");
}
} }

View file

@ -19,10 +19,8 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import google.registry.config.TestRegistryConfig;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import google.registry.testing.RegistryConfigRule;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import javax.servlet.ServletConfig; import javax.servlet.ServletConfig;
@ -43,12 +41,6 @@ public class ExportSnapshotServletTest {
@Rule @Rule
public final InjectRule inject = new InjectRule(); public final InjectRule inject = new InjectRule();
@Rule
public final RegistryConfigRule configRule = new RegistryConfigRule(new TestRegistryConfig() {
@Override public String getSnapshotsBucket() {
return "Bucket-Id";
}});
@Mock @Mock
private HttpServletRequest req; private HttpServletRequest req;
@ -87,7 +79,7 @@ public class ExportSnapshotServletTest {
verify(backupService).launchNewBackup( verify(backupService).launchNewBackup(
ExportSnapshotServlet.QUEUE, ExportSnapshotServlet.QUEUE,
"auto_snapshot_20140801_010203", "auto_snapshot_20140801_010203",
"Bucket-Id", "domain-registry-snapshots",
ExportConstants.getBackupKinds()); ExportConstants.getBackupKinds());
verify(checkSnapshotServlet) verify(checkSnapshotServlet)
.enqueuePollTask("auto_snapshot_20140801_010203", ExportConstants.getReportingKinds()); .enqueuePollTask("auto_snapshot_20140801_010203", ExportConstants.getReportingKinds());

View file

@ -117,7 +117,6 @@ import google.registry.model.registry.label.ReservedList;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.model.smd.SignedMarkRevocationList; import google.registry.model.smd.SignedMarkRevocationList;
import google.registry.testing.DatastoreHelper; import google.registry.testing.DatastoreHelper;
import google.registry.testing.RegistryConfigRule;
import google.registry.tmch.TmchCertificateAuthority; import google.registry.tmch.TmchCertificateAuthority;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
@ -128,7 +127,6 @@ import org.joda.time.DateTime;
import org.joda.time.Interval; import org.joda.time.Interval;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
/** Unit tests for {@link DomainApplicationCreateFlow}. */ /** Unit tests for {@link DomainApplicationCreateFlow}. */
@ -137,9 +135,6 @@ public class DomainApplicationCreateFlowTest
private static final String CLAIMS_KEY = "2013041500/2/6/9/rJ1NrDO92vDsAzf7EQzgjX4R0000000001"; private static final String CLAIMS_KEY = "2013041500/2/6/9/rJ1NrDO92vDsAzf7EQzgjX4R0000000001";
@Rule
public final RegistryConfigRule configRule = new RegistryConfigRule();
/** This is the id of the SMD stored in "domain_create_sunrise_encoded_signed_mark.xml". */ /** This is the id of the SMD stored in "domain_create_sunrise_encoded_signed_mark.xml". */
public static final String SMD_ID = "0000001761376042759136-65535"; public static final String SMD_ID = "0000001761376042759136-65535";

View file

@ -26,7 +26,6 @@ import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.Work; import com.googlecode.objectify.Work;
import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Entity;
import google.registry.config.TestRegistryConfig;
import google.registry.model.common.CrossTldSingleton; import google.registry.model.common.CrossTldSingleton;
import google.registry.model.ofy.CommitLogManifest; import google.registry.model.ofy.CommitLogManifest;
import google.registry.model.ofy.Ofy; import google.registry.model.ofy.Ofy;
@ -34,10 +33,8 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.ExceptionRule; import google.registry.testing.ExceptionRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import google.registry.testing.RegistryConfigRule;
import java.util.List; import java.util.List;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -66,15 +63,6 @@ public class CommitLogRevisionsTranslatorFactoryTest {
@Rule @Rule
public final ExceptionRule thrown = new ExceptionRule(); public final ExceptionRule thrown = new ExceptionRule();
@Rule
public final RegistryConfigRule configRule = new RegistryConfigRule(
new TestRegistryConfig() {
@Override
public Duration getCommitLogDatastoreRetention() {
return Duration.standardDays(30);
}
});
private final FakeClock clock = new FakeClock(START_TIME); private final FakeClock clock = new FakeClock(START_TIME);
@Before @Before

View file

@ -22,6 +22,7 @@ import google.registry.config.RegistryEnvironment;
import org.junit.rules.ExternalResource; import org.junit.rules.ExternalResource;
/** JUnit Rule for overriding Nomulus configuration values. */ /** JUnit Rule for overriding Nomulus configuration values. */
@Deprecated // is obsoleted by YAML config; see b/33386530 for details
public final class RegistryConfigRule extends ExternalResource { public final class RegistryConfigRule extends ExternalResource {
private final Optional<RegistryConfig> override; private final Optional<RegistryConfig> override;

View file

@ -14,6 +14,8 @@
package google.registry.ui.server.registrar; package google.registry.ui.server.registrar;
import static google.registry.config.ConfigModule.LocalTestConfig.GOOGLE_APPS_ADMIN_EMAIL_DISPLAY_NAME;
import static google.registry.config.ConfigModule.LocalTestConfig.GOOGLE_APPS_SEND_FROM_EMAIL_ADDRESS;
import static google.registry.security.JsonHttpTestUtils.createJsonPayload; import static google.registry.security.JsonHttpTestUtils.createJsonPayload;
import static google.registry.security.JsonHttpTestUtils.createJsonResponseSupplier; import static google.registry.security.JsonHttpTestUtils.createJsonResponseSupplier;
import static google.registry.security.XsrfTokenManager.generateToken; import static google.registry.security.XsrfTokenManager.generateToken;
@ -100,6 +102,9 @@ public class RegistrarSettingsActionTestCase {
ImmutableMap.<String, Object>of(), new JsonResponse(new ResponseImpl(rsp))); ImmutableMap.<String, Object>of(), new JsonResponse(new ResponseImpl(rsp)));
action.registrarChangesNotificationEmailAddresses = ImmutableList.of( action.registrarChangesNotificationEmailAddresses = ImmutableList.of(
"notification@test.example", "notification2@test.example"); "notification@test.example", "notification2@test.example");
action.sendEmailUtils =
new SendEmailUtils(
GOOGLE_APPS_SEND_FROM_EMAIL_ADDRESS, GOOGLE_APPS_ADMIN_EMAIL_DISPLAY_NAME);
inject.setStaticField(Ofy.class, "clock", clock); inject.setStaticField(Ofy.class, "clock", clock);
inject.setStaticField(SendEmailUtils.class, "emailService", emailService); inject.setStaticField(SendEmailUtils.class, "emailService", emailService);
inject.setStaticField(SyncRegistrarsSheetAction.class, "modulesService", modulesService); inject.setStaticField(SyncRegistrarsSheetAction.class, "modulesService", modulesService);

View file

@ -11,6 +11,7 @@ java_library(
name = "util", name = "util",
srcs = glob(["*.java"]), srcs = glob(["*.java"]),
deps = [ deps = [
"//java/google/registry/config",
"//java/google/registry/util", "//java/google/registry/util",
"//javatests/google/registry/testing", "//javatests/google/registry/testing",
"@com_google_appengine_api_1_0_sdk", "@com_google_appengine_api_1_0_sdk",

View file

@ -15,7 +15,6 @@
package google.registry.util; package google.registry.util;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.util.SendEmailUtils.sendEmail;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
@ -23,6 +22,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.config.ConfigModule.LocalTestConfig;
import google.registry.testing.ExceptionRule; import google.registry.testing.ExceptionRule;
import google.registry.testing.InjectRule; import google.registry.testing.InjectRule;
import java.util.Properties; import java.util.Properties;
@ -53,20 +53,26 @@ public class SendEmailUtilsTest {
private SendEmailService emailService; private SendEmailService emailService;
private Message message; private Message message;
private SendEmailUtils sendEmailUtils;
@Before @Before
public void init() throws Exception { public void init() throws Exception {
inject.setStaticField(SendEmailUtils.class, "emailService", emailService); inject.setStaticField(SendEmailUtils.class, "emailService", emailService);
message = new MimeMessage(Session.getDefaultInstance(new Properties(), null)); message = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
when(emailService.createMessage()).thenReturn(message); when(emailService.createMessage()).thenReturn(message);
sendEmailUtils = new SendEmailUtils(
LocalTestConfig.GOOGLE_APPS_SEND_FROM_EMAIL_ADDRESS,
LocalTestConfig.GOOGLE_APPS_ADMIN_EMAIL_DISPLAY_NAME);
} }
@Test @Test
public void testSuccess_sendToOneAddress() throws Exception { public void testSuccess_sendToOneAddress() throws Exception {
assertThat(sendEmail( assertThat(
"johnny@fakesite.tld", sendEmailUtils.sendEmail(
"Welcome to the Internet", ImmutableList.of("johnny@fakesite.tld"),
"It is a dark and scary place.")).isTrue(); "Welcome to the Internet",
"It is a dark and scary place."))
.isTrue();
verifyMessageSent(); verifyMessageSent();
assertThat(message.getRecipients(RecipientType.TO)).asList() assertThat(message.getRecipients(RecipientType.TO)).asList()
.containsExactly(new InternetAddress("johnny@fakesite.tld")); .containsExactly(new InternetAddress("johnny@fakesite.tld"));
@ -76,10 +82,12 @@ public class SendEmailUtilsTest {
@Test @Test
public void testSuccess_sendToMultipleAddresses() throws Exception { public void testSuccess_sendToMultipleAddresses() throws Exception {
assertThat(sendEmail( assertThat(
ImmutableList.of("foo@example.com", "bar@example.com"), sendEmailUtils.sendEmail(
"Welcome to the Internet", ImmutableList.of("foo@example.com", "bar@example.com"),
"It is a dark and scary place.")).isTrue(); "Welcome to the Internet",
"It is a dark and scary place."))
.isTrue();
verifyMessageSent(); verifyMessageSent();
assertThat(message.getAllRecipients()).asList().containsExactly( assertThat(message.getAllRecipients()).asList().containsExactly(
new InternetAddress("foo@example.com"), new InternetAddress("foo@example.com"),
@ -88,10 +96,12 @@ public class SendEmailUtilsTest {
@Test @Test
public void testSuccess_ignoresMalformedEmailAddress() throws Exception { public void testSuccess_ignoresMalformedEmailAddress() throws Exception {
assertThat(sendEmail( assertThat(
ImmutableList.of("foo@example.com", "1iñvalidemail"), sendEmailUtils.sendEmail(
"Welcome to the Internet", ImmutableList.of("foo@example.com", "1iñvalidemail"),
"It is a dark and scary place.")).isTrue(); "Welcome to the Internet",
"It is a dark and scary place."))
.isTrue();
verifyMessageSent(); verifyMessageSent();
assertThat(message.getAllRecipients()).asList() assertThat(message.getAllRecipients()).asList()
.containsExactly(new InternetAddress("foo@example.com")); .containsExactly(new InternetAddress("foo@example.com"));
@ -99,22 +109,27 @@ public class SendEmailUtilsTest {
@Test @Test
public void testFailure_onlyGivenMalformedAddress() throws Exception { public void testFailure_onlyGivenMalformedAddress() throws Exception {
assertThat(sendEmail( assertThat(
ImmutableList.of("1iñvalidemail"), sendEmailUtils.sendEmail(
"Welcome to the Internet", ImmutableList.of("1iñvalidemail"),
"It is a dark and scary place.")).isFalse(); "Welcome to the Internet",
"It is a dark and scary place."))
.isFalse();
verify(emailService, never()).sendMessage(any(Message.class)); verify(emailService, never()).sendMessage(any(Message.class));
} }
@Test @Test
public void testFailure_exceptionThrownDuringSend() throws Exception { public void testFailure_exceptionThrownDuringSend() throws Exception {
doThrow(new MessagingException()).when(emailService).sendMessage(any(Message.class)); doThrow(new MessagingException()).when(emailService).sendMessage(any(Message.class));
assertThat(sendEmail( assertThat(
ImmutableList.of("foo@example.com"), sendEmailUtils.sendEmail(
"Welcome to the Internet", ImmutableList.of("foo@example.com"),
"It is a dark and scary place.")).isFalse(); "Welcome to the Internet",
"It is a dark and scary place."))
.isFalse();
verifyMessageSent(); verifyMessageSent();
assertThat(message.getAllRecipients()).asList() assertThat(message.getAllRecipients())
.asList()
.containsExactly(new InternetAddress("foo@example.com")); .containsExactly(new InternetAddress("foo@example.com"));
} }