Sonar cleanup in controllers etc
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / ExportAndImportDecisionBlackListEntries.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23 import com.google.gson.Gson;
24
25 import java.io.File;
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;
39 import java.util.Map;
40 import java.util.Set;
41 import java.util.stream.Collectors;
42
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45
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;
70
71 /**
72  * This class is used to import and export the black list entries which were used in the Decision Blacklist Guard YAML
73  * Policy.
74  *
75  */
76 @Controller
77 @RequestMapping("/")
78 public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseController {
79
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";
84
85     /**
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.
88      *
89      * @param request the request contains the policy data. So, based on that we can populate and read and write the
90      *        entries.
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.
94      */
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);
108
109             short rowNo = 1;
110             for (Object object : blackLists) {
111                 HSSFRow row = sheet.createRow(rowNo);
112                 row.createCell(0).setCellValue(1);
113                 row.createCell(1).setCellValue(object.toString());
114                 rowNo++;
115             }
116
117             String tmpFile = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
118
119             /*
120              * Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate.
121              *
122              */
123
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);
128
129             String fileName = "BlackList_Scope_" + adapter.getDomainDir() + "_Name_" + adapter.getPolicyName()
130                     + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
131
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.");
136             }
137
138             File temPath = new File(tmpFile);
139             if (!temPath.exists()) {
140                 temPath.mkdir();
141             }
142
143             String file = temPath + File.separator + fileName;
144             File filepath = new File(file);
145             FileOutputStream fos = new FileOutputStream(filepath);
146             workBook.write(fos);
147             fos.flush();
148
149             response.setCharacterEncoding("UTF-8");
150             response.setContentType("application / json");
151             request.setCharacterEncoding("UTF-8");
152
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) {
159             policyLogger.error(
160                     XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting BlackList Entries", e);
161         }
162     }
163
164     /**
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.
167      *
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.
170      */
171     @RequestMapping(value = {"/policycreation/importBlackListForDecisionPolicy"}, method = {RequestMethod.POST})
172     public void importBlackListFile(HttpServletRequest request, HttpServletResponse response) {
173         try {
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);
182             } else {
183                 readItems(items, errorLogs, model);
184             }
185             response.getWriter().write(new JSONObject(new JsonMessage(mapper.toJson(model))).toString());
186         } catch (FileUploadException | IOException e) {
187             policyLogger.error("Exception Occured while importing the BlackListEntry", e);
188         }
189     }
190
191     /**
192      * This method is used to read the first item, as we expect only one entry in the file upload.
193      *
194      * @param items The file entries which were uploaded from GUI.
195      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
196      * @param model Map which stores key value (blacklist and append list data)
197      * @throws Exception throws exception if it is not .xls format
198      */
199     private void readItems(List<FileItem> items, List<String> errorLogs, Map<String, Object> model) throws IOException {
200         Map<String, InputStream> files = new HashMap<>();
201
202         FileItem item = items.get(0);
203         files.put(item.getName(), item.getInputStream());
204         File file = new File(item.getName());
205         String fileName = file.getName();
206         try (OutputStream outputStream = new FileOutputStream(file);) {
207             IOUtils.copy(item.getInputStream(), outputStream);
208             if (fileName.startsWith("BlackList") && fileName.endsWith(".xls")) {
209                 readWorkBook(fileName, errorLogs, model);
210             } else {
211                 errorLogs.add("The File Name should start with BlackList and must be .xls format.");
212                 model.put(BLACKLISTENTRIESDATA, errorLogs);
213             }
214         }
215         Files.delete(file.toPath());
216     }
217
218     /**
219      * This method is used to read the workbook in xls file item.
220      *
221      * @param fileName fileName as input parameter
222      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
223      * @param model Map which stores key value (blacklist and append list data)
224      */
225     private void readWorkBook(String fileName, List<String> errorLogs, Map<String, Object> model) {
226         Set<String> blackListEntries = new HashSet<>();
227         Set<String> appendBlackListEntries = new HashSet<>();
228         try (Workbook workbook = WorkbookFactory.create(new File(fileName))) {
229             Sheet datatypeSheet = workbook.getSheetAt(0);
230             Iterator<Row> rowIterator = datatypeSheet.iterator();
231             readExcelRows(rowIterator, blackListEntries, appendBlackListEntries, errorLogs);
232             if (errorLogs.size() == 1) {
233                 model.put(BLACKLISTENTRIESDATA, blackListEntries);
234                 model.put("appendBlackListEntries", appendBlackListEntries);
235             } else {
236                 model.put(BLACKLISTENTRIESDATA, errorLogs);
237             }
238         } catch (Exception e) {
239             String error = "Error Occured While Reading File. Please check the format of the file.";
240             errorLogs.add(error);
241             model.put(BLACKLISTENTRIESDATA, errorLogs);
242             policyLogger.error(error, e);
243         }
244     }
245
246     /**
247      * This method is used to read all the rows from imported Excel sheet and set to respective objects.
248      *
249      * @param rowIterator Excel Sheet rows are passed as input parameters.
250      * @param blackListEntries the data is set to this object, which is going to be added.
251      * @param appendBlackListEntries the data is set to this object which is going to be removed.
252      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
253      */
254     private void readExcelRows(Iterator<Row> rowIterator, Set<String> blackListEntries,
255             Set<String> appendBlackListEntries, List<String> errorLogs) {
256         while (rowIterator.hasNext()) {
257             Row currentRow = rowIterator.next();
258             if (currentRow.getRowNum() == 0) {
259                 continue;
260             }
261             Iterator<Cell> cellIterator = currentRow.cellIterator();
262             readExcelCells(cellIterator, blackListEntries, appendBlackListEntries, errorLogs);
263         }
264     }
265
266     /**
267      * This method is used to read all the cells in the row.
268      *
269      * @param cellIterator iterating the cells and will parse based on the cell type.
270      * @param blackListEntries the data is set to this object, which is going to be added.
271      * @param appendBlackListEntries the data is set to this object which is going to be removed.
272      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
273      */
274     private void readExcelCells(Iterator<Cell> cellIterator, Set<String> blackListEntries,
275             Set<String> appendBlackListEntries, List<String> errorLogs) {
276         boolean actionCheck = false;
277         boolean blackListCheck = false;
278         String blEntry = "";
279         int actionEntry = 0;
280         int lineNo = 1;
281         while (cellIterator.hasNext()) {
282             Cell cell = cellIterator.next();
283             if (ACTION.equalsIgnoreCase(getCellHeaderName(cell))) {
284                 ReturnBlackList returnList = readActionCell(cell, lineNo, errorLogs);
285                 actionEntry = returnList.getActionValue();
286                 actionCheck = returnList.isEntryCheck();
287             }
288             if (BLACKLISTENTRY.equalsIgnoreCase(getCellHeaderName(cell))) {
289                 ReturnBlackList returnList = readBlackListCell(cell, lineNo, errorLogs);
290                 blEntry = returnList.getEntryValue();
291                 blackListCheck = returnList.isEntryCheck();
292             }
293             lineNo++;
294         }
295         if (actionCheck && blackListCheck) {
296             addBlackListEntries(actionEntry, blackListEntries, appendBlackListEntries, blEntry);
297         }
298     }
299
300     /**
301      * This method is used to read the Action cell entry.
302      *
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.
307      */
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\"";
312         int actionEntry = 0;
313         try {
314             actionEntry = (int) cell.getNumericCellValue();
315             returnValues.setEntryCheck(true);
316             if (actionEntry != 1 && actionEntry != 0) {
317                 errorLogs.add(error);
318             }
319         } catch (Exception e) {
320             errorLogs.add(error);
321             policyLogger.error(error, e);
322             actionEntry = 0;
323         }
324         returnValues.setActionValue(actionEntry);
325         return returnValues;
326     }
327
328     /**
329      * This method is used to read the BlackList cell entry.
330      *
331      * @param cell reading the blacklist entry cell.
332      * @param lineNo counts the number of the cell.
333      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
334      * @return returns the response on setting to ReturnBlackList class.
335      */
336     private ReturnBlackList readBlackListCell(Cell cell, int lineNo, List<String> errorLogs) {
337         ReturnBlackList returnValues = new ReturnBlackList();
338         String blEntry = "";
339         try {
340             blEntry = cell.getStringCellValue();
341             returnValues.setEntryCheck(true);
342         } catch (Exception e) {
343             String error = "Entry at row " + lineNo + " not added, the value in the " + BLACKLISTENTRY
344                     + " column is not a valid string";
345             errorLogs.add(error);
346             policyLogger.error(error, e);
347             returnValues.setActionValue(0);
348         }
349         returnValues.setEntryValue(blEntry);
350         return returnValues;
351     }
352
353     /**
354      * This method is used to add the data to blacklist and append list after parsing each and every row.
355      *
356      * @param actionEntry it has the input to add or not and holds either 0 or 1.
357      * @param blackListEntries list to add blacklist entries based on action entry = 1.
358      * @param appendBlackListEntries list to add append list entries based on action entry = 0.
359      * @param blEntry the value added to both entries based on action entry.
360      */
361     private void addBlackListEntries(int actionEntry, Set<String> blackListEntries, Set<String> appendBlackListEntries,
362             String blEntry) {
363         if (actionEntry == 1) {
364             blackListEntries.add(blEntry);
365         } else {
366             appendBlackListEntries.add(blEntry);
367         }
368     }
369
370     /**
371      * This method is used to identify the header of the cell.
372      *
373      * @param cell Excel sheet cell is passed as input parameter.
374      * @return the column header name value
375      */
376     private String getCellHeaderName(Cell cell) {
377         return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
378     }
379 }