2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 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;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.io.PrintWriter;
30 import java.nio.file.Files;
31 import java.text.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
40 import java.util.stream.Collectors;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43 import org.apache.commons.compress.utils.IOUtils;
44 import org.apache.commons.fileupload.FileItem;
45 import org.apache.commons.fileupload.FileUploadException;
46 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
47 import org.apache.commons.fileupload.servlet.ServletFileUpload;
48 import org.apache.poi.hssf.usermodel.HSSFRow;
49 import org.apache.poi.hssf.usermodel.HSSFSheet;
50 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
51 import org.apache.poi.ss.usermodel.Cell;
52 import org.apache.poi.ss.usermodel.Row;
53 import org.apache.poi.ss.usermodel.Sheet;
54 import org.apache.poi.ss.usermodel.Workbook;
55 import org.apache.poi.ss.usermodel.WorkbookFactory;
56 import org.json.JSONObject;
57 import org.onap.policy.common.logging.flexlogger.FlexLogger;
58 import org.onap.policy.common.logging.flexlogger.Logger;
59 import org.onap.policy.rest.adapter.PolicyRestAdapter;
60 import org.onap.policy.rest.adapter.ReturnBlackList;
61 import org.onap.policy.xacml.api.XACMLErrorConstants;
62 import org.onap.portalsdk.core.controller.RestrictedBaseController;
63 import org.onap.portalsdk.core.web.support.JsonMessage;
64 import org.springframework.stereotype.Controller;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.bind.annotation.RequestMethod;
71 * This class is used to import and export the black list entries which were used in the Decision Blacklist Guard YAML
77 public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseController {
79 private static final Logger policyLogger = FlexLogger.getLogger(ExportAndImportDecisionBlackListEntries.class);
80 private static final String BLACKLISTENTRIESDATA = "blackListEntries";
81 private static final String ACTION = "Action";
82 private static final String BLACKLISTENTRY = "BlackListEntry";
85 * This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can
86 * update the file on adding or removing the entries, for updating the policies or using in other Environments.
88 * @param request the request contains the policy data. So, based on that we can populate and read and write the
90 * @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory
91 * and making available to user to download from GUI.
92 * @throws IOException exception throws if anything goes wrong in the process.
94 @RequestMapping(value = {"/policycreation/exportDecisionBlackListEntries"}, method = {RequestMethod.POST})
95 public void exportBlackList(HttpServletRequest request, HttpServletResponse response) throws IOException {
96 try (HSSFWorkbook workBook = new HSSFWorkbook()) {
97 String requestData = request.getReader().lines().collect(Collectors.joining());
98 JSONObject root = new JSONObject(requestData);
99 PolicyRestAdapter adapter = new Gson().fromJson(root.get("policyData").toString(), PolicyRestAdapter.class);
100 DecisionPolicyController controller = new DecisionPolicyController();
101 controller.prePopulateDecisionPolicyData(adapter, null);
102 List<String> blackLists = adapter.getYamlparams().getBlackList();
103 HSSFSheet sheet = workBook.createSheet("BlackList");
104 HSSFRow headingRow = sheet.createRow(0);
105 headingRow.createCell(0).setCellValue("Action");
106 headingRow.createCell(1).setCellValue("BlackListEntry");
109 for (Object object : blackLists) {
110 HSSFRow row = sheet.createRow(rowNo);
111 row.createCell(0).setCellValue(1);
112 row.createCell(1).setCellValue(object.toString());
116 String tmpFile = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
119 * Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate.
123 SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
124 Date date = parseFormat.parse(root.get("date").toString().replaceAll("\"", ""));
125 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
126 String formatedDate = dateFormat.format(date);
128 String fileName = "BlackList_Scope_" + adapter.getDomainDir() + "_Name_" + adapter.getPolicyName()
129 + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
131 String deleteCheckPath = tmpFile + File.separator + fileName;
132 File deleteCheck = new File(deleteCheckPath);
133 if (deleteCheck.exists() && deleteCheck.delete()) {
134 policyLogger.info("Deleted the file from system before exporting a new file.");
137 File temPath = new File(tmpFile);
138 if (!temPath.exists()) {
142 String file = temPath + File.separator + fileName;
143 File filepath = new File(file);
144 FileOutputStream fos = new FileOutputStream(filepath);
148 response.setCharacterEncoding("UTF-8");
149 response.setContentType("application / json");
150 request.setCharacterEncoding("UTF-8");
152 PrintWriter out = response.getWriter();
153 String successMap = file.substring(file.lastIndexOf("webapps") + 8);
154 String responseString = new Gson().toJson(successMap);
155 JSONObject jsonResposne = new JSONObject("{data: " + responseString + "}");
156 out.write(jsonResposne.toString());
157 } catch (Exception e) {
159 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting BlackList Entries" , e);
164 * This method is used to import the BlackList excel file into the system. Which is used to create Decision
165 * Blacklist Guard YAML Policy.
167 * @param request the HTTP request contains file upload stream form GUI.
168 * @param response the response is send to the GUI after reading the file input stream.
169 * @throws FileUploadException throws fileUpload Exception.
170 * @throws IOException throws IO Exceptions.
172 @RequestMapping(value = {"/policycreation/importBlackListForDecisionPolicy"}, method = {RequestMethod.POST})
173 public void importBlackListFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
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());
191 * This method is used to read the first item, as we expect only one entry in the file upload.
193 * @param items The file entries which were uploaded from GUI.
194 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
195 * @param model Map which stores key value (blacklist and append list data)
196 * @throws Exception throws exception if it is not .xls format
198 private void readItems(List<FileItem> items, List<String> errorLogs, Map<String, Object> model) throws Exception {
199 Map<String, InputStream> files = new HashMap<>();
201 FileItem item = items.get(0);
202 files.put(item.getName(), item.getInputStream());
203 File file = new File(item.getName());
204 String fileName = file.getName();
205 try (OutputStream outputStream = new FileOutputStream(file);) {
206 IOUtils.copy(item.getInputStream(), outputStream);
207 if (fileName.startsWith("BlackList") && fileName.endsWith(".xls")) {
208 readWorkBook(fileName, errorLogs, model);
210 errorLogs.add("The File Name should start with BlackList and must be .xls format.");
211 model.put(BLACKLISTENTRIESDATA, errorLogs);
214 Files.delete(file.toPath());
218 * This method is used to read the workbook in xls file item.
220 * @param fileName fileName as input parameter
221 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
222 * @param model Map which stores key value (blacklist and append list data)
224 private void readWorkBook(String fileName, List<String> errorLogs, Map<String, Object> model) {
225 Set<String> blackListEntries = new HashSet<>();
226 Set<String> appendBlackListEntries = new HashSet<>();
227 try (Workbook workbook = WorkbookFactory.create(new File(fileName))) {
228 Sheet datatypeSheet = workbook.getSheetAt(0);
229 Iterator<Row> rowIterator = datatypeSheet.iterator();
230 readExcelRows(rowIterator, blackListEntries, appendBlackListEntries, errorLogs);
231 if (errorLogs.size() == 1) {
232 model.put(BLACKLISTENTRIESDATA, blackListEntries);
233 model.put("appendBlackListEntries", appendBlackListEntries);
235 model.put(BLACKLISTENTRIESDATA, errorLogs);
237 } catch (Exception e) {
238 String error = "Error Occured While Reading File. Please check the format of the file.";
239 errorLogs.add(error);
240 model.put(BLACKLISTENTRIESDATA, errorLogs);
241 policyLogger.error(error , e);
246 * This method is used to read all the rows from imported Excel sheet and set to respective objects.
248 * @param rowIterator Excel Sheet rows are passed as input parameters.
249 * @param blackListEntries the data is set to this object, which is going to be added.
250 * @param appendBlackListEntries the data is set to this object which is going to be removed.
251 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
253 private void readExcelRows(Iterator<Row> rowIterator, Set<String> blackListEntries,
254 Set<String> appendBlackListEntries, List<String> errorLogs) {
255 while (rowIterator.hasNext()) {
256 Row currentRow = rowIterator.next();
257 if (currentRow.getRowNum() == 0) {
260 Iterator<Cell> cellIterator = currentRow.cellIterator();
261 readExcelCells(cellIterator, blackListEntries, appendBlackListEntries, errorLogs);
266 * This method is used to read all the cells in the row.
268 * @param cellIterator iterating the cells and will parse based on the cell type.
269 * @param blackListEntries the data is set to this object, which is going to be added.
270 * @param appendBlackListEntries the data is set to this object which is going to be removed.
271 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
273 private void readExcelCells(Iterator<Cell> cellIterator, Set<String> blackListEntries,
274 Set<String> appendBlackListEntries, List<String> errorLogs) {
275 boolean actionCheck = false;
276 boolean blackListCheck = false;
280 while (cellIterator.hasNext()) {
281 Cell cell = cellIterator.next();
282 if (ACTION.equalsIgnoreCase(getCellHeaderName(cell))) {
283 ReturnBlackList returnList = readActionCell(cell, lineNo, errorLogs);
284 actionEntry = returnList.getActionValue();
285 actionCheck = returnList.isEntryCheck();
287 if (BLACKLISTENTRY.equalsIgnoreCase(getCellHeaderName(cell))) {
288 ReturnBlackList returnList = readBlackListCell(cell, lineNo, errorLogs);
289 blEntry = returnList.getEntryValue();
290 blackListCheck = returnList.isEntryCheck();
291 actionEntry = returnList.getActionValue();
295 if (actionCheck && blackListCheck) {
296 addBlackListEntries(actionEntry, blackListEntries, appendBlackListEntries, blEntry);
301 * This method is used to read the Action cell entry.
303 * @param cell reading the action entry cell.
304 * @param lineNo counts the number of the cell.
305 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
306 * @return returns the response on setting to ReturnBlackList class.
308 private ReturnBlackList readActionCell(Cell cell, int lineNo, List<String> errorLogs) {
309 ReturnBlackList returnValues = new ReturnBlackList();
310 String error = "Entry at row " + lineNo + " not added, the value in the " + ACTION
311 + "column is neither \"0\" nor \"1\"";
314 actionEntry = (int) cell.getNumericCellValue();
315 returnValues.setEntryCheck(true);
316 if (actionEntry != 1 && actionEntry != 0) {
317 errorLogs.add(error);
319 } catch (Exception e) {
320 errorLogs.add(error);
321 policyLogger.error(error, e);
324 returnValues.setActionValue(actionEntry);
330 * This method is used to read the BlackList cell entry.
332 * @param cell reading the blacklist entry cell.
333 * @param lineNo counts the number of the cell.
334 * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
335 * @return returns the response on setting to ReturnBlackList class.
337 private ReturnBlackList readBlackListCell(Cell cell, int lineNo, List<String> errorLogs) {
338 ReturnBlackList returnValues = new ReturnBlackList();
341 blEntry = cell.getStringCellValue();
342 returnValues.setEntryCheck(true);
343 } catch (Exception e) {
344 String error = "Entry at row " + lineNo + " not added, the value in the " + BLACKLISTENTRY
345 + " column is not a valid string";
346 errorLogs.add(error);
347 policyLogger.error(error, e);
348 returnValues.setActionValue(0);
350 returnValues.setEntryValue(blEntry);
355 * This method is used to add the data to blacklist and append list after parsing each and every row.
357 * @param actionEntry it has the input to add or not and holds either 0 or 1.
358 * @param blackListEntries list to add blacklist entries based on action entry = 1.
359 * @param appendBlackListEntries list to add append list entries based on action entry = 0.
360 * @param blEntry the value added to both entries based on action entry.
362 private void addBlackListEntries(int actionEntry, Set<String> blackListEntries, Set<String> appendBlackListEntries,
364 if (actionEntry == 1) {
365 blackListEntries.add(blEntry);
367 appendBlackListEntries.add(blEntry);
372 * This method is used to identify the header of the cell.
374 * @param cell Excel sheet cell is passed as input parameter.
375 * @return the column header name value
377 private String getCellHeaderName(Cell cell) {
378 return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();