Adding code coverage reduce duplicate lines
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyExportAndImportController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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.onap.policy.controller;
22
23
24 import java.io.BufferedWriter;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.FileWriter;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.util.ArrayList;
32 import java.util.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.List;
35 import java.util.Set;
36
37 import javax.script.SimpleBindings;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40
41 import org.apache.poi.hssf.usermodel.HSSFRow;
42 import org.apache.poi.hssf.usermodel.HSSFSheet;
43 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
44 import org.apache.poi.ss.usermodel.Cell;
45 import org.apache.poi.ss.usermodel.Row;
46 import org.apache.poi.ss.usermodel.Sheet;
47 import org.apache.poi.ss.usermodel.Workbook;
48 import org.json.JSONObject;
49 import org.onap.policy.common.logging.flexlogger.FlexLogger;
50 import org.onap.policy.common.logging.flexlogger.Logger;
51 import org.onap.policy.rest.adapter.PolicyExportAdapter;
52 import org.onap.policy.rest.dao.CommonClassDao;
53 import org.onap.policy.rest.jpa.ActionBodyEntity;
54 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
55 import org.onap.policy.rest.jpa.PolicyEditorScopes;
56 import org.onap.policy.rest.jpa.PolicyEntity;
57 import org.onap.policy.rest.jpa.PolicyVersion;
58 import org.onap.policy.rest.jpa.UserInfo;
59 import org.onap.policy.utils.UserUtils.Pair;
60 import org.onap.policy.xacml.api.XACMLErrorConstants;
61 import org.onap.portalsdk.core.controller.RestrictedBaseController;
62 import org.onap.portalsdk.core.web.support.UserUtils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.stereotype.Controller;
65 import org.springframework.web.bind.annotation.RequestMapping;
66
67 import com.fasterxml.jackson.databind.DeserializationFeature;
68 import com.fasterxml.jackson.databind.JsonNode;
69 import com.fasterxml.jackson.databind.ObjectMapper;
70
71
72 @Controller
73 @RequestMapping("/")
74 public class PolicyExportAndImportController extends RestrictedBaseController {
75         private static Logger   logger  = FlexLogger.getLogger(PolicyExportAndImportController.class);
76
77         private ArrayList<String> selectedPolicy;
78         private Set<String> scopes = null;
79         private List<String> roles = null;
80         private static String SUPERADMIN = "super-admin";
81         private static String SUPEREDITOR = "super-editor";
82         private static String ADMIN = "admin";
83         private static String EDITOR = "editor";
84
85         private static CommonClassDao commonClassDao;
86         
87         private PolicyEntity policyEntity;
88         private ConfigurationDataEntity configurationDataEntity;
89         private ActionBodyEntity actionBodyEntity;
90         private PolicyVersion policyVersion;
91
92         private Workbook workbook;
93
94         private HSSFWorkbook workBook2;
95         
96         private PolicyController policyController;
97         public PolicyController getPolicyController() {
98                 return policyController;
99         }
100
101         public void setPolicyController(PolicyController policyController) {
102                 this.policyController = policyController;
103         }
104
105         public static CommonClassDao getCommonClassDao() {
106                 return commonClassDao;
107         }
108
109         public static void setCommonClassDao(CommonClassDao commonClassDao) {
110                 PolicyExportAndImportController.commonClassDao = commonClassDao;
111         }
112
113         @Autowired
114         private PolicyExportAndImportController(CommonClassDao commonClassDao){
115                 PolicyExportAndImportController.commonClassDao = commonClassDao;
116         }
117
118         public PolicyExportAndImportController(){
119                 // Empty constructor
120         }
121
122         @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
123         public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
124                 try{
125                         String file;
126                         selectedPolicy = new ArrayList<>();
127                         ObjectMapper mapper = new ObjectMapper();
128                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
129                         JsonNode root = mapper.readTree(request.getReader());
130                         PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
131                         for (Object policyId :  adapter.getPolicyDatas()) {
132                                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
133                                 String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
134                                 String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, ".");
135                                 String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1);
136                                 selectedPolicy.add(policyName+":"+scope);
137                         }
138                         List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy);
139
140                         workBook2 = new HSSFWorkbook();
141                         HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
142
143                         HSSFRow headingRow = sheet.createRow(0);
144                         headingRow.createCell(0).setCellValue("policyName");
145                         headingRow.createCell(1).setCellValue("scope");
146                         headingRow.createCell(2).setCellValue("version");
147                         headingRow.createCell(3).setCellValue("policyData");
148                         headingRow.createCell(4).setCellValue("description");
149                         headingRow.createCell(5).setCellValue("configurationbody");
150                         headingRow.createCell(6).setCellValue("configurationName");
151
152                         short rowNo = 1;
153                         for (Object object : entityData) {
154                                 PolicyEntity policyEntity = (PolicyEntity) object;
155                                 HSSFRow row = sheet.createRow(rowNo);
156                                 row.createCell(0).setCellValue(policyEntity.getPolicyName());
157                                 row.createCell(1).setCellValue(policyEntity.getScope());
158                                 row.createCell(2).setCellValue(policyEntity.getVersion());
159                                 row.createCell(3).setCellValue(policyEntity.getPolicyData());
160                                 row.createCell(4).setCellValue(policyEntity.getDescription());
161                                 if(!policyEntity.getPolicyName().contains("Decision_")){
162                                         if(policyEntity.getConfigurationData() != null){
163                                                 row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody());
164                                                 row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
165                                         }
166                                         if(policyEntity.getActionBodyEntity() != null){
167                                                 row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
168                                                 row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
169                                         }
170                                 }else{
171                                         row.createCell(5).setCellValue("");
172                                         row.createCell(6).setCellValue("");
173                                 }
174                                 rowNo++;
175                         }
176
177                         String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
178                         String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
179                         File deleteCheck = new File(deleteCheckPath);
180                         if(deleteCheck.exists()){
181                                 deleteCheck.delete();
182                         }
183                         File temPath = new File(tmp);
184                         if(!temPath.exists()){
185                                 temPath.mkdir();
186                         }
187
188                         file =  temPath + File.separator + "PolicyExport.xls";
189                         File filepath = new File(file);
190                         FileOutputStream fos = new FileOutputStream(filepath);
191                         workBook2.write(fos);
192                         fos.flush();
193
194                         response.setCharacterEncoding("UTF-8");
195                         response.setContentType("application / json");
196                         request.setCharacterEncoding("UTF-8");
197
198                         PrintWriter out = response.getWriter();
199                         String successMap = file.substring(file.lastIndexOf("webapps")+8);
200                         String responseString = mapper.writeValueAsString(successMap);
201                         JSONObject j = new JSONObject("{data: " + responseString + "}");
202                         out.write(j.toString());
203                 }catch(Exception e){
204                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e);
205                 }
206         }
207
208         //Policy Import 
209         public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException{
210                 boolean configExists = false;
211                 boolean actionExists = false;
212                 String configName = null;
213                 String scope;
214                 boolean finalColumn;
215                 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
216                 String userId = UserUtils.getUserSession(request).getOrgUserId();
217                 UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
218
219                 List<Object> userRoles = controller.getRoles(userId);
220                 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
221                 roles = pair.u;
222                 scopes = pair.t;
223                 
224                 FileInputStream excelFile = new FileInputStream(new File(file));
225                 workbook = new HSSFWorkbook(excelFile);
226                 Sheet datatypeSheet = workbook.getSheetAt(0);
227                 Iterator<Row> rowIterator = datatypeSheet.iterator();
228
229                 while (rowIterator.hasNext()) {
230                         finalColumn = false;
231                         policyEntity = new PolicyEntity();
232                         configurationDataEntity = new ConfigurationDataEntity();
233                         actionBodyEntity = new ActionBodyEntity();
234                         policyVersion = new PolicyVersion();
235                         Row currentRow = rowIterator.next();
236                         if (currentRow.getRowNum() == 0) {
237                                 continue;
238                         }
239                         Iterator<Cell> cellIterator = currentRow.cellIterator();
240                         while (cellIterator.hasNext()) {
241                                 Cell cell = cellIterator.next();
242                                 if ("policyName".equalsIgnoreCase(getCellHeaderName(cell))) {
243                                         policyEntity.setPolicyName(cell.getStringCellValue());
244                                 }
245                                 if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
246                                         policyEntity.setScope(cell.getStringCellValue());
247                                 }
248                                 if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
249                                         policyEntity.setPolicyData(cell.getStringCellValue());
250                                 }
251                                 if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
252                                         policyEntity.setDescription(cell.getStringCellValue());
253                                 }
254                                 if ("configurationbody".equalsIgnoreCase(getCellHeaderName(cell))) {
255                                         if(policyEntity.getPolicyName().contains("Config_")){
256                                                 configExists = true;
257                                                 configurationDataEntity.setConfigBody(cell.getStringCellValue());
258                                         }else if(policyEntity.getPolicyName().contains("Action_")){
259                                                 actionExists = true;
260                                                 actionBodyEntity.setActionBody(cell.getStringCellValue());
261                                         }       
262                                 }
263                                 if ("configurationName".equalsIgnoreCase(getCellHeaderName(cell))) {
264                                         finalColumn = true;
265                                         configName = cell.getStringCellValue();
266                                         if(policyEntity.getPolicyName().contains("Config_")){
267                                                 configurationDataEntity.setConfigurationName(cell.getStringCellValue());
268                                         }else if(policyEntity.getPolicyName().contains("Action_")){
269                                                 actionBodyEntity.setActionBodyName(cell.getStringCellValue());
270                                         }       
271                                 }
272
273                                 if(finalColumn){
274                                         scope = policyEntity.getScope().replace(".", File.separator);
275                                         String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
276                                         SimpleBindings params = new SimpleBindings();
277                                         params.put("policyName", policyEntity.getPolicyName());
278                                         params.put("policyScope", policyEntity.getScope());
279                                         List<Object> queryData = controller.getDataByQuery(query, params);
280                                         if(!queryData.isEmpty()){
281                                                 continue;
282                                         }
283                                         if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) {
284                                                 //1. if Role contains super admin create scope.
285                                                 //2. if Role contains super editor don't create new scope and add to list to show to user.
286                                                 
287                                                 PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
288                                                 if(policyEditorScope == null){
289                                                         if(roles.contains(SUPERADMIN)){
290                                                                 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
291                                                                 policyEditorScopeEntity.setScopeName(scope);
292                                                                 policyEditorScopeEntity.setUserCreatedBy(userInfo);
293                                                                 policyEditorScopeEntity.setUserModifiedBy(userInfo);
294                                                                 commonClassDao.save(policyEditorScopeEntity);
295                                                         }else{
296                                                                 //Add Error Message a new Scope Exists, contact super-admin to create a new scope
297                                                                 continue;
298                                                         }
299                                                 }
300                                         }
301                                         if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
302                                                 if(scopes.isEmpty()){
303                                                         logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
304                                                 }else{
305                                                         //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list.
306                                                         if(roles.contains(ADMIN)){
307                                                                 String scopeCheck = scope.substring(0, scope.lastIndexOf('.'));
308                                                                 if(scopes.contains(scopeCheck)){
309                                                                         PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
310                                                                         policyEditorScopeEntity.setScopeName(scope);
311                                                                         policyEditorScopeEntity.setUserCreatedBy(userInfo);
312                                                                         policyEditorScopeEntity.setUserModifiedBy(userInfo);
313                                                                         commonClassDao.save(policyEditorScopeEntity);
314                                                                 }else{
315                                                                         continue;
316                                                                 }
317                                                         }else{
318                                                                 continue;
319                                                         }
320                                                 }
321                                         }       
322
323                                         if(configExists){
324                                                 if(configName.endsWith("json")){
325                                                         configurationDataEntity.setConfigType("JSON");
326                                                 }else if(configName.endsWith("txt")){
327                                                         configurationDataEntity.setConfigType("OTHER");
328                                                 }else if(configName.endsWith("xml")){
329                                                         configurationDataEntity.setConfigType("XML");
330                                                 }else if(configName.endsWith("properties")){
331                                                         configurationDataEntity.setConfigType("PROPERTIES");
332                                                 }
333                                                 configurationDataEntity.setDeleted(false);
334                                                 configurationDataEntity.setCreatedBy(userId);
335                                                 configurationDataEntity.setModifiedBy(userId);
336                                                 commonClassDao.save(configurationDataEntity);
337                                                 try(FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + configName)){
338                                                         BufferedWriter bw = new BufferedWriter(fw);
339                                                         bw.write(configurationDataEntity.getConfigBody());
340                                                         bw.close();
341                                                 } catch (IOException e) {
342                                                         logger.error("Exception Occured While cloning the configuration file",e);
343                                                 }
344                                         }
345                                         if(actionExists){
346                                                 actionBodyEntity.setDeleted(false);
347                                                 actionBodyEntity.setCreatedBy(userId);
348                                                 actionBodyEntity.setModifiedBy(userId);
349                                                 commonClassDao.save(actionBodyEntity);
350                                                 try(FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
351                                                         BufferedWriter bw = new BufferedWriter(fw);
352                                                         bw.write(actionBodyEntity.getActionBody());
353                                                         bw.close();
354                                                 } catch (IOException e) {
355                                                         logger.error("Exception Occured While cloning the configuration file",e);
356                                                 }
357                                         }
358                                         if(configName != null){
359                                                 if(configName.contains("Config_")){
360                                                         ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName);
361                                                         policyEntity.setConfigurationData(configuration);
362                                                 }else{
363                                                         ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName);
364                                                         policyEntity.setActionBodyEntity(actionBody);
365                                                 }
366                                         }
367                                         policyEntity.setCreatedBy(userId);
368                                         policyEntity.setModifiedBy(userId);
369                                         policyEntity.setDeleted(false);
370                                         commonClassDao.save(policyEntity);
371                                         
372                                         policyVersion = new PolicyVersion();
373                                         String policyName = policyEntity.getPolicyName().replace(".xml", "");
374                                         int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf('.')+1));
375                                         policyName = policyName.substring(0, policyName.lastIndexOf('.'));
376                                         
377                                         policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName);
378                                         policyVersion.setActiveVersion(version);
379                                         policyVersion.setHigherVersion(version);
380                                         policyVersion.setCreatedBy(userId);
381                                         policyVersion.setModifiedBy(userId);
382                                         commonClassDao.save(policyVersion);
383                                 }
384                         }
385                 }
386                 return null;
387         }
388
389         //return the column header name value
390         private String getCellHeaderName(Cell cell){
391                 return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
392         }
393 }