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.openecomp.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.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
38 import org.apache.poi.hssf.usermodel.HSSFRow;
39 import org.apache.poi.hssf.usermodel.HSSFSheet;
40 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
41 import org.apache.poi.ss.usermodel.Cell;
42 import org.apache.poi.ss.usermodel.Row;
43 import org.apache.poi.ss.usermodel.Sheet;
44 import org.apache.poi.ss.usermodel.Workbook;
45 import org.json.JSONObject;
46 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
47 import org.openecomp.policy.common.logging.flexlogger.Logger;
48 import org.openecomp.policy.model.Roles;
49 import org.openecomp.policy.rest.adapter.PolicyExportAdapter;
50 import org.openecomp.policy.rest.dao.CommonClassDao;
51 import org.openecomp.policy.rest.jpa.ActionBodyEntity;
52 import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
53 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
54 import org.openecomp.policy.rest.jpa.PolicyEntity;
55 import org.openecomp.policy.rest.jpa.PolicyVersion;
56 import org.openecomp.policy.rest.jpa.UserInfo;
57 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.stereotype.Controller;
62 import org.springframework.web.bind.annotation.RequestMapping;
64 import com.fasterxml.jackson.databind.DeserializationFeature;
65 import com.fasterxml.jackson.databind.JsonNode;
66 import com.fasterxml.jackson.databind.ObjectMapper;
71 public class PolicyExportAndImportController extends RestrictedBaseController {
72 private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
74 private ArrayList<String> selectedPolicy;
75 private Set<String> scopes = null;
76 private List<String> roles = null;
77 private static String SUPERADMIN = "super-admin";
78 private static String SUPEREDITOR = "super-editor";
79 private static String ADMIN = "admin";
80 private static String EDITOR = "editor";
82 private static CommonClassDao commonClassDao;
84 private PolicyEntity policyEntity;
85 private ConfigurationDataEntity configurationDataEntity;
86 private ActionBodyEntity actionBodyEntity;
87 private PolicyVersion policyVersion;
89 private Workbook workbook;
91 private HSSFWorkbook workBook2;
94 private PolicyExportAndImportController(CommonClassDao commonClassDao){
95 PolicyExportAndImportController.commonClassDao = commonClassDao;
98 public PolicyExportAndImportController(){}
100 @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
101 public void ExportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
104 selectedPolicy = new ArrayList<>();
105 ObjectMapper mapper = new ObjectMapper();
106 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
107 JsonNode root = mapper.readTree(request.getReader());
108 PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
109 for (Object policyId : adapter.getPolicyDatas()) {
110 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
111 String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
112 String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, ".");
113 String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1);
114 selectedPolicy.add(policyName+":"+scope);
116 List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy);
118 workBook2 = new HSSFWorkbook();
119 HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
121 HSSFRow headingRow = sheet.createRow(0);
122 headingRow.createCell(0).setCellValue("policyName");
123 headingRow.createCell(1).setCellValue("scope");
124 headingRow.createCell(2).setCellValue("version");
125 headingRow.createCell(3).setCellValue("policyData");
126 headingRow.createCell(4).setCellValue("description");
127 headingRow.createCell(5).setCellValue("configurationbody");
128 headingRow.createCell(6).setCellValue("configurationName");
131 for (Object object : entityData) {
132 PolicyEntity policyEntity = (PolicyEntity) object;
133 HSSFRow row = sheet.createRow(rowNo);
134 row.createCell(0).setCellValue(policyEntity.getPolicyName());
135 row.createCell(1).setCellValue(policyEntity.getScope());
136 row.createCell(2).setCellValue(policyEntity.getVersion());
137 row.createCell(3).setCellValue(policyEntity.getPolicyData());
138 row.createCell(4).setCellValue(policyEntity.getDescription());
139 if(!policyEntity.getPolicyName().contains("Decision_")){
140 if(policyEntity.getConfigurationData() != null){
141 row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody());
142 row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
144 if(policyEntity.getActionBodyEntity() != null){
145 row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
146 row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
149 row.createCell(5).setCellValue("");
150 row.createCell(6).setCellValue("");
155 String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
156 String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
157 File deleteCheck = new File(deleteCheckPath);
158 if(deleteCheck.exists()){
159 deleteCheck.delete();
161 File temPath = new File(tmp);
162 if(!temPath.exists()){
166 file = temPath + File.separator + "PolicyExport.xls";
167 File filepath = new File(file);
168 FileOutputStream fos = new FileOutputStream(filepath);
169 workBook2.write(fos);
172 response.setCharacterEncoding("UTF-8");
173 response.setContentType("application / json");
174 request.setCharacterEncoding("UTF-8");
176 PrintWriter out = response.getWriter();
177 String successMap = file.toString().substring(file.toString().lastIndexOf("webapps")+8);
178 String responseString = mapper.writeValueAsString(successMap);
179 JSONObject j = new JSONObject("{data: " + responseString + "}");
180 out.write(j.toString());
182 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e);
187 public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws Exception{
188 boolean configExists = false;
189 boolean actionExists = false;
190 String configName = null;
192 boolean finalColumn = false;
193 PolicyController controller = new PolicyController();
194 String userId = UserUtils.getUserSession(request).getOrgUserId();
195 UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
197 //Check if the Role and Scope Size are Null get the values from db.
198 List<Object> userRoles = PolicyController.getRoles(userId);
199 roles = new ArrayList<>();
200 scopes = new HashSet<>();
201 for(Object role: userRoles){
202 Roles userRole = (Roles) role;
203 roles.add(userRole.getRole());
204 if(userRole.getScope() != null){
205 if(userRole.getScope().contains(",")){
206 String[] multipleScopes = userRole.getScope().split(",");
207 for(int i =0; i < multipleScopes.length; i++){
208 scopes.add(multipleScopes[i]);
211 scopes.add(userRole.getScope());
215 FileInputStream excelFile = new FileInputStream(new File(file));
216 workbook = new HSSFWorkbook(excelFile);
217 Sheet datatypeSheet = workbook.getSheetAt(0);
218 Iterator<Row> rowIterator = datatypeSheet.iterator();
220 while (rowIterator.hasNext()) {
221 policyEntity = new PolicyEntity();
222 configurationDataEntity = new ConfigurationDataEntity();
223 actionBodyEntity = new ActionBodyEntity();
224 policyVersion = new PolicyVersion();
225 Row currentRow = rowIterator.next();
226 if (currentRow.getRowNum() == 0) {
229 Iterator<Cell> cellIterator = currentRow.cellIterator();
230 while (cellIterator.hasNext()) {
231 Cell cell = cellIterator.next();
232 if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) {
233 policyEntity.setPolicyName(cell.getStringCellValue());
235 if (getCellHeaderName(cell).equalsIgnoreCase("scope")) {
236 policyEntity.setScope(cell.getStringCellValue());
238 if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) {
239 policyEntity.setPolicyData(cell.getStringCellValue());
241 if (getCellHeaderName(cell).equalsIgnoreCase("description")) {
242 policyEntity.setDescription(cell.getStringCellValue());
244 if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) {
245 if(policyEntity.getPolicyName().contains("Config_")){
247 configurationDataEntity.setConfigBody(cell.getStringCellValue());
248 }else if(policyEntity.getPolicyName().contains("Action_")){
250 actionBodyEntity.setActionBody(cell.getStringCellValue());
253 if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) {
255 configName = cell.getStringCellValue();
256 if(policyEntity.getPolicyName().contains("Config_")){
257 configurationDataEntity.setConfigurationName(cell.getStringCellValue());
258 }else if(policyEntity.getPolicyName().contains("Action_")){
259 actionBodyEntity.setActionBodyName(cell.getStringCellValue());
264 scope = policyEntity.getScope().replace(".", File.separator);
265 String query = "FROM PolicyEntity where policyName = '"+policyEntity.getPolicyName()+"' and scope ='"+policyEntity.getScope()+"'";
266 List<Object> queryData = controller.getDataByQuery(query);
267 if(!queryData.isEmpty()){
270 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) {
271 //1. if Role contains super admin create scope.
272 //2. if Role contains super editor don't create new scope and add to list to show to user.
274 PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
275 if(policyEditorScope == null){
276 if(roles.contains(SUPERADMIN)){
277 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
278 policyEditorScopeEntity.setScopeName(scope);
279 policyEditorScopeEntity.setUserCreatedBy(userInfo);
280 policyEditorScopeEntity.setUserModifiedBy(userInfo);
281 commonClassDao.save(policyEditorScopeEntity);
283 //Add Error Message a new Scope Exists, contact super-admin to create a new scope
288 if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
289 if(scopes.isEmpty()){
290 //return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
292 //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list.
293 if(roles.contains(ADMIN)){
294 String scopeCheck = scope.substring(0, scope.lastIndexOf("."));
295 if(scopes.contains(scopeCheck)){
296 PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
297 policyEditorScopeEntity.setScopeName(scope);
298 policyEditorScopeEntity.setUserCreatedBy(userInfo);
299 policyEditorScopeEntity.setUserModifiedBy(userInfo);
300 commonClassDao.save(policyEditorScopeEntity);
311 if(configName.endsWith("json")){
312 configurationDataEntity.setConfigType("JSON");
313 }else if(configName.endsWith("txt")){
314 configurationDataEntity.setConfigType("OTHER");
315 }else if(configName.endsWith("xml")){
316 configurationDataEntity.setConfigType("XML");
317 }else if(configName.endsWith("properties")){
318 configurationDataEntity.setConfigType("PROPERTIES");
320 configurationDataEntity.setDeleted(false);
321 configurationDataEntity.setCreatedBy(userId);
322 configurationDataEntity.setModifiedBy(userId);
323 commonClassDao.save(configurationDataEntity);
326 actionBodyEntity.setDeleted(false);
327 actionBodyEntity.setCreatedBy(userId);
328 actionBodyEntity.setModifiedBy(userId);
329 commonClassDao.save(actionBodyEntity);
331 if(configName != null){
332 if(configName.contains("Config_")){
333 ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName);
334 policyEntity.setConfigurationData(configuration);
336 ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName);
337 policyEntity.setActionBodyEntity(actionBody);
340 policyEntity.setCreatedBy(userId);
341 policyEntity.setModifiedBy(userId);
342 policyEntity.setDeleted(false);
343 commonClassDao.save(policyEntity);
345 policyVersion = new PolicyVersion();
346 String policyName = policyEntity.getPolicyName().replace(".xml", "");
347 int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf(".")+1));
348 policyName = policyName.substring(0, policyName.lastIndexOf("."));
350 policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName);
351 policyVersion.setActiveVersion(version);
352 policyVersion.setHigherVersion(version);
353 policyVersion.setCreatedBy(userId);
354 policyVersion.setModifiedBy(userId);
355 commonClassDao.save(policyVersion);
362 //return the column header name value
363 private String getCellHeaderName(Cell cell){
364 String cellHeaderName = cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
365 return cellHeaderName;