Update db process part
[vfc/nfvo/driver/vnfm/svnfm.git] / nokia / vnfmdriver / vfcadaptorservice / vfcadaptor / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / cbam / impl / CbamMgmrImpl.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.impl;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.util.HashMap;
24
25 import org.apache.http.client.ClientProtocolException;
26 import org.apache.log4j.Logger;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMCreateVnfRequest;
30 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMCreateVnfResponse;
31 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMHealVnfRequest;
32 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMHealVnfResponse;
33 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMInstantiateVnfRequest;
34 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMInstantiateVnfResponse;
35 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMQueryOperExecutionResponse;
36 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMQueryVnfResponse;
37 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMScaleVnfRequest;
38 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMScaleVnfResponse;
39 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMTerminateVnfRequest;
40 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMTerminateVnfResponse;
41 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.inf.CbamMgmrInf;
42 import org.onap.vfc.nfvo.driver.vnfm.svnfm.common.bo.AdaptorEnv;
43 import org.onap.vfc.nfvo.driver.vnfm.svnfm.constant.CommonConstants;
44 import org.onap.vfc.nfvo.driver.vnfm.svnfm.http.client.HttpClientProcessorInf;
45 import org.onap.vfc.nfvo.driver.vnfm.svnfm.http.client.HttpResult;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.MediaType;
48 import org.springframework.stereotype.Component;
49 import org.springframework.web.bind.annotation.RequestMethod;
50
51 import com.google.gson.Gson;
52
53 @Component
54 public class CbamMgmrImpl implements CbamMgmrInf {
55         private static final Logger logger = Logger.getLogger(CbamMgmrImpl.class);
56         private Gson gson = new Gson();
57         
58         @Autowired 
59         private AdaptorEnv adaptorEnv;
60         
61         @Autowired
62         HttpClientProcessorInf httpClientProcessor;
63         
64         public String retrieveToken() throws ClientProtocolException, IOException, JSONException {
65                 String result = null;
66                 String url= adaptorEnv.getCbamApiUriFront() + CommonConstants.CbamRetrieveTokenPath;
67                 HashMap<String, String> map = new HashMap<>();
68                 map.put(CommonConstants.ACCEPT, "*/*");
69                 map.put(CommonConstants.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
70                 
71                 String bodyPostStr = String.format(CommonConstants.CbamRetrieveTokenPostStr, adaptorEnv.getClientId(), adaptorEnv.getClientSecret(), adaptorEnv.getCbamUserName(), adaptorEnv.getCbamPassword());
72                 
73                 logger.debug("CbamMgmrImpl -> retrieveToken, url is " + url);
74                 logger.debug("CbamMgmrImpl -> retrieveToken, bodyPostStr is " + bodyPostStr);
75                 
76                 String responseStr = httpClientProcessor.process(url, RequestMethod.POST, map, bodyPostStr).getContent();
77                 
78                 logger.info("CbamMgmrImpl -> retrieveToken, responseStr is " + responseStr);
79                 
80                 JSONObject tokenJsonObject = new JSONObject(responseStr);
81                 
82                 result = tokenJsonObject.getString(CommonConstants.CBAM_TOKEN_KEY);
83                 
84                 return result;
85         }
86         
87         public CBAMCreateVnfResponse createVnf(CBAMCreateVnfRequest cbamRequest) throws ClientProtocolException, IOException {
88                 String httpPath = CommonConstants.CbamCreateVnfPath;
89                 RequestMethod method = RequestMethod.POST;
90                         
91                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
92                 String responseStr = httpResult.getContent();
93                 
94                 logger.info("CbamMgmrImpl -> createVnf, responseStr is " + responseStr);
95                 int code = httpResult.getStatusCode();
96                 if(code == 201) {
97                         logger.info("CbamMgmrImpl -> createVnf success");
98                 }else {
99                         logger.error("CbamMgmrImpl -> createVnf error ");
100                 }
101                 CBAMCreateVnfResponse response = gson.fromJson(responseStr, CBAMCreateVnfResponse.class);
102                 
103                 return response;
104         }
105         
106         /* (non-Javadoc)
107          * @see com.nokia.vfcadaptor.cbam.impl.CbamMgmrInf#instantiateVnf(com.nokia.vfcadaptor.cbam.bo.CBAMInstantiateVnfRequest, java.lang.String)
108          */
109         public CBAMInstantiateVnfResponse instantiateVnf(CBAMInstantiateVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
110                 String httpPath = String.format(CommonConstants.CbamInstantiateVnfPath, vnfInstanceId);
111                 RequestMethod method = RequestMethod.POST;
112                         
113                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
114                 String responseStr = httpResult.getContent();
115                 
116                 logger.info("CbamMgmrImpl -> instantiateVnf, responseStr is " + responseStr);
117                 int code = httpResult.getStatusCode();
118                 if(code == 202) {
119                         logger.info("CbamMgmrImpl -> instantiateVnf success " );
120                 }else {
121                         logger.error("CbamMgmrImpl -> instantiateVnf error " );
122                 }
123                 CBAMInstantiateVnfResponse response = gson.fromJson(responseStr, CBAMInstantiateVnfResponse.class);
124                 
125                 return response;
126         }
127         
128         public CBAMTerminateVnfResponse terminateVnf(CBAMTerminateVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
129                 String httpPath = String.format(CommonConstants.CbamTerminateVnfPath, vnfInstanceId);
130                 RequestMethod method = RequestMethod.POST;
131                 
132                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
133                 String responseStr = httpResult.getContent();
134                 
135                 logger.info("CbamMgmrImpl -> terminateVnf, responseStr is " + responseStr);
136                 int code = httpResult.getStatusCode();
137                 if(code == 202) {
138                         logger.info("CbamMgmrImpl -> terminateVnf  sucess " );
139                 }else {
140                         logger.error("CbamMgmrImpl -> terminateVnf error " );
141                 }
142                 CBAMTerminateVnfResponse response = gson.fromJson(responseStr, CBAMTerminateVnfResponse.class);
143                 
144                 return response;
145         }
146         
147         public void deleteVnf(String vnfInstanceId) throws ClientProtocolException, IOException {
148                 String httpPath = String.format(CommonConstants.CbamDeleteVnfPath, vnfInstanceId);
149                 RequestMethod method = RequestMethod.DELETE;
150                 HttpResult httpResult = operateCbamHttpTask(null, httpPath, method);
151                 
152                 int code = httpResult.getStatusCode();
153                 if(code == 204) {
154                         logger.info("CbamMgmrImpl -> deleteVnf success.");
155                 }else {
156                     logger.error("CbamMgmrImpl -> deleteVnf error. detail info is " + httpResult.getContent());
157                 }
158                 
159         }
160         
161         public CBAMScaleVnfResponse scaleVnf(CBAMScaleVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
162                 String httpPath = String.format(CommonConstants.CbamScaleVnfPath, vnfInstanceId);
163                 RequestMethod method = RequestMethod.POST;
164                         
165                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
166                 String responseStr = httpResult.getContent();
167                 int code = httpResult.getStatusCode();
168                 if(code == 202) {
169                         logger.info("CbamMgmrImpl -> scaleVnf success.");
170                 }else {
171                     logger.error("CbamMgmrImpl -> scaleVnf error. " );
172                 }
173                 CBAMScaleVnfResponse response = gson.fromJson(responseStr, CBAMScaleVnfResponse.class);
174                 
175                 return response;
176         }
177
178         public CBAMHealVnfResponse healVnf(CBAMHealVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
179                 String httpPath = String.format(CommonConstants.CbamHealVnfPath, vnfInstanceId);
180                 RequestMethod method = RequestMethod.POST;
181                         
182                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
183                 String responseStr = httpResult.getContent();
184                 
185                 logger.info("CbamMgmrImpl -> healVnf, responseStr is " + responseStr);
186                 int code = httpResult.getStatusCode();
187                 if(code == 202) {
188                         logger.info("CbamMgmrImpl -> healVnf success.");
189                 }else {
190                     logger.error("CbamMgmrImpl -> healVnf error. " );
191                 }
192                 CBAMHealVnfResponse response = gson.fromJson(responseStr, CBAMHealVnfResponse.class);
193                 
194                 return response;
195         }
196         
197         public CBAMQueryVnfResponse queryVnf(String vnfInstanceId) throws ClientProtocolException, IOException {
198                 String httpPath = String.format(CommonConstants.CbamQueryVnfPath, vnfInstanceId);
199                 RequestMethod method = RequestMethod.GET;
200                 
201                 HttpResult httpResult = operateCbamHttpTask(null, httpPath, method);
202                 String responseStr = httpResult.getContent();
203                 
204                 logger.info("CbamMgmrImpl -> queryVnf, responseStr is " + responseStr);
205                 int code = httpResult.getStatusCode();
206                 if(code == 200) {
207                         logger.info("CbamMgmrImpl -> queryVnf success.");
208                 }else {
209                     logger.error("CbamMgmrImpl -> queryVnf error. " );
210                 }
211                 
212                 CBAMQueryVnfResponse response = gson.fromJson(responseStr, CBAMQueryVnfResponse.class);
213                 
214                 return response;
215         }
216
217         public HttpResult operateCbamHttpTask(Object httpBodyObj, String httpPath, RequestMethod method) throws ClientProtocolException, IOException {
218                 String token = null;
219                 try {
220                         token = retrieveToken();
221                 } catch (JSONException e) {
222                         logger.error("retrieveTokenError ", e);
223                 }
224         
225                 String url= adaptorEnv.getCbamApiUriFront() + httpPath;
226                 
227                 HashMap<String, String> map = new HashMap<>();
228                 map.put(CommonConstants.AUTHORIZATION, "bearer " + token);
229                 map.put(CommonConstants.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
230                 
231                 return httpClientProcessor.process(url, method, map, gson.toJson(httpBodyObj));
232         }
233
234         public CBAMQueryOperExecutionResponse queryOperExecution(String execId) throws ClientProtocolException, IOException{
235                 String httpPath = String.format(CommonConstants.CbamGetOperStatusPath, execId);
236                 RequestMethod method = RequestMethod.GET;
237                 
238                 HttpResult httpResult = operateCbamHttpTask(null, httpPath, method);
239                 String responseStr = httpResult.getContent();
240                 
241                 logger.info("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, responseStr is " + responseStr);
242                 
243                 int code = httpResult.getStatusCode();
244                 if(code == 200) {
245                         logger.info("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, success" );
246                 }else if(code == 202) {
247                         logger.info("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, ongoing" );
248                 }else {
249                         logger.error("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, error" );
250                 }
251                 
252                 
253                 CBAMQueryOperExecutionResponse response = gson.fromJson(responseStr, CBAMQueryOperExecutionResponse.class);
254                 
255                 return response;
256         }
257
258         public void setAdaptorEnv(AdaptorEnv adaptorEnv) {
259                 this.adaptorEnv = adaptorEnv;
260         }
261
262         @Override
263         public void uploadVnfPackage(String cbamPackageFilePath) throws ClientProtocolException, IOException {
264                 String httpPath = CommonConstants.CbamUploadVnfPackagePath;
265                 RequestMethod method = RequestMethod.POST;
266                 
267                 HttpResult httpResult = operateCbamHttpUploadTask(cbamPackageFilePath, httpPath, method);
268                 String responseStr = httpResult.getContent();
269                 
270                 logger.info("CbamMgmrImpl -> uploadVnfPackage, statusCode is " + httpResult.getStatusCode() + ", cause is " + httpResult.getStatusCause() + ". responseStr is " + responseStr);
271                 
272                 int code = httpResult.getStatusCode();
273                 if(code == 200) {
274                         logger.info("CbamMgmrImpl -> uploadVnfPackage, success" );
275                         logger.info("Upload vnf package " + cbamPackageFilePath + " to CBAM is successful.");
276                 }else {
277                         logger.error("CbamMgmrImpl -> uploadVnfPackage, error" );
278                 }
279         }
280
281         public HttpResult operateCbamHttpUploadTask(String filePath, String httpPath, RequestMethod method) throws ClientProtocolException, IOException {
282                 String token = null;
283                 try {
284                         token = retrieveToken();
285                 } catch (JSONException e) {
286                         logger.error("retrieveTokenError ", e);
287                 }
288                 String url = adaptorEnv.getCbamApiUriFront() + httpPath;
289                 String command =  "curl --insecure -X POST -H \"Authorization: bearer " + token + "\" --form content=@" + filePath + " " + url;
290                 StringBuffer respStr = new StringBuffer();
291                 try {
292                         logger.info("start to upload file.");
293                         String os = System.getProperty("os.name"); 
294                         String[] cmd = {"cmd", "/C", command};
295                         if(!os.toLowerCase().startsWith("win")){
296                                 cmd = new String[]{"/bin/sh"," -c ", command};
297                         }  
298                         Process process = Runtime.getRuntime().exec(cmd);
299              InputStream fis=process.getInputStream();    
300              InputStreamReader isr=new InputStreamReader(fis);    
301              BufferedReader br=new BufferedReader(isr);    
302              String line=null;    
303             while((line = br.readLine())!=null)    
304              {    
305                 respStr.append(line);    
306              }    
307                         
308                 } catch (Exception e) {
309                         logger.error("operateCbamHttpUploadTask error", e);
310                 }
311                 
312 //              HashMap<String, String> map = new HashMap<>();
313 //              map.put(CommonConstants.AUTHORIZATION, "bearer " + token);
314 //              map.put(CommonConstants.CONTENT_TYPE, "multipart/form-data, boundary=---CFSGSSGGSGdssdfsdhd---");
315 //              byte[] fileBytes = CommonUtil.getBytes(filePath);
316 //              logger.info("CbamMgmrImpl -> operateCbamHttpUploadTask, url is " + url);
317 //              logger.info("CbamMgmrImpl -> operateCbamHttpUploadTask, token is " + token);
318 //              logger.info("CbamMgmrImpl -> operateCbamHttpUploadTask, bodyPostStr byte lenth is " + fileBytes.length);
319                 
320 //              return httpClientProcessor.processBytes(url, method, map, fileBytes);
321                 
322                 HttpResult hResult = new HttpResult();
323                 hResult.setContent(respStr.toString());
324                 hResult.setStatusCode(200);
325                 return hResult;
326                 
327 //              String charset = "UTF-8";
328 //        File uploadFile1 = new File(filePath);
329 //        String requestURL = url;
330 //        HttpResult result = new HttpResult();
331 // 
332 //        try {
333 //            MultipartUtility multipart = new MultipartUtility(requestURL, charset);
334 //             
335 //            multipart.addHeaderField("User-Agent", "CodeJava");
336 //            multipart.addHeaderField(CommonConstants.AUTHORIZATION, "bearer " + token);
337 //             
338 //            multipart.addFilePart("fileUpload", uploadFile1);
339 // 
340 //            List<String> response = multipart.finish();
341 //             
342 //            result.setContent(Arrays.deepToString(response.toArray(new String[0])));
343 //            result.setStatusCode(200);
344 //        } catch (Exception ex) {
345 //              logger.error("CbamMgmrImpl -> operateCbamHttpUploadTask, error ", ex);
346 //            result.setStatusCode(500);
347 //        }
348 //        
349 //        return result;
350         }
351         
352 //      public static String postByHttps(String url, String body, Object contentType) {
353 //          String result = "";
354 //          Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);
355 //          Protocol.registerProtocol("https", https);
356 //          PostMethod post = new PostMethod(url);
357 //          HttpClient client = new HttpClient();
358 //          try {
359 //              post.setRequestHeader("Content-Type", contentType);
360 //              post.setRequestBody(body);
361 //              client.executeMethod(post);
362 //              result = post.getResponseBodyAsString();
363 //              Protocol.unregisterProtocol("https");
364 //              return result;
365 //          } catch (HttpException e) {
366 //              e.printStackTrace();
367 //          } catch (IOException e) {
368 //              e.printStackTrace();
369 //          } catch(Exception e) {
370 //              e.printStackTrace();
371 //          }
372 //       
373 //          return "error";
374 //      }
375
376         public HttpClientProcessorInf getHttpClientProcessor() {
377                 return httpClientProcessor;
378         }
379
380         public void setHttpClientProcessor(HttpClientProcessorInf httpClientProcessor) {
381                 this.httpClientProcessor = httpClientProcessor;
382         }
383 }