package itn.let.fax.addr.web; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; 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 javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper; import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo; import itn.com.cmm.EgovMessageSource; import itn.com.cmm.JsonResult; import itn.com.cmm.LoginVO; import itn.com.cmm.util.MJUtil; import itn.com.cmm.util.StringUtil; import itn.com.utl.fcc.service.EgovStringUtil; import itn.let.fax.addr.service.FaxAddrGroupService; import itn.let.fax.addr.service.FaxAddrGroupVO; import itn.let.fax.addr.service.FaxAddrService; import itn.let.fax.addr.service.FaxAddrTransHistVO; import itn.let.fax.addr.service.FaxAddrVO; import itn.let.mjo.msgdata.service.PhoneVO; @Controller public class FaxAddrController { @Resource (name = "FaxAddrService") private FaxAddrService faxAddrService; @Resource (name = "FaxAddrGroupService") private FaxAddrGroupService faxAddrGroupService; /** EgovMessageSource */ @Resource(name="egovMessageSource") EgovMessageSource egovMessageSource; /** * 주소록 타 회원으로 이전(복사) 처리 * @param addrVO * @param addrGroupVO * @param addrTransHistVO * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/transFaxAddrGroupAjax.do") public ModelAndView transFaxAddrGroupAjax(FaxAddrVO addrVO, FaxAddrGroupVO addrGroupVO, FaxAddrTransHistVO addrTransHistVO) throws Exception { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); try { String successCd = faxAddrService.updateFaxAddrAnotherMember(addrVO, addrGroupVO, addrTransHistVO); modelAndView.addObject("status", "success"); modelAndView.addObject("result", successCd); }catch(Exception e) { e.printStackTrace(); modelAndView.addObject("status", "fail"); return modelAndView; } return modelAndView; } /** * 팩스 주소록 사용자 화면 껍데기 * @param FaxAddrVO * @param model * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/selectFaxAddrList.do") public String selectFaxAddrWebList(@ModelAttribute("searchVO") FaxAddrVO faxAddrVO , FaxAddrGroupVO faxAddrGroupVO, ModelMap model, RedirectAttributes redirectAttributes) throws Exception { LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId == "") { /*redirectAttributes.addFlashAttribute("fail", true);*/ //redirectAttributes.addFlashAttribute("message", "문자온 서비스는 로그인 후 이용 가능합니다."); return "redirect:/web/user/login/login.do"; } return "/web/fax/addr/FaxAddrList"; } /** * 주소록 그룹 선택시 우측 주소록 리스트 화면 불러오기 * * @param AddrGroupVO * @param AddrVO * @param sessionVO * @param model * @return * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/selectFaxAddrListAjax.do"}) public ModelAndView selectMsgAddrListAjax( @ModelAttribute("searchVO") FaxAddrVO faxAddrVO, ModelMap model, RedirectAttributes redirectAttributes) throws Exception { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); //로그인 권한정보 불러오기 LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { faxAddrVO.setMberId(userId); }else { modelAndView.addObject("message", "로그인 후 이용이 가능합니다."); modelAndView.addObject("result", "loginFail"); return modelAndView; } try { List resultAddrList = faxAddrService.selectFaxAddrListAjax(faxAddrVO); modelAndView.addObject("resultAddrList", resultAddrList); modelAndView.addObject("result", "success"); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } return modelAndView; } /** * 사용자 팩스 주소록 리스트 Ajax * @param request * @param model * @param addrVO * @param redirectAttributes * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/selectFaxAddrAjax.do") public String selectFaxAddrAjax(HttpServletRequest request, ModelMap model, @ModelAttribute("searchVO") FaxAddrVO addrVO) throws Exception { //로그인 권한정보 불러오기 LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrVO.setMberId(userId); } if(addrVO.getPageUnit() != 10) { addrVO.setPageUnit(addrVO.getPageUnit()); } /** pageing */ PaginationInfo paginationInfo = new PaginationInfo(); paginationInfo.setCurrentPageNo(addrVO.getPageIndex()); paginationInfo.setRecordCountPerPage(addrVO.getPageUnit()); paginationInfo.setPageSize(addrVO.getPageSize()); addrVO.setFirstIndex(paginationInfo.getFirstRecordIndex()); addrVO.setLastIndex(paginationInfo.getLastRecordIndex()); addrVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage()); if("".equals(addrVO.getSearchSortCnd())){ //최초조회시 최신것 조회List addrVO.setSearchSortCnd("addrId"); addrVO.setSearchSortOrd("asc"); } System.out.println("=================================================="+addrVO.getSearchAddrGrpId()); List addrList = new ArrayList(); if(StringUtils.isNotEmpty(addrVO.getSearchAddrGrpId())) { addrList = faxAddrService.selectFaxAddrList(addrVO); } System.out.println("=================================================="); int totCnt = 0; if(addrList.size() > 0) { totCnt = addrList.get(0).getTotcnt(); } paginationInfo.setTotalRecordCount(totCnt); model.addAttribute("paginationInfo", paginationInfo); model.addAttribute("addrList", addrList); model.addAttribute("startKeyword",addrVO.getStartKeyword()); model.addAttribute("userId", userId); return "/web/fax/addr/FaxAddrListAjax"; } /** * 사용자 주소록 중복 리스트 Ajax * @param request * @param model * @param addrVO * @param redirectAttributes * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/selectFaxAddrDupliAjax.do") public String selectFaxAddrDupliAjax(HttpServletRequest request, ModelMap model, @ModelAttribute("searchVO") FaxAddrVO addrVO) throws Exception { //로그인 권한정보 불러오기 LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrVO.setMberId(userId); } if(addrVO.getPageUnit() != 10) { addrVO.setPageUnit(addrVO.getPageUnit()); } /** pageing */ PaginationInfo paginationInfo = new PaginationInfo(); paginationInfo.setCurrentPageNo(addrVO.getPageIndex()); paginationInfo.setRecordCountPerPage(addrVO.getPageUnit()); paginationInfo.setPageSize(addrVO.getPageSize()); addrVO.setFirstIndex(paginationInfo.getFirstRecordIndex()); addrVO.setLastIndex(paginationInfo.getLastRecordIndex()); addrVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage()); if("".equals(addrVO.getSearchSortCnd())){ //최초조회시 최신것 조회List addrVO.setSearchSortCnd("addrId"); addrVO.setSearchSortOrd("asc"); } List addrDupliList = faxAddrService.selectFaxAddrDupliListByAll(addrVO); int totCnt = 0; if(addrDupliList.size() > 0) { totCnt = addrDupliList.get(0).getTotcnt(); } paginationInfo.setTotalRecordCount(totCnt); model.addAttribute("paginationInfo2", paginationInfo); model.addAttribute("addrDupliList", addrDupliList); return "/web/fax/addr/FaxAddrListDupliAjax"; } @RequestMapping("/web/mjon/fax/addr/selectFaxAddrPrintAjax.do") public String selectFaxAddrPrint(@RequestParam("cellCheck2") String[] cellCheck, FaxAddrVO addrVO, HttpServletRequest request, HttpServletResponse response , ModelMap model) throws Exception { //로그인 권한정보 불러오기 LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrVO.setMberId(userId); } addrVO.setRecordCountPerPage(100000); addrVO.setFirstIndex(0); List addrList = faxAddrService.selectFaxAddrList(addrVO); String chk = ""; for(int i=0; i 0) { mv.addObject("result","dupl"); }else { if(userId != "") { try { faxAddrService.insertFaxAddr(addrVO); mv.addObject("result","success"); } catch (Exception e) { e.printStackTrace(); mv.addObject("result","fail"); } } else { mv.addObject("result","fail"); } } return mv; } /** * 주소록 다중수정 ajax * @param addrCheck * @param request * @param addrVO * @param model * @param redirectAttributes * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/updateFaxAddrListAjax.do") public ModelAndView updateFaxAddrListAjax(HttpServletRequest request, FaxAddrVO addrVO, Model model ,RedirectAttributes redirectAttributes ) throws Exception { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); addrVO.setLastUpdusrId(user.getId()); addrVO.setMberId(user.getId()); int listSize = addrVO.getAddrIds().length; for(int i=0; i 주소록그룹 수정 추가 if (addrVO.getAddrGrpIds()[i].equals("bookmark")) { // 자주보내는 번호 addrVO.setAddrGrpId("0"); addrVO.setBookmark("Y"); } else { addrVO.setAddrGrpId(addrVO.getAddrGrpIds()[i]); addrVO.setBookmark("N"); } addrVO.setAddrId(addrVO.getAddrIds()[i]); if(addrVO.getAddrPhones().length > 0) { addrVO.setAddrPhoneNo(addrVO.getAddrPhones()[i]); } else { addrVO.setAddrPhoneNo(null); } if(addrVO.getAddrNms().length > 0) { addrVO.setAddrNm(addrVO.getAddrNms()[i]); } else { addrVO.setAddrNm(null); } faxAddrService.updateFaxAddr(addrVO); modelAndView.addObject("result", "success"); } catch (Exception e) { e.printStackTrace(); modelAndView.addObject("result", "fail"); return modelAndView; } } return modelAndView; } /** * 주소록 다중수정 ajax * @param addrCheck * @param request * @param addrVO * @param model * @param redirectAttributes * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/updateFaxAddrAjax.do") public ModelAndView updateFaxAddrAjax(@RequestParam("addrCheck") String[] addrCheck, HttpServletRequest request, FaxAddrVO addrVO, Model model ,RedirectAttributes redirectAttributes ) throws Exception { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); addrVO.setLastUpdusrId(user.getId()); addrVO.setMberId(user.getId()); for(String id:addrCheck) { try { if("0".equals (addrVO.getAddrGrpId())) { addrVO.setBookmark("Y"); } else if(addrVO.getAddrGrpId() != null && !"".equals(addrVO.getAddrGrpId())) { addrVO.setBookmark("N"); } addrVO.setAddrId(id); faxAddrService.updateMemoFaxAddr(addrVO); modelAndView.addObject("result", "success"); } catch (Exception e) { e.printStackTrace(); modelAndView.addObject("result", "fail"); return modelAndView; } } return modelAndView; } /** * 주소록 그룹이동 ajax * @param addrCheck * @param request * @param addrVO * @param model * @param redirectAttributes * @return * @throws Exception */ @RequestMapping("/web/mjon/fax/addr/updateFaxAddrMoveGrpAjax.do") public ModelAndView updateFaxAddrMoveGrpAjax(@RequestParam("addrCheck") String[] addrCheck, @RequestParam("addrPhoneNos") String[] addrPhoneNos, HttpServletRequest request, FaxAddrVO addrVO, Model model, RedirectAttributes redirectAttributes ) throws Exception { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); addrVO.setLastUpdusrId(user.getId()); addrVO.setMberId(user.getId()); // 그룹미지정, 자주보내는 번호 구분처리 if("0".equals (addrVO.getAddrGrpId())) { // 그룹미지정 addrVO.setBookmark("N"); } else if("bookmark".equals (addrVO.getAddrGrpId())) { // 자주보내는 번호 addrVO.setBookmark("Y"); addrVO.setAddrGrpId("0"); } else if(addrVO.getAddrGrpId() != null && !"".equals(addrVO.getAddrGrpId())) { addrVO.setBookmark("N"); } /** * 보내려는 그룹에 등록되어있는 전화번호를 변수에 담아둠 */ List addrPhoneList = faxAddrService.selectPhoneNumInFaxAddrGroup(addrVO); String phoneNos = ""; for(int i=0; i addrPhoneList = faxAddrService.selectPhoneNumInFaxAddrGroup(addrVO); String phoneNos = ""; for(int i=0; i addrIdList = addrVO.getAddrIdList(); List tempList = new ArrayList(); for(String seqStr : addrIdList) { String seqId = seqStr.replace("[", ""); seqId = seqId.replace("]", ""); tempList.add(seqId); } addrVO.setAddrIdList(tempList); List resultList = faxAddrService.selectFaxAddrDataList(addrVO); if(resultList == null) { modelAndView.addObject("status", "emptyList"); modelAndView.addObject("message", "가져온 주소록 목록이 없습니다."); }else { modelAndView.addObject("status", "success"); modelAndView.addObject("resultList", resultList); modelAndView.addObject("resultListCnt", resultList.size()); } return modelAndView; } //주소록 엑셀 다운로드 @RequestMapping("/web/mjon/fax/addr/faxAddrExcelDownload.do") public void faxAddrExcelDownload(@RequestParam("cellCheck") String[] cellCheck, FaxAddrVO addrVO, HttpServletRequest request, HttpServletResponse response , ModelMap model) throws Exception { addrVO.setRecordCountPerPage(100000); addrVO.setFirstIndex(0); if("".equals(addrVO.getSearchSortCnd())){ //최초조회시 최신것 조회List addrVO.setSearchSortCnd("addrId"); addrVO.setSearchSortOrd("asc"); } LoginVO loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser(); // 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다. SXSSFWorkbook wb = new SXSSFWorkbook(100); CellStyle styleHeader = wb.createCellStyle(); styleHeader.setBorderBottom(CellStyle.BORDER_THIN); //테두리 두껍게 styleHeader.setBorderLeft(CellStyle.BORDER_THIN); styleHeader.setBorderRight(CellStyle.BORDER_THIN); styleHeader.setBorderTop(CellStyle.BORDER_THIN); CellStyle styleList = wb.createCellStyle(); Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); //글씨 bold Cell cell = null; Row row = null; String fileName ="주소록"; String sheetTitle = ""; try{ if("".equals(addrVO.getSearchSortCnd())){ //최초조회시 최신것 조회List addrVO.setSearchSortOrd("desc"); } addrVO.setMberId(loginVO.getId()); List addrList = faxAddrService.selectFaxAddrList(addrVO); { // row, cell 개수 순서대로 증가용 필드 int rowNumber = 0; int celNumber = 0; //화면 리스트 sheetTitle = "주소록" ; //제목 Sheet sheet = wb.createSheet(sheetTitle); row = sheet.createRow(rowNumber++); row = sheet.createRow(rowNumber++); //줄추가 //cell = row.createCell(celNumber++); //cell.setCellValue("번호"); //cell.setCellStyle(style); int y = 0; for(String field : cellCheck) { //셀 칼럼 크기 설정 sheet.setColumnWidth(y, 4000); cell = row.createCell(celNumber++); cell.setCellValue(addrVO.getHeaderName(field)); cell.setCellStyle(styleHeader); y++; } for(int i=0; i < addrList.size(); i++){ row = sheet.createRow(rowNumber++); //줄추가 celNumber = 0; //cell = row.createCell(celNumber++); //cell.setCellStyle(style); //cell.setCellValue(i+1); //번호 for(String field : cellCheck) { cell = row.createCell(celNumber++); cell.setCellStyle(styleList); cell.setCellValue(((FaxAddrVO)addrList.get(i)).getFieldValue(field)); } } } response.setHeader("Set-Cookie", "fileDownload=true; path=/"); SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ( "yyyy_MM_dd_HH_mm_ss", Locale.KOREA ); Date currentTime = new Date (); String mTime = mSimpleDateFormat.format ( currentTime ); fileName = fileName+"("+mTime+")"; response.setHeader("Content-Disposition", String.format("attachment; filename=\""+new String((fileName).getBytes("KSC5601"),"8859_1")+".xlsx")); wb.write(response.getOutputStream()); }catch(Exception e) { response.setHeader("Set-Cookie", "fileDownload=false; path=/"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setHeader("Content-Type","text/html; charset=utf-8"); OutputStream out = null; try { out = response.getOutputStream(); byte[] data = new String("fail..").getBytes(); out.write(data, 0, data.length); } catch(Exception ignore) { ignore.printStackTrace(); } finally { if(out != null) try { out.close(); } catch(Exception ignore) {} } }finally { // 디스크 적었던 임시파일을 제거합니다. wb.dispose(); try { wb.close(); } catch(Exception ignore) {} } } /** * 주소록 대량등록 - 엑셀파일 불러오기 * @param body * @param uploadFile * @param search * @param result * @param model * @param request * @return * @throws Exception */ @RequestMapping(value = "/web/mjon/fax/addr/sendExelFilePhoneNumAjax.do") @ResponseBody public Object sendExelFilePhoneNumAjax(final MultipartHttpServletRequest multiRequest) throws Exception { JsonResult jr = new JsonResult(); jr.setSuccess(false); jr.setMessage("엑셀 파일만 업로드할 수 있습니다."); try { //final Map files = multiRequest.getFileMap(); List files = (List) multiRequest.getFiles("file0"); // 파일명에 .이 있을경우 오류 => Ex) 테스트6.20.xlsx int fileNameSplitCnt = 0; if(!files.isEmpty()) { fileNameSplitCnt = files.get(0).getOriginalFilename().split("[.]").length; //System.out.println("fileNameSplitCnt : " + fileNameSplitCnt); if (files.get(0).getSize() > 0 && (files.get(0).getContentType().indexOf("spreadsheetml") > -1) || files.get(0).getContentType().indexOf("ms-excel") > -1 || files.get(0).getOriginalFilename().split("[.]")[fileNameSplitCnt-1].indexOf("xlsx") > -1 || files.get(0).getOriginalFilename().split("[.]")[fileNameSplitCnt-1].indexOf("xls") > -1) { // 엑셀 파일 용량 3MB이상 시 10만건 이상으로 서버가 다운되는 증상 발생 long fileSize = multiRequest.getFile("file0").getSize(); if(fileSize > 3374653) { jr.setMessage("엑셀 파일은 3MB를 넘을수 없습니다."); return jr; } String Ext = files.get(0).getOriginalFilename().split("[.]")[1]; String errMessage = ""; String cellValue = ""; String phoneRegExp = "^01(?:0|1|[6-9])[.-]?(\\d{3}|\\d{4})[.-]?(\\d{4})$"; //String phoneRegExp = "^(050[234567]{1}|01[016789]{1})-?[0-9]{3,4}-?[0-9]{4}$"; int errPhoneCnt = 0; int errNameCnt = 0; /*int errRep1Cnt = 0; int errRep2Cnt = 0; int errRep3Cnt = 0; int errRep4Cnt = 0;*/ int errMemoCnt = 0; //엑셀 확장자에 따른 처리 로직 분리 if(Ext.equals("xls")) { HSSFWorkbook workbook = new HSSFWorkbook(files.get(0).getInputStream()); HSSFSheet sheet = workbook.getSheetAt(0); if(sheet.getLastRowNum() > 20000) { // errMessage = "2만줄 이상의 업로드는 데이터 부하로 업로드 할수 없습니다."; jr.setSuccess(false); jr.setMessage(errMessage); return jr; } List> json = new ArrayList>(); PhoneVO pVO = new PhoneVO(); for(int i=2; i< sheet.getLastRowNum() + 2; i++){ //먼저 밸리데이션 체크(1줄은 생략) HSSFRow row = sheet.getRow(i); //열읽기 if(null == row) { continue; } HashMap jm = new HashMap<>(); // 행의 두번째 열(이름부터 받아오기) HSSFCell cell = null; boolean errSts = true; for(int j = 0 ; j < 3; j++){ //행읽기(6행까지나 2행까지만 필요) cellValue = ""; cell = row.getCell(j); //이름/핸드폰/info1/info2/info3/info4/메모 if(null == cell || "".equals(cell.toString().trim())) { //셀에 값이 없으면 if(j == 1) { if (sheet.getLastRowNum() == i) { continue; } //errPhoneCnt++; //errSts = false; break; } } if(null != cell){ switch(cell.getCellType()){ //숫자타임을 문자로 변환 case Cell.CELL_TYPE_NUMERIC: cell.setCellType(Cell.CELL_TYPE_STRING); } cellValue = StringUtil.getString(cell.getStringCellValue().trim()) ; } if(j == 0) { //이름 boolean nmChk = getNameRepLenChk("name", cellValue); if(nmChk && errSts) { jm.put("name", cellValue); }else { errNameCnt++; errSts = false; break; } } if(j == 1) { // 문자열에서 숫자만 추출 cellValue = getOnlyNumber(cellValue); //전화번호 if(MJUtil.checkFaxNum(cellValue) && errSts) {//휴대폼 번호 타입이 아닌 경우에만 저장 되도록 함 jm.put("phone", cellValue); }else { errPhoneCnt++; errSts = false; break; } } if(j == 2) { //메모 boolean repChk = getNameRepLenChk("memo", cellValue); if(repChk && errSts) { jm.put("memo", cellValue); }else { errMemoCnt++; errSts = false; break; } } } if(null != jm.get("phone")) { json.add(jm); } } int resultErrCnt = errPhoneCnt + errNameCnt + errMemoCnt; jr.setData(json); jr.setSuccess(true); if(resultErrCnt > 0) { jr.setMessage("올바르지 않은 팩스 번호가 "+ resultErrCnt +" 건 있습니다."); }else { jr.setMessage(""); } }else { //확장자가 xlsx OPCPackage opcPackage = OPCPackage.open(files.get(0).getInputStream()); XSSFWorkbook workbook = new XSSFWorkbook(opcPackage); XSSFSheet sheet = workbook.getSheetAt(0); // 첫번째 시트 불러오기 opcPackage.close(); //실제 데이터가 있는 셀의 갯수를 카운팅 한다.(팩스번호만 체크) int totRowDataCnt = 0; for(int r=1; r 20000) { // if(totRowDataCnt > 20001) { // errMessage = "2만줄 이상의 업로드는 데이터 부하로 업로드 할수 없습니다."; jr.setSuccess(false); jr.setMessage(errMessage); return jr; } List> json = new ArrayList>(); PhoneVO pVO = new PhoneVO(); //for(int i=2; i< sheet.getLastRowNum() + 2; i++){ //먼저 밸리데이션 체크(1줄은 생략) for(int i=2; i< totRowDataCnt + 2; i++){ //먼저 밸리데이션 체크(1줄은 생략) XSSFRow row = sheet.getRow(i); //열읽기 System.out.println(i); if(null == row) { continue; } HashMap jm = new HashMap<>(); // 행의 두번째 열(핸드폰부터 받아오기) XSSFCell cell = null; boolean errSts = true; for(int j = 0 ; j < 3; j++){ //행읽기(6행까지나 2행까지만 필요) cellValue = ""; cell = row.getCell(j); //이름/핸드폰/변환1/변환2/변환3/변환4/변환5/메모 if(null == cell || "".equals(cell.toString().trim())) { //셀에 값이 없으면 if(j == 1) { if (sheet.getLastRowNum() == i) { continue; } //errPhoneCnt++; //errSts = false; break; } } if(null != cell){ switch(cell.getCellType()){ //숫자타임을 문자로 변환 case Cell.CELL_TYPE_NUMERIC: cell.setCellType(Cell.CELL_TYPE_STRING); } cellValue = StringUtil.getString(cell.getStringCellValue().trim()) ; } if(j == 0) { //이름 boolean nmChk = getNameRepLenChk("name", cellValue); if(nmChk && errSts) { jm.put("name", cellValue); }else { errNameCnt++; errSts = false; break; } } if(j == 1) { // 문자열에서 숫자만 추출 cellValue = getOnlyNumber(cellValue); //전화번호 if(MJUtil.checkFaxNum(cellValue) && errSts) { jm.put("phone", cellValue); }else { errPhoneCnt++; errSts = false; break; } } if(j == 2) { //메모 boolean repChk = getNameRepLenChk("memo", cellValue); if(repChk && errSts) { jm.put("memo", cellValue); }else { errMemoCnt++; errSts = false; break; } } } if(null != jm.get("phone") && errSts) { json.add(jm); } } int resultErrCnt = errPhoneCnt + errNameCnt ; jr.setData(json); jr.setSuccess(true); if(resultErrCnt > 0) { jr.setMessage("올바르지 않은 팩스 번호가 "+ resultErrCnt +" 건 있습니다."); }else { jr.setMessage(""); } } //xlsx 처리 끝 } else { String ttt = files.get(0).getSize() + "_" + files.get(0).getContentType() + "_" + files.get(0).getOriginalFilename().split("[.]")[fileNameSplitCnt-1]; jr.setSuccess(false); jr.setMessage("엑셀파일 인식오류."); //jr.setMessage("엑셀파일 인식오류" + ttt); } } else { jr.setSuccess(false); jr.setMessage("엑셀파일 인식오류."); } return jr; } catch (Exception e) { System.out.println("+++++++++++++++ sendExelFilePhoneNumAjax Fax Controller Error!!! "+e); jr.setSuccess(false); jr.setMessage("엑셀파일 인식오류."); return jr; } } /** * 주소록 대량등록 - TXT파일 불러오기 * @param body * @param uploadFile * @param search * @param result * @param model * @param request * @return * @throws Exception */ @RequestMapping(value = "/web/mjon/fax/addr/sendTxtFilePhoneNumAjax.do") @ResponseBody public Object sendTxtFilePhoneNumAjax(final MultipartHttpServletRequest multiRequest) throws Exception { JsonResult jr = new JsonResult(); jr.setSuccess(false); jr.setMessage("TXT 파일만 업로드할 수 있습니다."); List files = (List) multiRequest.getFiles("file0"); if(!files.isEmpty()) { if (files.get(0).getSize() > 0 || files.get(0).getOriginalFilename().split("[.]")[1].indexOf("txt") > -1) { // txt 파일 용량 3MB이상 시 10만건 이상으로 서버가 다운되는 증상 발생 long fileSize = multiRequest.getFile("file0").getSize(); if(fileSize > 3374653) { jr.setMessage("txt 파일은 3MB를 넘을수 없습니다."); return jr; } BufferedReader reader = new BufferedReader(new InputStreamReader(multiRequest.getFile("file0").getInputStream())); String line = null; String[] splitedStr = null; String[] tempStr = null; int errPhoneCnt = 0; int totRowNum = 0; //String phoneRegExp = "^01(?:0|1|[6-9])[.-]?(\\d{3}|\\d{4})[.-]?(\\d{4})$"; //String phoneRegExp = "^(050[234567]{1}|01[016789]{1})-?[0-9]{3,4}-?[0-9]{4}$"; List> json = new ArrayList>(); //파일 읽어서 탭으로 구분해주기 while ((line = reader.readLine()) != null) { HashMap jm = new HashMap<>(); splitedStr = null; tempStr = null; //txt 파일의 데이터가 탭 혹은 콤마로 구분되어 있는지 구분처리 tempStr = line.split("\\,"); if(tempStr.length > 1) { splitedStr = line.split("\\,"); }else { splitedStr = line.split("\t");; } for (int i = 0; i < splitedStr.length; i++) { splitedStr[i] = splitedStr[i].trim(); if(i == 0) { //이름 jm.put("name", splitedStr[i]); } if(i == 1) { // 문자열에서 숫자만 추출 splitedStr[i] = getOnlyNumber(splitedStr[i]); if(MJUtil.checkFaxNum(splitedStr[i])) {//휴대폰번호 타입이 아닌 경우만 입력 되도록 함. //팩스 번호 jm.put("phone", splitedStr[i]); }else { errPhoneCnt++; } } if(i == 2) { //메모 jm.put("memo", splitedStr[i]); } } if(jm.get("phone") != null) { json.add(jm); } totRowNum++; } // end while jr.setData(json); jr.setSuccess(true); if (totRowNum > 20000) { jr.setMessage("20000"); } else { if(errPhoneCnt > 0) { jr.setMessage("올바르지 않은 팩스 번호가 "+ errPhoneCnt +" 건 있습니다."); }else { jr.setMessage(""); } } } } return jr; } /** * 주소록 대량등록 저장 * @param searchVO * @param model * @return "/web/mjon/addr/addrMassInsertByTempAjax.do" * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/faxAddrMassInsertByTempAjax.do"}) public ModelAndView faxAddrMassInsertByTempAjax(@ModelAttribute("searchVO") FaxAddrVO addrVO, RedirectAttributes redirectAttributes, ModelMap model) throws Exception{ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); String phoneRegExp = "^01(?:0|1|[6-9])[.-]?(\\d{3}|\\d{4})[.-]?(\\d{4})$"; //String phoneRegExp = "^(050[234567]{1}|01[016789]{1})-?[0-9]{3,4}-?[0-9]{4}$"; boolean isSuccess = true; String msg = ""; int resultCnt = 0; int dupliCnt = 0; // 중복 데이터 수 int errPhoneCnt = 0; List addrMassDupliList = new ArrayList(); // 중복 휴대폰번호 try { LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId.equals("")) { isSuccess = false; modelAndView.addObject("isSuccess", isSuccess); modelAndView.addObject("msg", "로그인 후 이용이 가능합니다."); return modelAndView; } else { addrVO.setMberId(userId); } //회원별 주소록 전체 갯수 조회 int addrBefAfterCnt = 0; int addrBefCnt = faxAddrService.selectFaxAddrTotalCount(addrVO); int addrNewCnt = addrVO.getPhoneList().length; //신규 추가할 주소록 갯수 int sumAddrCnt = addrBefCnt + addrNewCnt; //기존 + 신규 주소록 합산 // 신규 주소록 여부 체크 if (addrVO.getAddrGrpId().equals("NEW")) { FaxAddrGroupVO addrGroupVO = new FaxAddrGroupVO(); addrGroupVO.setMberId(userId); addrGroupVO.setAddrGrpNm(addrVO.getAddrGrpNm()); // 정렬순서 int nextOrderNumber = faxAddrGroupService.selectMaxOrderFaxNumber(addrGroupVO); addrGroupVO.setGrpOrder(nextOrderNumber); faxAddrGroupService.insertFaxAddrGroup(addrGroupVO); // 신규 추가한 그룹아이디 addrVO.setAddrGrpId(addrGroupVO.getAddrGrpId()); } // 그룹미지정, 자주보내는 번호 구분처리 if("bookmark".equals (addrVO.getAddrGrpId())) { // 자주보내는 번호 addrVO.setBookmark("Y"); addrVO.setAddrGrpId("0"); } else { addrVO.setBookmark("N"); } // 2024.01.24 10만건 -> 50만건으로 증설 요청으로 인한 증설 List addrDataInfo = new ArrayList(); if(addrBefCnt < 500000) { // 기존 등록된 주소록이 10만건 미만이면 //받는사람 리스트 건수 체크해주기 if(sumAddrCnt > 500000) { isSuccess = false; msg = "주소록은 총 50만개까지만 등록이 가능합니다."; } else { for(int i=0; i < addrNewCnt; i++) { FaxAddrVO tempAddrVO = new FaxAddrVO(); if(addrVO.getNameList().length > 0) { if(addrVO.getNameList()[i].equals("-")) { tempAddrVO.setAddrNm(null); }else { String tmpNm = addrVO.getNameList()[i].trim().replaceAll("§", ","); int nmLen = tmpNm.length(); if(nmLen > 12) { //isSuccess = false; //msg = "이름 항목의 내용(\" " + tmpNm + " \")이 길이를 초과하여 입력되었습니다. 12글자 이하로 입력해 주세요."; //break; tempAddrVO.setAddrNm(addrVO.getNameList()[i].trim().replaceAll("§", ",").substring(0, 12)); }else { tempAddrVO.setAddrNm(addrVO.getNameList()[i].trim().replaceAll("§", ",")); } } } else { tempAddrVO.setAddrNm(null); } if(addrVO.getPhoneList().length > 0) { if(addrVO.getPhoneList()[i].equals("-")) { tempAddrVO.setAddrPhoneNo(null); }else { tempAddrVO.setAddrPhoneNo(addrVO.getPhoneList()[i].trim().replaceAll("§", ",")); } } else { tempAddrVO.setAddrPhoneNo(null); } if(addrVO.getMemoList().length > 0) { if(addrVO.getMemoList()[i].equals("-")) { tempAddrVO.setAddrComment(null); }else { String tmpComment = addrVO.getMemoList()[i].replaceAll("§", ","); int commLen = tmpComment.length(); if(commLen > 125) { //isSuccess = false; //msg = "메모 항목의 내용(\" " + tmpComment + " \")이 길이를 초과하여 입력되었습니다. 100글자 이하로 입력해 주세요."; //break; tempAddrVO.setAddrComment(addrVO.getMemoList()[i].replaceAll("§", ",").substring(0, 125)); }else { tempAddrVO.setAddrComment(addrVO.getMemoList()[i].replaceAll("§", ",")); } } } else { tempAddrVO.setAddrComment(null); } tempAddrVO.setMberId(userId); tempAddrVO.setFrstRegisterId(userId); tempAddrVO.setAddrGrpId(addrVO.getAddrGrpId()); // 그룹 지정 // 그룹미지정, 자주보내는 번호 구분처리 if("Y".equals (addrVO.getBookmark())) { // 자주보내는 번호 tempAddrVO.setBookmark("Y"); tempAddrVO.setAddrGrpId("0"); } else { tempAddrVO.setBookmark("N"); } FaxAddrVO addrVO2 = new FaxAddrVO(); addrVO2.setMberId(userId); addrVO2.setAddrGrpId(addrVO.getAddrGrpId()); // 그룹 지정 addrVO2.setAddrPhoneNo(addrVO.getPhoneList()[i]); // 연락처 // 팩스 번호 유효성 검사 boolean isPhoneNoErr = true; if(!addrVO.getPhoneList()[i].matches(phoneRegExp)) {//휴대폼 번호 타입이 아닌 경우에만 통과 되도록 함 isPhoneNoErr = false; }else { errPhoneCnt++; } //int usedCnt = addrService.selectDuplAddrCnt(addrVO2); if(isPhoneNoErr == false) { //주소록 리스트에 데이터 추가해 주기 addrDataInfo.add(tempAddrVO); } } System.out.println("======================================================"); System.out.println("+++++++++++++++++++++++++ isSuccess ::: "+isSuccess); System.out.println("======================================================"); //주소록에 데이터 추가해 주기 if (isSuccess == true && addrDataInfo.size() > 0) { // 주소록 대량등록 By Temp 주소록 All resultCnt = faxAddrService.insertFaxAddrByTempAddrAll(addrDataInfo, addrVO); addrBefAfterCnt = faxAddrService.selectFaxAddrTotalCount(addrVO); addrMassDupliList = faxAddrService.selectTempFaxAddrDupliList(addrVO); resultCnt = addrBefAfterCnt - addrBefCnt; dupliCnt = addrNewCnt - resultCnt; } } } else { isSuccess = false; msg = "주소록은 총 50만개까지만 등록이 가능합니다."; } } catch(Exception e) { isSuccess = false; msg = "주소록 저장에 오류가 발생하였습니다. 시스템 관리자에게 문의 바랍니다."; System.out.println("=============================================="); System.out.println("+++++++++++++++++++ addrMassInsertByTempAjax Error ::: "+e.getMessage()); System.out.println("=============================================="); } modelAndView.addObject("isSuccess", isSuccess); modelAndView.addObject("msg", msg); modelAndView.addObject("resultCnt", resultCnt); modelAndView.addObject("dupliCnt", dupliCnt); modelAndView.addObject("errPhoneCnt", errPhoneCnt); modelAndView.addObject("addrMassDupliList", addrMassDupliList); return modelAndView; } /** * 주소록 그룹 리스트 화면 불러오기 * * @param MjonMsgDataVO * @param * @param sessionVO * @param model * @return * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/selectFaxAddrGroupListAjaxView.do"}) public String selectFaxAddrGroupListAjaxView( @ModelAttribute("searchVO") FaxAddrGroupVO faxaddrGroupVO, FaxAddrVO faxaddrVO, ModelMap model, RedirectAttributes redirectAttributes) throws Exception { //로그인 권한정보 불러오기 LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(loginVO == null) { return "redirect:/web/main/mainPage.do"; } if(userId != "") { faxaddrGroupVO.setMberId(userId); faxaddrVO.setMberId(userId); } if(faxaddrGroupVO.getPageUnit() != 10) { faxaddrGroupVO.setPageUnit(faxaddrGroupVO.getPageUnit()); } if("".equals(faxaddrGroupVO.getSearchSortCnd())){ //최초조회시 최신것 조회List faxaddrGroupVO.setSearchSortCnd("addrGrpId"); faxaddrGroupVO.setSearchSortOrd("desc"); } faxaddrGroupVO.setSiteId("web"); List addrGroupList = faxAddrGroupService.selectFaxAddrGroupList(faxaddrGroupVO); //회원별 주소록 전체 갯수 조회 int addrTotalCount = faxAddrService.selectFaxAddrTotalCount(faxaddrVO); faxaddrVO.setType("bookmark"); List addrBookmarkList = faxAddrService.selectFaxAddrBasicGrpList(faxaddrVO); faxaddrVO.setType("noGrp"); List addrNoGrpList = faxAddrService.selectFaxAddrBasicGrpList(faxaddrVO); model.addAttribute("addrTotalCount", addrTotalCount); model.addAttribute("addrGroupList", addrGroupList); model.addAttribute("addrBookmarkList", addrBookmarkList); model.addAttribute("addrNoGrpList", addrNoGrpList); return "web/fax/addr/FaxAddrGroupListAjaxView"; } /** * 주소록 그룹 목록 * @param searchVO * @param model * @return "/web/mjon/addr/addrGroupListAjax.do" * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/faxAddrGroupListAjax.do"}) public ModelAndView faxAddrGroupListAjax(@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO, RedirectAttributes redirectAttributes, ModelMap model) throws Exception{ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); boolean isSuccess = true; String msg = ""; List addrGroupList = null; try { LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrGroupVO.setMberId(userId); if(addrGroupVO.getPageUnit() != 10) { addrGroupVO.setPageUnit(addrGroupVO.getPageUnit()); } if("".equals(addrGroupVO.getSearchSortCnd())){ //최초조회시 최신것 조회List addrGroupVO.setSearchSortCnd("grpOrder"); addrGroupVO.setSearchSortOrd("desc"); } addrGroupVO.setSiteId("web"); addrGroupList = faxAddrGroupService.selectFaxAddrGroupList(addrGroupVO); } } catch(Exception e) { isSuccess = false; msg = e.getMessage(); } modelAndView.addObject("isSuccess", isSuccess); modelAndView.addObject("msg", msg); model.addAttribute("addrGroupList", addrGroupList); return modelAndView; } /** * 주소록 그룹별 중복 연락처 목록 * @param searchVO * @param model * @return "/web/mjon/addr/addrDupliListAjax.do" * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/faxAddrDupliListAjax.do"}) public ModelAndView faxAddrDupliListAjax(@ModelAttribute("searchVO") FaxAddrVO addrVO, RedirectAttributes redirectAttributes, ModelMap model) throws Exception{ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); boolean isSuccess = true; String msg = ""; List addrDupliList = null; try { LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrVO.setMberId(userId); // 주소록 그룹별 중복 연락처 목록 addrDupliList = faxAddrService.selectFaxAddrDupliList(addrVO); } } catch(Exception e) { isSuccess = false; msg = e.getMessage(); } modelAndView.addObject("isSuccess", isSuccess); modelAndView.addObject("msg", msg); model.addAttribute("addrDupliList", addrDupliList); return modelAndView; } /** * 주소록 그룹별 중복 연락처 삭제 * @param searchVO * @param model * @return "/web/mjon/addr/deleteAddrDupliList.do" * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/deleteFaxAddrDupliListAjax.do"}) public ModelAndView deleteFaxAddrDupliListAjax(@ModelAttribute("searchVO") FaxAddrVO addrVO, RedirectAttributes redirectAttributes, ModelMap model) throws Exception{ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); boolean isSuccess = true; String msg = ""; try { LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrVO.setMberId(userId); // 주소록 그룹별 중복 연락처 삭제 faxAddrService.deleteFaxAddrDupliList(addrVO); } else { isSuccess = false; msg = "로그인후 이용하세요."; } } catch(Exception e) { isSuccess = false; msg = e.getMessage(); } modelAndView.addObject("isSuccess", isSuccess); modelAndView.addObject("msg", msg); return modelAndView; } /** * 주소록 그룹별 중복 연락처 삭제 * @param searchVO * @param model * @return "/web/mjon/addr/deleteAddrByAllDupliListAjax.do" * @throws Exception */ @RequestMapping(value= {"/web/mjon/fax/addr/deleteFaxAddrByAllDupliListAjax.do"}) public ModelAndView deleteFaxAddrByAllDupliListAjax(@ModelAttribute("searchVO") FaxAddrVO addrVO, RedirectAttributes redirectAttributes, ModelMap model) throws Exception{ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("jsonView"); boolean isSuccess = true; String msg = ""; try { LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null; String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId()); if(userId != "") { addrVO.setMberId(userId); // 주소록 그룹별 중복 연락처 삭제 faxAddrService.deleteFaxAddrDupliListByAll(addrVO); } else { isSuccess = false; msg = "로그인후 이용하세요."; } } catch(Exception e) { isSuccess = false; msg = e.getMessage(); } modelAndView.addObject("isSuccess", isSuccess); modelAndView.addObject("msg", msg); return modelAndView; } public boolean getNameRepLenChk(String type, String value) { boolean rtnValue = true; // JSPark 2023.02.17 : 글자길이체크 주석처리 => 저장시 절삭하기 때문 /* if(type.equals("name")) { String tmpNm = value; int nmLen = tmpNm.length(); if(nmLen > 12) { rtnValue = false; } }else if(type.equals("rep")) { String tmpRep = value; int repLen = tmpRep.length(); if(repLen > 20) { rtnValue = false; } }else if(type.equals("memo")) { String tmpRep = value; int repLen = tmpRep.length(); if(repLen > 120) { rtnValue = false; } } */ return rtnValue; } // 문자열에서 숫자만 추출 public String getOnlyNumber(String str) { //String str = "aaa1234, ^&*2233pp"; String intStr = str.replaceAll("[^\\d]", ""); return intStr; } }