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