From 207c3cbc98131463bc28cbf6cab814f44af1ece2 Mon Sep 17 00:00:00 2001 From: Artem Prigoda Date: Sun, 12 Nov 2017 21:20:19 +0100 Subject: [PATCH] Add `@Nullable` annotations or initialize not-null fields We now run a static analyzer during our build which helps us to catch NPE during compilation. To make it work, we should annotate actual nullable fields with the @Nullable annotation, otherwise the analyzer will always consider such fields as nonnull by default and will report violations when a null value is assigned to them. --- .../dropwizard/assets/AssetsBundleTest.java | 4 +- .../dropwizard/auth/AuthDynamicFeature.java | 3 + .../java/io/dropwizard/auth/AuthFilter.java | 14 ++-- .../auth/AuthValueFactoryProvider.java | 2 + .../PolymorphicAuthValueFactoryProvider.java | 2 + .../client/DropwizardApacheConnector.java | 5 +- .../DropwizardSSLConnectionSocketFactory.java | 19 ++++-- .../dropwizard/client/HttpClientBuilder.java | 27 +++++++- .../client/HttpClientConfiguration.java | 2 + .../client/JerseyClientBuilder.java | 13 +++- .../client/proxy/AuthConfiguration.java | 15 +++- .../proxy/NonProxyListProxyRoutePlanner.java | 1 + .../client/proxy/ProxyConfiguration.java | 4 +- .../client/ssl/TlsConfiguration.java | 11 ++- .../ConfiguredCloseableHttpClientTest.java | 14 ++-- .../client/HttpClientBuilderTest.java | 68 +++++++++---------- .../client/JerseyClientBuilderTest.java | 8 ++- .../proxy/HttpClientConfigurationTest.java | 26 +++---- .../BaseConfigurationFactory.java | 20 +++--- .../ConfigurationParsingException.java | 17 +++-- .../JsonConfigurationFactory.java | 5 +- .../YamlConfigurationFactory.java | 3 +- .../BaseConfigurationFactoryTest.java | 31 ++++++--- .../ConfigurationValidationExceptionTest.java | 2 + .../SubstitutingSourceProviderTest.java | 5 +- .../java/io/dropwizard/Configuration.java | 2 + .../src/main/java/io/dropwizard/cli/Cli.java | 5 +- .../io/dropwizard/cli/ConfiguredCommand.java | 2 + .../server/AbstractServerFactory.java | 17 +++++ .../java/io/dropwizard/setup/Environment.java | 6 +- .../dropwizard/sslreload/SslReloadTask.java | 3 +- .../io/dropwizard/db/DataSourceFactory.java | 32 ++++++--- .../dropwizard/db/DataSourceFactoryTest.java | 3 + .../dropwizard/forms/MultiPartBundleTest.java | 9 ++- .../dropwizard/hibernate/HibernateBundle.java | 10 ++- .../hibernate/UnitOfWorkAspect.java | 35 ++++++---- .../java/io/dropwizard/hibernate/Dog.java | 5 ++ .../hibernate/JerseyIntegrationTest.java | 2 + .../dropwizard/hibernate/LazyLoadingTest.java | 7 +- .../hibernate/PersistenceExceptionMapper.java | 9 ++- .../java/io/dropwizard/hibernate/Person.java | 8 ++- .../hibernate/SessionFactoryFactoryTest.java | 12 ++-- .../hibernate/SubResourcesTest.java | 7 +- .../http2/Http2CConnectorFactory.java | 3 +- .../http2/Http2ConnectorFactory.java | 3 +- .../dropwizard/jackson/FuzzyEnumModule.java | 2 + .../java/io/dropwizard/jackson/Jackson.java | 4 +- ...onSensitivePropertyNamingStrategyTest.java | 4 ++ .../java/io/dropwizard/jackson/Issue1627.java | 9 ++- .../io/dropwizard/jackson/JacksonTest.java | 2 + .../dropwizard/jdbi/args/InstantArgument.java | 5 +- .../dropwizard/jdbi/args/InstantMapper.java | 3 + .../jdbi/args/JodaDateTimeArgument.java | 4 +- .../jdbi/args/JodaDateTimeMapper.java | 3 + .../jdbi/args/LocalDateArgument.java | 4 +- .../dropwizard/jdbi/args/LocalDateMapper.java | 3 + .../jdbi/args/LocalDateTimeArgument.java | 4 +- .../jdbi/args/LocalDateTimeMapper.java | 3 + .../jdbi/args/OffsetDateTimeArgument.java | 4 +- .../jdbi/args/OffsetDateTimeMapper.java | 4 ++ .../jdbi/args/ZonedDateTimeArgument.java | 4 +- .../jdbi/args/ZonedDateTimeMapper.java | 4 ++ .../io/dropwizard/jdbi/GuavaJDBITest.java | 3 +- .../java/io/dropwizard/jdbi/JDBITest.java | 3 +- .../jdbi/args/InstantMapperTest.java | 11 +-- .../jdbi/args/JodaDateTimeMapperTest.java | 13 ++-- .../jdbi/args/LocalDateMapperTest.java | 14 ++-- .../jdbi/args/LocalDateTimeMapperTest.java | 14 ++-- .../jdbi/args/OffsetDateTimeMapperTest.java | 13 ++-- .../jdbi/args/ZonedDateTimeMapperTest.java | 13 ++-- .../dropwizard/jdbi/timestamps/DBIClient.java | 9 ++- .../jdbi/timestamps/DatabaseInTimeZone.java | 6 +- .../JodaDateTimeSqlTimestampTest.java | 14 ++-- .../jersey/DropwizardResourceConfig.java | 12 ++-- .../jersey/errors/ErrorEntityWriter.java | 9 ++- .../jersey/errors/ErrorMessage.java | 6 +- .../jersey/filter/AllowedMethodsFilter.java | 2 +- .../guava/OptionalMessageBodyWriter.java | 6 +- .../guava/OptionalParamConverterProvider.java | 2 + .../jackson/JacksonMessageBodyProvider.java | 13 ++-- .../jersey/jsr310/InstantParam.java | 6 +- .../jersey/jsr310/InstantSecondParam.java | 6 +- .../jersey/jsr310/LocalDateParam.java | 5 +- .../jersey/jsr310/LocalDateTimeParam.java | 5 +- .../jersey/jsr310/LocalTimeParam.java | 5 +- .../jersey/jsr310/OffsetDateTimeParam.java | 5 +- .../jersey/jsr310/YearMonthParam.java | 5 +- .../dropwizard/jersey/jsr310/YearParam.java | 5 +- .../dropwizard/jersey/jsr310/ZoneIdParam.java | 5 +- .../jersey/jsr310/ZonedDateTimeParam.java | 5 +- .../OptionalDoubleParamConverterProvider.java | 2 + .../OptionalIntParamConverterProvider.java | 2 + .../OptionalLongParamConverterProvider.java | 2 + .../optional/OptionalMessageBodyWriter.java | 6 +- .../OptionalParamConverterProvider.java | 2 + .../jersey/params/AbstractParam.java | 9 +-- .../AbstractParamConverterProvider.java | 3 + .../jersey/params/BooleanParam.java | 8 ++- .../jersey/params/DateTimeParam.java | 8 ++- .../jersey/params/DurationParam.java | 12 ++-- .../jersey/params/InstantParam.java | 7 +- .../io/dropwizard/jersey/params/IntParam.java | 8 ++- .../jersey/params/LocalDateParam.java | 8 ++- .../dropwizard/jersey/params/LongParam.java | 8 ++- .../jersey/params/NonEmptyStringParam.java | 7 +- .../dropwizard/jersey/params/SizeParam.java | 12 ++-- .../dropwizard/jersey/params/UUIDParam.java | 7 +- .../jersey/sessions/FlashFactory.java | 4 ++ .../jersey/sessions/HttpSessionFactory.java | 3 + .../sessions/SessionFactoryProvider.java | 2 + .../jersey/setup/JerseyContainerHolder.java | 8 ++- .../jersey/setup/JerseyEnvironment.java | 1 + .../FuzzyEnumParamConverterProvider.java | 16 +++-- .../validation/ParamValidatorUnwrapper.java | 2 + .../MyMessageParamConverterProvider.java | 2 + .../jersey/filter/CharsetUtf8FilterTest.java | 12 +--- .../jersey/filter/RequestIdFilterTest.java | 16 ++--- .../jersey/filter/RuntimeFilterTest.java | 12 +--- .../gzip/ConfiguredGZipEncoderTest.java | 15 ++-- .../jersey/jackson/CustomDeserialization.java | 2 + .../JacksonMessageBodyProviderTest.java | 5 +- .../jersey/jackson/OkRepresentation.java | 7 +- .../jersey/validation/BeanParameter.java | 7 +- ...onstraintViolationExceptionMapperTest.java | 57 ++++++++-------- .../FuzzyEnumParamConverterProviderTest.java | 47 ++++++------- .../jersey/validation/SubBeanParameter.java | 2 +- .../validation/ValidRepresentation.java | 2 +- .../jersey/validation/ValidatingResource.java | 2 +- .../validation/WrappedFailingExample.java | 3 + .../WrappedValidRepresentation.java | 3 + .../io/dropwizard/jetty/BiDiGzipHandler.java | 2 + .../io/dropwizard/jetty/ConnectorFactory.java | 4 +- .../dropwizard/jetty/GzipHandlerFactory.java | 13 +++- .../jetty/HttpConnectorFactory.java | 20 ++++-- .../jetty/HttpsConnectorFactory.java | 61 ++++++++++++++++- .../Jetty93InstrumentedConnectionFactory.java | 7 +- .../java/io/dropwizard/jetty/NetUtil.java | 8 ++- .../ScheduledExecutorServiceBuilderTest.java | 20 +++--- .../logging/AbstractAppenderFactory.java | 3 + .../logging/FileAppenderFactory.java | 14 +++- ...CauseFirstThrowableProxyConverterTest.java | 2 + .../ganglia/GangliaReporterFactory.java | 7 ++ .../metrics/CsvReporterFactory.java | 10 ++- .../metrics/Slf4jReporterFactory.java | 6 +- .../metrics/BaseReporterFactoryTest.java | 8 +-- .../metrics/MetricAttributesTest.java | 6 +- .../migrations/AbstractLiquibaseCommand.java | 3 +- .../io/dropwizard/migrations/DbCommand.java | 5 +- .../layout/SafeRequestParameterConverter.java | 2 + .../servlets/assets/AssetServlet.java | 11 ++- .../servlets/tasks/LogConfigurationTask.java | 2 + .../servlets/tasks/TaskServlet.java | 3 +- .../servlets/SlowRequestFilterTest.java | 24 ++----- .../servlets/ThreadNameFilterTest.java | 17 ++--- .../servlets/assets/AssetServletTest.java | 2 + .../testing/DropwizardTestSupport.java | 34 ++++++---- .../testing/POJOConfigurationFactory.java | 3 +- .../testing/junit/DropwizardAppRule.java | 6 +- .../junit/DropwizardTestResourceConfig.java | 7 +- .../testing/junit/ResourceTestRule.java | 11 ++- .../testing/DropwizardTestSupportTest.java | 4 +- .../java/io/dropwizard/testing/Person.java | 4 +- .../testing/app/PersonResource.java | 6 +- .../junit/DropwizardAppRuleReentrantTest.java | 19 ++---- .../testing/junit/TestConfiguration.java | 4 +- .../dropwizard/testing/junit/TestEntity.java | 8 ++- .../main/java/io/dropwizard/util/Enums.java | 3 + .../java/io/dropwizard/util/Generics.java | 2 + .../validation/MaxDurationValidator.java | 4 +- .../validation/MaxSizeValidator.java | 4 +- .../validation/MinDurationValidator.java | 4 +- .../validation/MinSizeValidator.java | 4 +- .../dropwizard/validation/OneOfValidator.java | 2 +- .../selfvalidating/ValidationCaller.java | 4 ++ ...OptionalDoubleValidatedValueUnwrapper.java | 2 + .../OptionalIntValidatedValueUnwrapper.java | 2 + .../OptionalLongValidatedValueUnwrapper.java | 2 + .../validation/ConstraintPerson.java | 2 +- .../mustache/PerClassMustacheResolver.java | 2 + .../main/java/io/dropwizard/views/View.java | 5 +- .../views/ViewMessageBodyWriter.java | 12 +++- .../io/dropwizard/views/ViewBundleTest.java | 14 +--- .../views/ViewMessageBodyWriterTest.java | 39 +++++------ pom.xml | 2 +- 184 files changed, 1050 insertions(+), 548 deletions(-) diff --git a/dropwizard-assets/src/test/java/io/dropwizard/assets/AssetsBundleTest.java b/dropwizard-assets/src/test/java/io/dropwizard/assets/AssetsBundleTest.java index 2bfc200d875..239090f0f4e 100644 --- a/dropwizard-assets/src/test/java/io/dropwizard/assets/AssetsBundleTest.java +++ b/dropwizard-assets/src/test/java/io/dropwizard/assets/AssetsBundleTest.java @@ -24,8 +24,8 @@ public class AssetsBundleTest { private final ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); private final Environment environment = mock(Environment.class); - private AssetServlet servlet; - private String servletPath; + private AssetServlet servlet = new AssetServlet("/", "/", null, null); + private String servletPath = ""; @Before public void setUp() throws Exception { diff --git a/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthDynamicFeature.java b/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthDynamicFeature.java index a37b37de2d9..1f144d8ea96 100644 --- a/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthDynamicFeature.java +++ b/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthDynamicFeature.java @@ -3,6 +3,7 @@ import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; import org.glassfish.jersey.server.model.AnnotatedMethod; +import javax.annotation.Nullable; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; @@ -30,8 +31,10 @@ */ public class AuthDynamicFeature implements DynamicFeature { + @Nullable private final ContainerRequestFilter authFilter; + @Nullable private final Class authFilterClass; public AuthDynamicFeature(ContainerRequestFilter authFilter) { diff --git a/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthFilter.java b/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthFilter.java index 04a55133b97..5c4458d7a3e 100644 --- a/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthFilter.java +++ b/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthFilter.java @@ -4,6 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import javax.annotation.Priority; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.Priorities; @@ -18,11 +19,11 @@ public abstract class AuthFilter implements ContainerReq protected final Logger logger = LoggerFactory.getLogger(getClass()); - protected String prefix; - protected String realm; - protected Authenticator authenticator; - protected Authorizer

authorizer; - protected UnauthorizedHandler unauthorizedHandler; + protected String prefix = "Basic"; + protected String realm = "realm"; + protected Authenticator authenticator = credentials -> Optional.empty(); + protected Authorizer

authorizer = new PermitAllAuthorizer<>(); + protected UnauthorizedHandler unauthorizedHandler = new DefaultUnauthorizedHandler(); /** * Abstract builder for auth filters. @@ -34,6 +35,7 @@ public abstract static class AuthFilterBuilder authenticator; private Authorizer

authorizer = new PermitAllAuthorizer<>(); private UnauthorizedHandler unauthorizedHandler = new DefaultUnauthorizedHandler(); @@ -127,7 +129,7 @@ public T buildAuthFilter() { * See {@link SecurityContext} * @return {@code true}, if the request is authenticated, otherwise {@code false} */ - protected boolean authenticate(ContainerRequestContext requestContext, C credentials, String scheme) { + protected boolean authenticate(ContainerRequestContext requestContext, @Nullable C credentials, String scheme) { try { if (credentials == null) { return false; diff --git a/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthValueFactoryProvider.java b/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthValueFactoryProvider.java index ffe8564707a..12c32757706 100644 --- a/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthValueFactoryProvider.java +++ b/dropwizard-auth/src/main/java/io/dropwizard/auth/AuthValueFactoryProvider.java @@ -11,6 +11,7 @@ import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import java.lang.reflect.ParameterizedType; @@ -53,6 +54,7 @@ public AuthValueFactoryProvider(MultivaluedParameterExtractorProvider mpep, * @return the factory if annotated parameter matched type */ @Override + @Nullable public AbstractContainerRequestValueFactory createValueFactory(Parameter parameter) { if (!parameter.isAnnotationPresent(Auth.class)) { return null; diff --git a/dropwizard-auth/src/main/java/io/dropwizard/auth/PolymorphicAuthValueFactoryProvider.java b/dropwizard-auth/src/main/java/io/dropwizard/auth/PolymorphicAuthValueFactoryProvider.java index 69e42b420c3..be25c54acf8 100644 --- a/dropwizard-auth/src/main/java/io/dropwizard/auth/PolymorphicAuthValueFactoryProvider.java +++ b/dropwizard-auth/src/main/java/io/dropwizard/auth/PolymorphicAuthValueFactoryProvider.java @@ -11,6 +11,7 @@ import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import java.lang.reflect.ParameterizedType; @@ -58,6 +59,7 @@ public PolymorphicAuthValueFactoryProvider( * @return the factory if annotated parameter matched type */ @Override + @Nullable public AbstractContainerRequestValueFactory createValueFactory(Parameter parameter) { if (!parameter.isAnnotationPresent(Auth.class)) { return null; diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardApacheConnector.java b/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardApacheConnector.java index e75b513e793..b3dc36887d3 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardApacheConnector.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardApacheConnector.java @@ -20,6 +20,7 @@ import org.glassfish.jersey.client.spi.Connector; import org.glassfish.jersey.message.internal.Statuses; +import javax.annotation.Nullable; import javax.ws.rs.ProcessingException; import javax.ws.rs.core.Response; import java.io.ByteArrayInputStream; @@ -63,6 +64,7 @@ public class DropwizardApacheConnector implements Connector { /** * Default HttpUriRequestConfig */ + @Nullable private final RequestConfig defaultRequestConfig; /** @@ -70,7 +72,7 @@ public class DropwizardApacheConnector implements Connector { */ private final boolean chunkedEncodingEnabled; - public DropwizardApacheConnector(CloseableHttpClient client, RequestConfig defaultRequestConfig, + public DropwizardApacheConnector(CloseableHttpClient client, @Nullable RequestConfig defaultRequestConfig, boolean chunkedEncodingEnabled) { this.client = client; this.defaultRequestConfig = defaultRequestConfig; @@ -172,6 +174,7 @@ private Optional addJerseyRequestConfig(ClientRequest clientReque * @param jerseyRequest representation of an HTTP request in Jersey * @return a correct {@link org.apache.http.HttpEntity} implementation */ + @Nullable private HttpEntity getHttpEntity(ClientRequest jerseyRequest) { if (jerseyRequest.getEntity() == null) { return null; diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardSSLConnectionSocketFactory.java b/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardSSLConnectionSocketFactory.java index ce8910a7098..f040baf9c70 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardSSLConnectionSocketFactory.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/DropwizardSSLConnectionSocketFactory.java @@ -9,6 +9,7 @@ import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; +import javax.annotation.Nullable; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import java.io.File; @@ -17,16 +18,20 @@ import java.security.KeyStore; import java.util.List; +import static java.util.Objects.requireNonNull; + public class DropwizardSSLConnectionSocketFactory { private final TlsConfiguration configuration; + + @Nullable private final HostnameVerifier verifier; public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration) { this(configuration, null); } - public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration, HostnameVerifier verifier) { + public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration, @Nullable HostnameVerifier verifier) { this.configuration = configuration; this.verifier = verifier; } @@ -36,6 +41,7 @@ public SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationExc chooseHostnameVerifier()); } + @Nullable private String[] getSupportedCiphers() { final List supportedCiphers = configuration.getSupportedCiphers(); if (supportedCiphers == null) { @@ -44,6 +50,7 @@ private String[] getSupportedCiphers() { return supportedCiphers.toArray(new String[supportedCiphers.size()]); } + @Nullable private String[] getSupportedProtocols() { final List supportedProtocols = configuration.getSupportedProtocols(); if (supportedProtocols == null) { @@ -74,6 +81,7 @@ private SSLContext buildSslContext() throws SSLInitializationException { return sslContext; } + @Nullable private PrivateKeyStrategy choosePrivateKeyStrategy() { PrivateKeyStrategy privateKeyStrategy = null; if (configuration.getCertAlias() != null) { @@ -89,9 +97,10 @@ private PrivateKeyStrategy choosePrivateKeyStrategy() { private void loadKeyMaterial(SSLContextBuilder sslContextBuilder) throws Exception { if (configuration.getKeyStorePath() != null) { final KeyStore keystore = loadKeyStore(configuration.getKeyStoreType(), configuration.getKeyStorePath(), - configuration.getKeyStorePassword()); - - sslContextBuilder.loadKeyMaterial(keystore, configuration.getKeyStorePassword().toCharArray(), choosePrivateKeyStrategy()); + requireNonNull(configuration.getKeyStorePassword())); + + sslContextBuilder.loadKeyMaterial(keystore, + requireNonNull(configuration.getKeyStorePassword()).toCharArray(), choosePrivateKeyStrategy()); } } @@ -99,7 +108,7 @@ private void loadTrustMaterial(SSLContextBuilder sslContextBuilder) throws Excep KeyStore trustStore = null; if (configuration.getTrustStorePath() != null) { trustStore = loadKeyStore(configuration.getTrustStoreType(), configuration.getTrustStorePath(), - configuration.getTrustStorePassword()); + requireNonNull(configuration.getTrustStorePassword())); } TrustStrategy trustStrategy = null; if (configuration.isTrustSelfSignedCertificates()) { diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientBuilder.java b/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientBuilder.java index 18ffcf8003e..1fb975928fa 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientBuilder.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientBuilder.java @@ -46,6 +46,7 @@ import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; +import javax.annotation.Nullable; import javax.net.ssl.HostnameVerifier; import java.util.List; @@ -64,21 +65,43 @@ public class HttpClientBuilder { private static final HttpRequestRetryHandler NO_RETRIES = (exception, executionCount, context) -> false; private final MetricRegistry metricRegistry; + + @Nullable private String environmentName; + + @Nullable private Environment environment; private HttpClientConfiguration configuration = new HttpClientConfiguration(); private DnsResolver resolver = new SystemDefaultDnsResolver(); + + @Nullable private HostnameVerifier verifier; + + @Nullable private HttpRequestRetryHandler httpRequestRetryHandler; + + @Nullable private Registry registry; - private CredentialsProvider credentialsProvider = null; + @Nullable + private CredentialsProvider credentialsProvider; + private HttpClientMetricNameStrategy metricNameStrategy = HttpClientMetricNameStrategies.METHOD_ONLY; - private HttpRoutePlanner routePlanner = null; + + @Nullable + private HttpRoutePlanner routePlanner; + + @Nullable private RedirectStrategy redirectStrategy; private boolean disableContentCompression; + + @Nullable private List defaultHeaders; + + @Nullable private HttpProcessor httpProcessor; + + @Nullable private ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy; public HttpClientBuilder(MetricRegistry metricRegistry) { diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientConfiguration.java b/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientConfiguration.java index 68f2887c8b7..27370a52dec 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientConfiguration.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/HttpClientConfiguration.java @@ -163,6 +163,7 @@ public void setUserAgent(Optional userAgent) { } @JsonProperty("proxy") + @Nullable public ProxyConfiguration getProxyConfiguration() { return proxyConfiguration; } @@ -183,6 +184,7 @@ public void setValidateAfterInactivityPeriod(Duration validateAfterInactivityPer } @JsonProperty("tls") + @Nullable public TlsConfiguration getTlsConfiguration() { return tlsConfiguration; } diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/JerseyClientBuilder.java b/dropwizard-client/src/main/java/io/dropwizard/client/JerseyClientBuilder.java index 666af257dad..24d32ba5689 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/JerseyClientBuilder.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/JerseyClientBuilder.java @@ -25,6 +25,7 @@ import org.glassfish.jersey.client.rx.RxInvoker; import org.glassfish.jersey.client.spi.ConnectorProvider; +import javax.annotation.Nullable; import javax.net.ssl.HostnameVerifier; import javax.validation.Validator; import javax.ws.rs.client.Client; @@ -65,9 +66,17 @@ public class JerseyClientBuilder { private HttpClientBuilder apacheHttpClientBuilder; private Validator validator = Validators.newValidator(); + + @Nullable private Environment environment; + + @Nullable private ObjectMapper objectMapper; + + @Nullable private ExecutorService executorService; + + @Nullable private ConnectorProvider connectorProvider; private Duration shutdownGracePeriod = Duration.seconds(5); @@ -351,7 +360,7 @@ public Client build(String name) { // is used to ensure that the service is shut down if the // Jersey client disposes of it. executorService = new DropwizardExecutorProvider.DisposableExecutorService( - environment.lifecycle() + requireNonNull(environment).lifecycle() .executorService("jersey-client-" + name + "-%d") .minThreads(configuration.getMinThreads()) .maxThreads(configuration.getMaxThreads()) @@ -361,7 +370,7 @@ public Client build(String name) { } if (objectMapper == null) { - objectMapper = environment.getObjectMapper(); + objectMapper = requireNonNull(environment).getObjectMapper(); } if (environment != null) { diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/proxy/AuthConfiguration.java b/dropwizard-client/src/main/java/io/dropwizard/client/proxy/AuthConfiguration.java index 798d7061795..0a02aaba1b4 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/proxy/AuthConfiguration.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/proxy/AuthConfiguration.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; +import javax.annotation.Nullable; import javax.validation.constraints.Pattern; /** @@ -68,21 +69,26 @@ public class AuthConfiguration { public static final String NT_CREDS = "NT"; @NotEmpty - private String username; + private String username = ""; @NotEmpty - private String password; + private String password = ""; @Pattern(regexp = BASIC_AUTH_SCHEME + "|" + NTLM_AUTH_SCHEME) + @Nullable private String authScheme; + @Nullable private String realm; + @Nullable private String hostname; + @Nullable private String domain; @Pattern(regexp = USERNAME_PASSWORD_CREDS + "|" + NT_CREDS, flags = {Pattern.Flag.CASE_INSENSITIVE}) + @Nullable private String credentialType; public AuthConfiguration() { @@ -124,6 +130,7 @@ public void setPassword(String password) { } @JsonProperty + @Nullable public String getAuthScheme() { return authScheme; } @@ -134,6 +141,7 @@ public void setAuthScheme(String authScheme) { } @JsonProperty + @Nullable public String getRealm() { return realm; } @@ -144,6 +152,7 @@ public void setRealm(String realm) { } @JsonProperty + @Nullable public String getHostname() { return hostname; } @@ -154,6 +163,7 @@ public void setHostname(String hostname) { } @JsonProperty + @Nullable public String getDomain() { return domain; } @@ -164,6 +174,7 @@ public void setDomain(String domain) { } @JsonProperty + @Nullable public String getCredentialType() { return credentialType; } diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/proxy/NonProxyListProxyRoutePlanner.java b/dropwizard-client/src/main/java/io/dropwizard/client/proxy/NonProxyListProxyRoutePlanner.java index f2f1f6b57fa..5763fd3ee93 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/proxy/NonProxyListProxyRoutePlanner.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/proxy/NonProxyListProxyRoutePlanner.java @@ -54,6 +54,7 @@ protected List getNonProxyHostPatterns() { } @Override + @Nullable protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { for (Pattern nonProxyHostPattern : nonProxyHostPatterns) { if (nonProxyHostPattern.matcher(target.getHostName()).matches()) { diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/proxy/ProxyConfiguration.java b/dropwizard-client/src/main/java/io/dropwizard/client/proxy/ProxyConfiguration.java index d9fdeebcc35..79ab8fa07d4 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/proxy/ProxyConfiguration.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/proxy/ProxyConfiguration.java @@ -57,7 +57,7 @@ public class ProxyConfiguration { @NotEmpty - private String host; + private String host = ""; @PortRange(min = -1) private Integer port = -1; @@ -121,6 +121,7 @@ public void setScheme(String scheme) { } @JsonProperty + @Nullable public List getNonProxyHosts() { return nonProxyHosts; } @@ -130,6 +131,7 @@ public void setNonProxyHosts(List nonProxyHosts) { this.nonProxyHosts = nonProxyHosts; } + @Nullable public AuthConfiguration getAuth() { return auth; } diff --git a/dropwizard-client/src/main/java/io/dropwizard/client/ssl/TlsConfiguration.java b/dropwizard-client/src/main/java/io/dropwizard/client/ssl/TlsConfiguration.java index f0738a298b6..5165eb23487 100644 --- a/dropwizard-client/src/main/java/io/dropwizard/client/ssl/TlsConfiguration.java +++ b/dropwizard-client/src/main/java/io/dropwizard/client/ssl/TlsConfiguration.java @@ -15,15 +15,19 @@ public class TlsConfiguration { @NotEmpty private String protocol = "TLSv1.2"; + @Nullable private File keyStorePath; + @Nullable private String keyStorePassword; @NotEmpty private String keyStoreType = "JKS"; + @Nullable private File trustStorePath; + @Nullable private String trustStorePassword; @NotEmpty @@ -53,6 +57,7 @@ public boolean isTrustSelfSignedCertificates() { } @JsonProperty + @Nullable public File getKeyStorePath() { return keyStorePath; } @@ -63,6 +68,7 @@ public void setKeyStorePath(File keyStorePath) { } @JsonProperty + @Nullable public String getKeyStorePassword() { return keyStorePassword; } @@ -91,8 +97,8 @@ public void setTrustStoreType(String trustStoreType) { this.trustStoreType = trustStoreType; } - @JsonProperty + @Nullable public File getTrustStorePath() { return trustStorePath; } @@ -103,6 +109,7 @@ public void setTrustStorePath(File trustStorePath) { } @JsonProperty + @Nullable public String getTrustStorePassword() { return trustStorePassword; } @@ -174,4 +181,4 @@ public boolean isValidKeyStorePassword() { public boolean isValidTrustStorePassword() { return trustStorePath == null || trustStoreType.startsWith("Windows-") || !Strings.isNullOrEmpty(trustStorePassword); } -} \ No newline at end of file +} diff --git a/dropwizard-client/src/test/java/io/dropwizard/client/ConfiguredCloseableHttpClientTest.java b/dropwizard-client/src/test/java/io/dropwizard/client/ConfiguredCloseableHttpClientTest.java index 3ccdc0a9d8a..70b0a34230f 100644 --- a/dropwizard-client/src/test/java/io/dropwizard/client/ConfiguredCloseableHttpClientTest.java +++ b/dropwizard-client/src/test/java/io/dropwizard/client/ConfiguredCloseableHttpClientTest.java @@ -4,19 +4,15 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.Mockito; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) public class ConfiguredCloseableHttpClientTest { - public ConfiguredCloseableHttpClient configuredClient; - @Mock - private CloseableHttpClient closeableHttpClientMock; - @Mock - private RequestConfig defaultRequestConfigMock; + private ConfiguredCloseableHttpClient configuredClient; + + private CloseableHttpClient closeableHttpClientMock = Mockito.mock(CloseableHttpClient.class); + private RequestConfig defaultRequestConfigMock = Mockito.mock(RequestConfig.class); @Before public void setUp() { diff --git a/dropwizard-client/src/test/java/io/dropwizard/client/HttpClientBuilderTest.java b/dropwizard-client/src/test/java/io/dropwizard/client/HttpClientBuilderTest.java index 97e06a5af28..a01818035f6 100644 --- a/dropwizard-client/src/test/java/io/dropwizard/client/HttpClientBuilderTest.java +++ b/dropwizard-client/src/test/java/io/dropwizard/client/HttpClientBuilderTest.java @@ -1,25 +1,17 @@ package io.dropwizard.client; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.validateMockitoUsage; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.SocketAddress; -import java.net.URI; -import java.util.List; -import java.util.Optional; - -import javax.net.ssl.HostnameVerifier; - +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.httpclient.HttpClientMetricNameStrategies; +import com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager; +import com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor; +import com.google.common.collect.ImmutableList; +import io.dropwizard.client.proxy.AuthConfiguration; +import io.dropwizard.client.proxy.ProxyConfiguration; +import io.dropwizard.client.ssl.TlsConfiguration; +import io.dropwizard.lifecycle.Managed; +import io.dropwizard.lifecycle.setup.LifecycleEnvironment; +import io.dropwizard.setup.Environment; +import io.dropwizard.util.Duration; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.http.Header; import org.apache.http.HeaderIterator; @@ -68,19 +60,25 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.httpclient.HttpClientMetricNameStrategies; -import com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager; -import com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor; -import com.google.common.collect.ImmutableList; +import javax.annotation.Nullable; +import javax.net.ssl.HostnameVerifier; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.List; +import java.util.Optional; -import io.dropwizard.client.proxy.AuthConfiguration; -import io.dropwizard.client.proxy.ProxyConfiguration; -import io.dropwizard.client.ssl.TlsConfiguration; -import io.dropwizard.lifecycle.Managed; -import io.dropwizard.lifecycle.setup.LifecycleEnvironment; -import io.dropwizard.setup.Environment; -import io.dropwizard.util.Duration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.validateMockitoUsage; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; public class HttpClientBuilderTest { @@ -436,6 +434,7 @@ public void setCredentials(AuthScope authscope, Credentials credentials) { } @Override + @Nullable public Credentials getCredentials(AuthScope authscope) { return null; } @@ -531,8 +530,8 @@ public void usesNoProxy() throws Exception { checkProxy(new HttpClientConfiguration(), new HttpHost("dropwizard.io", 80), null); } - private CloseableHttpClient checkProxy(HttpClientConfiguration config, HttpHost target, HttpHost expectedProxy) - throws Exception { + private CloseableHttpClient checkProxy(HttpClientConfiguration config, HttpHost target, + @Nullable HttpHost expectedProxy) throws Exception { CloseableHttpClient httpClient = builder.using(config).build("test"); HttpRoutePlanner routePlanner = (HttpRoutePlanner) FieldUtils.getField(httpClient.getClass(), "routePlanner", true).get(httpClient); @@ -636,6 +635,7 @@ public boolean isRedirected(HttpRequest httpRequest, } @Override + @Nullable public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException { diff --git a/dropwizard-client/src/test/java/io/dropwizard/client/JerseyClientBuilderTest.java b/dropwizard-client/src/test/java/io/dropwizard/client/JerseyClientBuilderTest.java index 0fa1ca0b220..55b991ae0af 100644 --- a/dropwizard-client/src/test/java/io/dropwizard/client/JerseyClientBuilderTest.java +++ b/dropwizard-client/src/test/java/io/dropwizard/client/JerseyClientBuilderTest.java @@ -33,6 +33,7 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; +import javax.annotation.Nullable; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; @@ -295,6 +296,7 @@ public void checkServerTrusted(X509Certificate[] xcs, String string) throws Cert } @Override + @Nullable public X509Certificate[] getAcceptedIssuers() { return null; } @@ -348,7 +350,11 @@ public boolean isReadable(Class type, Type genericType, Annotation[] annotati } @Override - public JerseyClientBuilderTest readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { + @Nullable + public JerseyClientBuilderTest readFrom(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException, WebApplicationException { return null; } } diff --git a/dropwizard-client/src/test/java/io/dropwizard/client/proxy/HttpClientConfigurationTest.java b/dropwizard-client/src/test/java/io/dropwizard/client/proxy/HttpClientConfigurationTest.java index 70f900b5b51..4e912c382ec 100644 --- a/dropwizard-client/src/test/java/io/dropwizard/client/proxy/HttpClientConfigurationTest.java +++ b/dropwizard-client/src/test/java/io/dropwizard/client/proxy/HttpClientConfigurationTest.java @@ -13,13 +13,14 @@ import java.io.File; import java.util.List; +import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; public class HttpClientConfigurationTest { private final ObjectMapper objectMapper = Jackson.newObjectMapper(); - private HttpClientConfiguration configuration; + private HttpClientConfiguration configuration = new HttpClientConfiguration(); private void load(String configLocation) throws Exception { configuration = new YamlConfigurationFactory<>(HttpClientConfiguration.class, @@ -38,15 +39,13 @@ public void testNoProxy() throws Exception { public void testFullConfigBasicProxy() throws Exception { load("yaml/proxy.yml"); - ProxyConfiguration proxy = configuration.getProxyConfiguration(); - assertThat(proxy).isNotNull(); + ProxyConfiguration proxy = requireNonNull(configuration.getProxyConfiguration()); assertThat(proxy.getHost()).isEqualTo("192.168.52.11"); assertThat(proxy.getPort()).isEqualTo(8080); assertThat(proxy.getScheme()).isEqualTo("https"); - AuthConfiguration auth = proxy.getAuth(); - assertThat(auth).isNotNull(); + AuthConfiguration auth = requireNonNull(proxy.getAuth()); assertThat(auth.getUsername()).isEqualTo("secret"); assertThat(auth.getPassword()).isEqualTo("stuff"); @@ -58,15 +57,13 @@ public void testFullConfigBasicProxy() throws Exception { public void testFullConfigNtlmProxy() throws Exception { load("yaml/proxy_ntlm.yml"); - ProxyConfiguration proxy = configuration.getProxyConfiguration(); - assertThat(proxy).isNotNull(); + ProxyConfiguration proxy = requireNonNull(configuration.getProxyConfiguration()); assertThat(proxy.getHost()).isEqualTo("192.168.52.11"); assertThat(proxy.getPort()).isEqualTo(8080); assertThat(proxy.getScheme()).isEqualTo("https"); - AuthConfiguration auth = proxy.getAuth(); - assertThat(auth).isNotNull(); + AuthConfiguration auth = requireNonNull(proxy.getAuth()); assertThat(auth.getUsername()).isEqualTo("secret"); assertThat(auth.getPassword()).isEqualTo("stuff"); assertThat(auth.getAuthScheme()).isEqualTo("NTLM"); @@ -83,8 +80,7 @@ public void testFullConfigNtlmProxy() throws Exception { public void testNoScheme() throws Exception { load("./yaml/no_scheme.yml"); - ProxyConfiguration proxy = configuration.getProxyConfiguration(); - assertThat(proxy).isNotNull(); + ProxyConfiguration proxy = requireNonNull(configuration.getProxyConfiguration()); assertThat(proxy.getHost()).isEqualTo("192.168.52.11"); assertThat(proxy.getPort()).isEqualTo(8080); assertThat(proxy.getScheme()).isEqualTo("http"); @@ -94,8 +90,7 @@ public void testNoScheme() throws Exception { public void testNoAuth() throws Exception { load("./yaml/no_auth.yml"); - ProxyConfiguration proxy = configuration.getProxyConfiguration(); - assertThat(proxy).isNotNull(); + ProxyConfiguration proxy = requireNonNull(configuration.getProxyConfiguration()); assertThat(proxy.getHost()).isNotNull(); assertThat(proxy.getAuth()).isNull(); } @@ -104,8 +99,7 @@ public void testNoAuth() throws Exception { public void testNoPort() throws Exception { load("./yaml/no_port.yml"); - ProxyConfiguration proxy = configuration.getProxyConfiguration(); - assertThat(proxy).isNotNull(); + ProxyConfiguration proxy = requireNonNull(configuration.getProxyConfiguration()); assertThat(proxy.getHost()).isNotNull(); assertThat(proxy.getPort()).isEqualTo(-1); } @@ -114,7 +108,7 @@ public void testNoPort() throws Exception { public void testNoNonProxy() throws Exception { load("./yaml/no_port.yml"); - ProxyConfiguration proxy = configuration.getProxyConfiguration(); + ProxyConfiguration proxy = requireNonNull(configuration.getProxyConfiguration()); assertThat(proxy.getNonProxyHosts()).isNull(); } diff --git a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/BaseConfigurationFactory.java b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/BaseConfigurationFactory.java index 4f69da5d69e..757f7b188db 100644 --- a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/BaseConfigurationFactory.java +++ b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/BaseConfigurationFactory.java @@ -10,6 +10,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.annotation.Nullable; import javax.validation.ConstraintViolation; import javax.validation.Validator; @@ -27,6 +28,7 @@ import com.fasterxml.jackson.databind.node.TreeTraversingParser; import com.google.common.base.Joiner; import com.google.common.base.Splitter; +import com.google.common.base.Strings; /** * A generic factory class for loading configuration files, binding them to configuration objects, and @@ -44,7 +46,10 @@ public abstract class BaseConfigurationFactory implements ConfigurationFactor private final Class klass; private final String propertyPrefix; protected final ObjectMapper mapper; + + @Nullable private final Validator validator; + private final String formatName; private final JsonFactory parserFactory; @@ -60,21 +65,14 @@ public abstract class BaseConfigurationFactory implements ConfigurationFactor public BaseConfigurationFactory(JsonFactory parserFactory, String formatName, Class klass, - Validator validator, + @Nullable Validator validator, ObjectMapper objectMapper, String propertyPrefix) { this.klass = klass; this.formatName = formatName; - this.propertyPrefix = (propertyPrefix == null || propertyPrefix.endsWith(".")) - ? propertyPrefix : (propertyPrefix + '.'); - // Sub-classes may choose to omit data-binding; if so, null ObjectMapper passed: - if (objectMapper == null) { // sub-class has no need for mapper - this.mapper = null; - this.parserFactory = null; - } else { - this.mapper = objectMapper; - this.parserFactory = parserFactory; - } + this.propertyPrefix = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + '.'; + this.mapper = objectMapper; + this.parserFactory = parserFactory; this.validator = validator; } diff --git a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/ConfigurationParsingException.java b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/ConfigurationParsingException.java index c1146277df8..fcf61d960a4 100644 --- a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/ConfigurationParsingException.java +++ b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/ConfigurationParsingException.java @@ -6,6 +6,7 @@ import com.google.common.collect.ImmutableSet; import org.apache.commons.lang3.StringUtils; +import javax.annotation.Nullable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -17,6 +18,8 @@ import java.util.Iterator; import java.util.List; +import static java.util.Objects.requireNonNull; + /** * A {@link ConfigurationException} for errors parsing a configuration file. */ @@ -31,9 +34,13 @@ static class Builder { private List fieldPath = Collections.emptyList(); private int line = -1; private int column = -1; - private Exception cause = null; + + @Nullable + private Exception cause; private List suggestions = new ArrayList<>(); - private String suggestionBase = null; + + @Nullable + private String suggestionBase; private boolean suggestionsSorted = false; Builder(String summary) { @@ -134,7 +141,7 @@ public List getSuggestions() { return suggestions; } - suggestions.sort(new LevenshteinComparator(getSuggestionBase())); + suggestions.sort(new LevenshteinComparator(requireNonNull(getSuggestionBase()))); suggestionsSorted = true; return suggestions; @@ -156,6 +163,7 @@ public boolean hasSuggestions() { * * @return the base for suggestions. */ + @Nullable public String getSuggestionBase() { return suggestionBase; } @@ -176,6 +184,7 @@ public boolean hasSuggestionBase() { * * @return an Exception representing the cause of the problem, or null if there is none. */ + @Nullable public Exception getCause() { return cause; } @@ -273,7 +282,7 @@ ConfigurationParsingException build(String path) { } return hasCause() - ? new ConfigurationParsingException(path, sb.toString(), getCause()) + ? new ConfigurationParsingException(path, sb.toString(), requireNonNull(getCause())) : new ConfigurationParsingException(path, sb.toString()); } diff --git a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/JsonConfigurationFactory.java b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/JsonConfigurationFactory.java index 74d4c4c27e8..ac11153ac3e 100644 --- a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/JsonConfigurationFactory.java +++ b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/JsonConfigurationFactory.java @@ -1,10 +1,11 @@ package io.dropwizard.configuration; -import javax.validation.Validator; - import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; +import javax.annotation.Nullable; +import javax.validation.Validator; + /** * A factory class for loading JSON configuration files, binding them to configuration objects, and * validating their constraints. Allows for overriding configuration parameters from system properties. diff --git a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/YamlConfigurationFactory.java b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/YamlConfigurationFactory.java index 32350fd56dd..3979ec41756 100644 --- a/dropwizard-configuration/src/main/java/io/dropwizard/configuration/YamlConfigurationFactory.java +++ b/dropwizard-configuration/src/main/java/io/dropwizard/configuration/YamlConfigurationFactory.java @@ -1,5 +1,6 @@ package io.dropwizard.configuration; +import javax.annotation.Nullable; import javax.validation.Validator; import com.fasterxml.jackson.databind.ObjectMapper; @@ -22,7 +23,7 @@ public class YamlConfigurationFactory extends BaseConfigurationFactory { * @param propertyPrefix the system property name prefix used by overrides */ public YamlConfigurationFactory(Class klass, - Validator validator, + @Nullable Validator validator, ObjectMapper objectMapper, String propertyPrefix) { super(new YAMLFactory(), YAMLFactory.FORMAT_NAME_YAML, klass, validator, objectMapper, propertyPrefix); diff --git a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/BaseConfigurationFactoryTest.java b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/BaseConfigurationFactoryTest.java index 3e783e2bdec..6ac091a5ca6 100644 --- a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/BaseConfigurationFactoryTest.java +++ b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/BaseConfigurationFactoryTest.java @@ -17,6 +17,7 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.io.File; +import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Enumeration; @@ -56,12 +57,12 @@ public static class Example { @NotNull @Pattern(regexp = "[\\w]+[\\s]+[\\w]+([\\s][\\w]+)?") - private String name; + private String name = ""; @JsonProperty private int age = 1; - List type; + List type = ImmutableList.of(); @JsonProperty private Map properties = new LinkedHashMap<>(); @@ -136,14 +137,24 @@ static class NonInsatiableExample { } protected final Validator validator = BaseValidator.newValidator(); - protected ConfigurationFactory factory; - protected File malformedFile; - protected File emptyFile; - protected File invalidFile; - protected File validFile; - protected File typoFile; - protected File wrongTypeFile; - protected File malformedAdvancedFile; + protected ConfigurationFactory factory = new ConfigurationFactory() { + @Override + public Example build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { + return new Example(); + } + + @Override + public Example build() throws IOException, ConfigurationException { + return new Example(); + } + }; + protected File malformedFile = new File("/"); + protected File emptyFile = new File("/"); + protected File invalidFile = new File("/"); + protected File validFile = new File("/"); + protected File typoFile = new File("/"); + protected File wrongTypeFile = new File("/"); + protected File malformedAdvancedFile = new File("/"); protected static File resourceFileName(String resourceName) throws URISyntaxException { return new File(Resources.getResource(resourceName).toURI()); diff --git a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationValidationExceptionTest.java b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationValidationExceptionTest.java index ea343d0eeff..5c2c1c91905 100644 --- a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationValidationExceptionTest.java +++ b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationValidationExceptionTest.java @@ -4,6 +4,7 @@ import org.junit.Before; import org.junit.Test; +import javax.annotation.Nullable; import javax.validation.ConstraintViolation; import javax.validation.Validator; import javax.validation.constraints.NotNull; @@ -17,6 +18,7 @@ public class ConfigurationValidationExceptionTest { private static class Example { @NotNull + @Nullable // Weird combination, but Hibernate Validator is not good with the compile nullable checks String woo; } diff --git a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/SubstitutingSourceProviderTest.java b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/SubstitutingSourceProviderTest.java index 7614eef5353..bad394af45e 100644 --- a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/SubstitutingSourceProviderTest.java +++ b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/SubstitutingSourceProviderTest.java @@ -5,6 +5,7 @@ import org.apache.commons.lang3.text.StrSubstitutor; import org.junit.Test; +import javax.annotation.Nullable; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -42,6 +43,7 @@ public String lookup(String key) { public void shouldSubstituteOnlyExistingVariables() throws IOException { StrLookup dummyLookup = new StrLookup() { @Override + @Nullable public String lookup(String key) { return null; } @@ -56,6 +58,7 @@ public String lookup(String key) { public void shouldSubstituteWithDefaultValue() throws IOException { StrLookup dummyLookup = new StrLookup() { @Override + @Nullable public String lookup(String key) { return null; } @@ -67,7 +70,7 @@ public String lookup(String key) { } private static class DummySourceProvider implements ConfigurationSourceProvider { - public InputStream lastStream; + public InputStream lastStream = new ByteArrayInputStream(new byte[]{}); @Override public InputStream open(String s) throws IOException { diff --git a/dropwizard-core/src/main/java/io/dropwizard/Configuration.java b/dropwizard-core/src/main/java/io/dropwizard/Configuration.java index 7e1c8464e7d..de913ae0210 100644 --- a/dropwizard-core/src/main/java/io/dropwizard/Configuration.java +++ b/dropwizard-core/src/main/java/io/dropwizard/Configuration.java @@ -8,6 +8,7 @@ import io.dropwizard.server.DefaultServerFactory; import io.dropwizard.server.ServerFactory; +import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -65,6 +66,7 @@ public class Configuration { private ServerFactory server = new DefaultServerFactory(); @Valid + @Nullable private LoggingFactory logging; @Valid diff --git a/dropwizard-core/src/main/java/io/dropwizard/cli/Cli.java b/dropwizard-core/src/main/java/io/dropwizard/cli/Cli.java index c29ec0f8469..e28cc33729c 100644 --- a/dropwizard-core/src/main/java/io/dropwizard/cli/Cli.java +++ b/dropwizard-core/src/main/java/io/dropwizard/cli/Cli.java @@ -21,6 +21,8 @@ import java.util.SortedMap; import java.util.TreeMap; +import static java.util.Objects.requireNonNull; + /** * The command-line runner for Dropwizard application. */ @@ -70,7 +72,8 @@ public boolean run(String... arguments) throws Exception { parser.printVersion(stdOut); } else { final Namespace namespace = parser.parseArgs(arguments); - final Command command = commands.get(namespace.getString(COMMAND_NAME_ATTR)); + final Command command = requireNonNull(commands.get(namespace.getString(COMMAND_NAME_ATTR)), + "Command is not found"); try { command.run(bootstrap, namespace); } catch (Throwable e) { diff --git a/dropwizard-core/src/main/java/io/dropwizard/cli/ConfiguredCommand.java b/dropwizard-core/src/main/java/io/dropwizard/cli/ConfiguredCommand.java index d96880b0192..ccb4cbe14b0 100644 --- a/dropwizard-core/src/main/java/io/dropwizard/cli/ConfiguredCommand.java +++ b/dropwizard-core/src/main/java/io/dropwizard/cli/ConfiguredCommand.java @@ -12,6 +12,7 @@ import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; +import javax.annotation.Nullable; import javax.validation.Validator; import java.io.IOException; @@ -26,6 +27,7 @@ public abstract class ConfiguredCommand extends Command { private boolean asynchronous; + @Nullable private T configuration; protected ConfiguredCommand(String name, String description) { diff --git a/dropwizard-core/src/main/java/io/dropwizard/server/AbstractServerFactory.java b/dropwizard-core/src/main/java/io/dropwizard/server/AbstractServerFactory.java index 43fb73b5045..cbc465249b1 100644 --- a/dropwizard-core/src/main/java/io/dropwizard/server/AbstractServerFactory.java +++ b/dropwizard-core/src/main/java/io/dropwizard/server/AbstractServerFactory.java @@ -213,6 +213,7 @@ public abstract class AbstractServerFactory implements ServerFactory { private static final Pattern WINDOWS_NEWLINE = Pattern.compile("\\r\\n?"); @Valid + @Nullable private RequestLogFactory requestLog; @Valid @@ -235,21 +236,29 @@ public abstract class AbstractServerFactory implements ServerFactory { private Duration idleThreadTimeout = Duration.minutes(1); @Min(1) + @Nullable private Integer nofileSoftLimit; @Min(1) + @Nullable private Integer nofileHardLimit; + @Nullable private Integer gid; + @Nullable private Integer uid; + @Nullable private String user; + @Nullable private String group; + @Nullable private String umask; + @Nullable private Boolean startsAsRoot; private Boolean registerDefaultExceptionMappers = Boolean.TRUE; @@ -346,6 +355,7 @@ public void setIdleThreadTimeout(Duration idleThreadTimeout) { } @JsonProperty + @Nullable public Integer getNofileSoftLimit() { return nofileSoftLimit; } @@ -356,6 +366,7 @@ public void setNofileSoftLimit(Integer nofileSoftLimit) { } @JsonProperty + @Nullable public Integer getNofileHardLimit() { return nofileHardLimit; } @@ -366,6 +377,7 @@ public void setNofileHardLimit(Integer nofileHardLimit) { } @JsonProperty + @Nullable public Integer getGid() { return gid; } @@ -376,6 +388,7 @@ public void setGid(Integer gid) { } @JsonProperty + @Nullable public Integer getUid() { return uid; } @@ -386,6 +399,7 @@ public void setUid(Integer uid) { } @JsonProperty + @Nullable public String getUser() { return user; } @@ -396,6 +410,7 @@ public void setUser(String user) { } @JsonProperty + @Nullable public String getGroup() { return group; } @@ -406,6 +421,7 @@ public void setGroup(String group) { } @JsonProperty + @Nullable public String getUmask() { return umask; } @@ -416,6 +432,7 @@ public void setUmask(String umask) { } @JsonProperty + @Nullable public Boolean getStartsAsRoot() { return startsAsRoot; } diff --git a/dropwizard-core/src/main/java/io/dropwizard/setup/Environment.java b/dropwizard-core/src/main/java/io/dropwizard/setup/Environment.java index 0053eb126d9..e26f1b6ef01 100755 --- a/dropwizard-core/src/main/java/io/dropwizard/setup/Environment.java +++ b/dropwizard-core/src/main/java/io/dropwizard/setup/Environment.java @@ -14,6 +14,7 @@ import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; +import javax.annotation.Nullable; import javax.servlet.Servlet; import javax.validation.Validator; import java.util.concurrent.ArrayBlockingQueue; @@ -56,7 +57,7 @@ public Environment(String name, ObjectMapper objectMapper, Validator validator, MetricRegistry metricRegistry, - ClassLoader classLoader, + @Nullable ClassLoader classLoader, HealthCheckRegistry healthCheckRegistry) { this.name = name; this.objectMapper = objectMapper; @@ -107,7 +108,7 @@ public Environment(String name, ObjectMapper objectMapper, Validator validator, MetricRegistry metricRegistry, - ClassLoader classLoader) { + @Nullable ClassLoader classLoader) { this(name, objectMapper, validator, metricRegistry, classLoader, new HealthCheckRegistry()); } @@ -196,6 +197,7 @@ public MutableServletContextHandler getApplicationContext() { return servletContext; } + @Nullable public Servlet getJerseyServletContainer() { return jerseyServletContainer.getContainer(); } diff --git a/dropwizard-core/src/main/java/io/dropwizard/sslreload/SslReloadTask.java b/dropwizard-core/src/main/java/io/dropwizard/sslreload/SslReloadTask.java index e53a19feb29..e8b110cde75 100644 --- a/dropwizard-core/src/main/java/io/dropwizard/sslreload/SslReloadTask.java +++ b/dropwizard-core/src/main/java/io/dropwizard/sslreload/SslReloadTask.java @@ -1,6 +1,7 @@ package io.dropwizard.sslreload; import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableSet; import io.dropwizard.jetty.SslReload; import io.dropwizard.servlets.tasks.Task; import org.eclipse.jetty.util.ssl.SslContextFactory; @@ -10,7 +11,7 @@ /** A task that will refresh all ssl factories with up to date certificate information */ public class SslReloadTask extends Task { - private Collection reloader; + private Collection reloader = ImmutableSet.of(); protected SslReloadTask() { super("reload-ssl"); diff --git a/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java b/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java index 0c90f5bd24b..098f12d03a8 100644 --- a/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java +++ b/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java @@ -8,7 +8,9 @@ import io.dropwizard.validation.MinDuration; import io.dropwizard.validation.ValidationMethod; import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.hibernate.validator.constraints.NotEmpty; +import javax.annotation.Nullable; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @@ -316,8 +318,8 @@ public int get() { } } - @NotNull - private String driverClass = null; + @NotEmpty + private String driverClass = ""; @Min(0) @Max(100) @@ -329,20 +331,25 @@ public int get() { private boolean rollbackOnReturn = false; + @Nullable private Boolean autoCommitByDefault; + @Nullable private Boolean readOnlyByDefault; - private String user = null; + @Nullable + private String user; - private String password = null; + @Nullable + private String password; - @NotNull - private String url = null; + @NotEmpty + private String url = ""; @NotNull private Map properties = new LinkedHashMap<>(); + @Nullable private String defaultCatalog; @NotNull @@ -359,6 +366,7 @@ public int get() { @Min(1) private int maxSize = 100; + @Nullable private String initializationQuery; private boolean logAbandonedConnections = false; @@ -366,6 +374,7 @@ public int get() { private boolean logValidationErrors = false; @MinDuration(value = 1, unit = TimeUnit.SECONDS) + @Nullable private Duration maxConnectionAge; @NotNull @@ -380,6 +389,7 @@ public int get() { private String validationQuery = "/* Health Check */ SELECT 1"; @MinDuration(value = 1, unit = TimeUnit.SECONDS) + @Nullable private Duration validationQueryTimeout; private boolean checkConnectionWhileIdle = true; @@ -433,6 +443,7 @@ public void setDriverClass(String driverClass) { } @JsonProperty + @Nullable public String getUser() { return user; } @@ -443,6 +454,7 @@ public void setUser(String user) { } @JsonProperty + @Nullable public String getPassword() { return password; } @@ -603,6 +615,7 @@ public void setRollbackOnReturn(boolean rollbackOnReturn) { } @JsonProperty + @Nullable public Boolean getAutoCommitByDefault() { return autoCommitByDefault; } @@ -613,6 +626,7 @@ public void setAutoCommitByDefault(Boolean autoCommit) { } @JsonProperty + @Nullable public String getDefaultCatalog() { return defaultCatalog; } @@ -623,6 +637,7 @@ public void setDefaultCatalog(String defaultCatalog) { } @JsonProperty + @Nullable public Boolean getReadOnlyByDefault() { return readOnlyByDefault; } @@ -663,6 +678,7 @@ public void setInitialSize(int initialSize) { } @JsonProperty + @Nullable public String getInitializationQuery() { return initializationQuery; } @@ -855,7 +871,7 @@ public ManagedDataSource build(MetricRegistry metricRegistry, String name) { poolConfig.setMinIdle(minSize); if (getMaxConnectionAge().isPresent()) { - poolConfig.setMaxAge(maxConnectionAge.toMilliseconds()); + poolConfig.setMaxAge(getMaxConnectionAge().get().toMilliseconds()); } poolConfig.setMaxWait((int) maxWaitForConnection.toMilliseconds()); @@ -876,7 +892,7 @@ public ManagedDataSource build(MetricRegistry metricRegistry, String name) { poolConfig.setValidationInterval(validationInterval.toMilliseconds()); if (getValidationQueryTimeout().isPresent()) { - poolConfig.setValidationQueryTimeout((int) validationQueryTimeout.toSeconds()); + poolConfig.setValidationQueryTimeout((int) getValidationQueryTimeout().get().toSeconds()); } validatorClassName.ifPresent(poolConfig::setValidatorClassName); jdbcInterceptors.ifPresent(poolConfig::setJdbcInterceptors); diff --git a/dropwizard-db/src/test/java/io/dropwizard/db/DataSourceFactoryTest.java b/dropwizard-db/src/test/java/io/dropwizard/db/DataSourceFactoryTest.java index 644f8b20d01..a84569f2a27 100644 --- a/dropwizard-db/src/test/java/io/dropwizard/db/DataSourceFactoryTest.java +++ b/dropwizard-db/src/test/java/io/dropwizard/db/DataSourceFactoryTest.java @@ -12,6 +12,7 @@ import org.junit.Before; import org.junit.Test; +import javax.annotation.Nullable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -24,6 +25,8 @@ public class DataSourceFactoryTest { private final MetricRegistry metricRegistry = new MetricRegistry(); private DataSourceFactory factory; + + @Nullable private ManagedDataSource dataSource; @Before diff --git a/dropwizard-forms/src/test/java/io/dropwizard/forms/MultiPartBundleTest.java b/dropwizard-forms/src/test/java/io/dropwizard/forms/MultiPartBundleTest.java index 948a09699d2..e39da3b2c0b 100644 --- a/dropwizard-forms/src/test/java/io/dropwizard/forms/MultiPartBundleTest.java +++ b/dropwizard-forms/src/test/java/io/dropwizard/forms/MultiPartBundleTest.java @@ -2,20 +2,25 @@ import com.codahale.metrics.MetricRegistry; import io.dropwizard.jackson.Jackson; +import io.dropwizard.logging.BootstrapLogging; import io.dropwizard.setup.Environment; +import io.dropwizard.validation.BaseValidator; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MultiPartBundleTest { + static { + BootstrapLogging.bootstrap(); + } @Test public void testRun() throws Exception { final Environment environment = new Environment( "multipart-test", Jackson.newObjectMapper(), - null, + BaseValidator.newValidator(), new MetricRegistry(), getClass().getClassLoader() ); @@ -24,4 +29,4 @@ public void testRun() throws Exception { assertThat(environment.jersey().getResourceConfig().getClasses()).contains(MultiPartFeature.class); } -} \ No newline at end of file +} diff --git a/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/HibernateBundle.java b/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/HibernateBundle.java index 4989aabf3f3..13428c40361 100644 --- a/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/HibernateBundle.java +++ b/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/HibernateBundle.java @@ -12,9 +12,14 @@ import io.dropwizard.util.Duration; import org.hibernate.SessionFactory; +import javax.annotation.Nullable; + +import static java.util.Objects.requireNonNull; + public abstract class HibernateBundle implements ConfiguredBundle, DatabaseConfiguration { public static final String DEFAULT_NAME = "hibernate"; + @Nullable private SessionFactory sessionFactory; private boolean lazyLoadingEnabled = true; @@ -59,7 +64,8 @@ protected String name() { @Override public final void run(T configuration, Environment environment) throws Exception { final PooledDataSourceFactory dbConfig = getDataSourceFactory(configuration); - this.sessionFactory = sessionFactoryFactory.build(this, environment, dbConfig, entities, name()); + this.sessionFactory = requireNonNull(sessionFactoryFactory.build(this, environment, dbConfig, + entities, name())); registerUnitOfWorkListerIfAbsent(environment).registerSessionFactory(name(), sessionFactory); environment.healthChecks().register(name(), new SessionFactoryHealthCheck( @@ -89,7 +95,7 @@ public void setLazyLoadingEnabled(boolean lazyLoadingEnabled) { } public SessionFactory getSessionFactory() { - return sessionFactory; + return requireNonNull(sessionFactory); } protected void configure(org.hibernate.cfg.Configuration configuration) { diff --git a/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWorkAspect.java b/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWorkAspect.java index aaea86b8767..0c37ea4b884 100644 --- a/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWorkAspect.java +++ b/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWorkAspect.java @@ -5,8 +5,12 @@ import org.hibernate.Transaction; import org.hibernate.context.internal.ManagedSessionContext; +import javax.annotation.Nullable; import java.util.Map; +import static com.google.common.base.Preconditions.checkNotNull; +import static java.util.Objects.requireNonNull; + /** * An aspect providing operations around a method with the {@link UnitOfWork} annotation. * It opens a Hibernate session and optionally a transaction. @@ -40,11 +44,16 @@ public UnitOfWorkAspect(Map sessionFactories) { } // Context variables + @Nullable private UnitOfWork unitOfWork; + + @Nullable private Session session; + + @Nullable private SessionFactory sessionFactory; - public void beforeStart(UnitOfWork unitOfWork) { + public void beforeStart(@Nullable UnitOfWork unitOfWork) { if (unitOfWork == null) { return; } @@ -64,7 +73,7 @@ public void beforeStart(UnitOfWork unitOfWork) { try { configureSession(); ManagedSessionContext.bind(session); - beginTransaction(); + beginTransaction(unitOfWork, session); } catch (Throwable th) { session.close(); session = null; @@ -74,14 +83,14 @@ public void beforeStart(UnitOfWork unitOfWork) { } public void afterEnd() { - if (session == null) { + if (unitOfWork == null || session == null) { return; } try { - commitTransaction(); + commitTransaction(unitOfWork, session); } catch (Exception e) { - rollbackTransaction(); + rollbackTransaction(unitOfWork, session); throw e; } // We should not close the session to let the lazy loading work during serializing a response to the client. @@ -89,12 +98,12 @@ public void afterEnd() { } public void onError() { - if (session == null) { + if (unitOfWork == null || session == null) { return; } try { - rollbackTransaction(); + rollbackTransaction(unitOfWork, session); } finally { onFinish(); } @@ -112,19 +121,21 @@ public void onFinish() { } protected void configureSession() { + checkNotNull(unitOfWork); + checkNotNull(session); session.setDefaultReadOnly(unitOfWork.readOnly()); session.setCacheMode(unitOfWork.cacheMode()); session.setHibernateFlushMode(unitOfWork.flushMode()); } - private void beginTransaction() { + private void beginTransaction(UnitOfWork unitOfWork, Session session) { if (!unitOfWork.transactional()) { return; } session.beginTransaction(); } - private void rollbackTransaction() { + private void rollbackTransaction(UnitOfWork unitOfWork, Session session) { if (!unitOfWork.transactional()) { return; } @@ -134,7 +145,7 @@ private void rollbackTransaction() { } } - private void commitTransaction() { + private void commitTransaction(UnitOfWork unitOfWork, Session session) { if (!unitOfWork.transactional()) { return; } @@ -145,11 +156,11 @@ private void commitTransaction() { } protected Session getSession() { - return session; + return requireNonNull(session); } protected SessionFactory getSessionFactory() { - return sessionFactory; + return requireNonNull(sessionFactory); } } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Dog.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Dog.java index c713021063f..a0bbbb8d6df 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Dog.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Dog.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.Nullable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; @@ -13,13 +14,16 @@ @Table(name = "dogs") public class Dog { @Id + @Nullable private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "owner") + @Nullable private Person owner; @JsonProperty + @Nullable public String getName() { return name; } @@ -30,6 +34,7 @@ public void setName(String name) { } @JsonProperty + @Nullable public Person getOwner() { return owner; } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/JerseyIntegrationTest.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/JerseyIntegrationTest.java index e549f64832b..b6d32247635 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/JerseyIntegrationTest.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/JerseyIntegrationTest.java @@ -22,6 +22,7 @@ import org.junit.After; import org.junit.Test; +import javax.annotation.Nullable; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; @@ -82,6 +83,7 @@ public void save(Person person) { } } + @Nullable private SessionFactory sessionFactory; @Override diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/LazyLoadingTest.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/LazyLoadingTest.java index 95ddfa5bedd..946ba54c7a8 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/LazyLoadingTest.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/LazyLoadingTest.java @@ -23,10 +23,10 @@ import org.junit.Test; import javax.ws.rs.GET; +import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; -import javax.ws.rs.PUT; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; @@ -37,6 +37,7 @@ import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; public class LazyLoadingTest { @@ -150,7 +151,7 @@ public Response toResponse(ConstraintViolationException e) { } } - private DropwizardTestSupport dropwizardTestSupport; + private DropwizardTestSupport dropwizardTestSupport = mock(DropwizardTestSupport.class); private Client client = new JerseyClientBuilder().build(); public void setup(Class> applicationClass) { @@ -181,7 +182,7 @@ public void serialisesLazyObjectWhenEnabled() throws Exception { assertThat(raf.getOwner()) .isNotNull(); - assertThat(raf.getOwner().getName()) + assertThat(requireNonNull(raf.getOwner()).getName()) .isEqualTo("Coda"); } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/PersistenceExceptionMapper.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/PersistenceExceptionMapper.java index 1f0f7336d3d..c164583866a 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/PersistenceExceptionMapper.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/PersistenceExceptionMapper.java @@ -5,6 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import javax.persistence.PersistenceException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; @@ -12,12 +13,15 @@ import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; +import static java.util.Objects.requireNonNull; + @Provider public class PersistenceExceptionMapper implements ExtendedExceptionMapper { private static final Logger LOGGER = LoggerFactory.getLogger(DataException.class); @Context + @Nullable private Providers providers; @Override @@ -30,13 +34,14 @@ public Response toResponse(PersistenceException e) { // Cast is necessary since the return type is ExceptionMapper and Java // does not allow calling toResponse on the method with a Throwable @SuppressWarnings("unchecked") - final ExceptionMapper exceptionMapper = (ExceptionMapper) providers.getExceptionMapper(t.getClass()); + final ExceptionMapper exceptionMapper = (ExceptionMapper) + requireNonNull(providers).getExceptionMapper(t.getClass()); return exceptionMapper.toResponse(t); } @Override public boolean isMappable(PersistenceException e) { - return providers.getExceptionMapper(e.getCause().getClass()) != null; + return requireNonNull(providers).getExceptionMapper(e.getCause().getClass()) != null; } } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Person.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Person.java index 478462b0a08..b3b8abe8980 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Person.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/Person.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTime; +import javax.annotation.Nullable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -12,15 +13,17 @@ @Table(name = "people") public class Person { @Id - private String name; + private String name = ""; @Column - private String email; + private String email = ""; @Column + @Nullable private DateTime birthday; @JsonProperty + @Nullable public String getName() { return name; } @@ -41,6 +44,7 @@ public void setEmail(String email) { } @JsonProperty + @Nullable public DateTime getBirthday() { return birthday; } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SessionFactoryFactoryTest.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SessionFactoryFactoryTest.java index 3412fa9c19b..a709b43caf0 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SessionFactoryFactoryTest.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SessionFactoryFactoryTest.java @@ -21,6 +21,9 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; +import javax.annotation.Nullable; + +import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; @@ -39,7 +42,9 @@ public class SessionFactoryFactoryTest { private final Environment environment = mock(Environment.class); private final MetricRegistry metricRegistry = new MetricRegistry(); - private DataSourceFactory config; + private DataSourceFactory config = new DataSourceFactory(); + + @Nullable private SessionFactory sessionFactory; @Before @@ -47,7 +52,6 @@ public void setUp() throws Exception { when(environment.metrics()).thenReturn(metricRegistry); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); - config = new DataSourceFactory(); config.setUrl("jdbc:hsqldb:mem:DbTest-" + System.currentTimeMillis()); config.setUser("sa"); config.setDriverClass("org.hsqldb.jdbcDriver"); @@ -105,7 +109,7 @@ public void setsACustomPoolName() { public void buildsAWorkingSessionFactory() throws Exception { build(); - try (Session session = sessionFactory.openSession()) { + try (Session session = requireNonNull(sessionFactory).openSession()) { Transaction transaction = session.beginTransaction(); session.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate(); session.createNativeQuery("CREATE TABLE people (name varchar(100) primary key, email varchar(100), birthday timestamp(0))").executeUpdate(); @@ -120,7 +124,7 @@ public void buildsAWorkingSessionFactory() throws Exception { assertThat(entity.getEmail()) .isEqualTo("coda@example.com"); - assertThat(entity.getBirthday().toDateTime(DateTimeZone.UTC)) + assertThat(requireNonNull(entity.getBirthday()).toDateTime(DateTimeZone.UTC)) .isEqualTo(new DateTime(1979, 1, 2, 0, 22, DateTimeZone.UTC)); } } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SubResourcesTest.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SubResourcesTest.java index f74bf4c084a..900e856412e 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SubResourcesTest.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SubResourcesTest.java @@ -16,9 +16,9 @@ import org.junit.Test; import javax.ws.rs.GET; +import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; -import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Entity; @@ -27,6 +27,7 @@ import java.util.List; import java.util.Optional; +import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; public class SubResourcesTest { @@ -212,7 +213,7 @@ public void canReadFromSubResources() throws Exception { assertThat(dog.getName()).isEqualTo("Bello"); assertThat(dog.getOwner()).isNotNull(); - assertThat(dog.getOwner().getName()).isEqualTo("Greg"); + assertThat(requireNonNull(dog.getOwner()).getName()).isEqualTo("Greg"); } @Test @@ -224,7 +225,7 @@ public void canWriteSubResource() throws Exception { assertThat(dog.getName()).isEqualTo("Bandit"); assertThat(dog.getOwner()).isNotNull(); - assertThat(dog.getOwner().getName()).isEqualTo("Greg"); + assertThat(requireNonNull(dog.getOwner()).getName()).isEqualTo("Greg"); } @Test diff --git a/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2CConnectorFactory.java b/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2CConnectorFactory.java index 85b99356fd5..5642d284eaa 100644 --- a/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2CConnectorFactory.java +++ b/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2CConnectorFactory.java @@ -15,6 +15,7 @@ import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.eclipse.jetty.util.thread.ThreadPool; +import javax.annotation.Nullable; import javax.validation.constraints.Max; import javax.validation.constraints.Min; @@ -81,7 +82,7 @@ public void setInitialStreamRecvWindow(int initialStreamRecvWindow) { } @Override - public Connector build(Server server, MetricRegistry metrics, String name, ThreadPool threadPool) { + public Connector build(Server server, MetricRegistry metrics, String name, @Nullable ThreadPool threadPool) { // Prepare connection factories for HTTP/2c final HttpConfiguration httpConfig = buildHttpConfiguration(); diff --git a/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2ConnectorFactory.java b/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2ConnectorFactory.java index 31d6c1dc26c..363a9c93707 100644 --- a/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2ConnectorFactory.java +++ b/dropwizard-http2/src/main/java/io/dropwizard/http2/Http2ConnectorFactory.java @@ -20,6 +20,7 @@ import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.eclipse.jetty.util.thread.ThreadPool; +import javax.annotation.Nullable; import javax.validation.constraints.Max; import javax.validation.constraints.Min; @@ -95,7 +96,7 @@ public void setInitialStreamRecvWindow(int initialStreamRecvWindow) { } @Override - public Connector build(Server server, MetricRegistry metrics, String name, ThreadPool threadPool) { + public Connector build(Server server, MetricRegistry metrics, String name, @Nullable ThreadPool threadPool) { // HTTP/2 requires that a server MUST support TLSv1.2 and TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 cipher // See http://http2.github.io/http2-spec/index.html#rfc.section.9.2.2 setSupportedProtocols(ImmutableList.of("TLSv1.2")); diff --git a/dropwizard-jackson/src/main/java/io/dropwizard/jackson/FuzzyEnumModule.java b/dropwizard-jackson/src/main/java/io/dropwizard/jackson/FuzzyEnumModule.java index ac176dcf30d..b1a60cda587 100644 --- a/dropwizard-jackson/src/main/java/io/dropwizard/jackson/FuzzyEnumModule.java +++ b/dropwizard-jackson/src/main/java/io/dropwizard/jackson/FuzzyEnumModule.java @@ -15,6 +15,7 @@ import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import io.dropwizard.util.Enums; +import javax.annotation.Nullable; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; @@ -62,6 +63,7 @@ public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IO private static class PermissiveEnumDeserializers extends Deserializers.Base { @Override @SuppressWarnings("unchecked") + @Nullable public JsonDeserializer findEnumDeserializer(Class type, DeserializationConfig config, BeanDescription desc) throws JsonMappingException { diff --git a/dropwizard-jackson/src/main/java/io/dropwizard/jackson/Jackson.java b/dropwizard-jackson/src/main/java/io/dropwizard/jackson/Jackson.java index 0e74c3094a3..7373761ecfd 100644 --- a/dropwizard-jackson/src/main/java/io/dropwizard/jackson/Jackson.java +++ b/dropwizard-jackson/src/main/java/io/dropwizard/jackson/Jackson.java @@ -9,6 +9,8 @@ import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; +import javax.annotation.Nullable; + /** * A utility class for Jackson. */ @@ -33,7 +35,7 @@ public static ObjectMapper newObjectMapper() { * @param jsonFactory instance of {@link com.fasterxml.jackson.core.JsonFactory} to use * for the created {@link com.fasterxml.jackson.databind.ObjectMapper} instance. */ - public static ObjectMapper newObjectMapper(JsonFactory jsonFactory) { + public static ObjectMapper newObjectMapper(@Nullable JsonFactory jsonFactory) { final ObjectMapper mapper = new ObjectMapper(jsonFactory); return configure(mapper); diff --git a/dropwizard-jackson/src/test/java/io/dropwizard/jackson/AnnotationSensitivePropertyNamingStrategyTest.java b/dropwizard-jackson/src/test/java/io/dropwizard/jackson/AnnotationSensitivePropertyNamingStrategyTest.java index b95adb36123..79f25e3271a 100644 --- a/dropwizard-jackson/src/test/java/io/dropwizard/jackson/AnnotationSensitivePropertyNamingStrategyTest.java +++ b/dropwizard-jackson/src/test/java/io/dropwizard/jackson/AnnotationSensitivePropertyNamingStrategyTest.java @@ -6,11 +6,14 @@ import org.junit.Before; import org.junit.Test; +import javax.annotation.Nullable; + import static org.assertj.core.api.Assertions.assertThat; public class AnnotationSensitivePropertyNamingStrategyTest { public static class RegularExample { @JsonProperty + @Nullable String firstName; @SuppressWarnings("UnusedDeclaration") // Jackson @@ -24,6 +27,7 @@ public RegularExample(String firstName) { @JsonSnakeCase public static class SnakeCaseExample { @JsonProperty + @Nullable String firstName; @SuppressWarnings("UnusedDeclaration") // Jackson diff --git a/dropwizard-jackson/src/test/java/io/dropwizard/jackson/Issue1627.java b/dropwizard-jackson/src/test/java/io/dropwizard/jackson/Issue1627.java index 022161e3a58..4192e11ae5f 100644 --- a/dropwizard-jackson/src/test/java/io/dropwizard/jackson/Issue1627.java +++ b/dropwizard-jackson/src/test/java/io/dropwizard/jackson/Issue1627.java @@ -2,23 +2,30 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.Nullable; import java.util.UUID; public class Issue1627 { + + @Nullable private final String string; + + @Nullable private final UUID uuid; - public Issue1627(final String string, final UUID uuid) { + public Issue1627(@Nullable String string, @Nullable UUID uuid) { this.string = string; this.uuid = uuid; } @JsonProperty + @Nullable public String getString() { return this.string; } @JsonProperty + @Nullable public UUID getUuid() { return this.uuid; } diff --git a/dropwizard-jackson/src/test/java/io/dropwizard/jackson/JacksonTest.java b/dropwizard-jackson/src/test/java/io/dropwizard/jackson/JacksonTest.java index 1f7f509901d..313393e90db 100644 --- a/dropwizard-jackson/src/test/java/io/dropwizard/jackson/JacksonTest.java +++ b/dropwizard-jackson/src/test/java/io/dropwizard/jackson/JacksonTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import org.mockito.Mockito; +import javax.annotation.Nullable; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @@ -47,6 +48,7 @@ public void objectMapperSerializesNullValues() throws IOException { static class LogMetadata { + @Nullable public Path path; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantArgument.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantArgument.java index a2257c3f9fd..218fac710da 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantArgument.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantArgument.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; +import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -15,10 +16,12 @@ * An {@link Argument} for {@link Instant} objects. */ public class InstantArgument implements Argument { + + @Nullable private final Instant instant; private final Optional calendar; - protected InstantArgument(final Instant instant, final Optional calendar) { + protected InstantArgument(@Nullable final Instant instant, final Optional calendar) { this.instant = instant; this.calendar = calendar; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantMapper.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantMapper.java index e8daf376348..19df23cf51c 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantMapper.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantMapper.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultColumnMapper; +import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -34,6 +35,7 @@ public InstantMapper(final Optional tz) { } @Override + @Nullable public Instant mapColumn(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnNumber, cloneCalendar()) : @@ -42,6 +44,7 @@ public Instant mapColumn(ResultSet r, int columnNumber, StatementContext ctx) th } @Override + @Nullable public Instant mapColumn(ResultSet r, String columnLabel, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnLabel, cloneCalendar()) : diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeArgument.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeArgument.java index 89cdc8d3cdb..980c0a76512 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeArgument.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeArgument.java @@ -4,6 +4,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; +import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -16,10 +17,11 @@ */ public class JodaDateTimeArgument implements Argument { + @Nullable private final DateTime value; private final Optional calendar; - JodaDateTimeArgument(final DateTime value, final Optional calendar) { + JodaDateTimeArgument(@Nullable final DateTime value, final Optional calendar) { this.value = value; this.calendar = calendar; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeMapper.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeMapper.java index 77b133ee93e..40974b266f7 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeMapper.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/JodaDateTimeMapper.java @@ -4,6 +4,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultColumnMapper; +import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -50,6 +51,7 @@ private Calendar cloneCalendar() { } @Override + @Nullable public DateTime mapColumn(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnNumber, cloneCalendar()) : r.getTimestamp(columnNumber); @@ -59,6 +61,7 @@ public DateTime mapColumn(ResultSet r, int columnNumber, StatementContext ctx) t return new DateTime(timestamp.getTime()); } @Override + @Nullable public DateTime mapColumn(ResultSet r, String columnLabel, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnLabel, cloneCalendar()) : r.getTimestamp(columnLabel); diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateArgument.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateArgument.java index a2d64af99a7..819c07788e9 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateArgument.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateArgument.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; +import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -14,9 +15,10 @@ */ public class LocalDateArgument implements Argument { + @Nullable private final LocalDate value; - public LocalDateArgument(LocalDate value) { + public LocalDateArgument(@Nullable LocalDate value) { this.value = value; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateMapper.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateMapper.java index c48a2b533d7..cc830a79455 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateMapper.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateMapper.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultColumnMapper; +import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -13,6 +14,7 @@ */ public class LocalDateMapper implements ResultColumnMapper { @Override + @Nullable public LocalDate mapColumn(ResultSet r, String columnLabel, StatementContext ctx) throws SQLException { final Timestamp timestamp = r.getTimestamp(columnLabel); if (timestamp == null) { @@ -22,6 +24,7 @@ public LocalDate mapColumn(ResultSet r, String columnLabel, StatementContext ctx } @Override + @Nullable public LocalDate mapColumn(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException { final Timestamp timestamp = r.getTimestamp(columnNumber); if (timestamp == null) { diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeArgument.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeArgument.java index 7ea7fc7d1b9..c7c245321cb 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeArgument.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeArgument.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; +import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -14,9 +15,10 @@ */ public class LocalDateTimeArgument implements Argument { + @Nullable private final LocalDateTime value; - LocalDateTimeArgument(final LocalDateTime value) { + LocalDateTimeArgument(@Nullable final LocalDateTime value) { this.value = value; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeMapper.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeMapper.java index 5462f6adc5a..00a4e7dd95b 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeMapper.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/LocalDateTimeMapper.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultColumnMapper; +import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -14,6 +15,7 @@ public class LocalDateTimeMapper implements ResultColumnMapper { @Override + @Nullable public LocalDateTime mapColumn(ResultSet r, String columnLabel, StatementContext ctx) throws SQLException { final Timestamp timestamp = r.getTimestamp(columnLabel); if (timestamp == null) { @@ -23,6 +25,7 @@ public LocalDateTime mapColumn(ResultSet r, String columnLabel, StatementContext } @Override + @Nullable public LocalDateTime mapColumn(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException { final Timestamp timestamp = r.getTimestamp(columnNumber); if (timestamp == null) { diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeArgument.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeArgument.java index c63cfdcedd1..c68ef8ee2b9 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeArgument.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeArgument.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; +import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -16,10 +17,11 @@ */ public class OffsetDateTimeArgument implements Argument { + @Nullable private final OffsetDateTime value; private final Optional calendar; - OffsetDateTimeArgument(final OffsetDateTime value, final Optional calendar) { + OffsetDateTimeArgument(@Nullable final OffsetDateTime value, final Optional calendar) { this.value = value; this.calendar = calendar; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeMapper.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeMapper.java index 90cfe4a7e07..918df137981 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeMapper.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/OffsetDateTimeMapper.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultColumnMapper; +import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -52,6 +53,7 @@ private Calendar cloneCalendar() { } @Override + @Nullable public OffsetDateTime mapColumn(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnNumber, cloneCalendar()) : r.getTimestamp(columnNumber); @@ -59,12 +61,14 @@ public OffsetDateTime mapColumn(ResultSet r, int columnNumber, StatementContext } @Override + @Nullable public OffsetDateTime mapColumn(ResultSet r, String columnLabel, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnLabel, cloneCalendar()) : r.getTimestamp(columnLabel); return convertToOffsetDateTime(timestamp); } + @Nullable private OffsetDateTime convertToOffsetDateTime(Timestamp timestamp) { if (timestamp == null) { return null; diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeArgument.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeArgument.java index d8dc43fe9d8..d60f04ad4c8 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeArgument.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeArgument.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; +import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -16,10 +17,11 @@ */ public class ZonedDateTimeArgument implements Argument { + @Nullable private final ZonedDateTime value; private final Optional calendar; - ZonedDateTimeArgument(final ZonedDateTime value, final Optional calendar) { + ZonedDateTimeArgument(@Nullable final ZonedDateTime value, final Optional calendar) { this.value = value; this.calendar = calendar; } diff --git a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeMapper.java b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeMapper.java index a38a6cf6074..5a34a69e3dc 100644 --- a/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeMapper.java +++ b/dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/ZonedDateTimeMapper.java @@ -3,6 +3,7 @@ import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultColumnMapper; +import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; @@ -52,6 +53,7 @@ private Calendar cloneCalendar() { } @Override + @Nullable public ZonedDateTime mapColumn(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnNumber, cloneCalendar()) : r.getTimestamp(columnNumber); @@ -59,12 +61,14 @@ public ZonedDateTime mapColumn(ResultSet r, int columnNumber, StatementContext c } @Override + @Nullable public ZonedDateTime mapColumn(ResultSet r, String columnLabel, StatementContext ctx) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(columnLabel, cloneCalendar()) : r.getTimestamp(columnLabel); return convertToZonedDateTime(timestamp); } + @Nullable private ZonedDateTime convertToZonedDateTime(Timestamp timestamp) { if (timestamp == null) { return null; diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/GuavaJDBITest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/GuavaJDBITest.java index e80d2a923b7..ad7e0ce9aa7 100755 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/GuavaJDBITest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/GuavaJDBITest.java @@ -48,7 +48,7 @@ public class GuavaJDBITest { private final DBIFactory factory = new DBIFactory(); private final List managed = new ArrayList<>(); private final MetricRegistry metricRegistry = new MetricRegistry(); - private DBI dbi; + private DBI dbi = mock(DBI.class); @Before public void setUp() throws Exception { @@ -102,7 +102,6 @@ public void tearDown() throws Exception { for (Managed obj : managed) { obj.stop(); } - this.dbi = null; } @Test diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/JDBITest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/JDBITest.java index da8e8d68f16..c05c240542c 100755 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/JDBITest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/JDBITest.java @@ -48,7 +48,7 @@ public class JDBITest { private final DBIFactory factory = new DBIFactory(); private final List managed = new ArrayList<>(); private final MetricRegistry metricRegistry = new MetricRegistry(); - private DBI dbi; + private DBI dbi = mock(DBI.class); @Before public void setUp() throws Exception { @@ -102,7 +102,6 @@ public void tearDown() throws Exception { for (Managed obj : managed) { obj.stop(); } - this.dbi = null; } @Test diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/InstantMapperTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/InstantMapperTest.java index 87b9c77f284..f652fbd3bf7 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/InstantMapperTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/InstantMapperTest.java @@ -2,6 +2,7 @@ import org.junit.Test; import org.mockito.Mockito; +import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.Timestamp; @@ -10,11 +11,13 @@ import java.time.ZonedDateTime; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class InstantMapperTest { private final ResultSet resultSet = Mockito.mock(ResultSet.class); + private final StatementContext ctx = mock(StatementContext.class); @Test public void mapColumnByName() throws Exception { @@ -22,7 +25,7 @@ public void mapColumnByName() throws Exception { ZonedDateTime stored = expected.withZoneSameInstant(ZoneId.systemDefault()); when(resultSet.getTimestamp("instant")).thenReturn(Timestamp.from(stored.toInstant())); - Instant actual = new InstantMapper().mapColumn(resultSet, "instant", null); + Instant actual = new InstantMapper().mapColumn(resultSet, "instant", ctx); assertThat(actual).isEqualTo(expected.toInstant()); } @@ -31,7 +34,7 @@ public void mapColumnByName() throws Exception { public void mapColumnByName_TimestampIsNull() throws Exception { when(resultSet.getTimestamp("instant")).thenReturn(null); - Instant actual = new InstantMapper().mapColumn(resultSet, "instant", null); + Instant actual = new InstantMapper().mapColumn(resultSet, "instant", ctx); assertThat(actual).isNull(); } @@ -42,7 +45,7 @@ public void mapColumnByIndex() throws Exception { ZonedDateTime stored = expected.withZoneSameInstant(ZoneId.systemDefault()); when(resultSet.getTimestamp(1)).thenReturn(Timestamp.from(stored.toInstant())); - Instant actual = new InstantMapper().mapColumn(resultSet, 1, null); + Instant actual = new InstantMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isEqualTo(expected.toInstant()); } @@ -51,7 +54,7 @@ public void mapColumnByIndex() throws Exception { public void mapColumnByIndex_TimestampIsNull() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(null); - Instant actual = new InstantMapper().mapColumn(resultSet, 1, null); + Instant actual = new InstantMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isNull(); } diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/JodaDateTimeMapperTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/JodaDateTimeMapperTest.java index 49b8f9b5801..817734ddddd 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/JodaDateTimeMapperTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/JodaDateTimeMapperTest.java @@ -3,22 +3,25 @@ import org.joda.time.DateTime; import org.junit.Test; import org.mockito.Mockito; +import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JodaDateTimeMapperTest { - private final ResultSet resultSet = Mockito.mock(ResultSet.class); + private final ResultSet resultSet = mock(ResultSet.class); + private final StatementContext ctx = mock(StatementContext.class); @Test public void mapColumnByName() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(Timestamp.valueOf("2007-12-03 10:15:30.375")); - DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, "name", null); + DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isEqualTo(DateTime.parse("2007-12-03T10:15:30.375")); } @@ -27,7 +30,7 @@ public void mapColumnByName() throws Exception { public void mapColumnByName_TimestampIsNull() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(null); - DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, "name", null); + DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isNull(); } @@ -36,7 +39,7 @@ public void mapColumnByName_TimestampIsNull() throws Exception { public void mapColumnByIndex() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(Timestamp.valueOf("2007-12-03 10:15:30.375")); - DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, 1, null); + DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isEqualTo(DateTime.parse("2007-12-03T10:15:30.375")); } @@ -45,7 +48,7 @@ public void mapColumnByIndex() throws Exception { public void mapColumnByIndex_TimestampIsNull() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(null); - DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, 1, null); + DateTime actual = new JodaDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isNull(); } diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateMapperTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateMapperTest.java index 0c3090bc637..3b1a9535182 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateMapperTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateMapperTest.java @@ -1,24 +1,26 @@ package io.dropwizard.jdbi.args; import org.junit.Test; -import org.mockito.Mockito; +import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.Timestamp; import java.time.LocalDate; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LocalDateMapperTest { - private final ResultSet resultSet = Mockito.mock(ResultSet.class); + private final ResultSet resultSet = mock(ResultSet.class); + private final StatementContext ctx = mock(StatementContext.class); @Test public void mapColumnByName() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(Timestamp.valueOf("2007-12-03 00:00:00.000")); - LocalDate actual = new LocalDateMapper().mapColumn(resultSet, "name", null); + LocalDate actual = new LocalDateMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isEqualTo(LocalDate.parse("2007-12-03")); } @@ -27,7 +29,7 @@ public void mapColumnByName() throws Exception { public void mapColumnByName_TimestampIsNull() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(null); - LocalDate actual = new LocalDateMapper().mapColumn(resultSet, "name", null); + LocalDate actual = new LocalDateMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isNull(); } @@ -36,7 +38,7 @@ public void mapColumnByName_TimestampIsNull() throws Exception { public void mapColumnByIndex() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(Timestamp.valueOf("2007-12-03 00:00:00.000")); - LocalDate actual = new LocalDateMapper().mapColumn(resultSet, 1, null); + LocalDate actual = new LocalDateMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isEqualTo(LocalDate.parse("2007-12-03")); } @@ -45,7 +47,7 @@ public void mapColumnByIndex() throws Exception { public void mapColumnByIndex_TimestampIsNull() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(null); - LocalDate actual = new LocalDateMapper().mapColumn(resultSet, 1, null); + LocalDate actual = new LocalDateMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isNull(); } diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateTimeMapperTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateTimeMapperTest.java index 7d9607f11cc..392daf08253 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateTimeMapperTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/LocalDateTimeMapperTest.java @@ -1,24 +1,26 @@ package io.dropwizard.jdbi.args; import org.junit.Test; -import org.mockito.Mockito; +import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.Timestamp; import java.time.LocalDateTime; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LocalDateTimeMapperTest { - private final ResultSet resultSet = Mockito.mock(ResultSet.class); + private final ResultSet resultSet = mock(ResultSet.class); + private final StatementContext ctx = mock(StatementContext.class); @Test public void mapColumnByName() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(Timestamp.valueOf("2007-12-03 10:15:30.375")); - LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, "name", null); + LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isEqualTo(LocalDateTime.parse("2007-12-03T10:15:30.375")); } @@ -27,7 +29,7 @@ public void mapColumnByName() throws Exception { public void mapColumnByName_TimestampIsNull() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(null); - LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, "name", null); + LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isNull(); } @@ -36,7 +38,7 @@ public void mapColumnByName_TimestampIsNull() throws Exception { public void mapColumnByIndex() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(Timestamp.valueOf("2007-12-03 10:15:30.375")); - LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, 1, null); + LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isEqualTo(LocalDateTime.parse("2007-12-03T10:15:30.375")); } @@ -45,7 +47,7 @@ public void mapColumnByIndex() throws Exception { public void mapColumnByIndex_TimestampIsNull() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(null); - LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, 1, null); + LocalDateTime actual = new LocalDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isNull(); } diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/OffsetDateTimeMapperTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/OffsetDateTimeMapperTest.java index 71fd76eee05..630a24c523c 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/OffsetDateTimeMapperTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/OffsetDateTimeMapperTest.java @@ -2,6 +2,7 @@ import org.junit.Test; import org.mockito.Mockito; +import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.Timestamp; @@ -10,11 +11,13 @@ import java.time.ZoneId; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class OffsetDateTimeMapperTest { - private final ResultSet resultSet = Mockito.mock(ResultSet.class); + private final ResultSet resultSet = mock(ResultSet.class); + private final StatementContext ctx = mock(StatementContext.class); @Test public void mapColumnByName() throws Exception { @@ -22,7 +25,7 @@ public void mapColumnByName() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(Timestamp.from(now)); - OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, "name", null); + OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isEqualTo(OffsetDateTime.ofInstant(now, ZoneId.systemDefault())); } @@ -31,7 +34,7 @@ public void mapColumnByName() throws Exception { public void mapColumnByName_TimestampIsNull() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(null); - OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, "name", null); + OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isNull(); } @@ -42,7 +45,7 @@ public void mapColumnByIndex() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(Timestamp.from(now)); - OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, 1, null); + OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isEqualTo(OffsetDateTime.ofInstant(now, ZoneId.systemDefault())); } @@ -51,7 +54,7 @@ public void mapColumnByIndex() throws Exception { public void mapColumnByIndex_TimestampIsNull() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(null); - OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, 1, null); + OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isNull(); } diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/ZonedDateTimeMapperTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/ZonedDateTimeMapperTest.java index 227c34a6919..98677c31d82 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/ZonedDateTimeMapperTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/args/ZonedDateTimeMapperTest.java @@ -2,6 +2,7 @@ import org.junit.Test; import org.mockito.Mockito; +import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.Timestamp; @@ -9,17 +10,19 @@ import java.time.ZonedDateTime; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ZonedDateTimeMapperTest { - private final ResultSet resultSet = Mockito.mock(ResultSet.class); + private final ResultSet resultSet = mock(ResultSet.class); + private final StatementContext ctx = mock(StatementContext.class); @Test public void mapColumnByName() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(Timestamp.valueOf("2007-12-03 10:15:30.375")); - ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, "name", null); + ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isEqualTo(ZonedDateTime.of(2007, 12, 3, 10, 15, 30, 375_000_000, ZoneId.systemDefault())); } @@ -28,7 +31,7 @@ public void mapColumnByName() throws Exception { public void mapColumnByName_TimestampIsNull() throws Exception { when(resultSet.getTimestamp("name")).thenReturn(null); - ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, "name", null); + ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, "name", ctx); assertThat(actual).isNull(); } @@ -37,7 +40,7 @@ public void mapColumnByName_TimestampIsNull() throws Exception { public void mapColumnByIndex() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(Timestamp.valueOf("2007-12-03 10:15:30.375")); - ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, 1, null); + ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isEqualTo(ZonedDateTime.of(2007, 12, 3, 10, 15, 30, 375_000_000, ZoneId.systemDefault())); } @@ -46,7 +49,7 @@ public void mapColumnByIndex() throws Exception { public void mapColumnByIndex_TimestampIsNull() throws Exception { when(resultSet.getTimestamp(1)).thenReturn(null); - ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, 1, null); + ZonedDateTime actual = new ZonedDateTimeMapper().mapColumn(resultSet, 1, ctx); assertThat(actual).isNull(); } diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DBIClient.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DBIClient.java index abf137b8134..2484dd0347d 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DBIClient.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DBIClient.java @@ -1,6 +1,7 @@ package io.dropwizard.jdbi.timestamps; import com.codahale.metrics.MetricRegistry; +import com.google.common.collect.ImmutableList; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.jackson.Jackson; import io.dropwizard.jdbi.DBIFactory; @@ -10,10 +11,13 @@ import org.junit.rules.ExternalResource; import org.skife.jdbi.v2.DBI; +import javax.annotation.Nullable; import java.util.List; import java.util.Optional; import java.util.TimeZone; +import static java.util.Objects.requireNonNull; + /** * Configured JDBI client for the database */ @@ -21,15 +25,16 @@ public class DBIClient extends ExternalResource { private final TimeZone dbTimeZone; + @Nullable private DBI dbi; - private List managedObjects; + private List managedObjects = ImmutableList.of(); public DBIClient(TimeZone dbTimeZone) { this.dbTimeZone = dbTimeZone; } public DBI getDbi() { - return dbi; + return requireNonNull(dbi); } @Override diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DatabaseInTimeZone.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DatabaseInTimeZone.java index 6bd9ee88827..f75a5f6d4fe 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DatabaseInTimeZone.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/DatabaseInTimeZone.java @@ -8,6 +8,8 @@ import java.util.TimeZone; import java.util.concurrent.TimeUnit; +import static org.mockito.Mockito.mock; + /** * Run an instance of the H2 database in an another time zone */ @@ -16,7 +18,7 @@ public class DatabaseInTimeZone extends ExternalResource { private final TemporaryFolder temporaryFolder; private final TimeZone timeZone; - private Process process; + private Process process = mock(Process.class); public DatabaseInTimeZone(TemporaryFolder temporaryFolder, TimeZone timeZone) { this.temporaryFolder = temporaryFolder; @@ -62,4 +64,4 @@ private static boolean waitFor(Process process, long timeout, TimeUnit unit) thr } } } -} \ No newline at end of file +} diff --git a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/JodaDateTimeSqlTimestampTest.java b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/JodaDateTimeSqlTimestampTest.java index 54db3dce357..b4c9d597846 100644 --- a/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/JodaDateTimeSqlTimestampTest.java +++ b/dropwizard-jdbi/src/test/java/io/dropwizard/jdbi/timestamps/JodaDateTimeSqlTimestampTest.java @@ -16,6 +16,7 @@ import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; +import javax.annotation.Nullable; import java.util.Random; import java.util.TimeZone; @@ -29,11 +30,11 @@ public class JodaDateTimeSqlTimestampTest { private static final DateTimeFormatter ISO_FMT = ISODateTimeFormat.dateTimeNoMillis(); - private static TemporaryFolder temporaryFolder; - private static DatabaseInTimeZone databaseInTimeZone; - private static DateTimeZone dbTimeZone; - private static DBIClient dbiClient; + private static DateTimeZone dbTimeZone = DateTimeZone.UTC; + private static DBIClient dbiClient = new DBIClient(TimeZone.getDefault()); + @ClassRule + @Nullable public static TestRule chain; static { @@ -42,11 +43,10 @@ public class JodaDateTimeSqlTimestampTest { try { final TimeZone timeZone = getRandomTimeZone(); dbTimeZone = DateTimeZone.forTimeZone(timeZone); - temporaryFolder = new TemporaryFolder(); - databaseInTimeZone = new DatabaseInTimeZone(temporaryFolder, timeZone); + final TemporaryFolder temporaryFolder = new TemporaryFolder(); dbiClient = new DBIClient(timeZone); chain = RuleChain.outerRule(temporaryFolder) - .around(databaseInTimeZone) + .around(new DatabaseInTimeZone(temporaryFolder, timeZone)) .around(dbiClient); done = true; } catch (IllegalArgumentException e) { diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/DropwizardResourceConfig.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/DropwizardResourceConfig.java index 6a5b5994b8e..9fb65080b3d 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/DropwizardResourceConfig.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/DropwizardResourceConfig.java @@ -22,6 +22,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import javax.ws.rs.Path; import javax.ws.rs.ext.Provider; import java.io.Serializable; @@ -36,7 +37,7 @@ public class DropwizardResourceConfig extends ResourceConfig { private static final Logger LOGGER = LoggerFactory.getLogger(DropwizardResourceConfig.class); private static final String NEWLINE = String.format("%n"); private static final TypeResolver TYPE_RESOLVER = new TypeResolver(); - + private static final Pattern PATH_DIRTY_SLASHES = Pattern.compile("\\s*/\\s*/+\\s*"); private String urlPattern = "/*"; @@ -49,7 +50,7 @@ public DropwizardResourceConfig() { this(true, null); } - public DropwizardResourceConfig(boolean testOnly, MetricRegistry metricRegistry) { + public DropwizardResourceConfig(boolean testOnly, @Nullable MetricRegistry metricRegistry) { super(); if (metricRegistry == null) { @@ -135,7 +136,7 @@ public String getEndpointsInfo() { for (Class klass : allResourcesClasses) { new EndpointLogger(urlPattern, klass).populate(endpointLogLines); } - + final Set allResources = this.getResources(); for (Resource res : allResources) { for (Resource childRes : res.getChildResources()) { @@ -143,7 +144,7 @@ public String getEndpointsInfo() { // // This code will never be reached because of ambiguous (sub-)resource methods // related to the OPTIONS method and @Consumes/@Produces annotations. - + for (Class childResHandlerClass : childRes.getHandlerClasses()) { EndpointLogger epl = new EndpointLogger(urlPattern, childResHandlerClass); epl.populate(cleanUpPath(res.getPath() + epl.rootPath), epl.klass, false, childRes, endpointLogLines); @@ -161,7 +162,7 @@ public String getEndpointsInfo() { return msg.toString(); } - + @VisibleForTesting String cleanUpPath(String path) { return PATH_DIRTY_SLASHES.matcher(path).replaceAll("/").trim(); @@ -278,6 +279,7 @@ public void onEvent(ApplicationEvent event) { } @Override + @Nullable public RequestEventListener onRequest(RequestEvent requestEvent) { return null; } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorEntityWriter.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorEntityWriter.java index 755ae731f7d..0f534454f91 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorEntityWriter.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorEntityWriter.java @@ -2,6 +2,7 @@ import org.glassfish.jersey.message.MessageBodyWorkers; +import javax.annotation.Nullable; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; @@ -13,6 +14,8 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Type; +import static java.util.Objects.requireNonNull; + /** * This class allows producing non-JSON responses for particular entities. For example, register a instance with the * {@link ErrorMessage} entity and the TEXT_HTML MediaType to produce custom HTML error messages. @@ -33,7 +36,7 @@ public ErrorEntityWriter(MediaType contentType, Class representation) { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return headers.getAcceptableMediaTypes().contains(contentType); + return requireNonNull(headers).getAcceptableMediaTypes().contains(contentType); } @Override @@ -51,7 +54,7 @@ public void writeTo(T entity, OutputStream entityStream) throws IOException, WebApplicationException { - final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(representation, + final MessageBodyWriter writer = requireNonNull(mbw).get().getMessageBodyWriter(representation, representation, annotations, contentType); // Fix the headers, because Dropwizard error mappers always set the content type to APPLICATION_JSON @@ -67,8 +70,10 @@ public void writeTo(T entity, private Class representation; @Context + @Nullable private HttpHeaders headers; @Context + @Nullable private javax.inject.Provider mbw; } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorMessage.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorMessage.java index 20383247336..c6d40357594 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorMessage.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/ErrorMessage.java @@ -5,12 +5,15 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; +import javax.annotation.Nullable; import java.util.Objects; @JsonInclude(JsonInclude.Include.NON_NULL) public class ErrorMessage { private final int code; private final String message; + + @Nullable private final String details; public ErrorMessage(String message) { @@ -23,7 +26,7 @@ public ErrorMessage(int code, String message) { @JsonCreator public ErrorMessage(@JsonProperty("code") int code, @JsonProperty("message") String message, - @JsonProperty("details") String details) { + @Nullable @JsonProperty("details") String details) { this.code = code; this.message = message; this.details = details; @@ -40,6 +43,7 @@ public String getMessage() { } @JsonProperty("details") + @Nullable public String getDetails() { return details; } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/filter/AllowedMethodsFilter.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/filter/AllowedMethodsFilter.java index 1132fe3f943..db0e1a95f5d 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/filter/AllowedMethodsFilter.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/filter/AllowedMethodsFilter.java @@ -24,7 +24,7 @@ public class AllowedMethodsFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(AllowedMethodsFilter.class); - private ImmutableSet allowedMethods; + private ImmutableSet allowedMethods = ImmutableSet.of(); @Override public void init(FilterConfig config) { diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalMessageBodyWriter.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalMessageBodyWriter.java index 8043f49ebf6..e59e1ec49b2 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalMessageBodyWriter.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalMessageBodyWriter.java @@ -4,6 +4,7 @@ import io.dropwizard.jersey.optional.EmptyOptionalException; import org.glassfish.jersey.message.MessageBodyWorkers; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @@ -16,11 +17,14 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import static java.util.Objects.requireNonNull; + @Provider @Produces(MediaType.WILDCARD) public class OptionalMessageBodyWriter implements MessageBodyWriter> { @Inject + @Nullable private javax.inject.Provider mbw; // Jersey ignores this @@ -52,7 +56,7 @@ public void writeTo(Optional entity, final ParameterizedType actualGenericType = (ParameterizedType) genericType; final Type actualGenericTypeArgument = actualGenericType.getActualTypeArguments()[0]; - final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entity.get().getClass(), + final MessageBodyWriter writer = requireNonNull(mbw).get().getMessageBodyWriter(entity.get().getClass(), actualGenericTypeArgument, annotations, mediaType); writer.writeTo(entity.get(), entity.get().getClass(), actualGenericTypeArgument, diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalParamConverterProvider.java index 6b873cbe7d5..abf0a4d0f52 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/guava/OptionalParamConverterProvider.java @@ -6,6 +6,7 @@ import org.glassfish.jersey.internal.util.ReflectionHelper; import org.glassfish.jersey.internal.util.collection.ClassTypePair; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.ext.ParamConverter; @@ -27,6 +28,7 @@ public OptionalParamConverterProvider(final ServiceLocator locator) { * {@inheritDoc} */ @Override + @Nullable public ParamConverter getConverter(final Class rawType, final Type genericType, final Annotation[] annotations) { if (Optional.class.equals(rawType)) { final List ctps = ReflectionHelper.getTypeArgumentAndClass(genericType); diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProvider.java index 5f268012e6e..eedc541caa4 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProvider.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import javax.annotation.Nullable; import javax.ws.rs.core.MediaType; import java.lang.annotation.Annotation; import java.lang.reflect.Type; @@ -24,17 +25,17 @@ public JacksonMessageBodyProvider(ObjectMapper mapper) { @Override public boolean isReadable(Class type, - Type genericType, - Annotation[] annotations, - MediaType mediaType) { + @Nullable Type genericType, + @Nullable Annotation[] annotations, + @Nullable MediaType mediaType) { return isProvidable(type) && super.isReadable(type, genericType, annotations, mediaType); } @Override public boolean isWriteable(Class type, - Type genericType, - Annotation[] annotations, - MediaType mediaType) { + @Nullable Type genericType, + @Nullable Annotation[] annotations, + @Nullable MediaType mediaType) { return isProvidable(type) && super.isWriteable(type, genericType, annotations, mediaType); } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantParam.java index 9a2ddb9b1df..32be2177744 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantParam.java @@ -1,6 +1,8 @@ package io.dropwizard.jersey.jsr310; import io.dropwizard.jersey.params.AbstractParam; + +import javax.annotation.Nullable; import java.time.Instant; /** @@ -10,12 +12,12 @@ * @see Instant */ public class InstantParam extends AbstractParam { - public InstantParam(final String input) { + public InstantParam(@Nullable final String input) { super(input); } @Override - protected Instant parse(final String input) throws Exception { + protected Instant parse(@Nullable final String input) throws Exception { return Instant.ofEpochMilli(Long.parseLong(input)); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantSecondParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantSecondParam.java index c155853dcde..49da6d300f4 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantSecondParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantSecondParam.java @@ -1,6 +1,8 @@ package io.dropwizard.jersey.jsr310; import io.dropwizard.jersey.params.AbstractParam; + +import javax.annotation.Nullable; import java.time.Instant; /** @@ -10,12 +12,12 @@ * @see Instant */ public class InstantSecondParam extends AbstractParam { - public InstantSecondParam(final String input) { + public InstantSecondParam(@Nullable final String input) { super(input); } @Override - protected Instant parse(final String input) throws Exception { + protected Instant parse(@Nullable final String input) throws Exception { return Instant.ofEpochSecond(Long.parseLong(input)); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateParam.java index 195a7e78fd1..b517392e7cb 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.LocalDate; /** @@ -11,12 +12,12 @@ * @see LocalDate */ public class LocalDateParam extends AbstractParam { - public LocalDateParam(final String input) { + public LocalDateParam(@Nullable final String input) { super(input); } @Override - protected LocalDate parse(final String input) throws Exception { + protected LocalDate parse(@Nullable final String input) throws Exception { return LocalDate.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateTimeParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateTimeParam.java index 712898ffc33..84263b959eb 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateTimeParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalDateTimeParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.LocalDateTime; /** @@ -11,12 +12,12 @@ * @see LocalDateTime */ public class LocalDateTimeParam extends AbstractParam { - public LocalDateTimeParam(final String input) { + public LocalDateTimeParam(@Nullable final String input) { super(input); } @Override - protected LocalDateTime parse(final String input) throws Exception { + protected LocalDateTime parse(@Nullable final String input) throws Exception { return LocalDateTime.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalTimeParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalTimeParam.java index 8f2896a1049..e8c116361ec 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalTimeParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalTimeParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.LocalTime; /** @@ -11,12 +12,12 @@ * @see LocalTime */ public class LocalTimeParam extends AbstractParam { - public LocalTimeParam(final String input) { + public LocalTimeParam(@Nullable final String input) { super(input); } @Override - protected LocalTime parse(final String input) throws Exception { + protected LocalTime parse(@Nullable final String input) throws Exception { return LocalTime.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/OffsetDateTimeParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/OffsetDateTimeParam.java index 380dee0c48b..ea1aa6f9064 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/OffsetDateTimeParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/OffsetDateTimeParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.OffsetDateTime; /** @@ -11,12 +12,12 @@ * @see OffsetDateTime */ public class OffsetDateTimeParam extends AbstractParam { - public OffsetDateTimeParam(final String input) { + public OffsetDateTimeParam(@Nullable final String input) { super(input); } @Override - protected OffsetDateTime parse(final String input) throws Exception { + protected OffsetDateTime parse(@Nullable final String input) throws Exception { return OffsetDateTime.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearMonthParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearMonthParam.java index 0af0ef37c44..b16994ffb76 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearMonthParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearMonthParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.YearMonth; /** @@ -11,12 +12,12 @@ * @see YearMonth */ public class YearMonthParam extends AbstractParam { - public YearMonthParam(final String input) { + public YearMonthParam(@Nullable final String input) { super(input); } @Override - protected YearMonth parse(final String input) throws Exception { + protected YearMonth parse(@Nullable final String input) throws Exception { return YearMonth.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearParam.java index 7c92dc12c6a..1df6a08a468 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/YearParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.Year; /** @@ -11,12 +12,12 @@ * @see java.time.YearMonth */ public class YearParam extends AbstractParam { - public YearParam(final String input) { + public YearParam(@Nullable final String input) { super(input); } @Override - protected Year parse(final String input) throws Exception { + protected Year parse(@Nullable final String input) throws Exception { return Year.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZoneIdParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZoneIdParam.java index 821633b236a..12331ffd2c6 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZoneIdParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZoneIdParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.ZoneId; /** @@ -11,12 +12,12 @@ * @see ZoneId */ public class ZoneIdParam extends AbstractParam { - public ZoneIdParam(final String input) { + public ZoneIdParam(@Nullable final String input) { super(input); } @Override - protected ZoneId parse(final String input) throws Exception { + protected ZoneId parse(@Nullable final String input) throws Exception { return ZoneId.of(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZonedDateTimeParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZonedDateTimeParam.java index b90d618b85b..ca98aea9ea7 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZonedDateTimeParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/ZonedDateTimeParam.java @@ -2,6 +2,7 @@ import io.dropwizard.jersey.params.AbstractParam; +import javax.annotation.Nullable; import java.time.ZonedDateTime; /** @@ -11,12 +12,12 @@ * @see ZonedDateTime */ public class ZonedDateTimeParam extends AbstractParam { - public ZonedDateTimeParam(final String input) { + public ZonedDateTimeParam(@Nullable final String input) { super(input); } @Override - protected ZonedDateTime parse(final String input) throws Exception { + protected ZonedDateTime parse(@Nullable final String input) throws Exception { return ZonedDateTime.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalDoubleParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalDoubleParamConverterProvider.java index e6dadd2a186..1a7ea9a198f 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalDoubleParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalDoubleParamConverterProvider.java @@ -1,5 +1,6 @@ package io.dropwizard.jersey.optional; +import javax.annotation.Nullable; import javax.inject.Singleton; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; @@ -18,6 +19,7 @@ public class OptionalDoubleParamConverterProvider implements ParamConverterProvi */ @Override @SuppressWarnings("unchecked") + @Nullable public ParamConverter getConverter(final Class rawType, final Type genericType, final Annotation[] annotations) { return OptionalDouble.class.equals(rawType) ? (ParamConverter) paramConverter : null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalIntParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalIntParamConverterProvider.java index 03fe9f971af..338ea0a5c76 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalIntParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalIntParamConverterProvider.java @@ -1,5 +1,6 @@ package io.dropwizard.jersey.optional; +import javax.annotation.Nullable; import javax.inject.Singleton; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; @@ -18,6 +19,7 @@ public class OptionalIntParamConverterProvider implements ParamConverterProvider */ @Override @SuppressWarnings("unchecked") + @Nullable public ParamConverter getConverter(final Class rawType, final Type genericType, final Annotation[] annotations) { return OptionalInt.class.equals(rawType) ? (ParamConverter) paramConverter : null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalLongParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalLongParamConverterProvider.java index 1dc6ff23866..2f5528be81e 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalLongParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalLongParamConverterProvider.java @@ -1,5 +1,6 @@ package io.dropwizard.jersey.optional; +import javax.annotation.Nullable; import javax.inject.Singleton; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; @@ -18,6 +19,7 @@ public class OptionalLongParamConverterProvider implements ParamConverterProvide */ @Override @SuppressWarnings("unchecked") + @Nullable public ParamConverter getConverter(final Class rawType, final Type genericType, final Annotation[] annotations) { return OptionalLong.class.equals(rawType) ? (ParamConverter) paramConverter : null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalMessageBodyWriter.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalMessageBodyWriter.java index 6f60b2acbcf..d26a7685abc 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalMessageBodyWriter.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalMessageBodyWriter.java @@ -2,6 +2,7 @@ import org.glassfish.jersey.message.MessageBodyWorkers; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @@ -15,11 +16,14 @@ import java.lang.reflect.Type; import java.util.Optional; +import static java.util.Objects.requireNonNull; + @Provider @Produces(MediaType.WILDCARD) public class OptionalMessageBodyWriter implements MessageBodyWriter> { @Inject + @Nullable private javax.inject.Provider mbw; // Jersey ignores this @@ -52,7 +56,7 @@ public void writeTo(Optional entity, final Type innerGenericType = (genericType instanceof ParameterizedType) ? ((ParameterizedType) genericType).getActualTypeArguments()[0] : entity.get().getClass(); - final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entity.get().getClass(), + final MessageBodyWriter writer = requireNonNull(mbw).get().getMessageBodyWriter(entity.get().getClass(), innerGenericType, annotations, mediaType); writer.writeTo(entity.get(), entity.get().getClass(), innerGenericType, annotations, mediaType, httpHeaders, entityStream); diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalParamConverterProvider.java index 80e095e87df..0218efba7b2 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/optional/OptionalParamConverterProvider.java @@ -5,6 +5,7 @@ import org.glassfish.jersey.internal.util.ReflectionHelper; import org.glassfish.jersey.internal.util.collection.ClassTypePair; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.ext.ParamConverter; @@ -27,6 +28,7 @@ public OptionalParamConverterProvider(final ServiceLocator locator) { * {@inheritDoc} */ @Override + @Nullable public ParamConverter getConverter(final Class rawType, final Type genericType, final Annotation[] annotations) { if (Optional.class.equals(rawType)) { diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParam.java index fb5378db21a..8f18e2ad699 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParam.java @@ -4,6 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -19,7 +20,7 @@ public abstract class AbstractParam { private final String parameterName; private final T value; - protected AbstractParam(String input) { + protected AbstractParam(@Nullable String input) { this(input, "Parameter"); } @@ -29,7 +30,7 @@ protected AbstractParam(String input) { * @param input an input value from a client request */ @SuppressWarnings({"AbstractMethodCallInConstructor", "OverriddenMethodCallDuringObjectConstruction"}) - protected AbstractParam(String input, String parameterName) { + protected AbstractParam(@Nullable String input, String parameterName) { this.parameterName = parameterName; try { this.value = parse(input); @@ -49,7 +50,7 @@ protected AbstractParam(String input, String parameterName) { * @param e the exception thrown while parsing {@code input} * @return the {@link Response} to be sent to the client */ - protected Response error(String input, Exception e) { + protected Response error(@Nullable String input, Exception e) { LOGGER.debug("Invalid input received: {}", input); String errorMessage = errorMessage(e); if (errorMessage.contains("%s")) { @@ -100,7 +101,7 @@ protected Status getErrorStatus() { * @return {@code input}, parsed as an instance of {@code T} * @throws Exception if there is an error parsing the input */ - protected abstract T parse(String input) throws Exception; + protected abstract T parse(@Nullable String input) throws Exception; /** * Returns the underlying value. diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParamConverterProvider.java index d33ebe83697..41d0a05442c 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/AbstractParamConverterProvider.java @@ -5,6 +5,7 @@ import org.glassfish.jersey.internal.inject.ExtractorException; import org.glassfish.jersey.server.internal.LocalizationMessages; +import javax.annotation.Nullable; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.ParamConverter; @@ -28,6 +29,7 @@ public AbstractParamConverterProvider() { } @Override + @Nullable public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { if (AbstractParam.class.isAssignableFrom(rawType)) { final String parameterName = JerseyParameterNameProvider.getParameterNameFromAnnotations(annotations).orElse("Parameter"); @@ -42,6 +44,7 @@ public ParamConverter getConverter(Class rawType, Type genericType, An return new ParamConverter() { @Override @SuppressWarnings("unchecked") + @Nullable public T fromString(String value) { if (rawType != NonEmptyStringParam.class && Strings.isNullOrEmpty(value)) { return null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/BooleanParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/BooleanParam.java index c94f8ebfe11..481fd7d6a6e 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/BooleanParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/BooleanParam.java @@ -1,5 +1,7 @@ package io.dropwizard.jersey.params; +import javax.annotation.Nullable; + /** * A parameter encapsulating boolean values. If the query parameter value is {@code "true"}, * regardless of case, the returned value is {@link Boolean#TRUE}. If the query parameter value is @@ -7,11 +9,11 @@ * values will return a {@code 400 Bad Request} response. */ public class BooleanParam extends AbstractParam { - public BooleanParam(String input) { + public BooleanParam(@Nullable String input) { super(input); } - public BooleanParam(String input, String parameterName) { + public BooleanParam(@Nullable String input, String parameterName) { super(input, parameterName); } @@ -21,7 +23,7 @@ protected String errorMessage(Exception e) { } @Override - protected Boolean parse(String input) throws Exception { + protected Boolean parse(@Nullable String input) throws Exception { if ("true".equalsIgnoreCase(input)) { return Boolean.TRUE; } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DateTimeParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DateTimeParam.java index 2a45cdff643..76c1d2ee1fd 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DateTimeParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DateTimeParam.java @@ -3,21 +3,23 @@ import org.joda.time.DateTime; import org.joda.time.DateTimeZone; +import javax.annotation.Nullable; + /** * A parameter encapsulating date/time values. All non-parsable values will return a {@code 400 Bad * Request} response. All values returned are in UTC. */ public class DateTimeParam extends AbstractParam { - public DateTimeParam(String input) { + public DateTimeParam(@Nullable String input) { super(input); } - public DateTimeParam(String input, String parameterName) { + public DateTimeParam(@Nullable String input, String parameterName) { super(input, parameterName); } @Override - protected DateTime parse(String input) throws Exception { + protected DateTime parse(@Nullable String input) throws Exception { return new DateTime(input, DateTimeZone.UTC); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DurationParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DurationParam.java index c9626697d31..d90f8f896ee 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DurationParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/DurationParam.java @@ -2,17 +2,21 @@ import io.dropwizard.util.Duration; +import javax.annotation.Nullable; + +import static java.util.Objects.requireNonNull; + /** * A parameter encapsulating duration values. All non-parsable values will return a {@code 400 Bad * Request} response. Supports all input formats the {@link Duration} class supports. */ public class DurationParam extends AbstractParam { - public DurationParam(String input) { + public DurationParam(@Nullable String input) { super(input); } - public DurationParam(String input, String parameterName) { + public DurationParam(@Nullable String input, String parameterName) { super(input, parameterName); } @@ -22,8 +26,8 @@ protected String errorMessage(Exception e) { } @Override - protected Duration parse(String input) throws Exception { - return Duration.parse(input); + protected Duration parse(@Nullable String input) throws Exception { + return Duration.parse(requireNonNull(input)); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/InstantParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/InstantParam.java index 3389114f24b..b1435244733 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/InstantParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/InstantParam.java @@ -1,16 +1,17 @@ package io.dropwizard.jersey.params; +import javax.annotation.Nullable; import java.time.Instant; /** * A parameter encapsulating date/time values. All non-parsable values will return a {@code 400 Bad Request} response. */ public class InstantParam extends AbstractParam { - public InstantParam(final String input) { + public InstantParam(@Nullable final String input) { super(input); } - public InstantParam(final String input, final String parameterName) { + public InstantParam(@Nullable final String input, final String parameterName) { super(input, parameterName); } @@ -20,7 +21,7 @@ protected String errorMessage(Exception e) { } @Override - protected Instant parse(final String input) throws Exception { + protected Instant parse(@Nullable final String input) throws Exception { return Instant.parse(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/IntParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/IntParam.java index c7f4f63d708..949b2650732 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/IntParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/IntParam.java @@ -1,15 +1,17 @@ package io.dropwizard.jersey.params; +import javax.annotation.Nullable; + /** * A parameter encapsulating integer values. All non-decimal values will return a * {@code 400 Bad Request} response. */ public class IntParam extends AbstractParam { - public IntParam(String input) { + public IntParam(@Nullable String input) { super(input); } - public IntParam(String input, String parameterName) { + public IntParam(@Nullable String input, String parameterName) { super(input, parameterName); } @@ -19,7 +21,7 @@ protected String errorMessage(Exception e) { } @Override - protected Integer parse(String input) { + protected Integer parse(@Nullable String input) { return Integer.valueOf(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LocalDateParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LocalDateParam.java index c31f959e436..633cef5bd35 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LocalDateParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LocalDateParam.java @@ -2,21 +2,23 @@ import org.joda.time.LocalDate; +import javax.annotation.Nullable; + /** * A parameter encapsulating local date values. All non-parsable values will return a {@code 400 Bad * Request} response. */ public class LocalDateParam extends AbstractParam { - public LocalDateParam(String input) { + public LocalDateParam(@Nullable String input) { super(input); } - public LocalDateParam(String input, String parameterName) { + public LocalDateParam(@Nullable String input, String parameterName) { super(input, parameterName); } @Override - protected LocalDate parse(String input) throws Exception { + protected LocalDate parse(@Nullable String input) throws Exception { return new LocalDate(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LongParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LongParam.java index 3810a2a5532..e2022a23667 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LongParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/LongParam.java @@ -1,15 +1,17 @@ package io.dropwizard.jersey.params; +import javax.annotation.Nullable; + /** * A parameter encapsulating long values. All non-decimal values will return a {@code 400 Bad * Request} response. */ public class LongParam extends AbstractParam { - public LongParam(String input) { + public LongParam(@Nullable String input) { super(input); } - public LongParam(String input, String parameterName) { + public LongParam(@Nullable String input, String parameterName) { super(input, parameterName); } @@ -19,7 +21,7 @@ protected String errorMessage(Exception e) { } @Override - protected Long parse(String input) { + protected Long parse(@Nullable String input) { return Long.valueOf(input); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/NonEmptyStringParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/NonEmptyStringParam.java index 7ba7efa5f3b..ff79044d06f 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/NonEmptyStringParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/NonEmptyStringParam.java @@ -2,6 +2,7 @@ import com.google.common.base.Strings; +import javax.annotation.Nullable; import java.util.Optional; /** @@ -11,16 +12,16 @@ * {@code Optional.of("")}. */ public class NonEmptyStringParam extends AbstractParam> { - public NonEmptyStringParam(String input) { + public NonEmptyStringParam(@Nullable String input) { super(input); } - public NonEmptyStringParam(String input, String parameterName) { + public NonEmptyStringParam(@Nullable String input, String parameterName) { super(input, parameterName); } @Override - protected Optional parse(String input) throws Exception { + protected Optional parse(@Nullable String input) throws Exception { return Optional.ofNullable(Strings.emptyToNull(input)); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/SizeParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/SizeParam.java index 6547cb3dc36..59bbc28767f 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/SizeParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/SizeParam.java @@ -2,17 +2,21 @@ import io.dropwizard.util.Size; +import javax.annotation.Nullable; + +import static java.util.Objects.requireNonNull; + /** * A parameter encapsulating size values. All non-parsable values will return a {@code 400 Bad * Request} response. Supports all input formats the {@link Size} class supports. */ public class SizeParam extends AbstractParam { - public SizeParam(String input) { + public SizeParam(@Nullable String input) { super(input); } - public SizeParam(String input, String parameterName) { + public SizeParam(@Nullable String input, String parameterName) { super(input, parameterName); } @@ -22,7 +26,7 @@ protected String errorMessage(Exception e) { } @Override - protected Size parse(String input) throws Exception { - return Size.parse(input); + protected Size parse(@Nullable String input) throws Exception { + return Size.parse(requireNonNull(input)); } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/UUIDParam.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/UUIDParam.java index eef9289e872..4cd0a10cd48 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/UUIDParam.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params/UUIDParam.java @@ -1,5 +1,6 @@ package io.dropwizard.jersey.params; +import javax.annotation.Nullable; import java.util.UUID; /** @@ -8,11 +9,11 @@ */ public class UUIDParam extends AbstractParam { - public UUIDParam(String input) { + public UUIDParam(@Nullable String input) { super(input); } - public UUIDParam(String input, String parameterName) { + public UUIDParam(@Nullable String input, String parameterName) { super(input, parameterName); } @@ -22,7 +23,7 @@ protected String errorMessage(Exception e) { } @Override - protected UUID parse(String input) throws Exception { + protected UUID parse(@Nullable String input) throws Exception { return UUID.fromString(input); } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/FlashFactory.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/FlashFactory.java index a577791fec5..971e42a11dd 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/FlashFactory.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/FlashFactory.java @@ -2,13 +2,16 @@ import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory; +import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Context; public final class FlashFactory extends AbstractContainerRequestValueFactory> { @Context + @Nullable private HttpServletRequest request; + private boolean doNotCreate; public FlashFactory(boolean doNotCreate) { @@ -17,6 +20,7 @@ public FlashFactory(boolean doNotCreate) { @Override @SuppressWarnings("rawtypes") + @Nullable public Flash provide() { if (request == null) { return null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/HttpSessionFactory.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/HttpSessionFactory.java index df635b2d06a..bf8695505b2 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/HttpSessionFactory.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/HttpSessionFactory.java @@ -2,12 +2,14 @@ import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory; +import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Context; public final class HttpSessionFactory extends AbstractContainerRequestValueFactory { @Context + @Nullable private HttpServletRequest request; private boolean doNotCreate; @@ -16,6 +18,7 @@ public HttpSessionFactory(boolean doNotCreate) { } @Override + @Nullable public HttpSession provide() { if (request == null) { return null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/SessionFactoryProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/SessionFactoryProvider.java index 1bdcf44622c..6dcb36926f4 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/SessionFactoryProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/sessions/SessionFactoryProvider.java @@ -11,6 +11,7 @@ import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpSession; @@ -25,6 +26,7 @@ public SessionFactoryProvider(final MultivaluedParameterExtractorProvider extrac } @Override + @Nullable protected Factory createValueFactory(final Parameter parameter) { final Class classType = parameter.getRawType(); diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyContainerHolder.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyContainerHolder.java index 09a7fd95dec..7d4cc2ced07 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyContainerHolder.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyContainerHolder.java @@ -1,19 +1,23 @@ package io.dropwizard.jersey.setup; +import javax.annotation.Nullable; import javax.servlet.Servlet; public class JerseyContainerHolder { + + @Nullable private Servlet container; - public JerseyContainerHolder(Servlet container) { + public JerseyContainerHolder(@Nullable Servlet container) { this.container = container; } + @Nullable public Servlet getContainer() { return container; } - public void setContainer(Servlet container) { + public void setContainer(@Nullable Servlet container) { this.container = container; } } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyEnvironment.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyEnvironment.java index 1a556581466..d2a43979d9b 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyEnvironment.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/setup/JerseyEnvironment.java @@ -94,6 +94,7 @@ public void property(String name, @Nullable Object value) { * @see org.glassfish.jersey.server.ResourceConfig */ @SuppressWarnings("unchecked") + @Nullable public T getProperty(String name) { return (T) config.getProperties().get(name); } diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProvider.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProvider.java index a3d9daa78b0..c0712d47a62 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProvider.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProvider.java @@ -4,9 +4,11 @@ import com.google.common.base.Strings; import io.dropwizard.jersey.errors.ErrorMessage; import io.dropwizard.util.Enums; +import org.glassfish.jersey.internal.util.ReflectionHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; +import javax.annotation.Nullable; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -14,15 +16,13 @@ import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Type; import java.security.AccessController; import static io.dropwizard.jersey.validation.JerseyParameterNameProvider.getParameterNameFromAnnotations; -import org.glassfish.jersey.internal.util.ReflectionHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Provides converters to jersey for enums used as resource parameters. * @@ -39,7 +39,8 @@ public class FuzzyEnumParamConverterProvider implements ParamConverterProvider { private final static Joiner JOINER = Joiner.on(", "); @Override - public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { + @Nullable + public ParamConverter getConverter(Class rawType, @Nullable Type genericType, Annotation[] annotations) { if (!rawType.isEnum()) { return null; } @@ -51,6 +52,7 @@ public ParamConverter getConverter(Class rawType, Type genericType, An return new ParamConverter() { @Override + @Nullable public T fromString(String value) { if (Strings.isNullOrEmpty(value)) { return null; diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/ParamValidatorUnwrapper.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/ParamValidatorUnwrapper.java index 573668d7680..099283285be 100644 --- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/ParamValidatorUnwrapper.java +++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/ParamValidatorUnwrapper.java @@ -5,6 +5,7 @@ import io.dropwizard.jersey.params.AbstractParam; import org.hibernate.validator.spi.valuehandling.ValidatedValueUnwrapper; +import javax.annotation.Nullable; import java.lang.reflect.Type; /** @@ -15,6 +16,7 @@ public class ParamValidatorUnwrapper extends ValidatedValueUnwrapper abstractParam) { return abstractParam == null ? null : abstractParam.get(); } diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/MyMessageParamConverterProvider.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/MyMessageParamConverterProvider.java index 8229f7be650..5fcd346946e 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/MyMessageParamConverterProvider.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/MyMessageParamConverterProvider.java @@ -1,5 +1,6 @@ package io.dropwizard.jersey; +import javax.annotation.Nullable; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; @@ -11,6 +12,7 @@ public class MyMessageParamConverterProvider implements ParamConverterProvider { @Override @SuppressWarnings("unchecked") + @Nullable public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { if (genericType.equals(MyMessage.class)) { return (ParamConverter) new MyMessageParamConverter(); diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/CharsetUtf8FilterTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/CharsetUtf8FilterTest.java index 23107f583d3..21ce5ab43f8 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/CharsetUtf8FilterTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/CharsetUtf8FilterTest.java @@ -2,9 +2,6 @@ import com.google.common.net.HttpHeaders; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; @@ -13,16 +10,13 @@ import javax.ws.rs.core.MultivaluedMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) public class CharsetUtf8FilterTest { - @Mock - private ContainerRequestContext request; - - @Mock - private ContainerResponseContext response; + private ContainerRequestContext request = mock(ContainerRequestContext.class); + private ContainerResponseContext response = mock(ContainerResponseContext.class); private CharsetUtf8Filter charsetUtf8Filter = new CharsetUtf8Filter(); diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RequestIdFilterTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RequestIdFilterTest.java index 5a515e5aaed..6bea3ab9ea8 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RequestIdFilterTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RequestIdFilterTest.java @@ -2,10 +2,7 @@ import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import javax.ws.rs.container.ContainerRequestContext; @@ -16,20 +13,15 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) public class RequestIdFilterTest { - @Mock - private ContainerRequestContext request; - - @Mock - private ContainerResponseContext response; - - @Mock - private Logger logger; + private ContainerRequestContext request = mock(ContainerRequestContext.class); + private ContainerResponseContext response = mock(ContainerResponseContext.class); + private Logger logger = mock(Logger.class); private RequestIdFilter requestIdFilter = new RequestIdFilter(); private MultivaluedMap headers = new MultivaluedHashMap<>(); diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RuntimeFilterTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RuntimeFilterTest.java index 95c47c65ff8..a57fe040fb1 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RuntimeFilterTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/filter/RuntimeFilterTest.java @@ -1,10 +1,7 @@ package io.dropwizard.jersey.filter; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; @@ -12,16 +9,13 @@ import javax.ws.rs.core.MultivaluedMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) public class RuntimeFilterTest { - @Mock - private ContainerRequestContext request; - - @Mock - private ContainerResponseContext response; + private ContainerRequestContext request = mock(ContainerRequestContext.class); + private ContainerResponseContext response = mock(ContainerResponseContext.class); private RuntimeFilter runtimeFilter = new RuntimeFilter(); diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/gzip/ConfiguredGZipEncoderTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/gzip/ConfiguredGZipEncoderTest.java index 2de901d9152..1f37bfdf871 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/gzip/ConfiguredGZipEncoderTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/gzip/ConfiguredGZipEncoderTest.java @@ -2,6 +2,7 @@ import org.junit.Test; +import javax.annotation.Nullable; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.HttpHeaders; @@ -75,14 +76,6 @@ public void noEncodingwillNotAroundWrite() throws IOException, WebApplicationExc assertThat(context.isProceedCalled(), is(true)); } - - @Test(expected = NullPointerException.class) - public void contextMayNotBeNull() throws IOException { - ClientRequestContext context = null; - new ConfiguredGZipEncoder(false).filter(context); - } - - private class WriterInterceptorContextMock implements WriterInterceptorContext { private final MultivaluedMap headers; private OutputStream os = new OutputStream() { @@ -103,6 +96,7 @@ public void proceed() throws IOException, WebApplicationException { } @Override + @Nullable public Object getEntity() { return null; } @@ -128,11 +122,13 @@ public MultivaluedMap getHeaders() { } @Override + @Nullable public Object getProperty(String name) { return null; } @Override + @Nullable public Collection getPropertyNames() { return null; } @@ -158,6 +154,7 @@ public void setAnnotations(Annotation[] annotations) { } @Override + @Nullable public Class getType() { return null; } @@ -168,6 +165,7 @@ public void setType(Class type) { } @Override + @Nullable public Type getGenericType() { return null; } @@ -178,6 +176,7 @@ public void setGenericType(Type genericType) { } @Override + @Nullable public MediaType getMediaType() { return null; } diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/CustomDeserialization.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/CustomDeserialization.java index e0c5fae3c93..4bc0b4493ee 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/CustomDeserialization.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/CustomDeserialization.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import javax.annotation.Nullable; import java.io.IOException; /** @@ -41,6 +42,7 @@ public MyNastyException(JsonParser jp) { } @Override + @Nullable public String getMessage() { return null; } diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProviderTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProviderTest.java index 0ca6d300b3a..efe250b11e0 100755 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProviderTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProviderTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; import com.google.common.reflect.TypeToken; import io.dropwizard.jackson.Jackson; import io.dropwizard.validation.Validated; @@ -11,6 +12,7 @@ import org.junit.Before; import org.junit.Test; +import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @@ -71,7 +73,7 @@ public static class ListExample { @NotEmpty @Valid @JsonProperty - public List examples; + public List examples = ImmutableList.of(); } public interface Partial1 { @@ -86,6 +88,7 @@ public static class PartialExample { public int id; @NotNull(groups = Partial2.class) + @Nullable @JsonProperty public String text; } diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/OkRepresentation.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/OkRepresentation.java index d18b80dca64..d2a62109c5c 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/OkRepresentation.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/OkRepresentation.java @@ -2,10 +2,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.Nullable; import java.time.LocalDate; public class OkRepresentation { - private Integer message; + + private Integer message = 0; + + @Nullable private LocalDate date; @JsonProperty @@ -14,6 +18,7 @@ public Integer getMessage() { } @JsonProperty + @Nullable public LocalDate getDate() { return date; } diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/BeanParameter.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/BeanParameter.java index 62913280789..487525a6395 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/BeanParameter.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/BeanParameter.java @@ -3,13 +3,15 @@ import io.dropwizard.validation.ValidationMethod; import org.hibernate.validator.constraints.NotEmpty; +import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import javax.ws.rs.QueryParam; +import java.util.Objects; public class BeanParameter { @QueryParam("name") @NotEmpty - private String name; + private String name = ""; public String getName() { return name; @@ -17,10 +19,11 @@ public String getName() { @QueryParam("choice") @NotNull + @Nullable private Choice choice; public Choice getChoice() { - return choice; + return Objects.requireNonNull(choice); } @ValidationMethod(message = "name must be Coda") diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ConstraintViolationExceptionMapperTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ConstraintViolationExceptionMapperTest.java index 03178c92c4b..64df24b5209 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ConstraintViolationExceptionMapperTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ConstraintViolationExceptionMapperTest.java @@ -1,29 +1,30 @@ -package io.dropwizard.jersey.validation; - -import com.codahale.metrics.MetricRegistry; -import io.dropwizard.jersey.AbstractJerseyTest; -import io.dropwizard.jersey.DropwizardResourceConfig; -import io.dropwizard.jersey.jackson.JacksonMessageBodyProviderTest.Example; -import io.dropwizard.jersey.jackson.JacksonMessageBodyProviderTest.ListExample; -import io.dropwizard.jersey.jackson.JacksonMessageBodyProviderTest.PartialExample; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.Form; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assume.assumeThat; + package io.dropwizard.jersey.validation; + + import com.codahale.metrics.MetricRegistry; + import io.dropwizard.jersey.AbstractJerseyTest; + import io.dropwizard.jersey.DropwizardResourceConfig; + import io.dropwizard.jersey.jackson.JacksonMessageBodyProviderTest.Example; + import io.dropwizard.jersey.jackson.JacksonMessageBodyProviderTest.ListExample; + import io.dropwizard.jersey.jackson.JacksonMessageBodyProviderTest.PartialExample; + import org.junit.AfterClass; + import org.junit.BeforeClass; + import org.junit.Test; + + import javax.ws.rs.client.Entity; + import javax.ws.rs.core.Application; + import javax.ws.rs.core.Form; + import javax.ws.rs.core.GenericType; + import javax.ws.rs.core.MediaType; + import javax.ws.rs.core.Response; + import java.util.Collection; + import java.util.List; + import java.util.Locale; + import java.util.Map; + + import static java.util.Objects.requireNonNull; + import static org.assertj.core.api.Assertions.assertThat; + import static org.hamcrest.CoreMatchers.is; + import static org.junit.Assume.assumeThat; public class ConstraintViolationExceptionMapperTest extends AbstractJerseyTest { @@ -525,8 +526,8 @@ public void returnsValidatedMapRequestEntities() { Map map = response.readEntity(new GenericType>() { }); - assertThat(map.get("one").id).isEqualTo(1); - assertThat(map.get("two").id).isEqualTo(2); + assertThat(requireNonNull(map.get("one")).id).isEqualTo(1); + assertThat(requireNonNull(map.get("two")).id).isEqualTo(2); } @Test diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProviderTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProviderTest.java index ac5e1e72f6f..cd55c05988f 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProviderTest.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProviderTest.java @@ -1,18 +1,18 @@ package io.dropwizard.jersey.validation; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.io.IOException; -import java.lang.annotation.Annotation; +import io.dropwizard.jersey.errors.ErrorMessage; +import org.junit.Test; +import javax.annotation.Nullable; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ParamConverter; +import java.io.IOException; +import java.lang.annotation.Annotation; -import org.junit.Test; - -import io.dropwizard.jersey.errors.ErrorMessage; +import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FuzzyEnumParamConverterProviderTest { private final FuzzyEnumParamConverterProvider paramConverterProvider = new FuzzyEnumParamConverterProvider(); @@ -41,6 +41,7 @@ private enum ExplicitFromString { this.code = code; } + @Nullable public static ExplicitFromString fromString(String str) { for (ExplicitFromString e : ExplicitFromString.values()) { if (str.equals(e.code)) { @@ -106,6 +107,7 @@ private enum ExplicitFromStringNonStatic { this.code = code; } + @Nullable public ExplicitFromStringNonStatic fromString(String str) { for (ExplicitFromStringNonStatic e : ExplicitFromStringNonStatic.values()) { if (str.equals(e.code)) { @@ -126,6 +128,7 @@ private enum ExplicitFromStringPrivate { this.code = code; } + @Nullable private static ExplicitFromStringPrivate fromString(String str) { for (ExplicitFromStringPrivate e : ExplicitFromStringPrivate.values()) { if (str.equals(e.code)) { @@ -140,10 +143,13 @@ static class Klass { } + private ParamConverter getConverter(Class rawType) { + return requireNonNull(paramConverterProvider.getConverter(rawType, null, new Annotation[] {})); + } + @Test public void testFuzzyEnum() throws IOException { - final ParamConverter converter = - paramConverterProvider.getConverter(Fuzzy.class, null, new Annotation[] {}); + final ParamConverter converter = getConverter(Fuzzy.class); assertThat(converter.fromString(null)).isNull(); assertThat(converter.fromString("A.1")).isSameAs(Fuzzy.A_1); assertThat(converter.fromString("A-1")).isSameAs(Fuzzy.A_1); @@ -159,24 +165,21 @@ public void testFuzzyEnum() throws IOException { .matches(e -> ((ErrorMessage) e[0]).getMessage().contains("A_2")); } + @Test public void testToString() throws IOException { - final ParamConverter converter = - paramConverterProvider.getConverter(WithToString.class, null, new Annotation[] {}); + final ParamConverter converter = getConverter(WithToString.class); assertThat(converter.toString(WithToString.A_1)).isEqualTo(""); } @Test public void testNonEnum() throws IOException { - final ParamConverter converter = - paramConverterProvider.getConverter(Klass.class, null, new Annotation[] {}); - assertThat(converter).isNull(); + assertThat(paramConverterProvider.getConverter(Klass.class, null, new Annotation[] {})).isNull(); } @Test public void testEnumViaExplicitFromString() throws IOException { - final ParamConverter converter = - paramConverterProvider.getConverter(ExplicitFromString.class, null, new Annotation[] {}); + final ParamConverter converter = getConverter(ExplicitFromString.class); assertThat(converter.fromString("1")).isSameAs(ExplicitFromString.A); assertThat(converter.fromString("2")).isSameAs(ExplicitFromString.B); assertThatThrownBy(() -> converter.fromString("3")).isInstanceOf(WebApplicationException.class) @@ -188,7 +191,7 @@ public void testEnumViaExplicitFromString() throws IOException { @Test public void testEnumViaExplicitFromStringThatThrowsWebApplicationException() throws IOException { final ParamConverter converter = - paramConverterProvider.getConverter(ExplicitFromStringThrowsWebApplicationException.class, null, new Annotation[] {}); + getConverter(ExplicitFromStringThrowsWebApplicationException.class); assertThatThrownBy(() -> converter.fromString("3")).isInstanceOf(WebApplicationException.class) .extracting(e -> (((WebApplicationException)e).getResponse()).getStatusInfo()) .matches(e -> ((Response.StatusType) e[0]).getStatusCode() == 418) @@ -198,7 +201,7 @@ public void testEnumViaExplicitFromStringThatThrowsWebApplicationException() thr @Test public void testEnumViaExplicitFromStringThatThrowsOtherException() throws IOException { final ParamConverter converter = - paramConverterProvider.getConverter(ExplicitFromStringThrowsOtherException.class, null, new Annotation[] {}); + getConverter(ExplicitFromStringThrowsOtherException.class); assertThatThrownBy(() -> converter.fromString("1")).isInstanceOf(WebApplicationException.class) .extracting(e -> (((WebApplicationException)e).getResponse()).getEntity()) .matches(e -> ((ErrorMessage) e[0]).getCode() == 400) @@ -207,8 +210,7 @@ public void testEnumViaExplicitFromStringThatThrowsOtherException() throws IOExc @Test public void testEnumViaExplicitFromStringNonStatic() throws IOException { - final ParamConverter converter = - paramConverterProvider.getConverter(ExplicitFromStringNonStatic.class, null, new Annotation[] {}); + final ParamConverter converter = getConverter(ExplicitFromStringNonStatic.class); assertThatThrownBy(() -> converter.fromString("1")).isInstanceOf(WebApplicationException.class) .extracting(e -> (((WebApplicationException)e).getResponse()).getEntity()) .matches(e -> ((ErrorMessage) e[0]).getCode() == 400) @@ -220,8 +222,7 @@ public void testEnumViaExplicitFromStringNonStatic() throws IOException { @Test public void testEnumViaExplicitFromStringPrivate() throws IOException { - final ParamConverter converter = - paramConverterProvider.getConverter(ExplicitFromStringPrivate.class, null, new Annotation[] {}); + final ParamConverter converter = getConverter(ExplicitFromStringPrivate.class); assertThatThrownBy(() -> converter.fromString("1")).isInstanceOf(WebApplicationException.class) .extracting(e -> (((WebApplicationException)e).getResponse()).getEntity()) .matches(e -> ((ErrorMessage) e[0]).getCode() == 400) diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/SubBeanParameter.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/SubBeanParameter.java index 07e1daaad4a..e30e2a4f01e 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/SubBeanParameter.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/SubBeanParameter.java @@ -11,7 +11,7 @@ public class SubBeanParameter extends BeanParameter { @QueryParam("address") @NotEmpty - private String address; + private String address = ""; @ValidationMethod(message = "address must not be uppercase", diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidRepresentation.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidRepresentation.java index 2628c202e24..8281f2c3cfe 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidRepresentation.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidRepresentation.java @@ -5,7 +5,7 @@ public class ValidRepresentation { @NotEmpty - private String name; + private String name = ""; @JsonProperty public String getName() { diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidatingResource.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidatingResource.java index eb9cfb5c268..f4d7cee4fe7 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidatingResource.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidatingResource.java @@ -46,7 +46,7 @@ public class ValidatingResource { @QueryParam("sort") @Pattern(regexp = "^(asc|desc)$") - private String sortParam; + private String sortParam = ""; @POST @Path("foo") diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedFailingExample.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedFailingExample.java index d08f4d08148..7f2ba917c3e 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedFailingExample.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedFailingExample.java @@ -2,13 +2,16 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.Nullable; import javax.validation.Valid; public class WrappedFailingExample { @Valid + @Nullable private FailingExample example; @JsonProperty + @Nullable public FailingExample getExample() { return example; } diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedValidRepresentation.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedValidRepresentation.java index 58f344ffb63..49c69db489f 100644 --- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedValidRepresentation.java +++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/WrappedValidRepresentation.java @@ -2,13 +2,16 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.Nullable; import javax.validation.Valid; public class WrappedValidRepresentation { @Valid + @Nullable private ValidRepresentation representation; @JsonProperty + @Nullable public ValidRepresentation getRepresentation() { return representation; } diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java index 3985e03cbf5..458fbdc0b16 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java @@ -4,6 +4,7 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.gzip.GzipHandler; +import javax.annotation.Nullable; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; @@ -255,6 +256,7 @@ public Enumeration getHeaders(final String name) { * @param name a String specifying the name of a request header */ @Override + @Nullable public String getHeader(final String name) { if (headerName.equalsIgnoreCase(name)) { return null; diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/ConnectorFactory.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/ConnectorFactory.java index 27c9e93a35b..39df3422cd5 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/ConnectorFactory.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/ConnectorFactory.java @@ -7,6 +7,8 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.ThreadPool; +import javax.annotation.Nullable; + /** * A factory for creating Jetty {@link Connector}s. */ @@ -24,5 +26,5 @@ public interface ConnectorFactory extends Discoverable { Connector build(Server server, MetricRegistry metrics, String name, - ThreadPool threadPool); + @Nullable ThreadPool threadPool); } diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/GzipHandlerFactory.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/GzipHandlerFactory.java index d02c818bbf3..bfe86d00a72 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/GzipHandlerFactory.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/GzipHandlerFactory.java @@ -5,6 +5,7 @@ import io.dropwizard.util.Size; import org.eclipse.jetty.server.Handler; +import javax.annotation.Nullable; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @@ -83,7 +84,11 @@ public class GzipHandlerFactory { // By default compress responses for all user-agents private Set excludedUserAgentPatterns = new HashSet<>(); + + @Nullable private Set compressedMimeTypes; + + @Nullable private Set includedMethods; @Min(Deflater.DEFAULT_COMPRESSION) @@ -93,7 +98,7 @@ public class GzipHandlerFactory { private boolean gzipCompatibleInflation = true; private boolean syncFlush = false; - + @JsonProperty public boolean isEnabled() { return enabled; @@ -125,6 +130,7 @@ public void setBufferSize(Size size) { } @JsonProperty + @Nullable public Set getCompressedMimeTypes() { return compressedMimeTypes; } @@ -163,6 +169,7 @@ public void setExcludedUserAgentPatterns(Set excludedUserAgentPatterns) } @JsonProperty + @Nullable public Set getIncludedMethods() { return includedMethods; } @@ -171,7 +178,7 @@ public Set getIncludedMethods() { public void setIncludedMethods(Set methods) { this.includedMethods = methods; } - + @JsonProperty public boolean isSyncFlush() { return syncFlush; @@ -182,7 +189,7 @@ public void setSyncFlush(boolean syncFlush) { this.syncFlush = syncFlush; } - public BiDiGzipHandler build(Handler handler) { + public BiDiGzipHandler build(@Nullable Handler handler) { final BiDiGzipHandler gzipHandler = new BiDiGzipHandler(); gzipHandler.setHandler(handler); gzipHandler.setMinGzipSize((int) minimumEntitySize.toBytes()); diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpConnectorFactory.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpConnectorFactory.java index 0757b5482f7..0aa44bd06e5 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpConnectorFactory.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpConnectorFactory.java @@ -24,6 +24,7 @@ import org.eclipse.jetty.util.thread.ThreadPool; import org.hibernate.validator.valuehandling.UnwrapValidatedValue; +import javax.annotation.Nullable; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.util.Optional; @@ -220,7 +221,8 @@ public static ConnectorFactory admin() { @PortRange private int port = 8080; - private String bindHost = null; + @Nullable + private String bindHost; private boolean inheritChannel = false; @@ -248,7 +250,8 @@ public static ConnectorFactory admin() { @MinDuration(value = 1, unit = TimeUnit.MILLISECONDS) private Duration idleTimeout = Duration.seconds(30); - private Duration blockingTimeout = null; + @Nullable + private Duration blockingTimeout; @NotNull @MinSize(value = 1, unit = SizeUnit.BYTES) @@ -273,10 +276,13 @@ public static ConnectorFactory admin() { private Optional selectorThreads = Optional.empty(); @Min(0) + @Nullable private Integer acceptQueueSize; private boolean reuseAddress = true; - private Duration soLingerTime = null; + + @Nullable + private Duration soLingerTime; private boolean useServerHeader = false; private boolean useDateHeader = true; private boolean useForwardedHeaders = true; @@ -293,6 +299,7 @@ public void setPort(int port) { } @JsonProperty + @Nullable public String getBindHost() { return bindHost; } @@ -373,6 +380,7 @@ public void setIdleTimeout(Duration idleTimeout) { } @JsonProperty + @Nullable public Duration getBlockingTimeout() { return blockingTimeout; } @@ -443,6 +451,7 @@ public void setSelectorThreads(Optional selectorThreads) { } @JsonProperty + @Nullable public Integer getAcceptQueueSize() { return acceptQueueSize; } @@ -463,6 +472,7 @@ public void setReuseAddress(boolean reuseAddress) { } @JsonProperty + @Nullable public Duration getSoLingerTime() { return soLingerTime; } @@ -517,7 +527,7 @@ public void setHttpCompliance(HttpCompliance httpCompliance) { public Connector build(Server server, MetricRegistry metrics, String name, - ThreadPool threadPool) { + @Nullable ThreadPool threadPool) { final HttpConfiguration httpConfig = buildHttpConfiguration(); final HttpConnectionFactory httpConnectionFactory = buildHttpConnectionFactory(httpConfig); @@ -542,7 +552,7 @@ protected ServerConnector buildConnector(Server server, Scheduler scheduler, ByteBufferPool bufferPool, String name, - ThreadPool threadPool, + @Nullable ThreadPool threadPool, ConnectionFactory... factories) { final ServerConnector connector = new ServerConnector(server, threadPool, diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpsConnectorFactory.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpsConnectorFactory.java index 3b7dd4419a9..494c2377da4 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpsConnectorFactory.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/HttpsConnectorFactory.java @@ -24,6 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import java.io.File; @@ -224,42 +225,77 @@ public class HttpsConnectorFactory extends HttpConnectorFactory { private static final Logger LOGGER = LoggerFactory.getLogger(HttpsConnectorFactory.class); private static final AtomicBoolean LOGGED = new AtomicBoolean(false); + @Nullable private String keyStorePath; + @Nullable private String keyStorePassword; @NotEmpty private String keyStoreType = "JKS"; + @Nullable private String keyStoreProvider; + @Nullable private String trustStorePath; + @Nullable private String trustStorePassword; @NotEmpty private String trustStoreType = "JKS"; + @Nullable private String trustStoreProvider; + @Nullable private String keyManagerPassword; + @Nullable private Boolean needClientAuth; + + @Nullable private Boolean wantClientAuth; + + @Nullable private String certAlias; + + @Nullable private File crlPath; + + @Nullable private Boolean enableCRLDP; + + @Nullable private Boolean enableOCSP; + + @Nullable private Integer maxCertPathLength; + + @Nullable private URI ocspResponderUrl; + + @Nullable private String jceProvider; private boolean validateCerts = false; private boolean validatePeers = false; + + @Nullable private List supportedProtocols; + + @Nullable private List excludedProtocols; + + @Nullable private List supportedCipherSuites; + + @Nullable private List excludedCipherSuites; + private boolean allowRenegotiation = true; + + @Nullable private String endpointIdentificationAlgorithm; @JsonProperty @@ -273,6 +309,7 @@ public void setAllowRenegotiation(boolean allowRenegotiation) { } @JsonProperty + @Nullable public String getEndpointIdentificationAlgorithm() { return endpointIdentificationAlgorithm; } @@ -283,6 +320,7 @@ public void setEndpointIdentificationAlgorithm(String endpointIdentificationAlgo } @JsonProperty + @Nullable public String getKeyStorePath() { return keyStorePath; } @@ -293,6 +331,7 @@ public void setKeyStorePath(String keyStorePath) { } @JsonProperty + @Nullable public String getKeyStorePassword() { return keyStorePassword; } @@ -313,6 +352,7 @@ public void setKeyStoreType(String keyStoreType) { } @JsonProperty + @Nullable public String getKeyStoreProvider() { return keyStoreProvider; } @@ -333,6 +373,7 @@ public void setTrustStoreType(String trustStoreType) { } @JsonProperty + @Nullable public String getTrustStoreProvider() { return trustStoreProvider; } @@ -343,6 +384,7 @@ public void setTrustStoreProvider(String trustStoreProvider) { } @JsonProperty + @Nullable public String getKeyManagerPassword() { return keyManagerPassword; } @@ -353,6 +395,7 @@ public void setKeyManagerPassword(String keyManagerPassword) { } @JsonProperty + @Nullable public String getTrustStorePath() { return trustStorePath; } @@ -363,16 +406,18 @@ public void setTrustStorePath(String trustStorePath) { } @JsonProperty + @Nullable public String getTrustStorePassword() { return trustStorePassword; } @JsonProperty - public void setTrustStorePassword(String trustStorePassword) { + public void setTrustStorePassword(@Nullable String trustStorePassword) { this.trustStorePassword = trustStorePassword; } @JsonProperty + @Nullable public Boolean getNeedClientAuth() { return needClientAuth; } @@ -383,6 +428,7 @@ public void setNeedClientAuth(Boolean needClientAuth) { } @JsonProperty + @Nullable public Boolean getWantClientAuth() { return wantClientAuth; } @@ -393,6 +439,7 @@ public void setWantClientAuth(Boolean wantClientAuth) { } @JsonProperty + @Nullable public String getCertAlias() { return certAlias; } @@ -403,6 +450,7 @@ public void setCertAlias(String certAlias) { } @JsonProperty + @Nullable public File getCrlPath() { return crlPath; } @@ -413,6 +461,7 @@ public void setCrlPath(File crlPath) { } @JsonProperty + @Nullable public Boolean getEnableCRLDP() { return enableCRLDP; } @@ -423,6 +472,7 @@ public void setEnableCRLDP(Boolean enableCRLDP) { } @JsonProperty + @Nullable public Boolean getEnableOCSP() { return enableOCSP; } @@ -433,6 +483,7 @@ public void setEnableOCSP(Boolean enableOCSP) { } @JsonProperty + @Nullable public Integer getMaxCertPathLength() { return maxCertPathLength; } @@ -443,6 +494,7 @@ public void setMaxCertPathLength(Integer maxCertPathLength) { } @JsonProperty + @Nullable public URI getOcspResponderUrl() { return ocspResponderUrl; } @@ -453,6 +505,7 @@ public void setOcspResponderUrl(URI ocspResponderUrl) { } @JsonProperty + @Nullable public String getJceProvider() { return jceProvider; } @@ -473,6 +526,7 @@ public void setValidatePeers(boolean validatePeers) { } @JsonProperty + @Nullable public List getSupportedProtocols() { return supportedProtocols; } @@ -483,6 +537,7 @@ public void setSupportedProtocols(List supportedProtocols) { } @JsonProperty + @Nullable public List getExcludedProtocols() { return excludedProtocols; } @@ -493,11 +548,13 @@ public void setExcludedProtocols(List excludedProtocols) { } @JsonProperty + @Nullable public List getSupportedCipherSuites() { return supportedCipherSuites; } @JsonProperty + @Nullable public List getExcludedCipherSuites() { return excludedCipherSuites; } @@ -534,7 +591,7 @@ public boolean isValidKeyStorePassword() { } @Override - public Connector build(Server server, MetricRegistry metrics, String name, ThreadPool threadPool) { + public Connector build(Server server, MetricRegistry metrics, String name, @Nullable ThreadPool threadPool) { final HttpConfiguration httpConfig = buildHttpConfiguration(); final HttpConnectionFactory httpConnectionFactory = buildHttpConnectionFactory(httpConfig); diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/Jetty93InstrumentedConnectionFactory.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/Jetty93InstrumentedConnectionFactory.java index 1458122da17..0903ba4004d 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/Jetty93InstrumentedConnectionFactory.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/Jetty93InstrumentedConnectionFactory.java @@ -7,8 +7,11 @@ import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.util.component.ContainerLifeCycle; +import javax.annotation.Nullable; import java.util.List; +import static java.util.Objects.requireNonNull; + /** * A version {@link com.codahale.metrics.jetty9.InstrumentedConnectionFactory}, which supports Jetty 9.3 API. * NOTE: This class could be replaced, when dropwizard-metrics-jetty9 will support Jetty 9.3. @@ -46,6 +49,8 @@ public List getProtocols() { public Connection newConnection(Connector connector, EndPoint endPoint) { final Connection connection = connectionFactory.newConnection(connector, endPoint); connection.addListener(new Connection.Listener() { + + @Nullable private Timer.Context context; @Override @@ -55,7 +60,7 @@ public void onOpened(Connection connection) { @Override public void onClosed(Connection connection) { - context.stop(); + requireNonNull(context).stop(); } }); return connection; diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/NetUtil.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/NetUtil.java index d7a4f51fb85..7685d0547f2 100644 --- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/NetUtil.java +++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/NetUtil.java @@ -16,6 +16,7 @@ package io.dropwizard.jetty; import com.google.common.io.Files; + import java.io.File; import java.io.IOException; import java.net.InetAddress; @@ -31,6 +32,8 @@ import java.util.Locale; import java.util.concurrent.atomic.AtomicReference; +import static java.util.Objects.requireNonNull; + /** * This class is taken from the Netty project, and all credit goes to them. * It has been modified, to remove dependencies on other classes, and to convert to methods, rather than a @@ -96,6 +99,7 @@ public static int getDefaultTcpBacklog() { * @param newLocalIpFilter the new local ip filter */ public static void setLocalIpFilter(LocalIpFilter newLocalIpFilter) { + requireNonNull(newLocalIpFilter); LOCAL_IP_FILTER.set(newLocalIpFilter); } @@ -105,7 +109,7 @@ public static void setLocalIpFilter(LocalIpFilter newLocalIpFilter) { * @return ip filter */ public static LocalIpFilter getLocalIpFilter() { - return LOCAL_IP_FILTER.get(); + return requireNonNull(LOCAL_IP_FILTER.get()); } /** @@ -142,7 +146,7 @@ public static Collection getAllLocalIPs() throws SocketException { final Enumeration adrs = nif.getInetAddresses(); while (adrs.hasMoreElements()) { final InetAddress adr = adrs.nextElement(); - if (LOCAL_IP_FILTER.get().use(nif, adr)) { + if (getLocalIpFilter().use(nif, adr)) { listAdr.add(adr); } } diff --git a/dropwizard-lifecycle/src/test/java/io/dropwizard/lifecycle/setup/ScheduledExecutorServiceBuilderTest.java b/dropwizard-lifecycle/src/test/java/io/dropwizard/lifecycle/setup/ScheduledExecutorServiceBuilderTest.java index 0ddbd7e64ec..d3c1b09660e 100644 --- a/dropwizard-lifecycle/src/test/java/io/dropwizard/lifecycle/setup/ScheduledExecutorServiceBuilderTest.java +++ b/dropwizard-lifecycle/src/test/java/io/dropwizard/lifecycle/setup/ScheduledExecutorServiceBuilderTest.java @@ -1,26 +1,28 @@ package io.dropwizard.lifecycle.setup; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +import io.dropwizard.lifecycle.ExecutorServiceManager; +import io.dropwizard.util.Duration; +import org.junit.After; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import javax.annotation.Nullable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import io.dropwizard.lifecycle.ExecutorServiceManager; -import io.dropwizard.util.Duration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; public class ScheduledExecutorServiceBuilderTest { private static final Duration DEFAULT_SHUTDOWN_PERIOD = Duration.seconds(5L); private final LifecycleEnvironment le; + + @Nullable private ScheduledExecutorService execTracker; public ScheduledExecutorServiceBuilderTest() { diff --git a/dropwizard-logging/src/main/java/io/dropwizard/logging/AbstractAppenderFactory.java b/dropwizard-logging/src/main/java/io/dropwizard/logging/AbstractAppenderFactory.java index 24fa8f0ab97..e6df778a4b1 100644 --- a/dropwizard-logging/src/main/java/io/dropwizard/logging/AbstractAppenderFactory.java +++ b/dropwizard-logging/src/main/java/io/dropwizard/logging/AbstractAppenderFactory.java @@ -15,6 +15,7 @@ import io.dropwizard.logging.filter.FilterFactory; import io.dropwizard.logging.layout.LayoutFactory; +import javax.annotation.Nullable; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @@ -88,6 +89,7 @@ public abstract class AbstractAppenderFactory @NotNull protected Level threshold = Level.ALL; + @Nullable protected String logFormat; @NotNull @@ -136,6 +138,7 @@ public void setThreshold(String threshold) { } @JsonProperty + @Nullable public String getLogFormat() { return logFormat; } diff --git a/dropwizard-logging/src/main/java/io/dropwizard/logging/FileAppenderFactory.java b/dropwizard-logging/src/main/java/io/dropwizard/logging/FileAppenderFactory.java index c916638ff93..6140e4a5f86 100644 --- a/dropwizard-logging/src/main/java/io/dropwizard/logging/FileAppenderFactory.java +++ b/dropwizard-logging/src/main/java/io/dropwizard/logging/FileAppenderFactory.java @@ -22,8 +22,12 @@ import io.dropwizard.util.Size; import io.dropwizard.validation.MinSize; import io.dropwizard.validation.ValidationMethod; + +import javax.annotation.Nullable; import javax.validation.constraints.Min; +import static java.util.Objects.requireNonNull; + /** * An {@link AppenderFactory} implementation which provides an appender that writes events to a file, archiving older * files as it goes. @@ -124,15 +128,18 @@ @JsonTypeName("file") public class FileAppenderFactory extends AbstractAppenderFactory { + @Nullable private String currentLogFilename; private boolean archive = true; + @Nullable private String archivedLogFilenamePattern; @Min(0) private int archivedFileCount = 5; + @Nullable private Size maxFileSize; @MinSize(1) @@ -141,12 +148,13 @@ public class FileAppenderFactory extends Abst private boolean immediateFlush = true; @JsonProperty + @Nullable public String getCurrentLogFilename() { return currentLogFilename; } @JsonProperty - public void setCurrentLogFilename(String currentLogFilename) { + public void setCurrentLogFilename(@Nullable String currentLogFilename) { this.currentLogFilename = currentLogFilename; } @@ -161,6 +169,7 @@ public void setArchive(boolean archive) { } @JsonProperty + @Nullable public String getArchivedLogFilenamePattern() { return archivedLogFilenamePattern; } @@ -181,6 +190,7 @@ public void setArchivedFileCount(int archivedFileCount) { } @JsonProperty + @Nullable public Size getMaxFileSize() { return maxFileSize; } @@ -264,7 +274,7 @@ protected FileAppender buildAppender(LoggerContext context) { appender.setFile(currentLogFilename); appender.setBufferSize(new FileSize(bufferSize.toBytes())); - if (maxFileSize != null && !archivedLogFilenamePattern.contains("%d")) { + if (maxFileSize != null && !requireNonNull(archivedLogFilenamePattern).contains("%d")) { final FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy(); rollingPolicy.setContext(context); rollingPolicy.setMaxIndex(getArchivedFileCount()); diff --git a/dropwizard-logging/src/test/java/io/dropwizard/logging/PrefixedRootCauseFirstThrowableProxyConverterTest.java b/dropwizard-logging/src/test/java/io/dropwizard/logging/PrefixedRootCauseFirstThrowableProxyConverterTest.java index d7ebf3d8cbb..07fc21f0b20 100644 --- a/dropwizard-logging/src/test/java/io/dropwizard/logging/PrefixedRootCauseFirstThrowableProxyConverterTest.java +++ b/dropwizard-logging/src/test/java/io/dropwizard/logging/PrefixedRootCauseFirstThrowableProxyConverterTest.java @@ -5,6 +5,7 @@ import org.junit.Before; import org.junit.Test; +import javax.annotation.Nullable; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Collections; @@ -23,6 +24,7 @@ public class PrefixedRootCauseFirstThrowableProxyConverterTest { private final ThrowableProxy proxy = new ThrowableProxy(getException()); + @Nullable private Exception getException() { try { throwOuterWrapper(); diff --git a/dropwizard-metrics-ganglia/src/main/java/io/dropwizard/metrics/ganglia/GangliaReporterFactory.java b/dropwizard-metrics-ganglia/src/main/java/io/dropwizard/metrics/ganglia/GangliaReporterFactory.java index ff79dead77b..388d351dfd9 100644 --- a/dropwizard-metrics-ganglia/src/main/java/io/dropwizard/metrics/ganglia/GangliaReporterFactory.java +++ b/dropwizard-metrics-ganglia/src/main/java/io/dropwizard/metrics/ganglia/GangliaReporterFactory.java @@ -12,6 +12,7 @@ import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; +import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import java.io.IOException; import java.util.Optional; @@ -93,8 +94,13 @@ public class GangliaReporterFactory extends BaseReporterFactory { @Range(min = 0, max = 255) private int ttl = 1; + @Nullable private String prefix; + + @Nullable private UUID uuid; + + @Nullable private String spoof; @JsonProperty @@ -157,6 +163,7 @@ public void setTtl(int ttl) { this.ttl = ttl; } + @Nullable public String getPrefix() { return prefix; } diff --git a/dropwizard-metrics/src/main/java/io/dropwizard/metrics/CsvReporterFactory.java b/dropwizard-metrics/src/main/java/io/dropwizard/metrics/CsvReporterFactory.java index 1ed7ccf5e28..ff5e637df96 100644 --- a/dropwizard-metrics/src/main/java/io/dropwizard/metrics/CsvReporterFactory.java +++ b/dropwizard-metrics/src/main/java/io/dropwizard/metrics/CsvReporterFactory.java @@ -6,9 +6,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; -import javax.validation.constraints.NotNull; +import javax.annotation.Nullable; import java.io.File; +import static java.util.Objects.requireNonNull; + /** * A factory for configuring and building {@link CsvReporter} instances. *

@@ -39,21 +41,23 @@ */ @JsonTypeName("csv") public class CsvReporterFactory extends BaseFormattedReporterFactory { - @NotNull + @Nullable private File file; @JsonProperty + @Nullable public File getFile() { return file; } @JsonProperty - public void setFile(File file) { + public void setFile(@Nullable File file) { this.file = file; } @Override public ScheduledReporter build(MetricRegistry registry) { + final File file = requireNonNull(this.file, "File is not set"); final boolean creation = file.mkdirs(); if (!creation && !file.exists()) { throw new RuntimeException("Failed to create" + file.getAbsolutePath()); diff --git a/dropwizard-metrics/src/main/java/io/dropwizard/metrics/Slf4jReporterFactory.java b/dropwizard-metrics/src/main/java/io/dropwizard/metrics/Slf4jReporterFactory.java index 10890ca4882..e53cbea4cef 100644 --- a/dropwizard-metrics/src/main/java/io/dropwizard/metrics/Slf4jReporterFactory.java +++ b/dropwizard-metrics/src/main/java/io/dropwizard/metrics/Slf4jReporterFactory.java @@ -10,6 +10,8 @@ import org.slf4j.LoggerFactory; import org.slf4j.MarkerFactory; +import javax.annotation.Nullable; + /** * A {@link ReporterFactory} for {@link Slf4jReporter} instances. *

@@ -40,6 +42,7 @@ public class Slf4jReporterFactory extends BaseReporterFactory { @NotEmpty private String loggerName = "metrics"; + @Nullable private String markerName; @JsonProperty("logger") @@ -57,12 +60,13 @@ public Logger getLogger() { } @JsonProperty + @Nullable public String getMarkerName() { return markerName; } @JsonProperty - public void setMarkerName(String markerName) { + public void setMarkerName(@Nullable String markerName) { this.markerName = markerName; } diff --git a/dropwizard-metrics/src/test/java/io/dropwizard/metrics/BaseReporterFactoryTest.java b/dropwizard-metrics/src/test/java/io/dropwizard/metrics/BaseReporterFactoryTest.java index 9dbead3fa99..719ffa3efd0 100644 --- a/dropwizard-metrics/src/test/java/io/dropwizard/metrics/BaseReporterFactoryTest.java +++ b/dropwizard-metrics/src/test/java/io/dropwizard/metrics/BaseReporterFactoryTest.java @@ -82,13 +82,13 @@ public ScheduledReporter build(MetricRegistry registry) { }; @Parameterized.Parameter - public ImmutableSet includes; + public ImmutableSet includes = ImmutableSet.of(); @Parameterized.Parameter(1) - public ImmutableSet excludes; + public ImmutableSet excludes = ImmutableSet.of(); @Parameterized.Parameter(2) - public String name; + public String name = ""; @Parameterized.Parameter(3) public boolean expectedDefaultResult; @@ -100,7 +100,7 @@ public ScheduledReporter build(MetricRegistry registry) { public boolean expectedSubstringResult; @Parameterized.Parameter(6) - public String msg; + public String msg = ""; private final Metric metric = mock(Metric.class); diff --git a/dropwizard-metrics/src/test/java/io/dropwizard/metrics/MetricAttributesTest.java b/dropwizard-metrics/src/test/java/io/dropwizard/metrics/MetricAttributesTest.java index eec2fad319b..1c57654bc35 100644 --- a/dropwizard-metrics/src/test/java/io/dropwizard/metrics/MetricAttributesTest.java +++ b/dropwizard-metrics/src/test/java/io/dropwizard/metrics/MetricAttributesTest.java @@ -40,13 +40,13 @@ public ScheduledReporter build(MetricRegistry registry) { }; @Parameter - public EnumSet includes; + public EnumSet includes = EnumSet.noneOf(MetricAttribute.class); @Parameter(1) - public EnumSet excludes; + public EnumSet excludes = EnumSet.noneOf(MetricAttribute.class); @Parameter(2) - public EnumSet expectedResult; + public EnumSet expectedResult = EnumSet.noneOf(MetricAttribute.class); @Test public void testGetDisabledAttributes() { diff --git a/dropwizard-migrations/src/main/java/io/dropwizard/migrations/AbstractLiquibaseCommand.java b/dropwizard-migrations/src/main/java/io/dropwizard/migrations/AbstractLiquibaseCommand.java index 146d7e75fb5..99e0841513f 100644 --- a/dropwizard-migrations/src/main/java/io/dropwizard/migrations/AbstractLiquibaseCommand.java +++ b/dropwizard-migrations/src/main/java/io/dropwizard/migrations/AbstractLiquibaseCommand.java @@ -17,6 +17,7 @@ import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; +import javax.annotation.Nullable; import java.sql.SQLException; public abstract class AbstractLiquibaseCommand extends ConfiguredCommand { @@ -59,7 +60,7 @@ public void configure(Subparser subparser) { @Override @SuppressWarnings("UseOfSystemOutOrSystemErr") - protected void run(Bootstrap bootstrap, Namespace namespace, T configuration) throws Exception { + protected void run(@Nullable Bootstrap bootstrap, Namespace namespace, T configuration) throws Exception { final PooledDataSourceFactory dbConfig = strategy.getDataSourceFactory(configuration); dbConfig.asSingleConnectionPool(); diff --git a/dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbCommand.java b/dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbCommand.java index 41bef0962ee..f1a471065c5 100644 --- a/dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbCommand.java +++ b/dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbCommand.java @@ -9,6 +9,8 @@ import java.util.SortedMap; import java.util.TreeMap; +import static java.util.Objects.requireNonNull; + public class DbCommand extends AbstractLiquibaseCommand { private static final String COMMAND_NAME_ATTR = "subcommand"; private final SortedMap> subcommands; @@ -48,7 +50,8 @@ public void configure(Subparser subparser) { @Override public void run(Namespace namespace, Liquibase liquibase) throws Exception { - final AbstractLiquibaseCommand subcommand = subcommands.get(namespace.getString(COMMAND_NAME_ATTR)); + final AbstractLiquibaseCommand subcommand = + requireNonNull(subcommands.get(namespace.getString(COMMAND_NAME_ATTR)), "Unable find the command"); subcommand.run(namespace, liquibase); } } diff --git a/dropwizard-request-logging/src/main/java/io/dropwizard/request/logging/layout/SafeRequestParameterConverter.java b/dropwizard-request-logging/src/main/java/io/dropwizard/request/logging/layout/SafeRequestParameterConverter.java index 6706f7cb0cb..cf256290df0 100644 --- a/dropwizard-request-logging/src/main/java/io/dropwizard/request/logging/layout/SafeRequestParameterConverter.java +++ b/dropwizard-request-logging/src/main/java/io/dropwizard/request/logging/layout/SafeRequestParameterConverter.java @@ -4,6 +4,7 @@ import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.util.OptionHelper; +import javax.annotation.Nullable; import java.util.Arrays; /** @@ -13,6 +14,7 @@ */ public class SafeRequestParameterConverter extends AccessConverter { + @Nullable private String key; @Override diff --git a/dropwizard-servlets/src/main/java/io/dropwizard/servlets/assets/AssetServlet.java b/dropwizard-servlets/src/main/java/io/dropwizard/servlets/assets/AssetServlet.java index 0f42d565cf1..522368c415d 100644 --- a/dropwizard-servlets/src/main/java/io/dropwizard/servlets/assets/AssetServlet.java +++ b/dropwizard-servlets/src/main/java/io/dropwizard/servlets/assets/AssetServlet.java @@ -9,6 +9,7 @@ import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; +import javax.annotation.Nullable; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; @@ -54,7 +55,11 @@ public long getLastModifiedTime() { private final String resourcePath; private final String uriPath; + + @Nullable private final String indexFile; + + @Nullable private final Charset defaultCharset; /** @@ -75,8 +80,8 @@ public long getLastModifiedTime() { */ public AssetServlet(String resourcePath, String uriPath, - String indexFile, - Charset defaultCharset) { + @Nullable String indexFile, + @Nullable Charset defaultCharset) { final String trimmedPath = SLASHES.trimFrom(resourcePath); this.resourcePath = trimmedPath.isEmpty() ? trimmedPath : trimmedPath + '/'; final String trimmedUri = SLASHES.trimTrailingFrom(uriPath); @@ -93,6 +98,7 @@ public String getUriPath() { return uriPath; } + @Nullable public String getIndexFile() { return indexFile; } @@ -194,6 +200,7 @@ protected void doGet(HttpServletRequest req, } } + @Nullable private CachedAsset loadAsset(String key) throws URISyntaxException, IOException { checkArgument(key.startsWith(uriPath)); final String requestedResourcePath = SLASHES.trimFrom(key.substring(uriPath.length())); diff --git a/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/LogConfigurationTask.java b/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/LogConfigurationTask.java index 580eb472bf1..b7b95a1a7d8 100644 --- a/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/LogConfigurationTask.java +++ b/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/LogConfigurationTask.java @@ -6,6 +6,7 @@ import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.PrintWriter; import java.util.List; @@ -67,6 +68,7 @@ private List getLoggerNames(ImmutableMultimap parameters return parameters.get("logger").asList(); } + @Nullable private Level getLoggerLevel(ImmutableMultimap parameters) { final List loggerLevels = parameters.get("level").asList(); return loggerLevels.isEmpty() ? null : Level.valueOf(loggerLevels.get(0)); diff --git a/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/TaskServlet.java b/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/TaskServlet.java index c4741cb7cc3..fa3ecd67927 100644 --- a/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/TaskServlet.java +++ b/dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/TaskServlet.java @@ -28,6 +28,7 @@ import java.util.concurrent.ConcurrentMap; import static com.codahale.metrics.MetricRegistry.name; +import static java.util.Objects.requireNonNull; /** * A servlet which provides access to administrative {@link Task}s. It only responds to {@code POST} @@ -118,7 +119,7 @@ protected void doPost(HttpServletRequest req, final PrintWriter output = resp.getWriter(); try { final TaskExecutor taskExecutor = taskExecutors.get(task); - taskExecutor.executeTask(getParams(req), getBody(req), output); + requireNonNull(taskExecutor).executeTask(getParams(req), getBody(req), output); } catch (Exception e) { LOGGER.error("Error running {}", task.getName(), e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); diff --git a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/SlowRequestFilterTest.java b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/SlowRequestFilterTest.java index 8d33c6e4d15..17f7b72e9e2 100644 --- a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/SlowRequestFilterTest.java +++ b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/SlowRequestFilterTest.java @@ -4,9 +4,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import javax.servlet.FilterChain; @@ -15,27 +12,18 @@ import javax.servlet.http.HttpServletResponse; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) public class SlowRequestFilterTest { - @Mock - private HttpServletRequest request; - - @Mock - private HttpServletResponse response; - - @Mock - private FilterChain chain; - - @Mock - private FilterConfig filterConfig; - - @Mock - private Logger logger; + private HttpServletRequest request = mock(HttpServletRequest.class); + private HttpServletResponse response = mock(HttpServletResponse.class); + private FilterChain chain = mock(FilterChain.class); + private FilterConfig filterConfig = mock(FilterConfig.class); + private Logger logger = mock(Logger.class); private SlowRequestFilter slowRequestFilter = new SlowRequestFilter(Duration.milliseconds(500)); diff --git a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/ThreadNameFilterTest.java b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/ThreadNameFilterTest.java index f15d9429354..dca19450fff 100644 --- a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/ThreadNameFilterTest.java +++ b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/ThreadNameFilterTest.java @@ -3,9 +3,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -14,23 +11,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) public class ThreadNameFilterTest { - @Mock - private HttpServletRequest request; + private HttpServletRequest request = mock(HttpServletRequest.class); - @Mock - private HttpServletResponse response; + private HttpServletResponse response = mock(HttpServletResponse.class); - @Mock - private FilterChain chain; + private FilterChain chain = mock(FilterChain.class); - @Mock - private FilterConfig filterConfig; + private FilterConfig filterConfig = mock(FilterConfig.class); private ThreadNameFilter threadNameFilter = new ThreadNameFilter(); diff --git a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/AssetServletTest.java b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/AssetServletTest.java index 80ba1a69b74..04c8633a6c0 100644 --- a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/AssetServletTest.java +++ b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/AssetServletTest.java @@ -11,6 +11,7 @@ import org.junit.BeforeClass; import org.junit.Test; +import javax.annotation.Nullable; import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; @@ -58,6 +59,7 @@ public NoCharsetAssetServlet() { private static final ServletTester SERVLET_TESTER = new ServletTester(); private final HttpTester.Request request = HttpTester.newRequest(); + @Nullable private HttpTester.Response response; @BeforeClass diff --git a/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java b/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java index c35ae7b5c16..a7346961392 100644 --- a/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java +++ b/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java @@ -27,6 +27,7 @@ import java.util.function.Function; import static com.google.common.base.MoreObjects.firstNonNull; +import static java.util.Objects.requireNonNull; /** * A test support class for starting and stopping your application at the start and end of a test class. @@ -40,6 +41,8 @@ */ public class DropwizardTestSupport { protected final Class> applicationClass; + + @Nullable protected final String configPath; protected final Set configOverrides; protected final Optional customPropertyPrefix; @@ -52,9 +55,16 @@ public class DropwizardTestSupport { */ protected final boolean explicitConfig; + @Nullable protected C configuration; + + @Nullable protected Application application; + + @Nullable protected Environment environment; + + @Nullable protected Server jettyServer; protected List> listeners = new ArrayList<>(); @@ -64,12 +74,12 @@ public DropwizardTestSupport(Class> applicationClass, this(applicationClass, configPath, Optional.empty(), configOverrides); } - public DropwizardTestSupport(Class> applicationClass, String configPath, + public DropwizardTestSupport(Class> applicationClass, @Nullable String configPath, Optional customPropertyPrefix, ConfigOverride... configOverrides) { this(applicationClass, configPath, customPropertyPrefix, ServerCommand::new, configOverrides); } - public DropwizardTestSupport(Class> applicationClass, String configPath, + public DropwizardTestSupport(Class> applicationClass, @Nullable String configPath, Optional customPropertyPrefix, Function, Command> commandInstantiator, ConfigOverride... configOverrides) { @@ -168,7 +178,7 @@ private void stopIfRequired() { } // Don't leak appenders into other test cases - configuration.getLoggingFactory().reset(); + requireNonNull(configuration).getLoggingFactory().reset(); } private void applyConfigOverrides() { @@ -191,7 +201,7 @@ private void startIfRequired() { try { application = newApplication(); - final Bootstrap bootstrap = new Bootstrap(application) { + final Bootstrap bootstrap = new Bootstrap(getApplication()) { @Override public void run(C configuration, Environment environment) throws Exception { environment.lifecycle().addServerLifecycleListener(server -> jettyServer = server); @@ -209,13 +219,13 @@ public void run(C configuration, Environment environment) throws Exception { }; if (explicitConfig) { bootstrap.setConfigurationFactoryFactory((klass, validator, objectMapper, propertyPrefix) -> - new POJOConfigurationFactory<>(configuration)); + new POJOConfigurationFactory<>(getConfiguration())); } else if (customPropertyPrefix.isPresent()) { bootstrap.setConfigurationFactoryFactory((klass, validator, objectMapper, propertyPrefix) -> new YamlConfigurationFactory<>(klass, validator, objectMapper, customPropertyPrefix.get())); } - application.initialize(bootstrap); + getApplication().initialize(bootstrap); final Command command = commandInstantiator.apply(application); final ImmutableMap.Builder file = ImmutableMap.builder(); @@ -232,20 +242,20 @@ public void run(C configuration, Environment environment) throws Exception { } public C getConfiguration() { - return configuration; + return requireNonNull(configuration); } public int getLocalPort() { - return ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort(); + return ((ServerConnector) requireNonNull(jettyServer).getConnectors()[0]).getLocalPort(); } public int getAdminPort() { - final Connector[] connectors = jettyServer.getConnectors(); + final Connector[] connectors = requireNonNull(jettyServer).getConnectors(); return ((ServerConnector) connectors[connectors.length - 1]).getLocalPort(); } public int getPort(int connectorIndex) { - return ((ServerConnector) jettyServer.getConnectors()[connectorIndex]).getLocalPort(); + return ((ServerConnector) requireNonNull(jettyServer).getConnectors()[connectorIndex]).getLocalPort(); } public Application newApplication() { @@ -258,11 +268,11 @@ public Application newApplication() { @SuppressWarnings("unchecked") public > A getApplication() { - return (A) application; + return (A) requireNonNull(application); } public Environment getEnvironment() { - return environment; + return requireNonNull(environment); } public ObjectMapper getObjectMapper() { diff --git a/dropwizard-testing/src/main/java/io/dropwizard/testing/POJOConfigurationFactory.java b/dropwizard-testing/src/main/java/io/dropwizard/testing/POJOConfigurationFactory.java index 61cdbff520f..29ec456033c 100644 --- a/dropwizard-testing/src/main/java/io/dropwizard/testing/POJOConfigurationFactory.java +++ b/dropwizard-testing/src/main/java/io/dropwizard/testing/POJOConfigurationFactory.java @@ -4,6 +4,7 @@ import io.dropwizard.Configuration; import io.dropwizard.configuration.ConfigurationSourceProvider; import io.dropwizard.configuration.YamlConfigurationFactory; +import io.dropwizard.jackson.Jackson; import java.io.File; @@ -13,7 +14,7 @@ public class POJOConfigurationFactory @SuppressWarnings("unchecked") public POJOConfigurationFactory(C cfg) { - super((Class) cfg.getClass(), null, null, null); + super((Class) cfg.getClass(), null, Jackson.newObjectMapper(), "dw"); configuration = cfg; } diff --git a/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardAppRule.java b/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardAppRule.java index 35d0131d16e..6cd7d6beeba 100644 --- a/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardAppRule.java +++ b/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardAppRule.java @@ -75,6 +75,8 @@ public class DropwizardAppRule extends ExternalResource private final DropwizardTestSupport testSupport; private final AtomicInteger recursiveCallCount = new AtomicInteger(0); + + @Nullable private Client client; public DropwizardAppRule(Class> applicationClass) { @@ -87,12 +89,12 @@ public DropwizardAppRule(Class> applicationClass, this(applicationClass, configPath, Optional.empty(), configOverrides); } - public DropwizardAppRule(Class> applicationClass, String configPath, + public DropwizardAppRule(Class> applicationClass, @Nullable String configPath, Optional customPropertyPrefix, ConfigOverride... configOverrides) { this(applicationClass, configPath, customPropertyPrefix, ServerCommand::new, configOverrides); } - public DropwizardAppRule(Class> applicationClass, String configPath, + public DropwizardAppRule(Class> applicationClass, @Nullable String configPath, Optional customPropertyPrefix, Function, Command> commandInstantiator, ConfigOverride... configOverrides) { this(new DropwizardTestSupport<>(applicationClass, configPath, customPropertyPrefix, commandInstantiator, diff --git a/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardTestResourceConfig.java b/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardTestResourceConfig.java index ab1666de0fa..54560489983 100644 --- a/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardTestResourceConfig.java +++ b/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/DropwizardTestResourceConfig.java @@ -49,6 +49,11 @@ class DropwizardTestResourceConfig extends DropwizardResourceConfig { } DropwizardTestResourceConfig(@Context ServletConfig servletConfig) { - this(CONFIGURATION_REGISTRY.get(requireNonNull(servletConfig.getInitParameter(CONFIGURATION_ID)))); + this(getConfiguration(servletConfig)); + } + + private static ResourceTestJerseyConfiguration getConfiguration(@Context ServletConfig servletConfig) { + final String id = requireNonNull(servletConfig.getInitParameter(CONFIGURATION_ID), "No configuration id"); + return requireNonNull(CONFIGURATION_REGISTRY.get(id), "No configuration"); } } diff --git a/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/ResourceTestRule.java b/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/ResourceTestRule.java index f4c85918d52..b44befa779b 100755 --- a/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/ResourceTestRule.java +++ b/dropwizard-testing/src/main/java/io/dropwizard/testing/junit/ResourceTestRule.java @@ -16,6 +16,7 @@ import org.junit.runner.Description; import org.junit.runners.model.Statement; +import javax.annotation.Nullable; import javax.validation.Validator; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; @@ -25,6 +26,8 @@ import java.util.Set; import java.util.function.Consumer; +import static java.util.Objects.requireNonNull; + /** * A JUnit {@link TestRule} for testing Jersey resources. */ @@ -116,6 +119,8 @@ public static Builder builder() { } private ResourceTestJerseyConfiguration configuration; + + @Nullable private JerseyTest test; private ResourceTestRule(ResourceTestJerseyConfiguration configuration) { @@ -151,7 +156,7 @@ public WebTarget target(String path) { * @return the {@link JerseyTest} configured {@link Client} */ public Client client() { - return test.client(); + return getJerseyTest().client(); } /** @@ -161,7 +166,7 @@ public Client client() { * @return the underlying {@link JerseyTest} */ public JerseyTest getJerseyTest() { - return test; + return requireNonNull(test); } @Override @@ -198,7 +203,7 @@ protected void configureClient(ClientConfig clientConfig) { base.evaluate(); } finally { DropwizardTestResourceConfig.CONFIGURATION_REGISTRY.remove(configuration.getId()); - test.tearDown(); + requireNonNull(test).tearDown(); } } }; diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/DropwizardTestSupportTest.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/DropwizardTestSupportTest.java index db4b51573ff..5d38af5ebcd 100644 --- a/dropwizard-testing/src/test/java/io/dropwizard/testing/DropwizardTestSupportTest.java +++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/DropwizardTestSupportTest.java @@ -116,11 +116,11 @@ public String test() { public static class TestConfiguration extends Configuration { @NotEmpty @JsonProperty - private String message; + private String message = ""; @NotEmpty @JsonProperty - private String extra; + private String extra = ""; public String getMessage() { return message; diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/Person.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/Person.java index 0b0fd0c6e9e..5cbdf00ec74 100644 --- a/dropwizard-testing/src/test/java/io/dropwizard/testing/Person.java +++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/Person.java @@ -5,8 +5,8 @@ import java.util.Objects; public class Person { - private String name; - private String email; + private String name = ""; + private String email = ""; public Person() { /* Jackson deserialization */ } diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/app/PersonResource.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/app/PersonResource.java index c61e9dab876..30b547bb34f 100644 --- a/dropwizard-testing/src/test/java/io/dropwizard/testing/app/PersonResource.java +++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/app/PersonResource.java @@ -7,6 +7,7 @@ import io.dropwizard.validation.Validated; import org.eclipse.jetty.io.EofException; +import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.groups.Default; @@ -20,6 +21,8 @@ import javax.ws.rs.core.MediaType; import java.util.Map; +import static java.util.Objects.requireNonNull; + @Path("/person/{name}") @Produces(MediaType.APPLICATION_JSON) public class PersonResource { @@ -67,12 +70,13 @@ public Person eofException() throws Exception { public String validationGroupsException( @Valid @Validated(Partial1.class) @BeanParam BeanParameter params, @Valid @Validated(Default.class) byte[] entity) { - return params.age.toString() + entity.length; + return requireNonNull(params.age).toString() + entity.length; } public interface Partial1 { } public static class BeanParameter { @QueryParam("age") + @Nullable public Integer age; } } diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/DropwizardAppRuleReentrantTest.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/DropwizardAppRuleReentrantTest.java index 8ea0e344536..b4023c1e4a0 100644 --- a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/DropwizardAppRuleReentrantTest.java +++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/DropwizardAppRuleReentrantTest.java @@ -1,32 +1,21 @@ package io.dropwizard.testing.junit; import io.dropwizard.testing.DropwizardTestSupport; -import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; public class DropwizardAppRuleReentrantTest { - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - DropwizardTestSupport testSupport; - - @Mock - Statement statement; - - @Mock - Description description; + DropwizardTestSupport testSupport = mock(DropwizardTestSupport.class); + Statement statement = mock(Statement.class); + Description description = mock(Description.class); @Test public void testReentrantRuleStartsApplicationOnlyOnce() throws Throwable { diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestConfiguration.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestConfiguration.java index aca2b5bc9e8..1fe3fbf9b77 100644 --- a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestConfiguration.java +++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestConfiguration.java @@ -8,11 +8,11 @@ public class TestConfiguration extends Configuration { @JsonProperty @NotEmpty - private String message; + private String message = ""; @JsonProperty @NotEmpty - private String extra; + private String extra = ""; public TestConfiguration() { } diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestEntity.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestEntity.java index 499a3867e1f..7c5ffe32bb7 100644 --- a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestEntity.java +++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit/TestEntity.java @@ -1,5 +1,6 @@ package io.dropwizard.testing.junit; +import javax.annotation.Nullable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -8,6 +9,8 @@ import javax.persistence.Table; import javax.validation.constraints.NotNull; +import static java.util.Objects.requireNonNull; + @Entity @Table(name = "test_entities") class TestEntity { @@ -19,13 +22,14 @@ class TestEntity { @NotNull @Column(name = "desc") + @Nullable private String description; protected TestEntity() { // for Hibernate } - TestEntity(final String description) { + TestEntity(@Nullable String description) { this.description = description; } @@ -34,7 +38,7 @@ long getId() { } String getDescription() { - return description; + return requireNonNull(description); } void setDescription(final String description) { diff --git a/dropwizard-util/src/main/java/io/dropwizard/util/Enums.java b/dropwizard-util/src/main/java/io/dropwizard/util/Enums.java index ba4495e75b2..082fa3b229b 100644 --- a/dropwizard-util/src/main/java/io/dropwizard/util/Enums.java +++ b/dropwizard-util/src/main/java/io/dropwizard/util/Enums.java @@ -2,6 +2,8 @@ import com.google.common.base.CharMatcher; +import javax.annotation.Nullable; + /** * Helper methods for enum types. */ @@ -20,6 +22,7 @@ public class Enums { * @param constants The list of constants for the {@link Enum} to which you wish to convert. * @return The enum or null, if no enum constant matched the input value. */ + @Nullable public static Enum fromStringFuzzy(String value, Enum[] constants) { final String text = CharMatcher.whitespace() .removeFrom(value) diff --git a/dropwizard-util/src/main/java/io/dropwizard/util/Generics.java b/dropwizard-util/src/main/java/io/dropwizard/util/Generics.java index c48e1954187..908c0d710c8 100644 --- a/dropwizard-util/src/main/java/io/dropwizard/util/Generics.java +++ b/dropwizard-util/src/main/java/io/dropwizard/util/Generics.java @@ -1,5 +1,6 @@ package io.dropwizard.util; +import javax.annotation.Nullable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; @@ -74,6 +75,7 @@ public static Class getTypeParameter(Class klass, Class bou } @SuppressWarnings("unchecked") + @Nullable private static Class determineClass(Class bound, Type candidate) { if (candidate instanceof Class) { final Class cls = (Class) candidate; diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxDurationValidator.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxDurationValidator.java index b84681ff496..89da4fbfe7f 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxDurationValidator.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxDurationValidator.java @@ -12,8 +12,8 @@ */ public class MaxDurationValidator implements ConstraintValidator { - private long maxQty; - private TimeUnit maxUnit; + private long maxQty = 0; + private TimeUnit maxUnit = TimeUnit.MILLISECONDS; @Override public void initialize(MaxDuration constraintAnnotation) { diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxSizeValidator.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxSizeValidator.java index 7eb6a676422..1c86e8be6dc 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxSizeValidator.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/MaxSizeValidator.java @@ -12,8 +12,8 @@ */ public class MaxSizeValidator implements ConstraintValidator { - private long maxQty; - private SizeUnit maxUnit; + private long maxQty = 0; + private SizeUnit maxUnit = SizeUnit.BYTES; @Override public void initialize(MaxSize constraintAnnotation) { diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/MinDurationValidator.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/MinDurationValidator.java index 48087ef33ec..861d5107624 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/MinDurationValidator.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/MinDurationValidator.java @@ -12,8 +12,8 @@ */ public class MinDurationValidator implements ConstraintValidator { - private long minQty; - private TimeUnit minUnit; + private long minQty = 0; + private TimeUnit minUnit = TimeUnit.MILLISECONDS; @Override public void initialize(MinDuration constraintAnnotation) { diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/MinSizeValidator.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/MinSizeValidator.java index ffd5e224b0a..3f613403b3d 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/MinSizeValidator.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/MinSizeValidator.java @@ -12,8 +12,8 @@ */ public class MinSizeValidator implements ConstraintValidator { - private long minQty; - private SizeUnit minUnit; + private long minQty = 0; + private SizeUnit minUnit = SizeUnit.BYTES; @Override public void initialize(MinSize constraintAnnotation) { diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/OneOfValidator.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/OneOfValidator.java index 0da7297aa0b..aedf606916e 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/OneOfValidator.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/OneOfValidator.java @@ -4,7 +4,7 @@ import javax.validation.ConstraintValidatorContext; public class OneOfValidator implements ConstraintValidator { - private String[] values; + private String[] values = new String[]{}; private boolean caseInsensitive; private boolean ignoreWhitespace; diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/selfvalidating/ValidationCaller.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/selfvalidating/ValidationCaller.java index 6588097866f..439e0880e41 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/selfvalidating/ValidationCaller.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/selfvalidating/ValidationCaller.java @@ -1,5 +1,7 @@ package io.dropwizard.validation.selfvalidating; +import javax.annotation.Nullable; + /** * This class represents a wrapper for calling validation methods annotated with @SelfValidation. * It is used as a base class for the code generation. @@ -8,12 +10,14 @@ */ public abstract class ValidationCaller { + @Nullable protected T validationObject; public void setValidationObject(T obj) { this.validationObject = obj; } + @Nullable public T getValidationObject() { return validationObject; } diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalDoubleValidatedValueUnwrapper.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalDoubleValidatedValueUnwrapper.java index 2239fcccdc5..132e387725c 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalDoubleValidatedValueUnwrapper.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalDoubleValidatedValueUnwrapper.java @@ -2,6 +2,7 @@ import org.hibernate.validator.spi.valuehandling.ValidatedValueUnwrapper; +import javax.annotation.Nullable; import java.lang.reflect.Type; import java.util.OptionalDouble; @@ -12,6 +13,7 @@ */ public class OptionalDoubleValidatedValueUnwrapper extends ValidatedValueUnwrapper { @Override + @Nullable public Object handleValidatedValue(final OptionalDouble optional) { return optional.isPresent() ? optional.getAsDouble() : null; } diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalIntValidatedValueUnwrapper.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalIntValidatedValueUnwrapper.java index 7c152543188..f7e3b4a1269 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalIntValidatedValueUnwrapper.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalIntValidatedValueUnwrapper.java @@ -2,6 +2,7 @@ import org.hibernate.validator.spi.valuehandling.ValidatedValueUnwrapper; +import javax.annotation.Nullable; import java.lang.reflect.Type; import java.util.OptionalInt; @@ -12,6 +13,7 @@ */ public class OptionalIntValidatedValueUnwrapper extends ValidatedValueUnwrapper { @Override + @Nullable public Object handleValidatedValue(final OptionalInt optional) { return optional.isPresent() ? optional.getAsInt() : null; } diff --git a/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalLongValidatedValueUnwrapper.java b/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalLongValidatedValueUnwrapper.java index 8f215cfbb71..ace3117342a 100644 --- a/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalLongValidatedValueUnwrapper.java +++ b/dropwizard-validation/src/main/java/io/dropwizard/validation/valuehandling/OptionalLongValidatedValueUnwrapper.java @@ -2,6 +2,7 @@ import org.hibernate.validator.spi.valuehandling.ValidatedValueUnwrapper; +import javax.annotation.Nullable; import java.lang.reflect.Type; import java.util.OptionalLong; @@ -12,6 +13,7 @@ */ public class OptionalLongValidatedValueUnwrapper extends ValidatedValueUnwrapper { @Override + @Nullable public Object handleValidatedValue(final OptionalLong optional) { return optional.isPresent() ? optional.getAsLong() : null; } diff --git a/dropwizard-validation/src/test/java/io/dropwizard/validation/ConstraintPerson.java b/dropwizard-validation/src/test/java/io/dropwizard/validation/ConstraintPerson.java index 204cf59c772..94ea5f35d21 100644 --- a/dropwizard-validation/src/test/java/io/dropwizard/validation/ConstraintPerson.java +++ b/dropwizard-validation/src/test/java/io/dropwizard/validation/ConstraintPerson.java @@ -5,7 +5,7 @@ public class ConstraintPerson { @NotEmpty - private String name; + private String name = ""; @JsonProperty public String getName() { diff --git a/dropwizard-views-mustache/src/main/java/io/dropwizard/views/mustache/PerClassMustacheResolver.java b/dropwizard-views-mustache/src/main/java/io/dropwizard/views/mustache/PerClassMustacheResolver.java index be536e06b0b..f92176d9906 100644 --- a/dropwizard-views-mustache/src/main/java/io/dropwizard/views/mustache/PerClassMustacheResolver.java +++ b/dropwizard-views-mustache/src/main/java/io/dropwizard/views/mustache/PerClassMustacheResolver.java @@ -3,6 +3,7 @@ import com.github.mustachejava.MustacheResolver; import io.dropwizard.views.View; +import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -21,6 +22,7 @@ class PerClassMustacheResolver implements MustacheResolver { } @Override + @Nullable public Reader getReader(String resourceName) { final InputStream is = klass.getResourceAsStream(resourceName); if (is == null) { diff --git a/dropwizard-views/src/main/java/io/dropwizard/views/View.java b/dropwizard-views/src/main/java/io/dropwizard/views/View.java index 84c032ff72c..3f297e84e67 100644 --- a/dropwizard-views/src/main/java/io/dropwizard/views/View.java +++ b/dropwizard-views/src/main/java/io/dropwizard/views/View.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; +import javax.annotation.Nullable; import java.nio.charset.Charset; import java.util.Optional; @@ -10,6 +11,8 @@ */ public abstract class View { private final String templateName; + + @Nullable private final Charset charset; /** @@ -27,7 +30,7 @@ protected View(String templateName) { * @param templateName the name of the template resource * @param charset the character set for {@code templateName} */ - protected View(String templateName, Charset charset) { + protected View(String templateName, @Nullable Charset charset) { this.templateName = resolveName(templateName); this.charset = charset; } diff --git a/dropwizard-views/src/main/java/io/dropwizard/views/ViewMessageBodyWriter.java b/dropwizard-views/src/main/java/io/dropwizard/views/ViewMessageBodyWriter.java index 8a07b3a7b42..2c587e19693 100755 --- a/dropwizard-views/src/main/java/io/dropwizard/views/ViewMessageBodyWriter.java +++ b/dropwizard-views/src/main/java/io/dropwizard/views/ViewMessageBodyWriter.java @@ -5,6 +5,7 @@ import com.google.common.annotations.VisibleForTesting; import org.glassfish.jersey.message.internal.HeaderValueException; +import javax.annotation.Nullable; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; @@ -23,14 +24,21 @@ import java.util.ServiceLoader; import static com.codahale.metrics.MetricRegistry.name; +import static java.util.Objects.requireNonNull; @Provider -@Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML }) +@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML}) public class ViewMessageBodyWriter implements MessageBodyWriter { @Context + @Nullable private HttpHeaders headers; + @VisibleForTesting + void setHeaders(HttpHeaders headers) { + this.headers = headers; + } + private final Iterable renderers; private final MetricRegistry metricRegistry; @@ -70,7 +78,7 @@ public void writeTo(View t, try { for (ViewRenderer renderer : renderers) { if (renderer.isRenderable(t)) { - renderer.render(t, detectLocale(headers), entityStream); + renderer.render(t, detectLocale(requireNonNull(headers)), entityStream); return; } } diff --git a/dropwizard-views/src/test/java/io/dropwizard/views/ViewBundleTest.java b/dropwizard-views/src/test/java/io/dropwizard/views/ViewBundleTest.java index 2a02ce53125..52e16b115f3 100644 --- a/dropwizard-views/src/test/java/io/dropwizard/views/ViewBundleTest.java +++ b/dropwizard-views/src/test/java/io/dropwizard/views/ViewBundleTest.java @@ -6,12 +6,8 @@ import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.setup.Environment; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import javax.validation.constraints.NotNull; import javax.ws.rs.WebApplicationException; @@ -28,12 +24,8 @@ import static org.mockito.Mockito.when; public class ViewBundleTest { - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private JerseyEnvironment jerseyEnvironment; - - private final Environment environment = mock(Environment.class); + private JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); + private Environment environment = mock(Environment.class); private static class MyConfiguration extends Configuration { @NotNull @@ -61,7 +53,7 @@ public void setUp() throws Exception { @Test public void addsTheViewMessageBodyWriterToTheEnvironment() throws Exception { - new ViewBundle<>().run(null, environment); + new ViewBundle<>().run(new MyConfiguration(), environment); verify(jerseyEnvironment).register(any(ViewMessageBodyWriter.class)); } diff --git a/dropwizard-views/src/test/java/io/dropwizard/views/ViewMessageBodyWriterTest.java b/dropwizard-views/src/test/java/io/dropwizard/views/ViewMessageBodyWriterTest.java index 44956739bbd..802681d15f7 100755 --- a/dropwizard-views/src/test/java/io/dropwizard/views/ViewMessageBodyWriterTest.java +++ b/dropwizard-views/src/test/java/io/dropwizard/views/ViewMessageBodyWriterTest.java @@ -4,16 +4,15 @@ import com.codahale.metrics.Timer; import org.glassfish.jersey.message.internal.HeaderValueException; import org.glassfish.jersey.server.ContainerRequest; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; import java.io.IOException; import java.io.OutputStream; +import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collections; import java.util.Locale; @@ -31,20 +30,13 @@ import static org.mockito.Mockito.when; public class ViewMessageBodyWriterTest { - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - public ContainerRequest headers; - @Mock - public MetricRegistry metricRegistry; - @Mock - public View view; - @Mock - public OutputStream stream; - @Mock - public Timer timer; - @Mock - public Timer.Context timerContext; + + public ContainerRequest headers = mock(ContainerRequest.class); + public MetricRegistry metricRegistry = mock(MetricRegistry.class); + public View view = mock(View.class); + public OutputStream stream = mock(OutputStream.class); + public Timer timer = mock(Timer.class); + public Timer.Context timerContext = mock(Timer.Context.class); @Test public void writeToShouldUseValidRenderer() throws IOException { @@ -60,8 +52,10 @@ public void writeToShouldUseValidRenderer() throws IOException { final ViewMessageBodyWriter writer = spy(new ViewMessageBodyWriter(metricRegistry, Arrays.asList(nonRenderable, renderable))); doReturn(locale).when(writer).detectLocale(any()); + writer.setHeaders(mock(HttpHeaders.class)); - writer.writeTo(view, null, null, null, null, null, stream); + writer.writeTo(view, Class.class, Class.class, new Annotation[]{}, new MediaType(), + new MultivaluedHashMap<>(), stream); verify(nonRenderable).isRenderable(view); verifyNoMoreInteractions(nonRenderable); @@ -78,7 +72,8 @@ public void writeToShouldThrowWhenNoValidRendererFound() { when(timer.time()).thenReturn(timerContext); assertThatExceptionOfType(WebApplicationException.class).isThrownBy(() -> { - writer.writeTo(view, null, null, null, null, null, stream); + writer.writeTo(view, Class.class, Class.class, new Annotation[]{}, new MediaType(), + new MultivaluedHashMap<>(), stream); }).withCauseExactlyInstanceOf(ViewRenderException.class); verify(timerContext).stop(); @@ -98,9 +93,11 @@ public void writeToShouldHandleViewRenderingExceptions() throws IOException { final ViewMessageBodyWriter writer = spy(new ViewMessageBodyWriter(metricRegistry, Collections.singletonList(renderer))); doReturn(locale).when(writer).detectLocale(any()); + writer.setHeaders(mock(HttpHeaders.class)); assertThatExceptionOfType(WebApplicationException.class).isThrownBy(() -> { - writer.writeTo(view, null, null, null, null, null, stream); + writer.writeTo(view, Class.class, Class.class, new Annotation[]{}, new MediaType(), + new MultivaluedHashMap<>(), stream); }).withCause(exception); verify(timerContext).stop(); diff --git a/pom.xml b/pom.xml index c42839bc7dc..f3a05b0ba5d 100644 --- a/pom.xml +++ b/pom.xml @@ -354,7 +354,7 @@ -XepDisableWarningsInGeneratedCode - + -Xep:NullAway:ERROR -XepOpt:NullAway:AnnotatedPackages=io.dropwizard