[VID-3] Setting docker image tag
[vid.git] / vid / src / main / java / org / openecomp / 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
21 package org.openecomp.aai.util;
22
23 import java.io.UnsupportedEncodingException;
24 import java.net.MalformedURLException;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.net.URL;
28 import java.net.URLEncoder;
29 import java.security.KeyManagementException;
30 import java.text.DateFormat;
31 import java.text.SimpleDateFormat;
32 import java.util.Base64;
33 import java.util.Date;
34 import java.util.UUID;
35
36 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.Entity;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40
41 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.openecomp.portalsdk.core.util.SystemProperties;
43 import org.openecomp.vid.encryption.EncryptedPropValue;
44
45 /**
46  * The Class AAIRestInterface.
47  */
48 public class AAIRestInterface {
49
50         /** The logger. */
51         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class);
52         
53         /** The Constant dateFormat. */
54         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
55         
56         /** The client. */
57         private static Client client = null;
58         
59         /** The rest srvr base URL. */
60         private String restSrvrBaseURL;
61         
62         /** The certificate path. */
63         public String certificatePath = "";
64         
65         /**
66          * Instantiates a new AAI rest interface.
67          *
68          * @param certPath the cert path
69          */
70         public AAIRestInterface(String certPath)
71         {
72                 certificatePath = certPath;
73         }
74         
75         /**
76          * Encode URL.
77          *
78          * @param nodeKey the node key
79          * @return the string
80          * @throws UnsupportedEncodingException the unsupported encoding exception
81          */
82         public String encodeURL (String nodeKey) throws UnsupportedEncodingException {
83                 return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
84         }
85         
86         /**
87          * Inits the rest client.
88          */
89         private void initRestClient()
90         {
91                 String methodName = "initRestClient";
92                 
93                 if (client == null) {
94                         try {
95                                 client = HttpsAuthClient.getClient(certificatePath);
96                         }
97                         catch (KeyManagementException e){
98                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  "<== KeyManagementException in " + methodName + e.toString());
99                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) +  "<== KeyManagementException in " + methodName + e.toString());
100                         } catch (Exception e) {
101                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  "<== Exception in REST call to DB in initRestClient" + e.toString());
102                                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) +  "<== Exception in REST call to DB : " + e.toString());
103                         }
104                 }
105         }
106         
107         /**
108          * Sets the rest srvr base URL.
109          *
110          * @param baseURL the base URL
111          */
112         public void SetRestSrvrBaseURL(String baseURL)
113         {
114                 if (baseURL == null)
115                 {
116                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  "<== REST Server base URL cannot be null.");
117                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) +  "<== REST Server base URL cannot be null.");
118                 }
119                         
120                 restSrvrBaseURL = baseURL;
121         }
122         
123         /**
124          * Gets the rest srvr base URL.
125          *
126          * @return the rest srvr base URL
127          */
128         public String getRestSrvrBaseURL() 
129         {
130                 return restSrvrBaseURL;
131         }
132         
133         
134         /**
135          * Rest get.
136          *
137          * @param fromAppId the from app id
138          * @param transId the trans id
139          * @param requestUri the request uri
140          * @param xml the xml
141          * @return the string
142          */
143         public String RestGet(String fromAppId, String transId, String requestUri, boolean xml) throws UnsupportedEncodingException  {
144                 String methodName = "RestGet";
145                 
146                 String responseType = "application/json";
147                 if (xml)
148                 responseType = "application/xml";
149                   
150                 initRestClient();
151                 
152                 String url = "";
153                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
154         
155                 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri;
156                 
157             try {
158                 // what is the point of this, just to check syntax??
159                     URL urlObj= new URL(url);
160                         URI uri = new URI(urlObj.getProtocol(), urlObj.getUserInfo(), urlObj.getHost(), urlObj.getPort(), urlObj.getPath(), urlObj.getQuery(), urlObj.getRef());
161                         url = uri.toASCIIString();
162             } catch (URISyntaxException | MalformedURLException e) {
163                  logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " +  methodName + " bad URL");
164                  return null;
165                 }
166             logger.debug(dateFormat.format(new Date()) + "<== " + url + " for the get REST API");
167
168                 String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
169                 String vidPassword = EncryptedPropValue.decryptTriple(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
170                 String encodeThis = vidUsername + ":" + vidPassword;
171             
172                 final Response cres = client.target(url)
173                          .request()
174                  .accept(responseType)
175                  .header("X-TransactionId", transId)
176                  .header("X-FromAppId",  fromAppId)
177                  .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
178                  .header("Content-Type", "application/json")
179                  .get();
180                 
181                  if (cres.getStatus() == 200) {
182                          logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api GET was successful!");
183                          logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api GET was successful!");
184                  } else {
185                          logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+", url="+url);
186                  }
187                  
188                  return cres.readEntity(String.class);
189         }
190         
191         
192         /**
193          * Delete.
194          *
195          * @param sourceID the source ID
196          * @param transId the trans id
197          * @param path the path
198          * @return true, if successful
199          */
200         public boolean Delete(String sourceID,  String transId,  String path) throws UnsupportedEncodingException {
201                 String methodName = "Delete";
202                 String url="";
203                 transId += ":" + UUID.randomUUID().toString();
204                 logger.debug(dateFormat.format(new Date()) + "<== " +  methodName + " start");
205                 
206                 initRestClient();
207                 String request = "{}";
208                 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path;                
209                 
210                 String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
211                 String vidPassword = EncryptedPropValue.decryptTriple(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
212                 String encodeThis = vidUsername + ":" + vidPassword;
213                 
214                 final Response cres = client.target(url)
215                                  .request()
216                          .accept("application/json")
217                          .header("X-TransactionId", transId)
218                          .header("X-FromAppId",  sourceID)
219                          .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
220                          //.entity(request)
221                          .delete();
222                 
223                 if (cres.getStatus() == 404) { // resource not found
224                         String msg = "Resource does not exist...: " + cres.getStatus()
225                                         + ":" + cres.readEntity(String.class);
226                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + msg);
227                         return false;
228                 } else if (cres.getStatus() == 200  || cres.getStatus() == 204){
229                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted");
230                         return true;
231                 } else {
232                         String msg = "Deleting Resource failed: " + cres.getStatus()
233                                 + ":" + cres.readEntity(String.class);
234                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + msg);
235                 }
236
237                 return false;
238         }
239         
240     
241     /**
242      * Rest post.
243      *
244      * @param fromAppId the from app id
245      * @param transId the trans id
246      * @param path the path
247      * @param payload the payload
248      * @param xml the xml
249      * @return the string
250      */
251     public String RestPost(String fromAppId,  String transId,  String path, String payload, boolean xml) throws UnsupportedEncodingException {
252         String methodName = "RestPost";
253         String url="";
254         transId = UUID.randomUUID().toString();
255         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " +  methodName + " start");       
256         
257         try {
258             
259                 String responseType = "application/json";
260                 if (xml)
261                 responseType = "application/xml";
262                    
263             initRestClient();    
264     
265             url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL_BASE) + path;
266                         
267                         String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
268                         String vidPassword = EncryptedPropValue.decryptTriple(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
269                         String encodeThis = vidUsername + ":" + vidPassword;
270                                                 
271             final Response cres = client.target(url)
272                  .request()
273                  .accept(responseType)
274                  .header("X-TransactionId", transId)
275                  .header("X-FromAppId",  fromAppId)
276                  .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
277                  .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
278             
279             int statuscode = cres.getStatus();
280                 if ( statuscode >= 200 && statuscode <= 299 ) {
281                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
282                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
283                 return cres.readEntity(String.class);
284              } else {
285                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with status="+statuscode+", url="+url + ", msg=" + cres.readEntity(String.class));
286                 return null;
287              }    
288         
289         } catch (Exception e)
290         {
291                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
292         
293         }
294         
295         return null;
296     }
297     
298  
299         
300 }