이메일 발송 테스트 코드

This commit is contained in:
Rinjae
2025-11-10 11:00:37 +09:00
parent 4283c8b3fc
commit 5b354cffb1
9 changed files with 284 additions and 95 deletions
@@ -0,0 +1,64 @@
package com.eactive.ext.kjb.eai;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.io.File;
import java.nio.file.Paths;
@Data
@Builder
@Slf4j
public class EaiBatchInterface {
@Pattern(regexp = "^[a-zA-Z0-9]{13}$", message = "id는 12자리 영문대소문자 및 숫자 조합이어야 합니다.")
private String id;
@NotEmpty
@Pattern(regexp = "^(?:[a-zA-Z]:\\\\|\\\\|\\/)(?:[\\w\\-\\.]+[\\\\\\/])*[\\w\\-\\.]+$", message = "sendDir은 절대경로로 지정되어야 합니다.")
private String sendDir;
@NotEmpty
@Pattern(regexp = "^(?:[a-zA-Z]:\\\\|\\\\|\\/)(?:[\\w\\-\\.]+[\\\\\\/])*[\\w\\-\\.]+$", message = "backupDir은 절대경로로 지정되어야 합니다.")
private String backupDir;
@NotEmpty
@Pattern(regexp = "^(?:[a-zA-Z]:\\\\|\\\\|\\/)(?:[\\w\\-\\.]+[\\\\\\/])*[\\w\\-\\.]+$", message = "errorDir은 절대경로로 지정되어야 합니다.")
private String errorDir;
public void moveError(String filename) {
move(filename, errorDir);
}
public void moveBackup(String filename) {
move(filename, backupDir);
}
private void move(String filename, String targetDir) {
File file = Paths.get(sendDir, filename).toFile();
File targetDirFile = new File(targetDir);
File targetFile = new File(targetDir, file.getName());
log.debug("송신파일 이동 시작 - {} -> {}", filename, targetDir);
if (!file.exists()) {
log.warn("송신 파일이 존재 하지 않습니다. ({})", file.getAbsolutePath());
return;
}
if (!targetDirFile.exists()) {
if (!targetDirFile.mkdirs()) {
log.warn("대상 디렉토리 생성 실패 ({})", file.getAbsolutePath());
return;
}
}
if (!file.renameTo(targetFile)) {
log.warn("송신 파일 이동 실패 - {}", targetFile.getAbsolutePath());
return;
}
}
}
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
@Slf4j
@@ -17,6 +18,9 @@ public class EaiBatchMessage {
@Getter
private String count = "";
/**
* 요청시 사용 안함, 응답시 1: 성공, 2: 실패
*/
@Getter
private String resultCode = "";
@@ -28,14 +32,17 @@ public class EaiBatchMessage {
private boolean isReadOnly = false;
private String charset;
private EaiBatchMessage() {}
public static EaiBatchMessage createRequest(String interfaceId, String filename) {
public static EaiBatchMessage createRequest(String interfaceId, String filename, String charset) {
EaiBatchMessage message = new EaiBatchMessage();
message.interfaceId = interfaceId;
message.filename = filename;
message.charset = charset;
return message;
}
@@ -46,16 +53,16 @@ public class EaiBatchMessage {
message.isReadOnly = true;
if (rawMessage.length() >= 40) {
message.interfaceId = rawMessage.substring(0, 20).trim();
message.baseDate = rawMessage.substring(20, 28).trim();
message.count = rawMessage.substring(28, 38).trim();
message.resultCode = rawMessage.substring(38, 39).trim();
message.interfaceId = rawMessage.substring(0, 19).trim();
message.baseDate = rawMessage.substring(19, 27).trim();
message.count = rawMessage.substring(27, 37).trim();
message.resultCode = rawMessage.substring(37, 38).trim();
// filename 은 @@가 발견되면 이전 까지 trim / 발견되지 않으면 나머지 전체 그리고 trim
int endIdx = rawMessage.indexOf("@@", 39);
int endIdx = rawMessage.indexOf("@@", 38);
if (endIdx == -1) {
message.filename = rawMessage.substring(39).trim();
message.filename = rawMessage.substring(38).trim();
} else {
message.filename = rawMessage.substring(39, endIdx).trim();
message.filename = rawMessage.substring(38, endIdx).trim();
}
}
@@ -74,16 +81,20 @@ public class EaiBatchMessage {
return rawMessage;
} else {
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 0~19 : 인터페이스ID (20)
buffer.put(fixedString(interfaceId, 20));
// 19-8: 기준일자 (8)
buffer.put(fixedString(baseDate, 8));
// 27-10 : 건수 (10)
buffer.put(fixedString(count, 10));
// 37-1 : 결과코드 (1)
buffer.put(fixedString(resultCode, 1));
// 38-100 : 파일명 (100)
buffer.put(fixedString(filename, 100));
try {
// 인터페이스ID (19)
buffer.put(fixedString(interfaceId, 19));
// 기준일자 (8)
buffer.put(fixedString(baseDate, 8));
// 건수 (10)
buffer.put(fixedString(count, 10));
// 결과코드 (1)
buffer.put(fixedString(resultCode, 1));
// 파일명 (100)
buffer.put(fixedString(filename, 100));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// 종료 구분자 (2)
buffer.put("@@".getBytes());
@@ -93,11 +104,11 @@ public class EaiBatchMessage {
}
}
private byte[] fixedString(String str, int length) {
private byte[] fixedString(String str, int length) throws UnsupportedEncodingException {
if (str == null) {
str = "";
}
byte[] strBytes = str.getBytes();
byte[] strBytes = str.getBytes(this.charset);
byte[] result = new byte[length];
int copyLength = Math.min(strBytes.length, length);
@@ -1,5 +1,6 @@
package com.eactive.ext.kjb.eai;
import com.eactive.ext.kjb.common.KjbEaiBatchException;
import com.eactive.ext.kjb.common.KjbProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@@ -11,10 +12,13 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.util.Timeout;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.concurrent.*;
@Slf4j
public class KjbEaiBatchModule {
@@ -42,10 +46,16 @@ public class KjbEaiBatchModule {
}
}
public EaiBatchMessage call(String interfaceId, String filename) throws IOException {
EaiBatchMessage reqMessage = EaiBatchMessage.createRequest(interfaceId, filename);
public EaiBatchMessage call(@Valid EaiBatchInterface intf, String filename) throws KjbEaiBatchException {
EaiBatchMessage reqMessage = EaiBatchMessage.createRequest(intf.getId(), filename, property.getEaiBatchCharset());
log.debug("EAI 배치 호출: {}", reqMessage);
// 송신 파일 체크
File sendFile = Paths.get(intf.getSendDir(), filename).toFile();
if (!sendFile.exists() || !sendFile.isFile()) {
throw new KjbEaiBatchException("Not found send file - " + sendFile.toPath());
}
if (this.httpClient != null) {
URI uri = null;
try {
@@ -60,17 +70,37 @@ public class KjbEaiBatchModule {
final HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig);
String message = httpClient.execute(httpGet, response -> EntityUtils.toString(response.getEntity(), "EUC-KR"));
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() ->
httpClient.execute(httpGet, response -> EntityUtils.toString(response.getEntity(), "EUC-KR")));
EaiBatchMessage resMessage = EaiBatchMessage.fromResponse(message);
log.debug("EAI 배치 응답: {}", resMessage);
return resMessage;
EaiBatchMessage resMessage = null;
try {
String message = future.get(property.getEaiBatchTimeout(), TimeUnit.SECONDS);
resMessage = EaiBatchMessage.fromResponse(message);
log.debug("EAI 배치 응답: {}", resMessage);
return resMessage;
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("EAI Batch call exception", e);
throw new KjbEaiBatchException("EAI Batch call failed", e);
} finally {
executor.shutdown();
// EAI 송신 실패일 경우 에러 경로로 이동
if (resMessage != null && "1".equals(resMessage.getResultCode())) {
intf.moveBackup(filename);
} else {
intf.moveError(filename);
}
}
} else {
log.info("EAI_BATCH_URL 이 설정되지 않아 실제 호출하지 않음. 요청 메시지: {}", reqMessage);
// 정상응답 리턴
EaiBatchMessage resMessage = EaiBatchMessage.fromResponse(String.format("%-20s%-8s%-10s%-1s%s@@", interfaceId, "", "0000000000", "1", "S:" + filename));
EaiBatchMessage resMessage = EaiBatchMessage.fromResponse(String.format("%-19s%-8s%-10s%-1s%s@@", intf.getId(), "", "0000000000", "1", "S:" + filename));
log.debug("EAI 배치 응답(모의): {}", resMessage);
intf.moveBackup(filename);
return resMessage;
}
}