2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-2019 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;
23 import com.google.gson.Gson;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.PrintWriter;
31 import java.nio.file.Files;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Date;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.List;
41 import java.util.stream.Collectors;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
46 import org.apache.commons.compress.utils.IOUtils;
47 import org.apache.commons.fileupload.FileItem;
48 import org.apache.commons.fileupload.FileUploadException;
49 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
50 import org.apache.commons.fileupload.servlet.ServletFileUpload;
51 import org.apache.poi.hssf.usermodel.HSSFRow;
52 import org.apache.poi.hssf.usermodel.HSSFSheet;
53 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
54 import org.apache.poi.ss.usermodel.Cell;
55 import org.apache.poi.ss.usermodel.Row;
56 import org.apache.poi.ss.usermodel.Sheet;
57 import org.apache.poi.ss.usermodel.Workbook;
58 import org.apache.poi.ss.usermodel.WorkbookFactory;
59 import org.json.JSONObject;
60 import org.onap.policy.common.logging.flexlogger.FlexLogger;
61 import org.onap.policy.common.logging.flexlogger.Logger;
62 import org.onap.policy.rest.adapter.PolicyRestAdapter;
63 import org.onap.policy.rest.adapter.ReturnBlackList;
64 import org.onap.policy.xacml.api.XACMLErrorConstants;
65 import org.onap.portalsdk.core.controller.RestrictedBaseController;
66 import org.onap.portalsdk.core.web.support.JsonMessage;
67 import org.springframework.stereotype.Controller;
68 import org.springframework.web.bind.annotation.RequestMapping;
69 import org.springframework.web.bind.annotation.RequestMethod;
72 * This class is used to import and export the black list entries which were used in the Decision Blacklist Guard YAML
78 public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseController {
80 private static final Logger policyLogger = FlexLogger.getLogger(ExportAndImportDecisionBlackListEntries.class);
81 private static final String BLACKLISTENTRIESDATA = "blackListEntries";
82 private static final String ACTION = "Action";
83 private static final String BLACKLISTENTRY = "BlackListEntry";
86 * This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can
87 * update the file on adding or removing the entries, for updating the policies or using in other Environments.
89 * @param request the request contains the policy data. So, based on that we can populate and read and write the
91 * @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory
92 * and making available to user to download from GUI.
93 * @throws IOException exception throws if anything goes wrong in the process.
95 @RequestMapping(value = {"/policycreation/exportDecisionBlackListEntries"}, method = {RequestMethod.POST})
96 public void exportBlackList(HttpServletRequest request, HttpServletResponse response) throws IOException {
97 try (HSSFWorkbook workBook = new HSSFWorkbook()) {
98 String requestData = request.getReader().lines().collect(Collectors.joining());
99 JSONObject root = new JSONObject(requestData);
100 PolicyRestAdapter adapter = new Gson().fromJson(root.get("policyData").toString(), PolicyRestAdapter.class);
101 DecisionPolicyController controller = new DecisionPolicyController();
102 controller.prePopulateDecisionPolicyData(adapter, null);
103 List<String> blackLists = adapter.getYamlparams().getBlackList();
104 HSSFSheet sheet = workBook.createSheet("BlackList");
105 HSSFRow headingRow = sheet.createRow(0);
106 headingRow.createCell(0).setCellValue(ACTION);
107 headingRow.createCell(1).setCellValue(BLACKLISTENTRY);
110 for (Object object : blackLists) {
111 HSSFRow row = sheet.createRow(rowNo);
112 row.createCell(0).setCellValue(1);
113 row.createCell(1).setCellValue(object.toString());
117 String tmpFile = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
120 * Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate.
124 SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
125 Date date = parseFormat.parse(root.get("date").toString().replaceAll("\"", ""));
126 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
127 String formatedDate = dateFormat.format(date);
129 String fileName = "BlackList_Scope_" + adapter.getDomainDir() + "_Name_" + adapter.getPolicyName()
130 + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
132 String deleteCheckPath = tmpFile + File.separator + fileName;
133 File deleteCheck = new File(deleteCheckPath);
134 if (deleteCheck.exists() && deleteCheck.delete()) {
135 policyLogger.info("Deleted the file from system before exporting a new file.");
138 File temPath = new File(tmpFile);
139 if (!temPath.exists()) {
143 String file = temPath + File.separator + fileName;
144 File filepath = new File(file);
145 FileOutputStream fos = new FileOutputStream(filepath);
149 response.setCharacterEncoding("UTF-8");
150 response.setContentType("application / json");
151 request.setCharacterEncoding("UTF-8");
153 PrintWriter out = response.getWriter();
154 String successMap = file.substring(file.lastIndexOf("webapps") + 8);
155 String responseString = new Gson().toJson(successMap);
156 JSONObject jsonResposne = new JSONObject("{data: " + responseString + "}");
157 out.write(jsonResposne.toString());
158 } catch (Exception e) {
160 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting BlackList Entries", e);
165 * This method is used to import the BlackList excel file into the system. Which is used to create Decision
166 * Blacklist Guard YAML Policy.
168 * @param request the HTTP request contains file upload stream form GUI.
169 * @param response the response is send to the GUI after reading the file input stream.
171 @RequestMapping(value = {"/policycreation/importBlackListForDecisionPolicy"}, method = {RequestMethod.POST})
172 public void importBlackListFile(HttpServletRequest request, HttpServletResponse response) {
174 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
175 List<String> errorLogs = new ArrayList<>();
176 Gson mapper = new Gson();
177 errorLogs.add("error");
178 Map<String, Object> model = new HashMap<>();
179 if (items.isEmpty()) {
180 errorLogs.add("The File doesn't have any content and it is invalid.");
181 model.put(BLACKLISTENTRIESDATA, errorLogs);
183 readItems(items, errorLogs, model);
185 JsonMessage msg = new JsonMessage(mapper.toJson(model));
186 JSONObject jsonResposne = new JSONObject(msg);
187 response.getWriter().write(jsonResposne.toString());
188 } catch (FileUploadException | IOException e) {
189 policyLogger.error("Exception Occured while importing the BlackListEntry", e);
194 * This method is used to read the first item, as we expect only one entry in the file upload.
196 * @param items The file entries which were uploaded from GUI.
197 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
198 * @param model Map which stores key value (blacklist and append list data)
199 * @throws Exception throws exception if it is not .xls format
201 private void readItems(List<FileItem> items, List<String> errorLogs, Map<String, Object> model) throws IOException {
202 Map<String, InputStream> files = new HashMap<>();
204 FileItem item = items.get(0);
205 files.put(item.getName(), item.getInputStream());
206 File file = new File(item.getName());
207 String fileName = file.getName();
208 try (OutputStream outputStream = new FileOutputStream(file);) {
209 IOUtils.copy(item.getInputStream(), outputStream);
210 if (fileName.startsWith("BlackList") && fileName.endsWith(".xls")) {
211 readWorkBook(fileName, errorLogs, model);
213 errorLogs.add("The File Name should start with BlackList and must be .xls format.");
214 model.put(BLACKLISTENTRIESDATA, errorLogs);
217 Files.delete(file.toPath());
221 * This method is used to read the workbook in xls file item.
223 * @param fileName fileName as input parameter
224 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
225 * @param model Map which stores key value (blacklist and append list data)
227 private void readWorkBook(String fileName, List<String> errorLogs, Map<String, Object> model) {
228 Set<String> blackListEntries = new HashSet<>();
229 Set<String> appendBlackListEntries = new HashSet<>();
230 try (Workbook workbook = WorkbookFactory.create(new File(fileName))) {
231 Sheet datatypeSheet = workbook.getSheetAt(0);
232 Iterator<Row> rowIterator = datatypeSheet.iterator();
233 readExcelRows(rowIterator, blackListEntries, appendBlackListEntries, errorLogs);
234 if (errorLogs.size() == 1) {
235 model.put(BLACKLISTENTRIESDATA, blackListEntries);
236 model.put("appendBlackListEntries", appendBlackListEntries);
238 model.put(BLACKLISTENTRIESDATA, errorLogs);
240 } catch (Exception e) {
241 String error = "Error Occured While Reading File. Please check the format of the file.";
242 errorLogs.add(error);
243 model.put(BLACKLISTENTRIESDATA, errorLogs);
244 policyLogger.error(error, e);
249 * This method is used to read all the rows from imported Excel sheet and set to respective objects.
251 * @param rowIterator Excel Sheet rows are passed as input parameters.
252 * @param blackListEntries the data is set to this object, which is going to be added.
253 * @param appendBlackListEntries the data is set to this object which is going to be removed.
254 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
256 private void readExcelRows(Iterator<Row> rowIterator, Set<String> blackListEntries,
257 Set<String> appendBlackListEntries, List<String> errorLogs) {
258 while (rowIterator.hasNext()) {
259 Row currentRow = rowIterator.next();
260 if (currentRow.getRowNum() == 0) {
263 Iterator<Cell> cellIterator = currentRow.cellIterator();
264 readExcelCells(cellIterator, blackListEntries, appendBlackListEntries, errorLogs);
269 * This method is used to read all the cells in the row.
271 * @param cellIterator iterating the cells and will parse based on the cell type.
272 * @param blackListEntries the data is set to this object, which is going to be added.
273 * @param appendBlackListEntries the data is set to this object which is going to be removed.
274 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
276 private void readExcelCells(Iterator<Cell> cellIterator, Set<String> blackListEntries,
277 Set<String> appendBlackListEntries, List<String> errorLogs) {
278 boolean actionCheck = false;
279 boolean blackListCheck = false;
283 while (cellIterator.hasNext()) {
284 Cell cell = cellIterator.next();
285 if (ACTION.equalsIgnoreCase(getCellHeaderName(cell))) {
286 ReturnBlackList returnList = readActionCell(cell, lineNo, errorLogs);
287 actionEntry = returnList.getActionValue();
288 actionCheck = returnList.isEntryCheck();
290 if (BLACKLISTENTRY.equalsIgnoreCase(getCellHeaderName(cell))) {
291 ReturnBlackList returnList = readBlackListCell(cell, lineNo, errorLogs);
292 blEntry = returnList.getEntryValue();
293 blackListCheck = returnList.isEntryCheck();
297 if (actionCheck && blackListCheck) {
298 addBlackListEntries(actionEntry, blackListEntries, appendBlackListEntries, blEntry);
303 * This method is used to read the Action cell entry.
305 * @param cell reading the action entry cell.
306 * @param lineNo counts the number of the cell.
307 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
308 * @return returns the response on setting to ReturnBlackList class.
310 private ReturnBlackList readActionCell(Cell cell, int lineNo, List<String> errorLogs) {
311 ReturnBlackList returnValues = new ReturnBlackList();
312 String error = "Entry at row " + lineNo + " not added, the value in the " + ACTION
313 + "column is neither \"0\" nor \"1\"";
316 actionEntry = (int) cell.getNumericCellValue();
317 returnValues.setEntryCheck(true);
318 if (actionEntry != 1 && actionEntry != 0) {
319 errorLogs.add(error);
321 } catch (Exception e) {
322 errorLogs.add(error);
323 policyLogger.error(error, e);
326 returnValues.setActionValue(actionEntry);
331 * This method is used to read the BlackList cell entry.
333 * @param cell reading the blacklist entry cell.
334 * @param lineNo counts the number of the cell.
335 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
336 * @return returns the response on setting to ReturnBlackList class.
338 private ReturnBlackList readBlackListCell(Cell cell, int lineNo, List<String> errorLogs) {
339 ReturnBlackList returnValues = new ReturnBlackList();
342 blEntry = cell.getStringCellValue();
343 returnValues.setEntryCheck(true);
344 } catch (Exception e) {
345 String error = "Entry at row " + lineNo + " not added, the value in the " + BLACKLISTENTRY
346 + " column is not a valid string";
347 errorLogs.add(error);
348 policyLogger.error(error, e);
349 returnValues.setActionValue(0);
351 returnValues.setEntryValue(blEntry);
356 * This method is used to add the data to blacklist and append list after parsing each and every row.
358 * @param actionEntry it has the input to add or not and holds either 0 or 1.
359 * @param blackListEntries list to add blacklist entries based on action entry = 1.
360 * @param appendBlackListEntries list to add append list entries based on action entry = 0.
361 * @param blEntry the value added to both entries based on action entry.
363 private void addBlackListEntries(int actionEntry, Set<String> blackListEntries, Set<String> appendBlackListEntries,
365 if (actionEntry == 1) {
366 blackListEntries.add(blEntry);
368 appendBlackListEntries.add(blEntry);
373 * This method is used to identify the header of the cell.
375 * @param cell Excel sheet cell is passed as input parameter.
376 * @return the column header name value
378 private String getCellHeaderName(Cell cell) {
379 return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();