b82d73bbbf5ed19d77c4656f59dd9527e0fe7957
[so.git] / common / src / main / java / org / onap / so / rest / service / HttpRestServiceProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.rest.service;
22
23 import com.google.common.base.Optional;
24 import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
25 import org.onap.so.configuration.rest.HttpHeadersProvider;
26 import org.onap.so.rest.exceptions.HttpResouceNotFoundException;
27 import org.onap.so.rest.exceptions.InvalidRestRequestException;
28 import org.onap.so.rest.exceptions.RestProcessingException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.http.HttpEntity;
32 import org.springframework.http.HttpHeaders;
33 import org.springframework.http.HttpMethod;
34 import org.springframework.http.HttpStatus;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.web.client.HttpStatusCodeException;
37 import org.springframework.web.client.RestClientException;
38 import org.springframework.web.client.RestTemplate;
39
40 /**
41  * A Service to perform HTTP requests
42  *
43  * @author waqas.ikram@est.tech
44  */
45 public class HttpRestServiceProviderImpl implements HttpRestServiceProvider {
46
47     private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestServiceProviderImpl.class);
48     private final RestTemplate restTemplate;
49     private final HttpHeadersProvider httpHeadersProvider;
50
51     public HttpRestServiceProviderImpl(final RestTemplate restTemplate) {
52         this.restTemplate = restTemplate;
53         this.httpHeadersProvider = new BasicHttpHeadersProvider();
54     }
55
56     public HttpRestServiceProviderImpl(final RestTemplate restTemplate, final HttpHeadersProvider httpHeadersProvider) {
57         this.restTemplate = restTemplate;
58         this.httpHeadersProvider = httpHeadersProvider;
59     }
60
61     @Override
62     public <T> Optional<T> get(final String url, final Class<T> clazz) {
63         final ResponseEntity<T> response = getHttpResponse(url, clazz);
64         return createOptional(response, url, HttpMethod.GET);
65     }
66
67
68     @Override
69     public <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz) {
70         final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders());
71         return invokeHttpRequest(request, HttpMethod.GET, url, clazz);
72     }
73
74     @Override
75     public <T> Optional<T> post(final Object object, final String url, final Class<T> clazz) {
76         final ResponseEntity<T> response = postHttpRequest(object, url, clazz);
77         return createOptional(response, url, HttpMethod.POST);
78     }
79
80     @Override
81     public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz) {
82         final HttpEntity<?> request = new HttpEntity<>(object, getHttpHeaders());
83         return invokeHttpRequest(request, HttpMethod.POST, url, clazz);
84     }
85
86     @Override
87     public <T> Optional<T> put(final Object object, final String url, final Class<T> clazz) {
88         final ResponseEntity<T> response = putHttpRequest(object, url, clazz);
89         return createOptional(response, url, HttpMethod.PUT);
90     }
91
92     @Override
93     public <T> ResponseEntity<T> putHttpRequest(final Object object, final String url, final Class<T> clazz) {
94         final HttpEntity<?> request = new HttpEntity<>(object, getHttpHeaders());
95         return invokeHttpRequest(request, HttpMethod.PUT, url, clazz);
96     }
97
98     private <T> Optional<T> createOptional(final ResponseEntity<T> response, final String url,
99             final HttpMethod httpMethod) {
100         if (!response.getStatusCode().equals(HttpStatus.OK) && !response.getStatusCode().equals(HttpStatus.CREATED)) {
101             final String message = "Unable to invoke HTTP " + httpMethod + " using URL: " + url + ", Response Code: "
102                     + response.getStatusCode();
103             LOGGER.error(message);
104             return Optional.absent();
105         }
106
107         if (response.hasBody()) {
108             return Optional.of(response.getBody());
109         }
110
111         return Optional.absent();
112     }
113
114     private <T> ResponseEntity<T> invokeHttpRequest(final HttpEntity<?> request, final HttpMethod httpMethod,
115             final String url, final Class<T> clazz) {
116         LOGGER.trace("Will invoke HTTP {} using URL: {}", httpMethod, url);
117         try {
118             return restTemplate.exchange(url, httpMethod, request, clazz);
119
120         } catch (final HttpStatusCodeException httpStatusCodeException) {
121             final String message = "Unable to invoke HTTP " + httpMethod + " using url: " + url + ", Response: "
122                     + httpStatusCodeException.getRawStatusCode();
123             LOGGER.error(message, httpStatusCodeException);
124             final int rawStatusCode = httpStatusCodeException.getRawStatusCode();
125             if (rawStatusCode == HttpStatus.BAD_REQUEST.value()) {
126                 throw new InvalidRestRequestException("No result found for given url: " + url);
127             } else if (rawStatusCode == HttpStatus.NOT_FOUND.value()) {
128                 throw new HttpResouceNotFoundException("No result found for given url: " + url);
129             }
130             throw new RestProcessingException("Unable to invoke HTTP " + httpMethod + " using URL: " + url,
131                     httpStatusCodeException, rawStatusCode);
132
133         } catch (final RestClientException restClientException) {
134             LOGGER.error("Unable to invoke HTTP POST using url: {}", url, restClientException);
135             throw new RestProcessingException("Unable to invoke HTTP " + httpMethod + " using URL: " + url,
136                     restClientException);
137         }
138     }
139
140     @Override
141     public <T> ResponseEntity<T> deleteHttpRequest(final String url, final Class<T> clazz) {
142         try {
143             final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders());
144             return restTemplate.exchange(url, HttpMethod.DELETE, request, clazz);
145
146         } catch (final RestClientException restClientException) {
147             LOGGER.error("Unable to invoke HTTP DELETE using url: " + url, restClientException);
148             throw new InvalidRestRequestException("Unable to invoke HTTP DELETE using URL: " + url,
149                     restClientException);
150         }
151     }
152
153     private HttpHeaders getHttpHeaders() {
154         return httpHeadersProvider.getHttpHeaders();
155     }
156 }