org.onap migration
[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 java.io.UnsupportedEncodingException;
24 import java.net.URLEncoder;
25 import java.security.KeyManagementException;
26 import java.text.DateFormat;
27 import java.text.SimpleDateFormat;
28 import java.util.Base64;
29 import java.util.Date;
30 import java.util.UUID;
31
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.Response;
36
37 import com.att.eelf.configuration.EELFLogger;
38 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
39 import org.openecomp.portalsdk.core.util.SystemProperties;
40 import org.eclipse.jetty.util.security.Password;
41 import org.onap.vid.utils.Logging;
42 import org.springframework.http.HttpMethod;
43 import static org.onap.vid.utils.Logging.getHttpServletRequest;
44 import static org.onap.vid.utils.Logging.requestIdHeaderKey;
45
46
47 /**
48  * The Class AAIRestInterface.
49  */
50 public class AAIRestInterface {
51
52         /** The logger. */
53         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class);
54
55         final private EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai");
56
57         /** The Constant dateFormat. */
58         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
59
60         /** The client. */
61         private static Client client = null;
62
63         /** The rest srvr base URL. */
64         private String restSrvrBaseURL;
65
66         /** The certificate path. */
67         public String certificatePath = "";
68
69         private String START_STRING = " start";
70
71         private String TRANSACTION_ID_HEADER = "X-TransactionId";
72         private String FROM_APP_ID_HEADER = "X-FromAppId";
73         private String SUCCESSFUL_API_MESSAGE=" REST api POST was successful!";
74         private String URL_DECLERATION = ", url=";
75
76
77
78
79
80
81         /**
82          * Instantiates a new AAI rest interface.
83          *
84          * @param certPath the cert path
85          */
86         public AAIRestInterface(String certPath)
87         {
88                 certificatePath = certPath;
89         }
90
91         /**
92          * Encode URL.
93          *
94          * @param nodeKey the node key
95          * @return the string
96          * @throws UnsupportedEncodingException the unsupported encoding exception
97          */
98         public String encodeURL (String nodeKey) throws UnsupportedEncodingException {
99                 return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
100         }
101
102         /**
103          * Inits the rest client.
104          */
105         private void initRestClient()
106         {
107                 String methodName = "initRestClient";
108
109                 if (client == null) {
110                         try {
111                                 client = HttpsAuthClient.getClient(certificatePath);
112                         }
113                         catch (KeyManagementException e){
114                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  "<== KeyManagementException in " + methodName + e.toString());
115                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) +  "<== KeyManagementException in " + methodName + e.toString());
116                         } catch (Exception e) {
117                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  "<== Exception in REST call to DB in initRestClient" + e.toString());
118                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) +  "<== Exception in REST call to DB : " + e.toString());
119                         }
120                 }
121         }
122
123         /**
124          * Sets the rest srvr base URL.
125          *
126          * @param baseURL the base URL
127          */
128         public void SetRestSrvrBaseURL(String baseURL)
129         {
130                 if (baseURL == null)
131                 {
132                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  "<== REST Server base URL cannot be null.");
133                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) +  "<== REST Server base URL cannot be null.");
134                 }
135
136                 restSrvrBaseURL = baseURL;
137         }
138
139         /**
140          * Gets the rest srvr base URL.
141          *
142          * @return the rest srvr base URL
143          */
144         public String getRestSrvrBaseURL()
145         {
146                 return restSrvrBaseURL;
147         }
148
149
150         /**
151          * Rest get.
152          *
153          * @param fromAppId the from app id
154          * @param transId the trans id
155          * @param requestUri the request uri
156          * @param xml the xml
157          * @return the string
158          * @throws UnsupportedEncodingException
159          */
160         public Response RestGet(String fromAppId, String transId, String requestUri, boolean xml) throws UnsupportedEncodingException  {
161                 String methodName = "RestGet";
162
163                 String responseType = MediaType.APPLICATION_JSON;
164                 if (xml)
165                         responseType = MediaType.APPLICATION_XML;
166
167                 initRestClient();
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                 String url = "";
177                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING);
178
179                 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri;
180
181
182                 logger.debug(dateFormat.format(new Date()) + "<== " + url + " for the get REST API");
183                 Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
184
185                 final Response cres;
186                 if (useClientCert == true) {
187                         cres = client.target(url)
188                                         .request()
189                                         .accept(responseType)
190                                         .header(TRANSACTION_ID_HEADER, transId)
191                                         .header(FROM_APP_ID_HEADER,  fromAppId)
192                                         .header("Content-Type", MediaType.APPLICATION_JSON)
193                                         .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
194                                         .get();
195                 } else {
196
197                         String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
198                         String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
199                         String encodeThis = vidUsername + ":" + vidPassword;
200
201                         cres = client.target(url)
202                                         .request()
203                                         .accept(responseType)
204                                         .header(TRANSACTION_ID_HEADER, transId)
205                                         .header(FROM_APP_ID_HEADER,  fromAppId)
206                                         .header("Content-Type", "application/json")
207                                         .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
208                                         .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
209                                         .get();
210                 }
211                 Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
212 //              String r = cres.readEntity(String.class);
213                 if (cres.getStatus() == 200) {
214                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE);
215                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE);
216                 } else {
217                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+URL_DECLERATION+url);
218                 }
219                 return cres;
220 //               logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" resp=" + r );
221 //               return r;
222         }
223
224
225         /**
226          * Delete.
227          *
228          * @param sourceID the source ID
229          * @param transId the trans id
230          * @param path the path
231          * @return true, if successful
232          */
233         public boolean Delete(String sourceID,  String transId,  String path) {
234                 String methodName = "Delete";
235                 String url="";
236                 transId += ":" + UUID.randomUUID().toString();
237                 logger.debug(dateFormat.format(new Date()) + "<== " +  methodName + START_STRING);
238
239                 initRestClient();
240                 String request = "{}";
241                 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path;
242                 Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
243                 final Response cres = client.target(url)
244                                 .request()
245                                 .accept(MediaType.APPLICATION_JSON)
246                                 .header(TRANSACTION_ID_HEADER, transId)
247                                 .header(FROM_APP_ID_HEADER,  sourceID)
248                                 .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
249                                 //.entity(request)
250                                 .delete();
251                 Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
252                 if (cres.getStatus() == 404) { // resource not found
253                         String msg = "Resource does not exist...: " + cres.getStatus()
254                                         + ":" + cres.readEntity(String.class);
255                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + msg);
256                         return false;
257                 } else if (cres.getStatus() == 200  || cres.getStatus() == 204){
258                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted");
259                         return true;
260                 } else {
261                         String msg = "Deleting Resource failed: " + cres.getStatus()
262                                         + ":" + cres.readEntity(String.class);
263                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + msg);
264                 }
265
266                 return false;
267         }
268
269
270         /**
271          * Rest put.
272          *
273          * @param fromAppId the from app id
274          * @param transId the trans id
275          * @param path the path
276          * @param payload the payload
277          * @param xml the xml
278          * @return the string
279          */
280         public Response RestPut(String fromAppId,  String transId,  String path, String payload, boolean xml) {
281                 String methodName = "RestPut";
282                 String url="";
283                 transId = UUID.randomUUID().toString();
284                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " +  methodName + START_STRING);
285
286                 try {
287
288                         String responseType = MediaType.APPLICATION_JSON;
289                         if (xml)
290                                 responseType = "application/xml";
291
292                         initRestClient();
293
294                         url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path;
295                         Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, payload);
296                         final Response cres = client.target(url)
297                                         .request()
298                                         .accept(responseType)
299                                         .header(TRANSACTION_ID_HEADER, transId)
300                                         .header(FROM_APP_ID_HEADER,  fromAppId)
301                                         .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
302                                         .put(Entity.entity(payload, MediaType.APPLICATION_JSON));
303                         Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres);
304
305                         if (cres.getStatus() == 200 && cres.getStatus() <= 299) {
306                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION);
307                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION);
308                         } else {
309                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+URL_DECLERATION+url);
310                         }
311                         return cres;
312                 } catch (Exception e) {
313                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION+url+ ", Exception: " + e.toString());
314                 }
315                 return null;
316         }
317
318
319
320         /**
321          * Rest post.
322          *
323          * @param fromAppId the from app id
324          * @param transId the trans id
325          * @param path the path
326          * @param payload the payload
327          * @param xml the xml
328          * @return the string
329          */
330         public Response RestPost(String fromAppId,  String transId,  String path, String payload, boolean xml) {
331                 String methodName = "RestPost";
332                 String url="";
333                 transId = UUID.randomUUID().toString();
334                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " +  methodName + START_STRING);
335
336                 try {
337
338                         String responseType = MediaType.APPLICATION_JSON;
339                         if (xml)
340                                 responseType = "application/xml";
341
342                         initRestClient();
343
344                         url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL_BASE) + path;
345                         String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
346                         String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
347                         String encodeThis = vidUsername + ":" + vidPassword;
348                         
349                         Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload);
350                         final Response cres = client.target(url)
351                                         .request()
352                                         .accept(responseType)
353                                         .header(TRANSACTION_ID_HEADER, transId)
354                                         .header(FROM_APP_ID_HEADER,  fromAppId)
355                                         .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
356                                         .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
357                                         .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
358                         Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres);
359
360                         if (cres.getStatus() == 200 && cres.getStatus() <= 299) {
361                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION);
362                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION);
363                         } else {
364                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with status="+cres.getStatus()+URL_DECLERATION+url);
365                         }
366                         return cres;
367                 } catch (Exception e) {
368                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION+url+ ", Exception: " + e.toString());
369                 }
370                 return null;
371         }
372
373 }