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