feat : xml파일 처리 로직 처리중

master
Kurt92 6 months ago
parent 47667374a3
commit ddda6b4ca9

@ -0,0 +1,33 @@
package com.worker.dto;
import com.worker.entity.CpMain;
import jakarta.persistence.Lob;
import lombok.*;
import java.util.List;
public class SinmungoDto {
@Data
@Builder
public static class ParseResult {
private CpMain cpMain;
private List<ImgParser> imgParsers;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ImgParser {
private String fileName;
@Lob
private byte[] imageBytes;
}
}

@ -1,68 +0,0 @@
package com.worker.scheduler.smg;
import com.worker.entity.CpMain;
import com.worker.entity.CpSetinfo;
import com.worker.entity.CpSetinfoId;
import com.worker.entity.CpSetinfoRepository;
import com.worker.util.fileReader.XmlReader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
@RequiredArgsConstructor
@Slf4j
public class SinmongoInOutScheduler {
private final CpSetinfoRepository cpSetinfoRepository;
private final XmlReader xmlReader;
// esb에이전트 xml파일 읽기
@Scheduled(fixedRate = 10 * 60 * 1000) // 10분
// @Scheduled(fixedRate = 1000) // 10초
public void sinmongoInOutScheduler() {
//setinfo 테이블에서 esb에이전트 정보 조회
Optional<CpSetinfo> esbImgDir = cpSetinfoRepository.findById(
CpSetinfoId.builder()
.codeName("SERVER_INFO")
.groupCode("DIRECTORY")
.detailCode("IMAGE")
.build()
);
Optional<CpSetinfo> esbXmlDir = cpSetinfoRepository.findById(
CpSetinfoId.builder()
.codeName("국민신문고")
.groupCode("정보")
.detailCode("test")
.build()
);
//파일읽기
List<CpMain> parseResult = xmlReader.findXml(esbXmlDir.get().getStrValue4());
log.info(parseResult.toString());
//sinmongo 디렉토리로 파일 이동
//db폴링
//파일백업으로 이동
}
// 90일이 초과한 백업 파일들 삭제
public void sinmongoInOutFileRemoveScheduler() {
}
}

@ -0,0 +1,89 @@
package com.worker.scheduler.smg;
import com.worker.dto.SinmungoDto;
import com.worker.entity.*;
import com.worker.util.fileReader.XmlReader;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
@Slf4j
public class SinmungoInOutScheduler {
private final CpMainRepository cpMainRepository;
private final CpSetinfoRepository cpSetinfoRepository;
private final XmlReader xmlReader;
// esb에이전트 xml파일 읽기
@Scheduled(fixedRate = 10 * 60 * 1000) // 10분
@Transactional
public void sinmungoInOutScheduler() throws IOException {
//setinfo 테이블에서 esb에이전트 정보 조회
Optional<CpSetinfo> esbXmlDir = cpSetinfoRepository.findById(
CpSetinfoId.builder()
.codeName("국민신문고")
.groupCode("정보")
.detailCode("test")
.build()
);
Optional<CpSetinfo> esbBackupDir = cpSetinfoRepository.findById(
CpSetinfoId.builder()
.codeName("SERVER_INFO")
.groupCode("DIRECTORY")
.detailCode("IMAGEtest")
.build()
);
// 국민신문고 esb에이전트 pull path 정의
Path esbRcvPath = Paths.get(esbXmlDir.get().getStrValue4());
Path esbSendPath = Paths.get(esbXmlDir.get().getStrValue5());
// 백업 디렉토리
Path localImgPath = Paths.get(esbBackupDir.get().getStrValue1()); //img
Path localXmlPath = Paths.get(esbBackupDir.get().getStrValue2()); //sinmungo path 는 하드코딩 되어있었음
//파일읽기
List<SinmungoDto.ParseResult> parseResult = xmlReader.findXml(esbXmlDir.get().getStrValue4());
log.info(parseResult.toString());
// cpMain만 추출
List<CpMain> cpMainList = parseResult.stream()
.map(SinmungoDto.ParseResult::getCpMain)
.collect(Collectors.toList());
// db폴링
// cpMainRepository.saveAll(cpMainList);
// 파일백업으로 이동
// xml은 HP_ROOT/PROGRAM/BATCH/sinmungo 로 백업?
// xml안에 있던 이미지 바이너리는 HP_ROOT/DATA/IMAGE/${담당자번호?}/2025 로 백업?
Files.move(esbRcvPath, localXmlPath, StandardCopyOption.REPLACE_EXISTING);
List<SinmungoDto.ImgParser> imgParsers = parseResult.stream()
.flatMap(result -> result.getImgParsers().stream())
.collect(Collectors.toList());
xmlReader.imgLocalSave(localImgPath, imgParsers);
}
// 90일이 초과한 백업 파일들 삭제
public void sinmungoInOutFileRemoveScheduler() {
}
}

@ -1,5 +1,6 @@
package com.worker.util.fileReader;
import com.worker.dto.SinmungoDto;
import com.worker.entity.CpMain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@ -8,58 +9,91 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.lang.model.util.Elements;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.LinkedList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@Component
@Slf4j
public class XmlReader {
public List<CpMain> findXml(String dirPath) {
public List<SinmungoDto.ParseResult> findXml(String dirPath) {
File dir = new File(dirPath);
List<CpMain> cpMainList = new LinkedList<>();
List<SinmungoDto.ParseResult> result = new ArrayList<>();
if (!dir.exists() || !dir.isDirectory()) {
System.out.println(" 유효하지 않은 디렉토리 경로: " + dirPath);
log.info(" 디렉토리 경로 없음: " + dirPath);
return null;
}
File[] xmlFiles = dir.listFiles((d, name) -> name.toLowerCase().endsWith(".xml"));
if (xmlFiles == null || xmlFiles.length == 0) {
System.out.println(" XML 파일 없음: " + dirPath);
log.info(" XML 파일 없음: " + dirPath);
return null;
}
for (File xmlFile : xmlFiles) {
System.out.println(" 파일 파싱 중: " + xmlFile.getName());
cpMainList.add(parseXml(xmlFile));
log.info(" 파일 파싱 중: " + xmlFile.getName());
result.add(parseXml(xmlFile));
}
log.info(cpMainList.toString());
return cpMainList;
log.info(result.toString());
return result;
}
private CpMain parseXml(File xmlFile) {
private SinmungoDto.ParseResult parseXml(File xmlFile) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement(); // MINWON
List<SinmungoDto.ImgParser> imgBinary = new ArrayList<>();
CpMain.CpMainBuilder builderCp = CpMain.builder()
.mmSgnm(getTagValue("peter_name_v", root))
.mmSgtel(getTagValue("duty_id_v", root))
.mmCarno(getTagValue("carno", root))
.mmSgcont(getTagValue("text", root));
// 여기에 필요한 다른 필드도 매핑 추가
Element root = doc.getDocumentElement();
NodeList apndfilinfoList = root.getElementsByTagName("apndfilinfo");
if (apndfilinfoList.getLength() > 0) {
Element apndfilinfo = (Element) apndfilinfoList.item(0);
for (int i = 1; i <= 4; i++) {
String fileTag = "peti_file_path" + i + "_v";
String dataTag = "apndfilcont" + i;
String fileName = getTagValue(fileTag, apndfilinfo);
String base64Data = getTagValue(dataTag, apndfilinfo);
if (fileName != null && base64Data != null && !base64Data.isEmpty()) {
byte[] decoded = Base64.getDecoder().decode(base64Data);
imgBinary.add(SinmungoDto.ImgParser.builder()
.fileName(fileName)
.imageBytes(decoded)
.build());
}
}
}
return SinmungoDto.ParseResult.builder()
.cpMain(
CpMain.builder()
.mmSgnm(getTagValue("peter_name_v", root))
.mmSgtel(getTagValue("duty_id_v", root))
.mmCarno(getTagValue("carno", root))
.mmSgcont(getTagValue("text", root))
.build()
)
.imgParsers(imgBinary)
.build();
return builderCp.build();
} catch (Exception e) {
System.out.println("파싱 실패: " + xmlFile.getName());
@ -68,6 +102,21 @@ public class XmlReader {
}
}
public void imgLocalSave(Path localImgPath, List<SinmungoDto.ImgParser> imgParsers) {
for (SinmungoDto.ImgParser img : imgParsers) {
if (img.getFileName() != null && img.getImageBytes() != null) {
Path target = localImgPath.resolve(img.getFileName());
try {
Files.createDirectories(target.getParent());
Files.write(target, img.getImageBytes());
log.info("Saved image to {}", target);
} catch (IOException e) {
log.error("Failed to save image: " + target, e);
}
}
}
}
private String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag);
if (nodeList != null && nodeList.getLength() > 0) {

@ -22,6 +22,8 @@ spring:
logging:
level:
root: info
org.springframework.scheduling: info
org.springframework.scheduling.support: info
org.hibernate.SQL: debug
org.hibernate.type: trace
org.springframework.data.redis: info
Loading…
Cancel
Save