Skip to content

Commit

Permalink
Add @Nullable annotations or initialize not-null fields
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
arteam committed Nov 13, 2017
1 parent 3841415 commit 207c3cb
Show file tree
Hide file tree
Showing 184 changed files with 1,050 additions and 548 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -30,8 +31,10 @@
*/
public class AuthDynamicFeature implements DynamicFeature {

@Nullable
private final ContainerRequestFilter authFilter;

@Nullable
private final Class<? extends ContainerRequestFilter> authFilterClass;

public AuthDynamicFeature(ContainerRequestFilter authFilter) {
Expand Down
14 changes: 8 additions & 6 deletions dropwizard-auth/src/main/java/io/dropwizard/auth/AuthFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -18,11 +19,11 @@ public abstract class AuthFilter<C, P extends Principal> implements ContainerReq

protected final Logger logger = LoggerFactory.getLogger(getClass());

protected String prefix;
protected String realm;
protected Authenticator<C, P> authenticator;
protected Authorizer<P> authorizer;
protected UnauthorizedHandler unauthorizedHandler;
protected String prefix = "Basic";
protected String realm = "realm";
protected Authenticator<C, P> authenticator = credentials -> Optional.empty();
protected Authorizer<P> authorizer = new PermitAllAuthorizer<>();
protected UnauthorizedHandler unauthorizedHandler = new DefaultUnauthorizedHandler();

/**
* Abstract builder for auth filters.
Expand All @@ -34,6 +35,7 @@ public abstract static class AuthFilterBuilder<C, P extends Principal, T extends

private String realm = "realm";
private String prefix = "Basic";
@Nullable
private Authenticator<C, P> authenticator;
private Authorizer<P> authorizer = new PermitAllAuthorizer<>();
private UnauthorizedHandler unauthorizedHandler = new DefaultUnauthorizedHandler();
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -63,14 +64,15 @@ public class DropwizardApacheConnector implements Connector {
/**
* Default HttpUriRequestConfig
*/
@Nullable
private final RequestConfig defaultRequestConfig;

/**
* Should a chunked encoding be used in POST requests
*/
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;
Expand Down Expand Up @@ -172,6 +174,7 @@ private Optional<RequestConfig> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
Expand All @@ -36,6 +41,7 @@ public SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationExc
chooseHostnameVerifier());
}

@Nullable
private String[] getSupportedCiphers() {
final List<String> supportedCiphers = configuration.getSupportedCiphers();
if (supportedCiphers == null) {
Expand All @@ -44,6 +50,7 @@ private String[] getSupportedCiphers() {
return supportedCiphers.toArray(new String[supportedCiphers.size()]);
}

@Nullable
private String[] getSupportedProtocols() {
final List<String> supportedProtocols = configuration.getSupportedProtocols();
if (supportedProtocols == null) {
Expand Down Expand Up @@ -74,6 +81,7 @@ private SSLContext buildSslContext() throws SSLInitializationException {
return sslContext;
}

@Nullable
private PrivateKeyStrategy choosePrivateKeyStrategy() {
PrivateKeyStrategy privateKeyStrategy = null;
if (configuration.getCertAlias() != null) {
Expand All @@ -89,17 +97,18 @@ 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());
}
}

private void loadTrustMaterial(SSLContextBuilder sslContextBuilder) throws Exception {
KeyStore trustStore = null;
if (configuration.getTrustStorePath() != null) {
trustStore = loadKeyStore(configuration.getTrustStoreType(), configuration.getTrustStorePath(),
configuration.getTrustStorePassword());
requireNonNull(configuration.getTrustStorePassword()));
}
TrustStrategy trustStrategy = null;
if (configuration.isTrustSelfSignedCertificates()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<ConnectionSocketFactory> 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<? extends Header> defaultHeaders;

@Nullable
private HttpProcessor httpProcessor;

@Nullable
private ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy;

public HttpClientBuilder(MetricRegistry metricRegistry) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ public void setUserAgent(Optional<String> userAgent) {
}

@JsonProperty("proxy")
@Nullable
public ProxyConfiguration getProxyConfiguration() {
return proxyConfiguration;
}
Expand All @@ -183,6 +184,7 @@ public void setValidateAfterInactivityPeriod(Duration validateAfterInactivityPer
}

@JsonProperty("tls")
@Nullable
public TlsConfiguration getTlsConfiguration() {
return tlsConfiguration;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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())
Expand All @@ -361,7 +370,7 @@ public Client build(String name) {
}

if (objectMapper == null) {
objectMapper = environment.getObjectMapper();
objectMapper = requireNonNull(environment).getObjectMapper();
}

if (environment != null) {
Expand Down

0 comments on commit 207c3cb

Please sign in to comment.