Open Kilda Java Documentation
RestClientManager.java
Go to the documentation of this file.
1 package org.openkilda.helper;
2 
3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory;
5 
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.http.HttpHeaders;
8 import org.springframework.http.HttpMethod;
9 import org.springframework.http.HttpStatus;
10 import org.springframework.stereotype.Component;
11 
12 import com.fasterxml.jackson.databind.ObjectMapper;
13 import com.fasterxml.jackson.databind.type.TypeFactory;
14 
15 import java.io.IOException;
16 import java.util.List;
17 
18 import org.apache.http.HttpResponse;
19 import org.apache.http.client.HttpClient;
20 import org.apache.http.client.methods.HttpDelete;
21 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
22 import org.apache.http.client.methods.HttpGet;
23 import org.apache.http.client.methods.HttpPatch;
24 import org.apache.http.client.methods.HttpPost;
25 import org.apache.http.client.methods.HttpPut;
26 import org.apache.http.client.methods.HttpUriRequest;
27 import org.apache.http.entity.StringEntity;
28 import org.apache.http.impl.client.HttpClients;
39 
43 @Component
44 public class RestClientManager {
45 
46  private static final Logger LOGGER = LoggerFactory.getLogger(RestClientManager.class);
47 
48  @Autowired
49  private AuthPropertyService authPropertyService;
50 
51  @Autowired
52  private ObjectMapper mapper;
53 
54 
65  public HttpResponse invoke(final String apiUrl, final HttpMethod httpMethod,
66  final String payload, final String contentType, final String basicAuth) {
67  LOGGER.info("[invoke] - Start");
68 
69  HttpResponse httpResponse = null;
70 
71  try {
72  HttpClient client = HttpClients.createDefault();
73  HttpUriRequest httpUriRequest = null;
74  HttpEntityEnclosingRequestBase httpEntityEnclosingRequest = null;
75 
76  // Initializing Request
77  if (HttpMethod.POST.equals(httpMethod)) {
78  httpEntityEnclosingRequest = new HttpPost(apiUrl);
79  } else if (HttpMethod.PUT.equals(httpMethod)) {
80  httpEntityEnclosingRequest = new HttpPut(apiUrl);
81  } else if (HttpMethod.DELETE.equals(httpMethod)) {
82  httpUriRequest = new HttpDelete(apiUrl);
83  } else if (HttpMethod.PATCH.equals(httpMethod)) {
84  httpUriRequest = new HttpPatch(apiUrl);
85  }else {
86  httpUriRequest = new HttpGet(apiUrl);
87  }
88 
89  if (!HttpMethod.POST.equals(httpMethod) && !HttpMethod.PUT.equals(httpMethod)) {
90  // Setting Required Headers
91  if (!StringUtil.isNullOrEmpty(basicAuth)) {
92  LOGGER.debug("[invoke] Setting authorization in header as "
94  httpUriRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
95  }
96  }
97 
98  if (HttpMethod.POST.equals(httpMethod) || HttpMethod.PUT.equals(httpMethod)) {
99  LOGGER.info("[invoke] Executing POST/ PUT request : httpEntityEnclosingRequest : "
100  + httpEntityEnclosingRequest + " : payload : " + payload);
101  // Setting POST/PUT related headers
102  httpEntityEnclosingRequest.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
103  httpEntityEnclosingRequest.setHeader(IAuthConstants.Header.AUTHORIZATION, basicAuth);
104  // Setting request payload
105  httpEntityEnclosingRequest.setEntity(new StringEntity(payload));
106  httpResponse = client.execute(httpEntityEnclosingRequest);
107  LOGGER.debug("[invoke] Call executed successfully");
108  } else {
109  LOGGER.info("[invoke] Executing : httpUriRequest : " + httpUriRequest);
110  httpResponse = client.execute(httpUriRequest);
111  LOGGER.info("[invoke] Call executed successfully");
112  }
113 
114  } catch (Exception e) {
115  LOGGER.error("[invoke] Exception: ", e);
116  throw new RestCallFailedException(e);
117  }
118  LOGGER.info("[invoke] - End");
119  return httpResponse;
120  }
121 
130  @SuppressWarnings("unchecked")
131  public <T> List<T> getResponseList(final HttpResponse response, final Class<T> responseClass) {
132  return getResponse(response, List.class, responseClass);
133  }
134 
143  public <T> T getResponse(final HttpResponse response, final Class<T> responseClass) {
144  return getResponse(response, responseClass, null);
145  }
146 
157  private <T, E> T getResponse(final HttpResponse response, final Class<T> responseClass,
158  final Class<E> dependentClass) {
159  T obj = null;
160  try {
161  LOGGER.info("[getResponse] : StatusCode " + response.getStatusLine().getStatusCode());
162 
163  if (response.getStatusLine().getStatusCode() != HttpStatus.NO_CONTENT.value()) {
164  String responseEntity = IoUtil.toString(response.getEntity().getContent());
165 
166  LOGGER.debug("[getResponse] : response object " + responseEntity);
167  if (!(HttpStatus.valueOf(response.getStatusLine().getStatusCode())
168  .is2xxSuccessful() && response.getEntity() != null)) {
169  String errorMessage = null;
170  try {
171  if (responseEntity.startsWith("[")) {
172  responseEntity = responseEntity.replaceFirst("]", "").trim();
173  }
174  if (responseEntity.endsWith("]")) {
175  responseEntity = responseEntity.replace("]", "").trim();
176  }
177 
178  errorMessage =
179  mapper.readValue(responseEntity, ErrorMessage.class).getMessage();
180 
181  } catch (Exception e) {
182  if (response.getStatusLine().getStatusCode() == HttpStatus.UNAUTHORIZED
183  .value()) {
184  throw new UnauthorizedException(HttpError.UNAUTHORIZED.getMessage());
185  }
186 
187  LOGGER.error("[getResponse] Exception :", e);
188  errorMessage =
189  authPropertyService.getError(
190  IAuthConstants.Code.RESPONSE_PARSING_FAIL_ERROR)
191  .getMessage();
192  throw new RestCallFailedException(errorMessage);
193  }
194 
195  LOGGER.error("[getResponse] Exception : " + responseEntity);
196  throw new ExternalSystemException(response.getStatusLine().getStatusCode(),
197  errorMessage);
198 
199  } else {
200  if (dependentClass == null) {
201  obj = mapper.readValue(responseEntity, responseClass);
202  } else {
203  obj =
204  mapper.readValue(responseEntity, TypeFactory.defaultInstance()
205  .constructCollectionLikeType(responseClass, dependentClass));
206  }
207  }
208  }
209  } catch (IOException e) {
210  throw new RestCallFailedException(e.getMessage());
211  }
212  return obj;
213  }
214 
221  public static boolean isValidResponse(final HttpResponse response) {
222  LOGGER.debug("[isValidResponse] Response Code " + response.getStatusLine().getStatusCode());
223  boolean isValid = response.getStatusLine().getStatusCode() >= HttpStatus.OK.value()
224  && response.getStatusLine().getStatusCode() < HttpStatus.MULTIPLE_CHOICES.value()
225  && response.getEntity() != null;
226  if(isValid) {
227  return true;
228  } else {
229  try {
230  String content = IoUtil.toString(response.getEntity().getContent());
231  LOGGER.error("[getResponse] Invalid Response. Status Code: "
232  + response.getStatusLine().getStatusCode() + ", content: " + content);
233  throw new InvalidResponseException(response.getStatusLine().getStatusCode(),
234  content);
235  } catch (IOException exception) {
236  LOGGER.error("[getResponse] Exception :" + exception.getMessage(), exception);
237  throw new InvalidResponseException();
238  }
239  }
240  }
241 }
static boolean isValidResponse(final HttpResponse response)
static String toString(final InputStream inputStream)
Definition: IoUtil.java:29
static boolean isNullOrEmpty(final String data)
Definition: StringUtil.java:34
HttpResponse invoke(final String apiUrl, final HttpMethod httpMethod, final String payload, final String contentType, final String basicAuth)