com.nec.harvest.controller.PettyCashbookReportController.java Source code

Java tutorial

Introduction

Here is the source code for com.nec.harvest.controller.PettyCashbookReportController.java

Source

/*
 * Copyright(C) 2014
 * NEC Corporation All rights reserved.
 * 
 * No permission to use, copy, modify and distribute this software
 * and its documentation for any purpose is granted.
 * This software is provided under applicable license agreement only.
 */
package com.nec.harvest.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import com.nec.core.exception.ObjectNotFoundException;
import com.nec.harvest.bean.mapping.PettyCashbookReportBean;
import com.nec.harvest.bean.mapping.form.PettyCashBookForm;
import com.nec.harvest.bean.mapping.json.JSONBean;
import com.nec.harvest.constant.Constants;
import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.http.HttpServletContentType;
import com.nec.harvest.jasperreport.resolver.JasperReportResolver;
import com.nec.harvest.menu.group.DailyReportingProGroup;
import com.nec.harvest.model.PettyCashBookReport;
import com.nec.harvest.service.OrganizationService;
import com.nec.harvest.stereotype.SessionAttribute;
import com.nec.harvest.util.StringUtil;
import com.nec.harvest.uuid.GenerateUUID;

/**
 * @author sondn
 *
 */
@Controller
@RequestMapping(value = Constants.PETTY_CASHBOOK_REPORT_PATH)
public class PettyCashbookReportController extends DailyReportingProGroup
        implements AbstractRenderer, TitleRenderer {

    private static final Logger logger = LoggerFactory.getLogger(PettyCashbookReportController.class);

    private static final String TEMPLATE_PATH = "/jasperreports/petty-cashbook-report.jrxml";
    private static final String PDF_EXTENSION = ".pdf";
    private static final String SPACE_FULL = "  ";

    private static final char ZERO_CHAR = '0';

    private static final String DEVICE_TABLET = "TABLET";
    private static final String DEVICE_DESKTOP = "DESKTOP";

    private static String REPORT_TITLE;

    private static File reportToPdfFile;

    private final OrganizationService organizationService;

    private final JasperReportResolver jasperReportResolver;

    @Inject
    public PettyCashbookReportController(OrganizationService organizationService,
            JasperReportResolver jasperReportResolver) {
        this.organizationService = organizationService;
        this.jasperReportResolver = jasperReportResolver;
    }

    @Value(Constants.PDF_REPORT_TITLE)
    public void setReportTitle(String reportTitle) {
        PettyCashbookReportController.REPORT_TITLE = reportTitle;
    }

    /**
     * Default mapping without path variables for REPORT
     * 
     * @param request
     *            HttpServletRequest
     * @param response
     *            HttpServletResponse
     * @param model
     *            Spring model that can be used to render a view
     * @return A redirect URL
     */
    @Override
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
            @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
        if (logger.isDebugEnabled()) {
            logger.debug("Redering petty cash book report...");
        }

        // Build a link to redirect
        UriComponents uriComponent = UriComponentsBuilder.fromUriString(Constants.KOGUCHI_PATH).build();
        URI uri = uriComponent.expand(proGNo).encode().toUri();
        return "redirect:" + uri.toString();
    }

    /**
     * ????PDF?
     * 
     * @param orgCode
     *            String
     * @param response
     *            HttpServletResponse
     * @param device      
     *            Device
     * @param model     
     *            Model
     * @param pettyCashBookForm
     *            PettyCashBookForm
     * @return JSONBean
     */
    @RequestMapping(value = "/area", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JSONBean getDistrictInformation(@RequestBody final PettyCashBookForm pettyCashBookForm,
            final HttpServletResponse response, final Device device, final Model model) {
        if (logger.isDebugEnabled()) {
            logger.debug("Trying to rendering report...");
        }

        PettyCashBookReport pettyCashBook = null;

        // ??
        try {
            pettyCashBook = organizationService.findDistrictByShop(pettyCashBookForm.getShopCode());
            if (pettyCashBook != null) {
                logger.info("There is a organization {} in the DB", pettyCashBook.getStrCode());
            }
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // Ignore this CASE. If the database is not exist then can be showed empty
            pettyCashBook = new PettyCashBookReport();
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

            // ???????????
            return new JSONBean(Boolean.FALSE, -1, getSystemError());
        }

        List<PettyCashbookReportBean> pettyCashBookTmpLst = pettyCashBookForm.getPettyCashbookReportBean();
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        response.setCharacterEncoding(HttpServletContentType.DEFAULT_ENCODING);

        // PDF generate UUID
        final String PDF_UUID = GenerateUUID.randomUUID();

        // ??DD/MM/YYYY????
        Locale locale = new Locale("en", "EN", "EN");
        parameterMap.put(JRParameter.REPORT_LOCALE, locale);

        // 
        List<PettyCashbookReportBean> pettyCashFlLst = new ArrayList<PettyCashbookReportBean>(
                pettyCashBookTmpLst.size());
        PettyCashbookReportBean ptRptBean;

        // ??
        Map<String, String> grpItem = new HashMap<String, String>();

        // ??
        Double tmpKingaku = 0.0;

        // x,xxx???
        DecimalFormat formatter = new DecimalFormat("#,###");
        for (PettyCashbookReportBean subPtCh : pettyCashBookTmpLst) {
            if (!grpItem.containsKey(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()))) {
                if (StringUtils.isEmpty(subPtCh.getCltAmount())) {
                    grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), "0");
                } else {
                    // Modified by SONDN 2014-08-22
                    // Fixing bug CT-005: Allow end user input minus number
                    //               grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), 
                    //                     formatter.format(Double.valueOf(subPtCh.getCltAmount().replaceAll("[^0-9]", StringUtils.EMPTY))));

                    grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()),
                            formatter.format(Double.valueOf(StringUtil.removeCommaChar(subPtCh.getCltAmount()))));
                }
            } else {
                // Modified by SONDN 2014-08-22
                // Fixing bug CT-005: Allow end user input minus number
                //            tmpKingaku = Double.valueOf(grpItem.get(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName())).replaceAll("[^0-9]", StringUtils.EMPTY));
                //            if (!StringUtils.isEmpty(subPtCh.getCltAmount())) {
                //               tmpKingaku = tmpKingaku + Double.valueOf(subPtCh.getCltAmount().replaceAll("[^0-9]", StringUtils.EMPTY));
                //            }

                tmpKingaku = Double.valueOf(StringUtil.removeCommaChar(
                        grpItem.get(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()))));
                if (!StringUtils.isEmpty(subPtCh.getCltAmount())) {
                    tmpKingaku = tmpKingaku + Double.valueOf(subPtCh.getCltAmount());
                }
                grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()),
                        formatter.format(tmpKingaku));
            }
        }

        StringBuilder tmpStrDate;
        for (PettyCashbookReportBean childPtCh : pettyCashBookTmpLst) {
            ptRptBean = new PettyCashbookReportBean();

            // 
            ptRptBean.setKamokuCode(childPtCh.getCltItemCode());

            // ??
            String cltItemName = childPtCh.getCltItemName();
            if (StringUtils.isNotEmpty(cltItemName)) {
                ptRptBean.setKamokuName(SPACE_FULL.concat(cltItemName.substring(1)));
            } else {
                ptRptBean.setKamokuName(StringUtils.EMPTY);
            }

            // ?
            String cltAmount = childPtCh.getCltAmount();
            if (StringUtils.isNotEmpty(cltAmount)) {
                ptRptBean.setKingaku(formatter.format(Double.valueOf(cltAmount)));
            } else {
                ptRptBean.setKingaku(StringUtils.EMPTY);
            }

            // ??
            ptRptBean.setNaiyou(childPtCh.getCltContent());
            ptRptBean.setShito(childPtCh.getCltRemark());

            // 
            String cltDate = childPtCh.getCltDate();
            if (StringUtils.isNotEmpty(cltDate)) {
                tmpStrDate = new StringBuilder(cltDate.substring(5));
                if (ZERO_CHAR == tmpStrDate.charAt(0)) {
                    tmpStrDate.deleteCharAt(0);
                }

                int zeroCharPos = tmpStrDate.length() - 2;
                if (ZERO_CHAR == tmpStrDate.charAt(zeroCharPos)) {
                    tmpStrDate.deleteCharAt(zeroCharPos);
                }

                ptRptBean.setSrDate(tmpStrDate.toString());
            } else {
                ptRptBean.setSrDate(StringUtils.EMPTY);
            }

            // ?
            ptRptBean.setSumPrice(StringUtils.EMPTY);

            // 
            ptRptBean.setGrpFlg(Boolean.FALSE);
            ptRptBean.setGrpItemCode(StringUtils.EMPTY);
            ptRptBean.setGrpItemName(StringUtils.EMPTY);
            ptRptBean.setGrpCash(StringUtils.EMPTY);
            ptRptBean.setDetailLine(Boolean.FALSE);

            pettyCashFlLst.add(ptRptBean);
        }

        pettyCashFlLst.get(pettyCashFlLst.size() - 1).setDetailLine(Boolean.FALSE);

        // ? 
        ptRptBean = new PettyCashbookReportBean();
        ptRptBean.setSumPrice(pettyCashBookForm.getVerticalTotal());
        ptRptBean.setGrpFlg(Boolean.FALSE);
        ptRptBean.setDetailLine(Boolean.FALSE);
        pettyCashFlLst.add(ptRptBean);

        // 
        ptRptBean = new PettyCashbookReportBean();
        ptRptBean.setGrpFlg(Boolean.FALSE);
        //ptRptBean.setDetailLine(Boolean.TRUE);
        ptRptBean.setDetailLine(Boolean.FALSE);
        pettyCashFlLst.add(ptRptBean);

        // 
        ptRptBean = new PettyCashbookReportBean();
        ptRptBean.setGrpFlg(Boolean.TRUE);
        ptRptBean.setDetailLine(Boolean.TRUE);
        pettyCashFlLst.add(ptRptBean);

        // ????
        SortedSet<String> grpItemSorted = new TreeSet<String>(grpItem.keySet());
        for (String key : grpItemSorted) {
            ptRptBean = new PettyCashbookReportBean();
            ptRptBean.setGrpItemCode(key.split(PDF_UUID)[0]);
            ptRptBean.setGrpItemName(SPACE_FULL.concat(key.split(PDF_UUID)[1]));
            ptRptBean.setGrpCash(grpItem.get(key));
            ptRptBean.setGrpFlg(Boolean.FALSE);
            ptRptBean.setDetailLine(Boolean.FALSE);
            pettyCashFlLst.add(ptRptBean);
        }

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(pettyCashFlLst);

        // ?
        parameterMap.put("screenTitle", REPORT_TITLE);

        // 
        try {
            // ??????
            Locale.setDefault(new Locale("ja", "JP", "JP"));
            Date gregorianDate = new SimpleDateFormat("yyyy", Locale.ENGLISH).parse(pettyCashBookForm.getYear());
            SimpleDateFormat format = new SimpleDateFormat("GGGGyyyy");

            // 
            String tmpYearOriginal = format.format(gregorianDate);
            if (tmpYearOriginal.length() > 2) {
                parameterMap.put("year", tmpYearOriginal.substring(0, tmpYearOriginal.length() - 2));
                parameterMap.put("yearName", tmpYearOriginal.substring(tmpYearOriginal.length() - 2));
            } else {
                parameterMap.put("year", StringUtils.EMPTY);
                parameterMap.put("yearName", StringUtils.EMPTY);

                // 
                logger.warn("Original year {} is null or empty", tmpYearOriginal);
            }

        } catch (ParseException ex) {
            logger.warn("There is error happend when convert to Japanese's calendar format" + ex.getMessage());

            // Reset the locale
            Locale.setDefault(new Locale("en", "EN", "EN"));
        } catch (Exception ex) {
            logger.warn(ex.getMessage());

            // Reset the locale
            Locale.setDefault(new Locale("en", "EN", "EN"));
            return new JSONBean(Boolean.FALSE, -1, getSystemError());
        }

        // 
        parameterMap.put("month", pettyCashBookForm.getMonth());
        parameterMap.put("jRdataSource", JRdataSource);

        // 
        parameterMap.put("districtCode", pettyCashBook.getStrCode());
        // ??
        if (pettyCashBook.getStrNameR() != null && !StringUtils.isEmpty(pettyCashBook.getStrNameR())) {
            parameterMap.put("districtName",
                    pettyCashBook.getStrNameR().length() > 10 ? pettyCashBook.getStrNameR().subSequence(0, 10)
                            : pettyCashBook.getStrNameR());
        } else {
            parameterMap.put("districtName", StringUtils.EMPTY);
        }

        // 
        parameterMap.put("shopCode", pettyCashBookForm.getShopCode());
        // ??
        parameterMap.put("shopName", pettyCashBookForm.getShopName());
        // ???
        String totalDefault = pettyCashBookForm.getTotalDefault();
        parameterMap.put("settingAmount",
                StringUtils.isNotEmpty(totalDefault) ? totalDefault.substring(1) : StringUtils.EMPTY);
        // 
        parameterMap.put("Atotal", pettyCashBookForm.getVerticalTotal());
        // 
        String balance = pettyCashBookForm.getBalance();
        parameterMap.put("Abalance", StringUtils.isNotEmpty(balance) ? balance.substring(1) : StringUtils.EMPTY);
        Locale.setDefault(new Locale("en", "EN", "EN"));

        OutputStream output = null;

        try {

            JasperDesign jasperDesign = JRXmlLoader.load(getClass().getResourceAsStream(TEMPLATE_PATH));
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameterMap, JRdataSource);

            reportToPdfFile = new File(
                    jasperReportResolver.getReportPath() + File.separator + PDF_UUID + PDF_EXTENSION);
            if (logger.isDebugEnabled()) {
                logger.debug("Absolute path {}", reportToPdfFile.getAbsolutePath());
            }
            output = new FileOutputStream(reportToPdfFile);

            // PDF??
            JasperExportManager.exportReportToPdfStream(jasperPrint, output);
        } catch (JRException | IOException ex) {
            logger.error("PDF file doesn't exist", ex.getMessage());
            // PDF????????
            return new JSONBean(Boolean.FALSE, -1,
                    "PDF????????");
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException ex) {
                logger.warn("?????", ex.getMessage());
                // ?????
                return new JSONBean(Boolean.FALSE, -1, "?????");
            }
        }

        String kindOfDevice = device.isTablet() ? DEVICE_TABLET : DEVICE_DESKTOP;
        // Successfully created PDF
        return new JSONBean(Boolean.TRUE, kindOfDevice, PDF_UUID);
    }

    /**
     * PDF??
     * 
     * @param pdfUUID
     *            String
     * @param request
     *            HttpServletRequest
     * @param response
     *            HttpServletResponse
     * @param orgCode
     *            String
     * @param model
     *            Model
     * @param userOrgCode
     *            String
     */
    @RequestMapping(value = "/{orgCode}/{pdfUUID}", method = RequestMethod.GET)
    public void viewReport(@PathVariable String orgCode, @PathVariable String pdfUUID,
            final HttpServletResponse response) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("PDF??");
        }

        String fileURL = jasperReportResolver.getReportPath() + File.separator + pdfUUID + PDF_EXTENSION;
        String reportName = URLEncoder.encode(getTitleName(), HttpServletContentType.DEFAULT_ENCODING);

        // ??
        response.setHeader("Content-disposition", "inline; filename=" + reportName + PDF_EXTENSION);
        response.setContentType(HttpServletContentType.APPLICATION_PDF);
        response.setCharacterEncoding(HttpServletContentType.DEFAULT_ENCODING);

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            URL url = new File(fileURL).toURI().toURL();

            // Use Buffered Stream for reading/writing.
            bis = new BufferedInputStream(url.openStream());
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final MalformedURLException ex) {
            logger.warn(ex.getMessage());
            throw ex;
        } catch (final IOException ex) {
            logger.warn(ex.getMessage());
            throw ex;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }

    @Override
    public String getViewName() {
        return null;
    }

    @Override
    public String getTitleName() {
        return "? ???? ??";
    }
}