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. */
SUCCESS,
/** 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();

View file

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

View file

@ -337,7 +337,7 @@ public class DomainContent extends EppResource
@PostLoad
@SuppressWarnings("UnusedMethod")
private final void postLoad() {
private void postLoad() {
// Reconstitute the contact list.
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}. */
public void export(ImmutableList<Class> entityClasses, File outputFile) {
public void export(ImmutableList<Class<?>> entityClasses, File outputFile) {
// Configure Hibernate settings.
Map<String, String> settings = Maps.newHashMap();
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()
.filter(AttributeConverter.class::isAssignableFrom)
.collect(toImmutableList());

View file

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

View file

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

View file

@ -49,7 +49,7 @@ public interface JpaTransactionManager extends TransactionManager {
void transactNoRetry(Runnable work);
/** 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.

View file

@ -165,7 +165,7 @@ public class Transaction extends ImmutableObject implements Buildable {
enum Type {
UPDATE,
DELETE
};
}
/** Write the changes in the mutation to the datastore. */
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
* assigned their personal credentials.
*/
TOOL;
TOOL
}
/** 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.OutputStream;
import javax.inject.Inject;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
@ -79,12 +78,12 @@ public final class BrdaCopyAction implements Runnable {
public void run() {
try {
copyAsRyde();
} catch (IOException | PGPException e) {
} catch (IOException 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);
GcsFilename xmlFilename = new GcsFilename(stagingBucket, prefix + ".xml.ghostryde");
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.OutputStream;
import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.joda.time.DateTime;
@ -118,11 +117,8 @@ public final class Ghostryde {
static final String INNER_FILENAME = "file.xml";
static final DateTime INNER_MODIFICATION_TIME = DateTime.parse("2000-01-01TZ");
/**
* Creates a ghostryde file from an in-memory byte array.
*/
public static byte[] encode(byte[] data, PGPPublicKey key)
throws IOException, PGPException {
/** Creates a ghostryde file from an in-memory byte array. */
public static byte[] encode(byte[] data, PGPPublicKey key) throws IOException {
checkNotNull(data, "data");
checkArgument(key.isEncryptionKey(), "not an encryption key");
ByteArrayOutputStream output = new ByteArrayOutputStream();
@ -132,11 +128,8 @@ public final class Ghostryde {
return output.toByteArray();
}
/**
* Deciphers a ghostryde file from an in-memory byte array.
*/
public static byte[] decode(byte[] data, PGPPrivateKey key)
throws IOException, PGPException {
/** Deciphers a ghostryde file from an in-memory byte array. */
public static byte[] decode(byte[] data, PGPPrivateKey key) throws IOException {
checkNotNull(data, "data");
ByteArrayInputStream dataStream = new ByteArrayInputStream(data);
ByteArrayOutputStream output = new ByteArrayOutputStream();

View file

@ -42,7 +42,6 @@ import google.registry.request.auth.Auth;
import java.io.IOException;
import java.io.InputStream;
import javax.inject.Inject;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.joda.time.DateTime;
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. */
private byte[] readReportFromGcs(GcsFilename reportFilename) throws IOException, PGPException {
private byte[] readReportFromGcs(GcsFilename reportFilename) throws IOException {
try (InputStream gcsInput = gcsUtils.openInputStream(reportFilename);
InputStream ghostrydeDecoder = Ghostryde.decoder(gcsInput, stagingDecryptionKey)) {
return ByteStreams.toByteArray(ghostrydeDecoder);

View file

@ -74,9 +74,8 @@ public final class RydeEncoder extends FilterOutputStream {
OutputStream kompressor = closer.register(openCompressor(encryptLayer));
OutputStream fileLayer =
closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified));
OutputStream tarLayer =
this.out =
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();
}
public void prepareForQuery(YearMonth yearMonth) throws Exception {
public void prepareForQuery(YearMonth yearMonth) throws InterruptedException {
dnsCountQueryCoordinator.prepareForQuery(yearMonth);
}
}

View file

@ -35,5 +35,5 @@ public class BasicDnsCountQueryCoordinator implements DnsCountQueryCoordinator {
}
@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.
*
* 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 {
public BigqueryConnection bigquery;
@ -49,6 +49,12 @@ public interface DnsCountQueryCoordinator {
/** Creates the string used to query bigtable for DNS count information. */
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(
"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));
checkArgument(version == 1, String.format(
"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.
*/
private static void logFetchedBytes(String sourceUrl, byte[] bytes) throws IOException {
private static void logFetchedBytes(String sourceUrl, byte[] bytes) {
logger.atInfo().log(
"Fetched contents of %s -- Size: %d bytes; first %d chars:\n\n%s%s",
sourceUrl,

View file

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

View file

@ -52,7 +52,7 @@ final class BigqueryParameters {
private int bigqueryNumThreads = DEFAULT_NUM_THREADS;
/** 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
.setExecutorService(Executors.newFixedThreadPool(bigqueryNumThreads))
.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. */
protected boolean checkExecutionState() throws Exception {
protected boolean checkExecutionState() {
return true;
}

View file

@ -31,7 +31,7 @@ public class GetPremiumListCommand implements CommandWithRemoteApi {
private List<String> mainParameters;
@Override
public void run() throws Exception {
public void run() {
for (String premiumListName : mainParameters) {
if (PremiumListDualDao.exists(premiumListName)) {
System.out.printf(
@ -42,7 +42,7 @@ public class GetPremiumListCommand implements CommandWithRemoteApi {
.map(PremiumListEntry::toString)
.collect(Collectors.joining("\n")));
} 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);
Object entity = ofy().load().key(untypedKey).now();
if (entity == null) {
System.err.println(
String.format(
"Entity %s read from %s doesn't exist in Datastore! Skipping.",
untypedKey,
keyPathsFile == null ? "STDIN" : "File " + keyPathsFile.getAbsolutePath()));
System.err.printf(
"Entity %s read from %s doesn't exist in Datastore! Skipping.%n",
untypedKey, keyPathsFile == null ? "STDIN" : "File " + keyPathsFile.getAbsolutePath());
continue;
}
Class<T> clazz = new TypeInstantiator<T>(getClass()) {}.getExactType();

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -55,7 +55,7 @@ public abstract class EntityTestCase {
*/
ENABLED,
/** The test is not relevant for JPA coverage checks. */
DISABLED;
DISABLED
}
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.persistence.transaction.TransactionManagerFactory.jpaTm;
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.newContactResourceWithRoid;
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.eppcommon.Trid;
import google.registry.model.host.HostResource;
import google.registry.model.registrar.Registrar;
import google.registry.model.registry.Registries;
import google.registry.model.registry.Registry;
import google.registry.model.reporting.DomainTransactionRecord;
@ -144,13 +144,9 @@ public class DomainHistoryTest extends EntityTestCase {
.transact(
() -> {
jpaTm().insert(registry);
Registrar registrar =
appEngine
.makeRegistrar2()
.asBuilder()
.setAllowedTlds(ImmutableSet.of("tld"))
.build();
jpaTm().insert(registrar);
jpaTm()
.insert(
makeRegistrar2().asBuilder().setAllowedTlds(ImmutableSet.of("tld")).build());
});
HostResource host = newHostResourceWithRoid("ns1.example.com", "host1");

View file

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

View file

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

View file

@ -35,7 +35,7 @@ import org.junit.jupiter.api.BeforeEach;
/** Unit tests for {@link Spec11ThreatMatchDao}. */
@DualDatabaseTest
public class Spec11ThreatMatchDaoTest extends EntityTestCase {
class Spec11ThreatMatchDaoTest extends EntityTestCase {
private static final LocalDate TODAY = new LocalDate(2020, 8, 4);
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}. */
@DualDatabaseTest
public class Spec11ThreatMatchTest extends EntityTestCase {
public final class Spec11ThreatMatchTest extends EntityTestCase {
private static final String REGISTRAR_ID = "registrar";
private static final LocalDate DATE = LocalDate.parse("2020-06-10", ISODateTimeFormat.date());

View file

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

View file

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

View file

@ -55,11 +55,9 @@ public class LocalDateConverterTest {
private LocalDateConverterTestEntity persistAndLoadTestEntity(LocalDate date) {
LocalDateConverterTestEntity entity = new LocalDateConverterTestEntity(date);
jpaTm().transact(() -> jpaTm().insert(entity));
LocalDateConverterTestEntity retrievedEntity =
jpaTm()
return jpaTm()
.transact(
() -> jpaTm().loadByKey(VKey.createSql(LocalDateConverterTestEntity.class, "id")));
return retrievedEntity;
}
/** 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");
private static final ImmutableSet<Class> ALL_JPA_ENTITIES =
private static final ImmutableSet<Class<?>> ALL_JPA_ENTITIES =
PersistenceXmlUtility.getManagedClasses().stream()
.filter(e -> !IGNORE_ENTITIES.contains(e.getSimpleName()))
.filter(e -> e.isAnnotationPresent(Entity.class))
.filter(e -> !e.isAnnotationPresent(DiscriminatorValue.class))
.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.
private static final Map<String, Boolean> testsJpaEntities = Maps.newHashMap();
@ -81,7 +81,7 @@ public class JpaEntityCoverageExtension implements BeforeEachCallback, AfterEach
testsJpaEntities.clear();
}
public static Set<Class> getUncoveredEntities() {
public static Set<Class<?>> getUncoveredEntities() {
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
*/
private static boolean isPersisted(Class entityType) {
private static boolean isPersisted(Class<?> entityType) {
try {
List result =
List<?> result =
jpaTm()
.transact(
() ->

View file

@ -49,7 +49,7 @@ public class JpaTestRules {
public static class JpaIntegrationTestExtension extends JpaTransactionManagerExtension {
private JpaIntegrationTestExtension(
Clock clock,
ImmutableList<Class> extraEntityClasses,
ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) {
super(clock, Optional.of(GOLDEN_SCHEMA_SQL_PATH), extraEntityClasses, userProperties);
}
@ -63,7 +63,7 @@ public class JpaTestRules {
private JpaUnitTestExtension(
Clock clock,
Optional<String> initScriptPath,
ImmutableList<Class> extraEntityClasses,
ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) {
super(clock, initScriptPath, false, extraEntityClasses, userProperties);
}
@ -105,8 +105,8 @@ public class JpaTestRules {
private String initScript;
private Clock clock;
private List<Class> extraEntityClasses = new ArrayList<Class>();
private Map<String, String> userProperties = new HashMap<String, String>();
private List<Class<?>> extraEntityClasses = new ArrayList<>();
private Map<String, String> userProperties = new HashMap<>();
/**
* 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. */
public Builder withEntityClass(Class... classes) {
public Builder withEntityClass(Class<?>... classes) {
this.extraEntityClasses.addAll(ImmutableSet.copyOf(classes));
return this;
}

View file

@ -87,8 +87,8 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
private final Clock clock;
private final Optional<String> initScriptPath;
private final ImmutableList<Class> extraEntityClasses;
private final ImmutableMap userProperties;
private final ImmutableList<Class<?>> extraEntityClasses;
private final ImmutableMap<String, String> userProperties;
private static final JdbcDatabaseContainer database = create();
private static final HibernateSchemaExporter exporter =
@ -102,7 +102,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
private JpaTransactionManager cachedTm;
// 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
// false.
@ -112,7 +112,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
Clock clock,
Optional<String> initScriptPath,
boolean includeNomulusSchema,
ImmutableList<Class> extraEntityClasses,
ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) {
this.clock = clock;
this.initScriptPath = initScriptPath;
@ -125,7 +125,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
JpaTransactionManagerExtension(
Clock clock,
Optional<String> initScriptPath,
ImmutableList<Class> extraEntityClasses,
ImmutableList<Class<?>> extraEntityClasses,
ImmutableMap<String, String> userProperties) {
this.clock = clock;
this.initScriptPath = initScriptPath;
@ -143,7 +143,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
}
private static int getOrmEntityHash(
Optional<String> initScriptPath, ImmutableList<Class> extraEntityClasses) {
Optional<String> initScriptPath, ImmutableList<Class<?>> extraEntityClasses) {
return Streams.concat(
Stream.of(initScriptPath.orElse("")),
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));
}
ImmutableMap properties = PersistenceModule.provideDefaultDatabaseConfigs();
ImmutableMap<String, String> properties = PersistenceModule.provideDefaultDatabaseConfigs();
if (!userProperties.isEmpty()) {
// If there are user properties, create a new properties object with these added.
Map<String, String> mergedProperties = Maps.newHashMap();
@ -338,7 +338,7 @@ abstract class JpaTransactionManagerExtension implements BeforeEachCallback, Aft
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
// transaction replication mechanism.
return Stream.concat(extraEntityClasses.stream(), Stream.of(TransactionEntity.class))

View file

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

View file

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

View file

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

View file

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

View file

@ -154,8 +154,7 @@ public class LockDaoTest {
assertAboutLogs()
.that(logHandler)
.hasLogAtLevelWithMessage(
Level.WARNING,
String.format("Cloud SQL lock for testResource with tld GLOBAL should be null"));
Level.WARNING, "Cloud SQL lock for testResource with tld GLOBAL should be null");
}
@Test
@ -171,22 +170,19 @@ public class LockDaoTest {
.that(logHandler)
.hasLogAtLevelWithMessage(
Level.WARNING,
String.format(
"Datastore lock requestLogId of wrong does not equal Cloud SQL lock requestLogId"
+ " of testLogId"));
+ " of testLogId");
assertAboutLogs()
.that(logHandler)
.hasLogAtLevelWithMessage(
Level.WARNING,
String.format(
"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()
.that(logHandler)
.hasLogAtLevelWithMessage(
Level.WARNING,
String.format(
"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);
} else if (withJpaUnitTest) {
jpaUnitTestRule =
builder
.withEntityClass(jpaTestEntities.toArray(new Class[jpaTestEntities.size()]))
.buildUnitTestRule();
builder.withEntityClass(jpaTestEntities.toArray(new Class[0])).buildUnitTestRule();
jpaUnitTestRule.beforeEach(context);
} else {
jpaIntegrationTestRule = builder.buildIntegrationTestRule();

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -16,7 +16,6 @@ package google.registry.documentation;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.util.BuildPathUtils.getProjectRoot;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Joiner;
import java.nio.file.Files;
@ -41,9 +40,7 @@ class FlowDocumentationTest {
@Test
void testGeneratedMatchesGolden() throws Exception {
// Read the markdown file.
Path goldenMarkdownPath = GOLDEN_MARKDOWN_FILEPATH;
String goldenMarkdown = new String(Files.readAllBytes(goldenMarkdownPath), UTF_8);
String goldenMarkdown = Files.readString(GOLDEN_MARKDOWN_FILEPATH);
// Don't use Truth's isEqualTo() because the output is huge and unreadable for large files.
DocumentationGenerator generator = new DocumentationGenerator();

View file

@ -101,7 +101,7 @@ public final class NettyExtension implements AfterEachCallback {
ChannelInitializer<LocalChannel> clientInitializer =
new ChannelInitializer<LocalChannel>() {
@Override
protected void initChannel(LocalChannel ch) throws Exception {
protected void initChannel(LocalChannel ch) {
// Add the given handler
ch.pipeline().addLast(handler);
// Add the "dumpHandler" last to log the incoming message
@ -178,7 +178,7 @@ public final class NettyExtension implements AfterEachCallback {
}
@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.
assertThat(msg).isInstanceOf(ByteBuf.class);
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. */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ChannelFuture unusedFuture =
ctx.channel().closeFuture().addListener(f -> requestFuture.completeExceptionally(cause));
}
@ -205,7 +205,7 @@ public final class NettyExtension implements AfterEachCallback {
}
@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.
assertThat(msg).isInstanceOf(ByteBuf.class);
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. */
@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));
}
}

View file

@ -270,7 +270,7 @@ public abstract class ProbingAction implements Callable<ChannelFuture> {
.handler(
new ChannelInitializer<Channel>() {
@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.
for (Provider<? extends ChannelHandler> handlerProvider :
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(namespaceURI), "namespaceURI");
if (nsPrefixMap.containsKey(prefix)) {

View file

@ -84,7 +84,7 @@ public class ProxyServer implements Runnable {
*/
private static class ServerChannelInitializer extends ChannelInitializer<NioSocketChannel> {
@Override
protected void initChannel(NioSocketChannel inboundChannel) throws Exception {
protected void initChannel(NioSocketChannel inboundChannel) {
// Add inbound channel handlers.
FrontendProtocol inboundProtocol =
(FrontendProtocol) inboundChannel.parent().attr(PROTOCOL_KEY).get();
@ -110,8 +110,7 @@ public class ProxyServer implements Runnable {
.handler(
new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel outboundChannel)
throws Exception {
protected void initChannel(NioSocketChannel outboundChannel) {
addHandlers(
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,
// which is what Flogger uses under the hood.
InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE);

View file

@ -102,8 +102,7 @@ public class BackendMetricsHandler extends ChannelDuplexHandler {
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
checkArgument(msg instanceof FullHttpRequest, "Outgoing request must be FullHttpRequest.");
// 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

View file

@ -88,8 +88,7 @@ public class FrontendMetricsHandler extends ChannelDuplexHandler {
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
// 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
// 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
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg;
if (buf.equals(checkRequest)) {
ChannelFuture unusedFuture = ctx.writeAndFlush(checkResponse);

View file

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

View file

@ -133,7 +133,7 @@ public class ProxyProtocolHandler extends ByteToMessageDecoder {
* then removed from the pipeline.
*/
@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.
if (in.readableBytes() >= HEADER_PREFIX.length) {
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. */
@Override
protected void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception {
protected void channelRead0(ChannelHandlerContext ctx, I msg) {
Channel channel = ctx.channel();
Channel relayChannel = channel.attr(RELAY_CHANNEL_KEY).get();
if (relayChannel == null) {

View file

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

View file

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

View file

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

View file

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

View file

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