Examples

Functional style of Soap API call in Java Springboot using Generics and Builder Pattern.

We should be able to call Soap API in the following fashion.

Sample Outcome

return soapBaseClient
            .request(getUserService::getUser)
            .payload(soapClientRequestMapper.toGetUserRequest(userId))
            .then(soapClientResponseMapper::mapToGetUserResponse)
            .fetchResponse();

Java Code

Create a generic RequestMethod.java functional interface which will point the Soap Service method reference or lambda

@FunctionalInterface
public interface RequestMethod<P, R> {
    R execute(P payload);
}

Create a generic Request.java class with payload and then methods.

import java.util.function.Function;

public class Request<RequestPayloadType, ResponsePayloadType> {

    private final RequestMethod<RequestPayloadType, ResponsePayloadType> requestMethod;

    private RequestPayloadType payload;

    public Request(RequestMethod<RequestPayloadType, ResponsePayloadType> requestMethod) {
        this.requestMethod = requestMethod;
    }

    public Request<RequestPayloadType, ResponsePayloadType> payload(RequestPayloadType payload) {
        this.payload = payload;
        return this;
    }

    public <ProcessedResponseType> RequestCallback<ResponsePayloadType, ProcessedResponseType> then(
        Function<ResponsePayloadType, ProcessedResponseType> handler) {
        return new RequestCallback<>(
            () -> requestMethod.execute(payload),
            handler
        );
    }
}

Create a generic RequestCallback.java class with fetchResponse and several other methods to handle success or error scenario.

Create a SoapBaseClient.java class with generic request method.

Now, we can call Soap service like below.

Request mapper class.

Response mapper class.

Last updated