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