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