260327_01_ENH: 프로젝트 구조 리펙토링 및 README.md 갱신

This commit is contained in:
2026-03-27 11:01:47 +09:00
parent e72d061e58
commit 905906b923
65 changed files with 531 additions and 1581 deletions

View File

@@ -0,0 +1,19 @@
package com.kri.common.feature.auth.apikey;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import java.util.Optional;
/**
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면
* 된다.
*/
public interface ApiKeyUserClaimsProvider {
/**
* API Key 로 사용자 정보를 조회한다.
*
* @param apiKey 요청 헤더에서 받은 API Key
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
*/
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
}

View File

@@ -0,0 +1,29 @@
package com.kri.common.feature.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Value;
@Schema(
name = "JwtUserClaimsDto",
description = "JWT에 포함되는 사용자 정보"
)
@Value
@Builder
public class JwtUserClaimsDto {
@Schema(description = "사용자 ID")
String userId;
@Schema(description = "사용자 소속 회사")
String userCmpn;
@Schema(description = "팀 코드")
String userTeam;
@Schema(description = "사용자 이름")
String userName;
@Schema(description = "권한 코드")
Integer userRole;
}

View File

@@ -0,0 +1,136 @@
package com.kri.common.feature.auth.jwt;
import com.kri.common.autoconfigure.auth.jwt.JwtProperties;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
/**
* 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원
*/
@RequiredArgsConstructor
public class JwtService {
private final JwtProperties properties;
private SecretKey key;
@PostConstruct
public void init() {
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
String secret = properties.getSecret();
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
throw new IllegalStateException(
"kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256");
}
// secret 문자열을 HMAC 키로 전환
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
private String buildToken(Map<String, Object> claims, String subject, long validitySeconds) {
Date now = new Date();
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuer(properties.getIssuer())
.setIssuedAt(now)
.setExpiration(expiry)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
Map<String, Object> claims = new HashMap<>();
claims.put("userId", dto.getUserId());
claims.put("userCmpn", dto.getUserCmpn());
claims.put("userTeam", dto.getUserTeam());
claims.put("userName", dto.getUserName());
claims.put("role", dto.getUserRole());
return claims;
}
public String generateAccessToken(JwtUserClaimsDto userClaims) {
Map<String, Object> claims = buildClaims(userClaims);
return buildToken(claims, userClaims.getUserId(), properties.getAccessTokenValiditySeconds());
}
public String generateRefreshToken(String userId) {
return buildToken(Collections.emptyMap(), userId, properties.getRefreshTokenValiditySeconds());
}
public Jws<Claims> parseToken(String token) throws JwtException {
return Jwts.parserBuilder()
.requireIssuer(properties.getIssuer())
.setSigningKey(key)
.build()
.parseClaimsJws(token);
}
public Claims getClaims(String token) throws JwtException {
return parseToken(token).getBody();
}
public JwtUserClaimsDto toUserClaimsDto(Claims claims) {
String userId = claims.get("userId", String.class);
if (userId == null) {
userId = claims.getSubject();
}
String userCmpn = claims.get("userCmpn", String.class);
String userTeam = claims.get("userTeam", String.class);
String userName = claims.get("userName", String.class);
Number roleNumber = claims.get("role", Number.class);
Integer userRole = roleNumber != null ? roleNumber.intValue() : null;
return JwtUserClaimsDto.builder()
.userId(userId)
.userCmpn(userCmpn)
.userTeam(userTeam)
.userName(userName)
.userRole(userRole)
.build();
}
public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException {
Claims claims = getClaims(token);
return toUserClaimsDto(claims);
}
public Authentication toAuthentication(JwtUserClaimsDto dto) {
String principal = dto.getUserId();
List<GrantedAuthority> authorities = new ArrayList<>();
if (dto.getUserRole() != null) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + dto.getUserRole()));
}
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(principal, null, authorities);
auth.setDetails(dto);
return auth;
}
public Authentication toAuthentication(String token) throws JwtException {
return toAuthentication(toUserClaimsDto(token));
}
}

View File

@@ -0,0 +1,120 @@
package com.kri.common.feature.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractListCache<T> {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private List<T> list = List.of();
@EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true)
public void loadOnStartup() {
List<T> tempList = loadFromDb();
if (tempList != null) {
setList(tempList);
}
}
public List<T> getList() {
lock.readLock().lock();
try {
return list;
} finally {
lock.readLock().unlock();
}
}
public void setList(List<T> next) {
lock.writeLock().lock();
try {
this.list = List.copyOf(next == null ? List.of() : next);
} finally {
lock.writeLock().unlock();
}
}
@Transactional(readOnly = true)
public List<T> reload() {
List<T> tempList = loadFromDb();
if (tempList == null) {
throw new UnsupportedOperationException("This cache does not support reload().");
}
setList(tempList);
return getList();
}
public List<T> clear() {
lock.writeLock().lock();
try {
return list = List.of();
} finally {
lock.writeLock().unlock();
}
}
public void addAll(List<T> items) {
if (items == null || items.isEmpty()) {
return;
}
lock.writeLock().lock();
try {
List<T> merged = new java.util.ArrayList<>(this.list);
merged.addAll(items);
this.list = List.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
public void addAll(int index, Collection<? extends T> items) {
if (items == null || items.isEmpty()) {
return;
}
lock.writeLock().lock();
try {
ArrayList<T> next = new ArrayList<>(this.list);
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size濡?蹂댁젙
next.addAll(i, new ArrayList<>(items));
this.list = List.copyOf(next);
} finally {
lock.writeLock().unlock();
}
}
public void add(T item) {
lock.writeLock().lock();
try {
List<T> merged = new java.util.ArrayList<>(this.list);
merged.add(item);
this.list = List.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
public void add(int index, T item) {
lock.writeLock().lock();
try {
ArrayList<T> next = new ArrayList<>(this.list);
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size濡?蹂댁젙
next.add(i, item);
this.list = List.copyOf(next);
} finally {
lock.writeLock().unlock();
}
}
protected List<T> loadFromDb() {
return null;
}
}

View File

@@ -0,0 +1,118 @@
package com.kri.common.feature.cache;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractMapCache<K, V> {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private Map<K, V> map = Map.of();
@EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true)
public void loadOnStartup() {
Map<K, V> tempMap = loadFromDb();
if (tempMap != null) {
setMap(tempMap);
}
}
public Map<K, V> getMap() {
lock.readLock().lock();
try {
return map;
} finally {
lock.readLock().unlock();
}
}
/**
* 수동: 전체 교체(불변 스냅샷으로 보관)
*/
public void setMap(Map<K, V> next) {
lock.writeLock().lock();
try {
this.map = Map.copyOf(next == null ? Map.of() : next);
} finally {
lock.writeLock().unlock();
}
}
public V get(K key) {
lock.readLock().lock();
try {
return map.get(key);
} finally {
lock.readLock().unlock();
}
}
public boolean containsKey(K key) {
lock.readLock().lock();
try {
return map.containsKey(key);
} finally {
lock.readLock().unlock();
}
}
@Transactional(readOnly = true)
public Map<K, V> reload() {
Map<K, V> tempMap = loadFromDb();
if (tempMap == null) {
throw new UnsupportedOperationException("This cache does not support reload().");
}
setMap(tempMap);
return getMap();
}
public void put(K key, V value) {
lock.writeLock().lock();
try {
Map<K, V> merged = new HashMap<>(this.map);
merged.put(key, value);
this.map = Map.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
/**
* 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체)
*/
public void putAll(Map<K, V> entries) {
if (entries == null || entries.isEmpty()) {
return;
}
lock.writeLock().lock();
try {
Map<K, V> merged = new HashMap<>(this.map);
merged.putAll(entries);
this.map = Map.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
/**
* clear: 완전 비우기
*/
public void clear() {
lock.writeLock().lock();
try {
this.map = Map.of();
} finally {
lock.writeLock().unlock();
}
}
// 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현
protected Map<K, V> loadFromDb() {
return null;
}
}

View File

@@ -0,0 +1,273 @@
package com.kri.common.feature.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Objects;
public final class DateTimeUtil {
public static final ZoneId KST = ZoneId.of("Asia/Seoul");
public static final ZoneId UTC = ZoneOffset.UTC;
/**
* 날짜+시간: 2025-11-28 15:00:14
*/
public static final DateTimeFormatter DATETIME_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 날짜: 2025-11-28
*/
public static final DateTimeFormatter DATE_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
private DateTimeUtil() {
}
/* =======================
* Now (KST)
* ======================= */
/**
* 현재 KST 날짜+시간 문자열
*/
public static String nowKstDateTime() {
return formatKst(Instant.now(), DATETIME_FMT);
}
/**
* 현재 KST 날짜 문자열
*/
public static String nowKstDate() {
return nowKstZoned().format(DATE_FMT);
}
/**
* 현재 KST ZonedDateTime
*/
public static ZonedDateTime nowKstZoned() {
return Instant.now().atZone(KST);
}
/**
* 현재 KST LocalDateTime
*/
public static LocalDateTime nowKstLocalDateTime() {
return nowKstZoned().toLocalDateTime();
}
/**
* 현재 KST LocalDate
*/
public static LocalDate nowKstLocalDate() {
return nowKstZoned().toLocalDate();
}
/* =======================
* Format (Instant -> String)
* ======================= */
/**
* Instant -> KST 날짜+시간 문자열
*/
public static String formatKstDateTime(Instant instant) {
return formatKst(instant, DATETIME_FMT);
}
/**
* Instant -> KST 날짜 문자열
*/
public static String formatKstDate(Instant instant) {
return formatKst(instant, DATE_FMT);
}
/**
* Instant -> KST 문자열 (커스텀 포맷)
*/
public static String formatKst(Instant instant, DateTimeFormatter formatter) {
if (instant == null) {
return null;
}
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
return instant.atZone(KST).format(fmt);
}
/* =======================
* Validate
* ======================= */
/**
* "yyyy-MM-dd" 형태인지
*/
public static boolean isDate(String text) {
return tryParseLocalDate(text, DATE_FMT) != null;
}
/**
* "yyyy-MM-dd HH:mm:ss" 형태인지
*/
public static boolean isDateTime(String text) {
return tryParseLocalDateTime(text, DATETIME_FMT) != null;
}
/**
* ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지
*/
public static boolean isIsoDateTime(String text) {
if (text == null || text.isBlank()) {
return false;
}
final String s = text.trim();
try {
Instant.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
try {
OffsetDateTime.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
try {
ZonedDateTime.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
return false;
}
/* =======================
* Parse (String -> Instant)
* ======================= */
/**
* ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도)
*/
public static Instant parseToInstant(String text) {
if (text == null || text.isBlank()) {
return null;
}
final String s = text.trim();
try {
return Instant.parse(s);
} catch (DateTimeParseException ignored) {
}
try {
return OffsetDateTime.parse(s).toInstant();
} catch (DateTimeParseException ignored) {
}
try {
return ZonedDateTime.parse(s).toInstant();
} catch (DateTimeParseException ignored) {
}
throw new DateTimeParseException("Unsupported datetime format", s, 0);
}
/**
* 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT
*/
public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) {
if (text == null || text.isBlank()) {
return null;
}
Objects.requireNonNull(formatter, "formatter");
LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter);
return ldt.atZone(KST).toInstant();
}
/**
* "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석
*/
public static Instant parseKstDateTimeToInstant(String text) {
return parseKstToInstant(text, DATETIME_FMT);
}
/**
* "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석
*/
public static Instant parseKstDateToInstant(String text) {
if (text == null || text.isBlank()) {
return null;
}
LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT);
return ld.atStartOfDay(KST).toInstant();
}
/* =======================
* Convert / Helpers
* ======================= */
/**
* Instant -> KST ZonedDateTime
*/
public static ZonedDateTime toKstZoned(Instant instant) {
return instant == null ? null : instant.atZone(KST);
}
/**
* Instant -> KST LocalDateTime
*/
public static LocalDateTime toKstLocalDateTime(Instant instant) {
ZonedDateTime zdt = toKstZoned(instant);
return zdt == null ? null : zdt.toLocalDateTime();
}
/**
* Instant -> KST LocalDate
*/
public static LocalDate toKstLocalDate(Instant instant) {
ZonedDateTime zdt = toKstZoned(instant);
return zdt == null ? null : zdt.toLocalDate();
}
/**
* null/blank 안전 trim
*/
public static String trimToNull(String s) {
if (s == null) {
return null;
}
String t = s.trim();
return t.isEmpty() ? null : t;
}
public static LocalDate parseLocalDate(String text) {
return tryParseLocalDate(text, DATE_FMT);
}
public static LocalDateTime parseLocalDateTime(String text) {
return tryParseLocalDateTime(text, DATETIME_FMT);
}
private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) {
return null;
}
try {
return LocalDate.parse(text.trim(), fmt);
} catch (DateTimeParseException e) {
return null;
}
}
private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) {
return null;
}
try {
return LocalDateTime.parse(text.trim(), fmt);
} catch (DateTimeParseException e) {
return null;
}
}
}

View File

@@ -0,0 +1,26 @@
package com.kri.common.feature.datetime;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@JacksonAnnotationsInside
@JsonDeserialize(using = LenientLocalDateTimeDeserializer.class)
public @interface LenientLocalDateTime {
String[] patterns() default {
"yyyy-MM-dd",
"yyyy-MM-dd HH",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd'T'HH:mm",
"yyyy-MM-dd'T'HH:mm:ss"
};
}

View File

@@ -0,0 +1,93 @@
package com.kri.common.feature.datetime;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.Arrays;
public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
implements ContextualDeserializer {
private final DateTimeFormatter[] formatters;
public LenientLocalDateTimeDeserializer() {
this(new String[]{
"yyyy-MM-dd",
"yyyy-MM-dd HH",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd'T'HH:mm",
"yyyy-MM-dd'T'HH:mm:ss"
});
}
private LenientLocalDateTimeDeserializer(String[] patterns) {
this.formatters = Arrays.stream(patterns)
.map(LenientLocalDateTimeDeserializer::withDefaultTimeParts)
.toArray(DateTimeFormatter[]::new);
}
private static DateTimeFormatter withDefaultTimeParts(String pattern) {
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
.appendPattern(pattern);
// 초(ss)가 있는 패턴이면 ".밀리초(1~3자리)"를 옵션으로 허용
// 예: 2025-12-19T14:50:12.1 / .12 / .123
// (pattern 자체에 S가 들어간 경우는 중복 추가 방지)
if (pattern.contains("ss") && !pattern.contains("S")) {
b.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 3, true) // true => '.' 포함
.optionalEnd();
}
// 패턴에 분/초가 없으면 0으로 채움 (날짜만 와도 LocalDateTime으로 만들 수 있게)
return b
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.toFormatter();
}
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String s = DateTimeUtil.trimToNull(p.getText());
if (s == null) {
return null;
}
for (DateTimeFormatter f : formatters) {
try {
return LocalDateTime.parse(s, f);
} catch (DateTimeParseException ignored) {
}
}
throw ctxt.weirdStringException(s, LocalDateTime.class,
"Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime");
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException {
if (property == null) {
return this;
}
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
if (ann == null) {
ann = property.getContextAnnotation(LenientLocalDateTime.class);
}
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
}
}

View File

@@ -0,0 +1,6 @@
package com.kri.common.feature.enums;
public interface CodeEnum<T> {
T getCode();
}

View File

@@ -0,0 +1,23 @@
package com.kri.common.feature.enums;
public final class CodeEnumUtils {
private CodeEnumUtils() {
}
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
if (code == null) {
return null;
}
for (E e : enumClass.getEnumConstants()) {
if (e.getCode().equals(code)) {
return e;
}
}
throw new IllegalArgumentException(
"Unknown code [" + code + "] for enum class " + enumClass.getName()
);
}
}

View File

@@ -0,0 +1,17 @@
package com.kri.common.feature.excel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelColumn {
String header(); // 엑셀 헤더 이름
int order() default 0; // 컬럼 순서
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
package com.kri.common.feature.excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
public final class ExcelUtil {
private ExcelUtil() {
}
public static String getStringCell(Cell cell) {
if (cell == null) {
return null;
}
return switch (cell.getCellType()) {
case STRING -> cell.getStringCellValue();
case NUMERIC -> {
if (DateUtil.isCellDateFormatted(cell)) {
yield cell.getDateCellValue().toString();
} else {
double d = cell.getNumericCellValue();
if (d == Math.rint(d)) {
yield String.valueOf((long) d);
}
yield String.valueOf(d);
}
}
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
case FORMULA -> cell.getCellFormula();
case BLANK -> null;
default -> null; // ERROR, _NONE 등 나머지 타입
};
}
}

View File

@@ -0,0 +1,59 @@
package com.kri.common.feature.file;
import java.util.regex.Pattern;
public final class FileUtil {
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
/**
* 파일명에서 위험한 문자 제거
*/
public static String sanitizeFileName(String original) {
if (original == null || original.isBlank()) {
return "file";
}
String name = original.trim().replace("\\", "/");
int idx = name.lastIndexOf('/');
if (idx >= 0 && idx < name.length() - 1) {
name = name.substring(idx + 1);
}
name = FILENAME_SANITIZE.matcher(name).replaceAll("_");
// 너무 짧으면 기본값
if (name.isBlank()) {
return "file";
}
return name;
}
public static String getExtension(String fileName) {
if (fileName == null) {
return "";
}
int dot = fileName.lastIndexOf('.');
if (dot < 0 || dot == fileName.length() - 1) {
return "";
}
return fileName.substring(dot + 1);
}
public static String extractFileNameFromPath(String pathLike) {
if (pathLike == null || pathLike.isBlank()) {
return "";
}
String s = pathLike;
int q = s.indexOf('?');
if (q >= 0) {
s = s.substring(0, q);
}
int hash = s.indexOf('#');
if (hash >= 0) {
s = s.substring(0, hash);
}
int slash = s.lastIndexOf('/');
if (slash >= 0 && slash < s.length() - 1) {
return s.substring(slash + 1);
}
return s;
}
}

View File

@@ -0,0 +1,102 @@
package com.kri.common.feature.http;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
/**
* 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. -
* body는 문자열(JSON 등) 기준입니다.
*/
public class ExternalApiClient {
private final HttpClient httpClient;
private final Duration requestTimeout;
/**
* 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅)
*/
public ExternalApiClient() {
this(HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build(), Duration.ofSeconds(30));
}
/**
* 사용자 지정 HttpClient/요청 타임아웃으로 생성
*/
public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) {
this.httpClient = httpClient;
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
}
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
// GET/DELETE 등 body 없는 메서드는 noBody 사용
if (body == null || body.isEmpty()) {
return switch (method) {
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
default -> HttpRequest.BodyPublishers.noBody();
};
}
return HttpRequest.BodyPublishers.ofString(body);
}
public ExternalApiResponse get(String url, Map<String, String> headers) {
return send("GET", url, headers, null);
}
public ExternalApiResponse delete(String url, Map<String, String> headers) {
return send("DELETE", url, headers, null);
}
public ExternalApiResponse post(String url, Map<String, String> headers, String body) {
return send("POST", url, headers, body);
}
public ExternalApiResponse put(String url, Map<String, String> headers, String body) {
return send("PUT", url, headers, body);
}
public ExternalApiResponse patch(String url, Map<String, String> headers, String body) {
return send("PATCH", url, headers, body);
}
private ExternalApiResponse send(String method, String url, Map<String, String> headers,
String body) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(requestTimeout)
.method(method, buildBodyPublisher(method, body));
// 추가 헤더 설정
if (headers != null) {
headers.forEach((k, v) -> {
if (k != null && v != null) {
builder.header(k, v);
}
});
}
// body가 있고 Content-Type이 없다면 기본 application/json
if (body != null && (headers == null || !headers.keySet().stream()
.map(String::toLowerCase).anyMatch("content-type"::equals))) {
builder.header("Content-Type", "application/json; charset=utf-8");
}
HttpRequest request = builder.build();
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
} catch (IOException | InterruptedException e) {
// 인터럽트 복원
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), e);
}
}
}

View File

@@ -0,0 +1,37 @@
package com.kri.common.feature.http;
import java.net.http.HttpHeaders;
import java.util.List;
import java.util.Map;
/**
* 외부 API 호출 결과를 단순하게 담는 DTO.
*/
public class ExternalApiResponse {
private final int statusCode;
private final Map<String, List<String>> headers;
private final String body;
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
this.statusCode = statusCode;
this.headers = headers;
this.body = body;
}
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
return new ExternalApiResponse(status, headers.map(), body);
}
public int getStatusCode() {
return statusCode;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
}

View File

@@ -0,0 +1,27 @@
package com.kri.common.feature.jpa;
import com.kri.common.feature.enums.CodeEnum;
import com.kri.common.feature.enums.CodeEnumUtils;
import jakarta.persistence.AttributeConverter;
public abstract class AbstractCodeEnumConverter<
E extends Enum<E> & CodeEnum<V>,
V
> implements AttributeConverter<E, V> {
private final Class<E> enumClass;
protected AbstractCodeEnumConverter(Class<E> enumClass) {
this.enumClass = enumClass;
}
@Override
public V convertToDatabaseColumn(E attribute) {
return attribute == null ? null : attribute.getCode();
}
@Override
public E convertToEntityAttribute(V dbData) {
return CodeEnumUtils.fromCode(enumClass, dbData);
}
}

View File

@@ -0,0 +1,42 @@
package com.kri.common.feature.jpa;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PrePersist;
import java.util.UUID;
@MappedSuperclass
public abstract class BaseUuidEntity {
private static String generateId(int length) {
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
if (length <= 32) {
return base.substring(0, length);
}
StringBuilder sb = new StringBuilder(length);
sb.append(base);
while (sb.length() < length) {
sb.append(UUID.randomUUID().toString().replace("-", ""));
}
return sb.substring(0, length);
}
protected abstract String getId();
protected abstract void setId(String id);
/**
* 엔티티마다 컬럼 길이에 맞춰 오버라이드
*/
protected int idLength() {
return 32;
}
@PrePersist
protected void prePersistId() {
if (getId() == null || getId().isBlank()) {
setId(generateId(idLength()));
}
}
}

View File

@@ -0,0 +1,122 @@
package com.kri.common.feature.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
public final class JsonUtil {
private JsonUtil() {
// 유틸 클래스 - 인스턴스 생성 방지
}
/**
* 임의의 자바 객체를 Map으로 변환한다. 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는
* 용도이다.
*/
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
if (source == null) {
return Collections.emptyMap();
}
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(source, Map.class);
return map;
}
/**
* JSON 문자열을 Map으로 파싱한다.
*
* @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환)
*/
public static Map<String, Object> parseJsonToMap(ObjectMapper objectMapper, String json) {
if (json == null || json.isBlank()) {
return Collections.emptyMap();
}
try {
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) {
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
}
}
/**
* 객체를 JSON 문자열로 직렬화한다.
*/
public static String toJson(ObjectMapper objectMapper, Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("객체를 JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
}
}
/**
* 객체를 사람이 읽기 좋은 pretty JSON 문자열로 직렬화한다.
*/
public static String toPrettyJson(ObjectMapper objectMapper, Object value) {
try {
return objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("객체를 pretty JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
}
}
/**
* JSON 문자열을 주어진 타입으로 역직렬화한다. ex) fromJson(mapper, json, UserInfoDto.class)
*/
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
if (json == null || json.isBlank()) {
return null;
}
try {
return objectMapper.readValue(json, type);
} catch (IOException e) {
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.",
e);
}
}
/**
* JSON 문자열을 제네릭 타입으로 역직렬화한다. ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>()
* {})
*/
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
if (json == null || json.isBlank()) {
return null;
}
try {
return objectMapper.readValue(json, typeRef);
} catch (IOException e) {
throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e);
}
}
/**
* JSON 기반 deep copy (또는 타입 변환). 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
* <p>
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
*/
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
if (source == null) {
return null;
}
return objectMapper.convertValue(source, targetType);
}
/**
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
* <p>
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
*/
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {
if (source == null) {
return null;
}
return objectMapper.convertValue(source, targetType);
}
}

View File

@@ -0,0 +1,21 @@
package com.kri.common.feature.redis;
import java.time.Duration;
import org.springframework.data.redis.core.StringRedisTemplate;
public class RedisQueueHelper {
private final StringRedisTemplate rt;
public RedisQueueHelper(StringRedisTemplate rt) {
this.rt = rt;
}
public void enqueue(String key, String value) {
rt.opsForList().rightPush(key, value);
}
public String blockingDequeue(String key, Duration timeout) {
return rt.opsForList().leftPop(key, timeout);
}
}

View File

@@ -0,0 +1,13 @@
package com.kri.common.feature.util;
import java.util.UUID;
public final class CommonUtil {
private CommonUtil() {
}
public static String uuid32() {
return UUID.randomUUID().toString().replace("-", "");
}
}

View File

@@ -0,0 +1,45 @@
package com.kri.common.feature.util;
public final class NumericUtil {
private NumericUtil() {
}
public static boolean isNumeric(String s) {
if (s == null || s.isBlank()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
public static short safeParseShort(String s, short def) {
try {
return Short.parseShort(s);
} catch (Exception e) {
return def;
}
}
public static int safeParseInt(String s, short def) {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return def;
}
}
public static long safeParseLong(String s, short def) {
try {
return Long.parseLong(s);
} catch (Exception e) {
return def;
}
}
}

View File

@@ -0,0 +1,22 @@
package com.kri.common.feature.util;
public final class StringUtil {
private StringUtil() {
}
/** null 또는 "" 인지 */
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
/** null 또는 공백(whitespace)만 있는지 ("" 포함) - Java 11+ */
public static boolean isNullOrBlank(String s) {
return s == null || s.isBlank();
}
/** (옵션) 반대 버전도 같이 두면 실무에서 더 편함 */
public static boolean hasText(String s) {
return s != null && !s.isBlank();
}
}

View File

@@ -0,0 +1,120 @@
package com.kri.common.feature.web;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
public class BusinessException extends RuntimeException {
private final HttpStatus status;
private final String code;
private final Map<String, Object> extras;
private BusinessException(HttpStatus status, String code, String message,
Map<String, Object> extras, Throwable cause) {
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
this.status = status;
this.code = (code != null && !code.isBlank()) ? code : defaultCode(status); // 코드가 없으면 상태명으로 대체
this.extras = extras == null ? Collections.emptyMap()
: Collections.unmodifiableMap(new HashMap<>(extras));
}
private static String defaultCode(HttpStatus status) {
return status.name();
} // 예: NOT_FOUND, CONFLICT …
public static BusinessException of(HttpStatus status, String code, String message) {
return new BusinessException(status, code, message, null, null);
}
public static BusinessException of(HttpStatus status, String code, String message,
Map<String, Object> extras) {
return new BusinessException(status, code, message, extras, null);
}
// 편의 생성자들
// 400 Bad Request
public static BusinessException badRequest(String code, String message) {
return of(HttpStatus.BAD_REQUEST, code, message);
}
public static BusinessException badRequest(String message) {
return badRequest("BAD_REQUEST", message);
}
// 401 Unauthorized
public static BusinessException unauthorized(String code, String message) {
return of(HttpStatus.UNAUTHORIZED, code, message);
}
public static BusinessException unauthorized(String message) {
return unauthorized("UNAUTHORIZED", message);
}
// 403 Forbidden
public static BusinessException forbidden(String code, String message) {
return of(HttpStatus.FORBIDDEN, code, message);
}
public static BusinessException forbidden(String message) {
return forbidden("FORBIDDEN", message);
}
// 404 Not Found
public static BusinessException notFound(String code, String message) {
return of(HttpStatus.NOT_FOUND, code, message);
}
public static BusinessException notFound(String message) {
return notFound("NOT_FOUND", message);
}
// 409 Conflict
public static BusinessException conflict(String code, String message) {
return of(HttpStatus.CONFLICT, code, message);
}
public static BusinessException conflict(String message) {
return conflict("CONFLICT", message);
}
// 422 Unprocessable Entity (검증 에러 등에 자주 사용)
public static BusinessException validationError(String code, String message) {
return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message);
}
public static BusinessException validationError(String message) {
return validationError("VALIDATION_ERROR", message);
}
// 500 Internal Server Error
public static BusinessException internalError(String code, String message) {
return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message);
}
public static BusinessException internalError(String message) {
return internalError("INTERNAL_SERVER_ERROR", message);
}
public HttpStatus getStatus() {
return status;
}
public String getCode() {
return code;
}
public Map<String, Object> getExtras() {
return extras;
}
/**
* 편의: 체이닝으로 extras 추가
*/
public BusinessException with(String key, Object value) {
var map = new HashMap<>(this.extras);
map.put(key, value);
return new BusinessException(this.status, this.code, this.getMessage(), map, this.getCause());
}
}

View File

@@ -0,0 +1,21 @@
package com.kri.common.feature.web;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class RequestUserContext {
String userId;
String userCmpn;
String userTeam;
String userName;
Integer userRole;
String clientIp; // IpUtil ?먯꽌 媛€?몄삩 媛?
public boolean isAuthenticated() {
return userId != null;
}
}

View File

@@ -0,0 +1,21 @@
package com.kri.common.feature.web.page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "페이지 검색 조건")
public class PageRequestDto {
@Schema(description = "페이지 번호")
private int pageIndex = 0; // 0-base
@Schema(description = "페이지 크기")
private int pageSize = 10;
@Schema(description = "정렬 기준")
private String sortBy = "prjctIdx"; // 가변
@Schema(description = "오름차순/내림차순")
private String sortDir = "desc"; // asc/desc
}

View File

@@ -0,0 +1,35 @@
package com.kri.common.feature.web.page;
import java.util.List;
import lombok.Builder;
import lombok.Getter;
import org.springframework.data.domain.Page;
@Getter
@Builder
public class PageResponseDto<T> {
private List<T> content;
private long totalElements;
private int totalPages;
private int pageIndex;
private int pageSize;
private int numberOfElements;
private boolean first;
private boolean last;
private boolean empty;
public static <T> PageResponseDto<T> from(Page<T> page) {
return PageResponseDto.<T>builder()
.content(page.getContent())
.totalElements(page.getTotalElements())
.totalPages(page.getTotalPages())
.pageIndex(page.getNumber()) // ✅ 현재 페이지 index(0-base)
.pageSize(page.getSize())
.numberOfElements(page.getNumberOfElements())
.first(page.isFirst())
.last(page.isLast())
.empty(page.isEmpty())
.build();
}
}

View File

@@ -0,0 +1,77 @@
package com.kri.common.feature.web.page;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public final class Pageables {
private Pageables() {
}
public static Pageable of(PageRequestDto req, Class<?> sortType) {
int page = Math.max(req.getPageIndex(), 0);
int size = Math.max(req.getPageSize(), 1);
Sort sort = buildSort(req, sortType);
return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort);
}
private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
String sortBy = req.getSortBy();
if (sortBy == null || sortBy.isBlank()) {
return null;
}
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
? Sort.Direction.ASC
: Sort.Direction.DESC;
Set<String> allowed = allowedProperties(sortType);
List<String> props = Arrays.stream(sortBy.split(","))
.map(String::trim)
.filter(s -> !s.isBlank())
.collect(Collectors.toList());
// 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨)
List<String> invalid = props.stream()
.filter(p -> !allowed.contains(p))
.toList();
if (!invalid.isEmpty()) {
throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed);
}
return Sort.by(dir, props.toArray(String[]::new));
}
private static Set<String> allowedProperties(Class<?> sortType) {
try {
// getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적)
PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors();
Set<String> props = new HashSet<>();
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if ("class".equals(name)) {
continue;
}
if (pd.getReadMethod() == null) {
continue;
}
props.add(name);
}
return props;
} catch (Exception e) {
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
}
}
}