NoticeService.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. package com.its.web.service.notice;
  2. import com.its.web.dto.message.ResultDto;
  3. import com.its.web.dto.notice.AttachFileDto;
  4. import com.its.web.dto.notice.NoticeDto;
  5. import com.its.web.mapper.its.notice.NoticeMapper;
  6. import com.its.web.pagination.Pagination;
  7. import com.its.web.util.CommonUtil;
  8. import lombok.RequiredArgsConstructor;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.commons.io.FileUtils;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import javax.servlet.http.HttpServletRequest;
  15. import java.io.*;
  16. import java.net.URLDecoder;
  17. import java.util.*;
  18. @Slf4j
  19. @RequiredArgsConstructor
  20. @Service
  21. public class NoticeService {
  22. private final NoticeMapper mapper;
  23. @Value("${board-location}")
  24. String boardLocation;
  25. public Pagination findAllList(String page, String searchType, String searchText) {
  26. Pagination pagination = new Pagination(page, this.mapper.getNoticeTotalCount(), searchType, searchText);
  27. List<NoticeDto> list = this.mapper.findAllNotice(pagination);
  28. pagination.setList(list);
  29. return pagination;
  30. }
  31. public NoticeDto findNotice(String boardNo) {
  32. try {
  33. return this.mapper.findNoticeById(Long.parseLong(boardNo));
  34. }
  35. catch (NumberFormatException e){
  36. log.error("Cause NumberFormatException, Please Check The Board No -> {}", boardNo);
  37. return null;
  38. }
  39. }
  40. public List<NoticeDto> findMainNotice(int num) {
  41. return this.mapper.findMainNotice(num);
  42. }
  43. public AttachFileDto getAttachFile(String boardNo, String fileId) {
  44. AttachFileDto dto = new AttachFileDto();
  45. dto.setBoardNo(boardNo);
  46. String message = null;
  47. if (boardNo != null && fileId != null) {
  48. Map<String, String> paramMap = new HashMap<>();
  49. paramMap.put("boardNo", boardNo);
  50. paramMap.put("fileId", fileId);
  51. int result = this.mapper.getAttachFileCount(paramMap);
  52. if (result > 0) {
  53. File file = new File(boardLocation, fileId);
  54. int fileSize = (int) file.length();
  55. if (fileSize > 0) {
  56. try {
  57. byte[] byteArray = FileUtils.readFileToByteArray(file);
  58. if (byteArray.length > 0) {
  59. int i = 0;
  60. dto.setAttachFile(new byte[byteArray.length]);
  61. for (byte b : byteArray) {
  62. dto.getAttachFile()[i++] = b;
  63. }
  64. message = "파일 전송 완료.";
  65. }
  66. else {
  67. message = "파일을 찾을 수 없습니다.";
  68. }
  69. }
  70. catch (FileNotFoundException e) {
  71. log.error("File Not FoundException");
  72. message = "파일을 찾을 수 없습니다.";
  73. } catch (IOException e) {
  74. log.error("IOException");
  75. message = "파일을 읽는 중 오류가 발생하였습니다.";
  76. }
  77. }
  78. }
  79. else {
  80. message = "파일을 찾일 수 없습니다.";
  81. }
  82. }
  83. dto.setMessage(message);
  84. return dto;
  85. }
  86. public ResultDto deleteBoard(String boardNo) {
  87. NoticeDto deleteDto = this.findNotice(boardNo);
  88. String fileIds = deleteDto.getAttachFileId();
  89. if (fileIds != null){
  90. String[] idArray = fileIds.split("\\|");
  91. if (idArray.length > 0) {
  92. for(String id : idArray) {
  93. File file = new File(boardLocation, id);
  94. if (file.exists()) {
  95. boolean isDelete = file.delete();
  96. if (!isDelete) {
  97. log.error("게시물 파일이 삭제되지 않았습니다. {}", id);
  98. }
  99. }
  100. }
  101. }
  102. }
  103. int affectedRows = this.mapper.deleteBoard(boardNo);
  104. String message = "선택하신 게시물이 삭제되지 않았습니다.";
  105. String success = "F";
  106. if (affectedRows > 0) {
  107. message = "선택하신 게시물이 삭제되었습니다.";
  108. success = "S";
  109. }
  110. return CommonUtil.getResultDto(success, message);
  111. }
  112. public ResultDto writeNotice(NoticeDto.NoticeDtoWriteReq param, List<MultipartFile> attachFile, String webUserId) {
  113. Map<String, Object> paramMap = new HashMap<>();
  114. String fileNames = "";
  115. String fileIds = "";
  116. String message = "";
  117. String success = "S";
  118. paramMap.put("bContent", param.getBcontent());
  119. paramMap.put("bSubject", param.getBsubject());
  120. paramMap.put("webUserId", webUserId);
  121. if (attachFile != null && attachFile.size() > 0){
  122. for (MultipartFile file : attachFile) {
  123. String fileName = file.getOriginalFilename();
  124. if (fileName != null) {
  125. String ext = fileName.substring(fileName.lastIndexOf("."));
  126. String fileId = UUID.randomUUID().toString().replaceAll("-", "") + ext;
  127. boolean isSuccess = uploadAttachFile(file, fileId);
  128. fileNames = fileName + "|";
  129. fileIds = fileId + "|";
  130. if (!isSuccess) {
  131. message = "파일 생성 중 오류가 발생하였습니다.";
  132. success = "F";
  133. }
  134. }
  135. }
  136. }
  137. if (success.equals("S")) {
  138. if (attachFile != null) {
  139. int fileSize = attachFile.size();
  140. if (attachFile != null && fileSize == 1) {
  141. fileNames = fileNames + "|";
  142. fileIds = fileIds + "|";
  143. }
  144. else if (fileSize == 3) {
  145. fileNames = fileNames.substring(fileNames.length() - 1);
  146. fileIds = fileIds.substring(fileIds.length() - 1);
  147. }
  148. }
  149. else {
  150. fileNames = "||";
  151. fileIds = "||";
  152. }
  153. paramMap.put("attachFile", fileNames);
  154. paramMap.put("attachFileId", fileIds);
  155. int affectedRows = this.mapper.insertNotice(paramMap);
  156. message = "작성하신 게시물이 저장되었습니다.";
  157. if (affectedRows <= 0) {
  158. message = "작성하신 게시물이 저장되지 않았습니다.";
  159. success = "F";
  160. }
  161. }
  162. return CommonUtil.getResultDto(success, message);
  163. }
  164. public ResultDto modifyNotice(NoticeDto.NoticeDtoUpdateReq param, List<MultipartFile> attachFile) {
  165. Map<String, Object> paramMap = new HashMap<>();
  166. paramMap.put("bSubject", param.getBSubject());
  167. paramMap.put("bContent", param.getBContent());
  168. paramMap.put("boardNo", param.getBoardNo());
  169. String attachFileNames = param.getAttachFileNames();
  170. Map<Integer, String> sameIndex = new HashMap<>();
  171. String fileId = "||";
  172. String success = "S";
  173. String message = "작성하신 게시물이 수정되었습니다.";
  174. NoticeDto dto = this.findNotice(param.getBoardNo());
  175. if (dto != null) {
  176. if (!attachFileNames.equals(dto.getAttachFile())) {
  177. String originAttachFile = dto.getAttachFile();
  178. String originFileIds = dto.getAttachFileId();
  179. if (originAttachFile != null && originFileIds != null) {
  180. String[] fileNameArr = originAttachFile.split("\\|");
  181. String[] fileIdArr = originFileIds.split("\\|");
  182. String[] nameArr = attachFileNames.split("\\|");
  183. // 기존 파일과 같은 이름이 있는지 찾고 있으면 유지 해줘야한다
  184. if (fileNameArr.length > 0) {
  185. for (int ii = 0; ii < fileNameArr.length; ii++) {
  186. String originName = fileNameArr[ii];
  187. if (nameArr.length >= (ii +1) && originName.equals(nameArr[ii])) {
  188. sameIndex.put(ii, fileIdArr[ii]);
  189. }
  190. else {
  191. if (fileIdArr.length > ii && fileIdArr[ii] != null) {
  192. File file = new File(boardLocation, fileIdArr[ii]);
  193. if (file.exists()) {
  194. boolean isDelete = file.delete();
  195. if (!isDelete) {
  196. log.error("기존 파일 삭제가 진행되지 않았습니다. {}", fileIdArr[ii]);
  197. }
  198. }
  199. }
  200. }
  201. }
  202. }
  203. }
  204. }
  205. else {
  206. fileId = dto.getAttachFileId();
  207. }
  208. }
  209. if (attachFile != null && attachFile.size() > 0) {
  210. int cnt = 0;
  211. for (MultipartFile file : attachFile) {
  212. String orgName = file.getOriginalFilename();
  213. if (orgName != null && orgName.lastIndexOf(".") > 0) {
  214. String ext = orgName.substring(orgName.lastIndexOf("."));
  215. String attachFileId = UUID.randomUUID().toString().replaceAll("-", "") + ext;
  216. if (sameIndex.size() == 0) {
  217. sameIndex.put(cnt++, attachFileId);
  218. }
  219. else {
  220. for (int ii = 0; ii < 3; ii++) {
  221. if (sameIndex.get(ii) == null) {
  222. sameIndex.put(ii, attachFileId);
  223. break;
  224. }
  225. }
  226. }
  227. boolean isSuccess = uploadAttachFile(file, attachFileId);
  228. if (!isSuccess) {
  229. message = "파일 생성 중 오류가 발생하였습니다.";
  230. success = "F";
  231. return CommonUtil.getResultDto(success, message);
  232. }
  233. }
  234. }
  235. fileId = "";
  236. for (int ii = 0; ii < 3; ii++) {
  237. if (sameIndex.get(ii) != null) {
  238. fileId += sameIndex.get(ii);
  239. }
  240. if (ii != 2) {
  241. fileId += "|";
  242. }
  243. }
  244. }
  245. paramMap.put("attachFile", attachFileNames);
  246. paramMap.put("attachFileId", fileId);
  247. int affectedRows = this.mapper.updateNotice(paramMap);
  248. if (affectedRows <= 0) {
  249. message ="작성하신 게시물이 수정되지 않았습니다.";
  250. success = "F";
  251. }
  252. return CommonUtil.getResultDto(success, message);
  253. }
  254. public boolean uploadAttachFile(MultipartFile attachFile, String fileId) {
  255. File file = new File(boardLocation);
  256. boolean isMkFile = true;
  257. if (!file.exists()) {
  258. file.setExecutable(false, true); /*파일 실행 권한 설정 (파라미터 - 일반, 소유자)*/
  259. file.setReadable(true); /*파일 읽기 권한 설정*/
  260. file.setWritable(false, true);
  261. isMkFile = file.mkdirs();
  262. }
  263. if (isMkFile) {
  264. File transFile = new File(boardLocation + "/" + fileId);
  265. try {
  266. attachFile.transferTo(transFile);
  267. }
  268. catch (IOException e) {
  269. log.error("IOException - 첨부 파일 파일 생성 중 오류가 발생하였습니다.");
  270. isMkFile = false;
  271. }
  272. }
  273. else {
  274. log.error("디렉토리 생성 중 오류가 발생하였습니다.");
  275. }
  276. return isMkFile;
  277. }
  278. public int updateNoticeReadCount(String boardNo) {
  279. return this.mapper.updateNoticeReadCount(boardNo);
  280. }
  281. public String imageUpload(HttpServletRequest req){
  282. String uploadImageInfo = "";
  283. String fileName = req.getHeader("file-name");
  284. try {
  285. fileName = URLDecoder.decode(fileName, "UTF-8");
  286. }
  287. catch (UnsupportedEncodingException exception) {
  288. log.error("Can not Decoding UTF-8");
  289. }
  290. String filePath = boardLocation + "/upload";
  291. File file = new File(filePath);
  292. boolean isMkdirs = true;
  293. if (!file.exists()) {
  294. file.setExecutable(false, true); /*파일 실행 권한 설정 (파라미터 - 일반, 소유자)*/
  295. file.setReadable(true); /*파일 읽기 권한 설정*/
  296. file.setWritable(false, true);
  297. isMkdirs = file.mkdirs();
  298. }
  299. if (isMkdirs) {
  300. String realFileNm;
  301. realFileNm = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
  302. String rlFileNm = filePath + File.separator + realFileNm;
  303. OutputStream os = null;
  304. try (
  305. InputStream is = req.getInputStream();
  306. ) {
  307. os = new FileOutputStream(rlFileNm);
  308. int numRead;
  309. byte[] byteArray = new byte[Integer.parseInt(req.getHeader("file-size"))];
  310. if (is != null) {
  311. while ((numRead = is.read(byteArray, 0, byteArray.length)) != -1) {
  312. os.write(byteArray, 0, numRead);
  313. }
  314. }
  315. os.flush();
  316. } catch (IOException e) {
  317. log.error("IO Exception - noticeImageUpload");
  318. } catch (Exception e1) {
  319. log.error("Exception - noticeImageUpload");
  320. }
  321. finally {
  322. if(os != null) {
  323. try{
  324. os.close();
  325. }
  326. catch (IOException e) {
  327. log.error("Cause IOException...");
  328. }
  329. }
  330. }
  331. uploadImageInfo += "&bNewLine=true";
  332. uploadImageInfo += "&sFileName=" + fileName;
  333. uploadImageInfo += "&sFileURL=" + "/api/notice/upload/" + realFileNm;
  334. }
  335. return uploadImageInfo;
  336. }
  337. public byte[] getImage(String imageName) {
  338. byte[] image = null;
  339. File file = new File(boardLocation + "/upload", imageName);
  340. int fileSize = (int) file.length();
  341. if (fileSize > 0) {
  342. try {
  343. byte[] byteArray = FileUtils.readFileToByteArray(file);
  344. if (byteArray.length > 0) {
  345. int ii = 0;
  346. image = new byte[byteArray.length];
  347. for (byte b : byteArray) {
  348. image[ii++] = b;
  349. }
  350. }
  351. } catch (FileNotFoundException e) {
  352. log.error("Not Found File - {}", boardLocation + "/upload/" + imageName);
  353. } catch (IOException e) {
  354. log.error("Can Not Send Image Cause IOException - {}", boardLocation + "/upload/" + imageName);
  355. }
  356. }
  357. return image;
  358. }
  359. }