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.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.List;
37 import javax.script.SimpleBindings;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
41 import org.apache.poi.hssf.usermodel.HSSFRow;
42 import org.apache.poi.hssf.usermodel.HSSFSheet;
43 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
44 import org.apache.poi.ss.usermodel.Cell;
45 import org.apache.poi.ss.usermodel.Row;
46 import org.apache.poi.ss.usermodel.Sheet;
47 import org.apache.poi.ss.usermodel.Workbook;
48 import org.json.JSONObject;
49 import org.onap.policy.common.logging.flexlogger.FlexLogger;
50 import org.onap.policy.common.logging.flexlogger.Logger;
51 import org.onap.policy.rest.adapter.PolicyExportAdapter;
52 import org.onap.policy.rest.dao.CommonClassDao;
53 import org.onap.policy.rest.jpa.ActionBodyEntity;
54 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
55 import org.onap.policy.rest.jpa.PolicyEditorScopes;
56 import org.onap.policy.rest.jpa.PolicyEntity;
57 import org.onap.policy.rest.jpa.PolicyVersion;
58 import org.onap.policy.rest.jpa.UserInfo;
59 import org.onap.policy.utils.UserUtils.Pair;
60 import org.onap.policy.xacml.api.XACMLErrorConstants;
61 import org.onap.portalsdk.core.controller.RestrictedBaseController;
62 import org.onap.portalsdk.core.web.support.UserUtils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.stereotype.Controller;
65 import org.springframework.web.bind.annotation.RequestMapping;
67 import com.fasterxml.jackson.databind.DeserializationFeature;
68 import com.fasterxml.jackson.databind.JsonNode;
69 import com.fasterxml.jackson.databind.ObjectMapper;
74 public class PolicyExportAndImportController extends RestrictedBaseController {
75 private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
77 private ArrayList<String> selectedPolicy;
78 private Set<String> scopes = null;
79 private List<String> roles = null;
80 private static String SUPERADMIN = "super-admin";
81 private static String SUPEREDITOR = "super-editor";
82 private static String ADMIN = "admin";
83 private static String EDITOR = "editor";
85 private static CommonClassDao commonClassDao;
87 private PolicyEntity policyEntity;
88 private ConfigurationDataEntity configurationDataEntity;
89 private ActionBodyEntity actionBodyEntity;
90 private PolicyVersion policyVersion;
92 private Workbook workbook;
94 private HSSFWorkbook workBook2;
96 private PolicyController policyController;
97 public PolicyController getPolicyController() {
98 return policyController;
101 public void setPolicyController(PolicyController policyController) {
102 this.policyController = policyController;
105 public static CommonClassDao getCommonClassDao() {
106 return commonClassDao;
109 public static void setCommonClassDao(CommonClassDao commonClassDao) {
110 PolicyExportAndImportController.commonClassDao = commonClassDao;
114 private PolicyExportAndImportController(CommonClassDao commonClassDao){
115 PolicyExportAndImportController.commonClassDao = commonClassDao;
118 public PolicyExportAndImportController(){
122 @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
123 public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
126 selectedPolicy = new ArrayList<>();
127 ObjectMapper mapper = new ObjectMapper();
128 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
129 JsonNode root = mapper.readTree(request.getReader());
130 PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
131 for (Object policyId : adapter.getPolicyDatas()) {
132 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
133 String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
134 String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, ".");
135 String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1);
136 selectedPolicy.add(policyName+":"+scope);
138 List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy);
140 workBook2 = new HSSFWorkbook();
141 HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
143 HSSFRow headingRow = sheet.createRow(0);
144 headingRow.createCell(0).setCellValue("policyName");
145 headingRow.createCell(1).setCellValue("scope");
146 headingRow.createCell(2).setCellValue("version");
147 headingRow.createCell(3).setCellValue("policyData");
148 headingRow.createCell(4).setCellValue("description");
149 headingRow.createCell(5).setCellValue("configurationbody");
150 headingRow.createCell(6).setCellValue("configurationName");
153 for (Object object : entityData) {
154 PolicyEntity policyEntity = (PolicyEntity) object;
155 HSSFRow row = sheet.createRow(rowNo);
156 row.createCell(0).setCellValue(policyEntity.getPolicyName());
157 row.createCell(1).setCellValue(policyEntity.getScope());
158 row.createCell(2).setCellValue(policyEntity.getVersion());
159 row.createCell(3).setCellValue(policyEntity.getPolicyData());
160 row.createCell(4).setCellValue(policyEntity.getDescription());
161 if(!policyEntity.getPolicyName().contains("Decision_")){
162 if(policyEntity.getConfigurationData() != null){
163 row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody());
164 row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
166 if(policyEntity.getActionBodyEntity() != null){
167 row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
168 row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
171 row.createCell(5).setCellValue("");
172 row.createCell(6).setCellValue("");
177 String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
178 String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
179 File deleteCheck = new File(deleteCheckPath);
180 if(deleteCheck.exists()){
181 deleteCheck.delete();
183 File temPath = new File(tmp);
184 if(!temPath.exists()){
188 file = temPath + File.separator + "PolicyExport.xls";
189 File filepath = new File(file);
190 FileOutputStream fos = new FileOutputStream(filepath);
191 workBook2.write(fos);
194 response.setCharacterEncoding("UTF-8");
195 response.setContentType("application / json");
196 request.setCharacterEncoding("UTF-8");
198 PrintWriter out = response.getWriter();
199 String successMap = file.substring(file.lastIndexOf("webapps")+8);
200 String responseString = mapper.writeValueAsString(successMap);
201 JSONObject j = new JSONObject("{data: " + responseString + "}");
202 out.write(j.toString());
204 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e);
209 public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException{
210 boolean configExists = false;
211 boolean actionExists = false;
212 String configName = null;
215 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
216 String userId = UserUtils.getUserSession(request).getOrgUserId();
217 UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
219 List<Object> userRoles = controller.getRoles(userId);
220 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
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();
229 while (rowIterator.hasNext()) {
231 policyEntity = new PolicyEntity();
232 configurationDataEntity = new ConfigurationDataEntity();
233 actionBodyEntity = new ActionBodyEntity();
234 policyVersion = new PolicyVersion();
235 Row currentRow = rowIterator.next();
236 if (currentRow.getRowNum() == 0) {
239 Iterator<Cell> cellIterator = currentRow.cellIterator();
240 while (cellIterator.hasNext()) {
241 Cell cell = cellIterator.next();
242 if ("policyName".equalsIgnoreCase(getCellHeaderName(cell))) {
243 policyEntity.setPolicyName(cell.getStringCellValue());
245 if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
246 policyEntity.setScope(cell.getStringCellValue());
248 if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
249 policyEntity.setPolicyData(cell.getStringCellValue());
251 if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
252 policyEntity.setDescription(cell.getStringCellValue());
254 if ("configurationbody".equalsIgnoreCase(getCellHeaderName(cell))) {
255 if(policyEntity.getPolicyName().contains("Config_")){
257 configurationDataEntity.setConfigBody(cell.getStringCellValue());
258 }else if(policyEntity.getPolicyName().contains("Action_")){
260 actionBodyEntity.setActionBody(cell.getStringCellValue());
263 if ("configurationName".equalsIgnoreCase(getCellHeaderName(cell))) {
265 configName = cell.getStringCellValue();
266 if(policyEntity.getPolicyName().contains("Config_")){
267 configurationDataEntity.setConfigurationName(cell.getStringCellValue());
268 }else if(policyEntity.getPolicyName().contains("Action_")){
269 actionBodyEntity.setActionBodyName(cell.getStringCellValue());
274 scope = policyEntity.getScope().replace(".", File.separator);
275 String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
276 SimpleBindings params = new SimpleBindings();
277 params.put("policyName", policyEntity.getPolicyName());
278 params.put("policyScope", policyEntity.getScope());
279 List<Object> queryData = controller.getDataByQuery(query, params);
280 if(!queryData.isEmpty()){
283 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) {
284 //1. if Role contains super admin create scope.
285 //2. if Role contains super editor don't create new scope and add to list to show to user.
287 PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
288 if(policyEditorScope == null){
289 if(roles.contains(SUPERADMIN)){
290 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
291 policyEditorScopeEntity.setScopeName(scope);
292 policyEditorScopeEntity.setUserCreatedBy(userInfo);
293 policyEditorScopeEntity.setUserModifiedBy(userInfo);
294 commonClassDao.save(policyEditorScopeEntity);
296 //Add Error Message a new Scope Exists, contact super-admin to create a new scope
301 if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
302 if(scopes.isEmpty()){
303 logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
305 //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list.
306 if(roles.contains(ADMIN)){
307 String scopeCheck = scope.substring(0, scope.lastIndexOf('.'));
308 if(scopes.contains(scopeCheck)){
309 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
310 policyEditorScopeEntity.setScopeName(scope);
311 policyEditorScopeEntity.setUserCreatedBy(userInfo);
312 policyEditorScopeEntity.setUserModifiedBy(userInfo);
313 commonClassDao.save(policyEditorScopeEntity);
324 if(configName.endsWith("json")){
325 configurationDataEntity.setConfigType("JSON");
326 }else if(configName.endsWith("txt")){
327 configurationDataEntity.setConfigType("OTHER");
328 }else if(configName.endsWith("xml")){
329 configurationDataEntity.setConfigType("XML");
330 }else if(configName.endsWith("properties")){
331 configurationDataEntity.setConfigType("PROPERTIES");
333 configurationDataEntity.setDeleted(false);
334 configurationDataEntity.setCreatedBy(userId);
335 configurationDataEntity.setModifiedBy(userId);
336 commonClassDao.save(configurationDataEntity);
337 try(FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + configName)){
338 BufferedWriter bw = new BufferedWriter(fw);
339 bw.write(configurationDataEntity.getConfigBody());
341 } catch (IOException e) {
342 logger.error("Exception Occured While cloning the configuration file",e);
346 actionBodyEntity.setDeleted(false);
347 actionBodyEntity.setCreatedBy(userId);
348 actionBodyEntity.setModifiedBy(userId);
349 commonClassDao.save(actionBodyEntity);
350 try(FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
351 BufferedWriter bw = new BufferedWriter(fw);
352 bw.write(actionBodyEntity.getActionBody());
354 } catch (IOException e) {
355 logger.error("Exception Occured While cloning the configuration file",e);
358 if(configName != null){
359 if(configName.contains("Config_")){
360 ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName);
361 policyEntity.setConfigurationData(configuration);
363 ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName);
364 policyEntity.setActionBodyEntity(actionBody);
367 policyEntity.setCreatedBy(userId);
368 policyEntity.setModifiedBy(userId);
369 policyEntity.setDeleted(false);
370 commonClassDao.save(policyEntity);
372 policyVersion = new PolicyVersion();
373 String policyName = policyEntity.getPolicyName().replace(".xml", "");
374 int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf('.')+1));
375 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
377 policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName);
378 policyVersion.setActiveVersion(version);
379 policyVersion.setHigherVersion(version);
380 policyVersion.setCreatedBy(userId);
381 policyVersion.setModifiedBy(userId);
382 commonClassDao.save(policyVersion);
389 //return the column header name value
390 private String getCellHeaderName(Cell cell){
391 return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();