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