Fix various Error Prone errors that were found by the FOSS build

Most common:
- Unnecessary parentheses and operator precedence clarify (self-explanatory)
- Reference equality--there were a few instances of using == or != improperly
- Qualification of Builder (and similar) imports so that it's clear which type of Builder we're referring to
- Marking some immutable classes with @Immutable since EP desires that all enums be deeply immutable
- String.split() having "surprising behavior"

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=230971531
This commit is contained in:
gbrodman 2019-01-25 14:39:57 -08:00 committed by Ben McIlwain
parent 9cd37189c2
commit 3cf26ff9b6
52 changed files with 155 additions and 133 deletions

View file

@ -171,7 +171,7 @@ public final class TldFanoutAction implements Runnable {
} }
for (String param : params.keySet()) { for (String param : params.keySet()) {
// TaskOptions.param() does not accept null values. // TaskOptions.param() does not accept null values.
options.param(param, nullToEmpty((getFirst(params.get(param), null)))); options.param(param, nullToEmpty(getFirst(params.get(param), null)));
} }
return options; return options;
} }

View file

@ -31,7 +31,6 @@ import google.registry.flows.TransactionalFlow;
import google.registry.flows.annotations.ReportingSpec; import google.registry.flows.annotations.ReportingSpec;
import google.registry.model.contact.ContactCommand.Create; import google.registry.model.contact.ContactCommand.Create;
import google.registry.model.contact.ContactResource; import google.registry.model.contact.ContactResource;
import google.registry.model.contact.ContactResource.Builder;
import google.registry.model.domain.metadata.MetadataExtension; import google.registry.model.domain.metadata.MetadataExtension;
import google.registry.model.eppinput.ResourceCommand; import google.registry.model.eppinput.ResourceCommand;
import google.registry.model.eppoutput.CreateData.ContactCreateData; import google.registry.model.eppoutput.CreateData.ContactCreateData;
@ -71,7 +70,8 @@ public final class ContactCreateFlow implements TransactionalFlow {
Create command = (Create) resourceCommand; Create command = (Create) resourceCommand;
DateTime now = ofy().getTransactionTime(); DateTime now = ofy().getTransactionTime();
verifyResourceDoesNotExist(ContactResource.class, targetId, now); verifyResourceDoesNotExist(ContactResource.class, targetId, now);
ContactResource newContact = new Builder() ContactResource newContact =
new ContactResource.Builder()
.setContactId(targetId) .setContactId(targetId)
.setAuthInfo(command.getAuthInfo()) .setAuthInfo(command.getAuthInfo())
.setCreationClientId(clientId) .setCreationClientId(clientId)

View file

@ -39,7 +39,6 @@ import google.registry.flows.exceptions.ResourceHasClientUpdateProhibitedExcepti
import google.registry.model.contact.ContactCommand.Update; import google.registry.model.contact.ContactCommand.Update;
import google.registry.model.contact.ContactCommand.Update.Change; import google.registry.model.contact.ContactCommand.Update.Change;
import google.registry.model.contact.ContactResource; import google.registry.model.contact.ContactResource;
import google.registry.model.contact.ContactResource.Builder;
import google.registry.model.contact.PostalInfo; import google.registry.model.contact.PostalInfo;
import google.registry.model.domain.metadata.MetadataExtension; import google.registry.model.domain.metadata.MetadataExtension;
import google.registry.model.eppcommon.AuthInfo; import google.registry.model.eppcommon.AuthInfo;
@ -109,7 +108,7 @@ public final class ContactUpdateFlow implements TransactionalFlow {
.setXmlBytes(null) // We don't want to store contact details in the history entry. .setXmlBytes(null) // We don't want to store contact details in the history entry.
.setParent(Key.create(existingContact)); .setParent(Key.create(existingContact));
checkSameValuesNotAddedAndRemoved(statusesToAdd, statusToRemove); checkSameValuesNotAddedAndRemoved(statusesToAdd, statusToRemove);
Builder builder = existingContact.asBuilder(); ContactResource.Builder builder = existingContact.asBuilder();
Change change = command.getInnerChange(); Change change = command.getInnerChange();
// The spec requires the following behaviors: // The spec requires the following behaviors:
// * If you update part of a postal info, the fields that you didn't update are unchanged. // * If you update part of a postal info, the fields that you didn't update are unchanged.

View file

@ -62,7 +62,6 @@ import google.registry.flows.custom.EntityChanges;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.billing.BillingEvent; import google.registry.model.billing.BillingEvent;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.domain.DomainBase.Builder;
import google.registry.model.domain.GracePeriod; import google.registry.model.domain.GracePeriod;
import google.registry.model.domain.fee.BaseFee.FeeType; import google.registry.model.domain.fee.BaseFee.FeeType;
import google.registry.model.domain.fee.Credit; import google.registry.model.domain.fee.Credit;
@ -149,7 +148,7 @@ public final class DomainDeleteFlow implements TransactionalFlow {
flowCustomLogic.afterValidation( flowCustomLogic.afterValidation(
AfterValidationParameters.newBuilder().setExistingDomain(existingDomain).build()); AfterValidationParameters.newBuilder().setExistingDomain(existingDomain).build());
ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>(); ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
Builder builder; DomainBase.Builder builder;
if (existingDomain.getStatusValues().contains(StatusValue.PENDING_TRANSFER)) { if (existingDomain.getStatusValues().contains(StatusValue.PENDING_TRANSFER)) {
builder = builder =
denyPendingTransfer(existingDomain, TransferStatus.SERVER_CANCELLED, now, clientId) denyPendingTransfer(existingDomain, TransferStatus.SERVER_CANCELLED, now, clientId)

View file

@ -46,7 +46,6 @@ import google.registry.flows.annotations.ReportingSpec;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.billing.BillingEvent; import google.registry.model.billing.BillingEvent;
import google.registry.model.billing.BillingEvent.OneTime; import google.registry.model.billing.BillingEvent.OneTime;
import google.registry.model.billing.BillingEvent.OneTime.Builder;
import google.registry.model.billing.BillingEvent.Reason; import google.registry.model.billing.BillingEvent.Reason;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.domain.DomainCommand.Update; import google.registry.model.domain.DomainCommand.Update;
@ -258,7 +257,7 @@ public final class DomainRestoreRequestFlow implements TransactionalFlow {
.build(); .build();
} }
private Builder prepareBillingEvent(HistoryEntry historyEntry, Money cost, DateTime now) { private OneTime.Builder prepareBillingEvent(HistoryEntry historyEntry, Money cost, DateTime now) {
return new BillingEvent.OneTime.Builder() return new BillingEvent.OneTime.Builder()
.setTargetId(targetId) .setTargetId(targetId)
.setClientId(clientId) .setClientId(clientId)

View file

@ -191,7 +191,7 @@ public final class DomainTransferApproveFlow implements TransactionalFlow {
.setAutorenewPollMessage(Key.create(gainingClientAutorenewPollMessage)) .setAutorenewPollMessage(Key.create(gainingClientAutorenewPollMessage))
// Remove all the old grace periods and add a new one for the transfer. // Remove all the old grace periods and add a new one for the transfer.
.setGracePeriods( .setGracePeriods(
(billingEvent.isPresent()) billingEvent.isPresent()
? ImmutableSet.of( ? ImmutableSet.of(
GracePeriod.forBillingEvent(GracePeriodStatus.TRANSFER, billingEvent.get())) GracePeriod.forBillingEvent(GracePeriodStatus.TRANSFER, billingEvent.get()))
: ImmutableSet.of()) : ImmutableSet.of())

View file

@ -45,7 +45,6 @@ import google.registry.model.eppoutput.CreateData.HostCreateData;
import google.registry.model.eppoutput.EppResponse; import google.registry.model.eppoutput.EppResponse;
import google.registry.model.host.HostCommand.Create; import google.registry.model.host.HostCommand.Create;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.host.HostResource.Builder;
import google.registry.model.index.EppResourceIndex; import google.registry.model.index.EppResourceIndex;
import google.registry.model.index.ForeignKeyIndex; import google.registry.model.index.ForeignKeyIndex;
import google.registry.model.ofy.ObjectifyService; import google.registry.model.ofy.ObjectifyService;
@ -119,7 +118,7 @@ public final class HostCreateFlow implements TransactionalFlow {
: new UnexpectedExternalHostIpException(); : new UnexpectedExternalHostIpException();
} }
HostResource newHost = HostResource newHost =
new Builder() new HostResource.Builder()
.setCreationClientId(clientId) .setCreationClientId(clientId)
.setPersistedCurrentSponsorClientId(clientId) .setPersistedCurrentSponsorClientId(clientId)
.setFullyQualifiedHostName(targetId) .setFullyQualifiedHostName(targetId)

View file

@ -32,7 +32,6 @@ import google.registry.model.domain.DomainBase;
import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppcommon.StatusValue;
import google.registry.model.eppoutput.EppResponse; import google.registry.model.eppoutput.EppResponse;
import google.registry.model.host.HostInfoData; import google.registry.model.host.HostInfoData;
import google.registry.model.host.HostInfoData.Builder;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField; import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
import google.registry.util.Clock; import google.registry.util.Clock;
@ -72,7 +71,7 @@ public final class HostInfoFlow implements Flow {
if (isLinked(Key.create(host), now)) { if (isLinked(Key.create(host), now)) {
statusValues.add(StatusValue.LINKED); statusValues.add(StatusValue.LINKED);
} }
Builder hostInfoDataBuilder = HostInfoData.newBuilder(); HostInfoData.Builder hostInfoDataBuilder = HostInfoData.newBuilder();
// Hosts transfer with their superordinate domains, so for hosts with a superordinate domain, // Hosts transfer with their superordinate domains, so for hosts with a superordinate domain,
// the client id, last transfer time, and pending transfer status need to be read off of it. If // the client id, last transfer time, and pending transfer status need to be read off of it. If
// there is no superordinate domain, the host's own values for these fields will be correct. // there is no superordinate domain, the host's own values for these fields will be correct.

View file

@ -18,7 +18,6 @@ import static com.google.common.collect.Iterables.getLast;
import com.google.appengine.tools.cloudstorage.GcsFileMetadata; import com.google.appengine.tools.cloudstorage.GcsFileMetadata;
import com.google.appengine.tools.cloudstorage.GcsFileOptions; import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFileOptions.Builder;
import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.ListOptions; import com.google.appengine.tools.cloudstorage.ListOptions;
@ -113,7 +112,7 @@ public class GcsUtils {
/** Determines most appropriate {@link GcsFileOptions} based on filename extension. */ /** Determines most appropriate {@link GcsFileOptions} based on filename extension. */
private static GcsFileOptions getOptions(GcsFilename filename) { private static GcsFileOptions getOptions(GcsFilename filename) {
Builder builder = new GcsFileOptions.Builder().cacheControl("no-cache"); GcsFileOptions.Builder builder = new GcsFileOptions.Builder().cacheControl("no-cache");
MediaType mediaType = EXTENSIONS.get(getLast(Splitter.on('.').split(filename.getObjectName()))); MediaType mediaType = EXTENSIONS.get(getLast(Splitter.on('.').split(filename.getObjectName())));
if (mediaType != null) { if (mediaType != null) {
builder = builder.mimeType(mediaType.type()); builder = builder.mimeType(mediaType.type());

View file

@ -47,11 +47,11 @@ class KmsConnectionImpl implements KmsConnection {
@Inject @Inject
KmsConnectionImpl( KmsConnectionImpl(
@Config("cloudKmsProjectId") String projectId, @Config("cloudKmsProjectId") String projectId,
@Config("cloudKmsKeyRing") String kmsKeyringName, @Config("cloudKmsKeyRing") String kmsKeyRingName,
Retrier retrier, Retrier retrier,
CloudKMS kms) { CloudKMS kms) {
this.projectId = projectId; this.projectId = projectId;
this.kmsKeyRingName = kmsKeyringName; this.kmsKeyRingName = kmsKeyRingName;
this.retrier = retrier; this.retrier = retrier;
this.kms = kms; this.kms = kms;
} }

View file

@ -28,7 +28,6 @@ import com.googlecode.objectify.Result;
import com.googlecode.objectify.cmd.Query; import com.googlecode.objectify.cmd.Query;
import com.googlecode.objectify.util.ResultNow; import com.googlecode.objectify.util.ResultNow;
import google.registry.config.RegistryConfig; import google.registry.config.RegistryConfig;
import google.registry.model.EppResource.Builder;
import google.registry.model.EppResource.BuilderWithTransferData; import google.registry.model.EppResource.BuilderWithTransferData;
import google.registry.model.EppResource.ForeignKeyedEppResource; import google.registry.model.EppResource.ForeignKeyedEppResource;
import google.registry.model.EppResource.ResourceWithTransferData; import google.registry.model.EppResource.ResourceWithTransferData;
@ -222,7 +221,7 @@ public final class EppResourceUtils {
} }
/** Process an automatic transfer on a resource. */ /** Process an automatic transfer on a resource. */
public static <B extends Builder<?, B> & BuilderWithTransferData<B>> public static <B extends EppResource.Builder<?, B> & BuilderWithTransferData<B>>
void setAutomaticTransferSuccessProperties(B builder, TransferData transferData) { void setAutomaticTransferSuccessProperties(B builder, TransferData transferData) {
checkArgument(TransferStatus.PENDING.equals(transferData.getTransferStatus())); checkArgument(TransferStatus.PENDING.equals(transferData.getTransferStatus()));
builder.removeStatusValue(StatusValue.PENDING_TRANSFER) builder.removeStatusValue(StatusValue.PENDING_TRANSFER)
@ -239,13 +238,14 @@ public final class EppResourceUtils {
/** /**
* Perform common operations for projecting an {@link EppResource} at a given time: * Perform common operations for projecting an {@link EppResource} at a given time:
*
* <ul> * <ul>
* <li>Process an automatic transfer. * <li>Process an automatic transfer.
* </ul> * </ul>
*/ */
public static < public static <
T extends EppResource & ResourceWithTransferData, T extends EppResource & ResourceWithTransferData,
B extends Builder<?, B> & BuilderWithTransferData<B>> B extends EppResource.Builder<?, B> & BuilderWithTransferData<B>>
void projectResourceOntoBuilderAtTime(T resource, B builder, DateTime now) { void projectResourceOntoBuilderAtTime(T resource, B builder, DateTime now) {
TransferData transferData = resource.getTransferData(); TransferData transferData = resource.getTransferData();
// If there's a pending transfer that has expired, process it. // If there's a pending transfer that has expired, process it.
@ -289,7 +289,7 @@ public final class EppResourceUtils {
// and returns it projected forward to exactly the desired timestamp, or null if the resource is // and returns it projected forward to exactly the desired timestamp, or null if the resource is
// deleted at that timestamp. // deleted at that timestamp.
final Result<T> loadResult = final Result<T> loadResult =
(isAtOrAfter(timestamp, resource.getUpdateAutoTimestamp().getTimestamp())) isAtOrAfter(timestamp, resource.getUpdateAutoTimestamp().getTimestamp())
? new ResultNow<>(resource) ? new ResultNow<>(resource)
: loadMostRecentRevisionAtTime(resource, timestamp); : loadMostRecentRevisionAtTime(resource, timestamp);
return () -> { return () -> {

View file

@ -23,7 +23,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import google.registry.model.EppResource.Builder;
import google.registry.model.EppResource.BuilderWithTransferData; import google.registry.model.EppResource.BuilderWithTransferData;
import google.registry.model.EppResource.ForeignKeyedEppResource; import google.registry.model.EppResource.ForeignKeyedEppResource;
import google.registry.model.EppResource.ResourceWithTransferData; import google.registry.model.EppResource.ResourceWithTransferData;
@ -170,7 +169,7 @@ public final class ResourceTransferUtils {
*/ */
public static < public static <
R extends EppResource & ResourceWithTransferData, R extends EppResource & ResourceWithTransferData,
B extends Builder<R, B> & BuilderWithTransferData<B>> B extends EppResource.Builder<R, B> & BuilderWithTransferData<B>>
R approvePendingTransfer(R resource, TransferStatus transferStatus, DateTime now) { R approvePendingTransfer(R resource, TransferStatus transferStatus, DateTime now) {
checkArgument(transferStatus.isApproved(), "Not an approval transfer status"); checkArgument(transferStatus.isApproved(), "Not an approval transfer status");
B builder = resolvePendingTransfer(resource, transferStatus, now); B builder = resolvePendingTransfer(resource, transferStatus, now);

View file

@ -100,7 +100,8 @@ public class GracePeriod extends ImmutableObject {
@Nullable Key<BillingEvent.Recurring> billingEventRecurring) { @Nullable Key<BillingEvent.Recurring> billingEventRecurring) {
checkArgument((billingEventOneTime == null) || (billingEventRecurring == null), checkArgument((billingEventOneTime == null) || (billingEventRecurring == null),
"A grace period can have at most one billing event"); "A grace period can have at most one billing event");
checkArgument((billingEventRecurring != null) == (GracePeriodStatus.AUTO_RENEW.equals(type)), checkArgument(
(billingEventRecurring != null) == GracePeriodStatus.AUTO_RENEW.equals(type),
"Recurring billing events must be present on (and only on) autorenew grace periods"); "Recurring billing events must be present on (and only on) autorenew grace periods");
GracePeriod instance = new GracePeriod(); GracePeriod instance = new GracePeriod();
instance.type = checkArgumentNotNull(type); instance.type = checkArgumentNotNull(type);

View file

@ -19,7 +19,7 @@ import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.model.Buildable.Builder; import google.registry.model.Buildable;
import google.registry.model.EppResource; import google.registry.model.EppResource;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.eppcommon.AuthInfo; import google.registry.model.eppcommon.AuthInfo;
@ -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. */
interface ResourceCreateOrChange<B extends Builder<?>> {} interface ResourceCreateOrChange<B extends Buildable.Builder<?>> {}
/** /**
* An update command for an {@link EppResource}. * An update command for an {@link EppResource}.

View file

@ -149,7 +149,7 @@ public class HostResource extends EppResource implements ForeignKeyedEppResource
Optional.ofNullable(getLastSuperordinateChange()).orElse(getCreationTime()); Optional.ofNullable(getLastSuperordinateChange()).orElse(getCreationTime());
DateTime lastTransferOfCurrentSuperordinate = DateTime lastTransferOfCurrentSuperordinate =
Optional.ofNullable(superordinateDomain.getLastTransferTime()).orElse(START_OF_TIME); Optional.ofNullable(superordinateDomain.getLastTransferTime()).orElse(START_OF_TIME);
return (lastSuperordinateChange.isBefore(lastTransferOfCurrentSuperordinate)) return lastSuperordinateChange.isBefore(lastTransferOfCurrentSuperordinate)
? superordinateDomain.getLastTransferTime() ? superordinateDomain.getLastTransferTime()
: getLastTransferTime(); : getLastTransferTime();
} }

View file

@ -41,7 +41,7 @@ public class EppResourceIndexBucket extends ImmutableObject {
private static long getBucketIdFromEppResource(Key<? extends EppResource> resourceKey) { private static long getBucketIdFromEppResource(Key<? extends EppResource> resourceKey) {
int numBuckets = getEppResourceIndexBucketCount(); int numBuckets = getEppResourceIndexBucketCount();
// IDs can't be 0, so add 1 to the hash. // IDs can't be 0, so add 1 to the hash.
return Hashing.consistentHash(resourceKey.getName().hashCode(), numBuckets) + 1; return Hashing.consistentHash(resourceKey.getName().hashCode(), numBuckets) + 1L;
} }
/** Gets a bucket key as a function of an EppResource to be indexed. */ /** Gets a bucket key as a function of an EppResource to be indexed. */

View file

@ -130,8 +130,10 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable
/** /**
* Predicate for validating IANA IDs for this type of registrar. * Predicate for validating IANA IDs for this type of registrar.
* *
* @see <a href="http://www.iana.org/assignments/registrar-ids/registrar-ids.txt">Registrar IDs</a> * @see <a href="http://www.iana.org/assignments/registrar-ids/registrar-ids.txt">Registrar
* IDs</a>
*/ */
@SuppressWarnings("ImmutableEnumChecker")
private final Predicate<Long> ianaIdValidator; private final Predicate<Long> ianaIdValidator;
Type(Predicate<Long> ianaIdValidator) { Type(Predicate<Long> ianaIdValidator) {

View file

@ -36,6 +36,7 @@ import google.registry.xjc.eppcom.XjcEppcomTrStatusType;
import google.registry.xjc.rdecontact.XjcRdeContact; import google.registry.xjc.rdecontact.XjcRdeContact;
import google.registry.xjc.rdecontact.XjcRdeContactElement; import google.registry.xjc.rdecontact.XjcRdeContactElement;
import google.registry.xjc.rdecontact.XjcRdeContactTransferDataType; import google.registry.xjc.rdecontact.XjcRdeContactTransferDataType;
import java.util.Objects;
import javax.annotation.CheckForNull; import javax.annotation.CheckForNull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -101,7 +102,7 @@ final class ContactResourceToXjcConverter {
// required before an automated response action will be taken by // required before an automated response action will be taken by
// the registry. For all other status types, the value identifies // the registry. For all other status types, the value identifies
// the date and time when the request was completed. // the date and time when the request was completed.
if (model.getTransferData() != TransferData.EMPTY) { if (!Objects.equals(model.getTransferData(), TransferData.EMPTY)) {
bean.setTrnData(convertTransferData(model.getTransferData())); bean.setTrnData(convertTransferData(model.getTransferData()));
} }

View file

@ -17,12 +17,11 @@ package google.registry.rde;
import static google.registry.model.rde.RdeMode.FULL; import static google.registry.model.rde.RdeMode.FULL;
import static google.registry.model.rde.RdeMode.THIN; import static google.registry.model.rde.RdeMode.THIN;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import google.registry.model.rde.RdeMode; import google.registry.model.rde.RdeMode;
import java.util.Collections;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.Set;
/** Types of objects that get embedded in an escrow deposit. */ /** Types of objects that get embedded in an escrow deposit. */
public enum RdeResourceType { public enum RdeResourceType {
@ -34,11 +33,11 @@ public enum RdeResourceType {
HEADER("urn:ietf:params:xml:ns:rdeHeader-1.0", EnumSet.of(FULL, THIN)); HEADER("urn:ietf:params:xml:ns:rdeHeader-1.0", EnumSet.of(FULL, THIN));
private final String uri; private final String uri;
private final Set<RdeMode> modes; private final ImmutableSet<RdeMode> modes;
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 = ImmutableSet.copyOf(modes);
} }
/** Returns RDE XML schema URI specifying resource. */ /** Returns RDE XML schema URI specifying resource. */
@ -47,7 +46,7 @@ public enum RdeResourceType {
} }
/** Returns set indicating if resource is stored in BRDA thin deposits. */ /** Returns set indicating if resource is stored in BRDA thin deposits. */
public Set<RdeMode> getModes() { public ImmutableSet<RdeMode> getModes() {
return modes; return modes;
} }

View file

@ -164,8 +164,7 @@ final class RdeUploadUrl implements Comparable<RdeUploadUrl> {
@Override @Override
public boolean equals(@Nullable Object object) { public boolean equals(@Nullable Object object) {
return object == this return object == this
|| object instanceof RdeUploadUrl || (object instanceof RdeUploadUrl && Objects.equals(uri, ((RdeUploadUrl) object).uri));
&& Objects.equals(uri, ((RdeUploadUrl) object).uri);
} }
/** @see java.net.URI#hashCode() */ /** @see java.net.URI#hashCode() */
@ -200,9 +199,9 @@ final class RdeUploadUrl implements Comparable<RdeUploadUrl> {
@Override @Override
public boolean equals(@Nullable Object object) { public boolean equals(@Nullable Object object) {
return object == this return object == this
|| object instanceof Protocol || (object instanceof Protocol
&& port == ((Protocol) object).port && port == ((Protocol) object).port
&& Objects.equals(name, ((Protocol) object).name); && Objects.equals(name, ((Protocol) object).name));
} }
/** @see Object#hashCode() */ /** @see Object#hashCode() */

View file

@ -20,7 +20,9 @@ import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_OK;
import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.net.MediaType; import com.google.common.net.MediaType;
@ -96,7 +98,7 @@ public final class CopyDetailReportsAction implements Runnable {
for (String detailReportName : detailReportObjectNames) { for (String detailReportName : detailReportObjectNames) {
// The standard report format is "invoice_details_yyyy-MM_registrarId_tld.csv // The standard report format is "invoice_details_yyyy-MM_registrarId_tld.csv
// TODO(larryruili): Determine a safer way of enforcing this. // TODO(larryruili): Determine a safer way of enforcing this.
String registrarId = detailReportName.split("_")[3]; String registrarId = Iterables.get(Splitter.on('_').split(detailReportName), 3);
Optional<Registrar> registrar = Registrar.loadByClientId(registrarId); Optional<Registrar> registrar = Registrar.loadByClientId(registrarId);
if (!registrar.isPresent()) { if (!registrar.isPresent()) {
logger.atWarning().log( logger.atWarning().log(

View file

@ -11,6 +11,7 @@ java_library(
deps = [ deps = [
"//java/google/registry/util", "//java/google/registry/util",
"//third_party/objectify:objectify-v4_1", "//third_party/objectify:objectify-v4_1",
"@com_google_errorprone_error_prone_annotations",
"@com_google_guava", "@com_google_guava",
"@com_google_re2j", "@com_google_re2j",
], ],

View file

@ -19,13 +19,14 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import com.google.common.collect.RangeSet; import com.google.errorprone.annotations.Immutable;
import com.google.re2j.Matcher; import com.google.re2j.Matcher;
import com.google.re2j.Pattern; import com.google.re2j.Pattern;
import java.net.URI; import java.net.URI;
import java.util.Optional; import java.util.Optional;
/** An IDN table for a particular TLD. */ /** An IDN table for a particular TLD. */
@Immutable
public final class IdnTable { public final class IdnTable {
/** Regular expression to match a line of an IDN table. */ /** Regular expression to match a line of an IDN table. */
@ -48,8 +49,8 @@ public final class IdnTable {
/** Public URL of policy for this IDN table, which is needed by RDE. */ /** Public URL of policy for this IDN table, which is needed by RDE. */
private final URI policy; private final URI policy;
/** {@link RangeSet} containing the valid codepoints in this table. */ /** {@link ImmutableRangeSet} containing the valid codepoints in this table. */
private final RangeSet<Integer> validCodepoints; private final ImmutableRangeSet<Integer> validCodepoints;
/** Validates the language rules associated with this IDN table. */ /** Validates the language rules associated with this IDN table. */
private final Optional<LanguageValidator> languageValidator; private final Optional<LanguageValidator> languageValidator;
@ -58,7 +59,7 @@ public final class IdnTable {
String name, String name,
URI url, URI url,
URI policy, URI policy,
RangeSet<Integer> validCodepoints, ImmutableRangeSet<Integer> validCodepoints,
Optional<LanguageValidator> languageValidator) { Optional<LanguageValidator> languageValidator) {
this.name = name; this.name = name;
this.url = checkNotNull(url, "%s missing '# URL: http://foo.example/page' line", name); this.url = checkNotNull(url, "%s missing '# URL: http://foo.example/page' line", name);

View file

@ -22,12 +22,15 @@ import static java.lang.Character.UnicodeBlock.KATAKANA;
import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import com.google.errorprone.annotations.Immutable;
import java.lang.Character.UnicodeBlock; import java.lang.Character.UnicodeBlock;
import java.util.Objects;
/** /**
* Validates Japanese language domain labels. This class should only be used with a Japanese * Validates Japanese language domain labels. This class should only be used with a Japanese
* language IDN table. * language IDN table.
*/ */
@Immutable
class JapaneseLanguageValidator extends LanguageValidator { class JapaneseLanguageValidator extends LanguageValidator {
/** Any string with Japanese characters can have at most 15 characters. */ /** Any string with Japanese characters can have at most 15 characters. */
@ -82,7 +85,8 @@ class JapaneseLanguageValidator extends LanguageValidator {
// The KATAKANA_HIRAGANA_PROLONGED_SOUND_MARK can only occur after a HIRAGANA or KATAKANA // The KATAKANA_HIRAGANA_PROLONGED_SOUND_MARK can only occur after a HIRAGANA or KATAKANA
// character. // character.
if (codepoint == KATAKANA_HIRAGANA_PROLONGED_SOUND_MARK if (codepoint == KATAKANA_HIRAGANA_PROLONGED_SOUND_MARK
&& precedingUnicodeBlock != HIRAGANA && precedingUnicodeBlock != KATAKANA) { && !Objects.equals(precedingUnicodeBlock, HIRAGANA)
&& !Objects.equals(precedingUnicodeBlock, KATAKANA)) {
return false; return false;
} }

View file

@ -15,8 +15,10 @@
package google.registry.tldconfig.idn; package google.registry.tldconfig.idn;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.Immutable;
import java.util.Optional; import java.util.Optional;
@Immutable
abstract class LanguageValidator { abstract class LanguageValidator {
/** A registry of all known language validators keyed by their language code. */ /** A registry of all known language validators keyed by their language code. */

View file

@ -48,8 +48,9 @@ final class CanonicalizeLabelsCommand implements Command {
@Override @Override
public void run() throws IOException { public void run() throws IOException {
Set<String> labels = new TreeSet<>(); Set<String> labels = new TreeSet<>();
for (String label : mainParameters.isEmpty() for (String label :
? CharStreams.readLines(new InputStreamReader(stdin)) mainParameters.isEmpty()
? CharStreams.readLines(new InputStreamReader(stdin, UTF_8))
: Files.readLines(new File(mainParameters.get(0)), UTF_8)) { : Files.readLines(new File(mainParameters.get(0)), UTF_8)) {
label = label.trim(); label = label.trim();
if (label.startsWith("-")) { if (label.startsWith("-")) {

View file

@ -35,7 +35,7 @@ class CommandUtilities {
HOST(HostResource.class), HOST(HostResource.class),
DOMAIN(DomainBase.class); DOMAIN(DomainBase.class);
private Class<? extends EppResource> clazz; private final Class<? extends EppResource> clazz;
ResourceType(Class<? extends EppResource> clazz) { ResourceType(Class<? extends EppResource> clazz) {
this.clazz = clazz; this.clazz = clazz;

View file

@ -15,6 +15,7 @@
package google.registry.tools; package google.registry.tools;
import static google.registry.util.ResourceUtils.readResourceBytes; import static google.registry.util.ResourceUtils.readResourceBytes;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
@ -67,7 +68,7 @@ final class LoggingParameters {
// Add an extra leading newline in case base properties file does not end in a newline. // Add an extra leading newline in case base properties file does not end in a newline.
String customProperties = "\n" + Joiner.on('\n').join(configLines); String customProperties = "\n" + Joiner.on('\n').join(configLines);
ByteSource logConfig = ByteSource logConfig =
ByteSource.concat(baseConfig, ByteSource.wrap(customProperties.getBytes())); ByteSource.concat(baseConfig, ByteSource.wrap(customProperties.getBytes(UTF_8)));
try (InputStream input = logConfig.openStream()) { try (InputStream input = logConfig.openStream()) {
LogManager.getLogManager().readConfiguration(input); LogManager.getLogManager().readConfiguration(input);
} }

View file

@ -32,7 +32,6 @@ import com.google.common.collect.ImmutableSet;
import google.registry.model.common.GaeUserIdConverter; import google.registry.model.common.GaeUserIdConverter;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.RegistrarContact; import google.registry.model.registrar.RegistrarContact;
import google.registry.model.registrar.RegistrarContact.Builder;
import google.registry.tools.params.OptionalPhoneNumberParameter; import google.registry.tools.params.OptionalPhoneNumberParameter;
import google.registry.tools.params.PathParameter; import google.registry.tools.params.PathParameter;
import java.io.IOException; import java.io.IOException;
@ -235,7 +234,7 @@ final class RegistrarContactCommand extends MutatingCommand {
private RegistrarContact createContact(Registrar registrar) { private RegistrarContact createContact(Registrar registrar) {
checkArgument(!isNullOrEmpty(name), "--name is required when --mode=CREATE"); checkArgument(!isNullOrEmpty(name), "--name is required when --mode=CREATE");
checkArgument(!isNullOrEmpty(email), "--email is required when --mode=CREATE"); checkArgument(!isNullOrEmpty(email), "--email is required when --mode=CREATE");
Builder builder = new RegistrarContact.Builder(); RegistrarContact.Builder builder = new RegistrarContact.Builder();
builder.setParent(registrar); builder.setParent(registrar);
builder.setName(name); builder.setName(name);
builder.setEmailAddress(email); builder.setEmailAddress(email);
@ -267,7 +266,7 @@ final class RegistrarContactCommand extends MutatingCommand {
private RegistrarContact updateContact(RegistrarContact contact, Registrar registrar) { private RegistrarContact updateContact(RegistrarContact contact, Registrar registrar) {
checkNotNull(registrar); checkNotNull(registrar);
checkNotNull(email, "--email is required when --mode=UPDATE"); checkNotNull(email, "--email is required when --mode=UPDATE");
Builder builder = contact.asBuilder(); RegistrarContact.Builder builder = contact.asBuilder();
builder.setParent(registrar); builder.setParent(registrar);
if (!isNullOrEmpty(name)) { if (!isNullOrEmpty(name)) {
builder.setName(name); builder.setName(name);

View file

@ -21,7 +21,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import google.registry.model.registry.label.ReservedList; import google.registry.model.registry.label.ReservedList;
import google.registry.model.registry.label.ReservedList.Builder;
import google.registry.util.SystemClock; import google.registry.util.SystemClock;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Optional; import java.util.Optional;
@ -36,7 +35,9 @@ final class UpdateReservedListCommand extends CreateOrUpdateReservedListCommand
Optional<ReservedList> existing = ReservedList.get(name); Optional<ReservedList> existing = ReservedList.get(name);
checkArgument( checkArgument(
existing.isPresent(), "Could not update reserved list %s because it doesn't exist.", name); existing.isPresent(), "Could not update reserved list %s because it doesn't exist.", name);
Builder updated = existing.get() ReservedList.Builder updated =
existing
.get()
.asBuilder() .asBuilder()
.setReservedListMapFromLines(Files.readAllLines(input, UTF_8)) .setReservedListMapFromLines(Files.readAllLines(input, UTF_8))
.setLastUpdateTime(new SystemClock().nowUtc()); .setLastUpdateTime(new SystemClock().nowUtc());

View file

@ -15,12 +15,12 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.difference;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import google.registry.keyring.api.Keyring; import google.registry.keyring.api.Keyring;
import google.registry.rde.Ghostryde; import google.registry.rde.Ghostryde;
@ -40,7 +40,6 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.SortedMap; import java.util.SortedMap;
@ -141,17 +140,19 @@ final class ValidateEscrowDepositCommand implements Command {
} }
System.out.println(); System.out.println();
boolean good = true; boolean good = true;
List<String> badHostnameRefs = copyOf(difference(hostnameRefs, hostnames)); ImmutableList<String> badHostnameRefs =
ImmutableList.copyOf(difference(hostnameRefs, hostnames));
if (!badHostnameRefs.isEmpty()) { if (!badHostnameRefs.isEmpty()) {
System.out.printf("Bad host refs: %s\n", Joiner.on(", ").join(badHostnameRefs)); System.out.printf("Bad host refs: %s\n", Joiner.on(", ").join(badHostnameRefs));
good = false; good = false;
} }
List<String> badContactRefs = copyOf(difference(contactRefs, contacts)); ImmutableList<String> badContactRefs = ImmutableList.copyOf(difference(contactRefs, contacts));
if (!badContactRefs.isEmpty()) { if (!badContactRefs.isEmpty()) {
System.out.printf("Bad contact refs: %s\n", Joiner.on(", ").join(badContactRefs)); System.out.printf("Bad contact refs: %s\n", Joiner.on(", ").join(badContactRefs));
good = false; good = false;
} }
List<String> badRegistrarRefs = copyOf(difference(registrarRefs, registrars)); ImmutableList<String> badRegistrarRefs =
ImmutableList.copyOf(difference(registrarRefs, registrars));
if (!badRegistrarRefs.isEmpty()) { if (!badRegistrarRefs.isEmpty()) {
System.out.printf("Bad registrar refs: %s\n", Joiner.on(", ").join(badRegistrarRefs)); System.out.printf("Bad registrar refs: %s\n", Joiner.on(", ").join(badRegistrarRefs));
good = false; good = false;

View file

@ -21,7 +21,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import google.registry.model.registrar.Registrar.Builder;
import google.registry.model.registrar.RegistrarAddress; import google.registry.model.registrar.RegistrarAddress;
import google.registry.tools.MutatingCommand; import google.registry.tools.MutatingCommand;
import java.util.Objects; import java.util.Objects;
@ -40,7 +39,7 @@ public class PopulateNullRegistrarFieldsCommand extends MutatingCommand {
@Override @Override
protected void init() { protected void init() {
for (Registrar registrar : ofy().load().type(Registrar.class).ancestor(getCrossTldKey())) { for (Registrar registrar : ofy().load().type(Registrar.class).ancestor(getCrossTldKey())) {
Builder changeBuilder = registrar.asBuilder(); Registrar.Builder changeBuilder = registrar.asBuilder();
changeBuilder.setRegistrarName( changeBuilder.setRegistrarName(
firstNonNull(registrar.getRegistrarName(), registrar.getClientId())); firstNonNull(registrar.getRegistrarName(), registrar.getClientId()));

View file

@ -101,6 +101,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
@Inject @Config("gcsBufferSize") int gcsBufferSize; @Inject @Config("gcsBufferSize") int gcsBufferSize;
@Inject @Config("commitLogDatastoreRetention") Duration datastoreRetention; @Inject @Config("commitLogDatastoreRetention") Duration datastoreRetention;
@Inject @Config("dnsDefaultATtl") Duration dnsDefaultATtl; @Inject @Config("dnsDefaultATtl") Duration dnsDefaultATtl;
@SuppressWarnings("DurationVariableWithUnits") // false-positive Error Prone check
@Inject @Config("dnsDefaultNsTtl") Duration dnsDefaultNsTtl; @Inject @Config("dnsDefaultNsTtl") Duration dnsDefaultNsTtl;
@Inject @Config("dnsDefaultDsTtl") Duration dnsDefaultDsTtl; @Inject @Config("dnsDefaultDsTtl") Duration dnsDefaultDsTtl;
@Inject Clock clock; @Inject Clock clock;
@ -291,14 +292,15 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
loadAtPointInTime(nameserver, exportTime).now().getFullyQualifiedHostName())); loadAtPointInTime(nameserver, exportTime).now().getFullyQualifiedHostName()));
} }
for (DelegationSignerData dsData : domain.getDsData()) { for (DelegationSignerData dsData : domain.getDsData()) {
result.append(String.format( result.append(
String.format(
DS_FORMAT, DS_FORMAT,
domainLabel, domainLabel,
dnsDefaultDsTtl.getStandardSeconds(), dnsDefaultDsTtl.getStandardSeconds(),
dsData.getKeyTag(), dsData.getKeyTag(),
dsData.getAlgorithm(), dsData.getAlgorithm(),
dsData.getDigestType(), dsData.getDigestType(),
base16().encode((dsData.getDigest())))); base16().encode(dsData.getDigest())));
} }
return result.toString(); return result.toString();
} }

View file

@ -156,10 +156,10 @@ public final class FormFieldException extends FormException {
@Override @Override
public boolean equals(@Nullable Object obj) { public boolean equals(@Nullable Object obj) {
return this == obj return this == obj
|| obj instanceof FormFieldException || (obj instanceof FormFieldException
&& Objects.equals(getCause(), ((FormFieldException) obj).getCause()) && Objects.equals(getCause(), ((FormFieldException) obj).getCause())
&& Objects.equals(getMessage(), ((FormFieldException) obj).getMessage()) && Objects.equals(getMessage(), ((FormFieldException) obj).getMessage())
&& Objects.equals(names, ((FormFieldException) obj).names); && Objects.equals(names, ((FormFieldException) obj).names));
} }
@Override @Override

View file

@ -450,7 +450,7 @@ public class CidrAddressBlock implements Iterable<InetAddress>, Serializable {
} }
InetAddress next = InetAddresses.increment(previous); InetAddress next = InetAddresses.increment(previous);
return (contains(next)) ? next : null; return contains(next) ? next : null;
} }
}; };
} }

View file

@ -138,7 +138,7 @@ public final class DiffUtils {
&& ((DiffPair) value).b instanceof Set) { && ((DiffPair) value).b instanceof Set) {
DiffPair pair = ((DiffPair) value); DiffPair pair = ((DiffPair) value);
String prettyLineDiff = prettyPrintSetDiff((Set<?>) pair.a, (Set<?>) pair.b) + "\n"; String prettyLineDiff = prettyPrintSetDiff((Set<?>) pair.a, (Set<?>) pair.b) + "\n";
output = newPath + ((prettyLineDiff.startsWith("\n")) ? ":" : ": ") + prettyLineDiff; output = newPath + (prettyLineDiff.startsWith("\n") ? ":" : ": ") + prettyLineDiff;
} else { } else {
output = newPath + ": " + value + "\n"; output = newPath + ": " + value + "\n";
} }

View file

@ -279,9 +279,9 @@ public final class PosixTarHeader {
@Override @Override
public boolean equals(@Nullable Object rhs) { public boolean equals(@Nullable Object rhs) {
return rhs == this return rhs == this
|| rhs != null || (rhs != null
&& getClass() == rhs.getClass() && getClass() == rhs.getClass()
&& Arrays.equals(header, ((PosixTarHeader) rhs).header); && Arrays.equals(header, ((PosixTarHeader) rhs).header));
} }
/** @see Arrays#toString(byte[]) */ /** @see Arrays#toString(byte[]) */

View file

@ -21,7 +21,11 @@ public class XmlEnumUtils {
/** Read the {@link XmlEnumValue} string off of an enum. */ /** Read the {@link XmlEnumValue} string off of an enum. */
public static String enumToXml(Enum<?> input) { public static String enumToXml(Enum<?> input) {
try { try {
return input.getClass().getField(input.name()).getAnnotation(XmlEnumValue.class).value(); return input
.getDeclaringClass()
.getField(input.name())
.getAnnotation(XmlEnumValue.class)
.value();
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View file

@ -41,6 +41,7 @@ import javax.servlet.http.HttpServletRequest;
public final class WhoisModule { public final class WhoisModule {
@Provides @Provides
@SuppressWarnings("CloseableProvides")
static Reader provideHttpInputReader(HttpServletRequest req) { static Reader provideHttpInputReader(HttpServletRequest req) {
try { try {
return req.getReader(); return req.getReader();

View file

@ -57,13 +57,11 @@ 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<?> instanceType) private static <T> T unfreezeInstance(byte[] instanceData, Class<T> instanceType)
throws IOException { throws IOException {
try { try {
ByteArrayInputStream bin = new ByteArrayInputStream(instanceData); ByteArrayInputStream bin = new ByteArrayInputStream(instanceData);
@SuppressWarnings("unchecked") return XjcXmlTransformer.unmarshal(instanceType, bin);
T instance = (T) XjcXmlTransformer.unmarshal(instanceType, bin);
return instance;
} catch (XmlException e) { } catch (XmlException e) {
throw new IOException(e); throw new IOException(e);
} }
@ -91,12 +89,13 @@ public class JaxbFragment<T> implements Serializable {
out.writeObject(freezeInstance(instance)); out.writeObject(freezeInstance(instance));
} }
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException { private void readObject(ObjectInputStream in) throws IOException {
// read instanceType, then instanceData // read instanceType, then instanceData
Class<?> instanceType; Class<T> instanceType;
byte[] instanceData; byte[] instanceData;
try { try {
instanceType = (Class<?>) in.readObject(); instanceType = (Class<T>) in.readObject();
instanceData = (byte[]) in.readObject(); instanceData = (byte[]) in.readObject();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View file

@ -58,10 +58,11 @@ public abstract class XjcObject {
public String toString() { public String toString() {
try { try {
StringWriter out = new StringWriter(); StringWriter out = new StringWriter();
XjcXmlTransformer.marshalLenient((getClass() XjcXmlTransformer.marshalLenient(
.isAnnotationPresent(XmlRootElement.class)) getClass().isAnnotationPresent(XmlRootElement.class)
? this ? this
: new JAXBElement<>(new QName(getClass().getSimpleName()), Object.class, this), out); : new JAXBElement<>(new QName(getClass().getSimpleName()), Object.class, this),
out);
return out.toString(); return out.toString();
} catch (XmlException e) { } catch (XmlException e) {
return String.format("<!-- Invalid XML: %s -->", e.toString()); return String.format("<!-- Invalid XML: %s -->", e.toString());

View file

@ -38,7 +38,7 @@ public class TestDomainPricingCustomLogic extends DomainPricingCustomLogic {
@Override @Override
public FeesAndCredits customizeRenewPrice(RenewPriceParameters priceParameters) { public FeesAndCredits customizeRenewPrice(RenewPriceParameters priceParameters) {
return (priceParameters.domainName().toString().startsWith("costly-renew")) return priceParameters.domainName().toString().startsWith("costly-renew")
? addCustomFee( ? addCustomFee(
priceParameters.feesAndCredits(), Fee.create(ONE_HUNDRED_BUCKS, FeeType.RENEW)) priceParameters.feesAndCredits(), Fee.create(ONE_HUNDRED_BUCKS, FeeType.RENEW))
: priceParameters.feesAndCredits(); : priceParameters.feesAndCredits();
@ -46,7 +46,7 @@ public class TestDomainPricingCustomLogic extends DomainPricingCustomLogic {
@Override @Override
public FeesAndCredits customizeTransferPrice(TransferPriceParameters priceParameters) { public FeesAndCredits customizeTransferPrice(TransferPriceParameters priceParameters) {
return (priceParameters.domainName().toString().startsWith("expensive")) return priceParameters.domainName().toString().startsWith("expensive")
? addCustomFee( ? addCustomFee(
priceParameters.feesAndCredits(), Fee.create(ONE_HUNDRED_BUCKS, FeeType.TRANSFER)) priceParameters.feesAndCredits(), Fee.create(ONE_HUNDRED_BUCKS, FeeType.TRANSFER))
: priceParameters.feesAndCredits(); : priceParameters.feesAndCredits();
@ -54,7 +54,7 @@ public class TestDomainPricingCustomLogic extends DomainPricingCustomLogic {
@Override @Override
public FeesAndCredits customizeUpdatePrice(UpdatePriceParameters priceParameters) { public FeesAndCredits customizeUpdatePrice(UpdatePriceParameters priceParameters) {
return (priceParameters.domainName().toString().startsWith("non-free-update")) return priceParameters.domainName().toString().startsWith("non-free-update")
? addCustomFee( ? addCustomFee(
priceParameters.feesAndCredits(), Fee.create(ONE_HUNDRED_BUCKS, FeeType.UPDATE)) priceParameters.feesAndCredits(), Fee.create(ONE_HUNDRED_BUCKS, FeeType.UPDATE))
: priceParameters.feesAndCredits(); : priceParameters.feesAndCredits();

View file

@ -21,7 +21,6 @@ import com.google.common.collect.ImmutableList;
import google.registry.keyring.api.KeySerializer; import google.registry.keyring.api.KeySerializer;
import google.registry.model.server.KmsSecret; import google.registry.model.server.KmsSecret;
import google.registry.model.server.KmsSecretRevision; import google.registry.model.server.KmsSecretRevision;
import google.registry.model.server.KmsSecretRevision.Builder;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.BouncyCastleProviderRule;
import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPKeyPair;
@ -178,7 +177,7 @@ public class KmsKeyringTest {
KmsConnection kmsConnection = new FakeKmsConnection(); KmsConnection kmsConnection = new FakeKmsConnection();
KmsSecretRevision secretRevision = KmsSecretRevision secretRevision =
new Builder() new KmsSecretRevision.Builder()
.setEncryptedValue(kmsConnection.encrypt(secretName, secretValue).ciphertext()) .setEncryptedValue(kmsConnection.encrypt(secretName, secretValue).ciphertext())
.setKmsCryptoKeyVersionName(KmsTestHelper.DUMMY_CRYPTO_KEY_VERSION) .setKmsCryptoKeyVersionName(KmsTestHelper.DUMMY_CRYPTO_KEY_VERSION)
.setParent(secretName) .setParent(secretName)

View file

@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assert_;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Id;
@ -84,7 +85,7 @@ public class EntityTestCase {
outer: for (String fieldPath : fieldPaths) { outer: for (String fieldPath : fieldPaths) {
// Walk the field path and grab the value referred to on the object using reflection. // Walk the field path and grab the value referred to on the object using reflection.
Object fieldValue = obj; Object fieldValue = obj;
for (String fieldName : fieldPath.split("\\.")) { for (String fieldName : Splitter.on('.').split(fieldPath)) {
if (fieldValue == null) { if (fieldValue == null) {
throw new RuntimeException(String.format("field '%s' not found on %s", throw new RuntimeException(String.format("field '%s' not found on %s",
fieldPath, obj.getClass().getSimpleName())); fieldPath, obj.getClass().getSimpleName()));

View file

@ -95,7 +95,7 @@ public final class StaticResourceServlet extends HttpServlet {
String prefix = config.getInitParameter("prefix"); String prefix = config.getInitParameter("prefix");
verify(prefix.startsWith("/")); verify(prefix.startsWith("/"));
boolean isDirectory = Files.isDirectory(root); boolean isDirectory = Files.isDirectory(root);
verify(!isDirectory || isDirectory && prefix.endsWith("/")); verify(!isDirectory || (isDirectory && prefix.endsWith("/")));
fileServer = Optional.of(new FileServer(root, prefix)); fileServer = Optional.of(new FileServer(root, prefix));
} }

View file

@ -91,7 +91,6 @@ import google.registry.model.registry.label.PremiumList.PremiumListRevision;
import google.registry.model.registry.label.ReservedList; import google.registry.model.registry.label.ReservedList;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.model.transfer.TransferData; import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferData.Builder;
import google.registry.model.transfer.TransferStatus; import google.registry.model.transfer.TransferStatus;
import google.registry.tmch.LordnTaskUtils; import google.registry.tmch.LordnTaskUtils;
import java.util.Arrays; import java.util.Arrays;
@ -383,7 +382,8 @@ public class DatastoreHelper {
registrar.asBuilder().setAllowedTlds(difference(registrar.getAllowedTlds(), tld)).build()); registrar.asBuilder().setAllowedTlds(difference(registrar.getAllowedTlds(), tld)).build());
} }
private static Builder createTransferDataBuilder(DateTime requestTime, DateTime expirationTime) { private static TransferData.Builder createTransferDataBuilder(
DateTime requestTime, DateTime expirationTime) {
return new TransferData.Builder() return new TransferData.Builder()
.setTransferStatus(TransferStatus.PENDING) .setTransferStatus(TransferStatus.PENDING)
.setGainingClientId("NewRegistrar") .setGainingClientId("NewRegistrar")
@ -585,7 +585,8 @@ public class DatastoreHelper {
} else { } else {
deleteResource(autorenewPollMessage); deleteResource(autorenewPollMessage);
} }
Builder transferDataBuilder = createTransferDataBuilder(requestTime, expirationTime); TransferData.Builder transferDataBuilder =
createTransferDataBuilder(requestTime, expirationTime);
return persistResource(domain.asBuilder() return persistResource(domain.asBuilder()
.setPersistedCurrentSponsorClientId("TheRegistrar") .setPersistedCurrentSponsorClientId("TheRegistrar")
.addStatusValue(StatusValue.PENDING_TRANSFER) .addStatusValue(StatusValue.PENDING_TRANSFER)

View file

@ -49,6 +49,11 @@ public final class FakeServletInputStream extends ServletInputStream {
return input.read(); return input.read();
} }
@Override
public int read(byte[] b, int off, int len) throws IOException {
return input.read(b, off, len);
}
@Override @Override
public void close() throws IOException { public void close() throws IOException {
input.close(); input.close();

View file

@ -30,6 +30,7 @@ import com.google.appengine.tools.pipeline.impl.servlets.PipelineServlet;
import com.google.appengine.tools.pipeline.impl.servlets.TaskHandler; import com.google.appengine.tools.pipeline.impl.servlets.TaskHandler;
import com.google.apphosting.api.ApiProxy; import com.google.apphosting.api.ApiProxy;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import google.registry.mapreduce.MapreduceRunner; import google.registry.mapreduce.MapreduceRunner;
import google.registry.testing.AppEngineRule; import google.registry.testing.AppEngineRule;
@ -224,11 +225,11 @@ public abstract class MapreduceTestCase<T> extends ShardableTestCase {
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
Map<String, String> result = new HashMap<>(); Map<String, String> result = new HashMap<>();
String[] params = requestBody.split("&"); Iterable<String> params = Splitter.on('&').split(requestBody);
for (String param : params) { for (String param : params) {
String[] pair = param.split("="); List<String> pair = Splitter.on('=').splitToList(param);
String name = pair[0]; String name = pair.get(0);
String value = URLDecoder.decode(pair[1], "UTF-8"); String value = URLDecoder.decode(pair.get(1), "UTF-8");
if (result.containsKey(name)) { if (result.containsKey(name)) {
throw new IllegalArgumentException("Duplicate parameter: " + requestBody); throw new IllegalArgumentException("Duplicate parameter: " + requestBody);
} }

View file

@ -70,7 +70,7 @@ public abstract class CommandTestCase<C extends Command> {
public TemporaryFolder tmpDir = new TemporaryFolder(); public TemporaryFolder tmpDir = new TemporaryFolder();
@Before @Before
public final void beforeCommandTestCase() { public final void beforeCommandTestCase() throws Exception {
// Ensure the UNITTEST environment has been set before constructing a new command instance. // Ensure the UNITTEST environment has been set before constructing a new command instance.
RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule); RegistryToolEnvironment.UNITTEST.setup(systemPropertyRule);
command = newCommandInstance(); command = newCommandInstance();
@ -212,9 +212,10 @@ public abstract class CommandTestCase<C extends Command> {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected C newCommandInstance() { protected C newCommandInstance() throws Exception {
try { try {
return (C) new TypeToken<C>(getClass()){}.getRawType().newInstance(); return (C)
new TypeToken<C>(getClass()) {}.getRawType().getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException e) { } catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View file

@ -298,7 +298,7 @@ public class WhoisReaderTest {
@Test @Test
public void testNameserverLookupByIpWhitespace() throws Exception { public void testNameserverLookupByIpWhitespace() throws Exception {
assertNsLookup((" \t\t NAMESERVER \t 43.34.12.213 \r\n"), "43.34.12.213"); assertNsLookup(" \t\t NAMESERVER \t 43.34.12.213 \r\n", "43.34.12.213");
} }
@Test @Test

View file

@ -51,14 +51,14 @@ public class DateAdapterTest {
@Test @Test
public void testUnmarshalEmpty() { public void testUnmarshalEmpty() {
assertThat((new DateAdapter()).unmarshal(null)).isNull(); assertThat(new DateAdapter().unmarshal(null)).isNull();
assertThat((new DateAdapter()).unmarshal("")).isNull(); assertThat(new DateAdapter().unmarshal("")).isNull();
} }
@Test @Test
public void testUnmarshalInvalid() { public void testUnmarshalInvalid() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> assertThat((new DateAdapter()).unmarshal("oh my goth")).isNull()); () -> assertThat(new DateAdapter().unmarshal("oh my goth")).isNull());
} }
} }

View file

@ -43,7 +43,7 @@ public class UtcDateTimeAdapterTest {
@Test @Test
public void testMarshalEmpty() { public void testMarshalEmpty() {
assertThat((new UtcDateTimeAdapter()).marshal(null)).isEmpty(); assertThat(new UtcDateTimeAdapter().marshal(null)).isEmpty();
} }
@Test @Test
@ -60,14 +60,14 @@ public class UtcDateTimeAdapterTest {
@Test @Test
public void testUnmarshalEmpty() { public void testUnmarshalEmpty() {
assertThat((new UtcDateTimeAdapter()).unmarshal(null)).isNull(); assertThat(new UtcDateTimeAdapter().unmarshal(null)).isNull();
assertThat((new UtcDateTimeAdapter()).unmarshal("")).isNull(); assertThat(new UtcDateTimeAdapter().unmarshal("")).isNull();
} }
@Test @Test
public void testUnmarshalInvalid() { public void testUnmarshalInvalid() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> assertThat((new UtcDateTimeAdapter()).unmarshal("oh my goth")).isNull()); () -> assertThat(new UtcDateTimeAdapter().unmarshal("oh my goth")).isNull());
} }
} }