2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
24 import java.io.BufferedWriter;
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;
38 import javax.script.SimpleBindings;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
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.rest.adapter.PolicyExportAdapter;
53 import org.onap.policy.rest.dao.CommonClassDao;
54 import org.onap.policy.rest.jpa.ActionBodyEntity;
55 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
56 import org.onap.policy.rest.jpa.PolicyEditorScopes;
57 import org.onap.policy.rest.jpa.PolicyEntity;
58 import org.onap.policy.rest.jpa.PolicyVersion;
59 import org.onap.policy.rest.jpa.UserInfo;
60 import org.onap.policy.xacml.api.XACMLErrorConstants;
61 import org.openecomp.policy.model.Roles;
62 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
63 import org.openecomp.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;
68 import com.fasterxml.jackson.databind.DeserializationFeature;
69 import com.fasterxml.jackson.databind.JsonNode;
70 import com.fasterxml.jackson.databind.ObjectMapper;
75 public class PolicyExportAndImportController extends RestrictedBaseController {
76 private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
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";
86 private static CommonClassDao commonClassDao;
88 private PolicyEntity policyEntity;
89 private ConfigurationDataEntity configurationDataEntity;
90 private ActionBodyEntity actionBodyEntity;
91 private PolicyVersion policyVersion;
93 private Workbook workbook;
95 private HSSFWorkbook workBook2;
97 private PolicyController policyController;
98 public PolicyController getPolicyController() {
99 return policyController;
102 public void setPolicyController(PolicyController policyController) {
103 this.policyController = policyController;
106 public static CommonClassDao getCommonClassDao() {
107 return commonClassDao;
110 public static void setCommonClassDao(CommonClassDao commonClassDao) {
111 PolicyExportAndImportController.commonClassDao = commonClassDao;
115 private PolicyExportAndImportController(CommonClassDao commonClassDao){
116 PolicyExportAndImportController.commonClassDao = commonClassDao;
119 public PolicyExportAndImportController(){}
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{
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);
137 List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy);
139 workBook2 = new HSSFWorkbook();
140 HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
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");
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());
165 if(policyEntity.getActionBodyEntity() != null){
166 row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
167 row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
170 row.createCell(5).setCellValue("");
171 row.createCell(6).setCellValue("");
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();
182 File temPath = new File(tmp);
183 if(!temPath.exists()){
187 file = temPath + File.separator + "PolicyExport.xls";
188 File filepath = new File(file);
189 FileOutputStream fos = new FileOutputStream(filepath);
190 workBook2.write(fos);
193 response.setCharacterEncoding("UTF-8");
194 response.setContentType("application / json");
195 request.setCharacterEncoding("UTF-8");
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());
203 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e);
208 public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException{
209 boolean configExists = false;
210 boolean actionExists = false;
211 String configName = 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);
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]);
232 scopes.add(userRole.getScope());
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();
241 while (rowIterator.hasNext()) {
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) {
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());
257 if (getCellHeaderName(cell).equalsIgnoreCase("scope")) {
258 policyEntity.setScope(cell.getStringCellValue());
260 if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) {
261 policyEntity.setPolicyData(cell.getStringCellValue());
263 if (getCellHeaderName(cell).equalsIgnoreCase("description")) {
264 policyEntity.setDescription(cell.getStringCellValue());
266 if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) {
267 if(policyEntity.getPolicyName().contains("Config_")){
269 configurationDataEntity.setConfigBody(cell.getStringCellValue());
270 }else if(policyEntity.getPolicyName().contains("Action_")){
272 actionBodyEntity.setActionBody(cell.getStringCellValue());
275 if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) {
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());
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()){
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.
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);
308 //Add Error Message a new Scope Exists, contact super-admin to create a new scope
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");
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);
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");
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());
353 } catch (IOException e) {
354 logger.error("Exception Occured While cloning the configuration file",e);
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());
366 } catch (IOException e) {
367 logger.error("Exception Occured While cloning the configuration file",e);
370 if(configName != null){
371 if(configName.contains("Config_")){
372 ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName);
373 policyEntity.setConfigurationData(configuration);
375 ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName);
376 policyEntity.setActionBodyEntity(actionBody);
379 policyEntity.setCreatedBy(userId);
380 policyEntity.setModifiedBy(userId);
381 policyEntity.setDeleted(false);
382 commonClassDao.save(policyEntity);
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("."));
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);
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;