Fix some issues caught by IntelliJ static code analysis

The most common issues were:
* Arrays.asList() shouldn't be called with a single parameter.
* Broken Javadoc @links.
* Unnecessary casts and type declarations.
* Unnecessary unused variable initializations.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=230994311
This commit is contained in:
mcilwain 2019-01-25 16:53:20 -08:00 committed by Ben McIlwain
parent 3cf26ff9b6
commit c6e58d3bff
39 changed files with 132 additions and 165 deletions

View file

@ -29,7 +29,6 @@ import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.DateTimeUtils.isAtOrAfter;
import static java.nio.channels.Channels.newOutputStream;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparingLong;
import com.google.appengine.tools.cloudstorage.GcsFileOptions;
@ -208,7 +207,7 @@ public final class ExportCommitLogDiffAction implements Runnable {
ImmutableList.Builder<Iterable<? extends ImmutableObject>> entities =
new ImmutableList.Builder<>();
for (CommitLogManifest manifest : chunk) {
entities.add(asList(manifest));
entities.add(ImmutableList.of(manifest));
entities.add(ofy().load().type(CommitLogMutation.class).ancestor(manifest));
}
for (ImmutableObject entity : concat(entities.build())) {

View file

@ -19,13 +19,13 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterators.peekingIterator;
import static google.registry.backup.BackupUtils.createDeserializingIterator;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static java.util.Arrays.asList;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityTranslator;
import com.google.appengine.tools.cloudstorage.GcsFileMetadata;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.PeekingIterator;
import com.google.common.collect.Streams;
@ -106,7 +106,7 @@ public class RestoreCommitLogsAction implements Runnable {
PeekingIterator<ImmutableObject> commitLogs =
peekingIterator(createDeserializingIterator(input));
lastCheckpoint = (CommitLogCheckpoint) commitLogs.next();
saveOfy(asList(lastCheckpoint)); // Save the checkpoint itself.
saveOfy(ImmutableList.of(lastCheckpoint)); // Save the checkpoint itself.
while (commitLogs.hasNext()) {
CommitLogManifest manifest = restoreOneTransaction(commitLogs);
bucketTimestamps.put(manifest.getBucketId(), manifest.getCommitTime());

View file

@ -61,7 +61,7 @@ import org.joda.time.Duration;
* {@link ReadDnsQueueAction}, which is run as a cron job with running time shorter than the cron
* repeat time - meaning there should never be two instances running at once.
*
* @see google.registry.config.RegistryConfig#provideReadDnsQueueRuntime
* @see google.registry.config.RegistryConfig.ConfigModule#provideReadDnsQueueRuntime
*/
public class DnsQueue {

View file

@ -110,7 +110,7 @@ public class CheckBackupAction implements Runnable {
throw e;
} catch (Throwable e) {
throw new InternalServerErrorException(
String.format("Exception occurred while checking datastore exports."), e);
"Exception occurred while checking datastore exports.", e);
}
}

View file

@ -181,7 +181,7 @@ public final class ComparatorKeyring extends ComparingInvocationHandler<Keyring>
return "null";
}
StringBuilder builder = new StringBuilder("");
StringBuilder builder = new StringBuilder();
for (byte b : a.getFingerprint()) {
builder.append(String.format("%02x:", b));
}

View file

@ -137,7 +137,7 @@ public final class KmsUpdater {
* Encrypts updated secrets using KMS. If the configured {@code KeyRing} or {@code CryptoKey}
* associated with a secret doesn't exist, they will first be created.
*
* @see google.registry.config.RegistryConfigSettings#kms
* @see google.registry.config.RegistryConfigSettings.Kms
*/
private ImmutableMap<String, EncryptResponse> encryptValues(Map<String, byte[]> keyValues) {
ImmutableMap.Builder<String, EncryptResponse> encryptedValues = new ImmutableMap.Builder<>();

View file

@ -369,15 +369,8 @@ public abstract class EppResource extends BackupGroupRoot implements Buildable {
Streams.stream(keys).map(key -> (Key<EppResource>) key).collect(toImmutableList());
// Typing shenanigans are required to return the map with the correct required generic type.
return ofy()
.load()
.keys(typedKeys)
.entrySet()
.stream()
.collect(
ImmutableMap
.<Map.Entry<Key<EppResource>, EppResource>, Key<? extends EppResource>, EppResource>
toImmutableMap(Entry::getKey, Entry::getValue));
return ofy().load().keys(typedKeys).entrySet().stream()
.collect(ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue));
}
/**

View file

@ -33,11 +33,10 @@ public final class SchemaVersion {
*/
private static SortedSet<Class<?>> getAllPersistedTypes() {
SortedSet<Class<?>> persistedTypes = new TreeSet<>(Ordering.usingToString());
Queue<Class<?>> queue = new ArrayDeque<>();
// Do a breadth-first search for persisted types, starting with @Entity types and expanding each
// ImmutableObject by querying it for all its persisted field types.
persistedTypes.addAll(EntityClasses.ALL_CLASSES);
queue.addAll(persistedTypes);
Queue<Class<?>> queue = new ArrayDeque<>(persistedTypes);
while (!queue.isEmpty()) {
Class<?> clazz = queue.remove();
if (ImmutableObject.class.isAssignableFrom(clazz)) {

View file

@ -60,7 +60,7 @@ abstract class AugmentedDeleter implements Deleter {
@Override
public Result<Void> key(Key<?> key) {
handleDeletion(Arrays.asList(key));
handleDeletion(ImmutableList.of(key));
return delegate.keys(key);
}

View file

@ -28,7 +28,7 @@ import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
/*
* This package defines all entities which are managed via EPP XML and persisted to the Datastore
* via Objectify.
*

View file

@ -126,7 +126,7 @@ public class TmchXmlSignature {
StringBuilder builder = new StringBuilder();
builder.append("Signature failed core validation\n");
boolean sv = signature.getSignatureValue().validate(context);
builder.append("Signature validation status: " + sv + "\n");
builder.append(String.format("Signature validation status: %s\n", sv));
for (Reference ref : references) {
builder.append("references[");
builder.append(ref.getURI());

View file

@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools;
/**
* Marker interface for commands that use the remote api.
*
* <p>Just implementing this is sufficient to use the remote api; {@link RegistryTool} will
* install it as needed.
* <p>Just implementing this is sufficient to use the remote api; {@link RegistryTool} will install
* it as needed.
*/
package google.registry.tools;
interface CommandWithRemoteApi extends Command {}

View file

@ -43,10 +43,12 @@ final class GetResourceByKeyCommand implements CommandWithRemoteApi {
public void run() {
for (String keyString : mainParameters) {
System.out.println("\n");
Key<EppResource> resourceKey = checkNotNull(
Key.<EppResource>create(keyString), "Could not parse key string: " + keyString);
EppResource resource = checkNotNull(
ofy().load().key(resourceKey).now(), "Could not load resource for key: " + resourceKey);
Key<EppResource> resourceKey =
checkNotNull(Key.create(keyString), "Could not parse key string: " + keyString);
EppResource resource =
checkNotNull(
ofy().load().key(resourceKey).now(),
"Could not load resource for key: " + resourceKey);
System.out.println(expand ? resource.toHydratedString() : resource.toString());
}
}

View file

@ -131,7 +131,7 @@ final class ValidateEscrowDepositCommand implements Command {
}
}
System.out.println();
System.out.printf("Contents:\n");
System.out.println("Contents:");
for (Map.Entry<String, Long> count : counts.entrySet()) {
System.out.printf(" - %s: %,d %s\n",
count.getKey(),
@ -158,9 +158,9 @@ final class ValidateEscrowDepositCommand implements Command {
good = false;
}
if (good) {
System.out.printf("RDE deposit is XML schema valid\n");
System.out.println("RDE deposit is XML schema valid");
} else {
System.out.printf("RDE deposit is XML schema valid but has bad references\n");
System.out.println("RDE deposit is XML schema valid but has bad references");
}
}

View file

@ -83,13 +83,13 @@ public class CreateGroupsAction implements Runnable {
// that type.
groupsConnection.createGroup(groupKey);
groupsConnection.addMemberToGroup(parentGroup, groupKey, Role.MEMBER);
return Optional.<Exception>empty();
return Optional.empty();
} catch (Exception e) {
return Optional.of(e);
}
});
// Return the correct server response based on the results of the group creations.
if (results.stream().filter(Optional::isPresent).count() > 0) {
if (results.stream().anyMatch(Optional::isPresent)) {
StringWriter responseString = new StringWriter();
PrintWriter responseWriter = new PrintWriter(responseString);
for (int i = 0; i < results.size(); i++) {

View file

@ -31,8 +31,8 @@ import javax.annotation.concurrent.NotThreadSafe;
/**
* Exception thrown when a form field contains a bad value.
*
* <p>You can safely throw {@code FormFieldException} from within your validator functions, and
* the field name will automatically be propagated into the exception object for you.
* <p>You can safely throw {@code FormFieldException} from within your validator functions, and the
* field name will automatically be propagated into the exception object for you.
*
* <p>The way that field names work is a bit complicated, because we need to support complex nested
* field names like {@code foo[3].bar}. So what happens is the original exception will be thrown by
@ -41,9 +41,9 @@ import javax.annotation.concurrent.NotThreadSafe;
* name of that component. Then when the exception reaches the user, the {@link #getFieldName()}
* method will produce the fully-qualified field name.
*
* <p>This propagation mechanism is also very important when writing
* {@link FormField.Builder#transform(com.google.common.base.Function) transform} functions, which
* oftentimes will not know the name of the field they're validating.
* <p>This propagation mechanism is also very important when writing {@link
* FormField.Builder#transform} functions, which oftentimes will not know the name of the field
* they're validating.
*/
@NotThreadSafe
@SuppressWarnings("OverrideThrowableToString")

View file

@ -50,27 +50,27 @@ public class CollectionUtils {
/** Turns a null set into an empty set. JAXB leaves lots of null sets lying around. */
public static <T> Set<T> nullToEmpty(@Nullable Set<T> potentiallyNull) {
return firstNonNull(potentiallyNull, ImmutableSet.<T>of());
return firstNonNull(potentiallyNull, ImmutableSet.of());
}
/** Turns a null list into an empty list. */
public static <T> List<T> nullToEmpty(@Nullable List<T> potentiallyNull) {
return firstNonNull(potentiallyNull, ImmutableList.<T>of());
return firstNonNull(potentiallyNull, ImmutableList.of());
}
/** Turns a null map into an empty map. */
public static <T, U> Map<T, U> nullToEmpty(@Nullable Map<T, U> potentiallyNull) {
return firstNonNull(potentiallyNull, ImmutableMap.<T, U>of());
return firstNonNull(potentiallyNull, ImmutableMap.of());
}
/** Turns a null multimap into an empty multimap. */
public static <T, U> Multimap<T, U> nullToEmpty(@Nullable Multimap<T, U> potentiallyNull) {
return firstNonNull(potentiallyNull, ImmutableMultimap.<T, U>of());
return firstNonNull(potentiallyNull, ImmutableMultimap.of());
}
/** Turns a null sorted map into an empty sorted map.. */
public static <T, U> SortedMap<T, U> nullToEmpty(@Nullable SortedMap<T, U> potentiallyNull) {
return firstNonNull(potentiallyNull, ImmutableSortedMap.<T, U>of());
return firstNonNull(potentiallyNull, ImmutableSortedMap.of());
}
/** Defensive copy helper for {@link Set}. */

View file

@ -14,13 +14,12 @@
package google.registry.util;
import static java.util.Arrays.asList;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TransientFailureException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.flogger.FluentLogger;
import java.io.Serializable;
@ -65,7 +64,7 @@ public class TaskQueueUtils implements Serializable {
* @return successfully enqueued task
*/
public TaskHandle enqueue(Queue queue, TaskOptions task) {
return enqueue(queue, asList(task)).get(0);
return enqueue(queue, ImmutableList.of(task)).get(0);
}
/**

View file

@ -25,7 +25,6 @@ import static google.registry.backup.ExportCommitLogDiffAction.DIFF_FILE_PREFIX;
import static google.registry.model.ofy.CommitLogBucket.getBucketIds;
import static google.registry.model.ofy.CommitLogBucket.getBucketKey;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static java.util.Arrays.asList;
import static org.joda.time.DateTimeZone.UTC;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
@ -135,7 +134,7 @@ public class RestoreCommitLogsActionTest {
assertExpectedIds("previous to keep", "b", "d", "e", "f");
assertInDatastore(file1CommitLogs);
assertInDatastore(file2CommitLogs);
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
assertCommitLogBuckets(ImmutableMap.of(1, now.minusMinutes(1), 2, now.minusMinutes(2)));
}
@ -149,7 +148,7 @@ public class RestoreCommitLogsActionTest {
ofy().clearSessionCache();
assertExpectedIds("previous to keep");
assertInDatastore(commitLogs);
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
assertCommitLogBuckets(ImmutableMap.of());
}
@ -168,7 +167,7 @@ public class RestoreCommitLogsActionTest {
ofy().clearSessionCache();
assertExpectedIds("previous to keep", "a", "b");
assertInDatastore(commitLogs);
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
assertCommitLogBuckets(ImmutableMap.of(1, now));
}
@ -188,7 +187,7 @@ public class RestoreCommitLogsActionTest {
ofy().clearSessionCache();
assertExpectedIds("previous to keep");
assertInDatastore(commitLogs);
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
assertCommitLogBuckets(ImmutableMap.of(1, now));
}
@ -205,7 +204,7 @@ public class RestoreCommitLogsActionTest {
ofy().clearSessionCache();
assertExpectedIds("previous to keep");
assertInDatastore(commitLogs);
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
assertCommitLogBuckets(ImmutableMap.of(1, now));
}
@ -222,7 +221,7 @@ public class RestoreCommitLogsActionTest {
ofy().clearSessionCache();
assertThat(ofy().load().entity(TestObject.create("existing")).now().getField()).isEqualTo("b");
assertInDatastore(commitLogs);
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
assertCommitLogBuckets(ImmutableMap.of(1, now));
}
@ -242,7 +241,7 @@ public class RestoreCommitLogsActionTest {
assertExpectedIds("previous to keep");
assertInDatastore(commitLogs);
assertCommitLogBuckets(ImmutableMap.of(1, now));
assertInDatastore(asList(CommitLogCheckpointRoot.create(now)));
assertInDatastore(CommitLogCheckpointRoot.create(now));
}
private CommitLogCheckpoint createCheckpoint(DateTime now) {
@ -280,6 +279,10 @@ public class RestoreCommitLogsActionTest {
.containsExactly((Object[]) ids);
}
private void assertInDatastore(ImmutableObject entity) {
assertThat(ofy().load().entity(entity).now()).isEqualTo(entity);
}
private void assertInDatastore(Iterable<? extends ImmutableObject> entities) {
assertThat(ofy().load().entities(entities).values()).containsExactlyElementsIn(entities);
}

View file

@ -24,7 +24,6 @@ import google.registry.export.datastore.Operation.Metadata;
import google.registry.export.datastore.Operation.Progress;
import google.registry.testing.FakeClock;
import google.registry.testing.TestDataHelper;
import google.registry.util.Clock;
import java.io.IOException;
import org.joda.time.DateTime;
import org.joda.time.Duration;
@ -91,8 +90,8 @@ public class OperationTest {
Operation.OperationList operationList =
loadJson("operation_list.json", Operation.OperationList.class);
assertThat(operationList.toList()).hasSize(2);
Clock clock = new FakeClock(DateTime.parse("2018-10-29T16:01:04.645299Z"));
((FakeClock) clock).advanceOneMilli();
FakeClock clock = new FakeClock(DateTime.parse("2018-10-29T16:01:04.645299Z"));
clock.advanceOneMilli();
assertThat(operationList.toList().get(0).getRunningTime(clock)).isEqualTo(Duration.millis(1));
assertThat(operationList.toList().get(0).getProgress())
.isEqualTo("Progress: [51797/54513 entities]");

View file

@ -84,9 +84,7 @@ public class SheetSynchronizerTest {
// Explicitly constructs a List<Object> to avoid newArrayList typing to ArrayList<String>
private List<Object> createRow(Object... elements) {
List<Object> row = new ArrayList<>();
row.addAll(Arrays.asList(elements));
return row;
return new ArrayList<>(Arrays.asList(elements));
}
@Test

View file

@ -59,15 +59,15 @@ public class EppConsoleActionTest extends ShardableTestCase {
ArgumentCaptor<TransportCredentials> credentialsCaptor =
ArgumentCaptor.forClass(TransportCredentials.class);
ArgumentCaptor<SessionMetadata> metadataCaptor = ArgumentCaptor.forClass(SessionMetadata.class);
verify(action.eppRequestHandler).executeEpp(
metadataCaptor.capture(),
credentialsCaptor.capture(),
eq(EppRequestSource.CONSOLE),
eq(false),
eq(false),
eq(INPUT_XML_BYTES));
assertThat(((GaeUserCredentials) credentialsCaptor.getValue()).toString())
.contains("user=TestUserId");
verify(action.eppRequestHandler)
.executeEpp(
metadataCaptor.capture(),
credentialsCaptor.capture(),
eq(EppRequestSource.CONSOLE),
eq(false),
eq(false),
eq(INPUT_XML_BYTES));
assertThat(credentialsCaptor.getValue().toString()).contains("user=TestUserId");
assertThat(metadataCaptor.getValue().getClientId()).isEqualTo("ClientIdentifier");
}
}

View file

@ -30,7 +30,6 @@ import static org.joda.time.DateTimeZone.UTC;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Streams;
@ -173,29 +172,6 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
assertThat(ofy().load().type(HistoryEntry.class)).isEmpty();
}
public <T> T getOnlyGlobalResource(Class<T> clazz) {
return Iterables.getOnlyElement(ofy().load().type(clazz));
}
/** Helper to remove the grace period's billing event key to facilitate comparison. */
/** A helper class that sets the billing event parent history entry to facilitate comparison. */
public static class BillingEventParentSetter implements Function<BillingEvent, BillingEvent> {
private HistoryEntry historyEntry;
public static BillingEventParentSetter withParent(HistoryEntry historyEntry) {
BillingEventParentSetter instance = new BillingEventParentSetter();
instance.historyEntry = historyEntry;
return instance;
}
@Override
public BillingEvent apply(BillingEvent billingEvent) {
return billingEvent.asBuilder().setParent(historyEntry).build();
}
private BillingEventParentSetter() {}
}
/**
* Helper to facilitate comparison of maps of GracePeriods to BillingEvents. This takes a map of
* GracePeriods to BillingEvents and returns a map of the same entries that ignores the keys
@ -340,7 +316,7 @@ public abstract class FlowTestCase<F extends Flow> extends ShardableTestCase {
String.format(
"Invalid xml.\nExpected:\n%s\n\nActual:\n%s\n",
xml,
marshal(output, ValidationMode.LENIENT)),
Arrays.toString(marshal(output, ValidationMode.LENIENT))),
e);
}
// Clear the cache so that we don't see stale results in tests.

View file

@ -762,12 +762,8 @@ public class DomainDeleteFlowTest extends ResourceFlowTestCase<DomainDeleteFlow,
.asBuilder()
.setSuperordinateDomain(Key.create(reloadResourceByForeignKey()))
.build());
domain =
persistResource(
domain
.asBuilder()
.addSubordinateHost(subordinateHost.getFullyQualifiedHostName())
.build());
persistResource(
domain.asBuilder().addSubordinateHost(subordinateHost.getFullyQualifiedHostName()).build());
EppException thrown = assertThrows(DomainToDeleteHasHostsException.class, this::runFlow);
assertAboutEppExceptions().that(thrown).marshalsToXml();
}

View file

@ -99,25 +99,24 @@ public class DomainRestoreRequestFlowTest
.setType(HistoryEntry.Type.DOMAIN_DELETE)
.setParent(domain)
.build());
domain =
persistResource(
domain
.asBuilder()
.setRegistrationExpirationTime(clock.nowUtc().plusYears(5).plusDays(45))
.setDeletionTime(clock.nowUtc().plusDays(35))
.addGracePeriod(
GracePeriod.create(
GracePeriodStatus.REDEMPTION, clock.nowUtc().plusDays(1), "foo", null))
.setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE))
.setDeletePollMessage(
Key.create(
persistResource(
new PollMessage.OneTime.Builder()
.setClientId("TheRegistrar")
.setEventTime(clock.nowUtc().plusDays(5))
.setParent(historyEntry)
.build())))
.build());
persistResource(
domain
.asBuilder()
.setRegistrationExpirationTime(clock.nowUtc().plusYears(5).plusDays(45))
.setDeletionTime(clock.nowUtc().plusDays(35))
.addGracePeriod(
GracePeriod.create(
GracePeriodStatus.REDEMPTION, clock.nowUtc().plusDays(1), "foo", null))
.setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE))
.setDeletePollMessage(
Key.create(
persistResource(
new PollMessage.OneTime.Builder()
.setClientId("TheRegistrar")
.setEventTime(clock.nowUtc().plusDays(5))
.setParent(historyEntry)
.build())))
.build());
clock.advanceOneMilli();
}

View file

@ -325,27 +325,27 @@ public class DomainUpdateFlowTest extends ResourceFlowTestCase<DomainUpdateFlow,
setEppInput("domain_update_subordinate_hosts.xml");
persistReferencedEntities();
DomainBase domain = persistDomain();
HostResource existingHost = persistActiveSubordinateHost("ns1.example.tld", domain);
persistActiveSubordinateHost("ns1.example.tld", domain);
HostResource addedHost = persistActiveSubordinateHost("ns2.example.tld", domain);
domain =
persistResource(
domain
.asBuilder()
.addSubordinateHost("ns1.example.tld")
.addSubordinateHost("ns2.example.tld")
.setNameservers(
ImmutableSet.of(
Key.create(
loadByForeignKey(HostResource.class, "ns1.example.tld", clock.nowUtc())
.get())))
.build());
persistResource(
domain
.asBuilder()
.addSubordinateHost("ns1.example.tld")
.addSubordinateHost("ns2.example.tld")
.setNameservers(
ImmutableSet.of(
Key.create(
loadByForeignKey(HostResource.class, "ns1.example.tld", clock.nowUtc())
.get())))
.build());
clock.advanceOneMilli();
assertTransactionalFlow(true);
runFlowAssertResponse(loadFile("generic_success_response.xml"));
domain = reloadResourceByForeignKey();
assertThat(domain.getNameservers()).containsExactly(Key.create(addedHost));
assertThat(domain.getSubordinateHosts()).containsExactly("ns1.example.tld", "ns2.example.tld");
existingHost = loadByForeignKey(HostResource.class, "ns1.example.tld", clock.nowUtc()).get();
HostResource existingHost =
loadByForeignKey(HostResource.class, "ns1.example.tld", clock.nowUtc()).get();
addedHost = loadByForeignKey(HostResource.class, "ns2.example.tld", clock.nowUtc()).get();
assertThat(existingHost.getSuperordinateDomain()).isEqualTo(Key.create(domain));
assertThat(addedHost.getSuperordinateDomain()).isEqualTo(Key.create(domain));

View file

@ -30,6 +30,7 @@ import static google.registry.testing.DatastoreHelper.persistReservedList;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.math.BigDecimal.ROUND_UNNECESSARY;
import static org.joda.money.CurrencyUnit.EUR;
import static org.joda.money.CurrencyUnit.USD;
@ -497,7 +498,7 @@ public class RegistryTest extends EntityTestCase {
@Test
public void testEapFee_undefined() {
assertThat(Registry.get("tld").getEapFeeFor(clock.nowUtc()).getCost())
.isEqualTo(BigDecimal.ZERO.setScale(2));
.isEqualTo(BigDecimal.ZERO.setScale(2, ROUND_UNNECESSARY));
}
@Test
@ -514,7 +515,7 @@ public class RegistryTest extends EntityTestCase {
assertThat(registry.getEapFeeFor(clock.nowUtc()).getCost())
.isEqualTo(new BigDecimal("100.00"));
assertThat(registry.getEapFeeFor(clock.nowUtc().minusDays(2)).getCost())
.isEqualTo(BigDecimal.ZERO.setScale(2));
.isEqualTo(BigDecimal.ZERO.setScale(2, ROUND_UNNECESSARY));
assertThat(registry.getEapFeeFor(clock.nowUtc().plusDays(2)).getCost())
.isEqualTo(new BigDecimal("50.00"));
}

View file

@ -88,7 +88,8 @@ public class FrontendMetricsTest {
.and()
.hasNoOtherValues();
ChannelFuture unusedFuture = channel1.close();
@SuppressWarnings("unused")
ChannelFuture unusedFuture1 = channel1.close();
assertThat(channel1.isActive()).isFalse();
assertThat(FrontendMetrics.activeConnectionsGauge)
.hasValueForLabels(1, PROTOCOL, CERT_HASH)
@ -99,7 +100,8 @@ public class FrontendMetricsTest {
.and()
.hasNoOtherValues();
unusedFuture = channel2.close();
@SuppressWarnings("unused")
ChannelFuture unusedFuture2 = channel2.close();
assertThat(channel2.isActive()).isFalse();
assertThat(FrontendMetrics.activeConnectionsGauge).hasNoOtherValues();
assertThat(FrontendMetrics.totalConnectionsCounter)

View file

@ -46,6 +46,7 @@ import google.registry.model.domain.secdns.DelegationSignerData;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.host.HostResource;
import google.registry.model.poll.PollMessage;
import google.registry.model.poll.PollMessage.Autorenew;
import google.registry.model.reporting.HistoryEntry;
import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferStatus;
@ -377,9 +378,9 @@ public class XjcToDomainBaseConverterTest {
// First import in a transaction, then verify in another transaction.
// Ancestor queries don't work within the same transaction.
DomainBase domain = persistResource(convertDomainInTransaction(xjcDomain));
PollMessage pollMessage = ofy().load().key(domain.getAutorenewPollMessage()).now();
Autorenew pollMessage = ofy().load().key(domain.getAutorenewPollMessage()).now();
assertThat(pollMessage).isInstanceOf(PollMessage.Autorenew.class);
assertThat(((PollMessage.Autorenew) pollMessage).getTargetId()).isEqualTo(xjcDomain.getRoid());
assertThat(pollMessage.getTargetId()).isEqualTo(xjcDomain.getRoid());
assertThat(pollMessage.getClientId()).isEqualTo("RegistrarX");
assertThat(pollMessage.getEventTime()).isEqualTo(xjcDomain.getExDate());
assertThat(pollMessage.getMsg()).isEqualTo("Domain was auto-renewed.");

View file

@ -290,11 +290,13 @@ public final class AppEngineRule extends ExternalResource {
if (withUserService) {
// Set top-level properties on LocalServiceTestConfig for user login.
helper.setEnvIsLoggedIn(userInfo.isLoggedIn())
helper
.setEnvIsLoggedIn(userInfo.isLoggedIn())
// This envAttributes thing is the only way to set userId.
// see https://code.google.com/p/googleappengine/issues/detail?id=3579
.setEnvAttributes(ImmutableMap.<String, Object>of(
"com.google.appengine.api.users.UserService.user_id_key", userInfo.gaeUserId()))
.setEnvAttributes(
ImmutableMap.of(
"com.google.appengine.api.users.UserService.user_id_key", userInfo.gaeUserId()))
.setEnvAuthDomain(userInfo.authDomain())
.setEnvEmail(userInfo.email())
.setEnvIsAdmin(userInfo.isAdmin());

View file

@ -26,7 +26,7 @@ public class FakeLockHandler implements LockHandler {
private static final long serialVersionUID = 6437880915118738492L;
boolean lockSucceeds = true;
boolean lockSucceeds;
/**
* @param lockSucceeds if true - the lock acquisition will succeed and the callable will be

View file

@ -23,6 +23,7 @@ import static google.registry.testing.DatastoreHelper.persistPremiumList;
import static google.registry.testing.DatastoreHelper.persistReservedList;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.math.BigDecimal.ROUND_UNNECESSARY;
import static org.joda.money.CurrencyUnit.JPY;
import static org.joda.money.CurrencyUnit.USD;
import static org.joda.time.DateTimeZone.UTC;
@ -135,7 +136,7 @@ public class CreateTldCommandTest extends CommandTestCase<CreateTldCommand> {
Registry registry = Registry.get("xn--q9jyb4c");
assertThat(registry.getEapFeeFor(now.minusHours(1)).getCost())
.isEqualTo(BigDecimal.ZERO.setScale(2));
.isEqualTo(BigDecimal.ZERO.setScale(2, ROUND_UNNECESSARY));
assertThat(registry.getEapFeeFor(now.plusHours(1)).getCost())
.isEqualTo(new BigDecimal("50.00"));
assertThat(registry.getEapFeeFor(now.plusDays(1).plusHours(1)).getCost())

View file

@ -36,10 +36,11 @@ import org.mockito.ArgumentCaptor;
/**
* Class for verifying EPP commands sent to the server via the tool endpoint.
*
* <p>Provides its own (mock) {@link Connection} that will be monitored for EPP transmission. This
* Connection needs to be registered with the tool endpoint - something like this:
* <p>Provides its own (mock) {@link AppEngineConnection} that will be monitored for EPP
* transmission. This Connection needs to be registered with the tool endpoint - something like
* this:
*
* <pre> {@code
* <pre>{@code
* SomeToolCommand command = ...;
* EppToolVerifier eppToolVerifier = EppToolVerifier.create(command);
* // run command...

View file

@ -20,7 +20,6 @@ import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static google.registry.testing.TestDataHelper.loadFile;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@ -108,7 +107,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
.containsExactly(
"status", "SUCCESS",
"message", "Success",
"results", asList(loadRegistrar(CLIENT_ID).toJsonMap()));
"results", ImmutableList.of(loadRegistrar(CLIENT_ID).toJsonMap()));
assertMetric(CLIENT_ID, "read", "[OWNER]", "SUCCESS");
}
@ -164,7 +163,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
assertThat(response).containsExactly(
"status", "SUCCESS",
"message", "Saved TheRegistrar",
"results", asList(loadRegistrar(CLIENT_ID).toJsonMap()));
"results", ImmutableList.of(loadRegistrar(CLIENT_ID).toJsonMap()));
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
}
@ -285,7 +284,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
// This role is authorized to perform this change, make sure the change succeeded
// We got a success result:
assertThat(response).containsEntry("status", "SUCCESS");
assertThat(response).containsEntry("results", asList(updatedRegistrar.toJsonMap()));
assertThat(response).containsEntry("results", ImmutableList.of(updatedRegistrar.toJsonMap()));
// The updatedRegistrar had its value changed:
// (We check it separately from the next assert to get better error message on failure)
assertThat(getter.apply(updatedRegistrar)).isEqualTo(newValue);
@ -467,7 +466,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
.containsExactly(
"status", "SUCCESS",
"message", "Saved TheRegistrar",
"results", asList(loadRegistrar(CLIENT_ID).toJsonMap()));
"results", ImmutableList.of(loadRegistrar(CLIENT_ID).toJsonMap()));
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
}

View file

@ -22,8 +22,8 @@ import static google.registry.testing.CertificateSamples.SAMPLE_CERT_HASH;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static java.util.Arrays.asList;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import google.registry.model.registrar.Registrar;
import java.util.Map;
@ -52,7 +52,7 @@ public class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
"id", CLIENT_ID,
"args", modified.toJsonMap()));
assertThat(response).containsEntry("status", "SUCCESS");
assertThat(response).containsEntry("results", asList(modified.toJsonMap()));
assertThat(response).containsEntry("results", ImmutableList.of(modified.toJsonMap()));
assertThat(loadRegistrar(CLIENT_ID)).isEqualTo(modified);
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
}

View file

@ -17,7 +17,6 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Strings.repeat;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static java.util.Arrays.asList;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@ -59,7 +58,7 @@ public class WhoisSettingsTest extends RegistrarSettingsActionTestCase {
action.handleJsonRequest(
ImmutableMap.of("op", "update", "id", CLIENT_ID, "args", modified.toJsonMap()));
assertThat(response.get("status")).isEqualTo("SUCCESS");
assertThat(response.get("results")).isEqualTo(asList(modified.toJsonMap()));
assertThat(response.get("results")).isEqualTo(ImmutableList.of(modified.toJsonMap()));
assertThat(loadRegistrar(CLIENT_ID)).isEqualTo(modified);
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
}

View file

@ -67,8 +67,6 @@ public class CidrAddressBlockTest extends TestCase {
assertEquals(32, b1.getNetmask());
b1 = new CidrAddressBlock("2001:db8::1");
assertEquals(128, b1.getNetmask());
b1 = new CidrAddressBlock("3ffe::/16");
b1 = new CidrAddressBlock(InetAddresses.forString("5ffe::1"));
assertEquals(128, b1.getNetmask());
assertEquals("5ffe:0:0:0:0:0:0:1", b1.getIp());

View file

@ -19,6 +19,7 @@ import static google.registry.testing.JUnitBackports.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
@ -60,7 +61,7 @@ public class TeeOutputStreamTest {
@Test
public void testWriteInteger_failsAfterClose() throws Exception {
OutputStream tee = new TeeOutputStream(asList(outputA));
OutputStream tee = new TeeOutputStream(ImmutableList.of(outputA));
tee.close();
IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> tee.write(1));
assertThat(thrown).hasMessageThat().contains("outputstream closed");
@ -68,7 +69,7 @@ public class TeeOutputStreamTest {
@Test
public void testWriteByteArray_failsAfterClose() throws Exception {
OutputStream tee = new TeeOutputStream(asList(outputA));
OutputStream tee = new TeeOutputStream(ImmutableList.of(outputA));
tee.close();
IllegalStateException thrown =
assertThrows(IllegalStateException.class, () -> tee.write("hello".getBytes(UTF_8)));
@ -77,7 +78,7 @@ public class TeeOutputStreamTest {
@Test
public void testWriteByteSubarray_failsAfterClose() throws Exception {
OutputStream tee = new TeeOutputStream(asList(outputA));
OutputStream tee = new TeeOutputStream(ImmutableList.of(outputA));
tee.close();
IllegalStateException thrown =
assertThrows(IllegalStateException.class, () -> tee.write("hello".getBytes(UTF_8), 1, 3));

View file

@ -139,8 +139,7 @@ public class XmlTestUtils {
}
// First, handle all namespace specifications, updating our ns-to-URI map. Use a HashMap
// rather than an ImmutableMap.Builder so that we can override existing map entries.
HashMap<String, String> newNsMap = new HashMap<>();
newNsMap.putAll(nsMap);
HashMap<String, String> newNsMap = new HashMap<>(nsMap);
for (String key : namespacesBuilder.build()) {
// Parse the attribute name, of the form xmlns:nsid, and extract the namespace identifier.
// If there's no colon, we are setting the default namespace.