Skip to content

Commit

Permalink
Merge pull request dropwizard#4674 from rhowe/more-sonar-fixes
Browse files Browse the repository at this point in the history
Various linter fixes
  • Loading branch information
jplock authored Feb 2, 2022
2 parents 815765c + e31833f commit e47e0a5
Show file tree
Hide file tree
Showing 22 changed files with 80 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import java.util.Optional;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -36,7 +35,7 @@ public void run(Configuration configuration, Environment environment) { }
private ValidatorFactory validatorFactory;

@BeforeEach
void setUp() throws Exception {
void setUp() {
Bootstrap<Configuration> bootstrap = new Bootstrap<>(application);
application.initialize(bootstrap);

Expand All @@ -57,14 +56,10 @@ void shouldValidateNormally() {
// Run validation manually
Set<ConstraintViolation<Bean>> constraintViolations = validator.validate(new Bean(1));


assertThat(constraintViolations.size()).isEqualTo(1);

Optional<String> message = constraintViolations.stream()
.findFirst()
.map(ConstraintViolation::getMessage);

assertThat(message).hasValue("must be greater than or equal to 10");
assertThat(constraintViolations)
.singleElement()
.extracting(ConstraintViolation::getMessage)
.isEqualTo("must be greater than or equal to 10");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.codahale.metrics.health.HealthCheck;
import io.dropwizard.util.Duration;

import java.lang.InterruptedException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,19 +154,19 @@ void createDefaultFactory() throws Exception {
@Test
void metricsRecorded() throws Exception {
dataSource();
Map<String, Gauge> poolMetrics = metricRegistry.getGauges(MetricFilter.startsWith("io.dropwizard.db.ManagedPooledDataSource.test."));
assertThat(poolMetrics)
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.active")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.idle")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.waiting")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.size")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.created")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.borrowed")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.reconnected")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.released")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.releasedIdle")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.returned")
.containsKey("io.dropwizard.db.ManagedPooledDataSource.test.removeAbandoned");
assertThat(metricRegistry.getGauges(MetricFilter.startsWith("io.dropwizard.db.ManagedPooledDataSource.test.")))
.containsOnlyKeys(
"io.dropwizard.db.ManagedPooledDataSource.test.active",
"io.dropwizard.db.ManagedPooledDataSource.test.idle",
"io.dropwizard.db.ManagedPooledDataSource.test.waiting",
"io.dropwizard.db.ManagedPooledDataSource.test.size",
"io.dropwizard.db.ManagedPooledDataSource.test.created",
"io.dropwizard.db.ManagedPooledDataSource.test.borrowed",
"io.dropwizard.db.ManagedPooledDataSource.test.reconnected",
"io.dropwizard.db.ManagedPooledDataSource.test.released",
"io.dropwizard.db.ManagedPooledDataSource.test.releasedIdle",
"io.dropwizard.db.ManagedPooledDataSource.test.returned",
"io.dropwizard.db.ManagedPooledDataSource.test.removeAbandoned");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class BadLogApp extends Application<Configuration> {
private static final Logger LOGGER = LoggerFactory.getLogger(BadLogApp.class);

@Override
protected void onFatalError() {
protected void onFatalError(Throwable t) {
LOGGER.warn("Mayday we're going down");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ void noDateParameter() {
final String date = APP.client().target("http://localhost:" + APP.getLocalPort() + "/hello-world/date")
.request()
.get(String.class);
assertThat(date).isEqualTo("");
assertThat(date).isEmpty();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ void noDateParameter() {
final String date = APP.client().target("http://localhost:" + APP.getLocalPort() + "/hello-world/date")
.request()
.get(String.class);
assertThat(date).isEqualTo("");
assertThat(date).isEmpty();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ public HealthCheckManager(final List<HealthCheckConfiguration> configs,

this.aggregateHealthyName = MetricRegistry.name("health", "aggregate", "healthy");
this.aggregateUnhealthyName = MetricRegistry.name("health", "aggregate", "unhealthy");
metrics.register(aggregateHealthyName, (Gauge) this::calculateNumberOfHealthyChecks);
metrics.register(aggregateUnhealthyName, (Gauge) this::calculateNumberOfUnhealthyChecks);
metrics.register(aggregateHealthyName, (Gauge<Long>) this::calculateNumberOfHealthyChecks);
metrics.register(aggregateUnhealthyName, (Gauge<Long>) this::calculateNumberOfUnhealthyChecks);
}

// visible for testing
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ private Set<String> getNamesFromQueryParams(final Map<String, Collection<String>
private Collection<HealthStateView> getViews(final Map<String, Collection<String>> queryParams) {
final Set<String> names = getNamesFromQueryParams(queryParams);

final Collection<HealthStateView> views;
if (shouldReturnAllViews(names)) {
return unmodifiableList(new ArrayList<>(healthStateAggregator.healthStateViews()));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hibernate.resource.transaction.spi.TransactionStatus.ACTIVE;
import static org.hibernate.resource.transaction.spi.TransactionStatus.NOT_ACTIVE;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,10 @@ protected DeploymentContext configureDeployment() {
}

private int getResponseStatusForRequestMethod(String method, boolean includeEntity) {
final Response resourceResponse = includeEntity
? target("/ping").request().method(method, Entity.entity("", MediaType.TEXT_PLAIN))
: target("/ping").request().method(method);

try {
try (Response resourceResponse = includeEntity
? target("/ping").request().method(method, Entity.entity("", MediaType.TEXT_PLAIN))
: target("/ping").request().method(method)) {
return resourceResponse.getStatus();
} finally {
resourceResponse.close();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import java.util.OptionalDouble;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import java.time.format.DateTimeFormatter;
import java.util.Collection;

import static org.assertj.core.api.Assertions.as;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

Expand Down Expand Up @@ -344,7 +343,7 @@ void validSetTotalSizeCap() throws IOException, ConfigurationException, NoSuchFi

final FileAppender appender = factory.build(new ResourceConfigurationSourceProvider(), "yaml/appender_file_cap.yaml")
.buildAppender(new LoggerContext());
assertThat(appender).isInstanceOfSatisfying(RollingFileAppender.class, roller -> {
assertThat(appender).isInstanceOfSatisfying(RollingFileAppender.class, roller ->
assertThat(roller.getRollingPolicy()).isInstanceOfSatisfying(SizeAndTimeBasedRollingPolicy.class, policy -> {
try {
assertThat(totalSizeCap.get(policy))
Expand All @@ -359,8 +358,8 @@ void validSetTotalSizeCap() throws IOException, ConfigurationException, NoSuchFi
} catch (IllegalAccessException e) {
throw new RuntimeException("Unexpected illegal access", e);
}
});
});
})
);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ void testNoAddressResolutionForGraphite() throws Exception {
verify(builderSpy).build(argument.capture());

final Graphite graphite = argument.getValue();
assertThat(getField(graphite, "hostname")).isEqualTo("localhost");
assertThat(getField(graphite, "port")).isEqualTo(2003);
assertThat(getField(graphite, "address")).isNull();
final FieldAccessor<Graphite> graphiteFieldAccessor = new FieldAccessor<>(graphite);
assertThat(graphiteFieldAccessor.getField("hostname")).isEqualTo("localhost");
assertThat(graphiteFieldAccessor.getField("port")).isEqualTo(2003);
assertThat(graphiteFieldAccessor.getField("address")).isNull();
}

@Test
Expand All @@ -64,30 +65,23 @@ void testCorrectTransportForGraphiteUDP() throws Exception {
verify(builderSpy).build(argument.capture());

final GraphiteUDP graphite = argument.getValue();
assertThat(getField(graphite, "hostname")).isEqualTo("localhost");
assertThat(getField(graphite, "port")).isEqualTo(2003);
assertThat(getField(graphite, "address")).isNull();
final FieldAccessor<GraphiteUDP> graphiteUDPFieldAccessor = new FieldAccessor<>(graphite);
assertThat(graphiteUDPFieldAccessor.getField("hostname")).isEqualTo("localhost");
assertThat(graphiteUDPFieldAccessor.getField("port")).isEqualTo(2003);
assertThat(graphiteUDPFieldAccessor.getField("address")).isNull();
}

private static Object getField(GraphiteUDP graphite, String name) throws NoSuchFieldException {
try {
return getInaccessibleField(GraphiteUDP.class, name).get(graphite);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private static class FieldAccessor<T> {
T obj;

private static Object getField(Graphite graphite, String name) throws NoSuchFieldException {
try {
return getInaccessibleField(Graphite.class, name).get(graphite);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
FieldAccessor(T obj) {
this.obj = obj;
}
}

private static Field getInaccessibleField(Class klass, String name) throws NoSuchFieldException {
Field field = klass.getDeclaredField(name);
field.setAccessible(true);
return field;
Object getField(String name) throws IllegalAccessException, NoSuchFieldException {
Field field = obj.getClass().getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ private void stopIfRequired() {
try {
jettyServer.stop();
} catch (RuntimeException e) {
throw (RuntimeException) e;
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static String resourceFilePath(final String resourceClassPathLocation) {
try {
return new File(Resources.getResource(resourceClassPathLocation).toURI()).getAbsolutePath();
} catch (RuntimeException e) {
throw (RuntimeException) e;
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public void testDefaultVaryHeader() {
final Response clientResponse = RULE.client().target(
"http://localhost:" + RULE.getLocalPort() + "/test").request().header(ACCEPT_ENCODING, "gzip").get();

assertThat(clientResponse.getHeaders().get(VARY)).isEqualTo(Collections.singletonList((Object) ACCEPT_ENCODING));
assertThat(clientResponse.getHeaders().get(CONTENT_ENCODING)).isEqualTo(Collections.singletonList((Object) "gzip"));
assertThat(clientResponse.getHeaders())
.containsEntry(VARY, Collections.singletonList(ACCEPT_ENCODING))
.containsEntry(CONTENT_ENCODING, Collections.singletonList("gzip"));
}
}
17 changes: 8 additions & 9 deletions dropwizard-util/src/test/java/io/dropwizard/util/MapsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ class MapsTest {

@Test
void of2KeyValuePairs() {
final Map map = Maps.of(1, 60, 2, 61);
final HashMap hashMap = new HashMap();
final Map<Integer,Integer> map = Maps.of(1, 60, 2, 61);
final HashMap<Integer,Integer> hashMap = new HashMap<>();
hashMap.put(1, 60);
hashMap.put(2, 61);

Expand All @@ -21,8 +21,8 @@ void of2KeyValuePairs() {

@Test
void of3KeyValuePairs() {
final Map map = Maps.of(1, 60, 2, 61, 3, 62);
final HashMap hashMap = new HashMap();
final Map<Integer,Integer> map = Maps.of(1, 60, 2, 61, 3, 62);
final HashMap<Integer,Integer> hashMap = new HashMap<>();
hashMap.put(1, 60);
hashMap.put(2, 61);
hashMap.put(3, 62);
Expand All @@ -32,8 +32,8 @@ void of3KeyValuePairs() {

@Test
void of4KeyValuePairs() {
final Map map = Maps.of(1, 60, 2, 61, 3, 62, 4, 63);
final HashMap hashMap = new HashMap();
final Map<Integer,Integer> map = Maps.of(1, 60, 2, 61, 3, 62, 4, 63);
final HashMap<Integer,Integer> hashMap = new HashMap<>();
hashMap.put(1, 60);
hashMap.put(2, 61);
hashMap.put(3, 62);
Expand All @@ -44,8 +44,8 @@ void of4KeyValuePairs() {

@Test
void of5KeyValuePairs() {
final Map map = Maps.of(1, 60, 2, 61, 3, 62, 4, 63, 5, 64);
final HashMap hashMap = new HashMap();
final Map<Integer,Integer> map = Maps.of(1, 60, 2, 61, 3, 62, 4, 63, 5, 64);
final HashMap<Integer,Integer> hashMap = new HashMap<>();
hashMap.put(1, 60);
hashMap.put(2, 61);
hashMap.put(3, 62);
Expand All @@ -54,5 +54,4 @@ void of5KeyValuePairs() {

assertThat(map).isEqualTo(hashMap);
}

}
16 changes: 8 additions & 8 deletions dropwizard-util/src/test/java/io/dropwizard/util/SetsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,30 @@ class SetsTest {

@Test
void of2Elements() {
final Set set = Sets.of(1, 2);
final Set<Integer> set = Sets.of(1, 2);

assertThat(set).isEqualTo(new HashSet(Arrays.asList(1, 2)));
assertThat(set).isEqualTo(new HashSet<>(Arrays.asList(1, 2)));
}

@Test
void of3Elements() {
final Set set = Sets.of(1, 2, 1);
final Set<Integer> set = Sets.of(1, 2, 1);

assertThat(set).isEqualTo(new HashSet(Arrays.asList(1, 2)));
assertThat(set).isEqualTo(new HashSet<>(Arrays.asList(1, 2)));
}

@Test
void of4Elements() {
final Set set = Sets.of(1, 2, 1, 1);
final Set<Integer> set = Sets.of(1, 2, 1, 1);

assertThat(set).isEqualTo(new HashSet(Arrays.asList(1, 2)));
assertThat(set).isEqualTo(new HashSet<>(Arrays.asList(1, 2)));
}

@Test
void of5Elements() {
final Set set = Sets.of(1, 1, 2, 3, 3);
final Set<Integer> set = Sets.of(1, 1, 2, 3, 3);

assertThat(set).isEqualTo(new HashSet(Arrays.asList(1, 2, 3)));
assertThat(set).isEqualTo(new HashSet<>(Arrays.asList(1, 2, 3)));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,8 @@
@OverridesAttribute(constraint = MaxDataSize.class, name = "value")
long max() default Long.MAX_VALUE;

@OverridesAttribute.List({
@OverridesAttribute(constraint = MinDataSize.class, name = "unit"),
@OverridesAttribute(constraint = MaxDataSize.class, name = "unit")
})
@OverridesAttribute(constraint = MinDataSize.class, name = "unit")
@OverridesAttribute(constraint = MaxDataSize.class, name = "unit")
DataSizeUnit unit() default DataSizeUnit.BYTES;

String message() default "must be between {min} {unit} and {max} {unit}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,8 @@
@OverridesAttribute(constraint = MaxDuration.class, name = "value")
long max() default Long.MAX_VALUE;

@OverridesAttribute.List({
@OverridesAttribute(constraint = MinDuration.class, name = "unit"),
@OverridesAttribute(constraint = MaxDuration.class, name = "unit")
})
@OverridesAttribute(constraint = MinDuration.class, name = "unit")
@OverridesAttribute(constraint = MaxDuration.class, name = "unit")
TimeUnit unit() default TimeUnit.SECONDS;

String message() default "must be between {min} {unit} and {max} {unit}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,8 @@
@OverridesAttribute(constraint = MaxSize.class, name = "value")
long max() default Long.MAX_VALUE;

@OverridesAttribute.List({
@OverridesAttribute(constraint = MinSize.class, name = "unit"),
@OverridesAttribute(constraint = MaxSize.class, name = "unit")
})
@OverridesAttribute(constraint = MinSize.class, name = "unit")
@OverridesAttribute(constraint = MaxSize.class, name = "unit")
SizeUnit unit() default SizeUnit.BYTES;

String message() default "must be between {min} {unit} and {max} {unit}";
Expand Down
Loading

0 comments on commit e47e0a5

Please sign in to comment.