Fix some low-hanging code quality issue fruits (#1047)

* Fix some low-hanging code quality issue fruits

These include problems such as: use of raw types, unnecessary throw clauses,
unused variables, and more.
This commit is contained in:
Ben McIlwain 2021-04-01 18:04:21 -04:00 committed by GitHub
parent 891745391f
commit 55ef3279e6
79 changed files with 163 additions and 196 deletions

View file

@ -91,7 +91,7 @@ abstract class ProjectData {
/** The task was actually run and has finished successfully. */ /** The task was actually run and has finished successfully. */
SUCCESS, SUCCESS,
/** The task was up-to-date and successful, and hence didn't need to run again. */ /** The task was up-to-date and successful, and hence didn't need to run again. */
UP_TO_DATE; UP_TO_DATE
} }
abstract String uniqueName(); abstract String uniqueName();

View file

@ -505,7 +505,7 @@ public class DatastoreV1 {
} }
@StartBundle @StartBundle
public void startBundle(StartBundleContext c) throws Exception { public void startBundle(StartBundleContext c) {
datastore = datastore =
datastoreFactory.getDatastore( datastoreFactory.getDatastore(
c.getPipelineOptions(), v1Options.getProjectId(), v1Options.getLocalhost()); c.getPipelineOptions(), v1Options.getProjectId(), v1Options.getLocalhost());
@ -548,7 +548,7 @@ public class DatastoreV1 {
} }
@StartBundle @StartBundle
public void startBundle(StartBundleContext c) throws Exception { public void startBundle(StartBundleContext c) {
datastore = datastore =
datastoreFactory.getDatastore( datastoreFactory.getDatastore(
c.getPipelineOptions(), options.getProjectId(), options.getLocalhost()); c.getPipelineOptions(), options.getProjectId(), options.getLocalhost());
@ -556,7 +556,7 @@ public class DatastoreV1 {
} }
@ProcessElement @ProcessElement
public void processElement(ProcessContext c) throws Exception { public void processElement(ProcessContext c) {
Query query = c.element(); Query query = c.element();
// If query has a user set limit, then do not split. // If query has a user set limit, then do not split.
@ -626,7 +626,7 @@ public class DatastoreV1 {
} }
@StartBundle @StartBundle
public void startBundle(StartBundleContext c) throws Exception { public void startBundle(StartBundleContext c) {
datastore = datastore =
datastoreFactory.getDatastore( datastoreFactory.getDatastore(
c.getPipelineOptions(), options.getProjectId(), options.getLocalhost()); c.getPipelineOptions(), options.getProjectId(), options.getLocalhost());

View file

@ -93,7 +93,7 @@ public final class BackupPaths {
checkArgument(!isNullOrEmpty(exportDir), "Null or empty exportDir."); checkArgument(!isNullOrEmpty(exportDir), "Null or empty exportDir.");
checkArgument(!isNullOrEmpty(kind), "Null or empty kind."); checkArgument(!isNullOrEmpty(kind), "Null or empty kind.");
checkArgument(shard >= 0, "Negative shard %s not allowed.", shard); checkArgument(shard >= 0, "Negative shard %s not allowed.", shard);
return String.format(EXPORT_PATTERN_TEMPLATE, exportDir, kind, Integer.toString(shard)); return String.format(EXPORT_PATTERN_TEMPLATE, exportDir, kind, shard);
} }
/** Returns an {@link ImmutableList} of regex patterns that match all CommitLog files. */ /** Returns an {@link ImmutableList} of regex patterns that match all CommitLog files. */

View file

@ -337,7 +337,7 @@ public class DomainContent extends EppResource
@PostLoad @PostLoad
@SuppressWarnings("UnusedMethod") @SuppressWarnings("UnusedMethod")
private final void postLoad() { private void postLoad() {
// Reconstitute the contact list. // Reconstitute the contact list.
ImmutableSet.Builder<DesignatedContact> contactsBuilder = new ImmutableSet.Builder<>(); ImmutableSet.Builder<DesignatedContact> contactsBuilder = new ImmutableSet.Builder<>();

View file

@ -51,7 +51,7 @@ public class HibernateSchemaExporter {
} }
/** Exports DDL script to the {@code outputFile} for the given {@code entityClasses}. */ /** Exports DDL script to the {@code outputFile} for the given {@code entityClasses}. */
public void export(ImmutableList<Class> entityClasses, File outputFile) { public void export(ImmutableList<Class<?>> entityClasses, File outputFile) {
// Configure Hibernate settings. // Configure Hibernate settings.
Map<String, String> settings = Maps.newHashMap(); Map<String, String> settings = Maps.newHashMap();
settings.put(Environment.DIALECT, NomulusPostgreSQLDialect.class.getName()); settings.put(Environment.DIALECT, NomulusPostgreSQLDialect.class.getName());
@ -85,7 +85,7 @@ public class HibernateSchemaExporter {
} }
} }
private ImmutableList<Class> findAllConverters() { private ImmutableList<Class<?>> findAllConverters() {
return PersistenceXmlUtility.getManagedClasses().stream() return PersistenceXmlUtility.getManagedClasses().stream()
.filter(AttributeConverter.class::isAssignableFrom) .filter(AttributeConverter.class::isAssignableFrom)
.collect(toImmutableList()); .collect(toImmutableList());

View file

@ -41,7 +41,7 @@ public class PersistenceXmlUtility {
} }
/** Returns all managed classes defined in persistence.xml. */ /** Returns all managed classes defined in persistence.xml. */
public static ImmutableList<Class> getManagedClasses() { public static ImmutableList<Class<?>> getManagedClasses() {
return getParsedPersistenceXmlDescriptor().getManagedClassNames().stream() return getParsedPersistenceXmlDescriptor().getManagedClassNames().stream()
.map( .map(
className -> { className -> {

View file

@ -35,7 +35,6 @@ public class DateTimeConverter implements AttributeConverter<DateTime, Timestamp
@Override @Override
@Nullable @Nullable
public DateTime convertToEntityAttribute(@Nullable Timestamp dbData) { public DateTime convertToEntityAttribute(@Nullable Timestamp dbData) {
DateTime result = dbData == null ? null : new DateTime(dbData.getTime(), UTC); return (dbData == null) ? null : new DateTime(dbData.getTime(), UTC);
return result;
} }
} }

View file

@ -49,7 +49,7 @@ public interface JpaTransactionManager extends TransactionManager {
void transactNoRetry(Runnable work); void transactNoRetry(Runnable work);
/** Deletes the entity by its id, throws exception if the entity is not deleted. */ /** Deletes the entity by its id, throws exception if the entity is not deleted. */
public abstract <T> void assertDelete(VKey<T> key); <T> void assertDelete(VKey<T> key);
/** /**
* Releases all resources and shuts down. * Releases all resources and shuts down.

View file

@ -165,7 +165,7 @@ public class Transaction extends ImmutableObject implements Buildable {
enum Type { enum Type {
UPDATE, UPDATE,
DELETE DELETE
}; }
/** Write the changes in the mutation to the datastore. */ /** Write the changes in the mutation to the datastore. */
public abstract void writeToDatastore(); public abstract void writeToDatastore();

View file

@ -54,7 +54,7 @@ public abstract class SqlUser {
* Credential for RegistryTool. This is temporary, and will be removed when tool users are * Credential for RegistryTool. This is temporary, and will be removed when tool users are
* assigned their personal credentials. * assigned their personal credentials.
*/ */
TOOL; TOOL
} }
/** Information of a RobotUser for privilege management purposes. */ /** Information of a RobotUser for privilege management purposes. */

View file

@ -32,7 +32,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import javax.inject.Inject; import javax.inject.Inject;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
@ -79,12 +78,12 @@ public final class BrdaCopyAction implements Runnable {
public void run() { public void run() {
try { try {
copyAsRyde(); copyAsRyde();
} catch (IOException | PGPException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private void copyAsRyde() throws IOException, PGPException { private void copyAsRyde() throws IOException {
String prefix = RdeNamingUtils.makeRydeFilename(tld, watermark, THIN, 1, 0); String prefix = RdeNamingUtils.makeRydeFilename(tld, watermark, THIN, 1, 0);
GcsFilename xmlFilename = new GcsFilename(stagingBucket, prefix + ".xml.ghostryde"); GcsFilename xmlFilename = new GcsFilename(stagingBucket, prefix + ".xml.ghostryde");
GcsFilename xmlLengthFilename = new GcsFilename(stagingBucket, prefix + ".xml.length"); GcsFilename xmlLengthFilename = new GcsFilename(stagingBucket, prefix + ".xml.length");

View file

@ -37,7 +37,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -118,11 +117,8 @@ public final class Ghostryde {
static final String INNER_FILENAME = "file.xml"; static final String INNER_FILENAME = "file.xml";
static final DateTime INNER_MODIFICATION_TIME = DateTime.parse("2000-01-01TZ"); static final DateTime INNER_MODIFICATION_TIME = DateTime.parse("2000-01-01TZ");
/** /** Creates a ghostryde file from an in-memory byte array. */
* Creates a ghostryde file from an in-memory byte array. public static byte[] encode(byte[] data, PGPPublicKey key) throws IOException {
*/
public static byte[] encode(byte[] data, PGPPublicKey key)
throws IOException, PGPException {
checkNotNull(data, "data"); checkNotNull(data, "data");
checkArgument(key.isEncryptionKey(), "not an encryption key"); checkArgument(key.isEncryptionKey(), "not an encryption key");
ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream();
@ -132,11 +128,8 @@ public final class Ghostryde {
return output.toByteArray(); return output.toByteArray();
} }
/** /** Deciphers a ghostryde file from an in-memory byte array. */
* Deciphers a ghostryde file from an in-memory byte array. public static byte[] decode(byte[] data, PGPPrivateKey key) throws IOException {
*/
public static byte[] decode(byte[] data, PGPPrivateKey key)
throws IOException, PGPException {
checkNotNull(data, "data"); checkNotNull(data, "data");
ByteArrayInputStream dataStream = new ByteArrayInputStream(data); ByteArrayInputStream dataStream = new ByteArrayInputStream(data);
ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream();

View file

@ -42,7 +42,6 @@ import google.registry.request.auth.Auth;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import javax.inject.Inject; import javax.inject.Inject;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPrivateKey;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Duration; import org.joda.time.Duration;
@ -96,7 +95,7 @@ public final class RdeReportAction implements Runnable, EscrowTask {
} }
/** Reads and decrypts the XML file from cloud storage. */ /** Reads and decrypts the XML file from cloud storage. */
private byte[] readReportFromGcs(GcsFilename reportFilename) throws IOException, PGPException { private byte[] readReportFromGcs(GcsFilename reportFilename) throws IOException {
try (InputStream gcsInput = gcsUtils.openInputStream(reportFilename); try (InputStream gcsInput = gcsUtils.openInputStream(reportFilename);
InputStream ghostrydeDecoder = Ghostryde.decoder(gcsInput, stagingDecryptionKey)) { InputStream ghostrydeDecoder = Ghostryde.decoder(gcsInput, stagingDecryptionKey)) {
return ByteStreams.toByteArray(ghostrydeDecoder); return ByteStreams.toByteArray(ghostrydeDecoder);

View file

@ -74,9 +74,8 @@ public final class RydeEncoder extends FilterOutputStream {
OutputStream kompressor = closer.register(openCompressor(encryptLayer)); OutputStream kompressor = closer.register(openCompressor(encryptLayer));
OutputStream fileLayer = OutputStream fileLayer =
closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified)); closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified));
OutputStream tarLayer = this.out =
closer.register(openTarWriter(fileLayer, dataLength, filenamePrefix + ".xml", modified)); closer.register(openTarWriter(fileLayer, dataLength, filenamePrefix + ".xml", modified));
this.out = tarLayer;
} }
/** /**

View file

@ -128,7 +128,7 @@ public final class ActivityReportingQueryBuilder implements QueryBuilder {
return queriesBuilder.build(); return queriesBuilder.build();
} }
public void prepareForQuery(YearMonth yearMonth) throws Exception { public void prepareForQuery(YearMonth yearMonth) throws InterruptedException {
dnsCountQueryCoordinator.prepareForQuery(yearMonth); dnsCountQueryCoordinator.prepareForQuery(yearMonth);
} }
} }

View file

@ -35,5 +35,5 @@ public class BasicDnsCountQueryCoordinator implements DnsCountQueryCoordinator {
} }
@Override @Override
public void prepareForQuery(YearMonth yearMonth) throws Exception {} public void prepareForQuery(YearMonth yearMonth) {}
} }

View file

@ -32,7 +32,7 @@ public interface DnsCountQueryCoordinator {
/** /**
* Class to carry parameters for a new coordinator. * Class to carry parameters for a new coordinator.
* *
* If your report query requires any additional parameters, add them here. * <p>If your report query requires any additional parameters, add them here.
*/ */
class Params { class Params {
public BigqueryConnection bigquery; public BigqueryConnection bigquery;
@ -49,6 +49,12 @@ public interface DnsCountQueryCoordinator {
/** Creates the string used to query bigtable for DNS count information. */ /** Creates the string used to query bigtable for DNS count information. */
String createQuery(YearMonth yearMonth); String createQuery(YearMonth yearMonth);
/** Do any necessry preparation for the DNS query. */ /**
void prepareForQuery(YearMonth yearMonth) throws Exception; * Do any necessary preparation for the DNS query.
*
* <p>This potentially throws {@link InterruptedException} because some implementations use
* interruptible futures to prepare the query (and the correct thing to do with such exceptions is
* to handle them correctly or propagate them as-is, no {@link RuntimeException} wrapping).
*/
void prepareForQuery(YearMonth yearMonth) throws InterruptedException;
} }

View file

@ -46,7 +46,7 @@ public class ClaimsListParser {
checkArgument(firstLine.size() == 2, String.format( checkArgument(firstLine.size() == 2, String.format(
"Line 1: Expected 2 elements, found %d", firstLine.size())); "Line 1: Expected 2 elements, found %d", firstLine.size()));
Integer version = Integer.valueOf(firstLine.get(0)); int version = Integer.parseInt(firstLine.get(0));
DateTime creationTime = DateTime.parse(firstLine.get(1)); DateTime creationTime = DateTime.parse(firstLine.get(1));
checkArgument(version == 1, String.format( checkArgument(version == 1, String.format(
"Line 1: Expected version 1, found %d", version)); "Line 1: Expected version 1, found %d", version));

View file

@ -151,7 +151,7 @@ public final class Marksdb {
* *
* <p>Note that the DNL is long, hence truncating it instead of logging the whole thing. * <p>Note that the DNL is long, hence truncating it instead of logging the whole thing.
*/ */
private static void logFetchedBytes(String sourceUrl, byte[] bytes) throws IOException { private static void logFetchedBytes(String sourceUrl, byte[] bytes) {
logger.atInfo().log( logger.atInfo().log(
"Fetched contents of %s -- Size: %d bytes; first %d chars:\n\n%s%s", "Fetched contents of %s -- Size: %d bytes; first %d chars:\n\n%s%s",
sourceUrl, sourceUrl,

View file

@ -42,7 +42,7 @@ public final class SmdrlCsvParser {
List<String> firstLine = Splitter.on(',').splitToList(lines.get(0)); List<String> firstLine = Splitter.on(',').splitToList(lines.get(0));
checkArgument(firstLine.size() == 2, String.format( checkArgument(firstLine.size() == 2, String.format(
"Line 1: Expected 2 elements, found %d", firstLine.size())); "Line 1: Expected 2 elements, found %d", firstLine.size()));
Integer version = Integer.valueOf(firstLine.get(0)); int version = Integer.parseInt(firstLine.get(0));
checkArgument(version == 1, String.format( checkArgument(version == 1, String.format(
"Line 1: Expected version 1, found %d", version)); "Line 1: Expected version 1, found %d", version));
DateTime creationTime = DateTime.parse(firstLine.get(1)).withZone(UTC); DateTime creationTime = DateTime.parse(firstLine.get(1)).withZone(UTC);

View file

@ -52,7 +52,7 @@ final class BigqueryParameters {
private int bigqueryNumThreads = DEFAULT_NUM_THREADS; private int bigqueryNumThreads = DEFAULT_NUM_THREADS;
/** 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) {
return connectionBuilder return connectionBuilder
.setExecutorService(Executors.newFixedThreadPool(bigqueryNumThreads)) .setExecutorService(Executors.newFixedThreadPool(bigqueryNumThreads))
.setDatasetId(bigqueryDataset) .setDatasetId(bigqueryDataset)

View file

@ -47,7 +47,7 @@ public abstract class ConfirmingCommand implements Command {
} }
/** Run any pre-execute command checks and return true if they all pass. */ /** Run any pre-execute command checks and return true if they all pass. */
protected boolean checkExecutionState() throws Exception { protected boolean checkExecutionState() {
return true; return true;
} }

View file

@ -31,7 +31,7 @@ public class GetPremiumListCommand implements CommandWithRemoteApi {
private List<String> mainParameters; private List<String> mainParameters;
@Override @Override
public void run() throws Exception { public void run() {
for (String premiumListName : mainParameters) { for (String premiumListName : mainParameters) {
if (PremiumListDualDao.exists(premiumListName)) { if (PremiumListDualDao.exists(premiumListName)) {
System.out.printf( System.out.printf(
@ -42,7 +42,7 @@ public class GetPremiumListCommand implements CommandWithRemoteApi {
.map(PremiumListEntry::toString) .map(PremiumListEntry::toString)
.collect(Collectors.joining("\n"))); .collect(Collectors.joining("\n")));
} else { } else {
System.out.println(String.format("No list found with name %s.", premiumListName)); System.out.printf("No list found with name %s.%n", premiumListName);
} }
} }
} }

View file

@ -66,11 +66,9 @@ abstract class ReadEntityFromKeyPathCommand<T> extends MutatingCommand {
Key<?> untypedKey = parseKeyPath(keyPath); Key<?> untypedKey = parseKeyPath(keyPath);
Object entity = ofy().load().key(untypedKey).now(); Object entity = ofy().load().key(untypedKey).now();
if (entity == null) { if (entity == null) {
System.err.println( System.err.printf(
String.format( "Entity %s read from %s doesn't exist in Datastore! Skipping.%n",
"Entity %s read from %s doesn't exist in Datastore! Skipping.", untypedKey, keyPathsFile == null ? "STDIN" : "File " + keyPathsFile.getAbsolutePath());
untypedKey,
keyPathsFile == null ? "STDIN" : "File " + keyPathsFile.getAbsolutePath()));
continue; continue;
} }
Class<T> clazz = new TypeInstantiator<T>(getClass()) {}.getExactType(); Class<T> clazz = new TypeInstantiator<T>(getClass()) {}.getExactType();

View file

@ -123,7 +123,7 @@ final class SetupOteCommand extends ConfirmingCommand implements CommandWithRemo
} }
@Override @Override
public String execute() throws Exception { public String execute() {
ImmutableMap<String, String> clientIdToTld = oteAccountBuilder.buildAndPersist(); ImmutableMap<String, String> clientIdToTld = oteAccountBuilder.buildAndPersist();
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();

View file

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

View file

@ -130,15 +130,14 @@ public class GenerateSqlErDiagramCommand implements Command {
doc.select("body > table > tbody") doc.select("body > table > tbody")
.first() .first()
.append( .append(
String.format( "<tr>"
"<tr>" + "<td class=\"property_name\">last flyway file</td>"
+ "<td class=\"property_name\">last flyway file</td>" + "<td id=\""
+ "<td id=\"" + FLYWAY_FILE_ELEMENT_ID
+ FLYWAY_FILE_ELEMENT_ID + "\" class=\"property_value\">"
+ "\" class=\"property_value\">" + getLastFlywayFileName()
+ getLastFlywayFileName() + "</td>"
+ "</td>" + "</tr>");
+ "</tr>"));
// Add pan and zoom support for the embedded SVG in the HTML. // Add pan and zoom support for the embedded SVG in the HTML.
StringBuilder svgPanZoomLib = StringBuilder svgPanZoomLib =

View file

@ -135,7 +135,7 @@ public class AsyncTaskEnqueuerTest {
@MockitoSettings(strictness = Strictness.LENIENT) @MockitoSettings(strictness = Strictness.LENIENT)
@Test @Test
void test_enqueueAsyncResave_ignoresTasksTooFarIntoFuture() throws Exception { void test_enqueueAsyncResave_ignoresTasksTooFarIntoFuture() {
ContactResource contact = persistActiveContact("jd23456"); ContactResource contact = persistActiveContact("jd23456");
asyncTaskEnqueuer.enqueueAsyncResave(contact, clock.nowUtc(), clock.nowUtc().plusDays(31)); asyncTaskEnqueuer.enqueueAsyncResave(contact, clock.nowUtc(), clock.nowUtc().plusDays(31));
assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS); assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS);

View file

@ -476,7 +476,7 @@ public class DeleteContactsAndHostsActionTest
} }
@Test @Test
void testSuccess_targetResourcesDontExist_areDelayedForADay() throws Exception { void testSuccess_targetResourcesDontExist_areDelayedForADay() {
ContactResource contactNotSaved = newContactResource("somecontact"); ContactResource contactNotSaved = newContactResource("somecontact");
HostResource hostNotSaved = newHostResource("a11.blah.foo"); HostResource hostNotSaved = newHostResource("a11.blah.foo");
DateTime timeBeforeRun = clock.nowUtc(); DateTime timeBeforeRun = clock.nowUtc();
@ -515,7 +515,7 @@ public class DeleteContactsAndHostsActionTest
} }
@Test @Test
void testSuccess_unparseableTasks_areDelayedForADay() throws Exception { void testSuccess_unparseableTasks_areDelayedForADay() {
TaskOptions task = TaskOptions task =
TaskOptions.Builder.withMethod(Method.PULL).param("gobbledygook", "kljhadfgsd9f7gsdfh"); TaskOptions.Builder.withMethod(Method.PULL).param("gobbledygook", "kljhadfgsd9f7gsdfh");
getQueue(QUEUE_ASYNC_DELETE).add(task); getQueue(QUEUE_ASYNC_DELETE).add(task);
@ -531,7 +531,7 @@ public class DeleteContactsAndHostsActionTest
} }
@Test @Test
void testSuccess_resourcesNotInPendingDelete_areSkipped() throws Exception { void testSuccess_resourcesNotInPendingDelete_areSkipped() {
ContactResource contact = persistActiveContact("blah2222"); ContactResource contact = persistActiveContact("blah2222");
HostResource host = persistActiveHost("rustles.your.jimmies"); HostResource host = persistActiveHost("rustles.your.jimmies");
DateTime timeEnqueued = clock.nowUtc(); DateTime timeEnqueued = clock.nowUtc();
@ -563,7 +563,7 @@ public class DeleteContactsAndHostsActionTest
} }
@Test @Test
void testSuccess_alreadyDeletedResources_areSkipped() throws Exception { void testSuccess_alreadyDeletedResources_areSkipped() {
ContactResource contactDeleted = persistDeletedContact("blah1236", clock.nowUtc().minusDays(2)); ContactResource contactDeleted = persistDeletedContact("blah1236", clock.nowUtc().minusDays(2));
HostResource hostDeleted = persistDeletedHost("a.lim.lop", clock.nowUtc().minusDays(3)); HostResource hostDeleted = persistDeletedHost("a.lim.lop", clock.nowUtc().minusDays(3));
enqueuer.enqueueAsyncDelete( enqueuer.enqueueAsyncDelete(

View file

@ -191,7 +191,7 @@ public class RefreshDnsOnHostRenameActionTest
} }
@Test @Test
void testRun_hostDoesntExist_delaysTask() throws Exception { void testRun_hostDoesntExist_delaysTask() {
HostResource host = newHostResource("ns1.example.tld"); HostResource host = newHostResource("ns1.example.tld");
enqueuer.enqueueAsyncDnsRefresh(host, clock.nowUtc()); enqueuer.enqueueAsyncDnsRefresh(host, clock.nowUtc());
enqueueMapreduceOnly(); enqueueMapreduceOnly();
@ -222,7 +222,7 @@ public class RefreshDnsOnHostRenameActionTest
} }
@Test @Test
void test_noTasksToLease_releasesLockImmediately() throws Exception { void test_noTasksToLease_releasesLockImmediately() {
enqueueMapreduceOnly(); enqueueMapreduceOnly();
assertNoDnsTasksEnqueued(); assertNoDnsTasksEnqueued();
assertNoTasksEnqueued(QUEUE_ASYNC_HOST_RENAME); assertNoTasksEnqueued(QUEUE_ASYNC_HOST_RENAME);

View file

@ -141,8 +141,7 @@ public final class BackupTestStore implements AutoCloseable {
* to simulate an inconsistent export * to simulate an inconsistent export
* @return directory where data is exported * @return directory where data is exported
*/ */
File export( File export(String exportRootPath, Iterable<Class<?>> pojoTypes, Set<Key<?>> excludes)
String exportRootPath, Iterable<Class<?>> pojoTypes, Set<Key<? extends Object>> excludes)
throws IOException { throws IOException {
File exportDirectory = getExportDirectory(exportRootPath); File exportDirectory = getExportDirectory(exportRootPath);
for (Class<?> pojoType : pojoTypes) { for (Class<?> pojoType : pojoTypes) {

View file

@ -44,8 +44,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.KV;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -113,7 +111,7 @@ public class BackupTestStoreTest {
assertWithMessage("Directory %s should not exist.", exportFolder.getAbsoluteFile()) assertWithMessage("Directory %s should not exist.", exportFolder.getAbsoluteFile())
.that(exportFolder.exists()) .that(exportFolder.exists())
.isFalse(); .isFalse();
File actualExportFolder = export(exportRootPath, Collections.EMPTY_SET); File actualExportFolder = export(exportRootPath, ImmutableSet.of());
assertThat(actualExportFolder).isEquivalentAccordingToCompareTo(exportFolder); assertThat(actualExportFolder).isEquivalentAccordingToCompareTo(exportFolder);
try (Stream<String> files = try (Stream<String> files =
Files.walk(exportFolder.toPath()) Files.walk(exportFolder.toPath())
@ -136,14 +134,14 @@ public class BackupTestStoreTest {
assertWithMessage("Directory %s should not exist.", exportFolder.getAbsoluteFile()) assertWithMessage("Directory %s should not exist.", exportFolder.getAbsoluteFile())
.that(exportFolder.exists()) .that(exportFolder.exists())
.isFalse(); .isFalse();
assertThat(export(exportRootPath, Collections.EMPTY_SET)) assertThat(export(exportRootPath, ImmutableSet.of()))
.isEquivalentAccordingToCompareTo(exportFolder); .isEquivalentAccordingToCompareTo(exportFolder);
} }
@Test @Test
void export_dataReadBack() throws IOException { void export_dataReadBack() throws IOException {
String exportRootPath = tempDir.getAbsolutePath(); String exportRootPath = tempDir.getAbsolutePath();
File exportFolder = export(exportRootPath, Collections.EMPTY_SET); File exportFolder = export(exportRootPath, ImmutableSet.of());
ImmutableList<Object> loadedRegistries = ImmutableList<Object> loadedRegistries =
loadExportedEntities(new File(exportFolder, "/all_namespaces/kind_Registry/output-0")); loadExportedEntities(new File(exportFolder, "/all_namespaces/kind_Registry/output-0"));
assertThat(loadedRegistries).containsExactly(registry); assertThat(loadedRegistries).containsExactly(registry);
@ -228,7 +226,7 @@ public class BackupTestStoreTest {
assertThat(CommitLogImports.loadEntities(commitLogFile)).isEmpty(); assertThat(CommitLogImports.loadEntities(commitLogFile)).isEmpty();
} }
private File export(String exportRootPath, Set<Key<?>> excludes) throws IOException { private File export(String exportRootPath, ImmutableSet<Key<?>> excludes) throws IOException {
return store.export( return store.export(
exportRootPath, exportRootPath,
ImmutableList.of(ContactResource.class, DomainBase.class, Registry.class), ImmutableList.of(ContactResource.class, DomainBase.class, Registry.class),

View file

@ -220,7 +220,7 @@ public class EppTestCase {
return actualOutput; return actualOutput;
} }
private FakeResponse executeXmlCommand(String inputXml) throws Exception { private FakeResponse executeXmlCommand(String inputXml) {
EppRequestHandler handler = new EppRequestHandler(); EppRequestHandler handler = new EppRequestHandler();
FakeResponse response = new FakeResponse(); FakeResponse response = new FakeResponse();
handler.response = response; handler.response = response;

View file

@ -200,7 +200,7 @@ class CertificateCheckerTest {
} }
@Test @Test
void test_checkCertificate_validCertificateString() throws Exception { void test_checkCertificate_validCertificateString() {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
assertThat(certificateChecker.checkCertificate(SAMPLE_CERT3)).isEmpty(); assertThat(certificateChecker.checkCertificate(SAMPLE_CERT3)).isEmpty();
assertThat(certificateChecker.checkCertificate(SAMPLE_CERT)) assertThat(certificateChecker.checkCertificate(SAMPLE_CERT))
@ -208,7 +208,7 @@ class CertificateCheckerTest {
} }
@Test @Test
void test_checkCertificate_invalidCertificateString() throws Exception { void test_checkCertificate_invalidCertificateString() {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(

View file

@ -55,7 +55,7 @@ public abstract class EntityTestCase {
*/ */
ENABLED, ENABLED,
/** The test is not relevant for JPA coverage checks. */ /** The test is not relevant for JPA coverage checks. */
DISABLED; DISABLED
} }
protected FakeClock fakeClock = new FakeClock(DateTime.now(UTC)); protected FakeClock fakeClock = new FakeClock(DateTime.now(UTC));

View file

@ -20,6 +20,7 @@ import static google.registry.model.ImmutableObjectSubject.immutableObjectCorres
import static google.registry.model.registry.Registry.TldState.GENERAL_AVAILABILITY; import static google.registry.model.registry.Registry.TldState.GENERAL_AVAILABILITY;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.AppEngineExtension.makeRegistrar2;
import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.newContactResourceWithRoid; import static google.registry.testing.DatabaseHelper.newContactResourceWithRoid;
import static google.registry.testing.DatabaseHelper.newDomainBase; import static google.registry.testing.DatabaseHelper.newDomainBase;
@ -42,7 +43,6 @@ import google.registry.model.domain.rgp.GracePeriodStatus;
import google.registry.model.domain.secdns.DelegationSignerData; import google.registry.model.domain.secdns.DelegationSignerData;
import google.registry.model.eppcommon.Trid; import google.registry.model.eppcommon.Trid;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.registrar.Registrar;
import google.registry.model.registry.Registries; import google.registry.model.registry.Registries;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import google.registry.model.reporting.DomainTransactionRecord; import google.registry.model.reporting.DomainTransactionRecord;
@ -144,13 +144,9 @@ public class DomainHistoryTest extends EntityTestCase {
.transact( .transact(
() -> { () -> {
jpaTm().insert(registry); jpaTm().insert(registry);
Registrar registrar = jpaTm()
appEngine .insert(
.makeRegistrar2() makeRegistrar2().asBuilder().setAllowedTlds(ImmutableSet.of("tld")).build());
.asBuilder()
.setAllowedTlds(ImmutableSet.of("tld"))
.build();
jpaTm().insert(registrar);
}); });
HostResource host = newHostResourceWithRoid("ns1.example.com", "host1"); HostResource host = newHostResourceWithRoid("ns1.example.com", "host1");

View file

@ -54,7 +54,7 @@ import org.junit.jupiter.api.BeforeEach;
/** Unit tests for {@link Registry}. */ /** Unit tests for {@link Registry}. */
@DualDatabaseTest @DualDatabaseTest
public class RegistryTest extends EntityTestCase { public final class RegistryTest extends EntityTestCase {
RegistryTest() { RegistryTest() {
super(JpaEntityCoverageCheck.ENABLED); super(JpaEntityCoverageCheck.ENABLED);
@ -66,7 +66,7 @@ public class RegistryTest extends EntityTestCase {
} }
@TestOfyAndSql @TestOfyAndSql
public void testPersistence_updateReservedAndPremiumListSuccessfully() { void testPersistence_updateReservedAndPremiumListSuccessfully() {
ReservedList rl15 = persistReservedList("tld-reserved15", "potato,FULLY_BLOCKED"); ReservedList rl15 = persistReservedList("tld-reserved15", "potato,FULLY_BLOCKED");
PremiumList pl = persistPremiumList("tld2", "lol,USD 50", "cat,USD 700"); PremiumList pl = persistPremiumList("tld2", "lol,USD 50", "cat,USD 700");
Registry registry = Registry registry =

View file

@ -38,7 +38,7 @@ import org.joda.time.DateTime;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@DualDatabaseTest @DualDatabaseTest
public class HistoryEntryDaoTest extends EntityTestCase { class HistoryEntryDaoTest extends EntityTestCase {
private DomainBase domain; private DomainBase domain;
private HistoryEntry historyEntry; private HistoryEntry historyEntry;

View file

@ -35,7 +35,7 @@ import org.junit.jupiter.api.BeforeEach;
/** Unit tests for {@link Spec11ThreatMatchDao}. */ /** Unit tests for {@link Spec11ThreatMatchDao}. */
@DualDatabaseTest @DualDatabaseTest
public class Spec11ThreatMatchDaoTest extends EntityTestCase { class Spec11ThreatMatchDaoTest extends EntityTestCase {
private static final LocalDate TODAY = new LocalDate(2020, 8, 4); private static final LocalDate TODAY = new LocalDate(2020, 8, 4);
private static final LocalDate YESTERDAY = new LocalDate(2020, 8, 3); private static final LocalDate YESTERDAY = new LocalDate(2020, 8, 3);

View file

@ -40,7 +40,7 @@ import org.junit.jupiter.api.Disabled;
/** Unit tests for {@link Spec11ThreatMatch}. */ /** Unit tests for {@link Spec11ThreatMatch}. */
@DualDatabaseTest @DualDatabaseTest
public class Spec11ThreatMatchTest extends EntityTestCase { public final class Spec11ThreatMatchTest extends EntityTestCase {
private static final String REGISTRAR_ID = "registrar"; private static final String REGISTRAR_ID = "registrar";
private static final LocalDate DATE = LocalDate.parse("2020-06-10", ISODateTimeFormat.date()); private static final LocalDate DATE = LocalDate.parse("2020-06-10", ISODateTimeFormat.date());

View file

@ -82,7 +82,7 @@ class EntityCallbacksListenerTest {
@Test @Test
void verifyAllManagedEntities_haveNoMethodWithEmbedded() { void verifyAllManagedEntities_haveNoMethodWithEmbedded() {
ImmutableSet<Class> violations = ImmutableSet<Class<?>> violations =
PersistenceXmlUtility.getManagedClasses().stream() PersistenceXmlUtility.getManagedClasses().stream()
.filter(clazz -> clazz.isAnnotationPresent(Entity.class)) .filter(clazz -> clazz.isAnnotationPresent(Entity.class))
.filter(EntityCallbacksListenerTest::hasMethodAnnotatedWithEmbedded) .filter(EntityCallbacksListenerTest::hasMethodAnnotatedWithEmbedded)

View file

@ -30,19 +30,19 @@ class PersistenceXmlTest {
@Test @Test
void verifyClassTags_containOnlyRequiredClasses() { void verifyClassTags_containOnlyRequiredClasses() {
ImmutableList<Class> managedClassed = PersistenceXmlUtility.getManagedClasses(); ImmutableList<Class<?>> managedClasses = PersistenceXmlUtility.getManagedClasses();
ImmutableList<Class> unnecessaryClasses = ImmutableList<Class<?>> unnecessaryClasses =
managedClassed.stream() managedClasses.stream()
.filter( .filter(
clazz -> clazz ->
!clazz.isAnnotationPresent(Entity.class) !clazz.isAnnotationPresent(Entity.class)
&& !AttributeConverter.class.isAssignableFrom(clazz)) && !AttributeConverter.class.isAssignableFrom(clazz))
.collect(toImmutableList()); .collect(toImmutableList());
ImmutableSet<Class> duplicateClasses = ImmutableSet<Class<?>> duplicateClasses =
managedClassed.stream() managedClasses.stream()
.filter(clazz -> Collections.frequency(managedClassed, clazz) > 1) .filter(clazz -> Collections.frequency(managedClasses, clazz) > 1)
.collect(toImmutableSet()); .collect(toImmutableSet());
assertWithMessage("Found duplicate <class> tags defined in persistence.xml.") assertWithMessage("Found duplicate <class> tags defined in persistence.xml.")

View file

@ -55,11 +55,9 @@ public class LocalDateConverterTest {
private LocalDateConverterTestEntity persistAndLoadTestEntity(LocalDate date) { private LocalDateConverterTestEntity persistAndLoadTestEntity(LocalDate date) {
LocalDateConverterTestEntity entity = new LocalDateConverterTestEntity(date); LocalDateConverterTestEntity entity = new LocalDateConverterTestEntity(date);
jpaTm().transact(() -> jpaTm().insert(entity)); jpaTm().transact(() -> jpaTm().insert(entity));
LocalDateConverterTestEntity retrievedEntity = return jpaTm()
jpaTm() .transact(
.transact( () -> jpaTm().loadByKey(VKey.createSql(LocalDateConverterTestEntity.class, "id")));
() -> jpaTm().loadByKey(VKey.createSql(LocalDateConverterTestEntity.class, "id")));
return retrievedEntity;
} }
/** Override entity name to avoid the nested class reference. */ /** Override entity name to avoid the nested class reference. */

View file

@ -50,13 +50,13 @@ public class JpaEntityCoverageExtension implements BeforeEachCallback, AfterEach
// TransactionEntity is trivial, its persistence is tested in TransactionTest. // TransactionEntity is trivial, its persistence is tested in TransactionTest.
"TransactionEntity"); "TransactionEntity");
private static final ImmutableSet<Class> ALL_JPA_ENTITIES = private static final ImmutableSet<Class<?>> ALL_JPA_ENTITIES =
PersistenceXmlUtility.getManagedClasses().stream() PersistenceXmlUtility.getManagedClasses().stream()
.filter(e -> !IGNORE_ENTITIES.contains(e.getSimpleName())) .filter(e -> !IGNORE_ENTITIES.contains(e.getSimpleName()))
.filter(e -> e.isAnnotationPresent(Entity.class)) .filter(e -> e.isAnnotationPresent(Entity.class))
.filter(e -> !e.isAnnotationPresent(DiscriminatorValue.class)) .filter(e -> !e.isAnnotationPresent(DiscriminatorValue.class))
.collect(ImmutableSet.toImmutableSet()); .collect(ImmutableSet.toImmutableSet());
private static final Set<Class> allCoveredJpaEntities = Sets.newHashSet(); private static final Set<Class<?>> allCoveredJpaEntities = Sets.newHashSet();
// Map of test class name to boolean flag indicating if it tests any JPA entities. // Map of test class name to boolean flag indicating if it tests any JPA entities.
private static final Map<String, Boolean> testsJpaEntities = Maps.newHashMap(); private static final Map<String, Boolean> testsJpaEntities = Maps.newHashMap();
@ -81,7 +81,7 @@ public class JpaEntityCoverageExtension implements BeforeEachCallback, AfterEach
testsJpaEntities.clear(); testsJpaEntities.clear();
} }
public static Set<Class> getUncoveredEntities() { public static Set<Class<?>> getUncoveredEntities() {
return Sets.difference(ALL_JPA_ENTITIES, allCoveredJpaEntities); return Sets.difference(ALL_JPA_ENTITIES, allCoveredJpaEntities);
} }
@ -99,9 +99,9 @@ public class JpaEntityCoverageExtension implements BeforeEachCallback, AfterEach
* *
* @return true if an instance of {@code entityType} is found in the database and can be read * @return true if an instance of {@code entityType} is found in the database and can be read
*/ */
private static boolean isPersisted(Class entityType) { private static boolean isPersisted(Class<?> entityType) {
try { try {
List result = List<?> result =
jpaTm() jpaTm()
.transact( .transact(
() -> () ->

View file

@ -49,7 +49,7 @@ public class JpaTestRules {
public static class JpaIntegrationTestExtension extends JpaTransactionManagerExtension { public static class JpaIntegrationTestExtension extends JpaTransactionManagerExtension {
private JpaIntegrationTestExtension( private JpaIntegrationTestExtension(
Clock clock, Clock clock,
ImmutableList<Class> extraEntityClasses, ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) { ImmutableMap<String, String> userProperties) {
super(clock, Optional.of(GOLDEN_SCHEMA_SQL_PATH), extraEntityClasses, userProperties); super(clock, Optional.of(GOLDEN_SCHEMA_SQL_PATH), extraEntityClasses, userProperties);
} }
@ -63,7 +63,7 @@ public class JpaTestRules {
private JpaUnitTestExtension( private JpaUnitTestExtension(
Clock clock, Clock clock,
Optional<String> initScriptPath, Optional<String> initScriptPath,
ImmutableList<Class> extraEntityClasses, ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) { ImmutableMap<String, String> userProperties) {
super(clock, initScriptPath, false, extraEntityClasses, userProperties); super(clock, initScriptPath, false, extraEntityClasses, userProperties);
} }
@ -105,8 +105,8 @@ public class JpaTestRules {
private String initScript; private String initScript;
private Clock clock; private Clock clock;
private List<Class> extraEntityClasses = new ArrayList<Class>(); private List<Class<?>> extraEntityClasses = new ArrayList<>();
private Map<String, String> userProperties = new HashMap<String, String>(); private Map<String, String> userProperties = new HashMap<>();
/** /**
* Sets the SQL script to be used to initialize the database. If not set, * Sets the SQL script to be used to initialize the database. If not set,
@ -125,7 +125,7 @@ public class JpaTestRules {
} }
/** Adds annotated class(es) to the known entities for the database. */ /** Adds annotated class(es) to the known entities for the database. */
public Builder withEntityClass(Class... classes) { public Builder withEntityClass(Class<?>... classes) {
this.extraEntityClasses.addAll(ImmutableSet.copyOf(classes)); this.extraEntityClasses.addAll(ImmutableSet.copyOf(classes));
return this; return this;
} }

View file

@ -87,8 +87,8 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
private final Clock clock; private final Clock clock;
private final Optional<String> initScriptPath; private final Optional<String> initScriptPath;
private final ImmutableList<Class> extraEntityClasses; private final ImmutableList<Class<?>> extraEntityClasses;
private final ImmutableMap userProperties; private final ImmutableMap<String, String> userProperties;
private static final JdbcDatabaseContainer database = create(); private static final JdbcDatabaseContainer database = create();
private static final HibernateSchemaExporter exporter = private static final HibernateSchemaExporter exporter =
@ -102,7 +102,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
private JpaTransactionManager cachedTm; private JpaTransactionManager cachedTm;
// Hash of the ORM entity names requested by this rule instance. // Hash of the ORM entity names requested by this rule instance.
private int entityHash; private final int entityHash;
// Whether to create nomulus tables in the test db. Right now, only the JpaTestRules set this to // Whether to create nomulus tables in the test db. Right now, only the JpaTestRules set this to
// false. // false.
@ -112,7 +112,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
Clock clock, Clock clock,
Optional<String> initScriptPath, Optional<String> initScriptPath,
boolean includeNomulusSchema, boolean includeNomulusSchema,
ImmutableList<Class> extraEntityClasses, ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) { ImmutableMap<String, String> userProperties) {
this.clock = clock; this.clock = clock;
this.initScriptPath = initScriptPath; this.initScriptPath = initScriptPath;
@ -125,7 +125,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
JpaTransactionManagerExtension( JpaTransactionManagerExtension(
Clock clock, Clock clock,
Optional<String> initScriptPath, Optional<String> initScriptPath,
ImmutableList<Class> extraEntityClasses, ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) { ImmutableMap<String, String> userProperties) {
this.clock = clock; this.clock = clock;
this.initScriptPath = initScriptPath; this.initScriptPath = initScriptPath;
@ -143,7 +143,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
} }
private static int getOrmEntityHash( private static int getOrmEntityHash(
Optional<String> initScriptPath, ImmutableList<Class> extraEntityClasses) { Optional<String> initScriptPath, ImmutableList<Class<?>> extraEntityClasses) {
return Streams.concat( return Streams.concat(
Stream.of(initScriptPath.orElse("")), Stream.of(initScriptPath.orElse("")),
extraEntityClasses.stream().map(Class::getCanonicalName)) extraEntityClasses.stream().map(Class::getCanonicalName))
@ -172,7 +172,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
executeSql(new String(Files.readAllBytes(tempSqlFile.toPath()), StandardCharsets.UTF_8)); executeSql(new String(Files.readAllBytes(tempSqlFile.toPath()), StandardCharsets.UTF_8));
} }
ImmutableMap properties = PersistenceModule.provideDefaultDatabaseConfigs(); ImmutableMap<String, String> properties = PersistenceModule.provideDefaultDatabaseConfigs();
if (!userProperties.isEmpty()) { if (!userProperties.isEmpty()) {
// If there are user properties, create a new properties object with these added. // If there are user properties, create a new properties object with these added.
Map<String, String> mergedProperties = Maps.newHashMap(); Map<String, String> mergedProperties = Maps.newHashMap();
@ -338,7 +338,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
return Bootstrap.getEntityManagerFactoryBuilder(descriptor, properties).build(); return Bootstrap.getEntityManagerFactoryBuilder(descriptor, properties).build();
} }
private ImmutableList<Class> getTestEntities() { private ImmutableList<Class<?>> getTestEntities() {
// We have to add the TransactionEntity to extra entities, as this is required by the // We have to add the TransactionEntity to extra entities, as this is required by the
// transaction replication mechanism. // transaction replication mechanism.
return Stream.concat(extraEntityClasses.stream(), Stream.of(TransactionEntity.class)) return Stream.concat(extraEntityClasses.stream(), Stream.of(TransactionEntity.class))

View file

@ -180,7 +180,7 @@ class JpaTransactionManagerImplTest {
@Test @Test
void transact_retriesNestedOptimisticLockExceptions() { void transact_retriesNestedOptimisticLockExceptions() {
JpaTransactionManager spyJpaTm = spy(jpaTm()); JpaTransactionManager spyJpaTm = spy(jpaTm());
doThrow(new RuntimeException().initCause(new OptimisticLockException())) doThrow(new RuntimeException(new OptimisticLockException()))
.when(spyJpaTm) .when(spyJpaTm)
.delete(any(VKey.class)); .delete(any(VKey.class));
spyJpaTm.transact(() -> spyJpaTm.insert(theEntity)); spyJpaTm.transact(() -> spyJpaTm.insert(theEntity));
@ -220,8 +220,8 @@ class JpaTransactionManagerImplTest {
void transactNewReadOnly_retriesNestedJdbcConnectionExceptions() { void transactNewReadOnly_retriesNestedJdbcConnectionExceptions() {
JpaTransactionManager spyJpaTm = spy(jpaTm()); JpaTransactionManager spyJpaTm = spy(jpaTm());
doThrow( doThrow(
new RuntimeException() new RuntimeException(
.initCause(new JDBCConnectionException("connection exception", new SQLException()))) new JDBCConnectionException("connection exception", new SQLException())))
.when(spyJpaTm) .when(spyJpaTm)
.loadByKey(any(VKey.class)); .loadByKey(any(VKey.class));
spyJpaTm.transact(() -> spyJpaTm.insert(theEntity)); spyJpaTm.transact(() -> spyJpaTm.insert(theEntity));

View file

@ -52,7 +52,7 @@ public class JpaTransactionManagerRuleTest {
jpaTm() jpaTm()
.transact( .transact(
() -> { () -> {
List results = List<?> results =
jpaTm() jpaTm()
.getEntityManager() .getEntityManager()
.createNativeQuery("SELECT * FROM \"TestEntity\"") .createNativeQuery("SELECT * FROM \"TestEntity\"")

View file

@ -78,7 +78,7 @@ public class SecretManagerClientTest {
} }
@AfterEach @AfterEach
void afterEach() throws IOException { void afterEach() {
if (isUnitTest) { if (isUnitTest) {
return; return;
} }

View file

@ -130,7 +130,7 @@ class IcannHttpReporterTest {
} }
@Test @Test
void testFail_transportException() throws Exception { void testFail_transportException() {
IcannHttpReporter reporter = createReporter(); IcannHttpReporter reporter = createReporter();
reporter.httpTransport = reporter.httpTransport =
createMockTransport(HttpStatusCodes.STATUS_CODE_FORBIDDEN, ByteSource.empty()); createMockTransport(HttpStatusCodes.STATUS_CODE_FORBIDDEN, ByteSource.empty());

View file

@ -154,8 +154,7 @@ public class LockDaoTest {
assertAboutLogs() assertAboutLogs()
.that(logHandler) .that(logHandler)
.hasLogAtLevelWithMessage( .hasLogAtLevelWithMessage(
Level.WARNING, Level.WARNING, "Cloud SQL lock for testResource with tld GLOBAL should be null");
String.format("Cloud SQL lock for testResource with tld GLOBAL should be null"));
} }
@Test @Test
@ -171,22 +170,19 @@ public class LockDaoTest {
.that(logHandler) .that(logHandler)
.hasLogAtLevelWithMessage( .hasLogAtLevelWithMessage(
Level.WARNING, Level.WARNING,
String.format( "Datastore lock requestLogId of wrong does not equal Cloud SQL lock requestLogId"
"Datastore lock requestLogId of wrong does not equal Cloud SQL lock requestLogId" + " of testLogId");
+ " of testLogId"));
assertAboutLogs() assertAboutLogs()
.that(logHandler) .that(logHandler)
.hasLogAtLevelWithMessage( .hasLogAtLevelWithMessage(
Level.WARNING, Level.WARNING,
String.format( "Datastore lock acquiredTime of 1969-12-31T00:00:00.000Z does not equal Cloud SQL"
"Datastore lock acquiredTime of 1969-12-31T00:00:00.000Z does not equal Cloud SQL" + " lock acquiredTime of 1970-01-01T00:00:00.000Z");
+ " lock acquiredTime of 1970-01-01T00:00:00.000Z"));
assertAboutLogs() assertAboutLogs()
.that(logHandler) .that(logHandler)
.hasLogAtLevelWithMessage( .hasLogAtLevelWithMessage(
Level.WARNING, Level.WARNING,
String.format( "Datastore lock expirationTime of 1969-12-31T00:00:00.003Z does not equal Cloud"
"Datastore lock expirationTime of 1969-12-31T00:00:00.003Z does not equal Cloud" + " SQL lock expirationTime of 1970-01-01T00:00:00.002Z");
+ " SQL lock expirationTime of 1970-01-01T00:00:00.002Z"));
} }
} }

View file

@ -381,9 +381,7 @@ public final class AppEngineExtension implements BeforeEachCallback, AfterEachCa
jpaIntegrationWithCoverageExtension.beforeEach(context); jpaIntegrationWithCoverageExtension.beforeEach(context);
} else if (withJpaUnitTest) { } else if (withJpaUnitTest) {
jpaUnitTestRule = jpaUnitTestRule =
builder builder.withEntityClass(jpaTestEntities.toArray(new Class[0])).buildUnitTestRule();
.withEntityClass(jpaTestEntities.toArray(new Class[jpaTestEntities.size()]))
.buildUnitTestRule();
jpaUnitTestRule.beforeEach(context); jpaUnitTestRule.beforeEach(context);
} else { } else {
jpaIntegrationTestRule = builder.buildIntegrationTestRule(); jpaIntegrationTestRule = builder.buildIntegrationTestRule();

View file

@ -31,7 +31,7 @@ public class ContextCapturingMetaExtension implements BeforeEachCallback {
private ExtensionContext context; private ExtensionContext context;
@Override @Override
public void beforeEach(ExtensionContext context) throws Exception { public void beforeEach(ExtensionContext context) {
this.context = context; this.context = context;
} }

View file

@ -76,7 +76,7 @@ class CreateCdnsTldTest extends CommandTestCase<CreateCdnsTld> {
@Test @Test
@MockitoSettings(strictness = Strictness.LENIENT) @MockitoSettings(strictness = Strictness.LENIENT)
void testSandboxTldRestrictions() throws Exception { void testSandboxTldRestrictions() {
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,

View file

@ -365,7 +365,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
} }
@Test @Test
void testFail_clientCertFileFlagWithViolation() throws Exception { void testFail_clientCertFileFlagWithViolation() {
fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
InsecureCertificateException thrown = InsecureCertificateException thrown =
assertThrows( assertThrows(
@ -395,7 +395,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
} }
@Test @Test
void testFail_clientCertFileFlagWithMultipleViolations() throws Exception { void testFail_clientCertFileFlagWithMultipleViolations() {
fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z"));
InsecureCertificateException thrown = InsecureCertificateException thrown =
assertThrows( assertThrows(
@ -452,7 +452,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
} }
@Test @Test
void testFail_failoverClientCertFileFlagWithViolations() throws Exception { void testFail_failoverClientCertFileFlagWithViolations() {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
InsecureCertificateException thrown = InsecureCertificateException thrown =
assertThrows( assertThrows(
@ -482,7 +482,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
} }
@Test @Test
void testFail_failoverClientCertFileFlagWithMultipleViolations() throws Exception { void testFail_failoverClientCertFileFlagWithMultipleViolations() {
fakeClock.setTo(DateTime.parse("2055-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2055-11-01T00:00:00Z"));
InsecureCertificateException thrown = InsecureCertificateException thrown =
assertThrows( assertThrows(

View file

@ -101,7 +101,7 @@ class CurlCommandTest extends CommandTestCase<CurlCommand> {
@Test @Test
@MockitoSettings(strictness = Strictness.LENIENT) @MockitoSettings(strictness = Strictness.LENIENT)
void testPostInvocation_badContentType() throws Exception { void testPostInvocation_badContentType() {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->

View file

@ -80,7 +80,7 @@ class DedupeOneTimeBillingEventIdsCommandTest
} }
@Test @Test
void resaveBillingEvent_failsWhenReferredByDomain() throws Exception { void resaveBillingEvent_failsWhenReferredByDomain() {
persistResource( persistResource(
domain domain
.asBuilder() .asBuilder()

View file

@ -115,7 +115,7 @@ class GenerateDnsReportCommandTest extends CommandTestCase<GenerateDnsReportComm
"2607:f8b0:400d:c00:0:0:0:c1")); "2607:f8b0:400d:c00:0:0:0:c1"));
@BeforeEach @BeforeEach
void beforeEach() throws Exception { void beforeEach() {
output = tmpDir.resolve("out.dat"); output = tmpDir.resolve("out.dat");
command.clock = clock; command.clock = clock;
clock.setTo(now); clock.setTo(now);

View file

@ -58,7 +58,7 @@ class GenerateSqlErDiagramCommandTest extends CommandTestCase<GenerateSqlErDiagr
} }
@Test @Test
void validateErDiagramIsUpToDate() throws Exception { void validateErDiagramIsUpToDate() {
String goldenFullDiagram = String goldenFullDiagram =
ResourceUtils.readResourceUtf8( ResourceUtils.readResourceUtf8(
Resources.getResource( Resources.getResource(

View file

@ -34,7 +34,7 @@ class SetSqlReplayCheckpointCommandTest extends CommandTestCase<SetSqlReplayChec
} }
@Test @Test
void testFailure_multipleParams() throws Exception { void testFailure_multipleParams() {
DateTime one = DateTime.parse("2000-06-06T22:00:00.0Z"); DateTime one = DateTime.parse("2000-06-06T22:00:00.0Z");
DateTime two = DateTime.parse("2001-06-06T22:00:00.0Z"); DateTime two = DateTime.parse("2001-06-06T22:00:00.0Z");
assertThrows(IllegalArgumentException.class, () -> runCommand(one.toString(), two.toString())); assertThrows(IllegalArgumentException.class, () -> runCommand(one.toString(), two.toString()));

View file

@ -266,8 +266,7 @@ class ShellCommandTest {
@Test @Test
void testEncapsulatedOutputStream_emptyStream() { void testEncapsulatedOutputStream_emptyStream() {
ByteArrayOutputStream backing = new ByteArrayOutputStream(); ByteArrayOutputStream backing = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(new ShellCommand.EncapsulatingOutputStream(backing, "out: ")).close();
new PrintStream(new ShellCommand.EncapsulatingOutputStream(backing, "out: "))) {}
assertThat(backing.toString()).isEqualTo(""); assertThat(backing.toString()).isEqualTo("");
} }

View file

@ -54,7 +54,7 @@ class PathParameterTest {
} }
@Test @Test
void testConvert_relativePath_returnsOriginalFile() throws Exception { void testConvert_relativePath_returnsOriginalFile() {
Path currentDirectory = Paths.get("").toAbsolutePath(); Path currentDirectory = Paths.get("").toAbsolutePath();
Path file = Paths.get(tmpDir.resolve("tmp.file").toString()); Path file = Paths.get(tmpDir.resolve("tmp.file").toString());
Path relative = file.relativize(currentDirectory); Path relative = file.relativize(currentDirectory);
@ -65,7 +65,7 @@ class PathParameterTest {
} }
@Test @Test
void testConvert_extraSlash_returnsWithoutSlash() throws Exception { void testConvert_extraSlash_returnsWithoutSlash() {
Path file = Paths.get(tmpDir.resolve("file.new").toString()); Path file = Paths.get(tmpDir.resolve("file.new").toString());
assertThat((Object) vanilla.convert(file + "/")).isEqualTo(file); assertThat((Object) vanilla.convert(file + "/")).isEqualTo(file);
} }
@ -115,7 +115,7 @@ class PathParameterTest {
private final PathParameter outputFile = new PathParameter.OutputFile(); private final PathParameter outputFile = new PathParameter.OutputFile();
@Test @Test
void testOutputFileValidate_normalFile_works() throws Exception { void testOutputFileValidate_normalFile_works() {
outputFile.validate("input", tmpDir.resolve("testfile").toString()); outputFile.validate("input", tmpDir.resolve("testfile").toString());
} }

View file

@ -146,7 +146,7 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
} }
@Test @Test
void testEmptyOrNullCertificate_doesNotClearOutCurrentOne() throws Exception { void testEmptyOrNullCertificate_doesNotClearOutCurrentOne() {
Registrar initialRegistrar = Registrar initialRegistrar =
persistResource( persistResource(
loadRegistrar(CLIENT_ID) loadRegistrar(CLIENT_ID)

View file

@ -16,7 +16,6 @@ package google.registry.documentation;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
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.nio.file.Files; import java.nio.file.Files;
@ -41,9 +40,7 @@ class FlowDocumentationTest {
@Test @Test
void testGeneratedMatchesGolden() throws Exception { void testGeneratedMatchesGolden() throws Exception {
// Read the markdown file. // Read the markdown file.
Path goldenMarkdownPath = GOLDEN_MARKDOWN_FILEPATH; String goldenMarkdown = Files.readString(GOLDEN_MARKDOWN_FILEPATH);
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

@ -101,7 +101,7 @@ public final class NettyExtension implements AfterEachCallback {
ChannelInitializer<LocalChannel> clientInitializer = ChannelInitializer<LocalChannel> clientInitializer =
new ChannelInitializer<LocalChannel>() { new ChannelInitializer<LocalChannel>() {
@Override @Override
protected void initChannel(LocalChannel ch) throws Exception { protected void initChannel(LocalChannel ch) {
// Add the given handler // Add the given handler
ch.pipeline().addLast(handler); ch.pipeline().addLast(handler);
// Add the "dumpHandler" last to log the incoming message // Add the "dumpHandler" last to log the incoming message
@ -178,7 +178,7 @@ public final class NettyExtension implements AfterEachCallback {
} }
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) {
// In the test we only send messages of type ByteBuf. // In the test we only send messages of type ByteBuf.
assertThat(msg).isInstanceOf(ByteBuf.class); assertThat(msg).isInstanceOf(ByteBuf.class);
String request = ((ByteBuf) msg).toString(UTF_8); String request = ((ByteBuf) msg).toString(UTF_8);
@ -189,7 +189,7 @@ public final class NettyExtension implements AfterEachCallback {
/** Saves any inbound error as the cause of the promise failure. */ /** Saves any inbound error as the cause of the promise failure. */
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ChannelFuture unusedFuture = ChannelFuture unusedFuture =
ctx.channel().closeFuture().addListener(f -> requestFuture.completeExceptionally(cause)); ctx.channel().closeFuture().addListener(f -> requestFuture.completeExceptionally(cause));
} }
@ -205,7 +205,7 @@ public final class NettyExtension implements AfterEachCallback {
} }
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) {
// In the test we only send messages of type ByteBuf. // In the test we only send messages of type ByteBuf.
assertThat(msg).isInstanceOf(ByteBuf.class); assertThat(msg).isInstanceOf(ByteBuf.class);
String response = ((ByteBuf) msg).toString(UTF_8); String response = ((ByteBuf) msg).toString(UTF_8);
@ -218,7 +218,7 @@ public final class NettyExtension implements AfterEachCallback {
/** Saves any inbound error into the failure cause of the promise. */ /** Saves any inbound error into the failure cause of the promise. */
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.channel().closeFuture().addListener(f -> responseFuture.completeExceptionally(cause)); ctx.channel().closeFuture().addListener(f -> responseFuture.completeExceptionally(cause));
} }
} }

View file

@ -270,7 +270,7 @@ public abstract class ProbingAction implements Callable<ChannelFuture> {
.handler( .handler(
new ChannelInitializer<Channel>() { new ChannelInitializer<Channel>() {
@Override @Override
protected void initChannel(Channel outboundChannel) throws Exception { protected void initChannel(Channel outboundChannel) {
// Uses Handlers from Protocol to fill pipeline in order of provided handlers. // Uses Handlers from Protocol to fill pipeline in order of provided handlers.
for (Provider<? extends ChannelHandler> handlerProvider : for (Provider<? extends ChannelHandler> handlerProvider :
protocol().handlerProviders()) { protocol().handlerProviders()) {

View file

@ -414,7 +414,7 @@ public class EppMessage {
} }
} }
void addNamespace(String prefix, String namespaceURI) throws Exception { void addNamespace(String prefix, String namespaceURI) {
checkArgument(!isNullOrEmpty(prefix), "prefix"); checkArgument(!isNullOrEmpty(prefix), "prefix");
checkArgument(!isNullOrEmpty(namespaceURI), "namespaceURI"); checkArgument(!isNullOrEmpty(namespaceURI), "namespaceURI");
if (nsPrefixMap.containsKey(prefix)) { if (nsPrefixMap.containsKey(prefix)) {

View file

@ -84,7 +84,7 @@ public class ProxyServer implements Runnable {
*/ */
private static class ServerChannelInitializer extends ChannelInitializer<NioSocketChannel> { private static class ServerChannelInitializer extends ChannelInitializer<NioSocketChannel> {
@Override @Override
protected void initChannel(NioSocketChannel inboundChannel) throws Exception { protected void initChannel(NioSocketChannel inboundChannel) {
// Add inbound channel handlers. // Add inbound channel handlers.
FrontendProtocol inboundProtocol = FrontendProtocol inboundProtocol =
(FrontendProtocol) inboundChannel.parent().attr(PROTOCOL_KEY).get(); (FrontendProtocol) inboundChannel.parent().attr(PROTOCOL_KEY).get();
@ -110,8 +110,7 @@ public class ProxyServer implements Runnable {
.handler( .handler(
new ChannelInitializer<NioSocketChannel>() { new ChannelInitializer<NioSocketChannel>() {
@Override @Override
protected void initChannel(NioSocketChannel outboundChannel) protected void initChannel(NioSocketChannel outboundChannel) {
throws Exception {
addHandlers( addHandlers(
outboundChannel.pipeline(), outboundProtocol.handlerProviders()); outboundChannel.pipeline(), outboundProtocol.handlerProviders());
} }
@ -301,7 +300,7 @@ public class ProxyServer implements Runnable {
} }
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) {
// Use JDK logger for Netty's LoggingHandler, // Use JDK logger for Netty's LoggingHandler,
// which is what Flogger uses under the hood. // which is what Flogger uses under the hood.
InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE); InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE);

View file

@ -102,8 +102,7 @@ public class BackendMetricsHandler extends ChannelDuplexHandler {
} }
@Override @Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
throws Exception {
checkArgument(msg instanceof FullHttpRequest, "Outgoing request must be FullHttpRequest."); checkArgument(msg instanceof FullHttpRequest, "Outgoing request must be FullHttpRequest.");
// For WHOIS, client certificate hash is always set to "none". // For WHOIS, client certificate hash is always set to "none".
// For EPP, the client hash attribute is set upon handshake completion, before the first HELLO // For EPP, the client hash attribute is set upon handshake completion, before the first HELLO

View file

@ -88,8 +88,7 @@ public class FrontendMetricsHandler extends ChannelDuplexHandler {
} }
@Override @Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
throws Exception {
// Only instrument request metrics when the response is actually sent to client. // Only instrument request metrics when the response is actually sent to client.
// It is OK to check the queue size preemptively here, not when the front element of the queue // It is OK to check the queue size preemptively here, not when the front element of the queue
// is acutally removed after the write to the client is successful, because responses are // is acutally removed after the write to the client is successful, because responses are

View file

@ -33,7 +33,7 @@ public class HealthCheckHandler extends ChannelInboundHandlerAdapter {
} }
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg; ByteBuf buf = (ByteBuf) msg;
if (buf.equals(checkRequest)) { if (buf.equals(checkRequest)) {
ChannelFuture unusedFuture = ctx.writeAndFlush(checkResponse); ChannelFuture unusedFuture = ctx.writeAndFlush(checkResponse);

View file

@ -125,8 +125,7 @@ public abstract class HttpsRelayServiceHandler extends ByteToMessageCodec<FullHt
} }
@Override @Override
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
throws Exception {
FullHttpRequest request = decodeFullHttpRequest(byteBuf); FullHttpRequest request = decodeFullHttpRequest(byteBuf);
loadCookies(request); loadCookies(request);
out.add(request); out.add(request);
@ -169,7 +168,7 @@ public abstract class HttpsRelayServiceHandler extends ByteToMessageCodec<FullHt
/** Terminates connection upon inbound exception. */ /** Terminates connection upon inbound exception. */
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (NON_FATAL_INBOUND_EXCEPTIONS.contains(Throwables.getRootCause(cause).getClass())) { if (NON_FATAL_INBOUND_EXCEPTIONS.contains(Throwables.getRootCause(cause).getClass())) {
logger.atWarning().withCause(cause).log( logger.atWarning().withCause(cause).log(
"Inbound exception caught for channel %s", ctx.channel()); "Inbound exception caught for channel %s", ctx.channel());

View file

@ -133,7 +133,7 @@ public class ProxyProtocolHandler extends ByteToMessageDecoder {
* then removed from the pipeline. * then removed from the pipeline.
*/ */
@Override @Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
// Wait until there are more bytes available than the header's length before processing. // Wait until there are more bytes available than the header's length before processing.
if (in.readableBytes() >= HEADER_PREFIX.length) { if (in.readableBytes() >= HEADER_PREFIX.length) {
if (containsHeader(in)) { if (containsHeader(in)) {

View file

@ -62,7 +62,7 @@ public class RelayHandler<I> extends SimpleChannelInboundHandler<I> {
/** Read message of type {@code I}, write it as-is into the relay channel. */ /** Read message of type {@code I}, write it as-is into the relay channel. */
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception { protected void channelRead0(ChannelHandlerContext ctx, I msg) {
Channel channel = ctx.channel(); Channel channel = ctx.channel();
Channel relayChannel = channel.attr(RELAY_CHANNEL_KEY).get(); Channel relayChannel = channel.attr(RELAY_CHANNEL_KEY).get();
if (relayChannel == null) { if (relayChannel == null) {

View file

@ -154,7 +154,7 @@ public abstract class ProtocolModuleTest {
new EmbeddedChannel( new EmbeddedChannel(
new ChannelInitializer<Channel>() { new ChannelInitializer<Channel>() {
@Override @Override
protected void initChannel(Channel ch) throws Exception { protected void initChannel(Channel ch) {
initializer.accept(ch); initializer.accept(ch);
} }
}); });

View file

@ -81,7 +81,7 @@ class BackendMetricsHandlerTest {
new EmbeddedChannel( new EmbeddedChannel(
new ChannelInitializer<EmbeddedChannel>() { new ChannelInitializer<EmbeddedChannel>() {
@Override @Override
protected void initChannel(EmbeddedChannel ch) throws Exception { protected void initChannel(EmbeddedChannel ch) {
ch.attr(PROTOCOL_KEY).set(backendProtocol); ch.attr(PROTOCOL_KEY).set(backendProtocol);
ch.attr(RELAY_CHANNEL_KEY).set(frontendChannel); ch.attr(RELAY_CHANNEL_KEY).set(frontendChannel);
ch.pipeline().addLast(handler); ch.pipeline().addLast(handler);

View file

@ -82,8 +82,8 @@ class EppServiceHandlerTest {
private EmbeddedChannel channel; private EmbeddedChannel channel;
private void setHandshakeSuccess(EmbeddedChannel channel, X509Certificate certificate) private void setHandshakeSuccess(EmbeddedChannel channel, X509Certificate certificate) {
throws Exception { @SuppressWarnings("unused")
Promise<X509Certificate> unusedPromise = Promise<X509Certificate> unusedPromise =
channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().setSuccess(certificate); channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().setSuccess(certificate);
} }
@ -92,7 +92,7 @@ class EppServiceHandlerTest {
setHandshakeSuccess(channel, clientCertificate); setHandshakeSuccess(channel, clientCertificate);
} }
private void setHandshakeFailure(EmbeddedChannel channel) throws Exception { private void setHandshakeFailure(EmbeddedChannel channel) {
Promise<X509Certificate> unusedPromise = Promise<X509Certificate> unusedPromise =
channel channel
.attr(CLIENT_CERTIFICATE_PROMISE_KEY) .attr(CLIENT_CERTIFICATE_PROMISE_KEY)
@ -135,12 +135,12 @@ class EppServiceHandlerTest {
channel = setUpNewChannel(eppServiceHandler); channel = setUpNewChannel(eppServiceHandler);
} }
private EmbeddedChannel setUpNewChannel(EppServiceHandler handler) throws Exception { private EmbeddedChannel setUpNewChannel(EppServiceHandler handler) {
return new EmbeddedChannel( return new EmbeddedChannel(
DefaultChannelId.newInstance(), DefaultChannelId.newInstance(),
new ChannelInitializer<EmbeddedChannel>() { new ChannelInitializer<EmbeddedChannel>() {
@Override @Override
protected void initChannel(EmbeddedChannel ch) throws Exception { protected void initChannel(EmbeddedChannel ch) {
ch.attr(REMOTE_ADDRESS_KEY).set(CLIENT_ADDRESS); ch.attr(REMOTE_ADDRESS_KEY).set(CLIENT_ADDRESS);
ch.attr(CLIENT_CERTIFICATE_PROMISE_KEY).set(ch.eventLoop().newPromise()); ch.attr(CLIENT_CERTIFICATE_PROMISE_KEY).set(ch.eventLoop().newPromise());
ch.pipeline().addLast(handler); ch.pipeline().addLast(handler);

View file

@ -61,7 +61,7 @@ class FrontendMetricsHandlerTest {
new EmbeddedChannel( new EmbeddedChannel(
new ChannelInitializer<EmbeddedChannel>() { new ChannelInitializer<EmbeddedChannel>() {
@Override @Override
protected void initChannel(EmbeddedChannel ch) throws Exception { protected void initChannel(EmbeddedChannel ch) {
ch.attr(PROTOCOL_KEY).set(frontendProtocol); ch.attr(PROTOCOL_KEY).set(frontendProtocol);
ch.attr(CLIENT_CERTIFICATE_HASH_KEY).set(CLIENT_CERT_HASH); ch.attr(CLIENT_CERTIFICATE_HASH_KEY).set(CLIENT_CERT_HASH);
ch.pipeline().addLast(handler); ch.pipeline().addLast(handler);

View file

@ -67,7 +67,7 @@ class QuotaManagerTest {
} }
@Test @Test
void testSuccess_rebate() throws Exception { void testSuccess_rebate() {
DateTime grantedTokenRefillTime = clock.nowUtc(); DateTime grantedTokenRefillTime = clock.nowUtc();
response = QuotaResponse.create(true, USER_ID, grantedTokenRefillTime); response = QuotaResponse.create(true, USER_ID, grantedTokenRefillTime);
QuotaRebate rebate = QuotaRebate.create(response); QuotaRebate rebate = QuotaRebate.create(response);