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