Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.nkapps.billing.controllers; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.nkapps.billing.configs.LayoutInterceptor; import com.nkapps.billing.models.BankStatement; import com.nkapps.billing.models.InvoicePojo; import com.nkapps.billing.models.PrintClaimPojo; import com.nkapps.billing.models.PrintClaimRegisterPojo; import com.nkapps.billing.models.PrintRegisterPojo; import com.nkapps.billing.models.Subject; import com.nkapps.billing.services.AuthService; import com.nkapps.billing.services.BankStatementPrintService; import com.nkapps.billing.services.BankStatementService; import com.nkapps.billing.services.PaymentService; import com.nkapps.billing.services.SearchService; /** * * @author nuraddin */ @Controller @RequestMapping("/bank-statement") public class BankStatementController { @Autowired private MessageSource messageSource; @Autowired private AuthService authService; @Autowired private BankStatementService bankStatementService; @Autowired private SearchService searchService; @Autowired private Environment environment; @Autowired private BankStatementPrintService bankStatementPrintService; @Autowired private PaymentService paymentService; Logger logger = LoggerFactory.getLogger(BankStatementController.class); @RequestMapping(value = "/index", method = RequestMethod.GET) public String index(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = authService.getSubject(); map.put("userName", subject.getName()); map.put("userRole", subject.getRole()); map.put("ns10Code", subject.getNs10Code()); map.put("ns11Code", subject.getNs11Code()); map.put("searchBy", searchService.execSearchBy(request, response)); map.put("searchWithinDate", searchService.execSearchWithinDate(request, response)); map.put("searchByDate", searchService.execSearchByDate(request, response)); return "bankstatement/index"; } @RequestMapping(value = "/upload", method = RequestMethod.GET) public String uploadGet(ModelMap map, HttpServletRequest request) { Subject subject = authService.getSubject(); map.put("userName", subject.getName()); map.put("userRole", subject.getRole()); map.put("ns10Code", subject.getNs10Code()); map.put("ns11Code", subject.getNs11Code()); return "bankstatement/upload"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadPost(@RequestParam("file") MultipartFile uploadedFile, ModelMap map, HttpServletRequest request) { try { File file = null; /** * Upload file */ // FileItemFactory factory = new DiskFileItemFactory(); // ServletFileUpload upload = new ServletFileUpload(factory); // List<FileItem> formItems = upload.parseRequest(request); // Iterator iterator = formItems.iterator(); // while(iterator.hasNext()){ // FileItem item = (FileItem) iterator.next(); // if(!item.isFormField()){ // File uploadedFile = new File(item.getName()); // // String filePath = bankStatementService.getUploadDir() + File.separator + uploadedFile.getName(); // file = new File(filePath); // item.write(file); // break; // } // } String filePath = bankStatementService.getUploadDir() + File.separator + uploadedFile.getOriginalFilename(); file = new File(filePath); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file)); stream.write(uploadedFile.getBytes()); stream.close(); String messages; if (file.getName().endsWith(".xls")) { // for payment manual, excel file String ip = authService.getClientIp(request); if (!authService.isAllowedByPropertyIp("bank_statement_payment_manual_allowed_ips", ip)) { throw new Exception(messageSource.getMessage("upload.you_have_not_privelege_to_upload_excel", null, LocaleContextHolder.getLocale())); } /** * Parse and Save */ Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue(); String issuerIp = authService.getClientIp(request); paymentService.parseAndSavePaymentManual(file, issuerSerialNumber, issuerIp); /** * Backup and Release uploads */ bankStatementService.backupAndRelease(file, null); messages = messageSource.getMessage("upload.file_successfull_uploded", null, LocaleContextHolder.getLocale()); } else { /** * Extract file */ File extractedFile = bankStatementService.extractedFile(file); /** * Parse and Save */ Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue(); String issuerIp = authService.getClientIp(request); messages = bankStatementService.parseAndSave(extractedFile, issuerSerialNumber, issuerIp); /** * Backup and Release uploads */ bankStatementService.backupAndRelease(file, extractedFile); if (messages.isEmpty()) { messages = messageSource.getMessage("upload.file_successfull_uploded", null, LocaleContextHolder.getLocale()); } else { messages = messageSource.getMessage("upload.file_successfull_uploded", null, LocaleContextHolder.getLocale()) + "<br/>" + messages; } } map.put("info", messages); } catch (Exception e) { logger.error(e.getMessage()); map.put("reason", e.getMessage().replace("\n", ";").replace("\r", ";")); } return "bankstatement/upload"; } @RequestMapping(value = "/list", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> list(HttpServletRequest request, HttpServletResponse response) { HashMap<String, Object> resMap = new LinkedHashMap<String, Object>(); try { // for saving search parameters searchService.execSearchBy(request, response); searchService.execSearchWithinDate(request, response); searchService.execSearchByDate(request, response); Map<String, String[]> map = request.getParameterMap(); HashMap<String, String> parameters = new HashMap<>(); for (String key : map.keySet()) { String[] mapValue = map.get(key); parameters.put(key, mapValue[0]); } resMap.put("success", true); resMap.put("draw", request.getParameter("draw")); resMap.put("data", bankStatementService.getList(parameters)); } catch (Exception e) { logger.error(e.getMessage()); resMap.put("success", false); resMap.put("reason", e.getMessage()); } return resMap; } @RequestMapping(value = "/edit-payment-date", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> editPaymentDate(HttpServletRequest request, HttpServletResponse response) { HashMap<String, Object> resMap = new LinkedHashMap<String, Object>(); try { String id = request.getParameter("pk"); Date paymentDate = new SimpleDateFormat("dd.MM.yyyy").parse(request.getParameter("value")); Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue(); String issuerIp = authService.getClientIp(request); bankStatementService.editPaymentDate(id, paymentDate, issuerSerialNumber, issuerIp); resMap.put("success", true); } catch (Exception e) { logger.error(e.getMessage()); resMap.put("success", false); resMap.put("reason", e.getMessage()); } return resMap; } @RequestMapping(value = "/edit-action-key", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> editActionKey(HttpServletRequest request, HttpServletResponse response) { HashMap<String, Object> resMap = new LinkedHashMap<String, Object>(); try { String bankStatementId = request.getParameter("pk"); String tin = request.getParameter("value"); Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue(); String issuerIp = authService.getClientIp(request); bankStatementService.editActionKey(bankStatementId, tin, issuerSerialNumber, issuerIp); resMap.put("success", true); } catch (Exception e) { logger.error(e.getMessage()); resMap.put("success", false); resMap.put("reason", e.getMessage()); } return resMap; } @RequestMapping(value = "/remove", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> remove(HttpServletRequest request, HttpServletResponse response) { HashMap<String, Object> resMap = new LinkedHashMap<String, Object>(); try { String ip = authService.getClientIp(request); if (!authService.isAllowedByPropertyIp("bank_statement_remove_allowed_ips", ip)) { throw new Exception( messageSource.getMessage("bank_statement.editable.you_have_not_privelege_to_remove", null, LocaleContextHolder.getLocale())); } String id = request.getParameter("id"); bankStatementService.remove(id); resMap.put("success", true); } catch (Exception e) { logger.error(e.getMessage()); resMap.put("success", false); resMap.put("reason", e.getMessage()); } return resMap; } @RequestMapping(value = "/view-invoice", method = RequestMethod.POST) public String viewInvoice(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception { List<InvoicePojo> items; String type = request.getParameter("type"); if ("single".equals(type)) { String bankStatementId = request.getParameter("bankStatementId"); items = bankStatementService.getSingleInvoice(bankStatementId); } else { Integer year = Integer.parseInt(request.getParameter("year")); Long from = Long.parseLong(request.getParameter("from")); Long to = Long.parseLong(request.getParameter("to")); items = bankStatementService.getFullInvoice(year, from, to); } map.put("items", items); return "/bankstatement/invoice" + LayoutInterceptor.WITHOUT_LAYOUT; } @RequestMapping(value = "/year", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> year(HttpServletRequest request, HttpServletResponse response) { HashMap<String, Object> resMap = new LinkedHashMap<String, Object>(); try { List<Map<String, Integer>> data = new ArrayList<>(); int year = Calendar.getInstance().get(Calendar.YEAR); for (int i = year; i >= year - 1; i--) { Map<String, Integer> record = new HashMap<>(); record.put("code", i); record.put("name", i); data.add(record); } resMap.put("success", true); resMap.put("data", data); } catch (Exception e) { logger.error(e.getMessage()); resMap.put("success", false); resMap.put("reason", e.getMessage()); } return resMap; } @RequestMapping(value = "/print-excel", method = RequestMethod.POST) public void printExcel(HttpServletRequest request, HttpServletResponse response) throws Exception { HSSFWorkbook workbook = null; String fileName; if ("paymentManual".equals(request.getParameter("type"))) { String bankStatementId = request.getParameter("bankStatementId"); BankStatement bs = bankStatementService.getBankStatementForPaymentManual(bankStatementId); workbook = bankStatementPrintService.printPaymentManual(bs); fileName = "PAYMENT_MANUAL_" + new SimpleDateFormat("dd.MM.yyyy HH-mm-ss").format(Calendar.getInstance().getTime()); } else { SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); Date periodStart = sdf.parse(request.getParameter("periodStart")); Date periodEnd = sdf.parse(request.getParameter("periodEnd")); switch (request.getParameter("type")) { case "claim": { List<PrintClaimPojo> listPojo = bankStatementService.getPrintClaimList(periodStart, periodEnd); workbook = bankStatementPrintService.printClaim(listPojo); break; } case "register": { List<PrintRegisterPojo> listPojo = bankStatementService.getPrintRegisterList(periodStart, periodEnd); workbook = bankStatementPrintService.printRegister(listPojo); break; } case "claimRegister": { List<PrintClaimRegisterPojo> listPojo = bankStatementService.getPrintClaimRegisterList(periodStart, periodEnd); workbook = bankStatementPrintService.printClaimRegister(listPojo); break; } } fileName = new SimpleDateFormat("dd.MM.yyyy HH-mm-ss").format(Calendar.getInstance().getTime()); } response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\""); response.addHeader("Cache-Control", "max-age=1, must-revalidate"); response.addHeader("Pragma", "no-cache"); OutputStream stream = response.getOutputStream(); workbook.write(stream); } }