From 88e9845c1ce1c406f02b79068ec8f682968f4e96 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 12 Feb 2026 11:22:05 +0900 Subject: [PATCH] =?UTF-8?q?260212=5F01=5FDOC:=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EC=A0=84=EC=B2=B4=EC=97=90=20=EA=B5=AC?= =?UTF-8?q?=EA=B8=80=20java=20=EC=8A=A4=ED=83=80=EC=9D=BC=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 89 +- build.gradle | 4 +- .../apikey/ApiKeyAdminAutoConfiguration.java | 1 + .../auth/apikey/ApiKeyAdminController.java | 93 +- .../common/auth/apikey/ApiKeyAuthFilter.java | 70 +- .../apikey/ApiKeyJpaAutoConfiguration.java | 145 ++- .../ApiKeyPreloadAutoConfiguration.java | 18 +- .../common/auth/apikey/ApiKeyProperties.java | 106 +- .../auth/apikey/ApiKeyUserClaimsProvider.java | 18 +- .../PreloadedApiKeyUserClaimsProvider.java | 124 +- .../kri/common/auth/dto/JwtUserClaimsDto.java | 24 +- .../common/auth/jwt/JwtAutoConfiguration.java | 34 +- .../kri/common/auth/jwt/JwtProperties.java | 37 +- .../com/kri/common/auth/jwt/JwtService.java | 329 ++--- .../persistence/entity/TApiKeyEntity.java | 65 +- .../entity/TApiKeyServiceMapEntity.java | 13 +- .../entity/TApiKeyServiceMapEntityId.java | 44 +- .../repository/ApiKeyRepository.java | 22 +- .../kri/common/cache/AbstractListCache.java | 195 +-- .../kri/common/cache/AbstractMapCache.java | 195 +-- .../com/kri/common/datetime/DateTimeUtil.java | 391 +++--- .../common/datetime/LenientLocalDateTime.java | 23 +- .../LenientLocalDateTimeDeserializer.java | 120 +- .../java/com/kri/common/enums/CodeEnum.java | 3 +- .../com/kri/common/enums/CodeEnumUtils.java | 29 +- .../com/kri/common/excel/ExcelColumn.java | 14 +- .../com/kri/common/excel/ExcelMapper.java | 1140 +++++++++-------- .../java/com/kri/common/excel/ExcelUtil.java | 56 +- .../java/com/kri/common/file/FileUtil.java | 91 +- .../kri/common/http/ExternalApiClient.java | 163 +-- .../kri/common/http/ExternalApiResponse.java | 41 +- .../common/jpa/AbstractCodeEnumConverter.java | 30 +- .../com/kri/common/jpa/BaseUuidEntity.java | 51 +- .../java/com/kri/common/json/JsonUtil.java | 190 ++- .../redis/CommonRedisAutoConfiguration.java | 25 +- .../kri/common/redis/RedisQueueHelper.java | 20 +- .../CommonSchedulingAutoConfiguration.java | 4 +- .../security/JwtAuthenticationFilter.java | 55 +- .../KriSecurityAutoConfiguration.java | 107 +- .../security/KriSecurityProperties.java | 28 +- .../swagger/KriSwaggerAutoConfiguration.java | 92 +- .../common/swagger/KriSwaggerProperties.java | 16 +- .../java/com/kri/common/util/CommonUtil.java | 60 +- .../com/kri/common/web/BusinessException.java | 171 +-- .../web/CommonWebAutoConfiguration.java | 20 +- .../java/com/kri/common/web/ErrorAdvice.java | 336 ++--- .../com/kri/common/web/MdcHandlerConfig.java | 54 +- .../com/kri/common/web/ServiceMdcAspect.java | 33 +- .../java/com/kri/common/web/TraceFilter.java | 37 +- .../kri/common/webmvc/CodeEnumConverter.java | 51 +- .../webmvc/IpAccessControlInterceptor.java | 24 +- .../common/webmvc/IpAccessControlService.java | 17 +- .../java/com/kri/common/webmvc/IpUtil.java | 34 +- .../common/webmvc/KriIpAccessProperties.java | 55 +- .../webmvc/KriWebMvcAutoConfiguration.java | 118 +- .../kri/common/webmvc/RequestUserContext.java | 18 +- .../RequestUserContextArgumentResolver.java | 104 +- .../common/webmvc/page/PageRequestDto.java | 17 +- .../common/webmvc/page/PageResponseDto.java | 50 +- .../com/kri/common/webmvc/page/Pageables.java | 102 +- src/main/resources/logback-spring.xml | 80 +- 61 files changed, 3029 insertions(+), 2667 deletions(-) diff --git a/README.md b/README.md index 92bd1bc..5edbdd3 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을 - 주요 클래스: `ExternalApiClient`, `ExternalApiResponse` 지원 메서드(문자열 body 기반) + - `ExternalApiResponse get(String url, Map headers)` - `ExternalApiResponse post(String url, Map headers, String body)` - `ExternalApiResponse put(String url, Map headers, String body)` @@ -27,11 +28,13 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을 - `ExternalApiResponse delete(String url, Map headers)` 기본 동작 + - 연결 타임아웃: 10초, 요청 타임아웃: 30초 - body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정 - 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원 응답 객체(`ExternalApiResponse`) + - 필드: `statusCode`(int), `headers`(Map>), `body`(String) - 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)` @@ -77,6 +80,7 @@ ExternalApiClient client = new ExternalApiClient(httpClient, Duration.ofSeconds( ``` 주의사항 + - 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요. - 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요. @@ -264,6 +268,7 @@ kri: - com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용) 권장 의존 방향(순환 금지): + - auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸) - security → auth.* 에 의존(필터 순서/체인 구성) - web, webmvc → spring-web 중심, security에 의존하지 않음 @@ -272,25 +277,33 @@ kri: ### 0.2 AutoConfiguration 로딩과 오버라이드 전략 -자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음 순서/특징을 가집니다. +자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음 +순서/특징을 가집니다. 1) com.kri.common.auth.jwt.JwtAutoConfiguration + - JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공 2) com.kri.common.security.KriSecurityAutoConfiguration + - SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입 - before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입 3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration + - 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터 4) com.kri.common.swagger.KriSwaggerAutoConfiguration + - OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록 -5) com.kri.common.redis.CommonRedisAutoConfiguration, com.kri.common.scheduling.CommonSchedulingAutoConfiguration +5) com.kri.common.redis.CommonRedisAutoConfiguration, + com.kri.common.scheduling.CommonSchedulingAutoConfiguration + - 선택 기능: RedisQueueHelper, @EnableScheduling 오버라이드 규칙: + - 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선 - 프로퍼티로 on/off 토글(@ConditionalOnProperty) @@ -299,7 +312,7 @@ kri: - Stateless 세션, CSRF 비활성화, CORS 기본 허용 - public-paths는 permitAll, 그 외 anyRequest().authenticated() - 필터 순서: ApiKeyAuthFilter → JwtAuthenticationFilter → UsernamePasswordAuthenticationFilter - - 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리 + - 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리 ### 0.4 설정 네임스페이스 정리 @@ -389,7 +402,7 @@ KriCommon은 다음 AutoConfiguration 들을 제공합니다. 모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다. | 클래스 | 역할 요약 | -| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +|---------------------------------------------------------------|---------------------------------------------------------------------------------------| | `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 | | `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` | | `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 | @@ -499,7 +512,7 @@ public class JwtProperties { **프로퍼티 요약** | 프로퍼티 | 타입 | 기본값 | 설명 | -| --------------------------------------------- | ------ | ------------ | -------------------------------------- | +|-----------------------------------------------|--------|--------------|----------------------------------------| | `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) | | `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 | | `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) | @@ -600,7 +613,7 @@ public class ApiKeyProperties { **프로퍼티 요약** | 프로퍼티 | 타입 | 기본값 | 설명 | -| ----------------------------- | ------- | ----------- | ----------------------- | +|-------------------------------|---------|-------------|-------------------------| | `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 | | `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 | @@ -677,7 +690,7 @@ public class KriSecurityProperties { **프로퍼티 요약** | 프로퍼티 | 타입 | 기본값 (일부) | 설명 | -| --------------------------- | ------------ | ---------------- | -------------------------- | +|-----------------------------|--------------|------------------|----------------------------| | `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 | | `kri.security.public-paths` | List | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 | @@ -866,7 +879,7 @@ public class KriIpAccessProperties { **프로퍼티 요약** | 프로퍼티 | 타입 | 설명 | -| -------------------------------- | ------------ | --------------------------------- | +|----------------------------------|--------------|-----------------------------------| | `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off | | `kri.webmvc.ip.additional-cidrs` | List | 기본 CIDR 목록에 *추가*할 CIDR 리스트 | @@ -944,7 +957,7 @@ public class CommonRedisAutoConfiguration { **프로퍼티** | 프로퍼티 | 타입 | 기본값 | 설명 | -| ---------------------- | ------- | ----- | ---------------------- | +|------------------------|---------|-------|------------------------| | `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 | #### 4.6.2. RedisQueueHelper 사용 예시 @@ -980,7 +993,7 @@ public class CommonSchedulingAutoConfiguration { } **프로퍼티** | 프로퍼티 | 타입 | 기본값 | 설명 | -| --------------------------- | ------- | ----- | -------------------------- | +|-----------------------------|---------|-------|----------------------------| | `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 | 서비스 쪽에서는 단순히: @@ -1022,7 +1035,6 @@ common: **던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다. - #### 4.9.2. 기본 사용 패턴 * 4.9.2.1. Not Found (404) @@ -1040,12 +1052,14 @@ public User getUserOrThrow(String userId) { ); } ``` + - HTTP 상태: 404 - code: "USER_NOT_FOUND" - message: "해당 사용자를 찾을 수 없습니다." - extras: { "userId": "..." } * 4.9.2.2. Conflict (409) + ``` if (userRepository.existsByLoginId(loginId)) { throw BusinessException.conflict( @@ -1056,6 +1070,7 @@ if (userRepository.existsByLoginId(loginId)) { ``` * 4.9.2.3. Forbidden (403) + ``` if (!currentUser.canAccess(targetProject)) { throw BusinessException.forbidden( @@ -1066,7 +1081,9 @@ if (!currentUser.canAccess(targetProject)) { ``` #### 4.9.3. 임의 상태 코드 지정: of(...) + of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다. + ``` throw BusinessException.of( HttpStatus.BAD_REQUEST, @@ -1075,7 +1092,9 @@ throw BusinessException.of( ).with("param", "startDate"); ``` + 추가 정보를 한 번에 넘기고 싶으면: + ``` Map extras = Map.of( "param", "startDate", @@ -1089,21 +1108,27 @@ throw BusinessException.of( extras ); ``` + > 실제 구현에는 of(status, code, message, Map) 시그니처가 존재합니다. #### 4.9.4. extras 체이닝: with(...) 활용 + with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다. + ``` throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.") .with("userId", userId) .with("searchType", "INTRANET"); ``` + * 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다. #### 4.9.5. Service / Controller에서의 사용 위치 + Service에서 던지고, Controller는 깔끔하게 유지 - Service 예시 +Service 예시 + ``` @Service @RequiredArgsConstructor @@ -1124,6 +1149,7 @@ public class UserService { ``` Controller 예시 + ``` @RestController @RequestMapping("/api/users") @@ -1145,12 +1171,15 @@ public class UserController { * ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리 #### 4.9.6. 실제 응답 JSON 예시 + ``` throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.") .with("userId", "u-123"); ``` + 요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다. + ```json { "type": "about:blank", @@ -1166,6 +1195,7 @@ throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없 "userId": "u-123" } ``` + > 이 포맷은 ErrorAdvice에서 공통으로 생성합니다. #### 4.9.7. 로그 출력 정책 @@ -1187,6 +1217,7 @@ ErrorAdvice 내부 로깅 정책(요약): #### 4.9.8. 에러 코드 enum으로 관리하기 (선택) 서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다. + ``` public enum UserErrorCodes { USER_NOT_FOUND, @@ -1199,6 +1230,7 @@ throw BusinessException.notFound( "사용자를 찾을 수 없습니다." ).with("userId", userId); ``` + #### 4.9.9. 요약 1. 던지는 쪽 (Service) @@ -1208,13 +1240,14 @@ throw BusinessException.notFound( * 필요시 of(status, code, message) * with("key", value)로 추가 정보(extras) 세팅 2. 받는 쪽 (Controller) - * 별도 try/catch 필요 없음 - * ErrorAdvice가 자동으로 JSON + 로그 처리 + * 별도 try/catch 필요 없음 + * ErrorAdvice가 자동으로 JSON + 로그 처리 3. 클라이언트/FE 입장 * 응답은 ProblemDetail 포맷 + code + extras 일관 구조 * FE에서는 code 기준으로 에러 분기 처리하면 됨 --- + ## 5. example-service 적용 요약 1. **의존성 추가** @@ -1263,34 +1296,38 @@ throw BusinessException.notFound( ## 7. 문제 해결 가이드(Troubleshooting) - 애플리케이션 시작 시 "kri.auth.jwt.secret must be at least 32 bytes" 오류 - - 원인: JWT 시크릿 최소 길이 미달 - - 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체 + - 원인: JWT 시크릿 최소 길이 미달 + - 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체 - 모든 요청이 401 Unauthorized - - 원인1: Authorization 헤더에 Bearer 토큰 미포함 - - 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함) - - 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검 + - 원인1: Authorization 헤더에 Bearer 토큰 미포함 + - 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함) + - 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검 - Swagger 페이지가 접근 불가(403/404) - - 원인: IP 접근 제어 또는 public-paths 미설정 - - 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로 포함 + - 원인: IP 접근 제어 또는 public-paths 미설정 + - 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로 + 포함 - ApiKeyUserClaimsProvider가 동작하지 않음 - - 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false` - - 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검 + - 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false` + - 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검 --- ## 8. FAQ - Q. API Key와 JWT는 어떻게 같이 쓰나요? - - A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 권장합니다. + - A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 + 권장합니다. - Q. ROLE 매핑은 어디서 바꾸나요? - - A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 오버라이드하거나 래핑하십시오. + - A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 + 오버라이드하거나 래핑하십시오. - Q. 기본 Security를 전면 교체할 수 있나요? - - A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 적용됩니다. + - A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 + 적용됩니다. --- diff --git a/build.gradle b/build.gradle index 86deb20..b7032b3 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } //버전 변경은 여기서 -def commonVer = "beta.1.0.63" +def commonVer = "beta.1.0.63" group = 'com.kri.common' version = commonVer @@ -68,7 +68,7 @@ dependencies { compileOnly 'org.springframework.boot:spring-boot-starter-data-redis' } -def giteaUser = findProperty("giteaUser") ?: "" +def giteaUser = findProperty("giteaUser") ?: "" def giteaToken = findProperty("giteaToken") ?: "" publishing { publications { diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminAutoConfiguration.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminAutoConfiguration.java index b686c08..8ad9f41 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminAutoConfiguration.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminAutoConfiguration.java @@ -10,4 +10,5 @@ import org.springframework.context.annotation.Import; @ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true") @Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록 public class ApiKeyAdminAutoConfiguration { + } diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminController.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminController.java index ffeb8de..9689021 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminController.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyAdminController.java @@ -2,6 +2,8 @@ package com.kri.common.auth.apikey; import com.kri.common.auth.dto.JwtUserClaimsDto; import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpStatus; import org.springframework.security.web.util.matcher.IpAddressMatcher; @@ -11,54 +13,67 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; -import java.util.List; -import java.util.Map; - @RestController @RequestMapping("/internal/apikey") -@ConditionalOnProperty(prefix="kri.auth.apikey", name="admin-api-enabled", havingValue="true") +@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true") public class ApiKeyAdminController { - private final ApiKeyProperties props; - private final PreloadedApiKeyUserClaimsProvider provider; - private final List allow; - public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) { - this.props = props; - this.provider = provider; - this.allow = props.getAdminAllowIps().stream().map(IpAddressMatcher::new).toList(); + private final ApiKeyProperties props; + private final PreloadedApiKeyUserClaimsProvider provider; + private final List allow; + + public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) { + this.props = props; + this.provider = provider; + this.allow = props.getAdminAllowIps().stream().map(IpAddressMatcher::new).toList(); + } + + @PostMapping("/reload") + public ReloadResult reload(HttpServletRequest req) { + assertAllowed(req); + int count = provider.reloadFromDb(); + return new ReloadResult(count); + } + + /** + * 현재 캐시 상태(키는 마스킹) + */ + @GetMapping("/cache") + public List cache(HttpServletRequest req) { + assertAllowed(req); + Map snap = provider.snapshot(); + return snap.entrySet().stream() + .map(e -> new CachedKeyView(mask(e.getKey()), e.getValue())) + .toList(); + } + + private void assertAllowed(HttpServletRequest req) { + if (!props.isAdminApiEnabled()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND); } - - @PostMapping("/reload") - public ReloadResult reload(HttpServletRequest req) { - assertAllowed(req); - int count = provider.reloadFromDb(); - return new ReloadResult(count); + String remote = req.getRemoteAddr(); + boolean ok = allow.stream().anyMatch(m -> m.matches(remote)); + if (!ok) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote); } + } - /** 현재 캐시 상태(키는 마스킹) */ - @GetMapping("/cache") - public List cache(HttpServletRequest req) { - assertAllowed(req); - Map snap = provider.snapshot(); - return snap.entrySet().stream() - .map(e -> new CachedKeyView(mask(e.getKey()), e.getValue())) - .toList(); + private String mask(String raw) { + if (raw == null) { + return ""; } - - private void assertAllowed(HttpServletRequest req) { - if (!props.isAdminApiEnabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND); - String remote = req.getRemoteAddr(); - boolean ok = allow.stream().anyMatch(m -> m.matches(remote)); - if (!ok) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote); + int n = raw.length(); + if (n <= 8) { + return raw.charAt(0) + "****"; } + return raw.substring(0, 4) + "****" + raw.substring(n - 4); + } - private String mask(String raw) { - if (raw == null) return ""; - int n = raw.length(); - if (n <= 8) return raw.charAt(0) + "****"; - return raw.substring(0, 4) + "****" + raw.substring(n - 4); - } + public record ReloadResult(int cachedKeyCount) { - public record ReloadResult(int cachedKeyCount) {} - public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {} + } + + public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) { + + } } diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java index 800135b..83cbb8a 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java @@ -5,54 +5,52 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; import lombok.RequiredArgsConstructor; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; - /** - * X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. - * - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. - * - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅. + * X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. - + * 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅. */ @RequiredArgsConstructor public class ApiKeyAuthFilter extends OncePerRequestFilter { - private final ApiKeyProperties apiKeyProperties; - private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider; - private final JwtService jwtService; + private final ApiKeyProperties apiKeyProperties; + private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider; + private final JwtService jwtService; - @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) - throws ServletException, IOException { + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) + throws ServletException, IOException { - // API Key 기능이 꺼져 있으면 아무 것도 안 함 - if (!apiKeyProperties.isEnabled()) { - filterChain.doFilter(request, response); - return; - } - - // 이미 다른 방식(JWT 등)으로 인증되어 있으면 패스 - if (SecurityContextHolder.getContext().getAuthentication() != null) { - filterChain.doFilter(request, response); - return; - } - - String headerName = apiKeyProperties.getHeaderName(); - String apiKey = request.getHeader(headerName); - - if (StringUtils.hasText(apiKey)) { - apiKeyUserClaimsProvider.findUserByApiKey(apiKey).ifPresent(dto -> { - Authentication auth = jwtService.toAuthentication(dto); - SecurityContextHolder.getContext().setAuthentication(auth); - }); - } - - filterChain.doFilter(request, response); + // API Key 기능이 꺼져 있으면 아무 것도 안 함 + if (!apiKeyProperties.isEnabled()) { + filterChain.doFilter(request, response); + return; } + + // 이미 다른 방식(JWT 등)으로 인증되어 있으면 패스 + if (SecurityContextHolder.getContext().getAuthentication() != null) { + filterChain.doFilter(request, response); + return; + } + + String headerName = apiKeyProperties.getHeaderName(); + String apiKey = request.getHeader(headerName); + + if (StringUtils.hasText(apiKey)) { + apiKeyUserClaimsProvider.findUserByApiKey(apiKey).ifPresent(dto -> { + Authentication auth = jwtService.toAuthentication(dto); + SecurityContextHolder.getContext().setAuthentication(auth); + }); + } + + filterChain.doFilter(request, response); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyJpaAutoConfiguration.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyJpaAutoConfiguration.java index 34185bf..354d920 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyJpaAutoConfiguration.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyJpaAutoConfiguration.java @@ -2,6 +2,9 @@ package com.kri.common.auth.apikey; import com.zaxxer.hikari.HikariDataSource; import jakarta.persistence.EntityManagerFactory; +import java.util.HashMap; +import java.util.Map; +import javax.sql.DataSource; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -19,97 +22,93 @@ import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; -import javax.sql.DataSource; -import java.util.HashMap; -import java.util.Map; - /* * @Primary 절대 금지 * 메인 JPA와 완전히 분리 */ @AutoConfiguration( - afterName = { - // 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고, - // 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함. - "org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration", - "org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration" - } + afterName = { + // 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고, + // 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함. + "org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration", + "org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration" + } ) @ConditionalOnClass(name = { - "org.springframework.data.jpa.repository.JpaRepository", - "jakarta.persistence.EntityManagerFactory", - "com.zaxxer.hikari.HikariDataSource" + "org.springframework.data.jpa.repository.JpaRepository", + "jakarta.persistence.EntityManagerFactory", + "com.zaxxer.hikari.HikariDataSource" }) @ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true") @EnableJpaRepositories( - basePackages = "com.kri.common.auth.persistence.repository", - entityManagerFactoryRef = "apiKeyEntityManagerFactory", - transactionManagerRef = "apiKeyTransactionManager" + basePackages = "com.kri.common.auth.persistence.repository", + entityManagerFactoryRef = "apiKeyEntityManagerFactory", + transactionManagerRef = "apiKeyTransactionManager" ) @EnableConfigurationProperties(ApiKeyProperties.class) public class ApiKeyJpaAutoConfiguration { - @Bean(name = "apiKeyDataSource") - public DataSource apiKeyDataSource(ApiKeyProperties props) { - var db = props.getDb(); - HikariDataSource ds = new HikariDataSource(); - ds.setJdbcUrl(db.getUrl()); - ds.setUsername(db.getUsername()); - ds.setPassword(db.getPassword()); - ds.setDriverClassName(db.getDriverClassName()); - return ds; - } - /** - * ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - * - intranet-extension처럼 HibernateJpaAutoConfiguration을 exclude 해도 동작 - */ - @Bean(name = "apiKeyEntityManagerFactory") - public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory( - @Qualifier("apiKeyDataSource") DataSource ds, - ObjectProvider pumProvider, - ApiKeyProperties props - ) { - HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - vendorAdapter.setShowSql(props.getJpa().isShowSql()); - vendorAdapter.setGenerateDdl(false); + @Bean(name = "apiKeyDataSource") + public DataSource apiKeyDataSource(ApiKeyProperties props) { + var db = props.getDb(); + HikariDataSource ds = new HikariDataSource(); + ds.setJdbcUrl(db.getUrl()); + ds.setUsername(db.getUsername()); + ds.setPassword(db.getPassword()); + ds.setDriverClassName(db.getDriverClassName()); + return ds; + } - LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); - emf.setDataSource(ds); - emf.setJpaVendorAdapter(vendorAdapter); - emf.setPackagesToScan("com.kri.common.auth.persistence.entity"); - emf.setPersistenceUnitName("apikey"); + /** + * ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - intranet-extension처럼 HibernateJpaAutoConfiguration을 + * exclude 해도 동작 + */ + @Bean(name = "apiKeyEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory( + @Qualifier("apiKeyDataSource") DataSource ds, + ObjectProvider pumProvider, + ApiKeyProperties props + ) { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + vendorAdapter.setShowSql(props.getJpa().isShowSql()); + vendorAdapter.setGenerateDdl(false); - PersistenceUnitManager pum = pumProvider.getIfAvailable(); - if (pum != null) { - emf.setPersistenceUnitManager(pum); - } + LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(ds); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setPackagesToScan("com.kri.common.auth.persistence.entity"); + emf.setPersistenceUnitName("apikey"); - // 최소 JPA 속성들 (원하면 yml로 확장 가능) - Map jpaProps = new HashMap<>(); - jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql())); - jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql())); - - emf.setJpaPropertyMap(jpaProps); - return emf; + PersistenceUnitManager pum = pumProvider.getIfAvailable(); + if (pum != null) { + emf.setPersistenceUnitManager(pum); } - @Bean(name = "apiKeyTransactionManager") - public PlatformTransactionManager apiKeyTransactionManager( - @Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf - ) { - return new JpaTransactionManager(emf); - } + // 최소 JPA 속성들 (원하면 yml로 확장 가능) + Map jpaProps = new HashMap<>(); + jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql())); + jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql())); - /** - * ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 - * 'jpaMappingContext'가 없을 때만 보완해준다. - * - * 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다. - */ - @Bean(name = "jpaMappingContext") - @ConditionalOnMissingBean(name = "jpaMappingContext") - public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) { - // FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함 - return new JpaMetamodelMappingContextFactoryBean(); - } + emf.setJpaPropertyMap(jpaProps); + return emf; + } + + @Bean(name = "apiKeyTransactionManager") + public PlatformTransactionManager apiKeyTransactionManager( + @Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf + ) { + return new JpaTransactionManager(emf); + } + + /** + * ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 'jpaMappingContext'가 없을 때만 보완해준다. + *

+ * 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다. + */ + @Bean(name = "jpaMappingContext") + @ConditionalOnMissingBean(name = "jpaMappingContext") + public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) { + // FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함 + return new JpaMetamodelMappingContextFactoryBean(); + } } diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyPreloadAutoConfiguration.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyPreloadAutoConfiguration.java index 00deb38..683f9d4 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyPreloadAutoConfiguration.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyPreloadAutoConfiguration.java @@ -13,13 +13,13 @@ import org.springframework.context.annotation.Bean; @ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true") public class ApiKeyPreloadAutoConfiguration { - @Bean - @ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만 - @ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class) - public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider( - ApiKeyProperties props, - ApiKeyRepository repo - ) { - return new PreloadedApiKeyUserClaimsProvider(props, repo); - } + @Bean + @ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만 + @ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class) + public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider( + ApiKeyProperties props, + ApiKeyRepository repo + ) { + return new PreloadedApiKeyUserClaimsProvider(props, repo); + } } diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java index f8ace3b..8817d6c 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java @@ -1,62 +1,80 @@ package com.kri.common.auth.apikey; +import java.util.List; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.util.List; - @Getter @Setter @ConfigurationProperties(prefix = "kri.auth.apikey") public class ApiKeyProperties { - /** - * API Key 인증 허용 여부 - */ - private boolean enabled = false; + /** + * API Key 인증 허용 여부 + */ + private boolean enabled = false; + + /** + * API Key 를 읽어올 헤더 이름 예: X-API-Key, X-EXTERNAL-KEY 등 + */ + private String headerName = "X-API-Key"; + + /** + * 이 서비스의 코드 (서비스별 preload 범위 결정) + */ + private String serviceCode; + + /** + * 기동 시 preload 할지 + */ + private boolean preloadOnStartup = false; + + /** + * 내부 관리 API(리로드/조회) 노출 여부 + */ + private boolean adminApiEnabled = false; + + /** + * 내부 관리 API 접근 허용 IP(CIDR) + */ + private List adminAllowIps = List.of("127.0.0.1/32"); + + /** + * apikey 전용 DB 설정(기본값 포함) + */ + private Db db = new Db(); + + /** + * apikey 전용 JPA 옵션 + */ + private Jpa jpa = new Jpa(); + + @Getter + @Setter + public static class Jpa { /** - * API Key 를 읽어올 헤더 이름 - * 예: X-API-Key, X-EXTERNAL-KEY 등 + * hibernate.show_sql */ - private String headerName = "X-API-Key"; + private boolean showSql = false; - /** 이 서비스의 코드 (서비스별 preload 범위 결정) */ - private String serviceCode; - - /** 기동 시 preload 할지 */ - private boolean preloadOnStartup = false; - - /** 내부 관리 API(리로드/조회) 노출 여부 */ - private boolean adminApiEnabled = false; - - /** 내부 관리 API 접근 허용 IP(CIDR) */ - private List adminAllowIps = List.of("127.0.0.1/32"); - - /** apikey 전용 DB 설정(기본값 포함) */ - private Db db = new Db(); - - /** apikey 전용 JPA 옵션 */ - private Jpa jpa = new Jpa(); - - @Getter @Setter - public static class Jpa { - /** hibernate.show_sql */ - private boolean showSql = false; - - /** hibernate.format_sql */ - private boolean formatSql = false; - } + /** + * hibernate.format_sql + */ + private boolean formatSql = false; + } - @Getter @Setter - public static class Db { - //내부 통신용 url - private String url = - "jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8"; - private String username = "kriit"; - private String password = "it#51304"; - private String driverClassName = "com.mysql.cj.jdbc.Driver"; - } + @Getter + @Setter + public static class Db { + + //내부 통신용 url + private String url = + "jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8"; + private String username = "kriit"; + private String password = "it#51304"; + private String driverClassName = "com.mysql.cj.jdbc.Driver"; + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java index b926038..4317899 100644 --- a/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java @@ -4,16 +4,16 @@ import com.kri.common.auth.dto.JwtUserClaimsDto; import java.util.Optional; /** - * 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. - * 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다. + * 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 + * 된다. */ public interface ApiKeyUserClaimsProvider { - /** - * API Key 로 사용자 정보를 조회한다. - * - * @param apiKey 요청 헤더에서 받은 API Key - * @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty() - */ - Optional findUserByApiKey(String apiKey); + /** + * API Key 로 사용자 정보를 조회한다. + * + * @param apiKey 요청 헤더에서 받은 API Key + * @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty() + */ + Optional findUserByApiKey(String apiKey); } \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/apikey/PreloadedApiKeyUserClaimsProvider.java b/src/main/java/com/kri/common/auth/apikey/PreloadedApiKeyUserClaimsProvider.java index f2803bf..ea0cbff 100644 --- a/src/main/java/com/kri/common/auth/apikey/PreloadedApiKeyUserClaimsProvider.java +++ b/src/main/java/com/kri/common/auth/apikey/PreloadedApiKeyUserClaimsProvider.java @@ -3,73 +3,89 @@ package com.kri.common.auth.apikey; import com.kri.common.auth.dto.JwtUserClaimsDto; import com.kri.common.auth.persistence.entity.TApiKeyEntity; import com.kri.common.auth.persistence.repository.ApiKeyRepository; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.util.StringUtils; - import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.util.StringUtils; -public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider, ApplicationRunner { +public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider, + ApplicationRunner { - private final ApiKeyProperties props; - private final ApiKeyRepository repo; + private final ApiKeyProperties props; + private final ApiKeyRepository repo; - /** 캐시를 통째로 교체(swap)하기 위한 AtomicReference */ - private final AtomicReference> cacheRef = - new AtomicReference<>(Collections.emptyMap()); + /** + * 캐시를 통째로 교체(swap)하기 위한 AtomicReference + */ + private final AtomicReference> cacheRef = + new AtomicReference<>(Collections.emptyMap()); - public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) { - this.props = props; - this.repo = repo; + public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) { + this.props = props; + this.repo = repo; + } + + /** + * 런타임에는 DB 조회 금지: 캐시만 조회 + */ + @Override + public Optional findUserByApiKey(String apiKey) { + if (!StringUtils.hasText(apiKey)) { + return Optional.empty(); + } + return Optional.ofNullable(cacheRef.get().get(apiKey)); + } + + /** + * 기동 시 preload + */ + @Override + public void run(ApplicationArguments args) { + if (!props.isEnabled()) { + return; + } + if (!props.isPreloadOnStartup()) { + return; + } + reloadFromDb(); + } + + /** + * 운영용: DB에서 다시 읽어 캐시 전체 교체 + */ + public synchronized int reloadFromDb() { + if (!StringUtils.hasText(props.getServiceCode())) { + // serviceCode 없으면 preload 불가 → 안전하게 빈 캐시 + cacheRef.set(Collections.emptyMap()); + return 0; } - /** 런타임에는 DB 조회 금지: 캐시만 조회 */ - @Override - public Optional findUserByApiKey(String apiKey) { - if (!StringUtils.hasText(apiKey)) return Optional.empty(); - return Optional.ofNullable(cacheRef.get().get(apiKey)); + var list = repo.findActiveKeysForService(props.getServiceCode()); + + Map next = new ConcurrentHashMap<>(Math.max(16, list.size())); + for (TApiKeyEntity e : list) { + next.put(e.getApiKey(), JwtUserClaimsDto.builder() + .userId(e.getUserId()) + .userCmpn(e.getUserCmpn()) + .userTeam(e.getUserTeam()) + .userName(e.getUserName()) + .userRole(e.getUserRole()) + .build()); } - /** 기동 시 preload */ - @Override - public void run(ApplicationArguments args) { - if (!props.isEnabled()) return; - if (!props.isPreloadOnStartup()) return; - reloadFromDb(); - } + cacheRef.set(Collections.unmodifiableMap(next)); + return next.size(); + } - /** 운영용: DB에서 다시 읽어 캐시 전체 교체 */ - public synchronized int reloadFromDb() { - if (!StringUtils.hasText(props.getServiceCode())) { - // serviceCode 없으면 preload 불가 → 안전하게 빈 캐시 - cacheRef.set(Collections.emptyMap()); - return 0; - } - - var list = repo.findActiveKeysForService(props.getServiceCode()); - - Map next = new ConcurrentHashMap<>(Math.max(16, list.size())); - for (TApiKeyEntity e : list) { - next.put(e.getApiKey(), JwtUserClaimsDto.builder() - .userId(e.getUserId()) - .userCmpn(e.getUserCmpn()) - .userTeam(e.getUserTeam()) - .userName(e.getUserName()) - .userRole(e.getUserRole()) - .build()); - } - - cacheRef.set(Collections.unmodifiableMap(next)); - return next.size(); - } - - /** Admin 조회용(마스킹은 컨트롤러에서) */ - public Map snapshot() { - return cacheRef.get(); - } + /** + * Admin 조회용(마스킹은 컨트롤러에서) + */ + public Map snapshot() { + return cacheRef.get(); + } } diff --git a/src/main/java/com/kri/common/auth/dto/JwtUserClaimsDto.java b/src/main/java/com/kri/common/auth/dto/JwtUserClaimsDto.java index 9bf0ae1..20bc5b7 100644 --- a/src/main/java/com/kri/common/auth/dto/JwtUserClaimsDto.java +++ b/src/main/java/com/kri/common/auth/dto/JwtUserClaimsDto.java @@ -5,25 +5,25 @@ import lombok.Builder; import lombok.Value; @Schema( - name = "JwtUserClaimsDto", - description = "JWT에 포함되는 사용자 정보" + name = "JwtUserClaimsDto", + description = "JWT에 포함되는 사용자 정보" ) @Value @Builder public class JwtUserClaimsDto { - @Schema(description = "사용자 ID") - String userId; + @Schema(description = "사용자 ID") + String userId; - @Schema(description = "사용자 소속 회사") - String userCmpn; + @Schema(description = "사용자 소속 회사") + String userCmpn; - @Schema(description = "팀 코드") - String userTeam; + @Schema(description = "팀 코드") + String userTeam; - @Schema(description = "사용자 이름") - String userName; + @Schema(description = "사용자 이름") + String userName; - @Schema(description = "권한 코드") - Integer userRole; + @Schema(description = "권한 코드") + Integer userRole; } diff --git a/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java b/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java index 8564aa4..dd8f719 100644 --- a/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java +++ b/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java @@ -13,22 +13,22 @@ import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class}) public class JwtAutoConfiguration { - @Bean - @ConditionalOnMissingBean - public JwtService jwtService(JwtProperties properties) { - return new JwtService(properties); - } + @Bean + @ConditionalOnMissingBean + public JwtService jwtService(JwtProperties properties) { + return new JwtService(properties); + } - /** - * ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. - * (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행) - */ - @Bean - @ConditionalOnBean(ApiKeyUserClaimsProvider.class) - @ConditionalOnMissingBean - public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties, - ApiKeyUserClaimsProvider provider, - JwtService jwtService) { - return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService); - } + /** + * ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 + * addFilterBefore 로 수행) + */ + @Bean + @ConditionalOnBean(ApiKeyUserClaimsProvider.class) + @ConditionalOnMissingBean + public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties, + ApiKeyUserClaimsProvider provider, + JwtService jwtService) { + return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService); + } } diff --git a/src/main/java/com/kri/common/auth/jwt/JwtProperties.java b/src/main/java/com/kri/common/auth/jwt/JwtProperties.java index 1e44967..ea5cd66 100644 --- a/src/main/java/com/kri/common/auth/jwt/JwtProperties.java +++ b/src/main/java/com/kri/common/auth/jwt/JwtProperties.java @@ -1,6 +1,9 @@ package com.kri.common.auth.jwt; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; @Getter @@ -10,23 +13,23 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "kri.auth.jwt") public class JwtProperties { - /** - * HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장) - */ - private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M"; + /** + * HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장) + */ + private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M"; - /** - * 토큰 발급자(issuer) - */ - private String issuer = "kri-it"; + /** + * 토큰 발급자(issuer) + */ + private String issuer = "kri-it"; - /** - * Access Token 유효 시간(초 단위) - */ - private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간 + /** + * Access Token 유효 시간(초 단위) + */ + private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간 - /** - * (선택) Refresh Token 유효 시간(초 단위) - */ - private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일 + /** + * (선택) Refresh Token 유효 시간(초 단위) + */ + private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일 } diff --git a/src/main/java/com/kri/common/auth/jwt/JwtService.java b/src/main/java/com/kri/common/auth/jwt/JwtService.java index 35ee34d..43ed3ee 100644 --- a/src/main/java/com/kri/common/auth/jwt/JwtService.java +++ b/src/main/java/com/kri/common/auth/jwt/JwtService.java @@ -1,189 +1,192 @@ package com.kri.common.auth.jwt; import com.kri.common.auth.dto.JwtUserClaimsDto; -import io.jsonwebtoken.*; +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; -import javax.crypto.SecretKey; -import java.nio.charset.StandardCharsets; -import java.util.*; - /** - * 공통 JWT 유틸 서비스 - * - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - * - 일반 JWT + 내부 고정 토큰 둘 다 지원 + * 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원 */ @RequiredArgsConstructor public class JwtService { - private final JwtProperties properties; + private final JwtProperties properties; - private SecretKey key; + 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)); + @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 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 buildClaims(JwtUserClaimsDto dto) { + Map claims = new HashMap<>(); + // 필요한 항목만 골라서 claim에 넣어줌 + 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; + } + + // ====================================================== + // 토큰 생성 (DTO 기반) + // ====================================================== + + /** + * JwtUserClaimsDto 기반 Access Token 생성 - subject = userId - claims: userId, userCmpn, userTeam, + * userName, role + */ + public String generateAccessToken(JwtUserClaimsDto userClaims) { + Map claims = buildClaims(userClaims); + return buildToken( + claims, + userClaims.getUserId(), + properties.getAccessTokenValiditySeconds() + ); + } + + /** + * Refresh Token은 보통 userId만 넣고 심플하게 사용 + */ + public String generateRefreshToken(String userId) { + return buildToken( + Collections.emptyMap(), + userId, + properties.getRefreshTokenValiditySeconds() + ); + } + + // ====================================================== + // 토큰 파싱 + // ====================================================== + + /** + * 토큰 파싱 + 서명/만료 검증 + */ + public Jws parseToken(String token) throws JwtException { + return Jwts.parserBuilder() + .requireIssuer(properties.getIssuer()) + .setSigningKey(key) + .build() + .parseClaimsJws(token); + } + + /** + * 토큰에서 Claims만 추출 (검증 포함) + */ + public Claims getClaims(String token) throws JwtException { + return parseToken(token).getBody(); + } + + /** + * Claims → JwtUserClaimsDto 변환 + */ + public JwtUserClaimsDto toUserClaimsDto(Claims claims) { + // userId는 subject와 별도 claim 둘 다에서 시도 + 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); - private String buildToken(Map claims, String subject, long validitySeconds) { - Date now = new Date(); - Date expiry = new Date(now.getTime() + validitySeconds * 1000); + // 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue() + Number roleNumber = claims.get("role", Number.class); + Integer userRole = roleNumber != null ? roleNumber.intValue() : null; - return Jwts.builder() - .setClaims(claims) - .setSubject(subject) - .setIssuer(properties.getIssuer()) - .setIssuedAt(now) - .setExpiration(expiry) - .signWith(key, SignatureAlgorithm.HS256) - .compact(); + return JwtUserClaimsDto.builder() + .userId(userId) + .userCmpn(userCmpn) + .userTeam(userTeam) + .userName(userName) + .userRole(userRole) + .build(); + } + + /** + * 토큰 → JwtUserClaimsDto 바로 추출 + */ + public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException { + Claims claims = getClaims(token); + return toUserClaimsDto(claims); + } + + // ====================================================== + // Authentication 변환 (Spring Security 연동용) + // ====================================================== + + /** + * DTO → Spring Security Authentication 변환 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. ex) role = + * 1 → "ROLE_1" 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면, 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨. + */ + public Authentication toAuthentication(JwtUserClaimsDto dto) { + String principal = dto.getUserId(); + + List authorities = new ArrayList<>(); + if (dto.getUserRole() != null) { + String authority = "ROLE_" + dto.getUserRole(); + authorities.add(new SimpleGrantedAuthority(authority)); } - private Map buildClaims(JwtUserClaimsDto dto) { - Map claims = new HashMap<>(); - // 필요한 항목만 골라서 claim에 넣어줌 - 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; - } + return new UsernamePasswordAuthenticationToken( + principal, + null, + authorities + ); + } - // ====================================================== - // 토큰 생성 (DTO 기반) - // ====================================================== - /** - * JwtUserClaimsDto 기반 Access Token 생성 - * - subject = userId - * - claims: - * userId, userCmpn, userTeam, userName, role - */ - public String generateAccessToken(JwtUserClaimsDto userClaims) { - Map claims = buildClaims(userClaims); - return buildToken( - claims, - userClaims.getUserId(), - properties.getAccessTokenValiditySeconds() - ); - } - - /** - * Refresh Token은 보통 userId만 넣고 심플하게 사용 - */ - public String generateRefreshToken(String userId) { - return buildToken( - Collections.emptyMap(), - userId, - properties.getRefreshTokenValiditySeconds() - ); - } - - // ====================================================== - // 토큰 파싱 - // ====================================================== - - /** - * 토큰 파싱 + 서명/만료 검증 - */ - public Jws parseToken(String token) throws JwtException { - return Jwts.parserBuilder() - .requireIssuer(properties.getIssuer()) - .setSigningKey(key) - .build() - .parseClaimsJws(token); - } - - /** - * 토큰에서 Claims만 추출 (검증 포함) - */ - public Claims getClaims(String token) throws JwtException { - return parseToken(token).getBody(); - } - - /** - * Claims → JwtUserClaimsDto 변환 - */ - public JwtUserClaimsDto toUserClaimsDto(Claims claims) { - // userId는 subject와 별도 claim 둘 다에서 시도 - 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); - - // 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue() - 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(); - } - - /** - * 토큰 → JwtUserClaimsDto 바로 추출 - */ - public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException { - Claims claims = getClaims(token); - return toUserClaimsDto(claims); - } - - // ====================================================== - // Authentication 변환 (Spring Security 연동용) - // ====================================================== - - /** - * DTO → Spring Security Authentication 변환 - * 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. - * ex) role = 1 → "ROLE_1" - * 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면, - * 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨. - */ - public Authentication toAuthentication(JwtUserClaimsDto dto) { - String principal = dto.getUserId(); - - List authorities = new ArrayList<>(); - if (dto.getUserRole() != null) { - String authority = "ROLE_" + dto.getUserRole(); - authorities.add(new SimpleGrantedAuthority(authority)); - } - - return new UsernamePasswordAuthenticationToken( - principal, - null, - authorities - ); - } - - /** - * 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에) - */ - public Authentication toAuthentication(String token) throws JwtException { - JwtUserClaimsDto dto = toUserClaimsDto(token); - return toAuthentication(dto); - } + /** + * 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에) + */ + public Authentication toAuthentication(String token) throws JwtException { + JwtUserClaimsDto dto = toUserClaimsDto(token); + return toAuthentication(dto); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyEntity.java b/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyEntity.java index d2c9c5e..fc64dd4 100644 --- a/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyEntity.java +++ b/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyEntity.java @@ -1,54 +1,59 @@ package com.kri.common.auth.persistence.entity; -import jakarta.persistence.*; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.LocalDateTime; +import java.util.Map; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; -import java.time.LocalDateTime; -import java.util.Map; - @Getter @Setter @Entity @Table(name = "t_api_key") public class TApiKeyEntity { - @Id - @Column(name = "api_key", nullable = false, length = 256) - private String apiKey; - /** 1=ACTIVE, 0=REVOKED */ - @Column(name = "status", nullable = false) - @ColumnDefault("1") - private Short status; + @Id + @Column(name = "api_key", nullable = false, length = 256) + private String apiKey; - @Column(name = "user_id", nullable = false, length = 32) - private String userId; + /** + * 1=ACTIVE, 0=REVOKED + */ + @Column(name = "status", nullable = false) + @ColumnDefault("1") + private Short status; - @Column(name = "user_cmpn", length = 64) - private String userCmpn; + @Column(name = "user_id", nullable = false, length = 32) + private String userId; - @Column(name = "user_team", length = 64) - private String userTeam; + @Column(name = "user_cmpn", length = 64) + private String userCmpn; - @Column(name = "user_name", length = 64) - private String userName; + @Column(name = "user_team", length = 64) + private String userTeam; - @Column(name = "user_role", nullable = false) - private Integer userRole; + @Column(name = "user_name", length = 64) + private String userName; - /*기본 정보 외*/ - @Column(name = "user_json") - @JdbcTypeCode(SqlTypes.JSON) - private Map userJson; + @Column(name = "user_role", nullable = false) + private Integer userRole; - @Column(name = "reg_user", nullable = false, length = 32) - private String regUser; + /*기본 정보 외*/ + @Column(name = "user_json") + @JdbcTypeCode(SqlTypes.JSON) + private Map userJson; - @Column(name = "reg_dt", nullable = false) - @ColumnDefault("CURRENT_TIMESTAMP") - private LocalDateTime regDt; + @Column(name = "reg_user", nullable = false, length = 32) + private String regUser; + + @Column(name = "reg_dt", nullable = false) + @ColumnDefault("CURRENT_TIMESTAMP") + private LocalDateTime regDt; } diff --git a/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntity.java b/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntity.java index ab022bf..323e143 100644 --- a/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntity.java +++ b/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntity.java @@ -11,10 +11,15 @@ import lombok.Setter; @Entity @Table(name = "t_api_key_service_map") public class TApiKeyServiceMapEntity { - @EmbeddedId - private TApiKeyServiceMapEntityId id; - public String getApiKey() { return id.getApiKey(); } + @EmbeddedId + private TApiKeyServiceMapEntityId id; - public String getServiceCode() { return id.getServiceCode(); } + public String getApiKey() { + return id.getApiKey(); + } + + public String getServiceCode() { + return id.getServiceCode(); + } } diff --git a/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntityId.java b/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntityId.java index 5cbc34b..45beb77 100644 --- a/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntityId.java +++ b/src/main/java/com/kri/common/auth/persistence/entity/TApiKeyServiceMapEntityId.java @@ -3,36 +3,40 @@ package com.kri.common.auth.persistence.entity; import jakarta.persistence.Column; import jakarta.persistence.Embeddable; import jakarta.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Objects; import lombok.Getter; import lombok.Setter; import org.hibernate.Hibernate; -import java.io.Serializable; -import java.util.Objects; - @Getter @Setter @Embeddable public class TApiKeyServiceMapEntityId implements Serializable { - @NotNull - @Column(name = "api_key", nullable = false, length = 256) - private String apiKey; - @NotNull - @Column(name = "service_code", nullable = false, length = 64) - private String serviceCode; + @NotNull + @Column(name = "api_key", nullable = false, length = 256) + private String apiKey; - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; - TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o; - return Objects.equals(this.apiKey, entity.apiKey) && - Objects.equals(this.serviceCode, entity.serviceCode); + @NotNull + @Column(name = "service_code", nullable = false, length = 64) + private String serviceCode; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public int hashCode() { - return Objects.hash(apiKey, serviceCode); + if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) { + return false; } + TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o; + return Objects.equals(this.apiKey, entity.apiKey) && + Objects.equals(this.serviceCode, entity.serviceCode); + } + + @Override + public int hashCode() { + return Objects.hash(apiKey, serviceCode); + } } diff --git a/src/main/java/com/kri/common/auth/persistence/repository/ApiKeyRepository.java b/src/main/java/com/kri/common/auth/persistence/repository/ApiKeyRepository.java index 229a38a..04fcd47 100644 --- a/src/main/java/com/kri/common/auth/persistence/repository/ApiKeyRepository.java +++ b/src/main/java/com/kri/common/auth/persistence/repository/ApiKeyRepository.java @@ -1,19 +1,21 @@ package com.kri.common.auth.persistence.repository; import com.kri.common.auth.persistence.entity.TApiKeyEntity; +import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import java.util.List; - public interface ApiKeyRepository extends JpaRepository { - /** ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 */ - @Query(""" - select a - from TApiKeyEntity a - join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey - where a.status = 1 and m.id.serviceCode = :serviceCode - """) - List findActiveKeysForService(@Param("serviceCode")String serviceCode); + + /** + * ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 + */ + @Query(""" + select a + from TApiKeyEntity a + join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey + where a.status = 1 and m.id.serviceCode = :serviceCode + """) + List findActiveKeysForService(@Param("serviceCode") String serviceCode); } diff --git a/src/main/java/com/kri/common/cache/AbstractListCache.java b/src/main/java/com/kri/common/cache/AbstractListCache.java index 9cbc6b4..42edc38 100644 --- a/src/main/java/com/kri/common/cache/AbstractListCache.java +++ b/src/main/java/com/kri/common/cache/AbstractListCache.java @@ -1,115 +1,120 @@ package com.kri.common.cache; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.context.event.EventListener; -import org.springframework.transaction.annotation.Transactional; - 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 { - private List list = List.of(); - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private List list = List.of(); - @EventListener(ApplicationReadyEvent.class) - @Transactional(readOnly = true) - public void loadOnStartup() { - List tempList = loadFromDb(); - if(tempList != null) setList(tempList); + @EventListener(ApplicationReadyEvent.class) + @Transactional(readOnly = true) + public void loadOnStartup() { + List tempList = loadFromDb(); + if (tempList != null) { + setList(tempList); + } + } + + public List getList() { + lock.readLock().lock(); + try { + return list; + } finally { + lock.readLock().unlock(); + } + } + + public void setList(List next) { + lock.writeLock().lock(); + try { + this.list = List.copyOf(next == null ? List.of() : next); + } finally { + lock.writeLock().unlock(); + } + } + + @Transactional(readOnly = true) + public List reload() { + List tempList = loadFromDb(); + if (tempList == null) { + throw new UnsupportedOperationException("This cache does not support reload()."); + } + setList(tempList); + return getList(); + } + + public List clear() { + lock.writeLock().lock(); + try { + return list = List.of(); + } finally { + lock.writeLock().unlock(); + } + } + + public void addAll(List items) { + if (items == null || items.isEmpty()) { + return; + } + lock.writeLock().lock(); + try { + List 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 items) { + if (items == null || items.isEmpty()) { + return; } - public List getList() { - lock.readLock().lock(); - try { - return list; - } finally { - lock.readLock().unlock(); - } + lock.writeLock().lock(); + try { + ArrayList 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(); } + } - @Transactional(readOnly = true) - public List reload() { - List tempList = loadFromDb(); - if(tempList == null) { - throw new UnsupportedOperationException("This cache does not support reload()."); - } - setList(tempList); - return getList(); + public void add(T item) { + lock.writeLock().lock(); + try { + List merged = new java.util.ArrayList<>(this.list); + merged.add(item); + this.list = List.copyOf(merged); + } finally { + lock.writeLock().unlock(); } + } - public List clear() { - lock.writeLock().lock(); - try{ - return list = List.of(); - } finally { - lock.writeLock().unlock(); - } + public void add(int index, T item) { + lock.writeLock().lock(); + + try { + ArrayList 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(); } + } - public void setList(List next) { - lock.writeLock().lock(); - try { - this.list = List.copyOf(next == null ? List.of() : next); - } finally { - lock.writeLock().unlock(); - } - } - - public void addAll(List items) { - if (items == null || items.isEmpty()) return; - lock.writeLock().lock(); - try { - List 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 items) { - if (items == null || items.isEmpty()) return; - - lock.writeLock().lock(); - try { - ArrayList 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 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 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 loadFromDb() { - return null; - } + protected List loadFromDb() { + return null; + } } diff --git a/src/main/java/com/kri/common/cache/AbstractMapCache.java b/src/main/java/com/kri/common/cache/AbstractMapCache.java index 8cf6d4b..4fe683a 100644 --- a/src/main/java/com/kri/common/cache/AbstractMapCache.java +++ b/src/main/java/com/kri/common/cache/AbstractMapCache.java @@ -1,110 +1,119 @@ package com.kri.common.cache; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.context.event.EventListener; -import org.springframework.transaction.annotation.Transactional; - 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 { - private Map map = Map.of(); - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private Map map = Map.of(); - @EventListener(ApplicationReadyEvent.class) - @Transactional(readOnly = true) - public void loadOnStartup() { - Map tempMap = loadFromDb(); - if(tempMap != null) setMap(tempMap); + @EventListener(ApplicationReadyEvent.class) + @Transactional(readOnly = true) + public void loadOnStartup() { + Map tempMap = loadFromDb(); + if (tempMap != null) { + setMap(tempMap); + } + } + + public Map getMap() { + lock.readLock().lock(); + try { + return map; + } finally { + lock.readLock().unlock(); + } + } + + /** + * 수동: 전체 교체(불변 스냅샷으로 보관) + */ + public void setMap(Map 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 reload() { + Map 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 merged = new HashMap<>(this.map); + merged.put(key, value); + this.map = Map.copyOf(merged); + } finally { + lock.writeLock().unlock(); + } + } + + /** + * 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체) + */ + public void putAll(Map entries) { + if (entries == null || entries.isEmpty()) { + return; } - public Map getMap() { - lock.readLock().lock(); - try { - return map; - } finally { - lock.readLock().unlock(); - } + lock.writeLock().lock(); + try { + Map merged = new HashMap<>(this.map); + merged.putAll(entries); + this.map = Map.copyOf(merged); + } finally { + lock.writeLock().unlock(); } + } - public V get(K key) { - lock.readLock().lock(); - try { - return map.get(key); - } finally { - lock.readLock().unlock(); - } + /** + * clear: 완전 비우기 + */ + public void clear() { + lock.writeLock().lock(); + try { + this.map = Map.of(); + } finally { + lock.writeLock().unlock(); } + } - public boolean containsKey(K key) { - lock.readLock().lock(); - try { - return map.containsKey(key); - } finally { - lock.readLock().unlock(); - } - } - - @Transactional(readOnly = true) - public Map reload() { - Map tempMap = loadFromDb(); - if(tempMap == null) { - throw new UnsupportedOperationException("This cache does not support reload()."); - } - setMap(tempMap); - return getMap(); - } - - /** 수동: 전체 교체(불변 스냅샷으로 보관) */ - public void setMap(Map next) { - lock.writeLock().lock(); - try { - this.map = Map.copyOf(next == null ? Map.of() : next); - } finally { - lock.writeLock().unlock(); - } - } - - public void put(K key, V value) { - lock.writeLock().lock(); - try { - Map merged = new HashMap<>(this.map); - merged.put(key, value); - this.map = Map.copyOf(merged); - } finally { - lock.writeLock().unlock(); - } - } - - /** 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체) */ - public void putAll(Map entries) { - if (entries == null || entries.isEmpty()) return; - - lock.writeLock().lock(); - try { - Map 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 loadFromDb() { - return null; - } + // 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현 + protected Map loadFromDb() { + return null; + } } diff --git a/src/main/java/com/kri/common/datetime/DateTimeUtil.java b/src/main/java/com/kri/common/datetime/DateTimeUtil.java index 2fc663a..4dd365b 100644 --- a/src/main/java/com/kri/common/datetime/DateTimeUtil.java +++ b/src/main/java/com/kri/common/datetime/DateTimeUtil.java @@ -1,186 +1,273 @@ package com.kri.common.datetime; -import java.time.*; +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 { - private 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"); - public static final ZoneId KST = ZoneId.of("Asia/Seoul"); - public static final ZoneId UTC = ZoneOffset.UTC; + private DateTimeUtil() { + } - /** 날짜+시간: 2025-11-28 15:00:14 */ - public static final DateTimeFormatter DATETIME_FMT = - DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + /* ======================= + * Now (KST) + * ======================= */ - /** 날짜: 2025-11-28 */ - public static final DateTimeFormatter DATE_FMT = - DateTimeFormatter.ofPattern("yyyy-MM-dd"); + /** + * 현재 KST 날짜+시간 문자열 + */ + public static String nowKstDateTime() { + return formatKst(Instant.now(), DATETIME_FMT); + } - /* ======================= - * Now (KST) - * ======================= */ + /** + * 현재 KST 날짜 문자열 + */ + public static String nowKstDate() { + return nowKstZoned().format(DATE_FMT); + } - /** 현재 KST 날짜+시간 문자열 */ - public static String nowKstDateTime() { - return formatKst(Instant.now(), DATETIME_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; } - /** 현재 KST 날짜 문자열 */ - public static String nowKstDate() { - return nowKstZoned().format(DATE_FMT); + 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) { } - /** 현재 KST ZonedDateTime */ - public static ZonedDateTime nowKstZoned() { - return Instant.now().atZone(KST); + return false; + } + + /* ======================= + * Parse (String -> Instant) + * ======================= */ + + /** + * ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도) + */ + public static Instant parseToInstant(String text) { + if (text == null || text.isBlank()) { + return null; } - /** 현재 KST LocalDateTime */ - public static LocalDateTime nowKstLocalDateTime() { - return nowKstZoned().toLocalDateTime(); + 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) { } - /** 현재 KST LocalDate */ - public static LocalDate nowKstLocalDate() { - return nowKstZoned().toLocalDate(); + 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"); - /* ======================= - * Format (Instant -> String) - * ======================= */ + LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter); + return ldt.atZone(KST).toInstant(); + } - /** Instant -> KST 날짜+시간 문자열 */ - public static String formatKstDateTime(Instant instant) { - return formatKst(instant, DATETIME_FMT); + /** + * "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(); + } - /** Instant -> KST 날짜 문자열 */ - public static String formatKstDate(Instant instant) { - return formatKst(instant, DATE_FMT); + /* ======================= + * 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; + } - /** 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); + 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; } - - /* ======================= - * Validate - * ======================= */ - - /** "yyyy-MM-dd" 형태인지 */ - public static boolean isDate(String text) { - return tryParseLocalDate(text, DATE_FMT) != null; + try { + return LocalDate.parse(text.trim(), fmt); + } catch (DateTimeParseException e) { + return null; } + } - /** "yyyy-MM-dd HH:mm:ss" 형태인지 */ - public static boolean isDateTime(String text) { - return tryParseLocalDateTime(text, DATETIME_FMT) != null; + private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) { + if (text == null || text.isBlank()) { + return 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; } + try { + return LocalDateTime.parse(text.trim(), fmt); + } catch (DateTimeParseException e) { + return null; } + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/datetime/LenientLocalDateTime.java b/src/main/java/com/kri/common/datetime/LenientLocalDateTime.java index 8163b5b..06868ef 100644 --- a/src/main/java/com/kri/common/datetime/LenientLocalDateTime.java +++ b/src/main/java/com/kri/common/datetime/LenientLocalDateTime.java @@ -2,8 +2,11 @@ package com.kri.common.datetime; import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -import java.lang.annotation.*; +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) @@ -12,12 +15,12 @@ import java.lang.annotation.*; @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" - }; + 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" + }; } diff --git a/src/main/java/com/kri/common/datetime/LenientLocalDateTimeDeserializer.java b/src/main/java/com/kri/common/datetime/LenientLocalDateTimeDeserializer.java index 58e1264..011af4d 100644 --- a/src/main/java/com/kri/common/datetime/LenientLocalDateTimeDeserializer.java +++ b/src/main/java/com/kri/common/datetime/LenientLocalDateTimeDeserializer.java @@ -6,7 +6,6 @@ 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; @@ -16,72 +15,79 @@ import java.time.temporal.ChronoField; import java.util.Arrays; public class LenientLocalDateTimeDeserializer extends JsonDeserializer - implements ContextualDeserializer { + implements ContextualDeserializer { - private final DateTimeFormatter[] formatters; + 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" - }); + 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(); } - private LenientLocalDateTimeDeserializer(String[] patterns) { - this.formatters = Arrays.stream(patterns) - .map(LenientLocalDateTimeDeserializer::withDefaultTimeParts) - .toArray(DateTimeFormatter[]::new); + // 패턴에 분/초가 없으면 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; } - 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(); + for (DateTimeFormatter f : formatters) { + try { + return LocalDateTime.parse(s, f); + } catch (DateTimeParseException ignored) { + } } - @Override - public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String s = DateTimeUtil.trimToNull(p.getText()); - if (s == null) return null; + throw ctxt.weirdStringException(s, LocalDateTime.class, + "Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime"); + } - 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; } - @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()); + LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class); + if (ann == null) { + ann = property.getContextAnnotation(LenientLocalDateTime.class); } + + return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns()); + } } diff --git a/src/main/java/com/kri/common/enums/CodeEnum.java b/src/main/java/com/kri/common/enums/CodeEnum.java index 8d88c74..f341a05 100644 --- a/src/main/java/com/kri/common/enums/CodeEnum.java +++ b/src/main/java/com/kri/common/enums/CodeEnum.java @@ -1,5 +1,6 @@ package com.kri.common.enums; public interface CodeEnum { - T getCode(); + + T getCode(); } \ No newline at end of file diff --git a/src/main/java/com/kri/common/enums/CodeEnumUtils.java b/src/main/java/com/kri/common/enums/CodeEnumUtils.java index 7cd8f1e..9245e23 100644 --- a/src/main/java/com/kri/common/enums/CodeEnumUtils.java +++ b/src/main/java/com/kri/common/enums/CodeEnumUtils.java @@ -2,19 +2,22 @@ package com.kri.common.enums; public final class CodeEnumUtils { - private CodeEnumUtils() {} + private CodeEnumUtils() { + } - public static & CodeEnum, V> E fromCode(Class 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() - ); + public static & CodeEnum, V> E fromCode(Class 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() + ); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/excel/ExcelColumn.java b/src/main/java/com/kri/common/excel/ExcelColumn.java index 7e20236..4f412bc 100644 --- a/src/main/java/com/kri/common/excel/ExcelColumn.java +++ b/src/main/java/com/kri/common/excel/ExcelColumn.java @@ -1,11 +1,17 @@ package com.kri.common.excel; -import java.lang.annotation.*; +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 그대로 + + String header(); // 엑셀 헤더 이름 + + int order() default 0; // 컬럼 순서 + + int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로 } \ No newline at end of file diff --git a/src/main/java/com/kri/common/excel/ExcelMapper.java b/src/main/java/com/kri/common/excel/ExcelMapper.java index 60ad20a..5ffaba0 100644 --- a/src/main/java/com/kri/common/excel/ExcelMapper.java +++ b/src/main/java/com/kri/common/excel/ExcelMapper.java @@ -1,7 +1,25 @@ package com.kri.common.excel; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.RichTextString; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.model.SharedStringsTable; @@ -13,623 +31,643 @@ import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; -import java.io.OutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.util.*; - /** * Excel <-> 객체/맵 변환 유틸리티 - * - * 전제: - * - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다. - * - 셀 값 파싱은 ExcelUtil.getStringCell(Cell) 사용. + *

+ * 전제: - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다. - 셀 값 파싱은 + * ExcelUtil.getStringCell(Cell) 사용. */ public final class ExcelMapper { - private ExcelMapper() { - // 유틸 클래스 - 인스턴스 생성 방지 + private ExcelMapper() { + // 유틸 클래스 - 인스턴스 생성 방지 + } + + /* ========================================================= + * 1. List -> XSSFWorkbook (in-memory 쓰기) + * ========================================================= */ + + public static Workbook writeToWorkbook(List data, Class clazz) { + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Sheet1"); + + // 1) @ExcelColumn 기반 메타 수집 + List fields = getExcelFields(clazz); + + // 2) 헤더 작성 + Row headerRow = sheet.createRow(0); + for (ExcelFieldMeta meta : fields) { + Cell cell = headerRow.createCell(meta.order()); + cell.setCellValue(meta.header()); } - /* ========================================================= - * 1. List -> XSSFWorkbook (in-memory 쓰기) - * ========================================================= */ - - public static Workbook writeToWorkbook(List data, Class clazz) { - Workbook workbook = new XSSFWorkbook(); - Sheet sheet = workbook.createSheet("Sheet1"); - - // 1) @ExcelColumn 기반 메타 수집 - List fields = getExcelFields(clazz); - - // 2) 헤더 작성 - Row headerRow = sheet.createRow(0); + // 3) 데이터 작성 + int rowIndex = 1; + if (data != null) { + for (T item : data) { + Row row = sheet.createRow(rowIndex++); for (ExcelFieldMeta meta : fields) { - Cell cell = headerRow.createCell(meta.order()); - cell.setCellValue(meta.header()); + Cell cell = row.createCell(meta.order()); + Object value = meta.getValue(item); + cell.setCellValue(value != null ? value.toString() : ""); } + } + } - // 3) 데이터 작성 - int rowIndex = 1; - if (data != null) { - for (T item : data) { - Row row = sheet.createRow(rowIndex++); - for (ExcelFieldMeta meta : fields) { - Cell cell = row.createCell(meta.order()); - Object value = meta.getValue(item); - cell.setCellValue(value != null ? value.toString() : ""); - } - } - } + // 4) 자동 너비 조정 + for (ExcelFieldMeta meta : fields) { + if (meta.width() > 0) { + sheet.setColumnWidth(meta.order(), meta.width() * 256); + } else { + sheet.autoSizeColumn(meta.order()); + } + } + + return workbook; + } + + /* ========================================================= + * 2. Workbook -> List (in-memory 읽기) + * ========================================================= */ + + public static List readFromWorkbook(Workbook workbook, Class clazz) { + Sheet sheet = workbook.getSheetAt(0); + + // 1) 헤더 행 + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + return List.of(); + } + + Map headerIndexMap = new HashMap<>(); + short lastCellNum = headerRow.getLastCellNum(); + for (int c = 0; c < lastCellNum; c++) { + Cell cell = headerRow.getCell(c); + if (cell != null) { + String headerName = cell.getStringCellValue(); + headerIndexMap.put(headerName, c); + } + } + + // 2) DTO 필드 메타 + List fields = getExcelFields(clazz); + + // 3) 데이터 행 -> DTO + List result = new ArrayList<>(); + int lastRowNum = sheet.getLastRowNum(); + + for (int r = 1; r <= lastRowNum; r++) { + Row row = sheet.getRow(r); + if (row == null) { + continue; + } + + try { + T instance = clazz.getDeclaredConstructor().newInstance(); - // 4) 자동 너비 조정 for (ExcelFieldMeta meta : fields) { - if (meta.width() > 0) { - sheet.setColumnWidth(meta.order(), meta.width() * 256); - } else { - sheet.autoSizeColumn(meta.order()); - } + Integer colIdx = headerIndexMap.get(meta.header()); + if (colIdx == null) { + continue; + } + + Cell cell = row.getCell(colIdx); + String cellValue = ExcelUtil.getStringCell(cell); + + if (cellValue != null) { + setFieldValue(instance, meta.field(), cellValue); + } } - return workbook; + result.add(instance); + } catch (Exception e) { + throw new RuntimeException("엑셀 파싱 중 오류 (row=" + (r + 1) + ")", e); + } } - /* ========================================================= - * 2. Workbook -> List (in-memory 읽기) - * ========================================================= */ + return result; + } - public static List readFromWorkbook(Workbook workbook, Class clazz) { - Sheet sheet = workbook.getSheetAt(0); + /* ========================================================= + * 3. Workbook -> List> (in-memory 읽기) + * ========================================================= */ - // 1) 헤더 행 - Row headerRow = sheet.getRow(0); - if (headerRow == null) { - return List.of(); - } + public static List> readAsMapList(Workbook workbook) { + Sheet sheet = workbook.getSheetAt(0); - Map headerIndexMap = new HashMap<>(); - short lastCellNum = headerRow.getLastCellNum(); - for (int c = 0; c < lastCellNum; c++) { - Cell cell = headerRow.getCell(c); - if (cell != null) { - String headerName = cell.getStringCellValue(); - headerIndexMap.put(headerName, c); - } - } - - // 2) DTO 필드 메타 - List fields = getExcelFields(clazz); - - // 3) 데이터 행 -> DTO - List result = new ArrayList<>(); - int lastRowNum = sheet.getLastRowNum(); - - for (int r = 1; r <= lastRowNum; r++) { - Row row = sheet.getRow(r); - if (row == null) continue; - - try { - T instance = clazz.getDeclaredConstructor().newInstance(); - - for (ExcelFieldMeta meta : fields) { - Integer colIdx = headerIndexMap.get(meta.header()); - if (colIdx == null) continue; - - Cell cell = row.getCell(colIdx); - String cellValue = ExcelUtil.getStringCell(cell); - - if (cellValue != null) { - setFieldValue(instance, meta.field(), cellValue); - } - } - - result.add(instance); - } catch (Exception e) { - throw new RuntimeException("엑셀 파싱 중 오류 (row=" + (r + 1) + ")", e); - } - } - - return result; + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + return List.of(); } - /* ========================================================= - * 3. Workbook -> List> (in-memory 읽기) - * ========================================================= */ + int lastCol = headerRow.getLastCellNum(); + List headers = new ArrayList<>(lastCol); - public static List> readAsMapList(Workbook workbook) { - Sheet sheet = workbook.getSheetAt(0); - - Row headerRow = sheet.getRow(0); - if (headerRow == null) { - return List.of(); - } - - int lastCol = headerRow.getLastCellNum(); - List headers = new ArrayList<>(lastCol); - - for (int c = 0; c < lastCol; c++) { - Cell cell = headerRow.getCell(c); - String headerName = (cell != null) ? cell.getStringCellValue() : ("COL_" + c); - headers.add(headerName); - } - - List> result = new ArrayList<>(); - int lastRow = sheet.getLastRowNum(); - - for (int r = 1; r <= lastRow; r++) { - Row row = sheet.getRow(r); - if (row == null) continue; - - Map rowMap = new LinkedHashMap<>(); - boolean allBlank = true; - - for (int c = 0; c < lastCol; c++) { - Cell cell = row.getCell(c); - String v = ExcelUtil.getStringCell(cell); - if (v != null && !v.isBlank()) { - allBlank = false; - } - rowMap.put(headers.get(c), v); - } - - if (!allBlank) { - result.add(rowMap); - } - } - - return result; + for (int c = 0; c < lastCol; c++) { + Cell cell = headerRow.getCell(c); + String headerName = (cell != null) ? cell.getStringCellValue() : ("COL_" + c); + headers.add(headerName); } - /* ========================================================= - * 4. List> -> Workbook (in-memory 쓰기) - * ========================================================= */ + List> result = new ArrayList<>(); + int lastRow = sheet.getLastRowNum(); - public static Workbook writeFromMapList(List> rows) { - Workbook workbook = new XSSFWorkbook(); - Sheet sheet = workbook.createSheet("Sheet1"); + for (int r = 1; r <= lastRow; r++) { + Row row = sheet.getRow(r); + if (row == null) { + continue; + } - if (rows == null || rows.isEmpty()) { - return workbook; + Map rowMap = new LinkedHashMap<>(); + boolean allBlank = true; + + for (int c = 0; c < lastCol; c++) { + Cell cell = row.getCell(c); + String v = ExcelUtil.getStringCell(cell); + if (v != null && !v.isBlank()) { + allBlank = false; } + rowMap.put(headers.get(c), v); + } - // 전체 헤더 집합 (순서 유지) - Set headerSet = new LinkedHashSet<>(); - for (Map row : rows) { - if (row != null) { - headerSet.addAll(row.keySet()); - } - } - - List headers = new ArrayList<>(headerSet); - - // 헤더 - Row headerRow = sheet.createRow(0); - for (int c = 0; c < headers.size(); c++) { - Cell cell = headerRow.createCell(c); - cell.setCellValue(headers.get(c)); - } - - // 데이터 - int rowIndex = 1; - for (Map rowMap : rows) { - Row row = sheet.createRow(rowIndex++); - if (rowMap == null) continue; - - for (int c = 0; c < headers.size(); c++) { - String key = headers.get(c); - Object value = rowMap.get(key); - if (value != null) { - row.createCell(c).setCellValue(value.toString()); - } - } - } - - // 자동 컬럼 너비 - for (int c = 0; c < headers.size(); c++) { - sheet.autoSizeColumn(c); - } - - return workbook; + if (!allBlank) { + result.add(rowMap); + } } - /* ========================================================= - * 5. Streaming Write (SXSSFWorkbook) - DTO 기반 - * ========================================================= */ + return result; + } + + /* ========================================================= + * 4. List> -> Workbook (in-memory 쓰기) + * ========================================================= */ + + public static Workbook writeFromMapList(List> rows) { + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Sheet1"); + + if (rows == null || rows.isEmpty()) { + return workbook; + } + + // 전체 헤더 집합 (순서 유지) + Set headerSet = new LinkedHashSet<>(); + for (Map row : rows) { + if (row != null) { + headerSet.addAll(row.keySet()); + } + } + + List headers = new ArrayList<>(headerSet); + + // 헤더 + Row headerRow = sheet.createRow(0); + for (int c = 0; c < headers.size(); c++) { + Cell cell = headerRow.createCell(c); + cell.setCellValue(headers.get(c)); + } + + // 데이터 + int rowIndex = 1; + for (Map rowMap : rows) { + Row row = sheet.createRow(rowIndex++); + if (rowMap == null) { + continue; + } + + for (int c = 0; c < headers.size(); c++) { + String key = headers.get(c); + Object value = rowMap.get(key); + if (value != null) { + row.createCell(c).setCellValue(value.toString()); + } + } + } + + // 자동 컬럼 너비 + for (int c = 0; c < headers.size(); c++) { + sheet.autoSizeColumn(c); + } + + return workbook; + } + + /* ========================================================= + * 5. Streaming Write (SXSSFWorkbook) - DTO 기반 + * ========================================================= */ + + /** + * 대용량 쓰기를 위한 스트리밍 버전. + * + * @param data 엑셀에 쓸 DTO 리스트 (이미 메모리에 있음) + * @param clazz DTO 타입 + * @param rowAccessWindowSize SXSSFWorkbook row window (예: 100, 500 등) + */ + public static SXSSFWorkbook writeStreaming(List data, + Class clazz, + int rowAccessWindowSize) { + SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); + Sheet sheet = workbook.createSheet("Sheet1"); + + // 1) 메타 수집 + List fields = getExcelFields(clazz); + + // 2) 헤더 + Row headerRow = sheet.createRow(0); + for (ExcelFieldMeta meta : fields) { + Cell cell = headerRow.createCell(meta.order()); + cell.setCellValue(meta.header()); + } + + // 3) 데이터 + int rowIndex = 1; + if (data != null) { + for (T item : data) { + Row row = sheet.createRow(rowIndex++); + + for (ExcelFieldMeta meta : fields) { + Cell cell = row.createCell(meta.order()); + Object value = meta.getValue(item); + if (value != null) { + cell.setCellValue(value.toString()); + } else { + cell.setBlank(); + } + } + } + } + + // autoSizeColumn은 대용량에서는 비추천 (메모리 많이 씀) -> 필요하면 호출 + // for (ExcelFieldMeta meta : fields) { + // sheet.autoSizeColumn(meta.order()); + // } + + return workbook; + } + + + /* ========================================================= + * 5-1. Streaming Append Writer (SXSSFWorkbook) - DTO 기반 (chunk 지원) + * ========================================================= */ + + public static StreamingWriter openStreamingWriter(Class clazz, + int rowAccessWindowSize) { + SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); + Sheet sheet = workbook.createSheet("Sheet1"); + + // temp 파일 압축 저장 - 디스크 사용량 감소 + workbook.setCompressTempFiles(true); + + // 1) 메타 수집 + List fields = getExcelFields(clazz); + + // 2) 헤더 작성 + Row headerRow = sheet.createRow(0); + for (ExcelFieldMeta meta : fields) { + Cell cell = headerRow.createCell(meta.order()); + cell.setCellValue(meta.header()); + } + + return new StreamingWriter<>(workbook, sheet, fields, 1); + } + + public static SXSSFWorkbook writeStreamingFromMap(List> rows, + int rowAccessWindowSize) { + SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); + Sheet sheet = workbook.createSheet("Sheet1"); + + if (rows == null || rows.isEmpty()) { + return workbook; + } + + // 전체 헤더 집합 + Set headerSet = new LinkedHashSet<>(); + for (Map row : rows) { + if (row != null) { + headerSet.addAll(row.keySet()); + } + } + List headers = new ArrayList<>(headerSet); + + // 헤더 + Row headerRow = sheet.createRow(0); + for (int c = 0; c < headers.size(); c++) { + headerRow.createCell(c).setCellValue(headers.get(c)); + } + + // 데이터 + int rowIndex = 1; + for (Map rowMap : rows) { + Row row = sheet.createRow(rowIndex++); + if (rowMap == null) { + continue; + } + + for (int c = 0; c < headers.size(); c++) { + String key = headers.get(c); + Object value = rowMap.get(key); + if (value != null) { + row.createCell(c).setCellValue(value.toString()); + } + } + } + + return workbook; + } + + + /* ========================================================= + * 6. Streaming Write (SXSSFWorkbook) - Map 기반 + * ========================================================= */ + + /** + * XSSFReader + SAX 기반 스트리밍 읽기. - 첫 번째 시트만 읽음. - 1행은 헤더, 2행부터 데이터로 가정. + */ + public static void readStreaming(InputStream inputStream, RowMapHandler handler) { + try { + OPCPackage pkg = OPCPackage.open(inputStream); + XSSFReader reader = new XSSFReader(pkg); + SharedStringsTable sst = (SharedStringsTable) reader.getSharedStringsTable(); + + XMLReader parser = XMLReaderFactory.createXMLReader(); + SheetToMapHandler sheetHandler = new SheetToMapHandler(sst, handler); + parser.setContentHandler(sheetHandler); + + Iterator sheets = reader.getSheetsData(); + if (sheets.hasNext()) { + try (InputStream sheetIS = sheets.next()) { + InputSource sheetSource = new InputSource(sheetIS); + parser.parse(sheetSource); + } + } + + pkg.close(); + } catch (Exception e) { + throw new RuntimeException("Streaming 엑셀 읽기 중 오류", e); + } + } + + /* ========================================================= + * 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler + * ========================================================= */ + + private static List getExcelFields(Class clazz) { + List result = new ArrayList<>(); + + for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + ExcelColumn ann = field.getAnnotation(ExcelColumn.class); + if (ann == null) { + continue; + } + + field.setAccessible(true); + result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width())); + } + } + + result.sort(Comparator.comparingInt(ExcelFieldMeta::order)); + return result; + } + + private static void setFieldValue(Object target, Field field, String value) + throws IllegalAccessException { + Class type = field.getType(); + + // 1) null 또는 공백 처리 + if (value == null || value.isBlank()) { + // primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴 + if (type.isPrimitive()) { + return; + } + // 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅 + field.set(target, null); + return; + } + + String trimmed = value.trim(); + + try { + if (type == String.class) { + field.set(target, trimmed); + + } else if (type == Integer.class || type == int.class) { + field.set(target, Integer.parseInt(trimmed)); + + } else if (type == Long.class || type == long.class) { + field.set(target, Long.parseLong(trimmed)); + + } else if (type == Boolean.class || type == boolean.class) { + // "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능 + field.set(target, Boolean.parseBoolean(trimmed)); + + } else { + // TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장 + field.set(target, trimmed); + } + } catch (NumberFormatException e) { + // 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함 + throw new RuntimeException( + "엑셀 값 파싱 실패: field=" + field.getName() + + ", type=" + type.getSimpleName() + + ", value='" + value + "'", + e + ); + } + } + + @FunctionalInterface + public interface RowMapHandler { /** - * 대용량 쓰기를 위한 스트리밍 버전. - * - * @param data 엑셀에 쓸 DTO 리스트 (이미 메모리에 있음) - * @param clazz DTO 타입 - * @param rowAccessWindowSize SXSSFWorkbook row window (예: 100, 500 등) + * @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터) + * @param rowIndex 엑셀 실제 행 번호 (1-based) */ - public static SXSSFWorkbook writeStreaming(List data, - Class clazz, - int rowAccessWindowSize) { - SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); - Sheet sheet = workbook.createSheet("Sheet1"); + void handleRow(Map row, int rowIndex); + } - // 1) 메타 수집 - List fields = getExcelFields(clazz); + /* ========================================================= + * 8. 내부 메타 수집 & 필드 세터 + * ========================================================= */ - // 2) 헤더 - Row headerRow = sheet.createRow(0); - for (ExcelFieldMeta meta : fields) { - Cell cell = headerRow.createCell(meta.order()); - cell.setCellValue(meta.header()); - } + /** + * chunk 단위로 append 가능한 SXSSF Writer - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush - + * 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성 + */ + public static final class StreamingWriter implements AutoCloseable { - // 3) 데이터 - int rowIndex = 1; - if (data != null) { - for (T item : data) { - Row row = sheet.createRow(rowIndex++); + private final SXSSFWorkbook workbook; + private final Sheet sheet; + private final List fields; + private int rowIndex; - for (ExcelFieldMeta meta : fields) { - Cell cell = row.createCell(meta.order()); - Object value = meta.getValue(item); - if (value != null) { - cell.setCellValue(value.toString()); - } else { - cell.setBlank(); - } - } - } - } - - // autoSizeColumn은 대용량에서는 비추천 (메모리 많이 씀) -> 필요하면 호출 - // for (ExcelFieldMeta meta : fields) { - // sheet.autoSizeColumn(meta.order()); - // } - - return workbook; + private StreamingWriter(SXSSFWorkbook workbook, Sheet sheet, List fields, + int rowIndex) { + this.workbook = workbook; + this.sheet = sheet; + this.fields = fields; + this.rowIndex = rowIndex; } + public void append(T item) { + if (item == null) { + return; + } - /* ========================================================= - * 5-1. Streaming Append Writer (SXSSFWorkbook) - DTO 기반 (chunk 지원) - * ========================================================= */ - - public static StreamingWriter openStreamingWriter(Class clazz, int rowAccessWindowSize) { - SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); - Sheet sheet = workbook.createSheet("Sheet1"); - - // temp 파일 압축 저장 - 디스크 사용량 감소 - workbook.setCompressTempFiles(true); - - // 1) 메타 수집 - List fields = getExcelFields(clazz); - - // 2) 헤더 작성 - Row headerRow = sheet.createRow(0); - for (ExcelFieldMeta meta : fields) { - Cell cell = headerRow.createCell(meta.order()); - cell.setCellValue(meta.header()); + Row row = sheet.createRow(rowIndex++); + for (ExcelFieldMeta meta : fields) { + Cell cell = row.createCell(meta.order()); + Object value = meta.getValue(item); + if (value != null) { + cell.setCellValue(value.toString()); + } else { + cell.setBlank(); } + } + } - return new StreamingWriter<>(workbook, sheet, fields, 1); + public void appendAll(Collection items) { + if (items == null || items.isEmpty()) { + return; + } + for (T item : items) { + append(item); + } } /** - * chunk 단위로 append 가능한 SXSSF Writer - * - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush - * - 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성 + * XLSX는 마지막에 한 번 write 해야 파일이 완성됩니다. */ - public static final class StreamingWriter implements AutoCloseable { - private final SXSSFWorkbook workbook; - private final Sheet sheet; - private final List fields; - private int rowIndex; - - private StreamingWriter(SXSSFWorkbook workbook, Sheet sheet, List fields, int rowIndex) { - this.workbook = workbook; - this.sheet = sheet; - this.fields = fields; - this.rowIndex = rowIndex; - } - - public void append(T item) { - if (item == null) return; - - Row row = sheet.createRow(rowIndex++); - for (ExcelFieldMeta meta : fields) { - Cell cell = row.createCell(meta.order()); - Object value = meta.getValue(item); - if (value != null) cell.setCellValue(value.toString()); - else cell.setBlank(); - } - } - - public void appendAll(Collection items) { - if (items == null || items.isEmpty()) return; - for (T item : items) append(item); - } - - /** XLSX는 마지막에 한 번 write 해야 파일이 완성됩니다. */ - public void writeTo(OutputStream out) throws IOException { - workbook.write(out); - out.flush(); - } - - @Override - public void close() throws IOException { - // SXSSF temp 파일 제거 - workbook.dispose(); - workbook.close(); - } + public void writeTo(OutputStream out) throws IOException { + workbook.write(out); + out.flush(); } + @Override + public void close() throws IOException { + // SXSSF temp 파일 제거 + workbook.dispose(); + workbook.close(); + } + } - /* ========================================================= - * 6. Streaming Write (SXSSFWorkbook) - Map 기반 - * ========================================================= */ + /** + * SAX 핸들러: 한 행을 Map 으로 만들어 RowMapHandler에 전달. + */ + private static class SheetToMapHandler extends DefaultHandler { - public static SXSSFWorkbook writeStreamingFromMap(List> rows, - int rowAccessWindowSize) { - SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); - Sheet sheet = workbook.createSheet("Sheet1"); + private final SharedStringsTable sst; + private final RowMapHandler handler; + private final Map cellMap = new HashMap<>(); + private int currentRowNum; + private String currentCellRef; + private String currentCellType; + private StringBuilder currentValue; + private boolean isValueOpen; + private List headers = new ArrayList<>(); + private boolean headerProcessed = false; - if (rows == null || rows.isEmpty()) { - return workbook; - } - - // 전체 헤더 집합 - Set headerSet = new LinkedHashSet<>(); - for (Map row : rows) { - if (row != null) { - headerSet.addAll(row.keySet()); - } - } - List headers = new ArrayList<>(headerSet); - - // 헤더 - Row headerRow = sheet.createRow(0); - for (int c = 0; c < headers.size(); c++) { - headerRow.createCell(c).setCellValue(headers.get(c)); - } - - // 데이터 - int rowIndex = 1; - for (Map rowMap : rows) { - Row row = sheet.createRow(rowIndex++); - if (rowMap == null) continue; - - for (int c = 0; c < headers.size(); c++) { - String key = headers.get(c); - Object value = rowMap.get(key); - if (value != null) { - row.createCell(c).setCellValue(value.toString()); - } - } - } - - return workbook; + SheetToMapHandler(SharedStringsTable sst, RowMapHandler handler) { + this.sst = sst; + this.handler = handler; } - /* ========================================================= - * 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler - * ========================================================= */ - - @FunctionalInterface - public interface RowMapHandler { - /** - * @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터) - * @param rowIndex 엑셀 실제 행 번호 (1-based) - */ - void handleRow(Map row, int rowIndex); + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) { + if ("row".equals(qName)) { + String r = attributes.getValue("r"); + if (r != null) { + currentRowNum = Integer.parseInt(r); + } else { + currentRowNum++; + } + cellMap.clear(); + } else if ("c".equals(qName)) { + currentCellRef = attributes.getValue("r"); + currentCellType = attributes.getValue("t"); // "s"면 shared string + } else if ("v".equals(qName) || "t".equals(qName)) { + currentValue = new StringBuilder(); + isValueOpen = true; + } } - /** - * XSSFReader + SAX 기반 스트리밍 읽기. - * - 첫 번째 시트만 읽음. - * - 1행은 헤더, 2행부터 데이터로 가정. - */ - public static void readStreaming(InputStream inputStream, RowMapHandler handler) { - try { - OPCPackage pkg = OPCPackage.open(inputStream); - XSSFReader reader = new XSSFReader(pkg); - SharedStringsTable sst = (SharedStringsTable) reader.getSharedStringsTable(); - - XMLReader parser = XMLReaderFactory.createXMLReader(); - SheetToMapHandler sheetHandler = new SheetToMapHandler(sst, handler); - parser.setContentHandler(sheetHandler); - - Iterator sheets = reader.getSheetsData(); - if (sheets.hasNext()) { - try (InputStream sheetIS = sheets.next()) { - InputSource sheetSource = new InputSource(sheetIS); - parser.parse(sheetSource); - } - } - - pkg.close(); - } catch (Exception e) { - throw new RuntimeException("Streaming 엑셀 읽기 중 오류", e); - } + @Override + public void characters(char[] ch, int start, int length) { + if (isValueOpen && currentValue != null) { + currentValue.append(ch, start, length); + } } - /** - * SAX 핸들러: 한 행을 Map 으로 만들어 RowMapHandler에 전달. - */ - private static class SheetToMapHandler extends DefaultHandler { - private final SharedStringsTable sst; - private final RowMapHandler handler; + @Override + public void endElement(String uri, String localName, String qName) { + if ("v".equals(qName) || "t".equals(qName)) { + String raw = currentValue != null ? currentValue.toString() : ""; + String resolved = resolveCellValue(raw, currentCellType); - private int currentRowNum; - private String currentCellRef; - private String currentCellType; - private StringBuilder currentValue; - private boolean isValueOpen; - - private final Map cellMap = new HashMap<>(); - private List headers = new ArrayList<>(); - private boolean headerProcessed = false; - - SheetToMapHandler(SharedStringsTable sst, RowMapHandler handler) { - this.sst = sst; - this.handler = handler; + if (currentCellRef != null) { + int colIdx = new CellReference(currentCellRef).getCol(); + cellMap.put(colIdx, resolved); } - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) { - if ("row".equals(qName)) { - String r = attributes.getValue("r"); - if (r != null) { - currentRowNum = Integer.parseInt(r); - } else { - currentRowNum++; - } - cellMap.clear(); - } else if ("c".equals(qName)) { - currentCellRef = attributes.getValue("r"); - currentCellType = attributes.getValue("t"); // "s"면 shared string - } else if ("v".equals(qName) || "t".equals(qName)) { - currentValue = new StringBuilder(); - isValueOpen = true; + isValueOpen = false; + currentValue = null; + } else if ("row".equals(qName)) { + // 1행: 헤더 + if (!headerProcessed) { + if (!cellMap.isEmpty()) { + int maxCol = cellMap.keySet().stream().max(Integer::compareTo).orElse(-1); + headers = new ArrayList<>(maxCol + 1); + for (int c = 0; c <= maxCol; c++) { + String header = cellMap.getOrDefault(c, "COL_" + c); + headers.add(header); } - } - - @Override - public void characters(char[] ch, int start, int length) { - if (isValueOpen && currentValue != null) { - currentValue.append(ch, start, length); - } - } - - @Override - public void endElement(String uri, String localName, String qName) { - if ("v".equals(qName) || "t".equals(qName)) { - String raw = currentValue != null ? currentValue.toString() : ""; - String resolved = resolveCellValue(raw, currentCellType); - - if (currentCellRef != null) { - int colIdx = new CellReference(currentCellRef).getCol(); - cellMap.put(colIdx, resolved); - } - - isValueOpen = false; - currentValue = null; - } else if ("row".equals(qName)) { - // 1행: 헤더 - if (!headerProcessed) { - if (!cellMap.isEmpty()) { - int maxCol = cellMap.keySet().stream().max(Integer::compareTo).orElse(-1); - headers = new ArrayList<>(maxCol + 1); - for (int c = 0; c <= maxCol; c++) { - String header = cellMap.getOrDefault(c, "COL_" + c); - headers.add(header); - } - } - headerProcessed = true; - } else { - if (headers == null || headers.isEmpty()) return; - - Map rowMap = new LinkedHashMap<>(); - boolean allBlank = true; - - for (int c = 0; c < headers.size(); c++) { - String v = cellMap.get(c); - if (v != null && !v.isBlank()) { - allBlank = false; - } - rowMap.put(headers.get(c), v); - } - - if (!allBlank) { - handler.handleRow(rowMap, currentRowNum); - } - } - } - } - - private String resolveCellValue(String raw, String cellType) { - if ("s".equals(cellType)) { - try { - int idx = Integer.parseInt(raw); - RichTextString rich = sst.getItemAt(idx); // 또는 getEntryAt(idx) 인 버전도 있음 - return (rich != null) ? rich.getString() : ""; - } catch (Exception e) { - return raw; - } - } - return raw; - } - } - - /* ========================================================= - * 8. 내부 메타 수집 & 필드 세터 - * ========================================================= */ - - private static List getExcelFields(Class clazz) { - List result = new ArrayList<>(); - - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { - for (Field field : c.getDeclaredFields()) { - ExcelColumn ann = field.getAnnotation(ExcelColumn.class); - if (ann == null) continue; - - field.setAccessible(true); - result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width())); - } - } - - result.sort(Comparator.comparingInt(ExcelFieldMeta::order)); - return result; - } - - private static void setFieldValue(Object target, Field field, String value) throws IllegalAccessException { - Class type = field.getType(); - - // 1) null 또는 공백 처리 - if (value == null || value.isBlank()) { - // primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴 - if (type.isPrimitive()) { - return; - } - // 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅 - field.set(target, null); + } + headerProcessed = true; + } else { + if (headers == null || headers.isEmpty()) { return; + } + + Map rowMap = new LinkedHashMap<>(); + boolean allBlank = true; + + for (int c = 0; c < headers.size(); c++) { + String v = cellMap.get(c); + if (v != null && !v.isBlank()) { + allBlank = false; + } + rowMap.put(headers.get(c), v); + } + + if (!allBlank) { + handler.handleRow(rowMap, currentRowNum); + } } + } + } - String trimmed = value.trim(); - + private String resolveCellValue(String raw, String cellType) { + if ("s".equals(cellType)) { try { - if (type == String.class) { - field.set(target, trimmed); - - } else if (type == Integer.class || type == int.class) { - field.set(target, Integer.parseInt(trimmed)); - - } else if (type == Long.class || type == long.class) { - field.set(target, Long.parseLong(trimmed)); - - } else if (type == Boolean.class || type == boolean.class) { - // "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능 - field.set(target, Boolean.parseBoolean(trimmed)); - - } else { - // TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장 - field.set(target, trimmed); - } - } catch (NumberFormatException e) { - // 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함 - throw new RuntimeException( - "엑셀 값 파싱 실패: field=" + field.getName() + - ", type=" + type.getSimpleName() + - ", value='" + value + "'", - e - ); + int idx = Integer.parseInt(raw); + RichTextString rich = sst.getItemAt(idx); // 또는 getEntryAt(idx) 인 버전도 있음 + return (rich != null) ? rich.getString() : ""; + } catch (Exception e) { + return raw; } + } + return raw; } + } - private record ExcelFieldMeta(Field field, String header, int order, int width) { - Object getValue(Object target) { - try { - return field.get(target); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } + private record ExcelFieldMeta(Field field, String header, int order, int width) { + + Object getValue(Object target) { + try { + return field.get(target); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } } + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/excel/ExcelUtil.java b/src/main/java/com/kri/common/excel/ExcelUtil.java index d17cc42..73e5296 100644 --- a/src/main/java/com/kri/common/excel/ExcelUtil.java +++ b/src/main/java/com/kri/common/excel/ExcelUtil.java @@ -1,37 +1,35 @@ package com.kri.common.excel; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.lang.reflect.Field; -import java.util.*; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DateUtil; public final class ExcelUtil { - private 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 등 나머지 타입 - }; + 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 등 나머지 타입 + }; + } } diff --git a/src/main/java/com/kri/common/file/FileUtil.java b/src/main/java/com/kri/common/file/FileUtil.java index 17f61fc..66a4645 100644 --- a/src/main/java/com/kri/common/file/FileUtil.java +++ b/src/main/java/com/kri/common/file/FileUtil.java @@ -3,52 +3,57 @@ package com.kri.common.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; - } + private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]"); - 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 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 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; + 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; + } } diff --git a/src/main/java/com/kri/common/http/ExternalApiClient.java b/src/main/java/com/kri/common/http/ExternalApiClient.java index 0b043ad..178aaf5 100644 --- a/src/main/java/com/kri/common/http/ExternalApiClient.java +++ b/src/main/java/com/kri/common/http/ExternalApiClient.java @@ -9,91 +9,94 @@ import java.time.Duration; import java.util.Map; /** - * 간단한 외부 API 통신 모듈. - * - url, 추가 헤더, body를 받아 호출합니다. - * - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. - * - body는 문자열(JSON 등) 기준입니다. + * 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. - + * body는 문자열(JSON 등) 기준입니다. */ public class ExternalApiClient { - private final HttpClient httpClient; - private final Duration requestTimeout; + private final HttpClient httpClient; + private final Duration requestTimeout; - /** - * 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅) - */ - public ExternalApiClient() { - this(HttpClient.newBuilder() - .connectTimeout(Duration.ofSeconds(10)) - .build(), Duration.ofSeconds(30)); + /** + * 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅) + */ + 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); + } - /** - * 사용자 지정 HttpClient/요청 타임아웃으로 생성 - */ - public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) { - this.httpClient = httpClient; - this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout; - } - - public ExternalApiResponse get(String url, Map headers) { - return send("GET", url, headers, null); - } - - public ExternalApiResponse delete(String url, Map headers) { - return send("DELETE", url, headers, null); - } - - public ExternalApiResponse post(String url, Map headers, String body) { - return send("POST", url, headers, body); - } - - public ExternalApiResponse put(String url, Map headers, String body) { - return send("PUT", url, headers, body); - } - - public ExternalApiResponse patch(String url, Map headers, String body) { - return send("PATCH", url, headers, body); - } - - private ExternalApiResponse send(String method, String url, Map 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 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); - } - } - - 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 headers) { + return send("GET", url, headers, null); + } + + public ExternalApiResponse delete(String url, Map headers) { + return send("DELETE", url, headers, null); + } + + public ExternalApiResponse post(String url, Map headers, String body) { + return send("POST", url, headers, body); + } + + public ExternalApiResponse put(String url, Map headers, String body) { + return send("PUT", url, headers, body); + } + + public ExternalApiResponse patch(String url, Map headers, String body) { + return send("PATCH", url, headers, body); + } + + private ExternalApiResponse send(String method, String url, Map 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 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); } + } } diff --git a/src/main/java/com/kri/common/http/ExternalApiResponse.java b/src/main/java/com/kri/common/http/ExternalApiResponse.java index 0c7cdbc..d05a674 100644 --- a/src/main/java/com/kri/common/http/ExternalApiResponse.java +++ b/src/main/java/com/kri/common/http/ExternalApiResponse.java @@ -8,29 +8,30 @@ import java.util.Map; * 외부 API 호출 결과를 단순하게 담는 DTO. */ public class ExternalApiResponse { - private final int statusCode; - private final Map> headers; - private final String body; - public ExternalApiResponse(int statusCode, Map> headers, String body) { - this.statusCode = statusCode; - this.headers = headers; - this.body = body; - } + private final int statusCode; + private final Map> headers; + private final String body; - public int getStatusCode() { - return statusCode; - } + public ExternalApiResponse(int statusCode, Map> headers, String body) { + this.statusCode = statusCode; + this.headers = headers; + this.body = body; + } - public Map> getHeaders() { - return headers; - } + public static ExternalApiResponse of(int status, HttpHeaders headers, String body) { + return new ExternalApiResponse(status, headers.map(), body); + } - public String getBody() { - return body; - } + public int getStatusCode() { + return statusCode; + } - public static ExternalApiResponse of(int status, HttpHeaders headers, String body) { - return new ExternalApiResponse(status, headers.map(), body); - } + public Map> getHeaders() { + return headers; + } + + public String getBody() { + return body; + } } diff --git a/src/main/java/com/kri/common/jpa/AbstractCodeEnumConverter.java b/src/main/java/com/kri/common/jpa/AbstractCodeEnumConverter.java index 7b18ecb..cc32d7a 100644 --- a/src/main/java/com/kri/common/jpa/AbstractCodeEnumConverter.java +++ b/src/main/java/com/kri/common/jpa/AbstractCodeEnumConverter.java @@ -5,23 +5,23 @@ import com.kri.common.enums.CodeEnumUtils; import jakarta.persistence.AttributeConverter; public abstract class AbstractCodeEnumConverter< - E extends Enum & CodeEnum, - V - > implements AttributeConverter { + E extends Enum & CodeEnum, + V + > implements AttributeConverter { - private final Class enumClass; + private final Class enumClass; - protected AbstractCodeEnumConverter(Class enumClass) { - this.enumClass = enumClass; - } + protected AbstractCodeEnumConverter(Class enumClass) { + this.enumClass = enumClass; + } - @Override - public V convertToDatabaseColumn(E attribute) { - return attribute == null ? null : attribute.getCode(); - } + @Override + public V convertToDatabaseColumn(E attribute) { + return attribute == null ? null : attribute.getCode(); + } - @Override - public E convertToEntityAttribute(V dbData) { - return CodeEnumUtils.fromCode(enumClass, dbData); - } + @Override + public E convertToEntityAttribute(V dbData) { + return CodeEnumUtils.fromCode(enumClass, dbData); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/jpa/BaseUuidEntity.java b/src/main/java/com/kri/common/jpa/BaseUuidEntity.java index 51112d9..7f3930e 100644 --- a/src/main/java/com/kri/common/jpa/BaseUuidEntity.java +++ b/src/main/java/com/kri/common/jpa/BaseUuidEntity.java @@ -2,36 +2,41 @@ package com.kri.common.jpa; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.PrePersist; - import java.util.UUID; @MappedSuperclass public abstract class BaseUuidEntity { - protected abstract String getId(); - protected abstract void setId(String id); - /** 엔티티마다 컬럼 길이에 맞춰 오버라이드 */ - protected int idLength() { return 32; } + private static String generateId(int length) { + String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars - @PrePersist - protected void prePersistId() { - if (getId() == null || getId().isBlank()) { - setId(generateId(idLength())); - } + if (length <= 32) { + return base.substring(0, length); } - 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); + 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())); + } + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/json/JsonUtil.java b/src/main/java/com/kri/common/json/JsonUtil.java index 5947ca7..8777d84 100644 --- a/src/main/java/com/kri/common/json/JsonUtil.java +++ b/src/main/java/com/kri/common/json/JsonUtil.java @@ -3,122 +3,120 @@ package com.kri.common.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() { - // 유틸 클래스 - 인스턴스 생성 방지 - } + private JsonUtil() { + // 유틸 클래스 - 인스턴스 생성 방지 + } - /** - * 임의의 자바 객체를 Map으로 변환한다. - * 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, - * 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 용도이다. - */ - public static Map toMap(ObjectMapper objectMapper, T source) { - if (source == null) { - return Collections.emptyMap(); - } - @SuppressWarnings("unchecked") - Map map = objectMapper.convertValue(source, Map.class); - return map; + /** + * 임의의 자바 객체를 Map으로 변환한다. 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 + * 용도이다. + */ + public static Map toMap(ObjectMapper objectMapper, T source) { + if (source == null) { + return Collections.emptyMap(); } + @SuppressWarnings("unchecked") + Map map = objectMapper.convertValue(source, Map.class); + return map; + } - /** - * JSON 문자열을 Map으로 파싱한다. - * - * @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환) - */ - public static Map parseJsonToMap(ObjectMapper objectMapper, String json) { - if (json == null || json.isBlank()) { - return Collections.emptyMap(); - } - try { - return objectMapper.readValue(json, new TypeReference>() {}); - } catch (IOException e) { - throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e); - } + /** + * JSON 문자열을 Map으로 파싱한다. + * + * @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환) + */ + public static Map parseJsonToMap(ObjectMapper objectMapper, String json) { + if (json == null || json.isBlank()) { + return Collections.emptyMap(); } + try { + return objectMapper.readValue(json, new TypeReference>() { + }); + } 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); - } + /** + * 객체를 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); - } + /** + * 객체를 사람이 읽기 좋은 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 fromJson(ObjectMapper objectMapper, String json, Class 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, UserInfoDto.class) + */ + public static T fromJson(ObjectMapper objectMapper, String json, Class 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>() {}) - */ - public static T fromJson(ObjectMapper objectMapper, String json, TypeReference typeRef) { - if (json == null || json.isBlank()) { - return null; - } - try { - return objectMapper.readValue(json, typeRef); - } catch (IOException e) { - throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e); - } + /** + * JSON 문자열을 제네릭 타입으로 역직렬화한다. ex) fromJson(mapper, json, new TypeReference>() + * {}) + */ + public static T fromJson(ObjectMapper objectMapper, String json, TypeReference 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 형태로 깊은 복사/매핑한다. - * - * ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class); - */ - public static T deepCopy(ObjectMapper objectMapper, T source, Class targetType) { - if (source == null) { - return null; - } - return objectMapper.convertValue(source, targetType); + /** + * JSON 기반 deep copy (또는 타입 변환). 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다. + *

+ * ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class); + */ + public static T deepCopy(ObjectMapper objectMapper, T source, Class targetType) { + if (source == null) { + return null; } + return objectMapper.convertValue(source, targetType); + } - /** - * 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용. - * - * ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class); - */ - public static T convert(ObjectMapper objectMapper, S source, Class targetType) { - if (source == null) { - return null; - } - return objectMapper.convertValue(source, targetType); + /** + * 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용. + *

+ * ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class); + */ + public static T convert(ObjectMapper objectMapper, S source, Class targetType) { + if (source == null) { + return null; } + return objectMapper.convertValue(source, targetType); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/redis/CommonRedisAutoConfiguration.java b/src/main/java/com/kri/common/redis/CommonRedisAutoConfiguration.java index fb05ee3..a13275a 100644 --- a/src/main/java/com/kri/common/redis/CommonRedisAutoConfiguration.java +++ b/src/main/java/com/kri/common/redis/CommonRedisAutoConfiguration.java @@ -1,10 +1,14 @@ package com.kri.common.redis; import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.*; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.*; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; @AutoConfiguration @ConditionalOnClass(RedisTemplate.class) @@ -12,11 +16,16 @@ import org.springframework.data.redis.core.*; @ConditionalOnBean(RedisConnectionFactory.class) public class CommonRedisAutoConfiguration { - @Bean @ConditionalOnMissingBean - public StringRedisTemplate stringRedisTemplate(org.springframework.data.redis.connection.RedisConnectionFactory cf) { - return new StringRedisTemplate(cf); - } + @Bean + @ConditionalOnMissingBean + public StringRedisTemplate stringRedisTemplate( + org.springframework.data.redis.connection.RedisConnectionFactory cf) { + return new StringRedisTemplate(cf); + } - @Bean @ConditionalOnMissingBean - public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { return new RedisQueueHelper(rt); } + @Bean + @ConditionalOnMissingBean + public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { + return new RedisQueueHelper(rt); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/redis/RedisQueueHelper.java b/src/main/java/com/kri/common/redis/RedisQueueHelper.java index dc55e5c..cd80d78 100644 --- a/src/main/java/com/kri/common/redis/RedisQueueHelper.java +++ b/src/main/java/com/kri/common/redis/RedisQueueHelper.java @@ -1,11 +1,21 @@ package com.kri.common.redis; -import org.springframework.data.redis.core.StringRedisTemplate; 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); } + + 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); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/scheduling/CommonSchedulingAutoConfiguration.java b/src/main/java/com/kri/common/scheduling/CommonSchedulingAutoConfiguration.java index 5f701fe..808fcd3 100644 --- a/src/main/java/com/kri/common/scheduling/CommonSchedulingAutoConfiguration.java +++ b/src/main/java/com/kri/common/scheduling/CommonSchedulingAutoConfiguration.java @@ -7,4 +7,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; @AutoConfiguration @EnableScheduling @ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false) -public class CommonSchedulingAutoConfiguration { } \ No newline at end of file +public class CommonSchedulingAutoConfiguration { + +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java b/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java index b62fa04..c64e25a 100644 --- a/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java +++ b/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java @@ -6,43 +6,42 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; import lombok.RequiredArgsConstructor; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; - @RequiredArgsConstructor public class JwtAuthenticationFilter extends OncePerRequestFilter { - private final JwtService jwtService; + private final JwtService jwtService; - @Override - protected void doFilterInternal( - HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain - ) throws ServletException, IOException { - // 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음) - if (SecurityContextHolder.getContext().getAuthentication() == null) { - String header = request.getHeader("Authorization"); - if (header != null && header.startsWith("Bearer ")) { - String token = header.substring("Bearer ".length()); - try { - // ★ 오직 "정상 JWT" 만 처리 - Authentication auth = jwtService.toAuthentication(token); - SecurityContextHolder.getContext().setAuthentication(auth); - } catch (JwtException ex) { - // 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고: - // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - // return; - // - // 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐 - } - } + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + // 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음) + if (SecurityContextHolder.getContext().getAuthentication() == null) { + String header = request.getHeader("Authorization"); + if (header != null && header.startsWith("Bearer ")) { + String token = header.substring("Bearer ".length()); + try { + // ★ 오직 "정상 JWT" 만 처리 + Authentication auth = jwtService.toAuthentication(token); + SecurityContextHolder.getContext().setAuthentication(auth); + } catch (JwtException ex) { + // 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고: + // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + // return; + // + // 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐 } - - filterChain.doFilter(request, response); + } } + + filterChain.doFilter(request, response); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java b/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java index 645b381..64062c5 100644 --- a/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java +++ b/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java @@ -1,8 +1,6 @@ package com.kri.common.security; import com.kri.common.auth.apikey.ApiKeyAuthFilter; -import com.kri.common.auth.apikey.ApiKeyProperties; -import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider; import com.kri.common.auth.jwt.JwtProperties; import com.kri.common.auth.jwt.JwtService; import lombok.RequiredArgsConstructor; @@ -15,73 +13,74 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; -import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @AutoConfiguration(before = SecurityAutoConfiguration.class) @EnableConfigurationProperties({KriSecurityProperties.class, JwtProperties.class}) @ConditionalOnProperty(prefix = "kri.security", name = "enabled", havingValue = "true", matchIfMissing = true) @EnableMethodSecurity( - jsr250Enabled = true, - prePostEnabled = true + jsr250Enabled = true, + prePostEnabled = true ) @RequiredArgsConstructor public class KriSecurityAutoConfiguration { - private final KriSecurityProperties securityProperties; - private final JwtProperties jwtProperties; + private final KriSecurityProperties securityProperties; + private final JwtProperties jwtProperties; - @Bean - @ConditionalOnMissingBean - public JwtService jwtService(JwtProperties properties) { - return new JwtService(properties); - } + @Bean + @ConditionalOnMissingBean + public JwtService jwtService(JwtProperties properties) { + return new JwtService(properties); + } - @Bean - @ConditionalOnMissingBean - public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) { - return new JwtAuthenticationFilter(jwtService); - } + @Bean + @ConditionalOnMissingBean + public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) { + return new JwtAuthenticationFilter(jwtService); + } - /** - * 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 - * 이 기본 Security 구성이 적용된다. - */ - @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") - @Bean - @ConditionalOnMissingBean(SecurityFilterChain.class) - public SecurityFilterChain kriSecurityFilterChain( - HttpSecurity http, - ObjectProvider apiKeyAuthFilterProvider, - JwtAuthenticationFilter jwtAuthenticationFilter - ) throws Exception { + /** + * 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 이 기본 Security 구성이 적용된다. + */ + @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") + @Bean + @ConditionalOnMissingBean(SecurityFilterChain.class) + public SecurityFilterChain kriSecurityFilterChain( + HttpSecurity http, + ObjectProvider apiKeyAuthFilterProvider, + JwtAuthenticationFilter jwtAuthenticationFilter + ) throws Exception { - http - .httpBasic(AbstractHttpConfigurer::disable) - .csrf(AbstractHttpConfigurer::disable) - .cors(Customizer.withDefaults()) - .sessionManagement(session -> - session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) - ) - .authorizeHttpRequests(auth -> { - // ✅ yaml에서 정의한 public-paths 전부 permitAll - if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths().isEmpty()) { - auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)).permitAll(); - } - // ✅ 나머지는 전부 인증 필요 - auth.anyRequest().authenticated(); - }); + http + .httpBasic(AbstractHttpConfigurer::disable) + .csrf(AbstractHttpConfigurer::disable) + .cors(Customizer.withDefaults()) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .authorizeHttpRequests(auth -> { + // ✅ yaml에서 정의한 public-paths 전부 permitAll + if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths() + .isEmpty()) { + auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)) + .permitAll(); + } + // ✅ 나머지는 전부 인증 필요 + auth.anyRequest().authenticated(); + }); - // ✅ API Key 필터가 존재하면 먼저 태움 - apiKeyAuthFilterProvider.ifAvailable(filter -> - http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class) - ); - // ✅ 그 다음 JWT 필터 - http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + // ✅ API Key 필터가 존재하면 먼저 태움 + apiKeyAuthFilterProvider.ifAvailable(filter -> + http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class) + ); + // ✅ 그 다음 JWT 필터 + http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); - return http.build(); - } + return http.build(); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/security/KriSecurityProperties.java b/src/main/java/com/kri/common/security/KriSecurityProperties.java index dbcb569..0184e85 100644 --- a/src/main/java/com/kri/common/security/KriSecurityProperties.java +++ b/src/main/java/com/kri/common/security/KriSecurityProperties.java @@ -1,28 +1,26 @@ package com.kri.common.security; +import java.util.List; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.util.List; - @Getter @Setter @ConfigurationProperties(prefix = "kri.security") public class KriSecurityProperties { - /** - * 이 자동구성 사용 여부 - */ - private boolean enabled = true; + /** + * 이 자동구성 사용 여부 + */ + private boolean enabled = true; - /** - * 인증 없이 허용할 URL 패턴들 - * 서비스에서 application.yml로 오버라이드 - */ - private List publicPaths = List.of( - "/v3/api-docs/**", - "/swagger-ui.html", - "/swagger-ui/**" - ); + /** + * 인증 없이 허용할 URL 패턴들 서비스에서 application.yml로 오버라이드 + */ + private List publicPaths = List.of( + "/v3/api-docs/**", + "/swagger-ui.html", + "/swagger-ui/**" + ); } \ No newline at end of file diff --git a/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java b/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java index cd2f21e..db06b8b 100644 --- a/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java +++ b/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java @@ -22,56 +22,56 @@ import org.springframework.context.annotation.Bean; @RequiredArgsConstructor public class KriSwaggerAutoConfiguration { - private final KriSwaggerProperties properties; - private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해 + private final KriSwaggerProperties properties; + private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해 - @Bean - @ConditionalOnMissingBean - public OpenAPI kriOpenAPI() { + @Bean + @ConditionalOnMissingBean + public OpenAPI kriOpenAPI() { - // 🔐 JWT Bearer + API-Key 스키마 정의 - Components components = new Components() - .addSecuritySchemes("BearerAuth", - new SecurityScheme() - .type(SecurityScheme.Type.HTTP) - .scheme("bearer") - .bearerFormat("JWT")) - .addSecuritySchemes("ApiKeyAuth", - new SecurityScheme() - .type(SecurityScheme.Type.APIKEY) - .in(SecurityScheme.In.HEADER) - .name(apiKeyProperties.getHeaderName())); // 예: X-API-Key + // 🔐 JWT Bearer + API-Key 스키마 정의 + Components components = new Components() + .addSecuritySchemes("BearerAuth", + new SecurityScheme() + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT")) + .addSecuritySchemes("ApiKeyAuth", + new SecurityScheme() + .type(SecurityScheme.Type.APIKEY) + .in(SecurityScheme.In.HEADER) + .name(apiKeyProperties.getHeaderName())); // 예: X-API-Key - // 🔐 기본적으로 두 보안 스키마를 전역에 적용 - SecurityRequirement securityRequirement = new SecurityRequirement() - .addList("BearerAuth") - .addList("ApiKeyAuth"); + // 🔐 기본적으로 두 보안 스키마를 전역에 적용 + SecurityRequirement securityRequirement = new SecurityRequirement() + .addList("BearerAuth") + .addList("ApiKeyAuth"); - return new OpenAPI() - .components(components) - .addSecurityItem(securityRequirement) - .info(new Info() - .title(properties.getTitle()) - .description(properties.getDescription()) - .version(properties.getVersion()) - ); + return new OpenAPI() + .components(components) + .addSecurityItem(securityRequirement) + .info(new Info() + .title(properties.getTitle()) + .description(properties.getDescription()) + .version(properties.getVersion()) + ); + } + + @Bean(name = "kriGroupedOpenApi") + @ConditionalOnMissingBean(name = "kriGroupedOpenApi") + public GroupedOpenApi kriGroupedOpenApi() { + GroupedOpenApi.Builder builder = GroupedOpenApi.builder() + .group("kri-api") + .pathsToMatch("/api/**", "/internal/**"); + + String base = properties.getBasePackage(); + if (base != null && !base.isBlank()) { + builder.packagesToScan( + base, + "com.kri.common.auth.apikey" + ); } - @Bean(name = "kriGroupedOpenApi") - @ConditionalOnMissingBean(name = "kriGroupedOpenApi") - public GroupedOpenApi kriGroupedOpenApi() { - GroupedOpenApi.Builder builder = GroupedOpenApi.builder() - .group("kri-api") - .pathsToMatch("/api/**", "/internal/**"); - - String base = properties.getBasePackage(); - if (base != null && !base.isBlank()) { - builder.packagesToScan( - base, - "com.kri.common.auth.apikey" - ); - } - - return builder.build(); - } + return builder.build(); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java b/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java index 7816717..808e813 100644 --- a/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java +++ b/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java @@ -9,14 +9,14 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "kri.swagger") public class KriSwaggerProperties { - private boolean enabled = true; + private boolean enabled = true; - private String title = "KRI API"; - private String description = "KRI Common API Docs"; - private String version = "v1"; + private String title = "KRI API"; + private String description = "KRI Common API Docs"; + private String version = "v1"; - /** - * 문서화할 base package (null 이면 전체) - */ - private String basePackage; + /** + * 문서화할 base package (null 이면 전체) + */ + private String basePackage; } diff --git a/src/main/java/com/kri/common/util/CommonUtil.java b/src/main/java/com/kri/common/util/CommonUtil.java index a29f19b..a290767 100644 --- a/src/main/java/com/kri/common/util/CommonUtil.java +++ b/src/main/java/com/kri/common/util/CommonUtil.java @@ -4,40 +4,44 @@ import java.util.UUID; public final class CommonUtil { - public static String uuid32() { - return UUID.randomUUID().toString().replace("-", ""); - } + public static String uuid32() { + return UUID.randomUUID().toString().replace("-", ""); + } - 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 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 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 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; - } + public static long safeParseLong(String s, short def) { + try { + return Long.parseLong(s); + } catch (Exception e) { + return def; } + } } diff --git a/src/main/java/com/kri/common/web/BusinessException.java b/src/main/java/com/kri/common/web/BusinessException.java index 78ab993..c195bb1 100644 --- a/src/main/java/com/kri/common/web/BusinessException.java +++ b/src/main/java/com/kri/common/web/BusinessException.java @@ -1,105 +1,120 @@ package com.kri.common.web; -import org.springframework.http.HttpStatus; 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 extras; - private static String defaultCode(HttpStatus status) { return status.name(); } // 예: NOT_FOUND, CONFLICT … + private final HttpStatus status; + private final String code; + private final Map extras; - private BusinessException(HttpStatus status, String code, String message, - Map 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 BusinessException(HttpStatus status, String code, String message, + Map 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)); + } - 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 extras) { - return new BusinessException(status, code, message, extras, null); - } + private static String defaultCode(HttpStatus status) { + return status.name(); + } // 예: NOT_FOUND, CONFLICT … - // 편의 생성자들 - // 400 Bad Request - public static BusinessException badRequest(String code, String message) { - return of(HttpStatus.BAD_REQUEST, code, message); - } + public static BusinessException of(HttpStatus status, String code, String message) { + return new BusinessException(status, code, message, null, null); + } - public static BusinessException badRequest(String message) { - return badRequest("BAD_REQUEST", message); - } + public static BusinessException of(HttpStatus status, String code, String message, + Map extras) { + return new BusinessException(status, code, message, extras, null); + } - // 401 Unauthorized - public static BusinessException unauthorized(String code, String message) { - return of(HttpStatus.UNAUTHORIZED, code, message); - } + // 편의 생성자들 + // 400 Bad Request + public static BusinessException badRequest(String code, String message) { + return of(HttpStatus.BAD_REQUEST, code, message); + } - public static BusinessException unauthorized(String message) { - return unauthorized("UNAUTHORIZED", message); - } + public static BusinessException badRequest(String message) { + return badRequest("BAD_REQUEST", message); + } - // 403 Forbidden - public static BusinessException forbidden(String code, String message) { - return of(HttpStatus.FORBIDDEN, code, message); - } + // 401 Unauthorized + public static BusinessException unauthorized(String code, String message) { + return of(HttpStatus.UNAUTHORIZED, code, message); + } - public static BusinessException forbidden(String message) { - return forbidden("FORBIDDEN", message); - } + public static BusinessException unauthorized(String message) { + return unauthorized("UNAUTHORIZED", message); + } - // 404 Not Found - public static BusinessException notFound(String code, String message) { - return of(HttpStatus.NOT_FOUND, code, message); - } + // 403 Forbidden + public static BusinessException forbidden(String code, String message) { + return of(HttpStatus.FORBIDDEN, code, message); + } - public static BusinessException notFound(String message) { - return notFound("NOT_FOUND", message); - } + public static BusinessException forbidden(String message) { + return forbidden("FORBIDDEN", message); + } - // 409 Conflict - public static BusinessException conflict(String code, String message) { - return of(HttpStatus.CONFLICT, code, message); - } + // 404 Not Found + public static BusinessException notFound(String code, String message) { + return of(HttpStatus.NOT_FOUND, code, message); + } - public static BusinessException conflict(String message) { - return conflict("CONFLICT", message); - } + public static BusinessException notFound(String message) { + return notFound("NOT_FOUND", message); + } - // 422 Unprocessable Entity (검증 에러 등에 자주 사용) - public static BusinessException validationError(String code, String message) { - return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message); - } + // 409 Conflict + public static BusinessException conflict(String code, String message) { + return of(HttpStatus.CONFLICT, code, message); + } - public static BusinessException validationError(String message) { - return validationError("VALIDATION_ERROR", message); - } + public static BusinessException conflict(String message) { + return conflict("CONFLICT", message); + } - // 500 Internal Server Error - public static BusinessException internalError(String code, String message) { - return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message); - } + // 422 Unprocessable Entity (검증 에러 등에 자주 사용) + public static BusinessException validationError(String code, String message) { + return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message); + } - public static BusinessException internalError(String message) { - return internalError("INTERNAL_SERVER_ERROR", message); - } + public static BusinessException validationError(String message) { + return validationError("VALIDATION_ERROR", message); + } - public HttpStatus getStatus() { return status; } - public String getCode() { return code; } - public Map getExtras() { return extras; } + // 500 Internal Server Error + public static BusinessException internalError(String code, String message) { + return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message); + } - /** 편의: 체이닝으로 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()); - } + public static BusinessException internalError(String message) { + return internalError("INTERNAL_SERVER_ERROR", message); + } + + public HttpStatus getStatus() { + return status; + } + + public String getCode() { + return code; + } + + public Map 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()); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/web/CommonWebAutoConfiguration.java b/src/main/java/com/kri/common/web/CommonWebAutoConfiguration.java index 4ca1333..a971952 100644 --- a/src/main/java/com/kri/common/web/CommonWebAutoConfiguration.java +++ b/src/main/java/com/kri/common/web/CommonWebAutoConfiguration.java @@ -2,17 +2,23 @@ package com.kri.common.web; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; @AutoConfiguration @ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true) public class CommonWebAutoConfiguration { - @Bean public ErrorAdvice errorAdvice() { return new ErrorAdvice(); } - @Bean public FilterRegistrationBean traceFilter() { - var reg = new FilterRegistrationBean<>(new TraceFilter()); - reg.setOrder(Ordered.HIGHEST_PRECEDENCE); - return reg; - } + + @Bean + public ErrorAdvice errorAdvice() { + return new ErrorAdvice(); + } + + @Bean + public FilterRegistrationBean traceFilter() { + var reg = new FilterRegistrationBean<>(new TraceFilter()); + reg.setOrder(Ordered.HIGHEST_PRECEDENCE); + return reg; + } } diff --git a/src/main/java/com/kri/common/web/ErrorAdvice.java b/src/main/java/com/kri/common/web/ErrorAdvice.java index b7597c4..2f1e296 100644 --- a/src/main/java/com/kri/common/web/ErrorAdvice.java +++ b/src/main/java/com/kri/common/web/ErrorAdvice.java @@ -2,6 +2,11 @@ package com.kri.common.web; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.ConstraintViolationException; +import java.time.Instant; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -11,6 +16,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.ErrorResponseException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -18,190 +25,201 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.NoHandlerFoundException; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.servlet.resource.NoResourceFoundException; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; - @RestControllerAdvice public class ErrorAdvice { - private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class); - // 기본값은 모두 false → 외부 응답엔 노출 안 함 - @Value("${common.error.expose.handler:false}") - private boolean exposeHandler; - @Value("${common.error.expose.service:false}") - private boolean exposeService; + private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class); - /* ---------- 공통 ProblemDetail 빌더 ---------- */ - protected ProblemDetail pd(HttpStatus status, String code, String message, - HttpServletRequest req, Map extras) { - ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message); - p.setTitle(status.getReasonPhrase()); - p.setProperty("code", code); - p.setProperty("timestamp", Instant.now().toString()); - p.setProperty("path", req.getRequestURI()); + // 기본값은 모두 false → 외부 응답엔 노출 안 함 + @Value("${common.error.expose.handler:false}") + private boolean exposeHandler; + @Value("${common.error.expose.service:false}") + private boolean exposeService; - String traceId = MDC.get("traceId"); - if (traceId != null) p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적 + private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) { + Set httpMethods = e.getSupportedHttpMethods(); + if (httpMethods != null && !httpMethods.isEmpty()) { + // ✅ 핵심 수정: Enum::name 대신 HttpMethod::name + return httpMethods.stream() + .map(HttpMethod::name) + .collect(Collectors.joining(", ")); + } + String[] methods = e.getSupportedMethods(); // 구버전 호환용 + if (methods != null && methods.length > 0) { + return String.join(", ", methods); + } + return "N/A"; + } - // ↓↓↓ 외부로 숨기고 싶으면 기본 false - if (exposeHandler) { - String handler = MDC.get("handler"); // Controller#method - if (handler != null) p.setProperty("handler", handler); - } - if (exposeService) { - String service = MDC.get("service"); // Service#method (최초 진입) - if (service != null) p.setProperty("service", service); - } + /* ---------- 공통 ProblemDetail 빌더 ---------- */ + protected ProblemDetail pd(HttpStatus status, String code, String message, + HttpServletRequest req, Map extras) { + ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message); + p.setTitle(status.getReasonPhrase()); + p.setProperty("code", code); + p.setProperty("timestamp", Instant.now().toString()); + p.setProperty("path", req.getRequestURI()); - if (extras != null) extras.forEach(p::setProperty); - return p; + String traceId = MDC.get("traceId"); + if (traceId != null) { + p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적 } - /* ---------- Custom Exception ---------- */ - @ExceptionHandler(BusinessException.class) - public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) { - logBusiness(e, req); // ← 로그 먼저 - return pd( - e.getStatus(), - e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨) - e.getMessage(), - req, - e.getExtras().isEmpty() ? null : e.getExtras() - ); + // ↓↓↓ 외부로 숨기고 싶으면 기본 false + if (exposeHandler) { + String handler = MDC.get("handler"); // Controller#method + if (handler != null) { + p.setProperty("handler", handler); + } + } + if (exposeService) { + String service = MDC.get("service"); // Service#method (최초 진입) + if (service != null) { + p.setProperty("service", service); + } } - /* 상황별 로그 레벨/스택트레이스 정책 */ - private void logBusiness(BusinessException e, HttpServletRequest req) { - int sc = e.getStatus().value(); - String traceId = MDC.get("traceId"); - String path = req.getRequestURI(); - String code = e.getCode(); - var extras = e.getExtras(); - - if (sc >= 500) { - // 5xx: 운영 이슈 → ERROR + 스택트레이스 - log.error("BusinessException status={} code={} path={} traceId={} extras={}", - sc, code, path, traceId, extras, e); - } else if (sc == 409 || sc == 404 || sc == 400 || sc == 403 || sc == 422) { - // 사용자/도메인 입력 문제 → WARN, 스택트레이스 제외 - log.warn("BusinessException status={} code={} path={} traceId={} extras={}", - sc, code, path, traceId, extras); - } else { - // 기타 → WARN 기본 - log.warn("BusinessException status={} code={} path={} traceId={} extras={}", - sc, code, path, traceId, extras); - } + if (extras != null) { + extras.forEach(p::setProperty); } + return p; + } - /* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */ - @ExceptionHandler(MethodArgumentNotValidException.class) - public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest req) { - var fieldErrors = e.getBindingResult().getFieldErrors().stream() - .map(fe -> Map.of( - "field", fe.getField(), - "message", Optional.ofNullable(fe.getDefaultMessage()).orElse("invalid"), - "rejectedValue", String.valueOf(fe.getRejectedValue()) - )) - .collect(Collectors.toList()); - return pd(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "요청 데이터가 올바르지 않습니다.", req, - Map.of("errors", fieldErrors)); - } + /* ---------- Custom Exception ---------- */ + @ExceptionHandler(BusinessException.class) + public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) { + logBusiness(e, req); // ← 로그 먼저 + return pd( + e.getStatus(), + e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨) + e.getMessage(), + req, + e.getExtras().isEmpty() ? null : e.getExtras() + ); + } - /* ---------- 400: 파라미터/타입 문제 ---------- */ - @ExceptionHandler({ - MissingServletRequestParameterException.class, - HttpMessageNotReadableException.class - }) - public ProblemDetail handleBadRequest(RuntimeException e, HttpServletRequest req) { - String msg = (e instanceof HttpMessageNotReadableException) - ? "요청 바디를 읽을 수 없습니다(형식 오류/잘못된 JSON)." - : e.getMessage(); - return pd(HttpStatus.BAD_REQUEST, "BAD_REQUEST", msg, req, null); - } + /* 상황별 로그 레벨/스택트레이스 정책 */ + private void logBusiness(BusinessException e, HttpServletRequest req) { + int sc = e.getStatus().value(); + String traceId = MDC.get("traceId"); + String path = req.getRequestURI(); + String code = e.getCode(); + var extras = e.getExtras(); - @ExceptionHandler(MethodArgumentTypeMismatchException.class) - public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, HttpServletRequest req) { - String need = (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type"; - String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need; - return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null); + if (sc >= 500) { + // 5xx: 운영 이슈 → ERROR + 스택트레이스 + log.error("BusinessException status={} code={} path={} traceId={} extras={}", + sc, code, path, traceId, extras, e); + } else if (sc == 409 || sc == 404 || sc == 400 || sc == 403 || sc == 422) { + // 사용자/도메인 입력 문제 → WARN, 스택트레이스 제외 + log.warn("BusinessException status={} code={} path={} traceId={} extras={}", + sc, code, path, traceId, extras); + } else { + // 기타 → WARN 기본 + log.warn("BusinessException status={} code={} path={} traceId={} extras={}", + sc, code, path, traceId, extras); } + } - /* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */ - @ExceptionHandler(ConstraintViolationException.class) - public ProblemDetail handleConstraintViolation(ConstraintViolationException e, HttpServletRequest req) { - var errors = e.getConstraintViolations().stream() - .map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage())) - .collect(Collectors.toList()); - return pd(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", "요청 파라미터가 제약을 위반했습니다.", req, - Map.of("errors", errors)); - } + /* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, + HttpServletRequest req) { + var fieldErrors = e.getBindingResult().getFieldErrors().stream() + .map(fe -> Map.of( + "field", fe.getField(), + "message", Optional.ofNullable(fe.getDefaultMessage()).orElse("invalid"), + "rejectedValue", String.valueOf(fe.getRejectedValue()) + )) + .collect(Collectors.toList()); + return pd(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "요청 데이터가 올바르지 않습니다.", req, + Map.of("errors", fieldErrors)); + } - /* ---------- 404/405/415 등 표준 스프링 예외 ---------- */ - @ExceptionHandler(NoResourceFoundException.class) - public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) { - return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null); - } + /* ---------- 400: 파라미터/타입 문제 ---------- */ + @ExceptionHandler({ + MissingServletRequestParameterException.class, + HttpMessageNotReadableException.class + }) + public ProblemDetail handleBadRequest(RuntimeException e, HttpServletRequest req) { + String msg = (e instanceof HttpMessageNotReadableException) + ? "요청 바디를 읽을 수 없습니다(형식 오류/잘못된 JSON)." + : e.getMessage(); + return pd(HttpStatus.BAD_REQUEST, "BAD_REQUEST", msg, req, null); + } - @ExceptionHandler(NoHandlerFoundException.class) - public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) { - return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null); - } + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, + HttpServletRequest req) { + String need = + (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type"; + String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need; + return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null); + } - @ExceptionHandler(HttpRequestMethodNotSupportedException.class) - public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest req) { - String supported = resolveSupportedMethods(e); - String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported; - // 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported) - return pd(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", msg, req, null); - } + /* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */ + @ExceptionHandler(ConstraintViolationException.class) + public ProblemDetail handleConstraintViolation(ConstraintViolationException e, + HttpServletRequest req) { + var errors = e.getConstraintViolations().stream() + .map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage())) + .collect(Collectors.toList()); + return pd(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", "요청 파라미터가 제약을 위반했습니다.", req, + Map.of("errors", errors)); + } - @ExceptionHandler(HttpMediaTypeNotSupportedException.class) - public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, HttpServletRequest req) { - String supported = e.getSupportedMediaTypes().stream().map(Object::toString).collect(Collectors.joining(",")); - String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported; - return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null); - } + /* ---------- 404/405/415 등 표준 스프링 예외 ---------- */ + @ExceptionHandler(NoResourceFoundException.class) + public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) { + return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null); + } - /* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */ - @ExceptionHandler({ ResponseStatusException.class, ErrorResponseException.class }) - public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) { - HttpStatus status; - String reason; - if (e instanceof ResponseStatusException rse) { - status = HttpStatus.valueOf(rse.getStatusCode().value()); - reason = Optional.ofNullable(rse.getReason()).orElse(status.getReasonPhrase()); - } else { // ErrorResponseException (Spring 6+) - var ere = (ErrorResponseException) e; - status = HttpStatus.valueOf(ere.getStatusCode().value()); - reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail).orElse(status.getReasonPhrase()); - } - return pd(status, "ERROR", reason, req, null); - } + @ExceptionHandler(NoHandlerFoundException.class) + public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) { + return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null); + } - /* ---------- 마지막: 예상 못한 예외는 500 ---------- */ - @ExceptionHandler(Exception.class) - public ProblemDetail handleAny(Exception e, HttpServletRequest req) { - log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e); - return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null); - } + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, + HttpServletRequest req) { + String supported = resolveSupportedMethods(e); + String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported; + // 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported) + return pd(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", msg, req, null); + } - private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) { - Set httpMethods = e.getSupportedHttpMethods(); - if (httpMethods != null && !httpMethods.isEmpty()) { - // ✅ 핵심 수정: Enum::name 대신 HttpMethod::name - return httpMethods.stream() - .map(HttpMethod::name) - .collect(Collectors.joining(", ")); - } - String[] methods = e.getSupportedMethods(); // 구버전 호환용 - if (methods != null && methods.length > 0) { - return String.join(", ", methods); - } - return "N/A"; + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, + HttpServletRequest req) { + String supported = e.getSupportedMediaTypes().stream().map(Object::toString) + .collect(Collectors.joining(",")); + String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported; + return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null); + } + + /* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */ + @ExceptionHandler({ResponseStatusException.class, ErrorResponseException.class}) + public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) { + HttpStatus status; + String reason; + if (e instanceof ResponseStatusException rse) { + status = HttpStatus.valueOf(rse.getStatusCode().value()); + reason = Optional.ofNullable(rse.getReason()).orElse(status.getReasonPhrase()); + } else { // ErrorResponseException (Spring 6+) + var ere = (ErrorResponseException) e; + status = HttpStatus.valueOf(ere.getStatusCode().value()); + reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail) + .orElse(status.getReasonPhrase()); } + return pd(status, "ERROR", reason, req, null); + } + + /* ---------- 마지막: 예상 못한 예외는 500 ---------- */ + @ExceptionHandler(Exception.class) + public ProblemDetail handleAny(Exception e, HttpServletRequest req) { + log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e); + return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null); + } } diff --git a/src/main/java/com/kri/common/web/MdcHandlerConfig.java b/src/main/java/com/kri/common/web/MdcHandlerConfig.java index b29328e..cdb0e5d 100644 --- a/src/main/java/com/kri/common/web/MdcHandlerConfig.java +++ b/src/main/java/com/kri/common/web/MdcHandlerConfig.java @@ -1,33 +1,39 @@ package com.kri.common.web; -import jakarta.servlet.http.*; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.slf4j.MDC; import org.springframework.context.annotation.Bean; import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.config.annotation.*; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; public class MdcHandlerConfig { - @Bean - public WebMvcConfigurer mdcWebMvcConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() { - @Override - public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) { - if (handler instanceof HandlerMethod hm) { - String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController - String method = hm.getMethod().getName(); // ex) create - MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create - } - return true; - } - @Override - public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) { - MDC.remove("handler"); - } - }); + + @Bean + public WebMvcConfigurer mdcWebMvcConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() { + @Override + public boolean preHandle(HttpServletRequest req, HttpServletResponse res, + Object handler) { + if (handler instanceof HandlerMethod hm) { + String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController + String method = hm.getMethod().getName(); // ex) create + MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create } - }; - } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest req, HttpServletResponse res, + Object handler, Exception ex) { + MDC.remove("handler"); + } + }); + } + }; + } } diff --git a/src/main/java/com/kri/common/web/ServiceMdcAspect.java b/src/main/java/com/kri/common/web/ServiceMdcAspect.java index 705e21c..cd693b0 100644 --- a/src/main/java/com/kri/common/web/ServiceMdcAspect.java +++ b/src/main/java/com/kri/common/web/ServiceMdcAspect.java @@ -1,25 +1,30 @@ package com.kri.common.web; import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.*; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; import org.slf4j.MDC; import org.springframework.stereotype.Component; @Aspect @Component public class ServiceMdcAspect { - @Around("within(@org.springframework.stereotype.Service *)") - public Object aroundService(ProceedingJoinPoint pjp) throws Throwable { - boolean first = (MDC.get("service") == null); - if (first) { - String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService - String mtd = pjp.getSignature().getName(); // ex) enqueue - MDC.put("service", cls + "#" + mtd); // ex) ExportService#enqueue - } - try { - return pjp.proceed(); - } finally { - if (first) MDC.remove("service"); - } + + @Around("within(@org.springframework.stereotype.Service *)") + public Object aroundService(ProceedingJoinPoint pjp) throws Throwable { + boolean first = (MDC.get("service") == null); + if (first) { + String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService + String mtd = pjp.getSignature().getName(); // ex) enqueue + MDC.put("service", + cls + "#" + mtd); // ex) ExportService#enqueue } + try { + return pjp.proceed(); + } finally { + if (first) { + MDC.remove("service"); + } + } + } } diff --git a/src/main/java/com/kri/common/web/TraceFilter.java b/src/main/java/com/kri/common/web/TraceFilter.java index fed0139..617abb0 100644 --- a/src/main/java/com/kri/common/web/TraceFilter.java +++ b/src/main/java/com/kri/common/web/TraceFilter.java @@ -1,28 +1,35 @@ package com.kri.common.web; -import jakarta.servlet.*; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.slf4j.MDC; import java.io.IOException; import java.util.UUID; +import org.slf4j.MDC; public class TraceFilter implements Filter { - private static final String REQ_HEADER = "X-Request-Id"; - private static final String MDC_KEY = "traceId"; - @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException { - var httpReq = (HttpServletRequest) req; - var httpRes = (HttpServletResponse) res; + private static final String REQ_HEADER = "X-Request-Id"; + private static final String MDC_KEY = "traceId"; - String id = httpReq.getHeader(REQ_HEADER); - if (id == null || id.isBlank()) id = UUID.randomUUID().toString(); + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + var httpReq = (HttpServletRequest) req; + var httpRes = (HttpServletResponse) res; - try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) { - httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo - chain.doFilter(req, res); - } + String id = httpReq.getHeader(REQ_HEADER); + if (id == null || id.isBlank()) { + id = UUID.randomUUID().toString(); } + + try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) { + httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo + chain.doFilter(req, res); + } + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/CodeEnumConverter.java b/src/main/java/com/kri/common/webmvc/CodeEnumConverter.java index a46acc6..78d7647 100644 --- a/src/main/java/com/kri/common/webmvc/CodeEnumConverter.java +++ b/src/main/java/com/kri/common/webmvc/CodeEnumConverter.java @@ -4,33 +4,36 @@ import com.kri.common.enums.CodeEnum; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; -public class CodeEnumConverter implements ConverterFactory { +public class CodeEnumConverter implements ConverterFactory { - @Override - public Converter getConverter(Class targetType) { - return source -> convert(source, targetType); + @Override + public Converter getConverter(Class targetType) { + return source -> convert(source, targetType); + } + + private T convert(String source, Class targetType) { + if (source == null || source.isBlank()) { + return null; } - private T convert(String source, Class targetType) { - if (source == null || source.isBlank()) return null; - - // 1) enum name으로 먼저 시도 (EMAIL, SMS 등) - if (targetType.isEnum()) { - for (T e : targetType.getEnumConstants()) { - if (((Enum) e).name().equalsIgnoreCase(source)) { - return e; - } - } + // 1) enum name으로 먼저 시도 (EMAIL, SMS 등) + if (targetType.isEnum()) { + for (T e : targetType.getEnumConstants()) { + if (((Enum) e).name().equalsIgnoreCase(source)) { + return e; } - - // 2) code로 시도 ("11" 등) - for (T e : targetType.getEnumConstants()) { - Object code = e.getCode(); - if (code != null && source.equals(String.valueOf(code))) { - return e; - } - } - - throw new IllegalArgumentException("Unknown enum value: " + source + " for " + targetType.getName()); + } } + + // 2) code로 시도 ("11" 등) + for (T e : targetType.getEnumConstants()) { + Object code = e.getCode(); + if (code != null && source.equals(String.valueOf(code))) { + return e; + } + } + + throw new IllegalArgumentException( + "Unknown enum value: " + source + " for " + targetType.getName()); + } } diff --git a/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java b/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java index 44457bd..6fc71c3 100644 --- a/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java +++ b/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java @@ -8,19 +8,19 @@ import org.springframework.web.servlet.HandlerInterceptor; @RequiredArgsConstructor public class IpAccessControlInterceptor implements HandlerInterceptor { - private final IpAccessControlService ipAccessControlService; + private final IpAccessControlService ipAccessControlService; - @Override - public boolean preHandle(HttpServletRequest request, - HttpServletResponse response, - Object handler) throws Exception { + @Override + public boolean preHandle(HttpServletRequest request, + HttpServletResponse response, + Object handler) throws Exception { - String clientIpAddress = IpUtil.getClientIp(request); - if (!ipAccessControlService.isAccessible(clientIpAddress)) { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - return false; - } - - return true; + String clientIpAddress = IpUtil.getClientIp(request); + if (!ipAccessControlService.isAccessible(clientIpAddress)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return false; } + + return true; + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/IpAccessControlService.java b/src/main/java/com/kri/common/webmvc/IpAccessControlService.java index 65b0345..52ab44b 100644 --- a/src/main/java/com/kri/common/webmvc/IpAccessControlService.java +++ b/src/main/java/com/kri/common/webmvc/IpAccessControlService.java @@ -1,20 +1,19 @@ package com.kri.common.webmvc; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.security.web.util.matcher.IpAddressMatcher; -import java.util.List; - @RequiredArgsConstructor public class IpAccessControlService { - private final KriIpAccessProperties properties; + private final KriIpAccessProperties properties; - public boolean isAccessible(String ipAddress) { - List cidrs = properties.getEffectiveCidrs(); + public boolean isAccessible(String ipAddress) { + List cidrs = properties.getEffectiveCidrs(); - return cidrs.stream() - .map(IpAddressMatcher::new) - .anyMatch(matcher -> matcher.matches(ipAddress)); - } + return cidrs.stream() + .map(IpAddressMatcher::new) + .anyMatch(matcher -> matcher.matches(ipAddress)); + } } diff --git a/src/main/java/com/kri/common/webmvc/IpUtil.java b/src/main/java/com/kri/common/webmvc/IpUtil.java index 904c83e..4fdd99b 100644 --- a/src/main/java/com/kri/common/webmvc/IpUtil.java +++ b/src/main/java/com/kri/common/webmvc/IpUtil.java @@ -4,24 +4,24 @@ import jakarta.servlet.http.HttpServletRequest; public final class IpUtil { - private IpUtil() { + private IpUtil() { + } + + public static String getClientIp(HttpServletRequest request) { + // 1. Proxy 환경 고려: X-Forwarded-For 헤더 우선 + String xff = request.getHeader("X-Forwarded-For"); + if (xff != null && !xff.isBlank()) { + // X-Forwarded-For: client, proxy1, proxy2 ... + return xff.split(",")[0].trim(); } - public static String getClientIp(HttpServletRequest request) { - // 1. Proxy 환경 고려: X-Forwarded-For 헤더 우선 - String xff = request.getHeader("X-Forwarded-For"); - if (xff != null && !xff.isBlank()) { - // X-Forwarded-For: client, proxy1, proxy2 ... - return xff.split(",")[0].trim(); - } - - // 2. 그 다음 X-Real-IP - String realIp = request.getHeader("X-Real-IP"); - if (realIp != null && !realIp.isBlank()) { - return realIp; - } - - // 3. 최후 fallback - return request.getRemoteAddr(); + // 2. 그 다음 X-Real-IP + String realIp = request.getHeader("X-Real-IP"); + if (realIp != null && !realIp.isBlank()) { + return realIp; } + + // 3. 최후 fallback + return request.getRemoteAddr(); + } } diff --git a/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java b/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java index c41c085..081bf74 100644 --- a/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java +++ b/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java @@ -1,44 +1,41 @@ package com.kri.common.webmvc; -import lombok.Getter; -import lombok.Setter; -import org.springframework.boot.context.properties.ConfigurationProperties; - import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; @Getter @Setter @ConfigurationProperties(prefix = "kri.webmvc.ip") public class KriIpAccessProperties { - /** - * 공통에서 고정으로 들고 갈 기본 CIDR 들 - * → setter 없음 (외부에서 못 바꿈) - */ - private final List defaultCidrs = List.of( - "127.0.0.1/32", // 로컬 IPv4 - "::1/128", // 로컬 IPv6 - "10.10.13.0/24", //석오 내부망 - "211.254.145.128/25" //석오 내부망 외부 IP - ); + /** + * 공통에서 고정으로 들고 갈 기본 CIDR 들 → setter 없음 (외부에서 못 바꿈) + */ + private final List defaultCidrs = List.of( + "127.0.0.1/32", // 로컬 IPv4 + "::1/128", // 로컬 IPv6 + "10.10.13.0/24", //석오 내부망 + "211.254.145.128/25" //석오 내부망 외부 IP + ); - /** - * 서비스에서 추가로 넣고 싶은 CIDR 목록 - * application.yml / properties 로 바인딩되는 리스트 - * - * 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16 - */ - private List additionalCidrs = new ArrayList<>(); + /** + * 서비스에서 추가로 넣고 싶은 CIDR 목록 application.yml / properties 로 바인딩되는 리스트 + *

+ * 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16 + */ + private List additionalCidrs = new ArrayList<>(); - /** - * 기본 + 추가를 합친 최종 목록 - */ - public List getEffectiveCidrs() { - return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream()) - .distinct() - .collect(Collectors.toList()); - } + /** + * 기본 + 추가를 합친 최종 목록 + */ + public List getEffectiveCidrs() { + return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream()) + .distinct() + .collect(Collectors.toList()); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java b/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java index 92038ae..81f3976 100644 --- a/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java +++ b/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java @@ -19,70 +19,70 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @RequiredArgsConstructor public class KriWebMvcAutoConfiguration { - private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor) + private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor) + // 선택 주입: 있으면 쓰고, 없으면 안 씀 + private final ObjectProvider ipAccessControlInterceptorProvider; - @Bean - @ConditionalOnMissingBean - public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) { - return new IpAccessControlService(ipProps); - } + @Bean + @ConditionalOnMissingBean + public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) { + return new IpAccessControlService(ipProps); + } - @Bean - @ConditionalOnMissingBean - public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) { - return new IpAccessControlInterceptor(service); - } + @Bean + @ConditionalOnMissingBean + public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) { + return new IpAccessControlInterceptor(service); + } - // 선택 주입: 있으면 쓰고, 없으면 안 씀 - private final ObjectProvider ipAccessControlInterceptorProvider; + @Bean + @ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작 + @ConditionalOnMissingBean + public RequestUserContextArgumentResolver requestUserContextArgumentResolver( + JwtService jwtService + ) { + return new RequestUserContextArgumentResolver(jwtService); + } - @Bean - @ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작 - @ConditionalOnMissingBean - public RequestUserContextArgumentResolver requestUserContextArgumentResolver( - JwtService jwtService - ) { - return new RequestUserContextArgumentResolver(jwtService); - } + /** + * 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean + */ + @Bean + public WebMvcConfigurer kriCommonWebMvcConfigurer( + KriIpAccessProperties properties, + ObjectProvider ipAccessControlInterceptorProvider, + ObjectProvider requestUserContextArgumentResolverProvider + ) { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + // 기본 CORS – 필요하면 나중에 조정 + registry.addMapping("/**") + .allowedOriginPatterns("*") + .allowedMethods("*") + .allowedHeaders("*") + .allowCredentials(true); + } - /** - * 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean - */ - @Bean - public WebMvcConfigurer kriCommonWebMvcConfigurer( - KriIpAccessProperties properties, - ObjectProvider ipAccessControlInterceptorProvider, - ObjectProvider requestUserContextArgumentResolverProvider - ) { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - // 기본 CORS – 필요하면 나중에 조정 - registry.addMapping("/**") - .allowedOriginPatterns("*") - .allowedMethods("*") - .allowedHeaders("*") - .allowCredentials(true); - } + @Override + public void addInterceptors(InterceptorRegistry registry) { + ipAccessControlInterceptorProvider.ifAvailable(interceptor -> + registry.addInterceptor(interceptor) + .order(1) + .addPathPatterns("/swagger-ui/**", "/v3/api-docs/**") + ); + } - @Override - public void addInterceptors(InterceptorRegistry registry) { - ipAccessControlInterceptorProvider.ifAvailable(interceptor -> - registry.addInterceptor(interceptor) - .order(1) - .addPathPatterns("/swagger-ui/**", "/v3/api-docs/**") - ); - } + @Override + public void addArgumentResolvers( + java.util.List resolvers) { + requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add); + } - @Override - public void addArgumentResolvers(java.util.List resolvers) { - requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add); - } - - @Override - public void addFormatters(org.springframework.format.FormatterRegistry registry) { - registry.addConverterFactory(new com.kri.common.webmvc.CodeEnumConverter()); - } - }; - } + @Override + public void addFormatters(org.springframework.format.FormatterRegistry registry) { + registry.addConverterFactory(new com.kri.common.webmvc.CodeEnumConverter()); + } + }; + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/RequestUserContext.java b/src/main/java/com/kri/common/webmvc/RequestUserContext.java index c5de3ac..438a6c3 100644 --- a/src/main/java/com/kri/common/webmvc/RequestUserContext.java +++ b/src/main/java/com/kri/common/webmvc/RequestUserContext.java @@ -7,15 +7,15 @@ import lombok.Value; @Builder public class RequestUserContext { - String userId; - String userCmpn; - String userTeam; - String userName; - Integer userRole; + String userId; + String userCmpn; + String userTeam; + String userName; + Integer userRole; - String clientIp; // IpUtil 에서 가져온 값 + String clientIp; // IpUtil 에서 가져온 값 - public boolean isAuthenticated() { - return userId != null; - } + public boolean isAuthenticated() { + return userId != null; + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java b/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java index a7f83e2..3730ab3 100644 --- a/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java +++ b/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java @@ -1,7 +1,7 @@ package com.kri.common.webmvc; -import com.kri.common.auth.jwt.JwtService; import com.kri.common.auth.dto.JwtUserClaimsDto; +import com.kri.common.auth.jwt.JwtService; import io.jsonwebtoken.JwtException; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; @@ -17,60 +17,60 @@ import org.springframework.web.method.support.ModelAndViewContainer; @RequiredArgsConstructor public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver { - private final JwtService jwtService; + private final JwtService jwtService; - @Override - public boolean supportsParameter(MethodParameter parameter) { - return RequestUserContext.class.isAssignableFrom(parameter.getParameterType()); + @Override + public boolean supportsParameter(MethodParameter parameter) { + return RequestUserContext.class.isAssignableFrom(parameter.getParameterType()); + } + + @Override + public Object resolveArgument( + MethodParameter parameter, + @Nullable ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, + @Nullable WebDataBinderFactory binderFactory + ) { + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); + + String clientIp = request != null ? IpUtil.getClientIp(request) : null; + + JwtUserClaimsDto claims = null; + + // 1) SecurityContext 에 이미 JwtUserClaimsDto 가 principal 로 들어있는 경우 + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getPrincipal() instanceof JwtUserClaimsDto jwtDto) { + claims = jwtDto; } - @Override - public Object resolveArgument( - MethodParameter parameter, - @Nullable ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - @Nullable WebDataBinderFactory binderFactory - ) { - HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); - - String clientIp = request != null ? IpUtil.getClientIp(request) : null; - - JwtUserClaimsDto claims = null; - - // 1) SecurityContext 에 이미 JwtUserClaimsDto 가 principal 로 들어있는 경우 - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (auth != null && auth.getPrincipal() instanceof JwtUserClaimsDto jwtDto) { - claims = jwtDto; + // 2) 현재 공통 JwtService 는 principal 을 userId(String) 로 쓰고 있으니까, + // 필요하면 Authorization 헤더에서 직접 토큰 파싱 + if (claims == null && request != null) { + String authHeader = request.getHeader("Authorization"); + if (authHeader != null && authHeader.startsWith("Bearer ")) { + String token = authHeader.substring(7); + try { + claims = jwtService.toUserClaimsDto(token); + } catch (JwtException ex) { + // 토큰 이상하면 그냥 anonymous 로 둠 } - - // 2) 현재 공통 JwtService 는 principal 을 userId(String) 로 쓰고 있으니까, - // 필요하면 Authorization 헤더에서 직접 토큰 파싱 - if (claims == null && request != null) { - String authHeader = request.getHeader("Authorization"); - if (authHeader != null && authHeader.startsWith("Bearer ")) { - String token = authHeader.substring(7); - try { - claims = jwtService.toUserClaimsDto(token); - } catch (JwtException ex) { - // 토큰 이상하면 그냥 anonymous 로 둠 - } - } - } - - if (claims == null) { - // 비인증 상태: IP만 채운 빈 컨텍스트 - return RequestUserContext.builder() - .clientIp(clientIp) - .build(); - } - - return RequestUserContext.builder() - .userId(claims.getUserId()) - .userCmpn(claims.getUserCmpn()) - .userTeam(claims.getUserTeam()) - .userName(claims.getUserName()) - .userRole(claims.getUserRole()) - .clientIp(clientIp) - .build(); + } } + + if (claims == null) { + // 비인증 상태: IP만 채운 빈 컨텍스트 + return RequestUserContext.builder() + .clientIp(clientIp) + .build(); + } + + return RequestUserContext.builder() + .userId(claims.getUserId()) + .userCmpn(claims.getUserCmpn()) + .userTeam(claims.getUserTeam()) + .userName(claims.getUserName()) + .userRole(claims.getUserRole()) + .clientIp(clientIp) + .build(); + } } diff --git a/src/main/java/com/kri/common/webmvc/page/PageRequestDto.java b/src/main/java/com/kri/common/webmvc/page/PageRequestDto.java index 5c0eaca..25f1695 100644 --- a/src/main/java/com/kri/common/webmvc/page/PageRequestDto.java +++ b/src/main/java/com/kri/common/webmvc/page/PageRequestDto.java @@ -8,13 +8,14 @@ import lombok.Setter; @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 + @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 } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/page/PageResponseDto.java b/src/main/java/com/kri/common/webmvc/page/PageResponseDto.java index dc714c4..960a43a 100644 --- a/src/main/java/com/kri/common/webmvc/page/PageResponseDto.java +++ b/src/main/java/com/kri/common/webmvc/page/PageResponseDto.java @@ -1,35 +1,35 @@ package com.kri.common.webmvc.page; +import java.util.List; import lombok.Builder; import lombok.Getter; import org.springframework.data.domain.Page; -import java.util.List; - @Getter @Builder -public class PageResponseDto { - private List 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 class PageResponseDto { - public static PageResponseDto from(Page page) { - return PageResponseDto.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(); - } + private List 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 PageResponseDto from(Page page) { + return PageResponseDto.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(); + } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/page/Pageables.java b/src/main/java/com/kri/common/webmvc/page/Pageables.java index 7901fb6..e4db793 100644 --- a/src/main/java/com/kri/common/webmvc/page/Pageables.java +++ b/src/main/java/com/kri/common/webmvc/page/Pageables.java @@ -1,67 +1,77 @@ package com.kri.common.webmvc.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; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.util.*; -import java.util.stream.Collectors; - 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); + private Pageables() { + } - Sort sort = buildSort(req, sortType); - return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort); + 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; } - 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; - Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir()) - ? Sort.Direction.ASC - : Sort.Direction.DESC; + Set allowed = allowedProperties(sortType); - Set allowed = allowedProperties(sortType); + List props = Arrays.stream(sortBy.split(",")) + .map(String::trim) + .filter(s -> !s.isBlank()) + .collect(Collectors.toList()); - List props = Arrays.stream(sortBy.split(",")) - .map(String::trim) - .filter(s -> !s.isBlank()) - .collect(Collectors.toList()); + // 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨) + List invalid = props.stream() + .filter(p -> !allowed.contains(p)) + .toList(); - // 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨) - List invalid = props.stream() - .filter(p -> !allowed.contains(p)) - .toList(); + if (!invalid.isEmpty()) { + throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed); + } - if (!invalid.isEmpty()) { - throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed); + return Sort.by(dir, props.toArray(String[]::new)); + } + + private static Set allowedProperties(Class sortType) { + try { + // getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적) + PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors(); + Set props = new HashSet<>(); + for (PropertyDescriptor pd : pds) { + String name = pd.getName(); + if ("class".equals(name)) { + continue; } - - return Sort.by(dir, props.toArray(String[]::new)); - } - - private static Set allowedProperties(Class sortType) { - try { - // getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적) - PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors(); - Set 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); + if (pd.getReadMethod() == null) { + continue; } + props.add(name); + } + return props; + } catch (Exception e) { + throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e); } + } } \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index e5bb0e0..8527e7a 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -1,50 +1,50 @@ - - - + + + + + ${LOG_PATTERN} + + + + + ${LOG_PATTERN} + + ${LOG_DIR}/${APP_NAME}.log + + ${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz + 14 + + - - + + + + 0 + true + 8192 + - - - - - ${LOG_PATTERN} - - + + - - - ${LOG_DIR}/${APP_NAME}.log - - ${LOG_PATTERN} - - - ${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz - 14 - - + + + + + - - - 8192 - 0 - true - - + + - - + + - - - - + \ No newline at end of file