[VID-3] Setting docker image tag
[vid.git] / vid / src / main / java / org / openecomp / vid / mso / MsoRestInterface.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.vid.mso;
22
23
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.Collections;
27 import java.util.Date;
28
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.MultivaluedHashMap;
33 import javax.ws.rs.core.Response;
34
35 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
36 import org.openecomp.portalsdk.core.util.SystemProperties;
37
38 import org.apache.commons.codec.binary.Base64;
39 import org.openecomp.vid.client.HttpBasicClient;
40 import org.openecomp.vid.client.HttpsBasicClient;
41 import org.openecomp.vid.encryption.EncryptedPropValue;
42 import org.openecomp.vid.mso.rest.RequestDetails;
43
44 /**
45  * The Class MsoRestInterface.
46  */
47 public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc {
48
49         /** The logger. */
50         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoRestInterface.class);
51         
52         /** The Constant dateFormat. */
53         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
54         
55         /** The client. */
56         private static Client client = null;
57         
58         /** The common headers. */
59         private MultivaluedHashMap<String, Object> commonHeaders;
60         
61         /**
62          * Instantiates a new mso rest interface.
63          */
64         public MsoRestInterface() {
65                 super();
66         }
67         
68         /* (non-Javadoc)
69          * @see org.openecomp.vid.mso.MsoRestInterfaceIfc#initRestClient()
70          */
71         public void initRestClient()
72         {
73                 final String methodname = "initRestClient()";
74                 
75                 final String username = SystemProperties.getProperty(MsoProperties.MSO_USER_NAME);
76                 final String password = SystemProperties.getProperty(MsoProperties.MSO_PASSWORD);
77                 final String mso_url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL);
78                 final String decrypted_password = EncryptedPropValue.decryptTriple(password);
79                 
80                 String authString = username + ":" + decrypted_password;
81                 
82                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
83                 String authStringEnc = new String(authEncBytes);
84
85                 commonHeaders = new MultivaluedHashMap<String, Object> ();
86                 commonHeaders.put("Authorization",  Collections.singletonList((Object) ("Basic " + authStringEnc)));
87                 
88                 boolean use_ssl = true;
89                 if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) {
90                         if ( mso_url.startsWith("https")) {
91                                 use_ssl = true;
92                         }
93                         else {
94                                 use_ssl = false;
95                         }
96                 }
97                 if (client == null) {
98                         
99                         try {
100                                 if ( use_ssl ) { 
101                                         //logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  methodname + " getting HttpsBasicClient with username=" + username
102                                         //              + " password=" + password);
103                                         client = HttpsBasicClient.getClient();
104                                 }
105                                 else {
106                                         //logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  methodname + " getting HttpsBasicClient with username=" + username
107                                         //              + " password=" + password);
108                                         client = HttpBasicClient.getClient();
109                                 }
110                         } catch (Exception e) {
111                                 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) +  methodname + " Unable to get the SSL client");
112                         }
113                 }
114         }
115         
116         /* (non-Javadoc)
117          * @see org.openecomp.vid.mso.MsoRestInterfaceIfc#Get(java.lang.Object, java.lang.String, java.lang.String, org.openecomp.vid.mso.RestObject)
118          */
119         @SuppressWarnings("unchecked")
120         public <T> void  Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception {
121                 String methodName = "Get";
122                 
123                 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
124                 
125                 String url="";
126                 restObject.set(t);
127                 
128                 url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
129         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " +  methodName + " sending request to url= " + url);
130                 
131         initRestClient();
132                 
133                 final Response cres = client.target(url)
134                          .request()
135                  .accept("application/json")
136                  .headers(commonHeaders)
137                  .get();
138                 
139                 int status = cres.getStatus();
140                 restObject.setStatusCode (status);
141                 
142                 if (status == 200) {
143                          t = (T) cres.readEntity(t.getClass());
144                          restObject.set(t);
145                          logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!");
146                     
147                  } else {
148                      throw new Exception(methodName + " with status="+ status + ", url= " + url );
149                  }
150
151                 logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
152                 
153                 return;
154         }
155    
156    /* (non-Javadoc)
157     * @see org.openecomp.vid.mso.MsoRestInterfaceIfc#Delete(java.lang.Object, org.openecomp.vid.mso.rest.RequestDetails, java.lang.String, java.lang.String, org.openecomp.vid.mso.RestObject)
158     */
159    @SuppressWarnings("unchecked")
160          public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
161          
162                 String methodName = "Delete";
163                 String url="";
164                 Response cres = null;
165                 
166                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " +  methodName + " start");
167                 logRequest (r);
168
169                 try {
170                         initRestClient();
171                         
172                         url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
173                         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url);
174         
175                         cres = client.target(url)
176                                          .request()
177                                  .accept("application/json")
178                                  .headers(commonHeaders)
179                                  //.entity(r)
180                                  .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
181                                //  .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
182                                  //.delete(Entity.entity(r, MediaType.APPLICATION_JSON));
183                         
184                         int status = cres.getStatus();
185                 restObject.setStatusCode (status);
186                 
187                         if (status == 404) { // resource not found
188                                 String msg = "Resource does not exist...: " + cres.getStatus();
189                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
190                         } else if (status == 200  || status == 204){
191                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted");
192                         } else if (status == 202) {
193                                 String msg = "Delete in progress: " + status;
194                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
195                         }
196                         else {
197                                 String msg = "Deleting Resource failed: " + status;
198                                         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
199                         }
200                         
201                         try {
202                                 t = (T) cres.readEntity(t.getClass());
203                                 restObject.set(t);
204             }
205             catch ( Exception e ) {
206                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e="
207                                 + e.getMessage());
208             }
209    
210         } 
211                 catch (Exception e)
212         {
213                  logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
214                  throw e;
215         
216         }
217         }
218         
219         /* (non-Javadoc)
220          * @see org.openecomp.vid.mso.MsoRestInterfaceIfc#Post(java.lang.Object, org.openecomp.vid.mso.rest.RequestDetails, java.lang.String, java.lang.String, org.openecomp.vid.mso.RestObject)
221          */
222         @SuppressWarnings("unchecked")
223         public <T> void Post(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception {
224
225         String methodName = "Post";
226         String url="";
227         
228         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " +  methodName + " start");
229        
230         logRequest (r);
231         try {
232             
233             initRestClient();    
234     
235             url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
236             logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " +  methodName + " sending request to url= " + url);
237             // Change the content length
238             final Response cres = client.target(url)
239                  .request()
240                  .accept("application/json")
241                          .headers(commonHeaders)
242                  //.header("content-length", 201)
243                  //.header("X-FromAppId",  sourceID)
244                  .post(Entity.entity(r, MediaType.APPLICATION_JSON));
245             
246             try {
247                                 t = (T) cres.readEntity(t.getClass());
248                                 restObject.set(t);
249             }
250             catch ( Exception e ) {
251                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e="
252                                 + e.getMessage());
253             }
254
255             int status = cres.getStatus();
256                 restObject.setStatusCode (status);
257                 
258                 if ( status >= 200 && status <= 299 ) {
259                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
260                         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
261                 
262              } else {
263                  logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url);
264              }    
265    
266         } catch (Exception e)
267         {
268                  logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
269                  throw e;
270         
271         }
272     }
273
274         
275     /**
276      * Gets the single instance of MsoRestInterface.
277      *
278      * @param <T> the generic type
279      * @param clazz the clazz
280      * @return single instance of MsoRestInterface
281      * @throws IllegalAccessException the illegal access exception
282      * @throws InstantiationException the instantiation exception
283      */
284     public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
285         {
286                 return clazz.newInstance();
287         } 
288         
289     
290 }