guidop21
guidop21

Reputation: 197

Spring Boot: Manage Multiple Endpoint with Rest Template?

In my Spring Boot project I have set several endpoints (which refer to some GET or POST REST API) in the application-dev.yml file.

spring:
    username: xxx
    password: acb132
    route:
      source:
        protocol: https://
        ip: 10.xxx.y.zz/
        root: "swdfr/"
        paths: >
            - "ofh/ert/hAFG5"
            - "ofh/ert/ryt54"

I would like to manage these endpoints within a service class with a single method. Currently I have implemented this solution:

//REST CONTROLLER
    @GetMapping("/Multiple_Get")
    public void manageGetEndpointsWithRestTemplate() throws Exception{
    final String methodName = "manageGetEndpointsWithRestTemplate()";
        try {
            service.manageGetEndpointsWithRestTemplate();
        } catch (final Exception e) {
            this.errorLog(methodName, e);
            throw e;
        }   
    }
    
//SERVICE
    @ResponseBody
    public void manageGetEndpointsWithRestTemplate() {
        final String methodName = "manageGetEndpointsWithRestTemplate()";
        try {
            String urlGet1 = protocol + ip + root + paths.get(0);
            String urlGet2 = protocol + ip + root + paths.get(1);

            HttpHeaders headers = new HttpHeaders();
            headers.setBasicAuth(username, password);
            HttpEntity request = new HttpEntity(headers);

            try {
                RestTemplate restTemplate;
                if (urlGet1.startsWith("https") || urlGet2.startsWith("https")) {
                    restTemplate = getRestTemplateForSelfSsl();
                } else {
                    restTemplate = new RestTemplate();
                }

                // GET1
                ResponseEntity<String> response1 = restTemplate.exchange(urlGet1, HttpMethod.GET, request,
                        String.class);
                HttpStatus statusCode1 = response1.getStatusCode();
                logger.info("STATUS GET1: " + statusCode1);
                
                // GET2
                ResponseEntity<String> response2 = restTemplate.exchange(urlGet2, HttpMethod.GET, request,
                        String.class);
                HttpStatus statusCode2 = response2.getStatusCode();
                logger.info("STATUS GET2: " + statusCode2);
                
            } catch (HttpStatusCodeException e) {
                logger.error(e.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

public RestTemplate getRestTemplateForSelfSsl()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] x509Certificates, String s) -> true;
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
            .build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
}

I would like to use a single method making it as generalizable as possible especially if I have to manage a large number of endpoints. Do you have any ideas? Thanks in advance

Upvotes: 0

Views: 1772

Answers (1)

sas
sas

Reputation: 532

You can iterate over all the paths and execute the common code, considering you are doing GET request for all.

@ResponseBody
public void manageGetEndpointsWithRestTemplate() {
    final String methodName = "manageGetEndpointsWithRestTemplate()";
    try {
        paths.forEach(path -> {
            String urlGet = protocol + ip + root + path;
            HttpHeaders headers = new HttpHeaders();
            headers.setBasicAuth(username, password);
            HttpEntity request = new HttpEntity(headers);
            try {
                RestTemplate restTemplate = urlGet.startsWith("https") ? getRestTemplateForSelfSsl() : new RestTemplate();
                ResponseEntity<String> response = restTemplate.exchange(urlGet, HttpMethod.GET, request,
                        String.class);
                HttpStatus statusCode = response.getStatusCode();
                logger.info("STATUS GET - {} : {}", urlGet, statusCode);
            } catch (HttpStatusCodeException e) {
                logger.error(e.getMessage());
            }
        });
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

In case you're gonna use POST or any other HTTP methods, mention in application-dev.yml file along with the paths. Add few extra logic to determine the HTTP.XXX before passing into restTemplate.exchange().

Upvotes: 1

Related Questions