Skip to content

Commit

Permalink
Opinionated code cleanup: use LVTI
Browse files Browse the repository at this point in the history
* Change explicit type declarations to use 'var'
* Rename local vars from short names like 'm' and 'sr' to
  more descriptive ones like 'method' and 'serverRegistry'

And no, I don't care if you ever read this and prefer code
like Foo foo = new Foo(),
  • Loading branch information
sleberknight committed Jul 5, 2024
1 parent b24c43c commit a205a1c
Show file tree
Hide file tree
Showing 26 changed files with 296 additions and 336 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import io.dropwizard.hibernate.HibernateBundle;
import org.apache.cxf.ext.logging.LoggingInInterceptor;
import org.apache.cxf.ext.logging.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import org.kiwiproject.dropwizard.jakarta.xml.ws.BasicAuthentication;
import org.kiwiproject.dropwizard.jakarta.xml.ws.ClientBuilder;
import org.kiwiproject.dropwizard.jakarta.xml.ws.EndpointBuilder;
Expand Down Expand Up @@ -63,45 +62,45 @@ public void run(JakartaXmlWsExampleConfiguration configuration, Environment envi

// Hello world service
@SuppressWarnings("unused")
EndpointImpl e = jwsBundle.publishEndpoint(
var endpoint = jwsBundle.publishEndpoint(
new EndpointBuilder("/simple", new SimpleService()));

// publishEndpoint returns javax.xml.ws.Endpoint to enable further customization.
// e.getProperties().put(...);

// Publish Hello world service again using different JakartaXmlWsBundle instance
e = anotherJwsBundle.publishEndpoint(
endpoint = anotherJwsBundle.publishEndpoint(
new EndpointBuilder("/simple", new SimpleService()));

// Java first service protected with basic authentication
e = jwsBundle.publishEndpoint(
endpoint = jwsBundle.publishEndpoint(
new EndpointBuilder("/javafirst", new JavaFirstServiceImpl())
.authentication(new BasicAuthentication(new BasicAuthenticator(), "TOP_SECRET")));

// WSDL first service using server side Jakarta XML Web Services handler and CXF logging interceptors.
// The server handler is defined in the wsdlfirstservice-handlerchain.xml file, via the
// HandlerChain annotation on WsdlFirstServiceImpl
e = jwsBundle.publishEndpoint(
endpoint = jwsBundle.publishEndpoint(
new EndpointBuilder("/wsdlfirst", new WsdlFirstServiceImpl())
.cxfInInterceptors(new LoggingInInterceptor())
.cxfOutInterceptors(new LoggingOutInterceptor()));

// Service using Hibernate
PersonDAO personDAO = new PersonDAO(hibernate.getSessionFactory());
e = jwsBundle.publishEndpoint(
var personDAO = new PersonDAO(hibernate.getSessionFactory());
endpoint = jwsBundle.publishEndpoint(
new EndpointBuilder("/hibernate",
new HibernateExampleService(personDAO))
.sessionFactory(hibernate.getSessionFactory()));

// Publish the same service again using different JakartaXmlWsBundle instance
e = anotherJwsBundle.publishEndpoint(
endpoint = anotherJwsBundle.publishEndpoint(
new EndpointBuilder("/hibernate",
new HibernateExampleService(personDAO))
.sessionFactory(hibernate.getSessionFactory()));

// WSDL first service using MTOM. Invoking enableMTOM on EndpointBuilder is not necessary
// if you use @MTOM Jakarta XML Web Services annotation on your service implementation class.
e = jwsBundle.publishEndpoint(
endpoint = jwsBundle.publishEndpoint(
new EndpointBuilder("/mtom", new MtomServiceImpl())
.enableMtom()
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.kiwiproject.dropwizard.jakarta.xml.ws.example.db;

import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.kiwiproject.dropwizard.jakarta.xml.ws.example.core.Person;
Expand All @@ -19,15 +18,15 @@ public PersonDAO(SessionFactory sessionFactory) {

// set up embedded database

Session sess = sessionFactory.openSession();
var session = sessionFactory.openSession();
try {
sess.beginTransaction();
sess.createNativeQuery("create table people(id bigint primary key auto_increment not null, " +
session.beginTransaction();
session.createNativeQuery("create table people(id bigint primary key auto_increment not null, " +
"fullname varchar(256) not null, jobtitle varchar(256) not null);", Void.class).executeUpdate();
sess.createNativeQuery("create sequence hibernate_sequence", Void.class).executeUpdate();
session.createNativeQuery("create sequence hibernate_sequence", Void.class).executeUpdate();
} finally {
sess.getTransaction().commit();
sess.close();
session.getTransaction().commit();
session.close();
}
}

Expand All @@ -41,7 +40,7 @@ public Person create(Person person) {

public List<Person> findAll() {
@SuppressWarnings("unchecked")
Query<Person> query =
var query =
(Query<Person>) namedQuery("org.kiwiproject.dropwizard.jakarta.xml.ws.example.core.Person.findAll");
return list(query);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.apache.cxf.helpers.IOUtils;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.mtomservice.Hello;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.mtomservice.HelloResponse;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.mtomservice.MtomService;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.mtomservice.ObjectFactory;

Expand All @@ -31,16 +29,16 @@ public AccessMtomServiceResource(MtomService mtomServiceClient) {
@Timed
public String getFoo() {

ObjectFactory of = new ObjectFactory();
Hello h = of.createHello();
h.setTitle("Hello");
h.setBinary(new DataHandler(new ByteArrayDataSource("test".getBytes(), "text/plain")));
var objectFactory = new ObjectFactory();
var hello = objectFactory.createHello();
hello.setTitle("Hello");
hello.setBinary(new DataHandler(new ByteArrayDataSource("test".getBytes(), "text/plain")));

HelloResponse hr = mtomServiceClient.hello(h);
var helloResponse = mtomServiceClient.hello(hello);

try {
return "Hello response: " + hr.getTitle() + ", " +
IOUtils.readStringFromStream(hr.getBinary().getInputStream()) +
return "Hello response: " + helloResponse.getTitle() + ", " +
IOUtils.readStringFromStream(helloResponse.getBinary().getInputStream()) +
" at " + LocalDateTime.now();
} catch (IOException e) {
throw new UncheckedIOException(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ public AccessProtectedServiceResource(JavaFirstService javaFirstService) {
@GET
public String getEcho() {
try {

BindingProvider bp = (BindingProvider) javaFirstService;
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "johndoe");
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "secret");
var bindingProvider = (BindingProvider) javaFirstService;
bindingProvider.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "johndoe");
bindingProvider.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "secret");

return this.javaFirstService.echo("Hello from the protected service!");
} catch (JavaFirstService.JavaFirstServiceException jfse) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.wsdlfirstservice.Echo;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.wsdlfirstservice.EchoResponse;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.wsdlfirstservice.ObjectFactory;
import ws.example.ws.xml.jakarta.dropwizard.kiwiproject.org.wsdlfirstservice.WsdlFirstService;

Expand All @@ -30,13 +28,12 @@ public AccessWsdlFirstServiceResource(WsdlFirstService wsdlFirstServiceClient) {
@GET
@Timed
public String getFoo() {
var objectFactory = new ObjectFactory();
var echo = objectFactory.createEcho();
echo.setValue("echo value");

ObjectFactory of = new ObjectFactory();
Echo e = of.createEcho();
e.setValue("echo value");
var echoResponse = wsdlFirstServiceClient.echo(echo);

EchoResponse er = wsdlFirstServiceClient.echo(e);

return "Echo response: " + er.getValue() + " at " + LocalDateTime.now();
return "Echo response: " + echoResponse.getValue() + " at " + LocalDateTime.now();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import org.kiwiproject.dropwizard.jakarta.xml.ws.example.db.PersonDAO;

import java.util.List;
import java.util.Optional;

@WebService
public class HibernateExampleService {
Expand All @@ -31,9 +30,9 @@ public List<Person> getPersons() {
@WebMethod
@UnitOfWork
public Person getPerson(long id) throws Exception {
Optional<Person> result = this.personDAO.findById(id);
if (result.isPresent()) {
return result.get();
var personOptional = this.personDAO.findById(id);
if (personOptional.isPresent()) {
return personOptional.get();
}

throw new Exception("Person with id " + id + " not found");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public String echo(String in) throws JavaFirstServiceException {
throw new JavaFirstServiceException("Invalid parameter");
}

Principal user = (Principal) wsContext.getMessageContext().get("dropwizard.jakarta.xml.ws.principal");
return in + "; principal: " + user.getName() + " at " + LocalDateTime.now();
var userPrincipal = (Principal) wsContext.getMessageContext().get("dropwizard.jakarta.xml.ws.principal");
return in + "; principal: " + userPrincipal.getName() + " at " + LocalDateTime.now();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ public class MtomServiceImpl implements MtomService {
@Override
public HelloResponse hello(Hello parameters) {
try {
byte[] bin = IOUtils.readBytesFromStream(parameters.getBinary().getInputStream());
HelloResponse response = new HelloResponse();
var bytes = IOUtils.readBytesFromStream(parameters.getBinary().getInputStream());
var response = new HelloResponse();
response.setTitle(parameters.getTitle());
response.setBinary(new DataHandler(new ByteArrayDataSource(bin,
response.setBinary(new DataHandler(new ByteArrayDataSource(bytes,
parameters.getBinary().getContentType())));
return response;
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class WsdlFirstServiceImpl implements WsdlFirstService {
@Override
@Metered
public EchoResponse echo(Echo parameters) {
EchoResponse response = new EchoResponse();
var response = new EchoResponse();
response.setValue(parameters.getValue());
return response;
}
Expand All @@ -31,7 +31,7 @@ public EchoResponse echo(Echo parameters) {
@UseAsyncMethod
@Metered
public EchoResponse nonBlockingEcho(NonBlockingEcho parameters) {
EchoResponse response = new EchoResponse();
var response = new EchoResponse();
response.setValue("Blocking: " + parameters.getValue());
return response;
}
Expand All @@ -40,21 +40,21 @@ public Future<EchoResponse> nonBlockingEchoAsync(
final NonBlockingEcho parameters,
final AsyncHandler<EchoResponse> asyncHandler) {

final ServerAsyncResponse<EchoResponse> sar = new ServerAsyncResponse<>();
final var asyncResponse = new ServerAsyncResponse<EchoResponse>();

new Thread(() -> {
try {
Thread.sleep(1000);
EchoResponse response = new EchoResponse();
var response = new EchoResponse();
response.setValue("Non-blocking: " + parameters.getValue());
sar.set(response);
asyncResponse.set(response);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
sar.exception(e);
asyncResponse.exception(e);
}
asyncHandler.handleResponse(sar);
asyncHandler.handleResponse(asyncResponse);
}).start();

return sar;
return asyncResponse;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ protected AbstractInvoker(Invoker underlying) {
*/
public Method getTargetMethod(Exchange exchange) {

Object o = exchange.getBindingOperationInfo().getOperationInfo().getProperty(Method.class.getName());
var object = exchange.getBindingOperationInfo().getOperationInfo().getProperty(Method.class.getName());

if (o instanceof Method method) {
if (object instanceof Method method) {
return method;
} else {
throw new IllegalStateException("Target method not found on OperationInfo");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
Expand Down Expand Up @@ -52,20 +51,20 @@ public void setAuthenticator(BasicAuthentication authentication) {
@Override
public void handleMessage(final Message message) throws Fault {

final Exchange exchange = message.getExchange();
final var exchange = message.getExchange();

BasicCredentials credentials = null;

try {
AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
var policy = message.get(AuthorizationPolicy.class);
if (policy != null && policy.getUserName() != null && policy.getPassword() != null) {
credentials = new BasicCredentials(policy.getUserName(), policy.getPassword());
} else {
// try the WS-Security UsernameToken
SecurityToken token = message.get(SecurityToken.class);
var token = message.get(SecurityToken.class);
if (token != null && token.getTokenType() == TokenType.UsernameToken) {
UsernameToken ut = (UsernameToken) token;
credentials = new BasicCredentials(ut.getName(), ut.getPassword());
var usernameToken = (UsernameToken) token;
credentials = new BasicCredentials(usernameToken.getName(), usernameToken.getPassword());
}
}

Expand All @@ -90,7 +89,7 @@ public void handleMessage(final Message message) throws Fault {
}

private void sendErrorResponse(Message message, int responseCode) {
Message outMessage = getOutMessage(message);
var outMessage = getOutMessage(message);
outMessage.put(Message.RESPONSE_CODE, responseCode);
// Set the response headers
@SuppressWarnings("unchecked")
Expand All @@ -109,10 +108,10 @@ private void sendErrorResponse(Message message, int responseCode) {
}

private Message getOutMessage(Message inMessage) {
Exchange exchange = inMessage.getExchange();
Message outMessage = exchange.getOutMessage();
var exchange = inMessage.getExchange();
var outMessage = exchange.getOutMessage();
if (outMessage == null) {
Endpoint endpoint = exchange.get(Endpoint.class);
var endpoint = exchange.get(Endpoint.class);
outMessage = endpoint.getBinding().createMessage();
exchange.setOutMessage(outMessage);
}
Expand All @@ -121,15 +120,15 @@ private Message getOutMessage(Message inMessage) {
}

private Conduit getConduit(Message inMessage) throws IOException {
Exchange exchange = inMessage.getExchange();
Conduit conduit = exchange.getDestination().getBackChannel(inMessage);
var exchange = inMessage.getExchange();
var conduit = exchange.getDestination().getBackChannel(inMessage);
exchange.setConduit(conduit);
return conduit;
}

private void close(Message outMessage) throws IOException {
OutputStream os = outMessage.getContent(OutputStream.class);
os.flush();
os.close();
var outputStream = outMessage.getContent(OutputStream.class);
outputStream.flush();
outputStream.close();
}
}
Loading

0 comments on commit a205a1c

Please sign in to comment.