/**********************************************************************************
 * 프로그램명 : FileDelete.java 작 성 자 : 강원중 작 성 일 : 2003. 7.23 최신변경일 : 2003. 5.14
 ***********************************************************************************/

package kr.co.kihyun.beans.totsys.board;

import java.io.File;
//import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
//import java.util.Map;
import java.util.Map.Entry;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.co.kihyun.beans.entity.Board;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.util.PMF;
import kr.co.kihyun.io.IUploadable;

import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.board.HttpFileDelete")
public class HttpFileDelete extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpFileDelete.class);

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		res.setContentType("text/html");
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();

		String svrFilename = Encoder.toJava(req.getParameter("fileList"));
		String boardGroupID = req.getParameter("boardGroupID");
		Long docID = MLong.parseLong(req.getParameter("docID"));
		Long reportID = MLong.parseLong(req.getParameter("reportID"));
		Long boardID = MLong.parseLong(req.getParameter("boardID"));
		String mode = MString.checkNull(req.getParameter("mode"));
                int maxSize = MInteger.parseInt(req.getParameter("maxSize"));
		LOG.debug("delete file list: {}, docID: {}, reportID: {}, boardID: {}",
		new Object[] {svrFilename, docID, reportID, boardID});

		try {
			if (svrFilename != null) {
                            
                        //3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Add by KWON,HAN
                        LOG.debug("svrFilename: {}", svrFilename); 
                        if(svrFilename.contains("..") || svrFilename. contains("/")) { // 특수문자열 검증
                            LOG.debug("HttpFileDelete doPost ===");
                            LOG.debug("3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Not Test {}", svrFilename);
                            LOG.debug("=========================");
                            return;
                        }
                        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                                
				if ("csv".equals(mode)) {
					File file = new File(MoumiConfig.getCsvFileRoot(), svrFilename);
					if (!file.delete())
						throw new IOException(svrFilename + " delete failed.");
				} else {
					PersistenceManager pm = PMF.get().getPersistenceManager();
					Transaction tx = pm.currentTransaction();
					try {
						tx.begin();
						IUploadable uploadable = null;
						if (docID != null) {
							uploadable = pm.getObjectById(TotDoc.class, docID);
						} else if (reportID != null) {
							uploadable = pm.getObjectById(TotReport.class, reportID);
						} else if (boardID != null) {
							uploadable = pm.getObjectById(Board.class, boardID);
						}
						if (uploadable.removeAttachment(svrFilename) == null) {
							LOG.error("{} does not deleted.", svrFilename);
							throw new ServletException(svrFilename + " does not deleted.");
						}
						pm.makePersistent(uploadable);
						for (Entry<String, List<Byte>> entry : uploadable.getAttachments().entrySet())
							LOG.debug("key: {}", entry.getKey());
						tx.commit();
					} catch (Exception e) {
						if (tx.isActive())
							tx.rollback();
						pm.close();
					}
				}
			}

                    //v2. 1.HTTP 응답분할 : Update by KWON,HAN                         
//			res.sendRedirect("/totsys/common/inc/board/doc/write_file_upload.jsp?execMode=del&svrFilename="
//					+ svrFilename + "&usrFilename=" + svrFilename + "&boardGroupID=" + boardGroupID + "&docID="
//					+ docID + "&boardID=" + boardID + "&mode=" + mode + "&reportID=" + reportID + "&maxSize=" + maxSize);
                    if (svrFilename != null) {               
                        // 수정 : 외부 입력값 필터링
                        String filtered_svrFilename = svrFilename.replaceAll("\r","").replaceAll("\n","");      
                        LOG.debug("v2 1.HTTP 응답분할 : HttpFileDelete.doPost() filtered_svrFilename={} : Not Test", filtered_svrFilename);
			res.sendRedirect("/totsys/common/inc/board/doc/write_file_upload.jsp?execMode=del&svrFilename="
					+ filtered_svrFilename + "&usrFilename=" + filtered_svrFilename + "&boardGroupID=" + boardGroupID + "&docID="
					+ docID + "&boardID=" + boardID + "&mode=" + mode + "&reportID=" + reportID + "&maxSize=" + maxSize);
                    }                        
                    //========================================                          
                        
                //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 : Update by YOUNGJUN,CHO
                } catch (IOException ioex) {
                        ioex.printStackTrace();
                //================================================
                        
		} catch (Exception ex) {
			LOG.error("File delete failed: {}", ex.getMessage());
			out.println(
					ServletUtil.alert(
					MoumiConfig.getMessageBundle().getString("moumi.message.popup.fileDeleteFail"))
					+ ": " + ex.getMessage());
                        
                    //v2. 1.HTTP 응답분할 : Update by KWON,HAN                                  
//			res.sendRedirect("/totsys/common/inc/board/doc/write_file_upload.jsp?execMode=del&svrFilename="
//					+ svrFilename + "&usrFilename=" + svrFilename + "&boardGroupID=" + boardGroupID + "&docID="
//					+ docID + "&boardID=" + boardID + "&mode=" + mode + "&reportID=" + reportID + "&maxSize=" + maxSize);
                        
                    if (svrFilename != null) {               
                        // 수정 : 외부 입력값 필터링
                        String filtered_svrFilename = svrFilename.replaceAll("\r","").replaceAll("\n","");      
                        LOG.debug("v2 1.HTTP 응답분할 : HttpFileDelete.doPost() filtered_svrFilename={} : Test OK ", filtered_svrFilename);
			res.sendRedirect("/totsys/common/inc/board/doc/write_file_upload.jsp?execMode=del&svrFilename="
					+ filtered_svrFilename + "&usrFilename=" + filtered_svrFilename + "&boardGroupID=" + boardGroupID + "&docID="
					+ docID + "&boardID=" + boardID + "&mode=" + mode + "&reportID=" + reportID + "&maxSize=" + maxSize);
                    }                        
                    //========================================                         
		}
	}

}
