Mohendra Amatya
Mohendra Amatya

Reputation: 441

Creation of a dynamic service in spring boot

I need a way to create a dynamic/generic rest client. My spring boot application need to connect to many third party clients, all of which have different request body, response body, some require special headers, while some require special authorization/authentication (e.g Basic Auth, JWT, HMAC etc).

So far I've managed to come up with the following client

public class GenericRestClient<T, V> {

    private RestTemplate restTemplate = new RestTemplate();

    public V execute(RequestDetails requestDetails, T data, ResponseErrorHandler errorHandler,
            Class<V> genericClass) throws ResourceAccessException, Exception {

        restTemplate.setErrorHandler(errorHandler);
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<T> entity = new HttpEntity<T>(data, headers);
        ResponseEntity<V> response = restTemplate.exchange(requestDetails.getUrl(), requestDetails.getRequestType(),
                entity, genericClass);
        return response.getBody();
    }

}

But my question is. Is there a way now to generate all the necessary headers, authentication and authorization when all of them have different requirements? How can I do that?

Is there a way to store java code like a script (e.g., JTX) in the database and use them, or is there any better way to create my need?

I want it such that even if a new client comes, no further coding needs to be done.

Upvotes: 3

Views: 1777

Answers (1)

Piotr Korlaga
Piotr Korlaga

Reputation: 3468

You can store configuration of every client in database. If you use JPA you will end up with class like that:

@Entity
class RestClientConfiguration{
    private String url;
    private Map<String,String> headers;

    //whatever data you need
}

Then you only need to pass RestClientConfiguration to your GenericRestClient class.

public class GenericRestClient<T, V> {

    public V execute(RequestDetails requestDetails, T data, ResponseErrorHandler errorHandler,
            Class<V> genericClass, RestClientConfiguration clientConfiguration) throws ResourceAccessException, Exception {

        String url = clientConfiguration.getUrl();
        Map<String, String> headerMap = clientConfiguration.getHeaders();

        //here add code which map headerMap which is a Map to HttpHeaders object


        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(errorHandler);
        HttpHeaders headers = new HttpHeaders();


        HttpEntity<T> entity = new HttpEntity<T>(data, headers);
        ResponseEntity<V> response = restTemplate.exchange(requestDetails.getUrl(), requestDetails.getRequestType(),
                entity, genericClass);
        return response.getBody();
    }
}

That's it. Hope I got your needs well. Let me know if something is not clear and we will work it out :)

Upvotes: 1

Related Questions