/*
 * 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 action;

import form.DownloadFileForm;
import java.io.File;
import java.io.FileInputStream;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author khanhdn1
 */
public class DownloadFileAction extends Action {

    private Logger logger = Logger.getLogger(DownloadFileAction.class);

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        DownloadFileForm frm = (DownloadFileForm) form;
        request.setAttribute("statusResultDownloadFile", "error");
        request.setAttribute("descErrorDownloadFile", "");

        String fileName = frm.getFileName();

        if (fileName == null) {
            logger.error("FileName is empty");
            request.setAttribute("descErrorDownloadFile", "FileName is empty");
            return mapping.findForward("resultDownloadFile");
        }

//        Pattern pattern = Pattern.compile("[^a-zA-Z0-9.-_]");
//        Pattern pattern = Pattern.compile("[^/./\\:*?\"<>|]");
        Pattern pattern = Pattern.compile("[^-_.A-Za-z0-9]");
        if (pattern.matcher(fileName).find()) {
            logger.error("FileName chứa ký tự đặc biệt");
            request.setAttribute("descErrorDownloadFile", "FileName chứa ký tự đặc biệt");
            return mapping.findForward("resultDownloadFile");
        }

        //Get the servers upload directory real path name
        String folderPath = getServlet().getServletContext().getRealPath("/") + "upload";
        String fileFullPath = folderPath + "/" + fileName;
        //create the upload folder if not exists
        logger.info("fileFullPath: " + fileFullPath);
        File fileDownload = new File(fileFullPath);
        if (!fileDownload.exists()) {
            logger.error("File không tồn tại");
            request.setAttribute("descErrorDownloadFile", "File không tồn tại");
            return mapping.findForward("resultDownloadFile");
        }
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            FileInputStream in = null;

            try {
                in = new FileInputStream(fileDownload);
                byte outputByte[] = new byte[(int) fileDownload.length()];
                while (in.read(outputByte) != -1) {
                    response.getOutputStream().write(outputByte);
                }
                logger.info("sendCertToClient(): flush file request statistics to client success");
            } catch (Exception e) {
                logger.error("Download File thất bại", e);
                request.setAttribute("descErrorDownloadFile", "Download File thất bại");
                return mapping.findForward("resultDownloadFile");
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } catch (Exception e) {
            logger.error("Download File thất bại", e);
            request.setAttribute("descErrorDownloadFile", "Download File thất bại");
            return mapping.findForward("resultDownloadFile");
        }

        request.setAttribute("statusResultDownloadFile", "success");
        return mapping.findForward("resultDownloadFile");
    }
}
