Skip to content

Commit

Permalink
Opinionated code cleanup: use Objects#nonNull (#116)
Browse files Browse the repository at this point in the history
* Change code using "!= null" to use Objects#nonNull instead
* In BasicAuthenticationInterceptor, add static import for
Collections#singletonList
  • Loading branch information
sleberknight authored Jul 5, 2024
1 parent f132225 commit 3020102
Show file tree
Hide file tree
Showing 9 changed files with 51 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static java.util.Collections.singletonList;
import static java.util.Objects.nonNull;

import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.basic.BasicCredentials;
import org.apache.cxf.common.security.SecurityToken;
Expand All @@ -18,7 +21,6 @@
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -57,12 +59,12 @@ public void handleMessage(final Message message) throws Fault {

try {
var policy = message.get(AuthorizationPolicy.class);
if (policy != null && policy.getUserName() != null && policy.getPassword() != null) {
if (nonNull(policy) && nonNull(policy.getUserName()) && nonNull(policy.getPassword())) {
credentials = new BasicCredentials(policy.getUserName(), policy.getPassword());
} else {
// try the WS-Security UsernameToken
var token = message.get(SecurityToken.class);
if (token != null && token.getTokenType() == TokenType.UsernameToken) {
if (nonNull(token) && token.getTokenType() == TokenType.UsernameToken) {
var usernameToken = (UsernameToken) token;
credentials = new BasicCredentials(usernameToken.getName(), usernameToken.getPassword());
}
Expand Down Expand Up @@ -94,9 +96,9 @@ private void sendErrorResponse(Message message, int responseCode) {
// Set the response headers
@SuppressWarnings("unchecked")
var responseHeaders = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
if (responseHeaders != null) {
responseHeaders.put("WWW-Authenticate", Collections.singletonList("Basic realm=" + authentication.getRealm()));
responseHeaders.put("Content-length", Collections.singletonList("0"));
if (nonNull(responseHeaders)) {
responseHeaders.put("WWW-Authenticate", singletonList("Basic realm=" + authentication.getRealm()));
responseHeaders.put("Content-length", singletonList("0"));
}
message.getInterceptorChain().abort();
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.nonNull;

import com.google.common.collect.ImmutableList;
import jakarta.xml.ws.handler.Handler;
Expand Down Expand Up @@ -50,8 +51,8 @@ public String getBindingId() {
* @param address Endpoint URL address..
*/
public ClientBuilder(Class<T> serviceClass, String address) {
checkArgument(serviceClass != null, "ServiceClass is null");
checkArgument(address != null, "Address is null");
checkArgument(nonNull(serviceClass), "ServiceClass is null");
checkArgument(nonNull(address), "Address is null");
checkArgument(!address.isBlank(), "Address is empty");
this.serviceClass = serviceClass;
this.address = address;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.nonNull;

import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.message.Message;
Expand Down Expand Up @@ -51,8 +52,8 @@ public Map<String, Object> getProperties() {
* @param service Service implementation.
*/
public EndpointBuilder(String path, Object service) {
checkArgument(service != null, "Service is null");
checkArgument(path != null, "Path is null");
checkArgument(nonNull(service), "Service is null");
checkArgument(nonNull(path), "Path is null");
checkArgument(!path.isBlank(), "Path is empty");
if (!path.startsWith("local:")) { // local transport is used in tests
path = (path.startsWith("/")) ? path : "/" + path;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static java.util.Objects.nonNull;

import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
Expand Down Expand Up @@ -87,7 +89,7 @@ private Invoker exceptionMetered(Invoker invoker, List<Method> meteredMethods) {
* @see com.codahale.metrics.jersey3.InstrumentedResourceMethodApplicationListener
*/
private String chooseName(String explicitName, boolean absolute, Method method, String... suffixes) {
if (explicitName != null && !explicitName.isEmpty()) {
if (nonNull(explicitName) && !explicitName.isEmpty()) {
if (absolute) {
return explicitName;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;

import com.codahale.metrics.Meter;
Expand Down Expand Up @@ -123,7 +124,7 @@ public Object invoke(Exchange exchange, Object o) {
var exceptionMeter = requireNonNull(meters.get(methodName));
var exceptionClass = exceptionMeter.getExceptionClass();
if (exceptionClass.isAssignableFrom(e.getClass()) ||
(e.getCause() != null &&
(nonNull(e.getCause()) &&
exceptionClass.isAssignableFrom(e.getCause().getClass()))) {
exceptionMeter.getMeter().mark();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.nonNull;

import io.dropwizard.core.ConfiguredBundle;
import io.dropwizard.core.setup.Bootstrap;
Expand Down Expand Up @@ -42,9 +43,9 @@ public JakartaXmlWsBundle(String servletPath) {
* @param jwsEnvironment Valid JakartaXmlWsEnvironment.
*/
public JakartaXmlWsBundle(String servletPath, JakartaXmlWsEnvironment jwsEnvironment) {
checkArgument(servletPath != null, "Servlet path is null");
checkArgument(nonNull(servletPath), "Servlet path is null");
checkArgument(servletPath.startsWith("/"), "%s is not an absolute path", servletPath);
checkArgument(jwsEnvironment != null, "jwsEnvironment is null");
checkArgument(nonNull(jwsEnvironment), "jwsEnvironment is null");
this.servletPath = servletPath.endsWith("/") ? servletPath + "*" : servletPath + "/*";
this.jwsEnvironment = jwsEnvironment;
}
Expand All @@ -57,15 +58,15 @@ public void initialize(Bootstrap<?> bootstrap) {

@Override
public void run(C configuration, Environment environment) {
checkArgument(environment != null, "Environment is null");
checkArgument(nonNull(environment), "Environment is null");
environment.servlets().addServlet("CXF Servlet " + jwsEnvironment.getDefaultPath(),
jwsEnvironment.buildServlet()).addMapping(servletPath);

environment.lifecycle().addServerLifecycleListener(
server -> jwsEnvironment.logEndpoints());

var publishedEndpointUrlPrefix = getPublishedEndpointUrlPrefix(configuration);
if (publishedEndpointUrlPrefix != null) {
if (nonNull(publishedEndpointUrlPrefix)) {
jwsEnvironment.setPublishedEndpointUrlPrefix(publishedEndpointUrlPrefix);
}
}
Expand All @@ -77,7 +78,7 @@ public void run(C configuration, Environment environment) {
* @return javax.xml.ws.Endpoint
*/
public EndpointImpl publishEndpoint(EndpointBuilder endpointBuilder) {
checkArgument(endpointBuilder != null, "EndpointBuilder is null");
checkArgument(nonNull(endpointBuilder), "EndpointBuilder is null");
return this.jwsEnvironment.publishEndpoint(endpointBuilder);
}

Expand All @@ -89,7 +90,7 @@ public EndpointImpl publishEndpoint(EndpointBuilder endpointBuilder) {
* @return Jakarta XML Web Services client proxy.
*/
public <T> T getClient(ClientBuilder<T> clientBuilder) {
checkArgument(clientBuilder != null, "ClientBuilder is null");
checkArgument(nonNull(clientBuilder), "ClientBuilder is null");
return jwsEnvironment.getClient(clientBuilder);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.nonNull;

import jakarta.servlet.http.HttpServlet;
import jakarta.validation.Validation;
Expand Down Expand Up @@ -99,12 +100,12 @@ public void logEndpoints() {
* to allow further customization.
*/
public EndpointImpl publishEndpoint(EndpointBuilder endpointBuilder) {
checkArgument(endpointBuilder != null, "EndpointBuilder is null");
checkArgument(nonNull(endpointBuilder), "EndpointBuilder is null");

var cxfEndpoint = new EndpointImpl(bus, endpointBuilder.getService());
if (endpointBuilder.publishedEndpointUrl() != null) {
if (nonNull(endpointBuilder.publishedEndpointUrl())) {
cxfEndpoint.setPublishedEndpointUrl(endpointBuilder.publishedEndpointUrl());
} else if (publishedEndpointUrlPrefix != null) {
} else if (nonNull(publishedEndpointUrlPrefix)) {
cxfEndpoint.setPublishedEndpointUrl(publishedEndpointUrlPrefix + endpointBuilder.getPath());
}
cxfEndpoint.publish(endpointBuilder.getPath());
Expand All @@ -120,7 +121,7 @@ public EndpointImpl publishEndpoint(EndpointBuilder endpointBuilder) {
var validatorFactory = Validation.buildDefaultValidatorFactory();
invoker = this.createValidatingInvoker(invoker, validatorFactory.getValidator());

if (endpointBuilder.getSessionFactory() != null) {
if (nonNull(endpointBuilder.getSessionFactory())) {
// Add invoker to handle UnitOfWork annotations. Note that this invoker is set up before
// instrumented invoker(s) in order for instrumented invoker(s) to wrap "unit of work" invoker.
invoker = unitOfWorkInvokerBuilder.create(
Expand All @@ -132,7 +133,7 @@ public EndpointImpl publishEndpoint(EndpointBuilder endpointBuilder) {
invoker = instrumentedInvokerBuilder.create(endpointBuilder.getService(), invoker);
cxfEndpoint.getService().setInvoker(invoker);

if (endpointBuilder.getAuthentication() != null) {
if (nonNull(endpointBuilder.getAuthentication())) {
// Configure CXF in interceptor to handle basic authentication
var basicAuthInterceptor = this.createBasicAuthenticationInterceptor();
basicAuthInterceptor.setAuthenticator(endpointBuilder.getAuthentication());
Expand All @@ -141,23 +142,23 @@ public EndpointImpl publishEndpoint(EndpointBuilder endpointBuilder) {

// CXF interceptors

if (endpointBuilder.getCxfInInterceptors() != null) {
if (nonNull(endpointBuilder.getCxfInInterceptors())) {
cxfEndpoint.getInInterceptors().addAll(endpointBuilder.getCxfInInterceptors());
}

if (endpointBuilder.getCxfInFaultInterceptors() != null) {
if (nonNull(endpointBuilder.getCxfInFaultInterceptors())) {
cxfEndpoint.getInFaultInterceptors().addAll(endpointBuilder.getCxfInFaultInterceptors());
}

if (endpointBuilder.getCxfOutInterceptors() != null) {
if (nonNull(endpointBuilder.getCxfOutInterceptors())) {
cxfEndpoint.getOutInterceptors().addAll(endpointBuilder.getCxfOutInterceptors());
}

if (endpointBuilder.getCxfOutFaultInterceptors() != null) {
if (nonNull(endpointBuilder.getCxfOutFaultInterceptors())) {
cxfEndpoint.getOutFaultInterceptors().addAll(endpointBuilder.getCxfOutFaultInterceptors());
}

if (endpointBuilder.getProperties() != null) {
if (nonNull(endpointBuilder.getProperties())) {
cxfEndpoint.getProperties().putAll(
endpointBuilder.getProperties());
}
Expand All @@ -179,28 +180,28 @@ public <T> T getClient(ClientBuilder<T> clientBuilder) {
proxyFactory.setAddress(clientBuilder.getAddress());

// Jakarta XML Web Services handlers
if (clientBuilder.getHandlers() != null) {
if (nonNull(clientBuilder.getHandlers())) {
for (var h : clientBuilder.getHandlers()) {
proxyFactory.getHandlers().add(h);
}
}

// ClientProxyFactoryBean bindingId
if (clientBuilder.getBindingId() != null) {
if (nonNull(clientBuilder.getBindingId())) {
proxyFactory.setBindingId(clientBuilder.getBindingId());
}

// CXF interceptors
if (clientBuilder.getCxfInInterceptors() != null) {
if (nonNull(clientBuilder.getCxfInInterceptors())) {
proxyFactory.getInInterceptors().addAll(clientBuilder.getCxfInInterceptors());
}
if (clientBuilder.getCxfInFaultInterceptors() != null) {
if (nonNull(clientBuilder.getCxfInFaultInterceptors())) {
proxyFactory.getInFaultInterceptors().addAll(clientBuilder.getCxfInFaultInterceptors());
}
if (clientBuilder.getCxfOutInterceptors() != null) {
if (nonNull(clientBuilder.getCxfOutInterceptors())) {
proxyFactory.getOutInterceptors().addAll(clientBuilder.getCxfOutInterceptors());
}
if (clientBuilder.getCxfOutFaultInterceptors() != null) {
if (nonNull(clientBuilder.getCxfOutFaultInterceptors())) {
proxyFactory.getOutFaultInterceptors().addAll(clientBuilder.getCxfOutFaultInterceptors());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;

import com.google.common.collect.ImmutableMap;
Expand Down Expand Up @@ -96,7 +97,7 @@ private void configureSession(Session session, UnitOfWork unitOfWork) {
private void rollbackTransaction(Session session, UnitOfWork unitOfWork) {
if (unitOfWork.transactional()) {
var txn = session.getTransaction();
if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
if (nonNull(txn) && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
txn.rollback();
}
}
Expand All @@ -109,7 +110,7 @@ private void rollbackTransaction(Session session, UnitOfWork unitOfWork) {
private void commitTransaction(Session session, UnitOfWork unitOfWork) {
if (unitOfWork.transactional()) {
var txn = session.getTransaction();
if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
if (nonNull(txn) && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
txn.commit();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws;

import static java.util.Objects.nonNull;

import io.dropwizard.validation.ConstraintViolations;
import io.dropwizard.validation.Validated;
import jakarta.validation.Valid;
Expand Down Expand Up @@ -43,13 +45,13 @@ public Object invoke(Exchange exchange, Object o) {
List<Object> params = null;
if (o instanceof List) {
params = CastUtils.cast((List<?>) o);
} else if (o != null) {
} else if (nonNull(o)) {
params = new MessageContentsList(o);
}
/* Get actual parameter list end */

// validate each parameter in the list
if (params != null) {
if (nonNull(params)) {
var i = 0;
try {
for (var parameter : params) {
Expand Down Expand Up @@ -79,7 +81,7 @@ public Object invoke(Exchange exchange, Object o) {
private Object validate(Annotation[] annotations, Object value) {
var classes = findValidationGroups(annotations);

if (classes != null && classes.length > 0) {
if (nonNull(classes) && classes.length > 0) {
var errors = ConstraintViolations.format(validator.validate(value, classes));
if (errors.isEmpty()) {
return value;
Expand Down

0 comments on commit 3020102

Please sign in to comment.