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