Epic-231:versioning, and backup the configuration
[sdnc/oam.git] / configbackuprestore / vnfconfigbackupservice / src / main / java / com / onap / sdnc / vnfbackupservice / service / VnfbackupServiceImpl.java
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : SDNC-FEATURES
4 * ================================================================================
5 * Copyright 2018 TechMahindra
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 com.onap.sdnc.vnfbackupservice.service;
21
22 import java.io.IOException;
23 import java.sql.Timestamp;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27
28 import org.apache.log4j.Logger;
29 import org.json.JSONArray;
30 import org.json.JSONException;
31 import org.json.JSONObject;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.beans.factory.annotation.Value;
34 import org.springframework.http.HttpEntity;
35 import org.springframework.http.HttpHeaders;
36 import org.springframework.http.HttpMethod;
37 import org.springframework.http.ResponseEntity;
38 import org.springframework.stereotype.Service;
39 import org.springframework.web.client.RestTemplate;
40
41 import com.fasterxml.jackson.core.JsonParseException;
42 import com.fasterxml.jackson.databind.JsonMappingException;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.onap.sdnc.vnfbackupservice.dao.VnfBackupServiceRepo;
45 import com.onap.sdnc.vnfbackupservice.model.VnfConfigDetailsDB;
46 import com.onap.sdnc.vnfbackupservice.model.VnfDisplayParams;
47 import com.onap.sdnc.vnfbackupservice.model.VnfServiceResponse;
48
49 import com.onap.sdnc.vnfbackupservice.scheduler.VnfConfigBackupScheduler;
50 import com.onap.sdnc.vnfbackupservice.scheduler.VnfRestClient;
51
52 @Service
53 public class VnfbackupServiceImpl implements VnfbackupService {
54
55         @Autowired
56         private RestTemplate restTemplate;
57
58         @Autowired
59         VnfBackupServiceRepo vnfBackupServiceDao;
60
61         @Autowired
62         VnfConfigBackupScheduler vnfConfigBackupScheduler;
63
64         @Value("${sdnc.rest.vnf.api.host}")
65         private String host;
66
67         @Value("${sdnc.rest.vnf.api.port}")
68         private String port;
69
70         @Value("${sdnc.rest.vnf.api.basepath}")
71         private String basePath;
72
73         @Value("${sdnc.rest.vnf.api.username}")
74         private String username;
75
76         @Value("${sdnc.rest.vnf.api.password}")
77         private String password;
78
79         @Autowired
80         VnfRestClient vnfRestClientlocal;
81
82         private static final Logger logger = Logger.getLogger(VnfbackupServiceImpl.class);
83
84         @Override
85         public VnfServiceResponse getAllVnfDetails() {
86                 VnfServiceResponse vnfServiceResponse = new VnfServiceResponse();
87                 String finalURL = "http://" + host + ":" + port + basePath + "/config/VNF-API:vnfs";
88                 String response = vnfRestClientlocal.vnfRestClient(finalURL, username, password);
89                 List<VnfDisplayParams> displayParams = parseVnfConfigDetails(response);
90                 vnfServiceResponse.setVnfDisplayList(displayParams);
91                 return vnfServiceResponse;
92         }
93
94         public List<VnfDisplayParams> parseVnfConfigDetails(String jsonInput) {
95                 List<VnfDisplayParams> displayParams = new ArrayList<VnfDisplayParams>();
96
97                 try {
98                         JSONObject vnf = new JSONObject(jsonInput);
99                         JSONArray vnfList = vnf.getJSONObject("vnfs").getJSONArray("vnf-list");
100
101                         for (int i = 0; i < vnfList.length(); i++) {
102                                 VnfDisplayParams vnfDisplayParams = new VnfDisplayParams();
103                                 String responseStatus = vnfList.getJSONObject(i).getJSONObject("service-status").get("response-code")
104                                                 .toString();
105                                 if ("200".equalsIgnoreCase(responseStatus)) {
106                                         String vnfId = vnfList.getJSONObject(i).get("vnf-id").toString();
107                                         String vnfName = vnfList.getJSONObject(i).getJSONObject("service-data")
108                                                         .getJSONObject("vnf-request-information").get("vnf-name").toString();
109                                         vnfDisplayParams.setVnfId(vnfId);
110                                         vnfDisplayParams.setVnfName(vnfName);
111                                         displayParams.add(vnfDisplayParams);
112                                 }
113                         }
114                 } catch (JSONException e) {
115                         logger.error("Exception is at parseVnfConfigDetails() :  " + e);
116                 }
117                 return displayParams;
118         }
119
120         @Override
121         public String backupVnfconfig(String vnfId) {
122                 long millis = System.currentTimeMillis();
123                 Timestamp date = new java.sql.Timestamp(millis);
124                 String finalURL = "http://" + host + ":" + port + basePath + "/config/VNF-API:vnfs/vnf-list/" + vnfId;
125                 logger.debug("connecting to restconf device:::" + finalURL);
126                 String response = vnfRestClientlocal.vnfRestClient(finalURL, username, password);
127                 String configInfo = response;
128                 Timestamp creationDate = date;
129                 Timestamp lastupdated = date;
130                 int status = 1;
131                 String vnfid = vnfId;
132                 String vnfname = "";
133                 VnfConfigDetailsDB getVnfDetails = null;
134                 String vnfversion = "Version-1";
135                 try {
136                         getVnfDetails = vnfBackupServiceDao.getVnfDetail(vnfId);
137                 } catch (Exception e) {
138                         logger.error("exception is at getVnfdetails() :  " + e);
139                 }
140                 if (getVnfDetails == null) {
141                         JSONObject vnf;
142                         try {
143                                 vnf = new JSONObject(response);
144                                 vnfname = vnf.getJSONArray("vnf-list").getJSONObject(0).getJSONObject("service-data")
145                                                 .getJSONObject("vnf-request-information").get("vnf-name").toString();
146
147                         } catch (JSONException e) {
148                                 logger.error("exception is at getVnfdetails() :  " + e);
149                         }
150                         vnfBackupServiceDao.saveVnfDetails(configInfo, creationDate, lastupdated, status, vnfid, vnfname,
151                                         vnfversion);
152                 } else {
153                         try {
154                                 String[] vnfvesionsplit = getVnfDetails.getVnfversion().split("-");
155                                 int tmpVnfversion = Integer.parseInt(vnfvesionsplit[1]) + 1;
156                                 vnfversion = vnfvesionsplit[0] + "-" + String.valueOf(tmpVnfversion);
157
158                                 ObjectMapper om = new ObjectMapper();
159                                 try {
160                                         Map<String, Object> m1 = (Map<String, Object>) (om.readValue(getVnfDetails.getConfiginfo(),
161                                                         Map.class));
162                                         Map<String, Object> m2 = (Map<String, Object>) (om.readValue(response, Map.class));
163
164                                         JSONObject vnf;
165                                         vnf = new JSONObject(response);
166                                         vnfname = vnf.getJSONArray("vnf-list").getJSONObject(0).getJSONObject("service-data")
167                                                         .getJSONObject("vnf-request-information").get("vnf-name").toString();
168
169                                         if (!m1.equals(m2)) {
170                                                 vnfBackupServiceDao.saveVnfDetails(configInfo, creationDate, lastupdated, status, vnfid,
171                                                                 vnfname, vnfversion);
172                                         }
173                                 } catch (Exception e) {
174                                         logger.error("exception is at getVnfdetails() :  " + e);
175                                 }
176                         } catch (Exception e) {
177                                 logger.error("exception is at getVnfdetails() :  " + e);
178                         }
179                 }
180                 return "success";
181         }
182
183         @Override
184         public String putVnfconfig(String configfile, String vnfId) {
185
186                 String indented = null;
187
188                 if (configfile != null) {
189                         restTemplate = new RestTemplate();
190                         String finalURL = "http://" + host + ":" + port + basePath + "/config/VNF-API:vnfs/vnf-list/" + vnfId;
191
192                         HttpHeaders headers = new HttpHeaders();
193
194                         logger.info("connecting to restconf device:::" + finalURL);
195                         String response = vnfRestClientlocal.vnfRestClient(finalURL, username, password);
196                         logger.info(response);
197                         ObjectMapper mapper = new ObjectMapper();
198                         try {
199                                 Object json = mapper.readValue(response, Object.class);
200                                 indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
201                                 logger.info(indented);
202                         } catch (JsonParseException e) {
203                                 logger.error("exception occer" + e);
204                         } catch (JsonMappingException e) {
205                                 logger.error("exception occer" + e);
206                         } catch (IOException e) {
207                                 logger.error("exception occer" + e);
208                         }
209
210                         if (!(configfile.equals(indented))) {
211                                 HttpEntity<String> requestEntity = new HttpEntity<String>(configfile,
212                                                 vnfRestClientlocal.generateHeaders(headers, username, password));
213
214                                 ResponseEntity<String> uri = restTemplate.exchange(finalURL, HttpMethod.PUT, requestEntity,
215                                                 String.class);
216                                 logger.info(uri.getStatusCode());
217                                 if (uri.getStatusCodeValue() == 200) {
218                                         vnfConfigBackupScheduler.initiateBackupService();
219                                 }
220                                 return "ok";
221                         } else {
222                                 throw new RuntimeException("Both configurations are same");
223                         }
224                 }
225                 return "ok";
226         }
227
228         @Override
229         public String updatedBackuptime() {
230                 String sdtime = vnfBackupServiceDao.getvnfschedulertime();
231                 return sdtime;
232         }
233
234 }