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.model.Roles;
53 import org.onap.policy.rest.adapter.PolicyExportAdapter;
54 import org.onap.policy.rest.dao.CommonClassDao;
55 import org.onap.policy.rest.jpa.ActionBodyEntity;
56 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
57 import org.onap.policy.rest.jpa.PolicyEditorScopes;
58 import org.onap.policy.rest.jpa.PolicyEntity;
59 import org.onap.policy.rest.jpa.PolicyVersion;
60 import org.onap.policy.rest.jpa.UserInfo;
61 import org.onap.policy.xacml.api.XACMLErrorConstants;
62 import org.onap.portalsdk.core.controller.RestrictedBaseController;
63 import org.onap.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(){
123 @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
124 public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
127 selectedPolicy = new ArrayList<>();
128 ObjectMapper mapper = new ObjectMapper();
129 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
130 JsonNode root = mapper.readTree(request.getReader());
131 PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
132 for (Object policyId : adapter.getPolicyDatas()) {
133 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
134 String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
135 String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, ".");
136 String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1);
137 selectedPolicy.add(policyName+":"+scope);
139 List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy);
141 workBook2 = new HSSFWorkbook();
142 HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
144 HSSFRow headingRow = sheet.createRow(0);
145 headingRow.createCell(0).setCellValue("policyName");
146 headingRow.createCell(1).setCellValue("scope");
147 headingRow.createCell(2).setCellValue("version");
148 headingRow.createCell(3).setCellValue("policyData");
149 headingRow.createCell(4).setCellValue("description");
150 headingRow.createCell(5).setCellValue("configurationbody");
151 headingRow.createCell(6).setCellValue("configurationName");
154 for (Object object : entityData) {
155 PolicyEntity policyEntity = (PolicyEntity) object;
156 HSSFRow row = sheet.createRow(rowNo);
157 row.createCell(0).setCellValue(policyEntity.getPolicyName());
158 row.createCell(1).setCellValue(policyEntity.getScope());
159 row.createCell(2).setCellValue(policyEntity.getVersion());
160 row.createCell(3).setCellValue(policyEntity.getPolicyData());
161 row.createCell(4).setCellValue(policyEntity.getDescription());
162 if(!policyEntity.getPolicyName().contains("Decision_")){
163 if(policyEntity.getConfigurationData() != null){
164 row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody());
165 row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
167 if(policyEntity.getActionBodyEntity() != null){
168 row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
169 row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
172 row.createCell(5).setCellValue("");
173 row.createCell(6).setCellValue("");
178 String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
179 String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
180 File deleteCheck = new File(deleteCheckPath);
181 if(deleteCheck.exists()){
182 deleteCheck.delete();
184 File temPath = new File(tmp);
185 if(!temPath.exists()){
189 file = temPath + File.separator + "PolicyExport.xls";
190 File filepath = new File(file);
191 FileOutputStream fos = new FileOutputStream(filepath);
192 workBook2.write(fos);
195 response.setCharacterEncoding("UTF-8");
196 response.setContentType("application / json");
197 request.setCharacterEncoding("UTF-8");
199 PrintWriter out = response.getWriter();
200 String successMap = file.substring(file.lastIndexOf("webapps")+8);
201 String responseString = mapper.writeValueAsString(successMap);
202 JSONObject j = new JSONObject("{data: " + responseString + "}");
203 out.write(j.toString());
205 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e);
210 public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException{
211 boolean configExists = false;
212 boolean actionExists = false;
213 String configName = null;
216 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
217 String userId = UserUtils.getUserSession(request).getOrgUserId();
218 UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
220 //Check if the Role and Scope Size are Null get the values from db.
221 List<Object> userRoles = controller.getRoles(userId);
222 roles = new ArrayList<>();
223 scopes = new HashSet<>();
224 for(Object role: userRoles){
225 Roles userRole = (Roles) role;
226 roles.add(userRole.getRole());
227 if(userRole.getScope() != null){
228 if(userRole.getScope().contains(",")){
229 String[] multipleScopes = userRole.getScope().split(",");
230 for(int i =0; i < multipleScopes.length; i++){
231 scopes.add(multipleScopes[i]);
234 scopes.add(userRole.getScope());
238 FileInputStream excelFile = new FileInputStream(new File(file));
239 workbook = new HSSFWorkbook(excelFile);
240 Sheet datatypeSheet = workbook.getSheetAt(0);
241 Iterator<Row> rowIterator = datatypeSheet.iterator();
243 while (rowIterator.hasNext()) {
245 policyEntity = new PolicyEntity();
246 configurationDataEntity = new ConfigurationDataEntity();
247 actionBodyEntity = new ActionBodyEntity();
248 policyVersion = new PolicyVersion();
249 Row currentRow = rowIterator.next();
250 if (currentRow.getRowNum() == 0) {
253 Iterator<Cell> cellIterator = currentRow.cellIterator();
254 while (cellIterator.hasNext()) {
255 Cell cell = cellIterator.next();
256 if ("policyName".equalsIgnoreCase(getCellHeaderName(cell))) {
257 policyEntity.setPolicyName(cell.getStringCellValue());
259 if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
260 policyEntity.setScope(cell.getStringCellValue());
262 if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
263 policyEntity.setPolicyData(cell.getStringCellValue());
265 if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
266 policyEntity.setDescription(cell.getStringCellValue());
268 if ("configurationbody".equalsIgnoreCase(getCellHeaderName(cell))) {
269 if(policyEntity.getPolicyName().contains("Config_")){
271 configurationDataEntity.setConfigBody(cell.getStringCellValue());
272 }else if(policyEntity.getPolicyName().contains("Action_")){
274 actionBodyEntity.setActionBody(cell.getStringCellValue());
277 if ("configurationName".equalsIgnoreCase(getCellHeaderName(cell))) {
279 configName = cell.getStringCellValue();
280 if(policyEntity.getPolicyName().contains("Config_")){
281 configurationDataEntity.setConfigurationName(cell.getStringCellValue());
282 }else if(policyEntity.getPolicyName().contains("Action_")){
283 actionBodyEntity.setActionBodyName(cell.getStringCellValue());
288 scope = policyEntity.getScope().replace(".", File.separator);
289 String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
290 SimpleBindings params = new SimpleBindings();
291 params.put("policyName", policyEntity.getPolicyName());
292 params.put("policyScope", policyEntity.getScope());
293 List<Object> queryData = controller.getDataByQuery(query, params);
294 if(!queryData.isEmpty()){
297 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) {
298 //1. if Role contains super admin create scope.
299 //2. if Role contains super editor don't create new scope and add to list to show to user.
301 PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
302 if(policyEditorScope == null){
303 if(roles.contains(SUPERADMIN)){
304 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
305 policyEditorScopeEntity.setScopeName(scope);
306 policyEditorScopeEntity.setUserCreatedBy(userInfo);
307 policyEditorScopeEntity.setUserModifiedBy(userInfo);
308 commonClassDao.save(policyEditorScopeEntity);
310 //Add Error Message a new Scope Exists, contact super-admin to create a new scope
315 if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
316 if(scopes.isEmpty()){
317 logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
319 //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list.
320 if(roles.contains(ADMIN)){
321 String scopeCheck = scope.substring(0, scope.lastIndexOf('.'));
322 if(scopes.contains(scopeCheck)){
323 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
324 policyEditorScopeEntity.setScopeName(scope);
325 policyEditorScopeEntity.setUserCreatedBy(userInfo);
326 policyEditorScopeEntity.setUserModifiedBy(userInfo);
327 commonClassDao.save(policyEditorScopeEntity);
338 if(configName.endsWith("json")){
339 configurationDataEntity.setConfigType("JSON");
340 }else if(configName.endsWith("txt")){
341 configurationDataEntity.setConfigType("OTHER");
342 }else if(configName.endsWith("xml")){
343 configurationDataEntity.setConfigType("XML");
344 }else if(configName.endsWith("properties")){
345 configurationDataEntity.setConfigType("PROPERTIES");
347 configurationDataEntity.setDeleted(false);
348 configurationDataEntity.setCreatedBy(userId);
349 configurationDataEntity.setModifiedBy(userId);
350 commonClassDao.save(configurationDataEntity);
351 try(FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + configName)){
352 BufferedWriter bw = new BufferedWriter(fw);
353 bw.write(configurationDataEntity.getConfigBody());
355 } catch (IOException e) {
356 logger.error("Exception Occured While cloning the configuration file",e);
360 actionBodyEntity.setDeleted(false);
361 actionBodyEntity.setCreatedBy(userId);
362 actionBodyEntity.setModifiedBy(userId);
363 commonClassDao.save(actionBodyEntity);
364 try(FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
365 BufferedWriter bw = new BufferedWriter(fw);
366 bw.write(actionBodyEntity.getActionBody());
368 } catch (IOException e) {
369 logger.error("Exception Occured While cloning the configuration file",e);
372 if(configName != null){
373 if(configName.contains("Config_")){
374 ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName);
375 policyEntity.setConfigurationData(configuration);
377 ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName);
378 policyEntity.setActionBodyEntity(actionBody);
381 policyEntity.setCreatedBy(userId);
382 policyEntity.setModifiedBy(userId);
383 policyEntity.setDeleted(false);
384 commonClassDao.save(policyEntity);
386 policyVersion = new PolicyVersion();
387 String policyName = policyEntity.getPolicyName().replace(".xml", "");
388 int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf('.')+1));
389 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
391 policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName);
392 policyVersion.setActiveVersion(version);
393 policyVersion.setHigherVersion(version);
394 policyVersion.setCreatedBy(userId);
395 policyVersion.setModifiedBy(userId);
396 commonClassDao.save(policyVersion);
403 //return the column header name value
404 private String getCellHeaderName(Cell cell){
405 return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();