Fix some statically detected code issues

This includes: unnecessary semicolons, suppress warnings, switch statements, final/private qualifiers, Optional wrapping, conditionals, both inline and non-inline variables, ternaries, Collection putAll() calls, StringBuilders, and throws declarations.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=244182539
This commit is contained in:
mcilwain 2019-04-18 07:34:10 -07:00 committed by jianglai
parent 9f360587ff
commit 24bb78bd16
54 changed files with 107 additions and 158 deletions

View file

@ -236,7 +236,7 @@ public final class DeleteOldCommitLogsAction implements Runnable {
enum Status { enum Status {
ALREADY_DELETED, ALREADY_DELETED,
AFTER_THRESHOLD, AFTER_THRESHOLD,
SUCCESS; SUCCESS
} }
public abstract Status status(); public abstract Status status();

View file

@ -116,7 +116,6 @@ public class SafeBrowsingTransforms {
* @param clientSupplier a serializable CloseableHttpClient supplier * @param clientSupplier a serializable CloseableHttpClient supplier
*/ */
@VisibleForTesting @VisibleForTesting
@SuppressWarnings("unchecked")
EvaluateSafeBrowsingFn( EvaluateSafeBrowsingFn(
ValueProvider<String> apiKeyProvider, ValueProvider<String> apiKeyProvider,
Retrier retrier, Retrier retrier,

View file

@ -473,7 +473,7 @@ public final class RegistryConfig {
PRODUCTION, PRODUCTION,
/** Pilot mode, for everything else (e.g. sandbox). */ /** Pilot mode, for everything else (e.g. sandbox). */
PILOT; PILOT
} }
/** /**

View file

@ -15,7 +15,6 @@
package google.registry.cron; package google.registry.cron;
import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions;
@ -24,6 +23,7 @@ import google.registry.request.Action;
import google.registry.request.Parameter; import google.registry.request.Parameter;
import google.registry.request.auth.Auth; import google.registry.request.auth.Auth;
import google.registry.util.TaskQueueUtils; import google.registry.util.TaskQueueUtils;
import java.time.Duration;
import java.util.Optional; import java.util.Optional;
import java.util.Random; import java.util.Random;
import javax.inject.Inject; import javax.inject.Inject;
@ -50,11 +50,12 @@ public final class CommitLogFanoutAction implements Runnable {
public void run() { public void run() {
Queue taskQueue = getQueue(queue); Queue taskQueue = getQueue(queue);
for (int bucketId : CommitLogBucket.getBucketIds()) { for (int bucketId : CommitLogBucket.getBucketIds()) {
TaskOptions taskOptions = TaskOptions.Builder.withUrl(endpoint) long delay =
jitterSeconds.map(i -> random.nextInt((int) Duration.ofSeconds(i).toMillis())).orElse(0);
TaskOptions taskOptions =
TaskOptions.Builder.withUrl(endpoint)
.param(BUCKET_PARAM, Integer.toString(bucketId)) .param(BUCKET_PARAM, Integer.toString(bucketId))
.countdownMillis(jitterSeconds.isPresent() .countdownMillis(delay);
? random.nextInt((int) SECONDS.toMillis(jitterSeconds.get()))
: 0);
taskQueueUtils.enqueue(taskQueue, taskOptions); taskQueueUtils.enqueue(taskQueue, taskOptions);
} }
} }

View file

@ -113,12 +113,9 @@ public class FlowDocumentation {
/** Iterates through javadoc tags on the underlying class and calls specific parsing methods. */ /** Iterates through javadoc tags on the underlying class and calls specific parsing methods. */
private void parseTags(ClassDoc flowDoc) { private void parseTags(ClassDoc flowDoc) {
for (Tag tag : flowDoc.tags()) { for (Tag tag : flowDoc.tags()) {
switch (tag.name()) { // Everything else is not a relevant tag.
case "@error": if ("@error".equals(tag.name())) {
parseErrorTag(tag); parseErrorTag(tag);
break;
default:
// Not a relevant tag.
} }
} }
} }

View file

@ -509,7 +509,6 @@ public class DomainFlowUtils {
* (if opening the message interval). This may cause an autorenew billing event to have an end * (if opening the message interval). This may cause an autorenew billing event to have an end
* time earlier than its event time (i.e. if it's being ended before it was ever triggered). * time earlier than its event time (i.e. if it's being ended before it was ever triggered).
*/ */
@SuppressWarnings("unchecked")
public static void updateAutorenewRecurrenceEndTime(DomainBase domain, DateTime newEndTime) { public static void updateAutorenewRecurrenceEndTime(DomainBase domain, DateTime newEndTime) {
Optional<PollMessage.Autorenew> autorenewPollMessage = Optional<PollMessage.Autorenew> autorenewPollMessage =
Optional.ofNullable(ofy().load().key(domain.getAutorenewPollMessage()).now()); Optional.ofNullable(ofy().load().key(domain.getAutorenewPollMessage()).now());

View file

@ -74,8 +74,6 @@ public final class PgpHelper {
public static PGPPublicKey lookupPublicKey( public static PGPPublicKey lookupPublicKey(
PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) { PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) {
try { try {
// Safe by specification.
@SuppressWarnings("unchecked")
Iterator<PGPPublicKeyRing> results = Iterator<PGPPublicKeyRing> results =
keyring.getKeyRings(checkNotNull(query, "query"), true, true); keyring.getKeyRings(checkNotNull(query, "query"), true, true);
verify(results.hasNext(), "No public key found matching substring: %s", query); verify(results.hasNext(), "No public key found matching substring: %s", query);
@ -98,7 +96,6 @@ public final class PgpHelper {
* @throws VerifyException if either keys couldn't be found. * @throws VerifyException if either keys couldn't be found.
* @see #lookupPublicKey * @see #lookupPublicKey
*/ */
@SuppressWarnings("deprecation")
public static PGPKeyPair lookupKeyPair( public static PGPKeyPair lookupKeyPair(
PGPPublicKeyRingCollection publics, PGPPublicKeyRingCollection publics,
PGPSecretKeyRingCollection privates, PGPSecretKeyRingCollection privates,
@ -130,8 +127,6 @@ public final class PgpHelper {
*/ */
public static Optional<PGPPublicKey> lookupPublicSubkey( public static Optional<PGPPublicKey> lookupPublicSubkey(
PGPPublicKeyRing ring, KeyRequirement want) { PGPPublicKeyRing ring, KeyRequirement want) {
// Safe by specification.
@SuppressWarnings("unchecked")
Iterator<PGPPublicKey> keys = ring.getPublicKeys(); Iterator<PGPPublicKey> keys = ring.getPublicKeys();
while (keys.hasNext()) { while (keys.hasNext()) {
PGPPublicKey key = keys.next(); PGPPublicKey key = keys.next();

View file

@ -53,7 +53,6 @@ import google.registry.model.tmch.TmchCrl;
public final class EntityClasses { public final class EntityClasses {
/** Set of entity classes. */ /** Set of entity classes. */
@SuppressWarnings("unchecked") // varargs
public static final ImmutableSet<Class<? extends ImmutableObject>> ALL_CLASSES = public static final ImmutableSet<Class<? extends ImmutableObject>> ALL_CLASSES =
ImmutableSet.of( ImmutableSet.of(
AllocationToken.class, AllocationToken.class,

View file

@ -140,7 +140,7 @@ public abstract class ImmutableObject implements Cloneable {
} }
/** Helper function to recursively hydrate an ImmutableObject. */ /** Helper function to recursively hydrate an ImmutableObject. */
private static final Object hydrate(Object value) { private static Object hydrate(Object value) {
if (value instanceof Key) { if (value instanceof Key) {
return hydrate(ofy().load().key((Key<?>) value).now()); return hydrate(ofy().load().key((Key<?>) value).now());
} else if (value instanceof Map) { } else if (value instanceof Map) {

View file

@ -608,7 +608,6 @@ public abstract class BillingEvent extends ImmutableObject
} }
@Override @Override
@SuppressWarnings("unchecked")
public Modification build() { public Modification build() {
Modification instance = getInstance(); Modification instance = getInstance();
checkNotNull(instance.reason); checkNotNull(instance.reason);

View file

@ -53,7 +53,7 @@ public class DesignatedContact extends ImmutableObject {
@XmlEnumValue("tech") @XmlEnumValue("tech")
TECH, TECH,
/** The registrant type is not reflected in XML and exists only for internal use. */ /** The registrant type is not reflected in XML and exists only for internal use. */
REGISTRANT; REGISTRANT
} }
public static DesignatedContact create(Type type, Key<ContactResource> contact) { public static DesignatedContact create(Type type, Key<ContactResource> contact) {

View file

@ -60,7 +60,7 @@ public class LaunchCheckExtension extends ImmutableObject implements CommandExte
/** A check to see if there are matching trademarks on the specified domain names. */ /** A check to see if there are matching trademarks on the specified domain names. */
@XmlEnumValue("claims") @XmlEnumValue("claims")
CLAIMS; CLAIMS
} }
/** /**

View file

@ -72,7 +72,7 @@ public class LaunchCreateExtension extends LaunchExtension implements CommandExt
* uses a "first-come, first-served" model. * uses a "first-come, first-served" model.
*/ */
@XmlEnumValue("registration") @XmlEnumValue("registration")
REGISTRATION; REGISTRATION
} }
@XmlAttribute @XmlAttribute

View file

@ -28,7 +28,7 @@ public class RestoreCommand {
REQUEST, REQUEST,
@XmlEnumValue("report") @XmlEnumValue("report")
REPORT; REPORT
} }
/** The restore operation. */ /** The restore operation. */

View file

@ -151,14 +151,10 @@ public class EppInput extends ImmutableObject {
/** Get the extension based on type, or null. If there are multiple, it chooses the first. */ /** Get the extension based on type, or null. If there are multiple, it chooses the first. */
public <E extends CommandExtension> Optional<E> getSingleExtension(Class<E> clazz) { public <E extends CommandExtension> Optional<E> getSingleExtension(Class<E> clazz) {
return Optional.ofNullable( return getCommandWrapper().getExtensions().stream()
getCommandWrapper()
.getExtensions()
.stream()
.filter(clazz::isInstance) .filter(clazz::isInstance)
.map(clazz::cast) .map(clazz::cast)
.findFirst() .findFirst();
.orElse(null));
} }
/** A tag that goes inside of an EPP {@literal <command>}. */ /** A tag that goes inside of an EPP {@literal <command>}. */
@ -225,7 +221,7 @@ public class EppInput extends ImmutableObject {
REJECT, REJECT,
@XmlEnumValue("request") @XmlEnumValue("request")
REQUEST; REQUEST
} }
@XmlAttribute(name = "op") @XmlAttribute(name = "op")
@ -251,7 +247,7 @@ public class EppInput extends ImmutableObject {
/** Request the next poll message. */ /** Request the next poll message. */
@XmlEnumValue("req") @XmlEnumValue("req")
REQUEST; REQUEST
} }
@XmlAttribute @XmlAttribute

View file

@ -31,7 +31,7 @@ public class MarkContact extends CommonMarkContactFields {
AGENT, AGENT,
@XmlEnumValue("thirdParty") @XmlEnumValue("thirdParty")
THIRD_PARTY; THIRD_PARTY
} }
@XmlAttribute @XmlAttribute

View file

@ -31,7 +31,7 @@ public class MarkHolder extends CommonMarkContactFields {
ASSIGNEE, ASSIGNEE,
@XmlEnumValue("licensee") @XmlEnumValue("licensee")
LICENSEE; LICENSEE
} }
@XmlAttribute @XmlAttribute

View file

@ -165,7 +165,7 @@ public class Registrar extends ImmutableObject implements Buildable, Jsonifiable
* This registrar is completely disabled and cannot perform any EPP actions whatsoever, nor log * This registrar is completely disabled and cannot perform any EPP actions whatsoever, nor log
* in to the registrar console. * in to the registrar console.
*/ */
DISABLED; DISABLED
} }
/** Regex for E.164 phone number format specified by {@code contact.xsd}. */ /** Regex for E.164 phone number format specified by {@code contact.xsd}. */

View file

@ -32,7 +32,7 @@ public abstract class CheckApiMetric {
private final String displayLabel; private final String displayLabel;
private Tier(String displayLabel) { Tier(String displayLabel) {
this.displayLabel = displayLabel; this.displayLabel = displayLabel;
} }
@ -49,7 +49,7 @@ public abstract class CheckApiMetric {
private final String displayLabel; private final String displayLabel;
private Availability(String displayLabel) { Availability(String displayLabel) {
this.displayLabel = displayLabel; this.displayLabel = displayLabel;
} }
@ -67,7 +67,7 @@ public abstract class CheckApiMetric {
private final String displayLabel; private final String displayLabel;
private Status(String displayLabel) { Status(String displayLabel) {
this.displayLabel = displayLabel; this.displayLabel = displayLabel;
} }

View file

@ -86,7 +86,7 @@ public class WebWhoisProtocolsModule {
httpServerCodecProvider, httpServerCodecProvider,
httpServerExpectContinueHandlerProvider, httpServerExpectContinueHandlerProvider,
webWhoisRedirectHandlerProvides); webWhoisRedirectHandlerProvides);
}; }
@Provides @Provides
@HttpsWhoisProtocol @HttpsWhoisProtocol
@ -101,7 +101,7 @@ public class WebWhoisProtocolsModule {
httpServerCodecProvider, httpServerCodecProvider,
httpServerExpectContinueHandlerProvider, httpServerExpectContinueHandlerProvider,
webWhoisRedirectHandlerProvides); webWhoisRedirectHandlerProvides);
}; }
@Provides @Provides
static HttpServerCodec provideHttpServerCodec() { static HttpServerCodec provideHttpServerCodec() {

View file

@ -105,7 +105,6 @@ public class WebWhoisRedirectHandler extends SimpleChannelInboundHandler<HttpReq
isHttps isHttps
? new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN) ? new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)
: new DefaultFullHttpResponse(HTTP_1_1, OK); : new DefaultFullHttpResponse(HTTP_1_1, OK);
;
} else { } else {
// HTTP -> HTTPS is a 301 redirect, whereas HTTPS -> web WHOIS site is 302 redirect. // HTTP -> HTTPS is a 301 redirect, whereas HTTPS -> web WHOIS site is 302 redirect.
response = new DefaultFullHttpResponse(HTTP_1_1, isHttps ? FOUND : MOVED_PERMANENTLY); response = new DefaultFullHttpResponse(HTTP_1_1, isHttps ? FOUND : MOVED_PERMANENTLY);

View file

@ -235,10 +235,7 @@ public abstract class RdapActionBase implements Runnable {
if (userAuthInfo.isUserAdmin()) { if (userAuthInfo.isUserAdmin()) {
return true; return true;
} }
if (registrarAccessor.getAllClientIdWithRoles().isEmpty()) { return !registrarAccessor.getAllClientIdWithRoles().isEmpty();
return false;
}
return true;
} }
DeletedItemHandling getDeletedItemHandling() { DeletedItemHandling getDeletedItemHandling() {

View file

@ -54,10 +54,6 @@ public final class RydeEncoder extends FilterOutputStream {
private final OutputStream sigOutput; private final OutputStream sigOutput;
private final RydePgpSigningOutputStream signer; private final RydePgpSigningOutputStream signer;
private final OutputStream encryptLayer;
private final OutputStream kompressor;
private final OutputStream fileLayer;
private final OutputStream tarLayer;
// We use a Closer to handle the stream .close, to make sure it's done correctly. // We use a Closer to handle the stream .close, to make sure it's done correctly.
private final Closer closer = Closer.create(); private final Closer closer = Closer.create();
private boolean isClosed = false; private boolean isClosed = false;
@ -73,10 +69,12 @@ public final class RydeEncoder extends FilterOutputStream {
super(null); super(null);
this.sigOutput = sigOutput; this.sigOutput = sigOutput;
signer = closer.register(new RydePgpSigningOutputStream(checkNotNull(rydeOutput), signingKey)); signer = closer.register(new RydePgpSigningOutputStream(checkNotNull(rydeOutput), signingKey));
encryptLayer = closer.register(openEncryptor(signer, RYDE_USE_INTEGRITY_PACKET, receiverKeys)); OutputStream encryptLayer =
kompressor = closer.register(openCompressor(encryptLayer)); closer.register(openEncryptor(signer, RYDE_USE_INTEGRITY_PACKET, receiverKeys));
fileLayer = closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified)); OutputStream kompressor = closer.register(openCompressor(encryptLayer));
tarLayer = OutputStream fileLayer =
closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified));
OutputStream tarLayer =
closer.register(openTarWriter(fileLayer, dataLength, filenamePrefix + ".xml", modified)); closer.register(openTarWriter(fileLayer, dataLength, filenamePrefix + ".xml", modified));
this.out = tarLayer; this.out = tarLayer;
} }

View file

@ -96,7 +96,6 @@ public class RydePgpSigningOutputStream extends ImprovedOutputStream {
* googler who was also uncertain about the precise reason why it's needed. * googler who was also uncertain about the precise reason why it's needed.
*/ */
private static void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) { private static void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) {
@SuppressWarnings("unchecked") // safe by specification.
Iterator<String> uidIter = publicKey.getUserIDs(); Iterator<String> uidIter = publicKey.getUserIDs();
if (uidIter.hasNext()) { if (uidIter.hasNext()) {
PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator(); PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator();

View file

@ -34,7 +34,7 @@ public interface DnsCountQueryCoordinator {
* *
* If your report query requires any additional parameters, add them here. * If your report query requires any additional parameters, add them here.
*/ */
public class Params { class Params {
public BigqueryConnection bigquery; public BigqueryConnection bigquery;
/** The Google Cloud project id. */ /** The Google Cloud project id. */

View file

@ -33,8 +33,6 @@ public class DnsCountQueryCoordinatorModule {
@Config("projectId") String projectId) { @Config("projectId") String projectId) {
DnsCountQueryCoordinator.Params params = DnsCountQueryCoordinator.Params params =
new DnsCountQueryCoordinator.Params(bigquery, projectId); new DnsCountQueryCoordinator.Params(bigquery, projectId);
DnsCountQueryCoordinator result = return instantiate(getClassFromString(customClass, DnsCountQueryCoordinator.class), params);
instantiate(getClassFromString(customClass, DnsCountQueryCoordinator.class), params);
return result;
} }
} }

View file

@ -88,14 +88,12 @@ public final class IcannReportingModule {
static BigqueryConnection provideBigqueryConnection( static BigqueryConnection provideBigqueryConnection(
BigqueryConnection.Builder bigQueryConnectionBuilder) { BigqueryConnection.Builder bigQueryConnectionBuilder) {
try { try {
BigqueryConnection connection = return bigQueryConnectionBuilder
bigQueryConnectionBuilder
.setExecutorService(MoreExecutors.newDirectExecutorService()) .setExecutorService(MoreExecutors.newDirectExecutorService())
.setDatasetId(ICANN_REPORTING_DATA_SET) .setDatasetId(ICANN_REPORTING_DATA_SET)
.setOverwrite(true) .setOverwrite(true)
.setPollInterval(Duration.standardSeconds(1)) .setPollInterval(Duration.standardSeconds(1))
.build(); .build();
return connection;
} catch (Throwable e) { } catch (Throwable e) {
throw new RuntimeException("Could not initialize BigqueryConnection!", e); throw new RuntimeException("Could not initialize BigqueryConnection!", e);
} }

View file

@ -293,11 +293,10 @@ public class AuthenticatedRegistrarAccessor {
// both GAE project admin and members of the gSuiteSupportGroupEmailAddress are considered // both GAE project admin and members of the gSuiteSupportGroupEmailAddress are considered
// admins for the RegistrarConsole. // admins for the RegistrarConsole.
return bypassAdminCheck return !bypassAdminCheck
? false && (userAuthInfo.isUserAdmin()
: userAuthInfo.isUserAdmin()
|| checkIsSupport( || checkIsSupport(
lazyGroupsConnection, user.getEmail(), gSuiteSupportGroupEmailAddress); lazyGroupsConnection, user.getEmail(), gSuiteSupportGroupEmailAddress));
} }
/** /**

View file

@ -98,7 +98,6 @@ public final class Marksdb {
} }
} }
@SuppressWarnings("deprecation")
private static void pgpVerifySignature(byte[] data, byte[] signature, PGPPublicKey publicKey) private static void pgpVerifySignature(byte[] data, byte[] signature, PGPPublicKey publicKey)
throws PGPException, SignatureException { throws PGPException, SignatureException {
Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastleProvider());

View file

@ -30,7 +30,6 @@ public final class TmchData {
private static final String BEGIN_ENCODED_SMD = "-----BEGIN ENCODED SMD-----"; private static final String BEGIN_ENCODED_SMD = "-----BEGIN ENCODED SMD-----";
private static final String END_ENCODED_SMD = "-----END ENCODED SMD-----"; private static final String END_ENCODED_SMD = "-----END ENCODED SMD-----";
@SuppressWarnings("deprecation")
static PGPPublicKey loadPublicKey(ByteSource pgpPublicKeyFile) { static PGPPublicKey loadPublicKey(ByteSource pgpPublicKeyFile) {
try (InputStream input = pgpPublicKeyFile.openStream(); try (InputStream input = pgpPublicKeyFile.openStream();
InputStream decoder = PGPUtil.getDecoderStream(input)) { InputStream decoder = PGPUtil.getDecoderStream(input)) {

View file

@ -53,13 +53,11 @@ final class BigqueryParameters {
/** Returns a new BigqueryConnection constructed according to the delegate's flag settings. */ /** Returns a new BigqueryConnection constructed according to the delegate's flag settings. */
BigqueryConnection newConnection(BigqueryConnection.Builder connectionBuilder) throws Exception { BigqueryConnection newConnection(BigqueryConnection.Builder connectionBuilder) throws Exception {
BigqueryConnection connection = return connectionBuilder
connectionBuilder
.setExecutorService(Executors.newFixedThreadPool(bigqueryNumThreads)) .setExecutorService(Executors.newFixedThreadPool(bigqueryNumThreads))
.setDatasetId(bigqueryDataset) .setDatasetId(bigqueryDataset)
.setOverwrite(bigqueryOverwrite) .setOverwrite(bigqueryOverwrite)
.setPollInterval(bigqueryPollInterval) .setPollInterval(bigqueryPollInterval)
.build(); .build();
return connection;
} }
} }

View file

@ -20,5 +20,5 @@ package google.registry.tools;
* <p>This exists only to allow us to test ShellCommand. * <p>This exists only to allow us to test ShellCommand.
*/ */
interface CommandRunner { interface CommandRunner {
public void run(String[] args) throws Exception; void run(String[] args) throws Exception;
} }

View file

@ -307,8 +307,7 @@ final class RegistrarContactCommand extends MutatingCommand {
private void unsetOtherWhoisAbuseFlags( private void unsetOtherWhoisAbuseFlags(
ImmutableSet<RegistrarContact> contacts, @Nullable String emailAddressNotToChange) { ImmutableSet<RegistrarContact> contacts, @Nullable String emailAddressNotToChange) {
for (RegistrarContact contact : contacts) { for (RegistrarContact contact : contacts) {
if (((emailAddressNotToChange == null) if (!contact.getEmailAddress().equals(emailAddressNotToChange)
|| !contact.getEmailAddress().equals(emailAddressNotToChange))
&& contact.getVisibleInDomainWhoisAsAbuse()) { && contact.getVisibleInDomainWhoisAsAbuse()) {
RegistrarContact newContact = RegistrarContact newContact =
contact.asBuilder().setVisibleInDomainWhoisAsAbuse(false).build(); contact.asBuilder().setVisibleInDomainWhoisAsAbuse(false).build();

View file

@ -41,8 +41,7 @@ public abstract class ParameterConverterValidator<T>
convert(value); convert(value);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
ParameterException pe = ParameterException pe =
new ParameterException(String.format("%s=%s %s", name, value, messageForInvalid)); new ParameterException(String.format("%s=%s %s", name, value, messageForInvalid), e);
pe.initCause(e);
throw pe; throw pe;
} }
} }

View file

@ -47,7 +47,6 @@ public class ResaveAllHistoryEntriesAction implements Runnable {
@Inject Response response; @Inject Response response;
@Inject ResaveAllHistoryEntriesAction() {} @Inject ResaveAllHistoryEntriesAction() {}
@SuppressWarnings("unchecked")
@Override @Override
public void run() { public void run() {
mrRunner mrRunner

View file

@ -51,9 +51,10 @@ public final class SoyTemplateUtils {
for (SoyFileInfo soyInfo : soyInfos) { for (SoyFileInfo soyInfo : soyInfos) {
builder.add(getResource(soyInfo.getClass(), soyInfo.getFileName())); builder.add(getResource(soyInfo.getClass(), soyInfo.getFileName()));
} }
Map<String, Object> globals = new HashMap<>(); Map<String, Object> globals;
try { try {
globals.putAll(SoyUtils.parseCompileTimeGlobals(asCharSource(SOY_GLOBALS, UTF_8))); globals =
new HashMap<>(SoyUtils.parseCompileTimeGlobals(asCharSource(SOY_GLOBALS, UTF_8)));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to load soy globals", e); throw new RuntimeException("Failed to load soy globals", e);
} }

View file

@ -351,22 +351,18 @@ public final class ConsoleRegistrarCreatorAction implements Runnable {
return; return;
} }
String environment = Ascii.toLowerCase(String.valueOf(registryEnvironment)); String environment = Ascii.toLowerCase(String.valueOf(registryEnvironment));
StringBuilder builder = new StringBuilder(); String body =
builder
.append(
String.format( String.format(
"The following registrar was created in %s by %s:\n", "The following registrar was created in %s by %s:\n",
environment, registrarAccessor.userIdForLogging())) environment, registrarAccessor.userIdForLogging())
.append(toEmailLine(clientId, "clientId")) + toEmailLine(clientId, "clientId")
.append(toEmailLine(name, "name")) + toEmailLine(name, "name")
.append(toEmailLine(billingAccount, "billingAccount")) + toEmailLine(billingAccount, "billingAccount")
.append(toEmailLine(ianaId, "ianaId")) + toEmailLine(ianaId, "ianaId")
.append(toEmailLine(referralEmail, "referralEmail")) + toEmailLine(referralEmail, "referralEmail")
.append(toEmailLine(driveId, "driveId")) + toEmailLine(driveId, "driveId")
.append( + String.format("Gave user %s web access to the registrar\n", consoleUserEmail.get());
String.format("Gave user %s web access to the registrar\n", consoleUserEmail.get()));
sendEmailUtils.sendEmail( sendEmailUtils.sendEmail(
String.format("Registrar %s created in %s", clientId.get(), environment), String.format("Registrar %s created in %s", clientId.get(), environment), body);
builder.toString());
} }
} }

View file

@ -246,8 +246,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
.map(RegistrarContact::toDiffableFieldMap) .map(RegistrarContact::toDiffableFieldMap)
.collect(toImmutableSet()); .collect(toImmutableSet());
// Use LinkedHashMap here to preserve ordering; null values mean we can't use ImmutableMap. // Use LinkedHashMap here to preserve ordering; null values mean we can't use ImmutableMap.
LinkedHashMap<String, Object> result = new LinkedHashMap<>(); LinkedHashMap<String, Object> result = new LinkedHashMap<>(registrar.toDiffableFieldMap());
result.putAll(registrar.toDiffableFieldMap());
result.put("contacts", expandedContacts); result.put("contacts", expandedContacts);
return result; return result;
} }

View file

@ -105,7 +105,7 @@ public final class PosixTarHeader {
DIRECTORY, DIRECTORY,
/** This indicates we read a file from an archive with an unsupported type. */ /** This indicates we read a file from an archive with an unsupported type. */
UNSUPPORTED; UNSUPPORTED
} }
public static final int HEADER_LENGTH = 512; public static final int HEADER_LENGTH = 512;

View file

@ -20,7 +20,6 @@ import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION; import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION;
import static com.google.common.net.HttpHeaders.CONTENT_LENGTH; import static com.google.common.net.HttpHeaders.CONTENT_LENGTH;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE; import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPHeader;
@ -73,18 +72,20 @@ public final class UrlFetchUtils {
checkState( checkState(
!data.contains(boundary), !data.contains(boundary),
"Multipart data contains autogenerated boundary: %s", boundary); "Multipart data contains autogenerated boundary: %s", boundary);
StringBuilder multipart = new StringBuilder(); String multipart =
multipart.append(format("--%s\r\n", boundary)); String.format("--%s\r\n", boundary)
multipart.append(format("%s: form-data; name=\"%s\"; filename=\"%s\"\r\n", + String.format(
CONTENT_DISPOSITION, name, filename)); "%s: form-data; name=\"%s\"; filename=\"%s\"\r\n",
multipart.append(format("%s: %s\r\n", CONTENT_TYPE, contentType.toString())); CONTENT_DISPOSITION, name, filename)
multipart.append("\r\n"); + String.format("%s: %s\r\n", CONTENT_TYPE, contentType)
multipart.append(data); + "\r\n"
multipart.append("\r\n"); + data
multipart.append(format("--%s--\r\n", boundary)); + "\r\n"
byte[] payload = multipart.toString().getBytes(UTF_8); + String.format("--%s--\r\n", boundary);
byte[] payload = multipart.getBytes(UTF_8);
request.addHeader( request.addHeader(
new HTTPHeader(CONTENT_TYPE, format("multipart/form-data; boundary=\"%s\"", boundary))); new HTTPHeader(
CONTENT_TYPE, String.format("multipart/form-data;" + " boundary=\"%s\"", boundary)));
request.addHeader(new HTTPHeader(CONTENT_LENGTH, Integer.toString(payload.length))); request.addHeader(new HTTPHeader(CONTENT_LENGTH, Integer.toString(payload.length)));
request.setPayload(payload); request.setPayload(payload);
} }

View file

@ -425,7 +425,6 @@ public class CloudDnsWriterTest {
} }
@Test @Test
@SuppressWarnings("unchecked")
public void retryMutateZoneOnError() { public void retryMutateZoneOnError() {
CloudDnsWriter spyWriter = spy(writer); CloudDnsWriter spyWriter = spy(writer);
// First call - throw. Second call - do nothing. // First call - throw. Second call - do nothing.

View file

@ -16,6 +16,7 @@ package google.registry.documentation;
import static com.google.common.truth.Truth.assert_; import static com.google.common.truth.Truth.assert_;
import static google.registry.util.BuildPathUtils.getProjectRoot; import static google.registry.util.BuildPathUtils.getProjectRoot;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import java.io.IOException; import java.io.IOException;
@ -47,7 +48,7 @@ public class FlowDocumentationTest {
Path goldenMarkdownPath = Path goldenMarkdownPath =
GOLDEN_MARKDOWN_FILEPATH; GOLDEN_MARKDOWN_FILEPATH;
String goldenMarkdown = new String(Files.readAllBytes(goldenMarkdownPath), "UTF-8"); String goldenMarkdown = new String(Files.readAllBytes(goldenMarkdownPath), UTF_8);
// Don't use Truth's isEqualTo() because the output is huge and unreadable for large files. // Don't use Truth's isEqualTo() because the output is huge and unreadable for large files.
DocumentationGenerator generator = new DocumentationGenerator(); DocumentationGenerator generator = new DocumentationGenerator();

View file

@ -86,7 +86,7 @@ public class ExportDomainListsActionTest extends MapreduceTestCase<ExportDomainL
eq(EXPORT_MIME_TYPE), eq(EXPORT_MIME_TYPE),
eq(folderId), eq(folderId),
bytesExportedToDrive.capture()); bytesExportedToDrive.capture());
assertThat(new String(bytesExportedToDrive.getValue(), "UTF-8")).isEqualTo(domains); assertThat(new String(bytesExportedToDrive.getValue(), UTF_8)).isEqualTo(domains);
} }
@Test @Test

View file

@ -60,7 +60,6 @@ import google.registry.xml.ValidationMode;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
@ -183,14 +182,11 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
ImmutableMap.Builder<GracePeriod, BillingEvent> builder = new ImmutableMap.Builder<>(); ImmutableMap.Builder<GracePeriod, BillingEvent> builder = new ImmutableMap.Builder<>();
for (Map.Entry<GracePeriod, ? extends BillingEvent> entry : gracePeriods.entrySet()) { for (Map.Entry<GracePeriod, ? extends BillingEvent> entry : gracePeriods.entrySet()) {
builder.put( builder.put(
((Function<GracePeriod, GracePeriod>)
gracePeriod ->
GracePeriod.create( GracePeriod.create(
gracePeriod.getType(), entry.getKey().getType(),
gracePeriod.getExpirationTime(), entry.getKey().getExpirationTime(),
gracePeriod.getClientId(), entry.getKey().getClientId(),
null)) null),
.apply(entry.getKey()),
stripBillingEventId(entry.getValue())); stripBillingEventId(entry.getValue()));
} }
return builder.build(); return builder.build();

View file

@ -383,7 +383,6 @@ public class BouncyCastleTest {
* Googler who was also uncertain about the precise reason why it's needed. * Googler who was also uncertain about the precise reason why it's needed.
*/ */
private void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) { private void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) {
@SuppressWarnings("unchecked") // Safe by specification.
Iterator<String> uidIter = publicKey.getUserIDs(); Iterator<String> uidIter = publicKey.getUserIDs();
if (uidIter.hasNext()) { if (uidIter.hasNext()) {
PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator(); PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator();

View file

@ -76,7 +76,6 @@ import google.registry.testing.sftp.SftpServerRule;
import google.registry.util.Retrier; import google.registry.util.Retrier;
import google.registry.util.TaskQueueUtils; import google.registry.util.TaskQueueUtils;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -353,7 +352,7 @@ public class RdeUploadActionTest {
+ "upload; last upload attempt was at 2010-10-16T22:23:00.000Z (97 minutes ago)"); + "upload; last upload attempt was at 2010-10-16T22:23:00.000Z (97 minutes ago)");
} }
private String slurp(InputStream is) throws FileNotFoundException, IOException { private String slurp(InputStream is) throws IOException {
return CharStreams.toString(new InputStreamReader(is, UTF_8)); return CharStreams.toString(new InputStreamReader(is, UTF_8));
} }
} }

View file

@ -30,7 +30,6 @@ import google.registry.testing.GpgSystemCommandRule;
import google.registry.testing.ShardableTestCase; import google.registry.testing.ShardableTestCase;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -208,7 +207,7 @@ public class RydeGpgIntegrationTest extends ShardableTestCase {
assertThat(slurp(xmlFile)).isEqualTo(content.get()); assertThat(slurp(xmlFile)).isEqualTo(content.get());
} }
private String slurp(File file) throws FileNotFoundException, IOException { private String slurp(File file) throws IOException {
return CharStreams.toString(new InputStreamReader(new FileInputStream(file), UTF_8)); return CharStreams.toString(new InputStreamReader(new FileInputStream(file), UTF_8));
} }

View file

@ -45,9 +45,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PublishInvoicesActionTest { public class PublishInvoicesActionTest {
private Dataflow dataflow;
private Projects projects;
private Jobs jobs;
private Get get; private Get get;
private BillingEmailUtils emailUtils; private BillingEmailUtils emailUtils;
@ -60,9 +57,9 @@ public class PublishInvoicesActionTest {
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
dataflow = mock(Dataflow.class); Dataflow dataflow = mock(Dataflow.class);
projects = mock(Projects.class); Projects projects = mock(Projects.class);
jobs = mock(Jobs.class); Jobs jobs = mock(Jobs.class);
get = mock(Get.class); get = mock(Get.class);
when(dataflow.projects()).thenReturn(projects); when(dataflow.projects()).thenReturn(projects);
when(projects.jobs()).thenReturn(jobs); when(projects.jobs()).thenReturn(jobs);

View file

@ -82,8 +82,7 @@ public class TestCacheRule extends ExternalResource {
} }
public TestCacheRule build() { public TestCacheRule build() {
TestCacheRule rule = new TestCacheRule(ImmutableList.copyOf(cacheHandlerMap.values())); return new TestCacheRule(ImmutableList.copyOf(cacheHandlerMap.values()));
return rule;
} }
} }

View file

@ -168,7 +168,6 @@ public class NordnUploadActionTest {
assertThat(action.loadAllTasks(queue, "tld")).containsExactly(task); assertThat(action.loadAllTasks(queue, "tld")).containsExactly(task);
} }
@SuppressWarnings("unchecked")
@Test @Test
public void test_loadAllTasks_retryLogic_allFailures() { public void test_loadAllTasks_retryLogic_allFailures() {
Queue queue = mock(Queue.class); Queue queue = mock(Queue.class);

View file

@ -235,7 +235,6 @@ public class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarC
verifyZeroInteractions(connection); verifyZeroInteractions(connection);
} }
@SuppressWarnings("unchecked")
@Test @Test
public void testFailure_groupCreationFails() throws Exception { public void testFailure_groupCreationFails() throws Exception {
when(connection.sendPostRequest( when(connection.sendPostRequest(

View file

@ -24,7 +24,6 @@ import google.registry.testing.AppEngineRule;
import google.registry.tools.LevelDbFileBuilder.Property; import google.registry.tools.LevelDbFileBuilder.Property;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -41,7 +40,7 @@ public class LevelDbFileBuilderTest {
@Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build();
@Test @Test
public void testSingleRecordWrites() throws FileNotFoundException, IOException { public void testSingleRecordWrites() throws IOException {
File subdir = tempFs.newFolder("folder"); File subdir = tempFs.newFolder("folder");
File logFile = new File(subdir, "testfile"); File logFile = new File(subdir, "testfile");
LevelDbFileBuilder builder = new LevelDbFileBuilder(logFile); LevelDbFileBuilder builder = new LevelDbFileBuilder(logFile);
@ -64,7 +63,7 @@ public class LevelDbFileBuilderTest {
} }
@Test @Test
public void testMultipleRecordWrites() throws FileNotFoundException, IOException { public void testMultipleRecordWrites() throws IOException {
File subdir = tempFs.newFolder("folder"); File subdir = tempFs.newFolder("folder");
File logFile = new File(subdir, "testfile"); File logFile = new File(subdir, "testfile");
LevelDbFileBuilder builder = new LevelDbFileBuilder(logFile); LevelDbFileBuilder builder = new LevelDbFileBuilder(logFile);

View file

@ -77,8 +77,7 @@ public class ConsoleUiActionTest {
action.userService = UserServiceFactory.getUserService(); action.userService = UserServiceFactory.getUserService();
action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService); action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
action.paramClientId = Optional.empty(); action.paramClientId = Optional.empty();
AuthResult authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false)); action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.authResult = authResult;
action.environment = RegistryEnvironment.UNITTEST; action.environment = RegistryEnvironment.UNITTEST;
action.registrarAccessor = action.registrarAccessor =

View file

@ -15,6 +15,7 @@
package google.registry.util; package google.registry.util;
import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.JUnitBackports.assertThrows;
import static org.junit.Assert.assertNotEquals;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.net.InetAddresses; import com.google.common.net.InetAddresses;
@ -264,8 +265,8 @@ public class CidrAddressBlockTest extends TestCase {
assertEquals(b0, b1); assertEquals(b0, b1);
assertEquals(b0, new CidrAddressBlock(b0.toString())); assertEquals(b0, new CidrAddressBlock(b0.toString()));
assertEquals(b0.hashCode(), b1.hashCode()); assertEquals(b0.hashCode(), b1.hashCode());
assertFalse(b0.equals(b2)); assertNotEquals(b0, b2);
assertFalse(b0.equals(b3)); assertNotEquals(b0, b3);
} }
public void testIterate() { public void testIterate() {