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