Skip to content

Commit

Permalink
Fix various Error Prone compiler warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
joschi committed Mar 9, 2018
1 parent 133c900 commit fba9bb9
Show file tree
Hide file tree
Showing 21 changed files with 88 additions and 119 deletions.
3 changes: 2 additions & 1 deletion dropwizard-configuration/pom.xml
Expand Up @@ -53,7 +53,8 @@
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<!-- Required for tests related to environment variables --> <!-- Required for tests related to environment variables -->
<configuration> <configuration>
<forkMode>always</forkMode> <forkCount>1</forkCount>
<reuseForks>false</reuseForks>
<environmentVariables> <environmentVariables>
<TEST>test_value</TEST> <TEST>test_value</TEST>
<TEST_SUFFIX>2</TEST_SUFFIX> <TEST_SUFFIX>2</TEST_SUFFIX>
Expand Down
@@ -1,19 +1,5 @@
package io.dropwizard.configuration; package io.dropwizard.configuration;


import static java.util.Objects.requireNonNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.annotation.Nullable;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
Expand All @@ -29,6 +15,20 @@
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;


import javax.annotation.Nullable;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.Objects.requireNonNull;

/** /**
* A generic factory class for loading configuration files, binding them to configuration objects, and * A generic factory class for loading configuration files, binding them to configuration objects, and
* validating their constraints. Allows for overriding configuration parameters from system properties. * validating their constraints. Allows for overriding configuration parameters from system properties.
Expand Down Expand Up @@ -104,9 +104,11 @@ protected JsonParser createParser(InputStream input) throws IOException {
@Override @Override
public T build() throws IOException, ConfigurationException { public T build() throws IOException, ConfigurationException {
try { try {
final JsonNode node = mapper.valueToTree(klass.newInstance()); final T instance = klass.getDeclaredConstructor().newInstance();
final JsonNode node = mapper.valueToTree(instance);
return build(node, "default configuration"); return build(node, "default configuration");
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | SecurityException e) { } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | SecurityException
| NoSuchMethodException | InvocationTargetException e) {
throw new IllegalArgumentException("Unable create an instance " + throw new IllegalArgumentException("Unable create an instance " +
"of the configuration class: '" + klass.getCanonicalName() + "'", e); "of the configuration class: '" + klass.getCanonicalName() + "'", e);
} }
Expand Down
Expand Up @@ -12,7 +12,7 @@


/** /**
* A delegating {@link ConfigurationSourceProvider} which replaces variables in the underlying configuration * A delegating {@link ConfigurationSourceProvider} which replaces variables in the underlying configuration
* source according to the rules of a custom {@link org.apache.commons.lang3.text.StrSubstitutor}. * source according to the rules of a custom {@link org.apache.commons.text.StrSubstitutor}.
*/ */
public class SubstitutingSourceProvider implements ConfigurationSourceProvider { public class SubstitutingSourceProvider implements ConfigurationSourceProvider {
private final ConfigurationSourceProvider delegate; private final ConfigurationSourceProvider delegate;
Expand Down
@@ -1,16 +1,14 @@
package io.dropwizard.configuration; package io.dropwizard.configuration;


import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.jackson.Jackson;
import org.junit.Test;


import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;


import org.junit.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.dropwizard.jackson.Jackson;


public class JsonConfigurationFactoryTest extends BaseConfigurationFactoryTest { public class JsonConfigurationFactoryTest extends BaseConfigurationFactoryTest {


Expand All @@ -28,50 +26,38 @@ public void setUp() throws Exception {
this.wrongTypeFile = resourceFileName("factory-test-wrong-type.json"); this.wrongTypeFile = resourceFileName("factory-test-wrong-type.json");
this.malformedAdvancedFile = resourceFileName("factory-test-malformed-advanced.json"); this.malformedAdvancedFile = resourceFileName("factory-test-malformed-advanced.json");
} }

@Override @Override
public void throwsAnExceptionOnMalformedFiles() throws Exception { public void throwsAnExceptionOnMalformedFiles() {
try { assertThatThrownBy(super::throwsAnExceptionOnMalformedFiles)
super.throwsAnExceptionOnMalformedFiles(); .hasMessageContaining("* Malformed JSON at line:");
} catch (ConfigurationParsingException e) {
assertThat(e)
.hasMessageContaining("* Malformed JSON at line:");
}
} }


@Override @Override
public void printsDetailedInformationOnMalformedContent() throws Exception { public void printsDetailedInformationOnMalformedContent() {
try { assertThatThrownBy(super::printsDetailedInformationOnMalformedContent)
super.printsDetailedInformationOnMalformedContent(); .isInstanceOf(ConfigurationParsingException.class)
} catch (ConfigurationParsingException e) { .hasMessageContaining(String.format(
assertThat(e) "%s has an error:%n" +
.hasMessageContaining(String.format( " * Malformed JSON at line: 7, column: 3; Unexpected close marker '}': expected ']'",
"%s has an error:%n" + malformedAdvancedFile.getName()));
" * Malformed JSON at line: 7, column: 3; Unexpected close marker '}': expected ']'",
malformedAdvancedFile.getName()));
}
} }


@Test(expected = ConfigurationParsingException.class) @Test
public void defaultJsonFactoryFailsOnComment() throws IOException, ConfigurationException { public void defaultJsonFactoryFailsOnComment() {
try { assertThatThrownBy(() -> factory.build(commentFile))
factory.build(commentFile);
} catch (ConfigurationParsingException e) {
assertThat(e)
.hasMessageContaining(String.format( .hasMessageContaining(String.format(
"%s has an error:%n" + "%s has an error:%n" +
" * Malformed JSON at line: 4, column: 4; Unexpected character ('/' (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)", " * Malformed JSON at line: 4, column: 4; Unexpected character ('/' (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)",
commentFile.getName())); commentFile.getName()));
throw e;
}
} }

@Test @Test
public void configuredMapperAllowsComment() throws IOException, ConfigurationException { public void configuredMapperAllowsComment() throws IOException, ConfigurationException {
ObjectMapper mapper = Jackson ObjectMapper mapper = Jackson
.newObjectMapper() .newObjectMapper()
.configure(Feature.ALLOW_COMMENTS, true); .configure(Feature.ALLOW_COMMENTS, true);

JsonConfigurationFactory<Example> factory = new JsonConfigurationFactory<>(Example.class, validator, mapper, "dw"); JsonConfigurationFactory<Example> factory = new JsonConfigurationFactory<>(Example.class, validator, mapper, "dw");
factory.build(commentFile); factory.build(commentFile);
} }
Expand Down
@@ -1,9 +1,9 @@
package io.dropwizard.configuration; package io.dropwizard.configuration;


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

import io.dropwizard.jackson.Jackson; import io.dropwizard.jackson.Jackson;


import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class YamlConfigurationFactoryTest extends BaseConfigurationFactoryTest { public class YamlConfigurationFactoryTest extends BaseConfigurationFactoryTest {


@Override @Override
Expand All @@ -19,30 +19,23 @@ public void setUp() throws Exception {
} }


@Override @Override
public void throwsAnExceptionOnMalformedFiles() throws Exception { public void throwsAnExceptionOnMalformedFiles() {
try { assertThatThrownBy(super::throwsAnExceptionOnMalformedFiles)
super.throwsAnExceptionOnMalformedFiles(); .hasMessageContaining(" * Failed to parse configuration; Cannot construct instance of `io.dropwizard.configuration.BaseConfigurationFactoryTest$Example`");
} catch (ConfigurationParsingException e) {
assertThat(e)
.hasMessageContaining(" * Failed to parse configuration; Cannot construct instance of `io.dropwizard.configuration.BaseConfigurationFactoryTest$Example`");
}
} }


@Override @Override
public void printsDetailedInformationOnMalformedContent() throws Exception { public void printsDetailedInformationOnMalformedContent() throws Exception {
try { assertThatThrownBy(super::printsDetailedInformationOnMalformedContent)
super.printsDetailedInformationOnMalformedContent(); .hasMessageContaining(String.format(
} catch (Throwable t) { "%s has an error:%n" +
assertThat(t).hasMessageContaining(String.format( " * Malformed YAML at line: 3, column: 22; while parsing a flow sequence\n" +
"%s has an error:%n" + " in 'reader', line 2, column 7:\n" +
" * Malformed YAML at line: 3, column: 22; while parsing a flow sequence\n" + " type: [ coder,wizard\n" +
" in 'reader', line 2, column 7:\n" + " ^\n" +
" type: [ coder,wizard\n" + "expected ',' or ']', but got StreamEnd\n" +
" ^\n" + " in 'reader', line 2, column 21:\n" +
"expected ',' or ']', but got StreamEnd\n" + " wizard\n" +
" in 'reader', line 2, column 21:\n" + " ^", malformedAdvancedFile.getName()));
" wizard\n" +
" ^", malformedAdvancedFile.getName()));
}
} }
} }
Expand Up @@ -13,7 +13,7 @@
/** /**
* When annotating a Jersey resource method, wraps the method in a Hibernate session. * When annotating a Jersey resource method, wraps the method in a Hibernate session.
* <p>To be used outside Jersey, one need to create a proxy of the component with the * <p>To be used outside Jersey, one need to create a proxy of the component with the
* annotated method.</p. * annotated method.</p>
* *
* @see UnitOfWorkApplicationListener * @see UnitOfWorkApplicationListener
* @see UnitOfWorkAwareProxyFactory * @see UnitOfWorkAwareProxyFactory
Expand Down
Expand Up @@ -36,7 +36,7 @@
* </tr> * </tr>
* <tr> * <tr>
* <td>{@code maxConcurrentStreams}</td> * <td>{@code maxConcurrentStreams}</td>
* <td><1024</td> * <td>1024</td>
* <td> * <td>
* The maximum number of concurrently open streams allowed on a single HTTP/2 connection. * The maximum number of concurrently open streams allowed on a single HTTP/2 connection.
* Larger values increase parallelism, but cost a memory commitment. * Larger values increase parallelism, but cost a memory commitment.
Expand Down
Expand Up @@ -21,7 +21,7 @@
* information: request method, request path, request ID, response status, * information: request method, request path, request ID, response status,
* response length (or -1 if not known). * response length (or -1 if not known).
* *
* @see https://devcenter.heroku.com/articles/http-request-id * @see <a href="https://devcenter.heroku.com/articles/http-request-id">Heroku - HTTP Request IDs</a>
*/ */
@Provider @Provider
@Priority(Priorities.USER) @Priority(Priorities.USER)
Expand Down
Expand Up @@ -17,7 +17,7 @@
* taken to execute the request, in seconds (based on the implementation from * taken to execute the request, in seconds (based on the implementation from
* Ruby on Rails). * Ruby on Rails).
* *
* @see https://github.com/rack/rack/blob/master/lib/rack/runtime.rb * @see <a href="https://github.com/rack/rack/blob/2.0.0/lib/rack/runtime.rb">Rack::Runtime</a>
*/ */
@Provider @Provider
@PreMatching @PreMatching
Expand Down
Expand Up @@ -76,7 +76,7 @@ public void noEncodingwillNotAroundWrite() throws IOException, WebApplicationExc
assertThat(context.isProceedCalled(), is(true)); assertThat(context.isProceedCalled(), is(true));
} }


private class WriterInterceptorContextMock implements WriterInterceptorContext { private static class WriterInterceptorContextMock implements WriterInterceptorContext {
private final MultivaluedMap<String, Object> headers; private final MultivaluedMap<String, Object> headers;
private OutputStream os = new OutputStream() { private OutputStream os = new OutputStream() {
@Override @Override
Expand Down
Expand Up @@ -25,6 +25,7 @@ private enum WithToString {
A_1, A_1,
A_2; A_2;


@Override
public String toString() { public String toString() {
return "<" + this.name() + ">"; return "<" + this.name() + ">";
} }
Expand Down
Expand Up @@ -30,7 +30,7 @@
*/ */
public class BiDiGzipHandler extends GzipHandler { public class BiDiGzipHandler extends GzipHandler {


private final ThreadLocal<Inflater> localInflater = new ThreadLocal<>(); private static final ThreadLocal<Inflater> localInflater = new ThreadLocal<>();


/** /**
* Size of the buffer for decompressing requests * Size of the buffer for decompressing requests
Expand All @@ -51,9 +51,6 @@ public void setInflateNoWrap(boolean inflateNoWrap) {
this.inflateNoWrap = inflateNoWrap; this.inflateNoWrap = inflateNoWrap;
} }


public BiDiGzipHandler() {
}

public void setInputBufferSize(int inputBufferSize) { public void setInputBufferSize(int inputBufferSize) {
this.inputBufferSize = inputBufferSize; this.inputBufferSize = inputBufferSize;
} }
Expand Down
Expand Up @@ -20,10 +20,8 @@
import java.net.SocketException; import java.net.SocketException;


/** /**
* @see https://github.com/apache/curator/blob/master/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java * @see <a href="https://github.com/apache/curator/blob/master/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java">LocalIpFilter</a>
*/ */
public interface LocalIpFilter { public interface LocalIpFilter {

boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException;
public boolean use(NetworkInterface networkInterface,
InetAddress address) throws SocketException;
} }
Expand Up @@ -35,7 +35,8 @@ public void start() throws Exception {
} }


/** /**
* Calls {@link AutoCloseable#close()} given in the {@link AutoCloseableManager(AutoCloseable)} * Calls {@link AutoCloseable#close()} on the closable provided in
* {@link AutoCloseableManager#AutoCloseableManager(AutoCloseable)}.
* *
* @throws Exception propagates {@link AutoCloseable#close()} exception * @throws Exception propagates {@link AutoCloseable#close()} exception
*/ */
Expand Down
Expand Up @@ -154,7 +154,7 @@ public String getLogFormat() {
} }


@JsonProperty @JsonProperty
public void setLogFormat(String logFormat) { public void setLogFormat(@Nullable String logFormat) {
this.logFormat = logFormat; this.logFormat = logFormat;
} }


Expand Down
Expand Up @@ -19,6 +19,8 @@
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;


import static com.google.common.base.Strings.isNullOrEmpty;

/** /**
* An {@link AppenderFactory} implementation which provides an appender that sends events to a * An {@link AppenderFactory} implementation which provides an appender that sends events to a
* syslog server. * syslog server.
Expand Down Expand Up @@ -124,28 +126,11 @@ public enum Facility {
@NotNull @NotNull
private String stackTracePrefix = SyslogAppender.DEFAULT_STACKTRACE_PATTERN; private String stackTracePrefix = SyslogAppender.DEFAULT_STACKTRACE_PATTERN;


// prefix the logFormat with the application name and PID (if available)
private String logFormat = LOG_TOKEN_NAME + LOG_TOKEN_PID + ": " +
SyslogAppender.DEFAULT_SUFFIX_PATTERN;

private boolean includeStackTrace = true; private boolean includeStackTrace = true;


/** public SyslogAppenderFactory() {
* Returns the Logback pattern with which events will be formatted. // prefix the logFormat with the application name and PID (if available)
*/ this.logFormat = LOG_TOKEN_NAME + LOG_TOKEN_PID + ": " + SyslogAppender.DEFAULT_SUFFIX_PATTERN;
@Override
@JsonProperty
public String getLogFormat() {
return logFormat;
}

/**
* Sets the Logback pattern with which events will be formatted.
*/
@Override
@JsonProperty
public void setLogFormat(String logFormat) {
this.logFormat = logFormat;
} }


/** /**
Expand Down Expand Up @@ -207,9 +192,11 @@ public Appender<ILoggingEvent> build(LoggerContext context, String applicationNa
final SyslogAppender appender = new SyslogAppender(); final SyslogAppender appender = new SyslogAppender();
appender.setName("syslog-appender"); appender.setName("syslog-appender");
appender.setContext(context); appender.setContext(context);
appender.setSuffixPattern(logFormat if (!isNullOrEmpty(logFormat)) {
.replaceAll(LOG_TOKEN_PID, pid) appender.setSuffixPattern(logFormat
.replaceAll(LOG_TOKEN_NAME, Matcher.quoteReplacement(applicationName))); .replaceAll(LOG_TOKEN_PID, pid)
.replaceAll(LOG_TOKEN_NAME, Matcher.quoteReplacement(applicationName)));
}
appender.setSyslogHost(host); appender.setSyslogHost(host);
appender.setPort(port); appender.setPort(port);
appender.setFacility(facility.toString().toLowerCase(Locale.ENGLISH)); appender.setFacility(facility.toString().toLowerCase(Locale.ENGLISH));
Expand Down
Expand Up @@ -17,6 +17,7 @@
import java.net.DatagramPacket; import java.net.DatagramPacket;
import java.net.DatagramSocket; import java.net.DatagramSocket;
import java.net.SocketException; import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;


Expand All @@ -41,7 +42,7 @@ public void setUp() throws Exception {
try { try {
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length); DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(datagramPacket); datagramSocket.receive(datagramPacket);
assertThat(new String(buffer, 0, datagramPacket.getLength())) assertThat(new String(buffer, 0, datagramPacket.getLength(), StandardCharsets.UTF_8))
.startsWith("INFO").contains("com.example.app: Application log " + i); .startsWith("INFO").contains("com.example.app: Application log " + i);
countDownLatch.countDown(); countDownLatch.countDown();
} catch (SocketException e) { } catch (SocketException e) {
Expand Down

0 comments on commit fba9bb9

Please sign in to comment.