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. */
@Qualifier
@Documented
public static @interface Backups {}
public @interface Backups {}
/** Number of threads in the threaded executor. */
private static final int NUM_THREADS = 10;

View file

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

View file

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

View file

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

View file

@ -136,10 +136,9 @@ public class VerifyEntityIntegrityAction implements Runnable {
getInputs())));
}
private static ImmutableSet<Input<? extends Object>> getInputs() {
ImmutableSet.Builder<Input<? extends Object>> builder =
new ImmutableSet.Builder<Input<? extends Object>>()
.add(EppResourceInputs.createIndexInput());
private static ImmutableSet<Input<?>> getInputs() {
ImmutableSet.Builder<Input<?>> builder =
new ImmutableSet.Builder<Input<?>>().add(EppResourceInputs.createIndexInput());
RESOURCE_CLASSES
.stream()
.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
* for all EppResources, to check {@link EppResourceIndex} constraints.
*/
private static enum EntityKind {
private enum EntityKind {
DOMAIN,
APPLICATION,
CONTACT,

View file

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

View file

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

View file

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

View file

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

View file

@ -122,7 +122,7 @@ public interface FlowComponent {
/** Module to delegate injection of a desired {@link Flow}. */
@Module
static class FlowComponentModule {
class FlowComponentModule {
// 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.
// TODO(b/29874464): fix this in a cleaner way.

View file

@ -14,6 +14,7 @@
package google.registry.flows;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.io.BaseEncoding.base64;
import static google.registry.xml.XmlTransformer.prettyPrint;
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.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import google.registry.flows.FlowModule.ClientId;
import google.registry.flows.FlowModule.InputXml;
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
* needs to be roughly correct.
*/
private static final Optional<String> extractTld(String domainName) {
private static Optional<String> extractTld(String domainName) {
int index = domainName.indexOf('.');
return index == -1
? Optional.empty()
@ -116,22 +118,19 @@ public class FlowReporter {
* 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).
*/
public static final ImmutableSet<String> extractTlds(Iterable<String> domainNames) {
ImmutableSet.Builder<String> set = new ImmutableSet.Builder<>();
for (String domainName : domainNames) {
Optional<String> extractedTld = extractTld(domainName);
if (extractedTld.isPresent()) {
set.add(extractedTld.get());
}
}
return set.build();
public static ImmutableSet<String> extractTlds(Iterable<String> domainNames) {
return Streams.stream(domainNames)
.map(FlowReporter::extractTld)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toImmutableSet());
}
/**
* Returns the ICANN activity report field for the given flow class, or the empty string if no
* 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);
if (reportingSpec != null) {
return reportingSpec.value().getFieldName();

View file

@ -24,5 +24,5 @@ import google.registry.model.eppcommon.Trid;
public interface ServerTridProvider {
/** 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;
/** Registrar password is incorrect. */
static class BadRegistrarPasswordException extends AuthenticationErrorException {
class BadRegistrarPasswordException extends AuthenticationErrorException {
public BadRegistrarPasswordException() {
super("Registrar password is incorrect");
}

View file

@ -110,7 +110,7 @@ public class AsyncFlowMetrics {
private final String metricLabelValue;
private OperationType(String metricLabelValue) {
OperationType(String metricLabelValue) {
this.metricLabelValue = metricLabelValue;
}
@ -135,7 +135,7 @@ public class AsyncFlowMetrics {
private final String metricLabelValue;
private OperationResult(String metricLabelValue) {
OperationResult(String 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
// delete it. Otherwise save it with the new end time.
if (isAtOrAfter(updatedAutorenewPollMessage.getEventTime(), newEndTime)) {
if (autorenewPollMessage.isPresent()) {
ofy().delete().entity(autorenewPollMessage.get());
}
autorenewPollMessage.ifPresent(autorenew -> ofy().delete().entity(autorenew));
} else {
ofy().save().entity(updatedAutorenewPollMessage);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -25,7 +25,7 @@ import java.util.Set;
public interface GroupsConnection {
/** The role of a member in a group. */
public enum Role {
enum Role {
MEMBER,
MANAGER,
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
* 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
* 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
* 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
@ -57,5 +57,5 @@ public interface GroupsConnection {
* including permissions on who is able to join). The configured admin owner for the Google App is
* 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}. */
@Qualifier
@Documented
public static @interface Key {
public @interface Key {
String value();
}

View file

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

View file

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

View file

@ -33,7 +33,7 @@ public interface Buildable {
*
* <p>This can be used without implementing {@link Buildable}.
*/
public abstract static class Builder<S> {
abstract class Builder<S> {
private S instance;
@ -77,7 +77,7 @@ public interface Buildable {
}
/** 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(S instance) {
@ -100,7 +100,7 @@ public interface Buildable {
*
* @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. */
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. */
public interface ResourceWithTransferData {
public TransferData getTransferData();
TransferData getTransferData();
/**
* The time that this resource was last 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. */
public interface BuilderWithTransferData<B extends BuilderWithTransferData<B>> {
public B setTransferData(TransferData transferData);
B setTransferData(TransferData transferData);
/** Set the time when this resource was transferred. */
public B setLastTransferTime(DateTime lastTransferTime);
B setLastTransferTime(DateTime lastTransferTime);
}
/** Abstract builder for {@link EppResource} types. */

View file

@ -66,7 +66,7 @@ public final class EppResourceUtils {
/** Helper to call {@link EppResource#cloneProjectedAtTime} without warnings. */
@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);
}

View file

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

View file

@ -30,7 +30,7 @@ public @interface NotBackedUp {
Reason reason();
/** 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. */
TRANSIENT,

View file

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

View file

@ -40,7 +40,7 @@ public class EntityGroupRoot extends BackupGroupRoot {
private String id;
/** 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");
}
}

View file

@ -67,7 +67,7 @@ public class DomainCommand {
*/
public interface CreateOrUpdate<T extends CreateOrUpdate<T>> extends SingleResourceCommand {
/** 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"}. */

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.
*/
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
* 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.
*/
private static final ImmutableMap<String, LaunchPhase> initEnumMapping() {
private static ImmutableMap<String, LaunchPhase> initEnumMapping() {
ImmutableMap.Builder<String, LaunchPhase> builder = new ImmutableMap.Builder<>();
for (Entry<String, LaunchPhase> entry : getTypesafeEnumMapping(LaunchPhase.class).entrySet()) {
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 =
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;
@SafeVarargs
private AllowedOn(Class<? extends EppResource>... classes) {
AllowedOn(Class<? extends EppResource>... classes) {
this.classes = ImmutableSet.copyOf(classes);
}
}
private StatusValue(AllowedOn allowedOn) {
StatusValue(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
* do that since it's "name" field is overloaded with a "hosts" attribute.
*/
public interface SingleResourceCommand extends ResourceCommand {
interface SingleResourceCommand extends ResourceCommand {
String getTargetId();
AuthInfo getAuthInfo();
@ -50,7 +50,7 @@ public interface ResourceCommand {
/** Abstract implementation of {@link ResourceCommand}. */
@XmlTransient
public abstract static class AbstractSingleResourceCommand extends ImmutableObject
abstract class AbstractSingleResourceCommand extends ImmutableObject
implements SingleResourceCommand {
@XmlElements({
@XmlElement(name = "id"),
@ -70,7 +70,7 @@ public interface ResourceCommand {
/** A check command for an {@link EppResource}. */
@XmlTransient
public static class ResourceCheck extends ImmutableObject implements ResourceCommand {
class ResourceCheck extends ImmutableObject implements ResourceCommand {
@XmlElements({
@XmlElement(name = "id"),
@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. */
public interface ResourceCreateOrChange<B extends Builder<?>> {}
interface ResourceCreateOrChange<B extends Builder<?>> {}
/**
* An update command for an {@link EppResource}.
@ -91,7 +91,7 @@ public interface ResourceCommand {
* @param <C> the change type
*/
@XmlTransient
public abstract static class ResourceUpdate
abstract class ResourceUpdate
<A extends ResourceUpdate.AddRemove,
B extends EppResource.Builder<?, ?>,
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.
* 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.
*
* <p>Any implementation of PremiumPricingEngine is responsible for determining all of these.
*/
public static class DomainPrices {
class DomainPrices {
private boolean isPremium;
// 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 Type(Predicate<Long> ianaIdValidator) {
Type(Predicate<Long> ianaIdValidator) {
this.ianaIdValidator = ianaIdValidator;
}

View file

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

View file

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

View file

@ -39,7 +39,7 @@ public enum TransferStatus {
private final String message;
private TransferStatus(String message) {
TransferStatus(String 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 com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import google.registry.monitoring.metrics.Metric;
import google.registry.monitoring.metrics.MetricPoint;
import javax.annotation.Nullable;
@ -43,8 +44,11 @@ import javax.annotation.Nullable;
*/
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) {
return assertAbout(LongMetricSubject::new).that(metric);
}

View file

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

View file

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

View file

@ -161,7 +161,7 @@ public class RdapJsonFormatter {
/** Value as it appears in RDAP messages. */
private final String rfc7483String;
private RdapStatus(String rfc7483String) {
RdapStatus(String rfc7483String) {
this.rfc7483String = rfc7483String;
}
@ -217,7 +217,7 @@ public class RdapJsonFormatter {
/** Value as it appears in RDAP messages. */
final String rfc7483String;
private RdapEntityRole(String rfc7483String) {
RdapEntityRole(String rfc7483String) {
this.rfc7483String = rfc7483String;
}
}
@ -238,7 +238,7 @@ public class RdapJsonFormatter {
/** Value as it appears in RDAP messages. */
private final String rfc7483String;
private RdapEventAction(String rfc7483String) {
RdapEventAction(String rfc7483String) {
this.rfc7483String = rfc7483String;
}
@ -675,10 +675,8 @@ public class RdapJsonFormatter {
? union(contactResource.getStatusValues(), StatusValue.LINKED)
: contactResource.getStatusValues(),
contactResource.getDeletionTime().isBefore(now)));
if (contactType.isPresent()) {
jsonBuilder.put("roles",
ImmutableList.of(convertContactTypeToRdapRole(contactType.get())));
}
contactType.ifPresent(
type -> jsonBuilder.put("roles", ImmutableList.of(convertContactTypeToRdapRole(type))));
jsonBuilder.put("links",
ImmutableList.of(makeLink("entity", contactResource.getRepoId(), linkBase)));
// 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
*/
abstract void runWithLock(DateTime watermark) throws Exception;
void runWithLock(DateTime watermark) throws Exception;
}
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));
XjcIirdeaResponseElement response = XjcXmlTransformer.unmarshal(
XjcIirdeaResponseElement.class, new ByteArrayInputStream(responseBytes));
XjcIirdeaResult result = response.getResult();
return result;
return response.getResult();
}
private URL makeReportUrl(String tld, String id) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -121,8 +121,7 @@ public class IcannHttpReporter {
XjcIirdeaResponseElement response =
XjcXmlTransformer.unmarshal(
XjcIirdeaResponseElement.class, new ByteArrayInputStream(content));
XjcIirdeaResult result = response.getResult();
return result;
return response.getResult();
}
/** 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. */
private String constructTotalRow(List<Integer> totals) {
StringBuilder rowString = new StringBuilder("Totals,,");
rowString.append(
totals.stream().map(Object::toString).collect(Collectors.joining(",")));
return rowString.toString();
return "Totals,," + totals.stream().map(Object::toString).collect(Collectors.joining(","));
}
/**
@ -206,8 +203,8 @@ public class IcannReportingStager {
*
* <p>This discards the first object, which is assumed to be the TLD field.
* */
private String constructRow(Iterable<? extends Object> iterable) {
Iterator<? extends Object> rowIter = iterable.iterator();
private String constructRow(Iterable<?> iterable) {
Iterator<?> rowIter = iterable.iterator();
StringBuilder rowString = new StringBuilder();
// Skip the TLD column
rowIter.next();

View file

@ -26,7 +26,7 @@ import java.lang.annotation.Target;
public @interface Action {
/** 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. */
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.
*/
public boolean executeWithLocks(
boolean executeWithLocks(
final Callable<Void> callable,
@Nullable String tld,
Duration leaseLength,

View file

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

View file

@ -64,32 +64,27 @@ final class AllocateDomainCommand extends MutatingEppToolCommand {
@Override
protected String postExecute() throws Exception {
StringBuilder builder = new StringBuilder();
// Check to see that we allocated everything.
return builder
.append(
ofy()
.transactNewReadOnly(
() -> {
String failureMessage =
ofy()
.load()
.keys(applicationKeys)
.values()
.stream()
.map(
application ->
application.getApplicationStatus()
== ApplicationStatus.ALLOCATED
? null
: application.getFullyQualifiedDomainName())
.filter(Objects::nonNull)
.collect(joining("\n"));
return failureMessage.isEmpty()
? "ALL SUCCEEDED"
: addHeader("FAILURES", failureMessage);
}))
.toString();
return ofy()
.transactNewReadOnly(
() -> {
String failureMessage =
ofy()
.load()
.keys(applicationKeys)
.values()
.stream()
.map(
application ->
application.getApplicationStatus()
== ApplicationStatus.ALLOCATED
? null
: application.getFullyQualifiedDomainName())
.filter(Objects::nonNull)
.collect(joining("\n"));
return failureMessage.isEmpty()
? "ALL SUCCEEDED"
: addHeader("FAILURES", failureMessage);
});
}
/** 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
* 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();
ImmutableMap<String, ? extends Object> getParameterMap() {
ImmutableMap<String, ?> getParameterMap() {
return ImmutableMap.of();
}

View file

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

View file

@ -133,7 +133,7 @@ abstract class EppToolCommand extends ConfirmingCommand implements ServerSideCom
String prompt = addHeader("Command(s)", Joiner.on("\n").join(commands)
+ (force ? "" : addHeader("Dry Run", Joiner.on("\n").join(processCommands(true)))));
force = force || isDryRun();
return prompt.toString();
return prompt;
}
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.domain.DomainApplication;
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.RegistrarAddress;
import google.registry.model.registrar.RegistrarContact;
@ -190,9 +192,8 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
Optional.ofNullable(registrant.getInternationalizedPostalInfo())
.orElse(registrant.getLocalizedPostalInfo()));
Optional<ContactAddress> address =
Optional.ofNullable(postalInfo.isPresent() ? postalInfo.get().getAddress() : null);
List<String> street =
address.isPresent() ? address.get().getStreet() : ImmutableList.of();
Optional.ofNullable(postalInfo.map(PostalInfo::getAddress).orElse(null));
List<String> street = address.map(Address::getStreet).orElseGet(ImmutableList::of);
Optional<ContactPhoneNumber> phoneNumber = Optional.ofNullable(registrant.getVoiceNumber());
// Each line containing an auction participant has the following format:
@ -211,16 +212,16 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
? formatter.print(domainApplication.getLastEppUpdateTime())
: "",
domainApplication.getCurrentSponsorClientId(),
nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getName() : ""),
nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getOrg() : ""),
nullToEmpty(postalInfo.map(PostalInfo::getName).orElse("")),
nullToEmpty(postalInfo.map(PostalInfo::getOrg).orElse("")),
Iterables.getFirst(street, ""),
street.stream().skip(1).filter(Objects::nonNull).collect(joining(" ")),
nullToEmpty(address.isPresent() ? address.get().getCity() : ""),
nullToEmpty(address.isPresent() ? address.get().getState() : ""),
nullToEmpty(address.isPresent() ? address.get().getZip() : ""),
nullToEmpty(address.isPresent() ? address.get().getCountryCode() : ""),
nullToEmpty(address.map(Address::getCity).orElse("")),
nullToEmpty(address.map(Address::getState).orElse("")),
nullToEmpty(address.map(Address::getZip).orElse("")),
nullToEmpty(address.map(Address::getCountryCode).orElse("")),
nullToEmpty(registrant.getEmailAddress()),
nullToEmpty(phoneNumber.isPresent() ? phoneNumber.get().toPhoneString() : ""),
nullToEmpty(phoneNumber.map(PhoneNumber::toPhoneString).orElse("")),
"",
domainApplication.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise"));
}
@ -234,8 +235,7 @@ final class GenerateAuctionDataCommand implements RemoteApiCommand {
Optional.ofNullable(
Optional.ofNullable(registrar.getLocalizedAddress())
.orElse(registrar.getInternationalizedAddress()));
List<String> street =
address.isPresent() ? address.get().getStreet() : ImmutableList.of();
List<String> street = address.map(Address::getStreet).orElseGet(ImmutableList::of);
// 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
return Joiner.on('|').join(ImmutableList.of(
registrar.getClientId(),
contact.isPresent() ? contact.get().getName() : "N/A",
contact.map(RegistrarContact::getName).orElse("N/A"),
nullToEmpty(registrar.getRegistrarName()),
Iterables.getFirst(street, ""),
Iterables.get(street, 1, ""),
address.isPresent() ? nullToEmpty(address.get().getCity()) : "",
address.isPresent() ? nullToEmpty(address.get().getState()) : "",
address.isPresent() ? nullToEmpty(address.get().getZip()) : "",
address.isPresent() ? nullToEmpty(address.get().getCountryCode()) : "",
address.map(registrarAddress -> nullToEmpty(registrarAddress.getCity())).orElse(""),
address.map(registrarAddress1 ->
nullToEmpty(registrarAddress1.getState())).orElse(""),
address.map(registrarAddress2 -> nullToEmpty(registrarAddress2.getZip())).orElse(""),
address.map(registrarAddress3 ->
nullToEmpty(registrarAddress3.getCountryCode())).orElse(""),
nullToEmpty(registrar.getEmailAddress()),
nullToEmpty(registrar.getPhoneNumber())));
}

View file

@ -54,7 +54,7 @@ public abstract class MutatingCommand extends ConfirmingCommand implements Remot
private static class EntityChange {
/** The possible types of mutation that can be performed on an entity. */
public static enum ChangeType {
public enum ChangeType {
CREATE, DELETE, UPDATE;
/** 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 ImmutableMap<String, String> extraProperties;
private RegistryToolEnvironment(
RegistryToolEnvironment(
RegistryEnvironment actualEnvironment,
ImmutableMap<String, String> extraProperties) {
this.actualEnvironment = actualEnvironment;
this.extraProperties = extraProperties;
}
private RegistryToolEnvironment(RegistryEnvironment actualEnvironment) {
RegistryToolEnvironment(RegistryEnvironment actualEnvironment) {
this(actualEnvironment, ImmutableMap.of());
}

View file

@ -27,7 +27,7 @@ public enum EppResourceTypeParameter {
private final Class<? extends EppResource> type;
private EppResourceTypeParameter(Class<? extends EppResource> type) {
EppResourceTypeParameter(Class<? extends EppResource> 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.
*/
public String getLogId();
String getLogId();
/**
* 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;
/** Holds functions to call whenever the code being retried fails. */
public static interface FailureReporter {
public interface FailureReporter {
/**
* 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.
*/
public void beforeRetry(Throwable thrown, int failures, int maxAttempts);
void beforeRetry(Throwable thrown, int failures, int maxAttempts);
/**
* 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.
*/
public void afterFinalFailure(Throwable thrown, int failures);
void afterFinalFailure(Throwable thrown, int failures);
}
@Inject

View file

@ -33,7 +33,7 @@ public final class TokenUtils {
private final String prefix;
private final int length;
private TokenType(String prefix, int length) {
TokenType(String prefix, int length) {
this.prefix = prefix;
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. */
public static final Predicate<Class<?>> hasAnnotation(
public static Predicate<Class<?>> hasAnnotation(
final Class<? extends Annotation> annotation) {
return clazz -> clazz.isAnnotationPresent(annotation);
}

View file

@ -25,7 +25,7 @@ public interface VoidCallable {
void call() throws Exception;
/** Returns the VoidCallable as a {@link Callable} that returns null. */
public default Callable<Void> asCallable() {
default Callable<Void> asCallable() {
return () -> {
call();
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.
.emitFieldIfDefined(
"Registrar Abuse Contact Email",
abuseContact.isPresent() ? abuseContact.get().getEmailAddress() : null)
abuseContact.map(RegistrarContact::getEmailAddress).orElse(null))
.emitFieldIfDefined(
"Registrar Abuse Contact Phone",
abuseContact.isPresent() ? abuseContact.get().getPhoneNumber() : null)
abuseContact.map(RegistrarContact::getPhoneNumber).orElse(null))
.emitStatusValues(domain.getStatusValues(), domain.getGracePeriods())
.emitContact("Registrant", domain.getRegistrant(), preferUnicode)
.emitContact("Admin", getContactReference(Type.ADMIN), preferUnicode)
@ -123,7 +123,7 @@ final class DomainWhoisResponse extends WhoisResponseImpl {
private Key<ContactResource> getContactReference(final Type type) {
Optional<DesignatedContact> contactOfType =
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. */

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. */
@AutoValue
abstract static class WhoisResponseResults {
abstract class WhoisResponseResults {
public abstract String plainTextOutput();
public abstract int numResults();

View file

@ -57,7 +57,7 @@ public class JaxbFragment<T> implements Serializable {
}
/** 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 {
try {
ByteArrayInputStream bin = new ByteArrayInputStream(instanceData);

View file

@ -110,7 +110,7 @@ public class MapreduceEntityCleanupActionTest
.setInput(input)
.setMapper(new TestMapper())
.setReducer(new TestReducer())
.setOutput(new InMemoryOutput<String>())
.setOutput(new InMemoryOutput<>())
.setNumReducers(2)
.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.InjectRule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import org.joda.time.DateTime;
import org.joda.time.Duration;
@ -429,9 +430,7 @@ public class DnsUpdateWriterTest {
private void assertThatUpdateAdds(
Update update, String resourceName, int recordType, String... resourceData) {
ArrayList<String> expectedData = new ArrayList<>();
for (String resourceDatum : resourceData) {
expectedData.add(resourceDatum);
}
Collections.addAll(expectedData, resourceData);
ArrayList<String> actualData = new ArrayList<>();
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.FakeClock;
import google.registry.testing.FakeSleeper;
import google.registry.testing.Lazies;
import google.registry.testing.TaskQueueHelper;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.CapturingLogHandler;
@ -94,7 +93,7 @@ public class BigqueryPollJobActionTest {
action.enqueuer = ENQUEUER;
action.projectId = PROJECT_ID;
action.jobId = JOB_ID;
action.chainedQueueName = Lazies.of(CHAINED_QUEUE_NAME);
action.chainedQueueName = () -> CHAINED_QUEUE_NAME;
Logger.getLogger(BigqueryPollJobAction.class.getName()).addHandler(logHandler);
}

View file

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

View file

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

View file

@ -124,7 +124,6 @@ import google.registry.model.smd.SignedMarkRevocationList;
import google.registry.tmch.TmchCertificateAuthority;
import google.registry.tmch.TmchXmlSignature;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import org.joda.money.CurrencyUnit;
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.
// We want the one with the newest creation time, but lacking an index we need this code.
List<DomainApplication> applications = ofy().load().type(DomainApplication.class).list();
Collections.sort(applications, comparing(DomainApplication::getCreationTime));
applications.sort(comparing(DomainApplication::getCreationTime));
assertAboutApplications().that(getLast(applications))
.hasFullyQualifiedDomainName(getUniqueIdFromCommand()).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.
assertThat(ofy().load().entity(someObject).now()).isEqualTo(someObject);
// Loading inside doWithFreshSessionCache() should reflect the mutation.
boolean ran = ofy().doWithFreshSessionCache(new Work<Boolean>() {
@Override
public Boolean run() {
assertThat(ofy().load().entity(someObject).now()).isEqualTo(modifiedObject);
return true;
}});
boolean ran =
ofy()
.doWithFreshSessionCache(
() -> {
assertThat(ofy().load().entity(someObject).now()).isEqualTo(modifiedObject);
return true;
});
assertThat(ran).isTrue();
// Test the normal loading again to verify that we've restored the original session unchanged.
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.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Work;
import com.googlecode.objectify.annotation.Entity;
import google.registry.model.common.CrossTldSingleton;
import google.registry.model.ofy.CommitLogManifest;
@ -155,11 +154,7 @@ public class CommitLogRevisionsTranslatorFactoryTest {
save(new TestObject());
clock.advanceBy(standardDays(1));
com.google.appengine.api.datastore.Entity entity =
ofy().transactNewReadOnly(new Work<com.google.appengine.api.datastore.Entity>() {
@Override
public com.google.appengine.api.datastore.Entity run() {
return ofy().save().toEntity(reload());
}});
ofy().transactNewReadOnly(() -> ofy().save().toEntity(reload()));
assertThat(entity.getProperties().keySet()).containsExactly("revisions.key", "revisions.value");
assertThat(entity.getProperties()).containsEntry(
"revisions.key", ImmutableList.of(START_TIME.toDate(), START_TIME.plusDays(1).toDate()));
@ -176,11 +171,7 @@ public class CommitLogRevisionsTranslatorFactoryTest {
@Test
public void testLoad_missingRevisionRawProperties_createsEmptyObject() throws Exception {
com.google.appengine.api.datastore.Entity entity =
ofy().transactNewReadOnly(new Work<com.google.appengine.api.datastore.Entity>() {
@Override
public com.google.appengine.api.datastore.Entity run() {
return ofy().save().toEntity(new TestObject());
}});
ofy().transactNewReadOnly(() -> ofy().save().toEntity(new TestObject()));
entity.removeProperty("revisions.key");
entity.removeProperty("revisions.value");
TestObject object = ofy().load().fromEntity(entity);

View file

@ -65,7 +65,7 @@ public class StatusValueAdapterTest {
.build()),
ValidationMode.LENIENT),
UTF_8);
assertThat(marshalled.toString()).contains("<host:status s=\"clientUpdateProhibited\"/>");
assertThat(marshalled).contains("<host:status s=\"clientUpdateProhibited\"/>");
}
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. */
public final class SheepCounterExample {
/**
/*
* 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
* application.

View file

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

View file

@ -75,15 +75,9 @@ public class RdapSearchActionTestCase {
.setRequestMethod(requestMethod)
.setStatusCode(metricStatusCode)
.setIncompletenessWarningType(incompletenessWarningType);
if (numDomainsRetrieved.isPresent()) {
builder.setNumDomainsRetrieved(numDomainsRetrieved.get());
}
if (numHostsRetrieved.isPresent()) {
builder.setNumHostsRetrieved(numHostsRetrieved.get());
}
if (numContactsRetrieved.isPresent()) {
builder.setNumContactsRetrieved(numContactsRetrieved.get());
}
numDomainsRetrieved.ifPresent(builder::setNumDomainsRetrieved);
numHostsRetrieved.ifPresent(builder::setNumHostsRetrieved);
numContactsRetrieved.ifPresent(builder::setNumContactsRetrieved);
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.GcsTestingUtils;
import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.Providers;
import google.registry.testing.ShardableTestCase;
import java.io.File;
import java.io.FileNotFoundException;
@ -104,9 +103,9 @@ public class BrdaCopyActionTest extends ShardableTestCase {
public void before() throws Exception {
action.gcsUtils = gcsUtils;
action.ghostryde = new Ghostryde(23);
action.pgpCompressionFactory = new RydePgpCompressionOutputStreamFactory(Providers.of(1024));
action.pgpEncryptionFactory = new RydePgpEncryptionOutputStreamFactory(Providers.of(1024));
action.pgpFileFactory = new RydePgpFileOutputStreamFactory(Providers.of(1024));
action.pgpCompressionFactory = new RydePgpCompressionOutputStreamFactory(() -> 1024);
action.pgpEncryptionFactory = new RydePgpEncryptionOutputStreamFactory(() -> 1024);
action.pgpFileFactory = new RydePgpFileOutputStreamFactory(() -> 1024);
action.pgpSigningFactory = new RydePgpSigningOutputStreamFactory();
action.tarFactory = new RydeTarOutputStreamFactory();
action.tld = "lol";

View file

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

View file

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

View file

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

View file

@ -190,8 +190,7 @@ public class RdeHostReaderTest {
oout.writeObject(reader);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream oin = new ObjectInputStream(bin);
RdeHostReader result = (RdeHostReader) oin.readObject();
return result;
return (RdeHostReader) oin.readObject();
}
/** 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.
*/
public void ping() {
requestQueue.add(new FutureTask<Void>(doNothing(), null));
requestQueue.add(new FutureTask<>(doNothing(), null));
}
/** Stops the HTTP server. */

View file

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

View file

@ -56,7 +56,6 @@ import com.google.common.collect.Streams;
import com.google.common.net.InetAddresses;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.Work;
import com.googlecode.objectify.cmd.Saver;
import google.registry.dns.writer.VoidDnsWriter;
import google.registry.model.Buildable;
@ -1030,11 +1029,7 @@ public class DatastoreHelper {
/** Force the create and update timestamps to get written into the resource. **/
public static <R> R cloneAndSetAutoTimestamps(final R resource) {
return ofy().transact(new Work<R>() {
@Override
public R run() {
return ofy().load().fromEntity(ofy().save().toEntity(resource));
}});
return ofy().transact(() -> ofy().load().fromEntity(ofy().save().toEntity(resource)));
}
/** 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
public String createString(int length) {
checkArgument(length > 0, "String length must be positive.");
String password = "";
StringBuilder password = new StringBuilder();
for (int i = 0; i < length; i++) {
password += iterator.next();
password.append(iterator.next());
}
switch (rule) {
case PREPEND_COUNTER:
return String.format("%04d_%s", counter++, password);
return String.format("%04d_%s", counter++, password.toString());
case 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);
final PGPPublicKey rdeReceiverKey =
PgpHelper.lookupPublicKey(publics, RECEIVER_KEY_EMAIL, ENCRYPT);
final PGPKeyPair brdaSigningKey = rdeSigningKey;
final PGPPublicKey brdaReceiverKey = rdeReceiverKey;
final String sshPublic =
readResourceUtf8(FakeKeyringModule.class, "testdata/registry-unittest.id_rsa.pub");
final String sshPrivate =
@ -141,12 +139,12 @@ public final class FakeKeyringModule {
@Override
public PGPKeyPair getBrdaSigningKey() {
return brdaSigningKey;
return rdeSigningKey;
}
@Override
public PGPPublicKey getBrdaReceiverKey() {
return brdaReceiverKey;
return rdeReceiverKey;
}
@Override

View file

@ -56,7 +56,7 @@ public final class FullFieldsTestEntityHelper {
public static Registrar makeRegistrar(
String clientId, String registrarName, Registrar.State state, Long ianaIdentifier) {
Registrar registrar = new Registrar.Builder()
return new Registrar.Builder()
.setClientId(clientId)
.setRegistrarName(registrarName)
.setType(Registrar.Type.REAL)
@ -82,7 +82,6 @@ public final class FullFieldsTestEntityHelper {
.setWhoisServer("whois.example.com")
.setReferralUrl("http://www.example.com")
.build();
return 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.
*/
public static <T> Lazy<T> of(final T instance) {
return new Lazy<T>() {
@Override
public T get() {
return instance;
}};
return () -> instance;
}
}

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