Clean up some code quality issues

This removes some qualifiers that aren't necessary (e.g. public/abstract on interfaces, private on enum constructors, final on private methods, static on nested interfaces/enums), uses Java 8 lambdas and features where that's an improvement

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=177182945
This commit is contained in:
mcilwain 2017-11-28 10:35:57 -08:00 committed by jianglai
parent 0935ba6450
commit e2db3f914e
109 changed files with 286 additions and 379 deletions

View file

@ -47,7 +47,7 @@ public final class BackupModule {
/** Dagger qualifier for backups. */ /** Dagger qualifier for backups. */
@Qualifier @Qualifier
@Documented @Documented
public static @interface Backups {} public @interface Backups {}
/** Number of threads in the threaded executor. */ /** Number of threads in the threaded executor. */
private static final int NUM_THREADS = 10; private static final int NUM_THREADS = 10;

View file

@ -536,7 +536,7 @@ public class DeleteContactsAndHostsAction implements Runnable {
private final String counterFormat; private final String counterFormat;
private final OperationResult operationResult; private final OperationResult operationResult;
private Type(String counterFormat, OperationResult operationResult) { Type(String counterFormat, OperationResult operationResult) {
this.counterFormat = counterFormat; this.counterFormat = counterFormat;
this.operationResult = operationResult; this.operationResult = operationResult;
} }

View file

@ -138,7 +138,7 @@ public class DeleteProberDataAction implements Runnable {
if (proberRoidSuffixes.contains(roidSuffix)) { if (proberRoidSuffixes.contains(roidSuffix)) {
deleteDomain(key); deleteDomain(key);
} else { } else {
getContext().incrementCounter(String.format("skipped, non-prober data")); getContext().incrementCounter("skipped, non-prober data");
} }
} catch (Throwable t) { } catch (Throwable t) {
logger.severefmt(t, "Error while deleting prober data for key %s", key); logger.severefmt(t, "Error while deleting prober data for key %s", key);

View file

@ -220,11 +220,10 @@ public class MapreduceEntityCleanupAction implements Runnable {
errorCount++; errorCount++;
} }
logger.infofmt("%s: %s", actualJobId, error.orElse("deletion requested")); logger.infofmt("%s: %s", actualJobId, error.orElse("deletion requested"));
if (payloadChunkBuilder.isPresent()) { payloadChunkBuilder.ifPresent(
payloadChunkBuilder stringBuilder ->
.get() stringBuilder.append(
.append(String.format("%s: %s\n", actualJobId, error.orElse("deletion requested"))); String.format("%s: %s\n", actualJobId, error.orElse("deletion requested"))));
}
} }
logger.infofmt( logger.infofmt(
"successfully requested async deletion of %s job(s); errors received on %s", "successfully requested async deletion of %s job(s); errors received on %s",

View file

@ -136,10 +136,9 @@ public class VerifyEntityIntegrityAction implements Runnable {
getInputs()))); getInputs())));
} }
private static ImmutableSet<Input<? extends Object>> getInputs() { private static ImmutableSet<Input<?>> getInputs() {
ImmutableSet.Builder<Input<? extends Object>> builder = ImmutableSet.Builder<Input<?>> builder =
new ImmutableSet.Builder<Input<? extends Object>>() new ImmutableSet.Builder<Input<?>>().add(EppResourceInputs.createIndexInput());
.add(EppResourceInputs.createIndexInput());
RESOURCE_CLASSES RESOURCE_CLASSES
.stream() .stream()
.map(clazz -> new DatastoreKeyInput(getKind(clazz), NUM_SHARDS)) .map(clazz -> new DatastoreKeyInput(getKind(clazz), NUM_SHARDS))
@ -153,7 +152,7 @@ public class VerifyEntityIntegrityAction implements Runnable {
* contact), which is used to check {@link ForeignKeyIndex} constraints, and one that is common * contact), which is used to check {@link ForeignKeyIndex} constraints, and one that is common
* for all EppResources, to check {@link EppResourceIndex} constraints. * for all EppResources, to check {@link EppResourceIndex} constraints.
*/ */
private static enum EntityKind { private enum EntityKind {
DOMAIN, DOMAIN,
APPLICATION, APPLICATION,
CONTACT, CONTACT,

View file

@ -56,7 +56,7 @@ public final class RegistryConfig {
@Qualifier @Qualifier
@Retention(RUNTIME) @Retention(RUNTIME)
@Documented @Documented
public static @interface Config { public @interface Config {
String value() default ""; String value() default "";
} }

View file

@ -127,16 +127,19 @@ public final class TldFanoutAction implements Runnable {
excludes); excludes);
Multimap<String, String> flowThruParams = filterKeys(params, not(in(CONTROL_PARAMS))); Multimap<String, String> flowThruParams = filterKeys(params, not(in(CONTROL_PARAMS)));
Queue taskQueue = getQueue(queue); Queue taskQueue = getQueue(queue);
String outputPayload = String.format( StringBuilder outputPayload =
"OK: Launched the following %d tasks in queue %s\n", tlds.size(), queue); new StringBuilder(
String.format("OK: Launched the following %d tasks in queue %s\n", tlds.size(), queue));
for (String tld : tlds) { for (String tld : tlds) {
TaskOptions taskOptions = createTaskOptions(tld, flowThruParams); TaskOptions taskOptions = createTaskOptions(tld, flowThruParams);
TaskHandle taskHandle = taskEnqueuer.enqueue(taskQueue, taskOptions); TaskHandle taskHandle = taskEnqueuer.enqueue(taskQueue, taskOptions);
outputPayload += String.format( outputPayload.append(
"- Task: %s, tld: %s, endpoint: %s\n", taskHandle.getName(), tld, taskOptions.getUrl()); String.format(
"- Task: %s, tld: %s, endpoint: %s\n",
taskHandle.getName(), tld, taskOptions.getUrl()));
} }
response.setContentType(PLAIN_TEXT_UTF_8); response.setContentType(PLAIN_TEXT_UTF_8);
response.setPayload(outputPayload); response.setPayload(outputPayload.toString());
} }
private TaskOptions createTaskOptions(String tld, Multimap<String, String> params) { private TaskOptions createTaskOptions(String tld, Multimap<String, String> params) {

View file

@ -44,15 +44,12 @@ public final class CloudDnsWriterModule {
@Config("projectId") String projectId, @Config("projectId") String projectId,
@Config("cloudDnsRootUrl") Optional<String> rootUrl, @Config("cloudDnsRootUrl") Optional<String> rootUrl,
@Config("cloudDnsServicePath") Optional<String> servicePath) { @Config("cloudDnsServicePath") Optional<String> servicePath) {
Dns.Builder builder = new Dns.Builder(transport, jsonFactory, credential.apply(DnsScopes.all())) Dns.Builder builder =
.setApplicationName(projectId); new Dns.Builder(transport, jsonFactory, credential.apply(DnsScopes.all()))
.setApplicationName(projectId);
if (rootUrl.isPresent()) { rootUrl.ifPresent(builder::setRootUrl);
builder.setRootUrl(rootUrl.get()); servicePath.ifPresent(builder::setServicePath);
}
if (servicePath.isPresent()) {
builder.setServicePath(servicePath.get());
}
return builder.build(); return builder.build();
} }

View file

@ -72,7 +72,7 @@ public final class SyncGroupMembersAction implements Runnable {
final int statusCode; final int statusCode;
final String message; final String message;
private Result(int statusCode, String message) { Result(int statusCode, String message) {
this.statusCode = statusCode; this.statusCode = statusCode;
this.message = message; this.message = message;
} }

View file

@ -122,7 +122,7 @@ public interface FlowComponent {
/** Module to delegate injection of a desired {@link Flow}. */ /** Module to delegate injection of a desired {@link Flow}. */
@Module @Module
static class FlowComponentModule { class FlowComponentModule {
// WARNING: @FlowScope is intentionally omitted here so that we get a fresh Flow instance on // WARNING: @FlowScope is intentionally omitted here so that we get a fresh Flow instance on
// each call to Provider<Flow>.get(), to avoid Flow instance re-use upon transaction retries. // each call to Provider<Flow>.get(), to avoid Flow instance re-use upon transaction retries.
// TODO(b/29874464): fix this in a cleaner way. // TODO(b/29874464): fix this in a cleaner way.

View file

@ -14,6 +14,7 @@
package google.registry.flows; package google.registry.flows;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.io.BaseEncoding.base64; import static com.google.common.io.BaseEncoding.base64;
import static google.registry.xml.XmlTransformer.prettyPrint; import static google.registry.xml.XmlTransformer.prettyPrint;
import static java.util.Collections.EMPTY_LIST; import static java.util.Collections.EMPTY_LIST;
@ -22,6 +23,7 @@ import com.google.common.base.Ascii;
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.Streams;
import google.registry.flows.FlowModule.ClientId; import google.registry.flows.FlowModule.ClientId;
import google.registry.flows.FlowModule.InputXml; import google.registry.flows.FlowModule.InputXml;
import google.registry.flows.annotations.ReportingSpec; import google.registry.flows.annotations.ReportingSpec;
@ -105,7 +107,7 @@ public class FlowReporter {
* just about anything could be supplied, and there's no reason to validate twice when this just * just about anything could be supplied, and there's no reason to validate twice when this just
* needs to be roughly correct. * needs to be roughly correct.
*/ */
private static final Optional<String> extractTld(String domainName) { private static Optional<String> extractTld(String domainName) {
int index = domainName.indexOf('.'); int index = domainName.indexOf('.');
return index == -1 return index == -1
? Optional.empty() ? Optional.empty()
@ -116,22 +118,19 @@ public class FlowReporter {
* Returns the set of unique results of {@link #extractTld} applied to each given domain name, * Returns the set of unique results of {@link #extractTld} applied to each given domain name,
* excluding any absent results (i.e. cases where no TLD was detected). * excluding any absent results (i.e. cases where no TLD was detected).
*/ */
public static final ImmutableSet<String> extractTlds(Iterable<String> domainNames) { public static ImmutableSet<String> extractTlds(Iterable<String> domainNames) {
ImmutableSet.Builder<String> set = new ImmutableSet.Builder<>(); return Streams.stream(domainNames)
for (String domainName : domainNames) { .map(FlowReporter::extractTld)
Optional<String> extractedTld = extractTld(domainName); .filter(Optional::isPresent)
if (extractedTld.isPresent()) { .map(Optional::get)
set.add(extractedTld.get()); .collect(toImmutableSet());
}
}
return set.build();
} }
/** /**
* Returns the ICANN activity report field for the given flow class, or the empty string if no * Returns the ICANN activity report field for the given flow class, or the empty string if no
* activity report field specification is found. * activity report field specification is found.
*/ */
private static final String extractActivityReportField(Class<? extends Flow> flowClass) { private static String extractActivityReportField(Class<? extends Flow> flowClass) {
ReportingSpec reportingSpec = flowClass.getAnnotation(ReportingSpec.class); ReportingSpec reportingSpec = flowClass.getAnnotation(ReportingSpec.class);
if (reportingSpec != null) { if (reportingSpec != null) {
return reportingSpec.value().getFieldName(); return reportingSpec.value().getFieldName();

View file

@ -24,5 +24,5 @@ import google.registry.model.eppcommon.Trid;
public interface ServerTridProvider { public interface ServerTridProvider {
/** Creates a new server Trid. */ /** Creates a new server Trid. */
public String createServerTrid(); String createServerTrid();
} }

View file

@ -29,7 +29,7 @@ public interface TransportCredentials {
void validate(Registrar registrar, String password) throws AuthenticationErrorException; void validate(Registrar registrar, String password) throws AuthenticationErrorException;
/** Registrar password is incorrect. */ /** Registrar password is incorrect. */
static class BadRegistrarPasswordException extends AuthenticationErrorException { class BadRegistrarPasswordException extends AuthenticationErrorException {
public BadRegistrarPasswordException() { public BadRegistrarPasswordException() {
super("Registrar password is incorrect"); super("Registrar password is incorrect");
} }

View file

@ -110,7 +110,7 @@ public class AsyncFlowMetrics {
private final String metricLabelValue; private final String metricLabelValue;
private OperationType(String metricLabelValue) { OperationType(String metricLabelValue) {
this.metricLabelValue = metricLabelValue; this.metricLabelValue = metricLabelValue;
} }
@ -135,7 +135,7 @@ public class AsyncFlowMetrics {
private final String metricLabelValue; private final String metricLabelValue;
private OperationResult(String metricLabelValue) { OperationResult(String metricLabelValue) {
this.metricLabelValue = metricLabelValue; this.metricLabelValue = metricLabelValue;
} }

View file

@ -509,9 +509,7 @@ public class DomainFlowUtils {
// If the resultant autorenew poll message would have no poll messages to deliver, then just // If the resultant autorenew poll message would have no poll messages to deliver, then just
// delete it. Otherwise save it with the new end time. // delete it. Otherwise save it with the new end time.
if (isAtOrAfter(updatedAutorenewPollMessage.getEventTime(), newEndTime)) { if (isAtOrAfter(updatedAutorenewPollMessage.getEventTime(), newEndTime)) {
if (autorenewPollMessage.isPresent()) { autorenewPollMessage.ifPresent(autorenew -> ofy().delete().entity(autorenew));
ofy().delete().entity(autorenewPollMessage.get());
}
} else { } else {
ofy().save().entity(updatedAutorenewPollMessage); ofy().save().entity(updatedAutorenewPollMessage);
} }

View file

@ -207,9 +207,7 @@ public final class DomainTransferApproveFlow implements TransactionalFlow {
autorenewEvent, autorenewEvent,
gainingClientPollMessage, gainingClientPollMessage,
gainingClientAutorenewPollMessage); gainingClientAutorenewPollMessage);
if (billingEvent.isPresent()) { billingEvent.ifPresent(entitiesToSave::add);
entitiesToSave.add(billingEvent.get());
}
ofy().save().entities(entitiesToSave.build()); ofy().save().entities(entitiesToSave.build());
// Delete the billing event and poll messages that were written in case the transfer would have // Delete the billing event and poll messages that were written in case the transfer would have
// been implicitly server approved. // been implicitly server approved.

View file

@ -197,9 +197,7 @@ public final class DomainTransferRequestFlow implements TransactionalFlow {
existingDomain, existingDomain,
trid, trid,
gainingClientId, gainingClientId,
(feesAndCredits.isPresent()) feesAndCredits.map(FeesAndCredits::getTotalCost),
? Optional.of(feesAndCredits.get().getTotalCost())
: Optional.empty(),
now); now);
// Create the transfer data that represents the pending transfer. // Create the transfer data that represents the pending transfer.
TransferData pendingTransferData = TransferData pendingTransferData =

View file

@ -193,9 +193,7 @@ public final class DomainUpdateFlow implements TransactionalFlow {
entitiesToSave.add(newDomain, historyEntry); entitiesToSave.add(newDomain, historyEntry);
Optional<BillingEvent.OneTime> statusUpdateBillingEvent = Optional<BillingEvent.OneTime> statusUpdateBillingEvent =
createBillingEventForStatusUpdates(existingDomain, newDomain, historyEntry, now); createBillingEventForStatusUpdates(existingDomain, newDomain, historyEntry, now);
if (statusUpdateBillingEvent.isPresent()) { statusUpdateBillingEvent.ifPresent(entitiesToSave::add);
entitiesToSave.add(statusUpdateBillingEvent.get());
}
EntityChanges entityChanges = EntityChanges entityChanges =
customLogic.beforeSave( customLogic.beforeSave(
BeforeSaveParameters.newBuilder() BeforeSaveParameters.newBuilder()

View file

@ -113,15 +113,15 @@ public final class HostCreateFlow implements TransactionalFlow {
? new SubordinateHostMustHaveIpException() ? new SubordinateHostMustHaveIpException()
: new UnexpectedExternalHostIpException(); : new UnexpectedExternalHostIpException();
} }
HostResource newHost = new Builder() HostResource newHost =
.setCreationClientId(clientId) new Builder()
.setPersistedCurrentSponsorClientId(clientId) .setCreationClientId(clientId)
.setFullyQualifiedHostName(targetId) .setPersistedCurrentSponsorClientId(clientId)
.setInetAddresses(command.getInetAddresses()) .setFullyQualifiedHostName(targetId)
.setRepoId(createRepoId(ObjectifyService.allocateId(), roidSuffix)) .setInetAddresses(command.getInetAddresses())
.setSuperordinateDomain( .setRepoId(createRepoId(ObjectifyService.allocateId(), roidSuffix))
superordinateDomain.isPresent() ? Key.create(superordinateDomain.get()) : null) .setSuperordinateDomain(superordinateDomain.map(Key::create).orElse(null))
.build(); .build();
historyBuilder historyBuilder
.setType(HistoryEntry.Type.HOST_CREATE) .setType(HistoryEntry.Type.HOST_CREATE)
.setModificationTime(now) .setModificationTime(now)

View file

@ -152,9 +152,8 @@ public final class HostUpdateFlow implements TransactionalFlow {
AddRemove remove = command.getInnerRemove(); AddRemove remove = command.getInnerRemove();
checkSameValuesNotAddedAndRemoved(add.getStatusValues(), remove.getStatusValues()); checkSameValuesNotAddedAndRemoved(add.getStatusValues(), remove.getStatusValues());
checkSameValuesNotAddedAndRemoved(add.getInetAddresses(), remove.getInetAddresses()); checkSameValuesNotAddedAndRemoved(add.getInetAddresses(), remove.getInetAddresses());
Key<DomainResource> newSuperordinateDomainKey = newSuperordinateDomain.isPresent() Key<DomainResource> newSuperordinateDomainKey =
? Key.create(newSuperordinateDomain.get()) newSuperordinateDomain.map(Key::create).orElse(null);
: null;
// If the superordinateDomain field is changing, set the lastSuperordinateChange to now. // If the superordinateDomain field is changing, set the lastSuperordinateChange to now.
DateTime lastSuperordinateChange = DateTime lastSuperordinateChange =
Objects.equals(newSuperordinateDomainKey, existingHost.getSuperordinateDomain()) Objects.equals(newSuperordinateDomainKey, existingHost.getSuperordinateDomain())

View file

@ -25,7 +25,7 @@ import java.util.Set;
public interface GroupsConnection { public interface GroupsConnection {
/** The role of a member in a group. */ /** The role of a member in a group. */
public enum Role { enum Role {
MEMBER, MEMBER,
MANAGER, MANAGER,
OWNER OWNER
@ -36,19 +36,19 @@ public interface GroupsConnection {
* member already exists in the group, then it returns normally. If the group doesn't exist, then * member already exists in the group, then it returns normally. If the group doesn't exist, then
* it is created. * it is created.
*/ */
public void addMemberToGroup(String groupKey, String email, Role role) throws IOException; void addMemberToGroup(String groupKey, String email, Role role) throws IOException;
/** /**
* Removes a member from the specified group, or throws {@link GoogleJsonResponseException} if the * Removes a member from the specified group, or throws {@link GoogleJsonResponseException} if the
* member doesn't exist. * member doesn't exist.
*/ */
public void removeMemberFromGroup(String groupKey, String email) throws IOException; void removeMemberFromGroup(String groupKey, String email) throws IOException;
/** /**
* Returns all of the members of the specified group. Note that it gets members only; not owners * Returns all of the members of the specified group. Note that it gets members only; not owners
* or managers. Returns an empty set if the group in question does not exist. * or managers. Returns an empty set if the group in question does not exist.
*/ */
public Set<String> getMembersOfGroup(String groupKey) throws IOException; Set<String> getMembersOfGroup(String groupKey) throws IOException;
/** /**
* Creates a group with the given email address (groupKey) that is open for external members to * Creates a group with the given email address (groupKey) that is open for external members to
@ -57,5 +57,5 @@ public interface GroupsConnection {
* including permissions on who is able to join). The configured admin owner for the Google App is * including permissions on who is able to join). The configured admin owner for the Google App is
* automatically added as an owner. * automatically added as an owner.
*/ */
public Group createGroup(String groupKey) throws IOException; Group createGroup(String groupKey) throws IOException;
} }

View file

@ -32,7 +32,7 @@ public final class KeyModule {
/** Dagger qualifier for keys from {@link Keyring}. */ /** Dagger qualifier for keys from {@link Keyring}. */
@Qualifier @Qualifier
@Documented @Documented
public static @interface Key { public @interface Key {
String value(); String value();
} }

View file

@ -45,7 +45,7 @@ public final class PgpHelper {
* Narrowed key search requirements. * Narrowed key search requirements.
* @see PgpHelper#lookupPublicKey * @see PgpHelper#lookupPublicKey
*/ */
public static enum KeyRequirement { ENCRYPT, SIGN, ENCRYPT_SIGN } public enum KeyRequirement { ENCRYPT, SIGN, ENCRYPT_SIGN }
/** Converts {@code publicKey} to bytes. */ /** Converts {@code publicKey} to bytes. */
public static byte[] convertPublicKeyToBytes(PGPPublicKey publicKey) { public static byte[] convertPublicKeyToBytes(PGPPublicKey publicKey) {

View file

@ -41,7 +41,7 @@ import org.bouncycastle.openpgp.PGPPublicKey;
*/ */
public class KmsKeyring implements Keyring { public class KmsKeyring implements Keyring {
static enum PrivateKeyLabel { enum PrivateKeyLabel {
BRDA_SIGNING_PRIVATE, BRDA_SIGNING_PRIVATE,
RDE_SIGNING_PRIVATE, RDE_SIGNING_PRIVATE,
RDE_STAGING_PRIVATE; RDE_STAGING_PRIVATE;
@ -51,7 +51,7 @@ public class KmsKeyring implements Keyring {
} }
} }
static enum PublicKeyLabel { enum PublicKeyLabel {
BRDA_RECEIVER_PUBLIC, BRDA_RECEIVER_PUBLIC,
BRDA_SIGNING_PUBLIC, BRDA_SIGNING_PUBLIC,
RDE_RECEIVER_PUBLIC, RDE_RECEIVER_PUBLIC,
@ -63,7 +63,7 @@ public class KmsKeyring implements Keyring {
} }
} }
static enum StringKeyLabel { enum StringKeyLabel {
BRAINTREE_PRIVATE_KEY_STRING, BRAINTREE_PRIVATE_KEY_STRING,
ICANN_REPORTING_PASSWORD_STRING, ICANN_REPORTING_PASSWORD_STRING,
JSON_CREDENTIAL_STRING, JSON_CREDENTIAL_STRING,

View file

@ -33,7 +33,7 @@ public interface Buildable {
* *
* <p>This can be used without implementing {@link Buildable}. * <p>This can be used without implementing {@link Buildable}.
*/ */
public abstract static class Builder<S> { abstract class Builder<S> {
private S instance; private S instance;
@ -77,7 +77,7 @@ public interface Buildable {
} }
/** Boilerplate for abstract immutable builders that need to be able to cast "this". */ /** Boilerplate for abstract immutable builders that need to be able to cast "this". */
public abstract class GenericBuilder<S, B extends GenericBuilder<?, ?>> extends Builder<S> { abstract class GenericBuilder<S, B extends GenericBuilder<?, ?>> extends Builder<S> {
protected GenericBuilder() {} protected GenericBuilder() {}
protected GenericBuilder(S instance) { protected GenericBuilder(S instance) {
@ -100,7 +100,7 @@ public interface Buildable {
* *
* @param <T> the derived type * @param <T> the derived type
*/ */
public interface Overlayable<T> extends Buildable { interface Overlayable<T> extends Buildable {
/** Return an overlay of this object using non-null fields from the source. */ /** Return an overlay of this object using non-null fields from the source. */
T overlay(T source); T overlay(T source);
} }

View file

@ -165,22 +165,22 @@ public abstract class EppResource extends BackupGroupRoot implements Buildable {
/** An interface for resources that have transfer data. */ /** An interface for resources that have transfer data. */
public interface ResourceWithTransferData { public interface ResourceWithTransferData {
public TransferData getTransferData(); TransferData getTransferData();
/** /**
* The time that this resource was last transferred. * The time that this resource was last transferred.
* *
* <p>Can be null if the resource has never been transferred. * <p>Can be null if the resource has never been transferred.
*/ */
public DateTime getLastTransferTime(); DateTime getLastTransferTime();
} }
/** An interface for builders of resources that have transfer data. */ /** An interface for builders of resources that have transfer data. */
public interface BuilderWithTransferData<B extends BuilderWithTransferData<B>> { public interface BuilderWithTransferData<B extends BuilderWithTransferData<B>> {
public B setTransferData(TransferData transferData); B setTransferData(TransferData transferData);
/** Set the time when this resource was transferred. */ /** Set the time when this resource was transferred. */
public B setLastTransferTime(DateTime lastTransferTime); B setLastTransferTime(DateTime lastTransferTime);
} }
/** Abstract builder for {@link EppResource} types. */ /** Abstract builder for {@link EppResource} types. */

View file

@ -66,7 +66,7 @@ public final class EppResourceUtils {
/** Helper to call {@link EppResource#cloneProjectedAtTime} without warnings. */ /** Helper to call {@link EppResource#cloneProjectedAtTime} without warnings. */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static final <T extends EppResource> T cloneProjectedAtTime(T resource, DateTime now) { private static <T extends EppResource> T cloneProjectedAtTime(T resource, DateTime now) {
return (T) resource.cloneProjectedAtTime(now); return (T) resource.cloneProjectedAtTime(now);
} }

View file

@ -52,7 +52,7 @@ public abstract class ImmutableObject implements Cloneable {
@Documented @Documented
@Retention(RUNTIME) @Retention(RUNTIME)
@Target(FIELD) @Target(FIELD)
public static @interface DoNotHydrate {} public @interface DoNotHydrate {}
@Ignore @Ignore
@XmlTransient @XmlTransient

View file

@ -30,7 +30,7 @@ public @interface NotBackedUp {
Reason reason(); Reason reason();
/** Reasons why a given entity does not need to be be backed up. */ /** Reasons why a given entity does not need to be be backed up. */
public enum Reason { enum Reason {
/** This entity is transient by design and has only a short-term useful lifetime. */ /** This entity is transient by design and has only a short-term useful lifetime. */
TRANSIENT, TRANSIENT,

View file

@ -83,7 +83,7 @@ public class Cursor extends ImmutableObject {
/** See the definition of scope on {@link #getScopeClass}. */ /** See the definition of scope on {@link #getScopeClass}. */
private final Class<? extends ImmutableObject> scope; private final Class<? extends ImmutableObject> scope;
private CursorType(Class<? extends ImmutableObject> scope) { CursorType(Class<? extends ImmutableObject> scope) {
this.scope = scope; this.scope = scope;
} }

View file

@ -40,7 +40,7 @@ public class EntityGroupRoot extends BackupGroupRoot {
private String id; private String id;
/** The root key for cross-tld resources such as registrars. */ /** The root key for cross-tld resources such as registrars. */
public static final Key<EntityGroupRoot> getCrossTldKey() { public static Key<EntityGroupRoot> getCrossTldKey() {
return Key.create(EntityGroupRoot.class, "cross-tld"); return Key.create(EntityGroupRoot.class, "cross-tld");
} }
} }

View file

@ -67,7 +67,7 @@ public class DomainCommand {
*/ */
public interface CreateOrUpdate<T extends CreateOrUpdate<T>> extends SingleResourceCommand { public interface CreateOrUpdate<T extends CreateOrUpdate<T>> extends SingleResourceCommand {
/** Creates a copy of this command with hard links to hosts and contacts. */ /** Creates a copy of this command with hard links to hosts and contacts. */
public T cloneAndLinkReferences(DateTime now) throws InvalidReferencesException; T cloneAndLinkReferences(DateTime now) throws InvalidReferencesException;
} }
/** The fields on "chgType" from {@link "http://tools.ietf.org/html/rfc5731"}. */ /** The fields on "chgType" from {@link "http://tools.ietf.org/html/rfc5731"}. */

View file

@ -38,9 +38,9 @@ public interface FeeCheckCommandExtension<
* *
* <p>Returns null if this version of the fee extension doesn't specify currency at the top level. * <p>Returns null if this version of the fee extension doesn't specify currency at the top level.
*/ */
public CurrencyUnit getCurrency(); CurrencyUnit getCurrency();
public ImmutableSet<C> getItems(); ImmutableSet<C> getItems();
public R createResponse(ImmutableList<? extends FeeCheckResponseExtensionItem> items); R createResponse(ImmutableList<? extends FeeCheckResponseExtensionItem> items);
} }

View file

@ -31,7 +31,7 @@ public interface FeeCheckResponseExtension<F extends FeeCheckResponseExtensionIt
* If currency is not supported at the top level of Check responses for this version of the fee * If currency is not supported at the top level of Check responses for this version of the fee
* extension, this function has not effect. * extension, this function has not effect.
*/ */
public void setCurrencyIfSupported(CurrencyUnit currency); void setCurrencyIfSupported(CurrencyUnit currency);
public ImmutableList<F> getItems(); ImmutableList<F> getItems();
} }

View file

@ -68,7 +68,7 @@ public class LaunchPhase extends ImmutableObject {
/** /**
* Returns a map of the static final fields to their values, case-converted. * Returns a map of the static final fields to their values, case-converted.
*/ */
private static final ImmutableMap<String, LaunchPhase> initEnumMapping() { private static ImmutableMap<String, LaunchPhase> initEnumMapping() {
ImmutableMap.Builder<String, LaunchPhase> builder = new ImmutableMap.Builder<>(); ImmutableMap.Builder<String, LaunchPhase> builder = new ImmutableMap.Builder<>();
for (Entry<String, LaunchPhase> entry : getTypesafeEnumMapping(LaunchPhase.class).entrySet()) { for (Entry<String, LaunchPhase> entry : getTypesafeEnumMapping(LaunchPhase.class).entrySet()) {
builder.put(UPPER_UNDERSCORE.to(LOWER_CAMEL, entry.getKey()), entry.getValue()); builder.put(UPPER_UNDERSCORE.to(LOWER_CAMEL, entry.getKey()), entry.getValue());

View file

@ -95,8 +95,11 @@ public class ProtocolDefinition {
} }
} }
/** Converts a service extension enum to its URI. */ /**
/** This stores a map from URI back to the service extension enum. */ * Converts a service extension enum to its URI.
*
* <p>This stores a map from URI back to the service extension enum.
*/
private static final ImmutableMap<String, ServiceExtension> serviceExtensionByUri = private static final ImmutableMap<String, ServiceExtension> serviceExtensionByUri =
uniqueIndex(EnumSet.allOf(ServiceExtension.class), ServiceExtension::getUri); uniqueIndex(EnumSet.allOf(ServiceExtension.class), ServiceExtension::getUri);

View file

@ -139,12 +139,12 @@ public enum StatusValue implements EppEnum {
private final ImmutableSet<Class<? extends EppResource>> classes; private final ImmutableSet<Class<? extends EppResource>> classes;
@SafeVarargs @SafeVarargs
private AllowedOn(Class<? extends EppResource>... classes) { AllowedOn(Class<? extends EppResource>... classes) {
this.classes = ImmutableSet.copyOf(classes); this.classes = ImmutableSet.copyOf(classes);
} }
} }
private StatusValue(AllowedOn allowedOn) { StatusValue(AllowedOn allowedOn) {
this.allowedOn = allowedOn; this.allowedOn = allowedOn;
} }

View file

@ -42,7 +42,7 @@ public interface ResourceCommand {
* a base class that gives them all of the resource's fields. The domain "Info" command also can't * a base class that gives them all of the resource's fields. The domain "Info" command also can't
* do that since it's "name" field is overloaded with a "hosts" attribute. * do that since it's "name" field is overloaded with a "hosts" attribute.
*/ */
public interface SingleResourceCommand extends ResourceCommand { interface SingleResourceCommand extends ResourceCommand {
String getTargetId(); String getTargetId();
AuthInfo getAuthInfo(); AuthInfo getAuthInfo();
@ -50,7 +50,7 @@ public interface ResourceCommand {
/** Abstract implementation of {@link ResourceCommand}. */ /** Abstract implementation of {@link ResourceCommand}. */
@XmlTransient @XmlTransient
public abstract static class AbstractSingleResourceCommand extends ImmutableObject abstract class AbstractSingleResourceCommand extends ImmutableObject
implements SingleResourceCommand { implements SingleResourceCommand {
@XmlElements({ @XmlElements({
@XmlElement(name = "id"), @XmlElement(name = "id"),
@ -70,7 +70,7 @@ public interface ResourceCommand {
/** A check command for an {@link EppResource}. */ /** A check command for an {@link EppResource}. */
@XmlTransient @XmlTransient
public static class ResourceCheck extends ImmutableObject implements ResourceCommand { class ResourceCheck extends ImmutableObject implements ResourceCommand {
@XmlElements({ @XmlElements({
@XmlElement(name = "id"), @XmlElement(name = "id"),
@XmlElement(name = "name") }) @XmlElement(name = "name") })
@ -82,7 +82,7 @@ public interface ResourceCommand {
} }
/** A create command, or the inner change (as opposed to add or remove) part of an update. */ /** A create command, or the inner change (as opposed to add or remove) part of an update. */
public interface ResourceCreateOrChange<B extends Builder<?>> {} interface ResourceCreateOrChange<B extends Builder<?>> {}
/** /**
* An update command for an {@link EppResource}. * An update command for an {@link EppResource}.
@ -91,7 +91,7 @@ public interface ResourceCommand {
* @param <C> the change type * @param <C> the change type
*/ */
@XmlTransient @XmlTransient
public abstract static class ResourceUpdate abstract class ResourceUpdate
<A extends ResourceUpdate.AddRemove, <A extends ResourceUpdate.AddRemove,
B extends EppResource.Builder<?, ?>, B extends EppResource.Builder<?, ?>,
C extends ResourceCreateOrChange<B>> extends AbstractSingleResourceCommand { C extends ResourceCreateOrChange<B>> extends AbstractSingleResourceCommand {

View file

@ -32,14 +32,14 @@ public interface PremiumPricingEngine {
* <p>Note that the fullyQualifiedDomainName must only contain a single part left of the TLD, i.e. * <p>Note that the fullyQualifiedDomainName must only contain a single part left of the TLD, i.e.
* subdomains are not allowed, but multi-part TLDs are. * subdomains are not allowed, but multi-part TLDs are.
*/ */
public DomainPrices getDomainPrices(String fullyQualifiedDomainName, DateTime priceTime); DomainPrices getDomainPrices(String fullyQualifiedDomainName, DateTime priceTime);
/** /**
* A class containing information on premium prices for a specific domain name. * A class containing information on premium prices for a specific domain name.
* *
* <p>Any implementation of PremiumPricingEngine is responsible for determining all of these. * <p>Any implementation of PremiumPricingEngine is responsible for determining all of these.
*/ */
public static class DomainPrices { class DomainPrices {
private boolean isPremium; private boolean isPremium;
// TODO(b/26901539): Refactor return values to support an arbitrary list of costs for each of // TODO(b/26901539): Refactor return values to support an arbitrary list of costs for each of

View file

@ -133,7 +133,7 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable
*/ */
private final Predicate<Long> ianaIdValidator; private final Predicate<Long> ianaIdValidator;
private Type(Predicate<Long> ianaIdValidator) { Type(Predicate<Long> ianaIdValidator) {
this.ianaIdValidator = ianaIdValidator; this.ianaIdValidator = ianaIdValidator;
} }

View file

@ -84,7 +84,7 @@ public class RegistrarContact extends ImmutableObject implements Jsonifiable {
return required; return required;
} }
private Type(String display, boolean required) { Type(String display, boolean required) {
this.displayName = display; this.displayName = display;
this.required = required; this.required = required;
} }

View file

@ -174,8 +174,7 @@ public final class PremiumListUtils {
"PremiumList was concurrently edited"); "PremiumList was concurrently edited");
PremiumList newList = premiumList.asBuilder() PremiumList newList = premiumList.asBuilder()
.setLastUpdateTime(now) .setLastUpdateTime(now)
.setCreationTime( .setCreationTime(oldPremiumList.isPresent() ? oldPremiumList.get().creationTime : now)
oldPremiumList.isPresent() ? oldPremiumList.get().creationTime : now)
.setRevision(newRevisionKey) .setRevision(newRevisionKey)
.build(); .build();
ofy().save().entities(newList, newRevision); ofy().save().entities(newList, newRevision);
@ -184,9 +183,7 @@ public final class PremiumListUtils {
// Update the cache. // Update the cache.
cachePremiumLists.put(premiumList.getName(), updated); cachePremiumLists.put(premiumList.getName(), updated);
// Delete the entities under the old PremiumList. // Delete the entities under the old PremiumList.
if (oldPremiumList.isPresent()) { oldPremiumList.ifPresent(PremiumListUtils::deleteRevisionAndEntriesOfPremiumList);
deleteRevisionAndEntriesOfPremiumList(oldPremiumList.get());
}
return updated; return updated;
} }

View file

@ -39,7 +39,7 @@ public enum TransferStatus {
private final String message; private final String message;
private TransferStatus(String message) { TransferStatus(String message) {
this.message = message; this.message = message;
} }

View file

@ -17,6 +17,7 @@ package google.registry.monitoring.metrics.contrib;
import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertAbout;
import com.google.common.truth.FailureMetadata; import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import google.registry.monitoring.metrics.Metric; import google.registry.monitoring.metrics.Metric;
import google.registry.monitoring.metrics.MetricPoint; import google.registry.monitoring.metrics.MetricPoint;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -43,8 +44,11 @@ import javax.annotation.Nullable;
*/ */
public final class LongMetricSubject extends AbstractMetricSubject<Long, LongMetricSubject> { public final class LongMetricSubject extends AbstractMetricSubject<Long, LongMetricSubject> {
/** {@link Subject.Factory} for assertions about {@link Metric<Long>} objects. */ /**
/** Static assertThat({@link Metric<Long>}) shortcut method. */ * Static assertThat({@link Metric<Long>}) shortcut method.
*
* @see Subject.Factory for assertions about {@link Metric<Long>} objects.
*/
public static LongMetricSubject assertThat(@Nullable Metric<Long> metric) { public static LongMetricSubject assertThat(@Nullable Metric<Long> metric) {
return assertAbout(LongMetricSubject::new).that(metric); return assertAbout(LongMetricSubject::new).that(metric);
} }

View file

@ -110,9 +110,7 @@ public abstract class EppMetric implements BigQueryMetric {
*/ */
private static <T> void addOptional( private static <T> void addOptional(
String key, Optional<T> value, ImmutableMap.Builder<String, String> map) { String key, Optional<T> value, ImmutableMap.Builder<String, String> map) {
if (value.isPresent()) { value.ifPresent(t -> map.put(key, t.toString()));
map.put(key, value.get().toString());
}
} }
/** Create an {@link EppMetric.Builder}. */ /** Create an {@link EppMetric.Builder}. */

View file

@ -512,9 +512,7 @@ public class RdapDomainSearchAction extends RdapActionBase {
IncompletenessWarningType incompletenessWarningType, IncompletenessWarningType incompletenessWarningType,
Optional<Long> numDomainsRetrieved, Optional<Long> numDomainsRetrieved,
DateTime now) { DateTime now) {
if (numDomainsRetrieved.isPresent()) { numDomainsRetrieved.ifPresent(metricInformationBuilder::setNumDomainsRetrieved);
metricInformationBuilder.setNumDomainsRetrieved(numDomainsRetrieved.get());
}
OutputDataType outputDataType = OutputDataType outputDataType =
(domains.size() > 1) ? OutputDataType.SUMMARY : OutputDataType.FULL; (domains.size() > 1) ? OutputDataType.SUMMARY : OutputDataType.FULL;
RdapAuthorization authorization = getAuthorization(); RdapAuthorization authorization = getAuthorization();

View file

@ -161,7 +161,7 @@ public class RdapJsonFormatter {
/** Value as it appears in RDAP messages. */ /** Value as it appears in RDAP messages. */
private final String rfc7483String; private final String rfc7483String;
private RdapStatus(String rfc7483String) { RdapStatus(String rfc7483String) {
this.rfc7483String = rfc7483String; this.rfc7483String = rfc7483String;
} }
@ -217,7 +217,7 @@ public class RdapJsonFormatter {
/** Value as it appears in RDAP messages. */ /** Value as it appears in RDAP messages. */
final String rfc7483String; final String rfc7483String;
private RdapEntityRole(String rfc7483String) { RdapEntityRole(String rfc7483String) {
this.rfc7483String = rfc7483String; this.rfc7483String = rfc7483String;
} }
} }
@ -238,7 +238,7 @@ public class RdapJsonFormatter {
/** Value as it appears in RDAP messages. */ /** Value as it appears in RDAP messages. */
private final String rfc7483String; private final String rfc7483String;
private RdapEventAction(String rfc7483String) { RdapEventAction(String rfc7483String) {
this.rfc7483String = rfc7483String; this.rfc7483String = rfc7483String;
} }
@ -675,10 +675,8 @@ public class RdapJsonFormatter {
? union(contactResource.getStatusValues(), StatusValue.LINKED) ? union(contactResource.getStatusValues(), StatusValue.LINKED)
: contactResource.getStatusValues(), : contactResource.getStatusValues(),
contactResource.getDeletionTime().isBefore(now))); contactResource.getDeletionTime().isBefore(now)));
if (contactType.isPresent()) { contactType.ifPresent(
jsonBuilder.put("roles", type -> jsonBuilder.put("roles", ImmutableList.of(convertContactTypeToRdapRole(type))));
ImmutableList.of(convertContactTypeToRdapRole(contactType.get())));
}
jsonBuilder.put("links", jsonBuilder.put("links",
ImmutableList.of(makeLink("entity", contactResource.getRepoId(), linkBase))); ImmutableList.of(makeLink("entity", contactResource.getRepoId(), linkBase)));
// If we are logged in as the owner of this contact, create the vCard. // If we are logged in as the owner of this contact, create the vCard.

View file

@ -61,7 +61,7 @@ class EscrowTaskRunner {
* *
* @param watermark the logical time for a point-in-time view of Datastore * @param watermark the logical time for a point-in-time view of Datastore
*/ */
abstract void runWithLock(DateTime watermark) throws Exception; void runWithLock(DateTime watermark) throws Exception;
} }
private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();

View file

@ -117,8 +117,7 @@ public class RdeReporter {
logger.infofmt("Received response:\n%s", new String(responseBytes, UTF_8)); logger.infofmt("Received response:\n%s", new String(responseBytes, UTF_8));
XjcIirdeaResponseElement response = XjcXmlTransformer.unmarshal( XjcIirdeaResponseElement response = XjcXmlTransformer.unmarshal(
XjcIirdeaResponseElement.class, new ByteArrayInputStream(responseBytes)); XjcIirdeaResponseElement.class, new ByteArrayInputStream(responseBytes));
XjcIirdeaResult result = response.getResult(); return response.getResult();
return result;
} }
private URL makeReportUrl(String tld, String id) { private URL makeReportUrl(String tld, String id) {

View file

@ -36,7 +36,7 @@ public enum RdeResourceType {
private final String uri; private final String uri;
private final Set<RdeMode> modes; private final Set<RdeMode> modes;
private RdeResourceType(String uri, EnumSet<RdeMode> modes) { RdeResourceType(String uri, EnumSet<RdeMode> modes) {
this.uri = uri; this.uri = uri;
this.modes = Collections.unmodifiableSet(modes); this.modes = Collections.unmodifiableSet(modes);
} }

View file

@ -70,8 +70,7 @@ public final class RdeUtil {
if (!watermarkMatcher.find()) { if (!watermarkMatcher.find()) {
throw new XmlException("Could not find RDE watermark in XML"); throw new XmlException("Could not find RDE watermark in XML");
} }
DateTime watermark = DATETIME_FORMATTER.parseDateTime(watermarkMatcher.group(1)); return DATETIME_FORMATTER.parseDateTime(watermarkMatcher.group(1));
return watermark;
} }
/** /**

View file

@ -204,7 +204,7 @@ public class RdeHostLinkAction implements Runnable {
} }
} }
private static enum HostLinkResult { private enum HostLinkResult {
HOST_NOT_FOUND, HOST_NOT_FOUND,
HOST_OUT_OF_ZONE, HOST_OUT_OF_ZONE,
SUPERORDINATE_DOMAIN_IN_PENDING_DELETE, SUPERORDINATE_DOMAIN_IN_PENDING_DELETE,

View file

@ -189,47 +189,41 @@ public class RdeImportUtils {
public static BillingEvent.Recurring createAutoRenewBillingEventForDomainImport( public static BillingEvent.Recurring createAutoRenewBillingEventForDomainImport(
XjcRdeDomain domain, HistoryEntry historyEntry) { XjcRdeDomain domain, HistoryEntry historyEntry) {
final BillingEvent.Recurring billingEvent = return new BillingEvent.Recurring.Builder()
new BillingEvent.Recurring.Builder() .setReason(Reason.RENEW)
.setReason(Reason.RENEW) .setFlags(ImmutableSet.of(Flag.AUTO_RENEW))
.setFlags(ImmutableSet.of(Flag.AUTO_RENEW)) .setTargetId(domain.getRoid())
.setTargetId(domain.getRoid()) .setClientId(domain.getClID())
.setClientId(domain.getClID()) .setEventTime(domain.getExDate())
.setEventTime(domain.getExDate()) .setRecurrenceEndTime(END_OF_TIME)
.setRecurrenceEndTime(END_OF_TIME) .setParent(historyEntry)
.setParent(historyEntry) .build();
.build();
return billingEvent;
} }
public static PollMessage.Autorenew createAutoRenewPollMessageForDomainImport( public static PollMessage.Autorenew createAutoRenewPollMessageForDomainImport(
XjcRdeDomain domain, HistoryEntry historyEntry) { XjcRdeDomain domain, HistoryEntry historyEntry) {
final PollMessage.Autorenew pollMessage = return new PollMessage.Autorenew.Builder()
new PollMessage.Autorenew.Builder() .setTargetId(domain.getRoid())
.setTargetId(domain.getRoid()) .setClientId(domain.getClID())
.setClientId(domain.getClID()) .setEventTime(domain.getExDate())
.setEventTime(domain.getExDate()) .setMsg("Domain was auto-renewed.")
.setMsg("Domain was auto-renewed.") .setParent(historyEntry)
.setParent(historyEntry) .build();
.build();
return pollMessage;
} }
public static HistoryEntry createHistoryEntryForDomainImport(XjcRdeDomain domain) { public static HistoryEntry createHistoryEntryForDomainImport(XjcRdeDomain domain) {
XjcRdeDomainElement element = new XjcRdeDomainElement(domain); XjcRdeDomainElement element = new XjcRdeDomainElement(domain);
final HistoryEntry historyEntry = return new HistoryEntry.Builder()
new HistoryEntry.Builder() .setType(HistoryEntry.Type.RDE_IMPORT)
.setType(HistoryEntry.Type.RDE_IMPORT) .setClientId(domain.getClID())
.setClientId(domain.getClID()) .setTrid(generateTridForImport())
.setTrid(generateTridForImport()) .setModificationTime(ofy().getTransactionTime())
.setModificationTime(ofy().getTransactionTime()) .setXmlBytes(getObjectXml(element))
.setXmlBytes(getObjectXml(element)) .setBySuperuser(true)
.setBySuperuser(true) .setReason("RDE Import")
.setReason("RDE Import") .setRequestedByRegistrar(false)
.setRequestedByRegistrar(false) .setParent(Key.create(null, DomainResource.class, domain.getRoid()))
.setParent(Key.create(null, DomainResource.class, domain.getRoid())) .build();
.build();
return historyEntry;
} }
public static byte[] getObjectXml(Object jaxbElement) { public static byte[] getObjectXml(Object jaxbElement) {

View file

@ -198,8 +198,7 @@ public class RdeParser implements Closeable {
checkArgumentNotNull(uri, "uri cannot be null"); checkArgumentNotNull(uri, "uri cannot be null");
try { try {
if (isAtElement(uri, name)) { if (isAtElement(uri, name)) {
Object element = unmarshaller.unmarshal(reader); return unmarshaller.unmarshal(reader);
return element;
} else { } else {
throw new IllegalStateException(String.format("Not at element %s:%s", uri, name)); throw new IllegalStateException(String.format("Not at element %s:%s", uri, name));
} }

View file

@ -121,8 +121,7 @@ public class IcannHttpReporter {
XjcIirdeaResponseElement response = XjcIirdeaResponseElement response =
XjcXmlTransformer.unmarshal( XjcXmlTransformer.unmarshal(
XjcIirdeaResponseElement.class, new ByteArrayInputStream(content)); XjcIirdeaResponseElement.class, new ByteArrayInputStream(content));
XjcIirdeaResult result = response.getResult(); return response.getResult();
return result;
} }
/** Verifies a given report filename matches the pattern tld-reportType-yyyyMM.csv. */ /** Verifies a given report filename matches the pattern tld-reportType-yyyyMM.csv. */

View file

@ -194,10 +194,7 @@ public class IcannReportingStager {
/** Returns a list of integers (totals) as a comma separated string. */ /** Returns a list of integers (totals) as a comma separated string. */
private String constructTotalRow(List<Integer> totals) { private String constructTotalRow(List<Integer> totals) {
StringBuilder rowString = new StringBuilder("Totals,,"); return "Totals,," + totals.stream().map(Object::toString).collect(Collectors.joining(","));
rowString.append(
totals.stream().map(Object::toString).collect(Collectors.joining(",")));
return rowString.toString();
} }
/** /**
@ -206,8 +203,8 @@ public class IcannReportingStager {
* *
* <p>This discards the first object, which is assumed to be the TLD field. * <p>This discards the first object, which is assumed to be the TLD field.
* */ * */
private String constructRow(Iterable<? extends Object> iterable) { private String constructRow(Iterable<?> iterable) {
Iterator<? extends Object> rowIter = iterable.iterator(); Iterator<?> rowIter = iterable.iterator();
StringBuilder rowString = new StringBuilder(); StringBuilder rowString = new StringBuilder();
// Skip the TLD column // Skip the TLD column
rowIter.next(); rowIter.next();

View file

@ -26,7 +26,7 @@ import java.lang.annotation.Target;
public @interface Action { public @interface Action {
/** HTTP methods recognized by the request processor. */ /** HTTP methods recognized by the request processor. */
public enum Method { GET, HEAD, POST } enum Method { GET, HEAD, POST }
/** HTTP path to serve the action from. The path components must be percent-escaped. */ /** HTTP path to serve the action from. The path components must be percent-escaped. */
String path(); String path();

View file

@ -37,7 +37,7 @@ public interface LockHandler extends Serializable {
* *
* @return true if all locks were acquired and the callable was run; false otherwise. * @return true if all locks were acquired and the callable was run; false otherwise.
*/ */
public boolean executeWithLocks( boolean executeWithLocks(
final Callable<Void> callable, final Callable<Void> callable,
@Nullable String tld, @Nullable String tld,
Duration leaseLength, Duration leaseLength,

View file

@ -29,7 +29,7 @@ public enum IdnTableEnum {
private final IdnTable table; private final IdnTable table;
private IdnTableEnum() { IdnTableEnum() {
this.table = load(Ascii.toLowerCase(name())); this.table = load(Ascii.toLowerCase(name()));
} }

View file

@ -64,32 +64,27 @@ final class AllocateDomainCommand extends MutatingEppToolCommand {
@Override @Override
protected String postExecute() throws Exception { protected String postExecute() throws Exception {
StringBuilder builder = new StringBuilder(); return ofy()
// Check to see that we allocated everything. .transactNewReadOnly(
return builder () -> {
.append( String failureMessage =
ofy() ofy()
.transactNewReadOnly( .load()
() -> { .keys(applicationKeys)
String failureMessage = .values()
ofy() .stream()
.load() .map(
.keys(applicationKeys) application ->
.values() application.getApplicationStatus()
.stream() == ApplicationStatus.ALLOCATED
.map( ? null
application -> : application.getFullyQualifiedDomainName())
application.getApplicationStatus() .filter(Objects::nonNull)
== ApplicationStatus.ALLOCATED .collect(joining("\n"));
? null return failureMessage.isEmpty()
: application.getFullyQualifiedDomainName()) ? "ALL SUCCEEDED"
.filter(Objects::nonNull) : addHeader("FAILURES", failureMessage);
.collect(joining("\n")); });
return failureMessage.isEmpty()
? "ALL SUCCEEDED"
: addHeader("FAILURES", failureMessage);
}))
.toString();
} }
/** Extract the registration period from the XML used to create the domain application. */ /** Extract the registration period from the XML used to create the domain application. */

View file

@ -26,5 +26,5 @@ public interface Command {
* <p>Just implementing this is sufficient to use the remote api; {@link RegistryTool} will * <p>Just implementing this is sufficient to use the remote api; {@link RegistryTool} will
* install it as needed. * install it as needed.
*/ */
public interface RemoteApiCommand extends Command {} interface RemoteApiCommand extends Command {}
} }

View file

@ -67,7 +67,7 @@ abstract class CreateOrUpdatePremiumListCommand extends ConfirmingCommand
abstract String getCommandPath(); abstract String getCommandPath();
ImmutableMap<String, ? extends Object> getParameterMap() { ImmutableMap<String, ?> getParameterMap() {
return ImmutableMap.of(); return ImmutableMap.of();
} }

View file

@ -36,7 +36,7 @@ public class CreatePremiumListCommand extends CreateOrUpdatePremiumListCommand {
} }
@Override @Override
ImmutableMap<String, ? extends Object> getParameterMap() { ImmutableMap<String, ?> getParameterMap() {
if (override) { if (override) {
return ImmutableMap.of("override", override); return ImmutableMap.of("override", override);
} else { } else {

View file

@ -133,7 +133,7 @@ abstract class EppToolCommand extends ConfirmingCommand implements ServerSideCom
String prompt = addHeader("Command(s)", Joiner.on("\n").join(commands) String prompt = addHeader("Command(s)", Joiner.on("\n").join(commands)
+ (force ? "" : addHeader("Dry Run", Joiner.on("\n").join(processCommands(true))))); + (force ? "" : addHeader("Dry Run", Joiner.on("\n").join(processCommands(true)))));
force = force || isDryRun(); force = force || isDryRun();
return prompt.toString(); return prompt;
} }
private List<String> processCommands(boolean dryRun) throws IOException { private List<String> processCommands(boolean dryRun) throws IOException {

View file

@ -42,6 +42,8 @@ import google.registry.model.contact.ContactResource;
import google.registry.model.contact.PostalInfo; import google.registry.model.contact.PostalInfo;
import google.registry.model.domain.DomainApplication; import google.registry.model.domain.DomainApplication;
import google.registry.model.domain.launch.ApplicationStatus; import google.registry.model.domain.launch.ApplicationStatus;
import google.registry.model.eppcommon.Address;
import google.registry.model.eppcommon.PhoneNumber;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarAddress; import google.registry.model.registrar.RegistrarAddress;
import google.registry.model.registrar.RegistrarContact; import google.registry.model.registrar.RegistrarContact;
@ -190,9 +192,8 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
Optional.ofNullable(registrant.getInternationalizedPostalInfo()) Optional.ofNullable(registrant.getInternationalizedPostalInfo())
.orElse(registrant.getLocalizedPostalInfo())); .orElse(registrant.getLocalizedPostalInfo()));
Optional<ContactAddress> address = Optional<ContactAddress> address =
Optional.ofNullable(postalInfo.isPresent() ? postalInfo.get().getAddress() : null); Optional.ofNullable(postalInfo.map(PostalInfo::getAddress).orElse(null));
List<String> street = List<String> street = address.map(Address::getStreet).orElseGet(ImmutableList::of);
address.isPresent() ? address.get().getStreet() : ImmutableList.of();
Optional<ContactPhoneNumber> phoneNumber = Optional.ofNullable(registrant.getVoiceNumber()); Optional<ContactPhoneNumber> phoneNumber = Optional.ofNullable(registrant.getVoiceNumber());
// Each line containing an auction participant has the following format: // Each line containing an auction participant has the following format:
@ -211,16 +212,16 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
? formatter.print(domainApplication.getLastEppUpdateTime()) ? formatter.print(domainApplication.getLastEppUpdateTime())
: "", : "",
domainApplication.getCurrentSponsorClientId(), domainApplication.getCurrentSponsorClientId(),
nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getName() : ""), nullToEmpty(postalInfo.map(PostalInfo::getName).orElse("")),
nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getOrg() : ""), nullToEmpty(postalInfo.map(PostalInfo::getOrg).orElse("")),
Iterables.getFirst(street, ""), Iterables.getFirst(street, ""),
street.stream().skip(1).filter(Objects::nonNull).collect(joining(" ")), street.stream().skip(1).filter(Objects::nonNull).collect(joining(" ")),
nullToEmpty(address.isPresent() ? address.get().getCity() : ""), nullToEmpty(address.map(Address::getCity).orElse("")),
nullToEmpty(address.isPresent() ? address.get().getState() : ""), nullToEmpty(address.map(Address::getState).orElse("")),
nullToEmpty(address.isPresent() ? address.get().getZip() : ""), nullToEmpty(address.map(Address::getZip).orElse("")),
nullToEmpty(address.isPresent() ? address.get().getCountryCode() : ""), nullToEmpty(address.map(Address::getCountryCode).orElse("")),
nullToEmpty(registrant.getEmailAddress()), nullToEmpty(registrant.getEmailAddress()),
nullToEmpty(phoneNumber.isPresent() ? phoneNumber.get().toPhoneString() : ""), nullToEmpty(phoneNumber.map(PhoneNumber::toPhoneString).orElse("")),
"", "",
domainApplication.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise")); domainApplication.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise"));
} }
@ -234,8 +235,7 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
Optional.ofNullable( Optional.ofNullable(
Optional.ofNullable(registrar.getLocalizedAddress()) Optional.ofNullable(registrar.getLocalizedAddress())
.orElse(registrar.getInternationalizedAddress())); .orElse(registrar.getInternationalizedAddress()));
List<String> street = List<String> street = address.map(Address::getStreet).orElseGet(ImmutableList::of);
address.isPresent() ? address.get().getStreet() : ImmutableList.of();
// Each line containing the registrar of an auction participant has the following format: // Each line containing the registrar of an auction participant has the following format:
// //
@ -244,14 +244,16 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
// Registrar Country|Registrar Email|Registrar Telephone // Registrar Country|Registrar Email|Registrar Telephone
return Joiner.on('|').join(ImmutableList.of( return Joiner.on('|').join(ImmutableList.of(
registrar.getClientId(), registrar.getClientId(),
contact.isPresent() ? contact.get().getName() : "N/A", contact.map(RegistrarContact::getName).orElse("N/A"),
nullToEmpty(registrar.getRegistrarName()), nullToEmpty(registrar.getRegistrarName()),
Iterables.getFirst(street, ""), Iterables.getFirst(street, ""),
Iterables.get(street, 1, ""), Iterables.get(street, 1, ""),
address.isPresent() ? nullToEmpty(address.get().getCity()) : "", address.map(registrarAddress -> nullToEmpty(registrarAddress.getCity())).orElse(""),
address.isPresent() ? nullToEmpty(address.get().getState()) : "", address.map(registrarAddress1 ->
address.isPresent() ? nullToEmpty(address.get().getZip()) : "", nullToEmpty(registrarAddress1.getState())).orElse(""),
address.isPresent() ? nullToEmpty(address.get().getCountryCode()) : "", address.map(registrarAddress2 -> nullToEmpty(registrarAddress2.getZip())).orElse(""),
address.map(registrarAddress3 ->
nullToEmpty(registrarAddress3.getCountryCode())).orElse(""),
nullToEmpty(registrar.getEmailAddress()), nullToEmpty(registrar.getEmailAddress()),
nullToEmpty(registrar.getPhoneNumber()))); nullToEmpty(registrar.getPhoneNumber())));
} }

View file

@ -54,7 +54,7 @@ public abstract class MutatingCommand extends ConfirmingCommand implements Remot
private static class EntityChange { private static class EntityChange {
/** The possible types of mutation that can be performed on an entity. */ /** The possible types of mutation that can be performed on an entity. */
public static enum ChangeType { public enum ChangeType {
CREATE, DELETE, UPDATE; CREATE, DELETE, UPDATE;
/** Return the ChangeType corresponding to the given combination of version existences. */ /** Return the ChangeType corresponding to the given combination of version existences. */

View file

@ -40,14 +40,14 @@ enum RegistryToolEnvironment {
private final RegistryEnvironment actualEnvironment; private final RegistryEnvironment actualEnvironment;
private final ImmutableMap<String, String> extraProperties; private final ImmutableMap<String, String> extraProperties;
private RegistryToolEnvironment( RegistryToolEnvironment(
RegistryEnvironment actualEnvironment, RegistryEnvironment actualEnvironment,
ImmutableMap<String, String> extraProperties) { ImmutableMap<String, String> extraProperties) {
this.actualEnvironment = actualEnvironment; this.actualEnvironment = actualEnvironment;
this.extraProperties = extraProperties; this.extraProperties = extraProperties;
} }
private RegistryToolEnvironment(RegistryEnvironment actualEnvironment) { RegistryToolEnvironment(RegistryEnvironment actualEnvironment) {
this(actualEnvironment, ImmutableMap.of()); this(actualEnvironment, ImmutableMap.of());
} }

View file

@ -27,7 +27,7 @@ public enum EppResourceTypeParameter {
private final Class<? extends EppResource> type; private final Class<? extends EppResource> type;
private EppResourceTypeParameter(Class<? extends EppResource> type) { EppResourceTypeParameter(Class<? extends EppResource> type) {
this.type = type; this.type = type;
} }

View file

@ -24,11 +24,11 @@ public interface RequestStatusChecker extends Serializable {
* *
* <p>Multiple calls must return the same value during the same Request. * <p>Multiple calls must return the same value during the same Request.
*/ */
public String getLogId(); String getLogId();
/** /**
* Returns true if the given request is currently running. * Returns true if the given request is currently running.
*/ */
public boolean isRunning(String requestLogId); boolean isRunning(String requestLogId);
} }

View file

@ -39,7 +39,7 @@ public class Retrier implements Serializable {
private final int attempts; private final int attempts;
/** Holds functions to call whenever the code being retried fails. */ /** Holds functions to call whenever the code being retried fails. */
public static interface FailureReporter { public interface FailureReporter {
/** /**
* Called after a retriable failure happened. * Called after a retriable failure happened.
@ -48,7 +48,7 @@ public class Retrier implements Serializable {
* *
* <p>Not called at all if the retrier succeeded on its first attempt. * <p>Not called at all if the retrier succeeded on its first attempt.
*/ */
public void beforeRetry(Throwable thrown, int failures, int maxAttempts); void beforeRetry(Throwable thrown, int failures, int maxAttempts);
/** /**
* Called after a a non-retriable error. * Called after a a non-retriable error.
@ -58,7 +58,7 @@ public class Retrier implements Serializable {
* *
* <p>Not called at all if the retrier succeeds. * <p>Not called at all if the retrier succeeds.
*/ */
public void afterFinalFailure(Throwable thrown, int failures); void afterFinalFailure(Throwable thrown, int failures);
} }
@Inject @Inject

View file

@ -33,7 +33,7 @@ public final class TokenUtils {
private final String prefix; private final String prefix;
private final int length; private final int length;
private TokenType(String prefix, int length) { TokenType(String prefix, int length) {
this.prefix = prefix; this.prefix = prefix;
this.length = length; this.length = length;
} }

View file

@ -101,7 +101,7 @@ public class TypeUtils {
} }
/** Returns a predicate that tests whether classes are annotated with the given annotation. */ /** Returns a predicate that tests whether classes are annotated with the given annotation. */
public static final Predicate<Class<?>> hasAnnotation( public static Predicate<Class<?>> hasAnnotation(
final Class<? extends Annotation> annotation) { final Class<? extends Annotation> annotation) {
return clazz -> clazz.isAnnotationPresent(annotation); return clazz -> clazz.isAnnotationPresent(annotation);
} }

View file

@ -25,7 +25,7 @@ public interface VoidCallable {
void call() throws Exception; void call() throws Exception;
/** Returns the VoidCallable as a {@link Callable} that returns null. */ /** Returns the VoidCallable as a {@link Callable} that returns null. */
public default Callable<Void> asCallable() { default Callable<Void> asCallable() {
return () -> { return () -> {
call(); call();
return null; return null;

View file

@ -95,10 +95,10 @@ final class DomainWhoisResponse extends WhoisResponseImpl {
// is an abuse contact, we can get an email address from it. // is an abuse contact, we can get an email address from it.
.emitFieldIfDefined( .emitFieldIfDefined(
"Registrar Abuse Contact Email", "Registrar Abuse Contact Email",
abuseContact.isPresent() ? abuseContact.get().getEmailAddress() : null) abuseContact.map(RegistrarContact::getEmailAddress).orElse(null))
.emitFieldIfDefined( .emitFieldIfDefined(
"Registrar Abuse Contact Phone", "Registrar Abuse Contact Phone",
abuseContact.isPresent() ? abuseContact.get().getPhoneNumber() : null) abuseContact.map(RegistrarContact::getPhoneNumber).orElse(null))
.emitStatusValues(domain.getStatusValues(), domain.getGracePeriods()) .emitStatusValues(domain.getStatusValues(), domain.getGracePeriods())
.emitContact("Registrant", domain.getRegistrant(), preferUnicode) .emitContact("Registrant", domain.getRegistrant(), preferUnicode)
.emitContact("Admin", getContactReference(Type.ADMIN), preferUnicode) .emitContact("Admin", getContactReference(Type.ADMIN), preferUnicode)
@ -123,7 +123,7 @@ final class DomainWhoisResponse extends WhoisResponseImpl {
private Key<ContactResource> getContactReference(final Type type) { private Key<ContactResource> getContactReference(final Type type) {
Optional<DesignatedContact> contactOfType = Optional<DesignatedContact> contactOfType =
domain.getContacts().stream().filter(d -> d.getType() == type).findFirst(); domain.getContacts().stream().filter(d -> d.getType() == type).findFirst();
return contactOfType.isPresent() ? contactOfType.get().getContactKey() : null; return contactOfType.map(DesignatedContact::getContactKey).orElse(null);
} }
/** Output emitter with logic for domains. */ /** Output emitter with logic for domains. */

View file

@ -37,7 +37,7 @@ public interface WhoisResponse {
/** A wrapper class for the plaintext response of a WHOIS command and its number of results. */ /** A wrapper class for the plaintext response of a WHOIS command and its number of results. */
@AutoValue @AutoValue
abstract static class WhoisResponseResults { abstract class WhoisResponseResults {
public abstract String plainTextOutput(); public abstract String plainTextOutput();
public abstract int numResults(); public abstract int numResults();

View file

@ -57,7 +57,7 @@ public class JaxbFragment<T> implements Serializable {
} }
/** Deserializes a JAXB element from xml bytes. */ /** Deserializes a JAXB element from xml bytes. */
private static <T> T unfreezeInstance(byte[] instanceData, Class<? extends Object> instanceType) private static <T> T unfreezeInstance(byte[] instanceData, Class<?> instanceType)
throws IOException { throws IOException {
try { try {
ByteArrayInputStream bin = new ByteArrayInputStream(instanceData); ByteArrayInputStream bin = new ByteArrayInputStream(instanceData);

View file

@ -110,7 +110,7 @@ public class MapreduceEntityCleanupActionTest
.setInput(input) .setInput(input)
.setMapper(new TestMapper()) .setMapper(new TestMapper())
.setReducer(new TestReducer()) .setReducer(new TestReducer())
.setOutput(new InMemoryOutput<String>()) .setOutput(new InMemoryOutput<>())
.setNumReducers(2) .setNumReducers(2)
.build(), .build(),
new MapReduceSettings.Builder().setWorkerQueueName(QUEUE_NAME).build()); new MapReduceSettings.Builder().setWorkerQueueName(QUEUE_NAME).build());

View file

@ -46,6 +46,7 @@ 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 java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Duration; import org.joda.time.Duration;
@ -429,9 +430,7 @@ public class DnsUpdateWriterTest {
private void assertThatUpdateAdds( private void assertThatUpdateAdds(
Update update, String resourceName, int recordType, String... resourceData) { Update update, String resourceName, int recordType, String... resourceData) {
ArrayList<String> expectedData = new ArrayList<>(); ArrayList<String> expectedData = new ArrayList<>();
for (String resourceDatum : resourceData) { Collections.addAll(expectedData, resourceData);
expectedData.add(resourceDatum);
}
ArrayList<String> actualData = new ArrayList<>(); ArrayList<String> actualData = new ArrayList<>();
for (Record record : findUpdateRecords(update, resourceName, recordType)) { for (Record record : findUpdateRecords(update, resourceName, recordType)) {

View file

@ -40,7 +40,6 @@ 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.FakeSleeper; import google.registry.testing.FakeSleeper;
import google.registry.testing.Lazies;
import google.registry.testing.TaskQueueHelper; import google.registry.testing.TaskQueueHelper;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.CapturingLogHandler; import google.registry.util.CapturingLogHandler;
@ -94,7 +93,7 @@ public class BigqueryPollJobActionTest {
action.enqueuer = ENQUEUER; action.enqueuer = ENQUEUER;
action.projectId = PROJECT_ID; action.projectId = PROJECT_ID;
action.jobId = JOB_ID; action.jobId = JOB_ID;
action.chainedQueueName = Lazies.of(CHAINED_QUEUE_NAME); action.chainedQueueName = () -> CHAINED_QUEUE_NAME;
Logger.getLogger(BigqueryPollJobAction.class.getName()).addHandler(logHandler); Logger.getLogger(BigqueryPollJobAction.class.getName()).addHandler(logHandler);
} }

View file

@ -53,7 +53,7 @@ interface EppTestComponent {
/** Module for injecting fakes and mocks. */ /** Module for injecting fakes and mocks. */
@Module @Module
static class FakesAndMocksModule { class FakesAndMocksModule {
private BigQueryMetricsEnqueuer metricsEnqueuer; private BigQueryMetricsEnqueuer metricsEnqueuer;
private DnsQueue dnsQueue; private DnsQueue dnsQueue;
@ -143,7 +143,7 @@ interface EppTestComponent {
} }
} }
public static class FakeServerTridProvider implements ServerTridProvider { class FakeServerTridProvider implements ServerTridProvider {
@Override @Override
public String createServerTrid() { public String createServerTrid() {

View file

@ -36,7 +36,6 @@ import google.registry.monitoring.whitebox.EppMetric;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.FakeClock; import google.registry.testing.FakeClock;
import google.registry.testing.FakeHttpSession; import google.registry.testing.FakeHttpSession;
import google.registry.testing.Providers;
import google.registry.testing.ShardableTestCase; import google.registry.testing.ShardableTestCase;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -74,7 +73,7 @@ public class FlowRunnerTest extends ShardableTestCase {
flowRunner.clientId = "TheRegistrar"; flowRunner.clientId = "TheRegistrar";
flowRunner.credentials = new PasswordOnlyTransportCredentials(); flowRunner.credentials = new PasswordOnlyTransportCredentials();
flowRunner.eppRequestSource = EppRequestSource.UNIT_TEST; flowRunner.eppRequestSource = EppRequestSource.UNIT_TEST;
flowRunner.flowProvider = Providers.<Flow>of(new TestCommandFlow()); flowRunner.flowProvider = TestCommandFlow::new;
flowRunner.flowClass = TestCommandFlow.class; flowRunner.flowClass = TestCommandFlow.class;
flowRunner.inputXmlBytes = "<xml/>".getBytes(UTF_8); flowRunner.inputXmlBytes = "<xml/>".getBytes(UTF_8);
flowRunner.isDryRun = false; flowRunner.isDryRun = false;

View file

@ -124,7 +124,6 @@ import google.registry.model.smd.SignedMarkRevocationList;
import google.registry.tmch.TmchCertificateAuthority; import google.registry.tmch.TmchCertificateAuthority;
import google.registry.tmch.TmchXmlSignature; import google.registry.tmch.TmchXmlSignature;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List; import java.util.List;
import org.joda.money.CurrencyUnit; import org.joda.money.CurrencyUnit;
import org.joda.money.Money; import org.joda.money.Money;
@ -205,7 +204,7 @@ public class DomainApplicationCreateFlowTest
// Check that the domain application was created and persisted with a history entry. // Check that the domain application was created and persisted with a history entry.
// We want the one with the newest creation time, but lacking an index we need this code. // We want the one with the newest creation time, but lacking an index we need this code.
List<DomainApplication> applications = ofy().load().type(DomainApplication.class).list(); List<DomainApplication> applications = ofy().load().type(DomainApplication.class).list();
Collections.sort(applications, comparing(DomainApplication::getCreationTime)); applications.sort(comparing(DomainApplication::getCreationTime));
assertAboutApplications().that(getLast(applications)) assertAboutApplications().that(getLast(applications))
.hasFullyQualifiedDomainName(getUniqueIdFromCommand()).and() .hasFullyQualifiedDomainName(getUniqueIdFromCommand()).and()
.hasNumEncodedSignedMarks(sunriseApplication ? 1 : 0).and() .hasNumEncodedSignedMarks(sunriseApplication ? 1 : 0).and()

View file

@ -393,12 +393,13 @@ public class OfyTest {
// Normal loading should come from the session cache and shouldn't reflect the mutation. // Normal loading should come from the session cache and shouldn't reflect the mutation.
assertThat(ofy().load().entity(someObject).now()).isEqualTo(someObject); assertThat(ofy().load().entity(someObject).now()).isEqualTo(someObject);
// Loading inside doWithFreshSessionCache() should reflect the mutation. // Loading inside doWithFreshSessionCache() should reflect the mutation.
boolean ran = ofy().doWithFreshSessionCache(new Work<Boolean>() { boolean ran =
@Override ofy()
public Boolean run() { .doWithFreshSessionCache(
assertThat(ofy().load().entity(someObject).now()).isEqualTo(modifiedObject); () -> {
return true; assertThat(ofy().load().entity(someObject).now()).isEqualTo(modifiedObject);
}}); return true;
});
assertThat(ran).isTrue(); assertThat(ran).isTrue();
// Test the normal loading again to verify that we've restored the original session unchanged. // Test the normal loading again to verify that we've restored the original session unchanged.
assertThat(ofy().load().entity(someObject).now()).isEqualTo(someObject); assertThat(ofy().load().entity(someObject).now()).isEqualTo(someObject);

View file

@ -23,7 +23,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMap;
import com.googlecode.objectify.Key; import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Work;
import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Entity;
import google.registry.model.common.CrossTldSingleton; import google.registry.model.common.CrossTldSingleton;
import google.registry.model.ofy.CommitLogManifest; import google.registry.model.ofy.CommitLogManifest;
@ -155,11 +154,7 @@ public class CommitLogRevisionsTranslatorFactoryTest {
save(new TestObject()); save(new TestObject());
clock.advanceBy(standardDays(1)); clock.advanceBy(standardDays(1));
com.google.appengine.api.datastore.Entity entity = com.google.appengine.api.datastore.Entity entity =
ofy().transactNewReadOnly(new Work<com.google.appengine.api.datastore.Entity>() { ofy().transactNewReadOnly(() -> ofy().save().toEntity(reload()));
@Override
public com.google.appengine.api.datastore.Entity run() {
return ofy().save().toEntity(reload());
}});
assertThat(entity.getProperties().keySet()).containsExactly("revisions.key", "revisions.value"); assertThat(entity.getProperties().keySet()).containsExactly("revisions.key", "revisions.value");
assertThat(entity.getProperties()).containsEntry( assertThat(entity.getProperties()).containsEntry(
"revisions.key", ImmutableList.of(START_TIME.toDate(), START_TIME.plusDays(1).toDate())); "revisions.key", ImmutableList.of(START_TIME.toDate(), START_TIME.plusDays(1).toDate()));
@ -176,11 +171,7 @@ public class CommitLogRevisionsTranslatorFactoryTest {
@Test @Test
public void testLoad_missingRevisionRawProperties_createsEmptyObject() throws Exception { public void testLoad_missingRevisionRawProperties_createsEmptyObject() throws Exception {
com.google.appengine.api.datastore.Entity entity = com.google.appengine.api.datastore.Entity entity =
ofy().transactNewReadOnly(new Work<com.google.appengine.api.datastore.Entity>() { ofy().transactNewReadOnly(() -> ofy().save().toEntity(new TestObject()));
@Override
public com.google.appengine.api.datastore.Entity run() {
return ofy().save().toEntity(new TestObject());
}});
entity.removeProperty("revisions.key"); entity.removeProperty("revisions.key");
entity.removeProperty("revisions.value"); entity.removeProperty("revisions.value");
TestObject object = ofy().load().fromEntity(entity); TestObject object = ofy().load().fromEntity(entity);

View file

@ -65,7 +65,7 @@ public class StatusValueAdapterTest {
.build()), .build()),
ValidationMode.LENIENT), ValidationMode.LENIENT),
UTF_8); UTF_8);
assertThat(marshalled.toString()).contains("<host:status s=\"clientUpdateProhibited\"/>"); assertThat(marshalled).contains("<host:status s=\"clientUpdateProhibited\"/>");
} }
private StatusValue unmarshal(String statusValueXml) throws Exception { private StatusValue unmarshal(String statusValueXml) throws Exception {

View file

@ -46,7 +46,7 @@ import java.util.logging.Logger;
/** A sample application which uses the Metrics API to count sheep while sleeping. */ /** A sample application which uses the Metrics API to count sheep while sleeping. */
public final class SheepCounterExample { public final class SheepCounterExample {
/** /*
* The code below for using a custom {@link LogManager} is only necessary to enable logging at JVM * The code below for using a custom {@link LogManager} is only necessary to enable logging at JVM
* shutdown to show the shutdown logs of {@link MetricReporter} in this small standalone * shutdown to show the shutdown logs of {@link MetricReporter} in this small standalone
* application. * application.

View file

@ -58,7 +58,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
@ -172,14 +171,7 @@ public class StackdriverWriterTest {
@Test @Test
public void testWrite_invalidMetricType_throwsException() throws Exception { public void testWrite_invalidMetricType_throwsException() throws Exception {
when(metric.getValueClass()) when(metric.getValueClass()).thenAnswer((Answer<Class<?>>) invocation -> Object.class);
.thenAnswer(
new Answer<Class<?>>() {
@Override
public Class<?> answer(InvocationOnMock invocation) throws Throwable {
return Object.class;
}
});
StackdriverWriter writer = StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);

View file

@ -75,15 +75,9 @@ public class RdapSearchActionTestCase {
.setRequestMethod(requestMethod) .setRequestMethod(requestMethod)
.setStatusCode(metricStatusCode) .setStatusCode(metricStatusCode)
.setIncompletenessWarningType(incompletenessWarningType); .setIncompletenessWarningType(incompletenessWarningType);
if (numDomainsRetrieved.isPresent()) { numDomainsRetrieved.ifPresent(builder::setNumDomainsRetrieved);
builder.setNumDomainsRetrieved(numDomainsRetrieved.get()); numHostsRetrieved.ifPresent(builder::setNumHostsRetrieved);
} numContactsRetrieved.ifPresent(builder::setNumContactsRetrieved);
if (numHostsRetrieved.isPresent()) {
builder.setNumHostsRetrieved(numHostsRetrieved.get());
}
if (numContactsRetrieved.isPresent()) {
builder.setNumContactsRetrieved(numContactsRetrieved.get());
}
verify(rdapMetrics).updateMetrics(builder.build()); verify(rdapMetrics).updateMetrics(builder.build());
} }
} }

View file

@ -35,7 +35,6 @@ import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.GcsTestingUtils; import google.registry.testing.GcsTestingUtils;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.Providers;
import google.registry.testing.ShardableTestCase; import google.registry.testing.ShardableTestCase;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -104,9 +103,9 @@ public class BrdaCopyActionTest extends ShardableTestCase {
public void before() throws Exception { public void before() throws Exception {
action.gcsUtils = gcsUtils; action.gcsUtils = gcsUtils;
action.ghostryde = new Ghostryde(23); action.ghostryde = new Ghostryde(23);
action.pgpCompressionFactory = new RydePgpCompressionOutputStreamFactory(Providers.of(1024)); action.pgpCompressionFactory = new RydePgpCompressionOutputStreamFactory(() -> 1024);
action.pgpEncryptionFactory = new RydePgpEncryptionOutputStreamFactory(Providers.of(1024)); action.pgpEncryptionFactory = new RydePgpEncryptionOutputStreamFactory(() -> 1024);
action.pgpFileFactory = new RydePgpFileOutputStreamFactory(Providers.of(1024)); action.pgpFileFactory = new RydePgpFileOutputStreamFactory(() -> 1024);
action.pgpSigningFactory = new RydePgpSigningOutputStreamFactory(); action.pgpSigningFactory = new RydePgpSigningOutputStreamFactory();
action.tarFactory = new RydeTarOutputStreamFactory(); action.tarFactory = new RydeTarOutputStreamFactory();
action.tld = "lol"; action.tld = "lol";

View file

@ -69,7 +69,6 @@ import google.registry.testing.FakeSleeper;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.IoSpyRule; import google.registry.testing.IoSpyRule;
import google.registry.testing.Lazies; import google.registry.testing.Lazies;
import google.registry.testing.Providers;
import google.registry.testing.TaskQueueHelper.TaskMatcher; import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.testing.sftp.SftpServerRule; import google.registry.testing.sftp.SftpServerRule;
import google.registry.util.Retrier; import google.registry.util.Retrier;
@ -156,21 +155,21 @@ public class RdeUploadActionTest {
}}; }};
private final RydePgpFileOutputStreamFactory literalFactory = private final RydePgpFileOutputStreamFactory literalFactory =
new RydePgpFileOutputStreamFactory(Providers.of(BUFFER_SIZE)) { new RydePgpFileOutputStreamFactory(() -> BUFFER_SIZE) {
@Override @Override
public RydePgpFileOutputStream create(OutputStream os, DateTime modified, String filename) { public RydePgpFileOutputStream create(OutputStream os, DateTime modified, String filename) {
return ioSpy.register(super.create(os, modified, filename)); return ioSpy.register(super.create(os, modified, filename));
}}; }};
private final RydePgpEncryptionOutputStreamFactory encryptFactory = private final RydePgpEncryptionOutputStreamFactory encryptFactory =
new RydePgpEncryptionOutputStreamFactory(Providers.of(BUFFER_SIZE)) { new RydePgpEncryptionOutputStreamFactory(() -> BUFFER_SIZE) {
@Override @Override
public RydePgpEncryptionOutputStream create(OutputStream os, PGPPublicKey publicKey) { public RydePgpEncryptionOutputStream create(OutputStream os, PGPPublicKey publicKey) {
return ioSpy.register(super.create(os, publicKey)); return ioSpy.register(super.create(os, publicKey));
}}; }};
private final RydePgpCompressionOutputStreamFactory compressFactory = private final RydePgpCompressionOutputStreamFactory compressFactory =
new RydePgpCompressionOutputStreamFactory(Providers.of(BUFFER_SIZE)) { new RydePgpCompressionOutputStreamFactory(() -> BUFFER_SIZE) {
@Override @Override
public RydePgpCompressionOutputStream create(OutputStream os) { public RydePgpCompressionOutputStream create(OutputStream os) {
return ioSpy.register(super.create(os)); return ioSpy.register(super.create(os));
@ -190,10 +189,11 @@ public class RdeUploadActionTest {
action.gcsUtils = new GcsUtils(gcsService, BUFFER_SIZE); action.gcsUtils = new GcsUtils(gcsService, BUFFER_SIZE);
action.ghostryde = new Ghostryde(BUFFER_SIZE); action.ghostryde = new Ghostryde(BUFFER_SIZE);
action.lazyJsch = action.lazyJsch =
Lazies.of( () ->
JSchModule.provideJSch( JSchModule.provideJSch(
"user@ignored", "user@ignored",
keyring.getRdeSshClientPrivateKey(), keyring.getRdeSshClientPublicKey())); keyring.getRdeSshClientPrivateKey(),
keyring.getRdeSshClientPublicKey());
action.jschSshSessionFactory = new JSchSshSessionFactory(standardSeconds(3)); action.jschSshSessionFactory = new JSchSshSessionFactory(standardSeconds(3));
action.response = response; action.response = response;
action.pgpCompressionFactory = compressFactory; action.pgpCompressionFactory = compressFactory;

View file

@ -26,7 +26,6 @@ import google.registry.keyring.api.Keyring;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderRule;
import google.registry.testing.FakeKeyringModule; import google.registry.testing.FakeKeyringModule;
import google.registry.testing.GpgSystemCommandRule; import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.Providers;
import google.registry.testing.ShardableTestCase; import google.registry.testing.ShardableTestCase;
import google.registry.util.FormattingLogger; import google.registry.util.FormattingLogger;
import java.io.File; import java.io.File;
@ -97,11 +96,11 @@ public class RydeGpgIntegrationTest extends ShardableTestCase {
RydeTarOutputStreamFactory tarFactory = RydeTarOutputStreamFactory tarFactory =
new RydeTarOutputStreamFactory(); new RydeTarOutputStreamFactory();
RydePgpFileOutputStreamFactory pgpFileFactory = RydePgpFileOutputStreamFactory pgpFileFactory =
new RydePgpFileOutputStreamFactory(Providers.of(bufSize.get())); new RydePgpFileOutputStreamFactory(bufSize::get);
RydePgpEncryptionOutputStreamFactory pgpEncryptionFactory = RydePgpEncryptionOutputStreamFactory pgpEncryptionFactory =
new RydePgpEncryptionOutputStreamFactory(Providers.of(bufSize.get())); new RydePgpEncryptionOutputStreamFactory(bufSize::get);
RydePgpCompressionOutputStreamFactory pgpCompressionFactory = RydePgpCompressionOutputStreamFactory pgpCompressionFactory =
new RydePgpCompressionOutputStreamFactory(Providers.of(bufSize.get())); new RydePgpCompressionOutputStreamFactory(bufSize::get);
RydePgpSigningOutputStreamFactory pgpSigningFactory = RydePgpSigningOutputStreamFactory pgpSigningFactory =
new RydePgpSigningOutputStreamFactory(); new RydePgpSigningOutputStreamFactory();

View file

@ -194,8 +194,7 @@ public class RdeContactReaderTest {
oout.writeObject(reader); oout.writeObject(reader);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream oin = new ObjectInputStream(bin); ObjectInputStream oin = new ObjectInputStream(bin);
RdeContactReader result = (RdeContactReader) oin.readObject(); return (RdeContactReader) oin.readObject();
return result;
} }
/** Verifies that contact id and ROID match expected values */ /** Verifies that contact id and ROID match expected values */

View file

@ -190,8 +190,7 @@ public class RdeHostReaderTest {
oout.writeObject(reader); oout.writeObject(reader);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream oin = new ObjectInputStream(bin); ObjectInputStream oin = new ObjectInputStream(bin);
RdeHostReader result = (RdeHostReader) oin.readObject(); return (RdeHostReader) oin.readObject();
return result;
} }
/** Verifies that domain name and ROID match expected values */ /** Verifies that domain name and ROID match expected values */

View file

@ -121,7 +121,7 @@ public final class TestServer {
* main event loop, for post-request processing. * main event loop, for post-request processing.
*/ */
public void ping() { public void ping() {
requestQueue.add(new FutureTask<Void>(doNothing(), null)); requestQueue.add(new FutureTask<>(doNothing(), null));
} }
/** Stops the HTTP server. */ /** Stops the HTTP server. */

View file

@ -298,12 +298,7 @@ public final class AppEngineRule extends ExternalResource {
} }
if (clock != null) { if (clock != null) {
helper.setClock(new com.google.appengine.tools.development.Clock() { helper.setClock(() -> clock.nowUtc().getMillis());
@Override
public long getCurrentTime() {
return clock.nowUtc().getMillis();
}
});
} }
if (withLocalModules) { if (withLocalModules) {

View file

@ -56,7 +56,6 @@ 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 com.googlecode.objectify.VoidWork; import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.Work;
import com.googlecode.objectify.cmd.Saver; import com.googlecode.objectify.cmd.Saver;
import google.registry.dns.writer.VoidDnsWriter; import google.registry.dns.writer.VoidDnsWriter;
import google.registry.model.Buildable; import google.registry.model.Buildable;
@ -1030,11 +1029,7 @@ public class DatastoreHelper {
/** Force the create and update timestamps to get written into the resource. **/ /** Force the create and update timestamps to get written into the resource. **/
public static <R> R cloneAndSetAutoTimestamps(final R resource) { public static <R> R cloneAndSetAutoTimestamps(final R resource) {
return ofy().transact(new Work<R>() { return ofy().transact(() -> ofy().load().fromEntity(ofy().save().toEntity(resource)));
@Override
public R run() {
return ofy().load().fromEntity(ofy().save().toEntity(resource));
}});
} }
/** Returns the entire map of {@link PremiumListEntry}s for the given {@link PremiumList}. */ /** Returns the entire map of {@link PremiumListEntry}s for the given {@link PremiumList}. */

View file

@ -60,16 +60,16 @@ public class DeterministicStringGenerator extends StringGenerator {
@Override @Override
public String createString(int length) { public String createString(int length) {
checkArgument(length > 0, "String length must be positive."); checkArgument(length > 0, "String length must be positive.");
String password = ""; StringBuilder password = new StringBuilder();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
password += iterator.next(); password.append(iterator.next());
} }
switch (rule) { switch (rule) {
case PREPEND_COUNTER: case PREPEND_COUNTER:
return String.format("%04d_%s", counter++, password); return String.format("%04d_%s", counter++, password.toString());
case DEFAULT: case DEFAULT:
default: default:
return password; return password.toString();
} }
} }

View file

@ -76,8 +76,6 @@ public final class FakeKeyringModule {
PgpHelper.lookupKeyPair(publics, privates, SIGNING_KEY_EMAIL, SIGN); PgpHelper.lookupKeyPair(publics, privates, SIGNING_KEY_EMAIL, SIGN);
final PGPPublicKey rdeReceiverKey = final PGPPublicKey rdeReceiverKey =
PgpHelper.lookupPublicKey(publics, RECEIVER_KEY_EMAIL, ENCRYPT); PgpHelper.lookupPublicKey(publics, RECEIVER_KEY_EMAIL, ENCRYPT);
final PGPKeyPair brdaSigningKey = rdeSigningKey;
final PGPPublicKey brdaReceiverKey = rdeReceiverKey;
final String sshPublic = final String sshPublic =
readResourceUtf8(FakeKeyringModule.class, "testdata/registry-unittest.id_rsa.pub"); readResourceUtf8(FakeKeyringModule.class, "testdata/registry-unittest.id_rsa.pub");
final String sshPrivate = final String sshPrivate =
@ -141,12 +139,12 @@ public final class FakeKeyringModule {
@Override @Override
public PGPKeyPair getBrdaSigningKey() { public PGPKeyPair getBrdaSigningKey() {
return brdaSigningKey; return rdeSigningKey;
} }
@Override @Override
public PGPPublicKey getBrdaReceiverKey() { public PGPPublicKey getBrdaReceiverKey() {
return brdaReceiverKey; return rdeReceiverKey;
} }
@Override @Override

View file

@ -56,7 +56,7 @@ public final class FullFieldsTestEntityHelper {
public static Registrar makeRegistrar( public static Registrar makeRegistrar(
String clientId, String registrarName, Registrar.State state, Long ianaIdentifier) { String clientId, String registrarName, Registrar.State state, Long ianaIdentifier) {
Registrar registrar = new Registrar.Builder() return new Registrar.Builder()
.setClientId(clientId) .setClientId(clientId)
.setRegistrarName(registrarName) .setRegistrarName(registrarName)
.setType(Registrar.Type.REAL) .setType(Registrar.Type.REAL)
@ -82,7 +82,6 @@ public final class FullFieldsTestEntityHelper {
.setWhoisServer("whois.example.com") .setWhoisServer("whois.example.com")
.setReferralUrl("http://www.example.com") .setReferralUrl("http://www.example.com")
.build(); .build();
return registrar;
} }
public static ImmutableList<RegistrarContact> makeRegistrarContacts(Registrar registrar) { public static ImmutableList<RegistrarContact> makeRegistrarContacts(Registrar registrar) {

View file

@ -23,10 +23,6 @@ public final class Lazies {
* Returns a {@link Lazy} that supplies a constant value. * Returns a {@link Lazy} that supplies a constant value.
*/ */
public static <T> Lazy<T> of(final T instance) { public static <T> Lazy<T> of(final T instance) {
return new Lazy<T>() { return () -> instance;
@Override
public T get() {
return instance;
}};
} }
} }

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