f5625ce211282408234c56cc22a5c1c6d45cf6cf
[vid.git] / vid-app-common / src / main / java / org / onap / vid / aai / util / AAIRestInterface.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.vid.aai.util;
22
23
24 import com.att.eelf.configuration.EELFLogger;
25 import org.apache.commons.lang3.exception.ExceptionUtils;
26 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
27 import org.onap.vid.aai.ExceptionWithRequestInfo;
28 import org.onap.vid.aai.ResponseWithRequestInfo;
29 import org.onap.vid.aai.exceptions.InvalidPropertyException;
30 import org.onap.vid.utils.Logging;
31 import org.springframework.beans.factory.annotation.Autowired;
32 import org.springframework.http.HttpMethod;
33
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.Invocation;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.Response;
39 import java.io.UnsupportedEncodingException;
40 import java.net.URLEncoder;
41 import java.util.Optional;
42 import java.util.UUID;
43
44 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
45 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
46
47
48 /**
49  * The Class AAIRestInterface.
50  */
51 public class AAIRestInterface {
52
53         /** The logger. */
54         protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class);
55
56         protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai");
57
58
59         /** The client. */
60         private Client client = null;
61
62         /** The rest srvr base URL. */
63         private String restSrvrBaseURL;
64
65         @Autowired
66         protected HttpsAuthClient httpsAuthClientFactory;
67         private final ServletRequestHelper servletRequestHelper;
68         private final SystemPropertyHelper systemPropertyHelper;
69
70         protected static final String START_STRING = " start";
71         protected static final String TRANSACTION_ID_HEADER = "X-TransactionId";
72         protected static final String FROM_APP_ID_HEADER = "X-FromAppId";
73         protected static final String SUCCESSFUL_API_MESSAGE = " REST api call was successful!";
74         protected static final String URL_DECLARATION = ", url=";
75
76         public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) {
77                 this.httpsAuthClientFactory = httpsAuthClientFactory;
78                 this.servletRequestHelper = servletRequestHelper;
79                 this.systemPropertyHelper = systemPropertyHelper;
80                 initRestClient();
81         }
82
83         /**
84          * For testing purpose
85          */
86         AAIRestInterface(Optional<Client> client,
87                                          HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper){
88                 this.httpsAuthClientFactory = httpsAuthClientFactory;
89                 this.servletRequestHelper = servletRequestHelper;
90                 this.systemPropertyHelper = systemPropertyHelper;
91                 if (client != null && client.isPresent()){
92                         this.client = client.get();
93                 }
94
95         }
96
97         /**
98          * Encode URL.
99          *
100          * @param nodeKey the node key
101          * @return the string
102          * @throws UnsupportedEncodingException the unsupported encoding exception
103          */
104         public String encodeURL (String nodeKey) throws UnsupportedEncodingException {
105                 return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
106         }
107
108     private void initRestClient() {
109         initRestClient(false);
110     }
111
112
113         private void initRestClient(boolean propagateExceptions) {
114                 if (client == null) {
115                         try {
116                                 client = httpsAuthClientFactory.getClient(HttpClientMode.WITH_KEYSTORE);
117                         } catch (Exception e) {
118                                 logger.info(EELFLoggerDelegate.errorLogger, "Exception in REST call to DB in initRestClient" + e.toString());
119                                 logger.debug(EELFLoggerDelegate.debugLogger, "Exception in REST call to DB : " + e.toString());
120                                 if (propagateExceptions) {
121                                         ExceptionUtils.rethrow(e);
122                                 }
123                         }
124                 }
125         }
126
127
128
129         /**
130          * Sets the rest srvr base URL.
131          *
132          * @param baseURL the base URL
133          */
134         public void SetRestSrvrBaseURL(String baseURL)
135         {
136                 if (baseURL == null) {
137                         logger.info(EELFLoggerDelegate.errorLogger, "REST Server base URL cannot be null.");
138                         logger.debug(EELFLoggerDelegate.debugLogger, "REST Server base URL cannot be null.");
139                 }
140
141                 restSrvrBaseURL = baseURL;
142         }
143
144         /**
145          * Gets the rest srvr base URL.
146          *
147          * @return the rest srvr base URL
148          */
149         public String getRestSrvrBaseURL() {
150                 return restSrvrBaseURL;
151         }
152
153
154         /**
155          * Rest get.
156          *
157          * @param fromAppId the from app id
158          * @param transId the trans id
159          * @param requestUri the request uri
160          * @param xml the xml
161          * @return the string
162          */
163         public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) {
164                 return RestGet(fromAppId, transId, requestUri, xml, false);
165         }
166
167         public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) {
168         String methodName = "RestGet";
169                 String url = systemPropertyHelper.getFullServicePath(requestUri);
170                 try {
171                         initRestClient(propagateExceptions);
172
173                         logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
174                         logger.debug(EELFLoggerDelegate.debugLogger, url + " for the get REST API");
175
176                         Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
177
178                         final Response response;
179             Invocation.Builder requestBuilder = client.target(url)
180                     .request()
181                     .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
182                     .header(TRANSACTION_ID_HEADER, transId)
183                     .header(FROM_APP_ID_HEADER, fromAppId)
184                     .header("Content-Type", MediaType.APPLICATION_JSON)
185                     .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId());
186             response = systemPropertyHelper.isClientCertEnabled() ?
187                     requestBuilder.get() : authenticateRequest(requestBuilder).get();
188                         Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response);
189
190                         if (response.getStatusInfo().equals(Response.Status.OK)) {
191                                 logger.debug(EELFLoggerDelegate.debugLogger, methodName + SUCCESSFUL_API_MESSAGE);
192                                 logger.info(EELFLoggerDelegate.errorLogger, methodName + SUCCESSFUL_API_MESSAGE);
193                         } else {
194                                 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
195                         }
196                         return new ResponseWithRequestInfo(response, url, HttpMethod.GET);
197                 } catch (Exception e) {
198                         logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
199                         if (propagateExceptions) {
200                 throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e);
201             } else {
202                 return new ResponseWithRequestInfo(null, url, HttpMethod.GET);
203             }
204                 }
205         }
206
207         protected String extractOrGenerateRequestId() {
208                 return servletRequestHelper.extractOrGenerateRequestId();
209         }
210
211
212         /**
213          * Delete.
214          *
215          * @param sourceID the source ID
216          * @param transId the trans id
217          * @param path the path
218          * @return true, if successful
219          */
220         public boolean Delete(String sourceID, String transId, String path) {
221                 String methodName = "Delete";
222                 transId += ":" + UUID.randomUUID().toString();
223                 logger.debug(methodName + START_STRING);
224                 Boolean response = false;
225                 String url = systemPropertyHelper.getFullServicePath(path);;
226                 try {
227
228                         initRestClient();
229                         Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
230                         final Response cres = client.target(url)
231                                         .request()
232                                         .accept(MediaType.APPLICATION_JSON)
233                                         .header(TRANSACTION_ID_HEADER, transId)
234                                         .header(FROM_APP_ID_HEADER, sourceID)
235                                         .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
236                                         .delete();
237                         Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
238                         if (cres.getStatusInfo().equals(Response.Status.NOT_FOUND)) {
239                                 logger.debug(EELFLoggerDelegate.debugLogger, "Resource does not exist...: " + cres.getStatus()
240                                                 + ":" + cres.readEntity(String.class));
241                                 response = false;
242                         } else if (cres.getStatusInfo().equals(Response.Status.OK) || cres.getStatusInfo().equals(Response.Status.NO_CONTENT)) {
243                                 logger.debug(EELFLoggerDelegate.debugLogger, "Resource " + url + " deleted");
244                                 logger.info(EELFLoggerDelegate.errorLogger, "Resource " + url + " deleted");
245                                 response = true;
246                         } else {
247                                 logger.debug(EELFLoggerDelegate.debugLogger, "Deleting Resource failed: " + cres.getStatus()
248                                                 + ":" + cres.readEntity(String.class));
249                                 response = false;
250                         }
251
252                 } catch (Exception e) {
253                         logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
254                 }
255                 return response;
256         }
257
258
259         /**
260          * Rest put.
261          *
262          * @param fromAppId the from app id
263          * @param path the path
264          * @param payload the payload
265          * @param xml the xml
266          * @return the string
267          */
268         public Response RestPut(String fromAppId, String path, String payload, boolean xml) {
269                 String methodName = "RestPut";
270                 String url=systemPropertyHelper.getFullServicePath(path);
271                 String transId = UUID.randomUUID().toString();
272                 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
273
274         Response response = null;
275                 try {
276                         initRestClient();
277                         Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, payload);
278                         response = authenticateRequest(client.target(url)
279                                         .request()
280                     .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
281                                         .header(TRANSACTION_ID_HEADER, transId)
282                                         .header(FROM_APP_ID_HEADER,  fromAppId))
283                                         .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
284                                         .put(Entity.entity(payload, MediaType.APPLICATION_JSON));
285                         Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, response);
286
287                         if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
288                                 logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName));
289                                 logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName));
290                         } else {
291                                 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
292                         }
293                 } catch (Exception e) {
294                         logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
295                 }
296                 return response;
297         }
298
299
300
301         /**
302          * Rest post.
303          *
304          * @param fromAppId the from app id
305          * @param path the path
306          * @param payload the payload
307          * @param xml the xml
308          * @return the string
309          */
310         public Response RestPost(String fromAppId, String path, String payload, boolean xml) {
311                 String methodName = "RestPost";
312                 String url=systemPropertyHelper.getServiceBasePath(path);
313                 String transId = UUID.randomUUID().toString();
314                 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
315
316         Response response = null;
317                 try {
318                         initRestClient();
319                         Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload);
320                         response = authenticateRequest(client.target(systemPropertyHelper.getServiceBasePath(path))
321                                         .request()
322                     .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
323                                         .header(TRANSACTION_ID_HEADER, transId)
324                                         .header(FROM_APP_ID_HEADER,  fromAppId))
325                                         .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
326                                         .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
327                         Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, response);
328
329                         if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
330                                 logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName));
331                                 logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName));
332                         } else {
333                                 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
334                         }
335                 } catch (Exception e) {
336                         logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
337                 }
338                 return response;
339         }
340
341         protected String getFailedResponseLogMessage(String path, String methodName, Exception e) {
342                 return methodName + URL_DECLARATION + path + ", Exception: " + e.toString();
343         }
344
345         protected String getValidResponseLogMessage(String methodName) {
346                 return methodName + URL_DECLARATION;
347         }
348
349         protected String getInvalidResponseLogMessage(String path, String methodName, Response cres) {
350                 return methodName + " with status=" + cres.getStatus() + URL_DECLARATION + path;
351         }
352
353         private Invocation.Builder authenticateRequest(Invocation.Builder requestBuilder) throws InvalidPropertyException, UnsupportedEncodingException {
354                 return requestBuilder
355                                 .header("Authorization", "Basic " + systemPropertyHelper.getEncodedCredentials());
356         }
357
358 }