260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용
This commit is contained in:
89
README.md
89
README.md
@@ -20,6 +20,7 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
|
|||||||
- 주요 클래스: `ExternalApiClient`, `ExternalApiResponse`
|
- 주요 클래스: `ExternalApiClient`, `ExternalApiResponse`
|
||||||
|
|
||||||
지원 메서드(문자열 body 기반)
|
지원 메서드(문자열 body 기반)
|
||||||
|
|
||||||
- `ExternalApiResponse get(String url, Map<String,String> headers)`
|
- `ExternalApiResponse get(String url, Map<String,String> headers)`
|
||||||
- `ExternalApiResponse post(String url, Map<String,String> headers, String body)`
|
- `ExternalApiResponse post(String url, Map<String,String> headers, String body)`
|
||||||
- `ExternalApiResponse put(String url, Map<String,String> headers, String body)`
|
- `ExternalApiResponse put(String url, Map<String,String> headers, String body)`
|
||||||
@@ -27,11 +28,13 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
|
|||||||
- `ExternalApiResponse delete(String url, Map<String,String> headers)`
|
- `ExternalApiResponse delete(String url, Map<String,String> headers)`
|
||||||
|
|
||||||
기본 동작
|
기본 동작
|
||||||
|
|
||||||
- 연결 타임아웃: 10초, 요청 타임아웃: 30초
|
- 연결 타임아웃: 10초, 요청 타임아웃: 30초
|
||||||
- body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정
|
- body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정
|
||||||
- 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원
|
- 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원
|
||||||
|
|
||||||
응답 객체(`ExternalApiResponse`)
|
응답 객체(`ExternalApiResponse`)
|
||||||
|
|
||||||
- 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String)
|
- 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String)
|
||||||
- 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)`
|
- 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)`
|
||||||
|
|
||||||
@@ -77,6 +80,7 @@ ExternalApiClient client = new ExternalApiClient(httpClient, Duration.ofSeconds(
|
|||||||
```
|
```
|
||||||
|
|
||||||
주의사항
|
주의사항
|
||||||
|
|
||||||
- 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요.
|
- 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요.
|
||||||
- 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요.
|
- 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요.
|
||||||
|
|
||||||
@@ -264,6 +268,7 @@ kri:
|
|||||||
- com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용)
|
- com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용)
|
||||||
|
|
||||||
권장 의존 방향(순환 금지):
|
권장 의존 방향(순환 금지):
|
||||||
|
|
||||||
- auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸)
|
- auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸)
|
||||||
- security → auth.* 에 의존(필터 순서/체인 구성)
|
- security → auth.* 에 의존(필터 순서/체인 구성)
|
||||||
- web, webmvc → spring-web 중심, security에 의존하지 않음
|
- web, webmvc → spring-web 중심, security에 의존하지 않음
|
||||||
@@ -272,25 +277,33 @@ kri:
|
|||||||
|
|
||||||
### 0.2 AutoConfiguration 로딩과 오버라이드 전략
|
### 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
|
1) com.kri.common.auth.jwt.JwtAutoConfiguration
|
||||||
|
|
||||||
- JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공
|
- JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공
|
||||||
|
|
||||||
2) com.kri.common.security.KriSecurityAutoConfiguration
|
2) com.kri.common.security.KriSecurityAutoConfiguration
|
||||||
|
|
||||||
- SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입
|
- SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입
|
||||||
- before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입
|
- before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입
|
||||||
|
|
||||||
3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration
|
3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration
|
||||||
|
|
||||||
- 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터
|
- 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터
|
||||||
|
|
||||||
4) com.kri.common.swagger.KriSwaggerAutoConfiguration
|
4) com.kri.common.swagger.KriSwaggerAutoConfiguration
|
||||||
|
|
||||||
- OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록
|
- 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
|
- 선택 기능: RedisQueueHelper, @EnableScheduling
|
||||||
|
|
||||||
오버라이드 규칙:
|
오버라이드 규칙:
|
||||||
|
|
||||||
- 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선
|
- 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선
|
||||||
- 프로퍼티로 on/off 토글(@ConditionalOnProperty)
|
- 프로퍼티로 on/off 토글(@ConditionalOnProperty)
|
||||||
|
|
||||||
@@ -299,7 +312,7 @@ kri:
|
|||||||
- Stateless 세션, CSRF 비활성화, CORS 기본 허용
|
- Stateless 세션, CSRF 비활성화, CORS 기본 허용
|
||||||
- public-paths는 permitAll, 그 외 anyRequest().authenticated()
|
- public-paths는 permitAll, 그 외 anyRequest().authenticated()
|
||||||
- 필터 순서: ApiKeyAuthFilter → JwtAuthenticationFilter → UsernamePasswordAuthenticationFilter
|
- 필터 순서: ApiKeyAuthFilter → JwtAuthenticationFilter → UsernamePasswordAuthenticationFilter
|
||||||
- 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리
|
- 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리
|
||||||
|
|
||||||
### 0.4 설정 네임스페이스 정리
|
### 0.4 설정 네임스페이스 정리
|
||||||
|
|
||||||
@@ -389,7 +402,7 @@ KriCommon은 다음 AutoConfiguration 들을 제공합니다.
|
|||||||
모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다.
|
모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다.
|
||||||
|
|
||||||
| 클래스 | 역할 요약 |
|
| 클래스 | 역할 요약 |
|
||||||
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
|---------------------------------------------------------------|---------------------------------------------------------------------------------------|
|
||||||
| `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 |
|
| `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 |
|
||||||
| `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` |
|
| `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` |
|
||||||
| `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 |
|
| `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 |
|
||||||
@@ -499,7 +512,7 @@ public class JwtProperties {
|
|||||||
**프로퍼티 요약**
|
**프로퍼티 요약**
|
||||||
|
|
||||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||||
| --------------------------------------------- | ------ | ------------ | -------------------------------------- |
|
|-----------------------------------------------|--------|--------------|----------------------------------------|
|
||||||
| `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) |
|
| `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) |
|
||||||
| `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 |
|
| `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 |
|
||||||
| `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) |
|
| `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.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 |
|
||||||
| `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 |
|
| `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.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 |
|
||||||
| `kri.security.public-paths` | List<String> | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 |
|
| `kri.security.public-paths` | List<String> | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 |
|
||||||
|
|
||||||
@@ -866,7 +879,7 @@ public class KriIpAccessProperties {
|
|||||||
**프로퍼티 요약**
|
**프로퍼티 요약**
|
||||||
|
|
||||||
| 프로퍼티 | 타입 | 설명 |
|
| 프로퍼티 | 타입 | 설명 |
|
||||||
| -------------------------------- | ------------ | --------------------------------- |
|
|----------------------------------|--------------|-----------------------------------|
|
||||||
| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off |
|
| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off |
|
||||||
| `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 CIDR 목록에 *추가*할 CIDR 리스트 |
|
| `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 CIDR 목록에 *추가*할 CIDR 리스트 |
|
||||||
|
|
||||||
@@ -944,7 +957,7 @@ public class CommonRedisAutoConfiguration {
|
|||||||
**프로퍼티**
|
**프로퍼티**
|
||||||
|
|
||||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||||
| ---------------------- | ------- | ----- | ---------------------- |
|
|------------------------|---------|-------|------------------------|
|
||||||
| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 |
|
| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 |
|
||||||
|
|
||||||
#### 4.6.2. RedisQueueHelper 사용 예시
|
#### 4.6.2. RedisQueueHelper 사용 예시
|
||||||
@@ -980,7 +993,7 @@ public class CommonSchedulingAutoConfiguration { }
|
|||||||
**프로퍼티**
|
**프로퍼티**
|
||||||
|
|
||||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||||
| --------------------------- | ------- | ----- | -------------------------- |
|
|-----------------------------|---------|-------|----------------------------|
|
||||||
| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 |
|
| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 |
|
||||||
|
|
||||||
서비스 쪽에서는 단순히:
|
서비스 쪽에서는 단순히:
|
||||||
@@ -1022,7 +1035,6 @@ common:
|
|||||||
|
|
||||||
**던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다.
|
**던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다.
|
||||||
|
|
||||||
|
|
||||||
#### 4.9.2. 기본 사용 패턴
|
#### 4.9.2. 기본 사용 패턴
|
||||||
|
|
||||||
* 4.9.2.1. Not Found (404)
|
* 4.9.2.1. Not Found (404)
|
||||||
@@ -1040,12 +1052,14 @@ public User getUserOrThrow(String userId) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- HTTP 상태: 404
|
- HTTP 상태: 404
|
||||||
- code: "USER_NOT_FOUND"
|
- code: "USER_NOT_FOUND"
|
||||||
- message: "해당 사용자를 찾을 수 없습니다."
|
- message: "해당 사용자를 찾을 수 없습니다."
|
||||||
- extras: { "userId": "..." }
|
- extras: { "userId": "..." }
|
||||||
|
|
||||||
* 4.9.2.2. Conflict (409)
|
* 4.9.2.2. Conflict (409)
|
||||||
|
|
||||||
```
|
```
|
||||||
if (userRepository.existsByLoginId(loginId)) {
|
if (userRepository.existsByLoginId(loginId)) {
|
||||||
throw BusinessException.conflict(
|
throw BusinessException.conflict(
|
||||||
@@ -1056,6 +1070,7 @@ if (userRepository.existsByLoginId(loginId)) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
* 4.9.2.3. Forbidden (403)
|
* 4.9.2.3. Forbidden (403)
|
||||||
|
|
||||||
```
|
```
|
||||||
if (!currentUser.canAccess(targetProject)) {
|
if (!currentUser.canAccess(targetProject)) {
|
||||||
throw BusinessException.forbidden(
|
throw BusinessException.forbidden(
|
||||||
@@ -1066,7 +1081,9 @@ if (!currentUser.canAccess(targetProject)) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
#### 4.9.3. 임의 상태 코드 지정: of(...)
|
#### 4.9.3. 임의 상태 코드 지정: of(...)
|
||||||
|
|
||||||
of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다.
|
of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다.
|
||||||
|
|
||||||
```
|
```
|
||||||
throw BusinessException.of(
|
throw BusinessException.of(
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
@@ -1075,7 +1092,9 @@ throw BusinessException.of(
|
|||||||
).with("param", "startDate");
|
).with("param", "startDate");
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
추가 정보를 한 번에 넘기고 싶으면:
|
추가 정보를 한 번에 넘기고 싶으면:
|
||||||
|
|
||||||
```
|
```
|
||||||
Map<String, Object> extras = Map.of(
|
Map<String, Object> extras = Map.of(
|
||||||
"param", "startDate",
|
"param", "startDate",
|
||||||
@@ -1089,21 +1108,27 @@ throw BusinessException.of(
|
|||||||
extras
|
extras
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
> 실제 구현에는 of(status, code, message, Map<String,Object>) 시그니처가 존재합니다.
|
> 실제 구현에는 of(status, code, message, Map<String,Object>) 시그니처가 존재합니다.
|
||||||
|
|
||||||
#### 4.9.4. extras 체이닝: with(...) 활용
|
#### 4.9.4. extras 체이닝: with(...) 활용
|
||||||
|
|
||||||
with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다.
|
with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다.
|
||||||
|
|
||||||
```
|
```
|
||||||
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||||
.with("userId", userId)
|
.with("userId", userId)
|
||||||
.with("searchType", "INTRANET");
|
.with("searchType", "INTRANET");
|
||||||
```
|
```
|
||||||
|
|
||||||
* 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다.
|
* 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다.
|
||||||
|
|
||||||
#### 4.9.5. Service / Controller에서의 사용 위치
|
#### 4.9.5. Service / Controller에서의 사용 위치
|
||||||
|
|
||||||
Service에서 던지고, Controller는 깔끔하게 유지
|
Service에서 던지고, Controller는 깔끔하게 유지
|
||||||
|
|
||||||
Service 예시
|
Service 예시
|
||||||
|
|
||||||
```
|
```
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -1124,6 +1149,7 @@ public class UserService {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Controller 예시
|
Controller 예시
|
||||||
|
|
||||||
```
|
```
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/users")
|
@RequestMapping("/api/users")
|
||||||
@@ -1145,12 +1171,15 @@ public class UserController {
|
|||||||
* ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리
|
* ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리
|
||||||
|
|
||||||
#### 4.9.6. 실제 응답 JSON 예시
|
#### 4.9.6. 실제 응답 JSON 예시
|
||||||
|
|
||||||
```
|
```
|
||||||
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||||
.with("userId", "u-123");
|
.with("userId", "u-123");
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다.
|
요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"type": "about:blank",
|
"type": "about:blank",
|
||||||
@@ -1166,6 +1195,7 @@ throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없
|
|||||||
"userId": "u-123"
|
"userId": "u-123"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 이 포맷은 ErrorAdvice에서 공통으로 생성합니다.
|
> 이 포맷은 ErrorAdvice에서 공통으로 생성합니다.
|
||||||
|
|
||||||
#### 4.9.7. 로그 출력 정책
|
#### 4.9.7. 로그 출력 정책
|
||||||
@@ -1187,6 +1217,7 @@ ErrorAdvice 내부 로깅 정책(요약):
|
|||||||
#### 4.9.8. 에러 코드 enum으로 관리하기 (선택)
|
#### 4.9.8. 에러 코드 enum으로 관리하기 (선택)
|
||||||
|
|
||||||
서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다.
|
서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다.
|
||||||
|
|
||||||
```
|
```
|
||||||
public enum UserErrorCodes {
|
public enum UserErrorCodes {
|
||||||
USER_NOT_FOUND,
|
USER_NOT_FOUND,
|
||||||
@@ -1199,6 +1230,7 @@ throw BusinessException.notFound(
|
|||||||
"사용자를 찾을 수 없습니다."
|
"사용자를 찾을 수 없습니다."
|
||||||
).with("userId", userId);
|
).with("userId", userId);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 4.9.9. 요약
|
#### 4.9.9. 요약
|
||||||
|
|
||||||
1. 던지는 쪽 (Service)
|
1. 던지는 쪽 (Service)
|
||||||
@@ -1208,13 +1240,14 @@ throw BusinessException.notFound(
|
|||||||
* 필요시 of(status, code, message)
|
* 필요시 of(status, code, message)
|
||||||
* with("key", value)로 추가 정보(extras) 세팅
|
* with("key", value)로 추가 정보(extras) 세팅
|
||||||
2. 받는 쪽 (Controller)
|
2. 받는 쪽 (Controller)
|
||||||
* 별도 try/catch 필요 없음
|
* 별도 try/catch 필요 없음
|
||||||
* ErrorAdvice가 자동으로 JSON + 로그 처리
|
* ErrorAdvice가 자동으로 JSON + 로그 처리
|
||||||
3. 클라이언트/FE 입장
|
3. 클라이언트/FE 입장
|
||||||
* 응답은 ProblemDetail 포맷 + code + extras 일관 구조
|
* 응답은 ProblemDetail 포맷 + code + extras 일관 구조
|
||||||
* FE에서는 code 기준으로 에러 분기 처리하면 됨
|
* FE에서는 code 기준으로 에러 분기 처리하면 됨
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. example-service 적용 요약
|
## 5. example-service 적용 요약
|
||||||
|
|
||||||
1. **의존성 추가**
|
1. **의존성 추가**
|
||||||
@@ -1263,34 +1296,38 @@ throw BusinessException.notFound(
|
|||||||
## 7. 문제 해결 가이드(Troubleshooting)
|
## 7. 문제 해결 가이드(Troubleshooting)
|
||||||
|
|
||||||
- 애플리케이션 시작 시 "kri.auth.jwt.secret must be at least 32 bytes" 오류
|
- 애플리케이션 시작 시 "kri.auth.jwt.secret must be at least 32 bytes" 오류
|
||||||
- 원인: JWT 시크릿 최소 길이 미달
|
- 원인: JWT 시크릿 최소 길이 미달
|
||||||
- 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체
|
- 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체
|
||||||
|
|
||||||
- 모든 요청이 401 Unauthorized
|
- 모든 요청이 401 Unauthorized
|
||||||
- 원인1: Authorization 헤더에 Bearer 토큰 미포함
|
- 원인1: Authorization 헤더에 Bearer 토큰 미포함
|
||||||
- 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함)
|
- 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함)
|
||||||
- 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검
|
- 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검
|
||||||
|
|
||||||
- Swagger 페이지가 접근 불가(403/404)
|
- Swagger 페이지가 접근 불가(403/404)
|
||||||
- 원인: IP 접근 제어 또는 public-paths 미설정
|
- 원인: IP 접근 제어 또는 public-paths 미설정
|
||||||
- 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로 포함
|
- 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로
|
||||||
|
포함
|
||||||
|
|
||||||
- ApiKeyUserClaimsProvider가 동작하지 않음
|
- ApiKeyUserClaimsProvider가 동작하지 않음
|
||||||
- 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false`
|
- 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false`
|
||||||
- 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검
|
- 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. FAQ
|
## 8. FAQ
|
||||||
|
|
||||||
- Q. API Key와 JWT는 어떻게 같이 쓰나요?
|
- Q. API Key와 JWT는 어떻게 같이 쓰나요?
|
||||||
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 권장합니다.
|
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를
|
||||||
|
권장합니다.
|
||||||
|
|
||||||
- Q. ROLE 매핑은 어디서 바꾸나요?
|
- Q. ROLE 매핑은 어디서 바꾸나요?
|
||||||
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 오버라이드하거나 래핑하십시오.
|
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를
|
||||||
|
오버라이드하거나 래핑하십시오.
|
||||||
|
|
||||||
- Q. 기본 Security를 전면 교체할 수 있나요?
|
- Q. 기본 Security를 전면 교체할 수 있나요?
|
||||||
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 적용됩니다.
|
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선
|
||||||
|
적용됩니다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//버전 변경은 여기서
|
//버전 변경은 여기서
|
||||||
def commonVer = "beta.1.0.63"
|
def commonVer = "beta.1.0.63"
|
||||||
|
|
||||||
group = 'com.kri.common'
|
group = 'com.kri.common'
|
||||||
version = commonVer
|
version = commonVer
|
||||||
@@ -68,7 +68,7 @@ dependencies {
|
|||||||
compileOnly 'org.springframework.boot:spring-boot-starter-data-redis'
|
compileOnly 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||||
}
|
}
|
||||||
|
|
||||||
def giteaUser = findProperty("giteaUser") ?: ""
|
def giteaUser = findProperty("giteaUser") ?: ""
|
||||||
def giteaToken = findProperty("giteaToken") ?: ""
|
def giteaToken = findProperty("giteaToken") ?: ""
|
||||||
publishing {
|
publishing {
|
||||||
publications {
|
publications {
|
||||||
|
|||||||
@@ -10,4 +10,5 @@ import org.springframework.context.annotation.Import;
|
|||||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
||||||
@Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록
|
@Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록
|
||||||
public class ApiKeyAdminAutoConfiguration {
|
public class ApiKeyAdminAutoConfiguration {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package com.kri.common.auth.apikey;
|
|||||||
|
|
||||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
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.bind.annotation.RestController;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/internal/apikey")
|
@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 {
|
public class ApiKeyAdminController {
|
||||||
private final ApiKeyProperties props;
|
|
||||||
private final PreloadedApiKeyUserClaimsProvider provider;
|
|
||||||
private final List<IpAddressMatcher> allow;
|
|
||||||
|
|
||||||
public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) {
|
private final ApiKeyProperties props;
|
||||||
this.props = props;
|
private final PreloadedApiKeyUserClaimsProvider provider;
|
||||||
this.provider = provider;
|
private final List<IpAddressMatcher> allow;
|
||||||
this.allow = props.getAdminAllowIps().stream().map(IpAddressMatcher::new).toList();
|
|
||||||
|
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<CachedKeyView> cache(HttpServletRequest req) {
|
||||||
|
assertAllowed(req);
|
||||||
|
Map<String, JwtUserClaimsDto> 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);
|
||||||
}
|
}
|
||||||
|
String remote = req.getRemoteAddr();
|
||||||
@PostMapping("/reload")
|
boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
|
||||||
public ReloadResult reload(HttpServletRequest req) {
|
if (!ok) {
|
||||||
assertAllowed(req);
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
||||||
int count = provider.reloadFromDb();
|
|
||||||
return new ReloadResult(count);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 현재 캐시 상태(키는 마스킹) */
|
private String mask(String raw) {
|
||||||
@GetMapping("/cache")
|
if (raw == null) {
|
||||||
public List<CachedKeyView> cache(HttpServletRequest req) {
|
return "";
|
||||||
assertAllowed(req);
|
|
||||||
Map<String, JwtUserClaimsDto> snap = provider.snapshot();
|
|
||||||
return snap.entrySet().stream()
|
|
||||||
.map(e -> new CachedKeyView(mask(e.getKey()), e.getValue()))
|
|
||||||
.toList();
|
|
||||||
}
|
}
|
||||||
|
int n = raw.length();
|
||||||
private void assertAllowed(HttpServletRequest req) {
|
if (n <= 8) {
|
||||||
if (!props.isAdminApiEnabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
return raw.charAt(0) + "****";
|
||||||
String remote = req.getRemoteAddr();
|
|
||||||
boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
|
|
||||||
if (!ok) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
|
||||||
}
|
}
|
||||||
|
return raw.substring(0, 4) + "****" + raw.substring(n - 4);
|
||||||
|
}
|
||||||
|
|
||||||
private String mask(String raw) {
|
public record ReloadResult(int cachedKeyCount) {
|
||||||
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 CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {}
|
|
||||||
|
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,54 +5,52 @@ import jakarta.servlet.FilterChain;
|
|||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터.
|
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. -
|
||||||
* - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임.
|
* 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
|
||||||
* - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
|
|
||||||
*/
|
*/
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ApiKeyAuthFilter extends OncePerRequestFilter {
|
public class ApiKeyAuthFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
private final ApiKeyProperties apiKeyProperties;
|
private final ApiKeyProperties apiKeyProperties;
|
||||||
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
|
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doFilterInternal(HttpServletRequest request,
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
FilterChain filterChain)
|
FilterChain filterChain)
|
||||||
throws ServletException, IOException {
|
throws ServletException, IOException {
|
||||||
|
|
||||||
// API Key 기능이 꺼져 있으면 아무 것도 안 함
|
// API Key 기능이 꺼져 있으면 아무 것도 안 함
|
||||||
if (!apiKeyProperties.isEnabled()) {
|
if (!apiKeyProperties.isEnabled()) {
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
return;
|
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 이미 다른 방식(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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,9 @@ package com.kri.common.auth.apikey;
|
|||||||
|
|
||||||
import com.zaxxer.hikari.HikariDataSource;
|
import com.zaxxer.hikari.HikariDataSource;
|
||||||
import jakarta.persistence.EntityManagerFactory;
|
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.ObjectProvider;
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||||
import org.springframework.transaction.PlatformTransactionManager;
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* @Primary 절대 금지
|
* @Primary 절대 금지
|
||||||
* 메인 JPA와 완전히 분리
|
* 메인 JPA와 완전히 분리
|
||||||
*/
|
*/
|
||||||
@AutoConfiguration(
|
@AutoConfiguration(
|
||||||
afterName = {
|
afterName = {
|
||||||
// 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고,
|
// 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고,
|
||||||
// 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함.
|
// 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함.
|
||||||
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration",
|
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration",
|
||||||
"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration"
|
"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration"
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@ConditionalOnClass(name = {
|
@ConditionalOnClass(name = {
|
||||||
"org.springframework.data.jpa.repository.JpaRepository",
|
"org.springframework.data.jpa.repository.JpaRepository",
|
||||||
"jakarta.persistence.EntityManagerFactory",
|
"jakarta.persistence.EntityManagerFactory",
|
||||||
"com.zaxxer.hikari.HikariDataSource"
|
"com.zaxxer.hikari.HikariDataSource"
|
||||||
})
|
})
|
||||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
||||||
@EnableJpaRepositories(
|
@EnableJpaRepositories(
|
||||||
basePackages = "com.kri.common.auth.persistence.repository",
|
basePackages = "com.kri.common.auth.persistence.repository",
|
||||||
entityManagerFactoryRef = "apiKeyEntityManagerFactory",
|
entityManagerFactoryRef = "apiKeyEntityManagerFactory",
|
||||||
transactionManagerRef = "apiKeyTransactionManager"
|
transactionManagerRef = "apiKeyTransactionManager"
|
||||||
)
|
)
|
||||||
@EnableConfigurationProperties(ApiKeyProperties.class)
|
@EnableConfigurationProperties(ApiKeyProperties.class)
|
||||||
public class ApiKeyJpaAutoConfiguration {
|
public class ApiKeyJpaAutoConfiguration {
|
||||||
|
|
||||||
@Bean(name = "apiKeyDataSource")
|
@Bean(name = "apiKeyDataSource")
|
||||||
public DataSource apiKeyDataSource(ApiKeyProperties props) {
|
public DataSource apiKeyDataSource(ApiKeyProperties props) {
|
||||||
var db = props.getDb();
|
var db = props.getDb();
|
||||||
HikariDataSource ds = new HikariDataSource();
|
HikariDataSource ds = new HikariDataSource();
|
||||||
ds.setJdbcUrl(db.getUrl());
|
ds.setJdbcUrl(db.getUrl());
|
||||||
ds.setUsername(db.getUsername());
|
ds.setUsername(db.getUsername());
|
||||||
ds.setPassword(db.getPassword());
|
ds.setPassword(db.getPassword());
|
||||||
ds.setDriverClassName(db.getDriverClassName());
|
ds.setDriverClassName(db.getDriverClassName());
|
||||||
return ds;
|
return ds;
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식
|
|
||||||
* - intranet-extension처럼 HibernateJpaAutoConfiguration을 exclude 해도 동작
|
|
||||||
*/
|
|
||||||
@Bean(name = "apiKeyEntityManagerFactory")
|
|
||||||
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
|
|
||||||
@Qualifier("apiKeyDataSource") DataSource ds,
|
|
||||||
ObjectProvider<PersistenceUnitManager> pumProvider,
|
|
||||||
ApiKeyProperties props
|
|
||||||
) {
|
|
||||||
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
|
||||||
vendorAdapter.setShowSql(props.getJpa().isShowSql());
|
|
||||||
vendorAdapter.setGenerateDdl(false);
|
|
||||||
|
|
||||||
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
/**
|
||||||
emf.setDataSource(ds);
|
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - intranet-extension처럼 HibernateJpaAutoConfiguration을
|
||||||
emf.setJpaVendorAdapter(vendorAdapter);
|
* exclude 해도 동작
|
||||||
emf.setPackagesToScan("com.kri.common.auth.persistence.entity");
|
*/
|
||||||
emf.setPersistenceUnitName("apikey");
|
@Bean(name = "apiKeyEntityManagerFactory")
|
||||||
|
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
|
||||||
|
@Qualifier("apiKeyDataSource") DataSource ds,
|
||||||
|
ObjectProvider<PersistenceUnitManager> pumProvider,
|
||||||
|
ApiKeyProperties props
|
||||||
|
) {
|
||||||
|
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||||
|
vendorAdapter.setShowSql(props.getJpa().isShowSql());
|
||||||
|
vendorAdapter.setGenerateDdl(false);
|
||||||
|
|
||||||
PersistenceUnitManager pum = pumProvider.getIfAvailable();
|
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||||
if (pum != null) {
|
emf.setDataSource(ds);
|
||||||
emf.setPersistenceUnitManager(pum);
|
emf.setJpaVendorAdapter(vendorAdapter);
|
||||||
}
|
emf.setPackagesToScan("com.kri.common.auth.persistence.entity");
|
||||||
|
emf.setPersistenceUnitName("apikey");
|
||||||
|
|
||||||
// 최소 JPA 속성들 (원하면 yml로 확장 가능)
|
PersistenceUnitManager pum = pumProvider.getIfAvailable();
|
||||||
Map<String, Object> jpaProps = new HashMap<>();
|
if (pum != null) {
|
||||||
jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql()));
|
emf.setPersistenceUnitManager(pum);
|
||||||
jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql()));
|
|
||||||
|
|
||||||
emf.setJpaPropertyMap(jpaProps);
|
|
||||||
return emf;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean(name = "apiKeyTransactionManager")
|
// 최소 JPA 속성들 (원하면 yml로 확장 가능)
|
||||||
public PlatformTransactionManager apiKeyTransactionManager(
|
Map<String, Object> jpaProps = new HashMap<>();
|
||||||
@Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf
|
jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql()));
|
||||||
) {
|
jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql()));
|
||||||
return new JpaTransactionManager(emf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
emf.setJpaPropertyMap(jpaProps);
|
||||||
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서
|
return emf;
|
||||||
* 'jpaMappingContext'가 없을 때만 보완해준다.
|
}
|
||||||
*
|
|
||||||
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
|
@Bean(name = "apiKeyTransactionManager")
|
||||||
*/
|
public PlatformTransactionManager apiKeyTransactionManager(
|
||||||
@Bean(name = "jpaMappingContext")
|
@Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf
|
||||||
@ConditionalOnMissingBean(name = "jpaMappingContext")
|
) {
|
||||||
public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) {
|
return new JpaTransactionManager(emf);
|
||||||
// FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함
|
}
|
||||||
return new JpaMetamodelMappingContextFactoryBean();
|
|
||||||
}
|
/**
|
||||||
|
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 'jpaMappingContext'가 없을 때만 보완해준다.
|
||||||
|
* <p>
|
||||||
|
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
|
||||||
|
*/
|
||||||
|
@Bean(name = "jpaMappingContext")
|
||||||
|
@ConditionalOnMissingBean(name = "jpaMappingContext")
|
||||||
|
public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) {
|
||||||
|
// FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함
|
||||||
|
return new JpaMetamodelMappingContextFactoryBean();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ import org.springframework.context.annotation.Bean;
|
|||||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
||||||
public class ApiKeyPreloadAutoConfiguration {
|
public class ApiKeyPreloadAutoConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만
|
@ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만
|
||||||
@ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class)
|
@ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class)
|
||||||
public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider(
|
public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider(
|
||||||
ApiKeyProperties props,
|
ApiKeyProperties props,
|
||||||
ApiKeyRepository repo
|
ApiKeyRepository repo
|
||||||
) {
|
) {
|
||||||
return new PreloadedApiKeyUserClaimsProvider(props, repo);
|
return new PreloadedApiKeyUserClaimsProvider(props, repo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +1,80 @@
|
|||||||
package com.kri.common.auth.apikey;
|
package com.kri.common.auth.apikey;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@ConfigurationProperties(prefix = "kri.auth.apikey")
|
@ConfigurationProperties(prefix = "kri.auth.apikey")
|
||||||
public class ApiKeyProperties {
|
public class ApiKeyProperties {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* API Key 인증 허용 여부
|
* API Key 인증 허용 여부
|
||||||
*/
|
*/
|
||||||
private boolean enabled = false;
|
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<String> 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 를 읽어올 헤더 이름
|
* hibernate.show_sql
|
||||||
* 예: X-API-Key, X-EXTERNAL-KEY 등
|
|
||||||
*/
|
*/
|
||||||
private String headerName = "X-API-Key";
|
private boolean showSql = false;
|
||||||
|
|
||||||
/** 이 서비스의 코드 (서비스별 preload 범위 결정) */
|
/**
|
||||||
private String serviceCode;
|
* hibernate.format_sql
|
||||||
|
*/
|
||||||
/** 기동 시 preload 할지 */
|
private boolean formatSql = false;
|
||||||
private boolean preloadOnStartup = false;
|
}
|
||||||
|
|
||||||
/** 내부 관리 API(리로드/조회) 노출 여부 */
|
|
||||||
private boolean adminApiEnabled = false;
|
|
||||||
|
|
||||||
/** 내부 관리 API 접근 허용 IP(CIDR) */
|
|
||||||
private List<String> 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Getter @Setter
|
@Getter
|
||||||
public static class Db {
|
@Setter
|
||||||
//내부 통신용 url
|
public static class Db {
|
||||||
private String url =
|
|
||||||
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
|
//내부 통신용 url
|
||||||
private String username = "kriit";
|
private String url =
|
||||||
private String password = "it#51304";
|
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
|
||||||
private String driverClassName = "com.mysql.cj.jdbc.Driver";
|
private String username = "kriit";
|
||||||
}
|
private String password = "it#51304";
|
||||||
|
private String driverClassName = "com.mysql.cj.jdbc.Driver";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,16 +4,16 @@ import com.kri.common.auth.dto.JwtUserClaimsDto;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스.
|
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면
|
||||||
* 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다.
|
* 된다.
|
||||||
*/
|
*/
|
||||||
public interface ApiKeyUserClaimsProvider {
|
public interface ApiKeyUserClaimsProvider {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* API Key 로 사용자 정보를 조회한다.
|
* API Key 로 사용자 정보를 조회한다.
|
||||||
*
|
*
|
||||||
* @param apiKey 요청 헤더에서 받은 API Key
|
* @param apiKey 요청 헤더에서 받은 API Key
|
||||||
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
|
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
|
||||||
*/
|
*/
|
||||||
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
||||||
}
|
}
|
||||||
@@ -3,73 +3,89 @@ package com.kri.common.auth.apikey;
|
|||||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||||
import com.kri.common.auth.persistence.repository.ApiKeyRepository;
|
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.Collections;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
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 ApiKeyProperties props;
|
||||||
private final ApiKeyRepository repo;
|
private final ApiKeyRepository repo;
|
||||||
|
|
||||||
/** 캐시를 통째로 교체(swap)하기 위한 AtomicReference */
|
/**
|
||||||
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
|
* 캐시를 통째로 교체(swap)하기 위한 AtomicReference
|
||||||
new AtomicReference<>(Collections.emptyMap());
|
*/
|
||||||
|
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
|
||||||
|
new AtomicReference<>(Collections.emptyMap());
|
||||||
|
|
||||||
public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) {
|
public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) {
|
||||||
this.props = props;
|
this.props = props;
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 런타임에는 DB 조회 금지: 캐시만 조회
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Optional<JwtUserClaimsDto> 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 조회 금지: 캐시만 조회 */
|
var list = repo.findActiveKeysForService(props.getServiceCode());
|
||||||
@Override
|
|
||||||
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
Map<String, JwtUserClaimsDto> next = new ConcurrentHashMap<>(Math.max(16, list.size()));
|
||||||
if (!StringUtils.hasText(apiKey)) return Optional.empty();
|
for (TApiKeyEntity e : list) {
|
||||||
return Optional.ofNullable(cacheRef.get().get(apiKey));
|
next.put(e.getApiKey(), JwtUserClaimsDto.builder()
|
||||||
|
.userId(e.getUserId())
|
||||||
|
.userCmpn(e.getUserCmpn())
|
||||||
|
.userTeam(e.getUserTeam())
|
||||||
|
.userName(e.getUserName())
|
||||||
|
.userRole(e.getUserRole())
|
||||||
|
.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 기동 시 preload */
|
cacheRef.set(Collections.unmodifiableMap(next));
|
||||||
@Override
|
return next.size();
|
||||||
public void run(ApplicationArguments args) {
|
}
|
||||||
if (!props.isEnabled()) return;
|
|
||||||
if (!props.isPreloadOnStartup()) return;
|
|
||||||
reloadFromDb();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 운영용: DB에서 다시 읽어 캐시 전체 교체 */
|
/**
|
||||||
public synchronized int reloadFromDb() {
|
* Admin 조회용(마스킹은 컨트롤러에서)
|
||||||
if (!StringUtils.hasText(props.getServiceCode())) {
|
*/
|
||||||
// serviceCode 없으면 preload 불가 → 안전하게 빈 캐시
|
public Map<String, JwtUserClaimsDto> snapshot() {
|
||||||
cacheRef.set(Collections.emptyMap());
|
return cacheRef.get();
|
||||||
return 0;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
var list = repo.findActiveKeysForService(props.getServiceCode());
|
|
||||||
|
|
||||||
Map<String, JwtUserClaimsDto> 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<String, JwtUserClaimsDto> snapshot() {
|
|
||||||
return cacheRef.get();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,25 +5,25 @@ import lombok.Builder;
|
|||||||
import lombok.Value;
|
import lombok.Value;
|
||||||
|
|
||||||
@Schema(
|
@Schema(
|
||||||
name = "JwtUserClaimsDto",
|
name = "JwtUserClaimsDto",
|
||||||
description = "JWT에 포함되는 사용자 정보"
|
description = "JWT에 포함되는 사용자 정보"
|
||||||
)
|
)
|
||||||
@Value
|
@Value
|
||||||
@Builder
|
@Builder
|
||||||
public class JwtUserClaimsDto {
|
public class JwtUserClaimsDto {
|
||||||
|
|
||||||
@Schema(description = "사용자 ID")
|
@Schema(description = "사용자 ID")
|
||||||
String userId;
|
String userId;
|
||||||
|
|
||||||
@Schema(description = "사용자 소속 회사")
|
@Schema(description = "사용자 소속 회사")
|
||||||
String userCmpn;
|
String userCmpn;
|
||||||
|
|
||||||
@Schema(description = "팀 코드")
|
@Schema(description = "팀 코드")
|
||||||
String userTeam;
|
String userTeam;
|
||||||
|
|
||||||
@Schema(description = "사용자 이름")
|
@Schema(description = "사용자 이름")
|
||||||
String userName;
|
String userName;
|
||||||
|
|
||||||
@Schema(description = "권한 코드")
|
@Schema(description = "권한 코드")
|
||||||
Integer userRole;
|
Integer userRole;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,22 +13,22 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
@EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class})
|
@EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class})
|
||||||
public class JwtAutoConfiguration {
|
public class JwtAutoConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public JwtService jwtService(JwtProperties properties) {
|
public JwtService jwtService(JwtProperties properties) {
|
||||||
return new JwtService(properties);
|
return new JwtService(properties);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성.
|
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서
|
||||||
* (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행)
|
* addFilterBefore 로 수행)
|
||||||
*/
|
*/
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
|
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties,
|
public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties,
|
||||||
ApiKeyUserClaimsProvider provider,
|
ApiKeyUserClaimsProvider provider,
|
||||||
JwtService jwtService) {
|
JwtService jwtService) {
|
||||||
return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService);
|
return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package com.kri.common.auth.jwt;
|
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;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -10,23 +13,23 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
|||||||
@ConfigurationProperties(prefix = "kri.auth.jwt")
|
@ConfigurationProperties(prefix = "kri.auth.jwt")
|
||||||
public class JwtProperties {
|
public class JwtProperties {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장)
|
* HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장)
|
||||||
*/
|
*/
|
||||||
private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M";
|
private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 토큰 발급자(issuer)
|
* 토큰 발급자(issuer)
|
||||||
*/
|
*/
|
||||||
private String issuer = "kri-it";
|
private String issuer = "kri-it";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Access Token 유효 시간(초 단위)
|
* Access Token 유효 시간(초 단위)
|
||||||
*/
|
*/
|
||||||
private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간
|
private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* (선택) Refresh Token 유효 시간(초 단위)
|
* (선택) Refresh Token 유효 시간(초 단위)
|
||||||
*/
|
*/
|
||||||
private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일
|
private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,189 +1,192 @@
|
|||||||
package com.kri.common.auth.jwt;
|
package com.kri.common.auth.jwt;
|
||||||
|
|
||||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
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 io.jsonwebtoken.security.Keys;
|
||||||
import jakarta.annotation.PostConstruct;
|
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 lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 공통 JWT 유틸 서비스
|
* 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원
|
||||||
* - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱
|
|
||||||
* - 일반 JWT + 내부 고정 토큰 둘 다 지원
|
|
||||||
*/
|
*/
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class JwtService {
|
public class JwtService {
|
||||||
|
|
||||||
private final JwtProperties properties;
|
private final JwtProperties properties;
|
||||||
|
|
||||||
private SecretKey key;
|
private SecretKey key;
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void init() {
|
public void init() {
|
||||||
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
|
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
|
||||||
String secret = properties.getSecret();
|
String secret = properties.getSecret();
|
||||||
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
|
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");
|
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));
|
// secret 문자열을 HMAC 키로 전환
|
||||||
|
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ======================================================
|
||||||
|
// 내부 공통 빌더
|
||||||
|
// ======================================================
|
||||||
|
|
||||||
|
private String buildToken(Map<String, Object> claims, String subject, long validitySeconds) {
|
||||||
|
Date now = new Date();
|
||||||
|
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
|
||||||
|
|
||||||
|
return Jwts.builder()
|
||||||
|
.setClaims(claims)
|
||||||
|
.setSubject(subject)
|
||||||
|
.setIssuer(properties.getIssuer())
|
||||||
|
.setIssuedAt(now)
|
||||||
|
.setExpiration(expiry)
|
||||||
|
.signWith(key, SignatureAlgorithm.HS256)
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
|
||||||
|
Map<String, Object> claims = new HashMap<>();
|
||||||
|
// 필요한 항목만 골라서 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<String, Object> 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<Claims> 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<String, Object> claims, String subject, long validitySeconds) {
|
// 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue()
|
||||||
Date now = new Date();
|
Number roleNumber = claims.get("role", Number.class);
|
||||||
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
|
Integer userRole = roleNumber != null ? roleNumber.intValue() : null;
|
||||||
|
|
||||||
return Jwts.builder()
|
return JwtUserClaimsDto.builder()
|
||||||
.setClaims(claims)
|
.userId(userId)
|
||||||
.setSubject(subject)
|
.userCmpn(userCmpn)
|
||||||
.setIssuer(properties.getIssuer())
|
.userTeam(userTeam)
|
||||||
.setIssuedAt(now)
|
.userName(userName)
|
||||||
.setExpiration(expiry)
|
.userRole(userRole)
|
||||||
.signWith(key, SignatureAlgorithm.HS256)
|
.build();
|
||||||
.compact();
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 토큰 → 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<GrantedAuthority> authorities = new ArrayList<>();
|
||||||
|
if (dto.getUserRole() != null) {
|
||||||
|
String authority = "ROLE_" + dto.getUserRole();
|
||||||
|
authorities.add(new SimpleGrantedAuthority(authority));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
|
return new UsernamePasswordAuthenticationToken(
|
||||||
Map<String, Object> claims = new HashMap<>();
|
principal,
|
||||||
// 필요한 항목만 골라서 claim에 넣어줌
|
null,
|
||||||
claims.put("userId", dto.getUserId());
|
authorities
|
||||||
claims.put("userCmpn", dto.getUserCmpn());
|
);
|
||||||
claims.put("userTeam", dto.getUserTeam());
|
}
|
||||||
claims.put("userName", dto.getUserName());
|
|
||||||
claims.put("role", dto.getUserRole());
|
|
||||||
return claims;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ======================================================
|
/**
|
||||||
// 토큰 생성 (DTO 기반)
|
* 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에)
|
||||||
// ======================================================
|
*/
|
||||||
/**
|
public Authentication toAuthentication(String token) throws JwtException {
|
||||||
* JwtUserClaimsDto 기반 Access Token 생성
|
JwtUserClaimsDto dto = toUserClaimsDto(token);
|
||||||
* - subject = userId
|
return toAuthentication(dto);
|
||||||
* - claims:
|
}
|
||||||
* userId, userCmpn, userTeam, userName, role
|
|
||||||
*/
|
|
||||||
public String generateAccessToken(JwtUserClaimsDto userClaims) {
|
|
||||||
Map<String, Object> 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<Claims> 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<GrantedAuthority> 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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,54 +1,59 @@
|
|||||||
package com.kri.common.auth.persistence.entity;
|
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.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
import org.hibernate.annotations.JdbcTypeCode;
|
import org.hibernate.annotations.JdbcTypeCode;
|
||||||
import org.hibernate.type.SqlTypes;
|
import org.hibernate.type.SqlTypes;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "t_api_key")
|
@Table(name = "t_api_key")
|
||||||
public class TApiKeyEntity {
|
public class TApiKeyEntity {
|
||||||
@Id
|
|
||||||
@Column(name = "api_key", nullable = false, length = 256)
|
|
||||||
private String apiKey;
|
|
||||||
|
|
||||||
/** 1=ACTIVE, 0=REVOKED */
|
@Id
|
||||||
@Column(name = "status", nullable = false)
|
@Column(name = "api_key", nullable = false, length = 256)
|
||||||
@ColumnDefault("1")
|
private String apiKey;
|
||||||
private Short status;
|
|
||||||
|
|
||||||
@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)
|
@Column(name = "user_id", nullable = false, length = 32)
|
||||||
private String userCmpn;
|
private String userId;
|
||||||
|
|
||||||
@Column(name = "user_team", length = 64)
|
@Column(name = "user_cmpn", length = 64)
|
||||||
private String userTeam;
|
private String userCmpn;
|
||||||
|
|
||||||
@Column(name = "user_name", length = 64)
|
@Column(name = "user_team", length = 64)
|
||||||
private String userName;
|
private String userTeam;
|
||||||
|
|
||||||
@Column(name = "user_role", nullable = false)
|
@Column(name = "user_name", length = 64)
|
||||||
private Integer userRole;
|
private String userName;
|
||||||
|
|
||||||
/*기본 정보 외*/
|
@Column(name = "user_role", nullable = false)
|
||||||
@Column(name = "user_json")
|
private Integer userRole;
|
||||||
@JdbcTypeCode(SqlTypes.JSON)
|
|
||||||
private Map<String, Object> userJson;
|
|
||||||
|
|
||||||
@Column(name = "reg_user", nullable = false, length = 32)
|
/*기본 정보 외*/
|
||||||
private String regUser;
|
@Column(name = "user_json")
|
||||||
|
@JdbcTypeCode(SqlTypes.JSON)
|
||||||
|
private Map<String, Object> userJson;
|
||||||
|
|
||||||
@Column(name = "reg_dt", nullable = false)
|
@Column(name = "reg_user", nullable = false, length = 32)
|
||||||
@ColumnDefault("CURRENT_TIMESTAMP")
|
private String regUser;
|
||||||
private LocalDateTime regDt;
|
|
||||||
|
@Column(name = "reg_dt", nullable = false)
|
||||||
|
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||||
|
private LocalDateTime regDt;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,15 @@ import lombok.Setter;
|
|||||||
@Entity
|
@Entity
|
||||||
@Table(name = "t_api_key_service_map")
|
@Table(name = "t_api_key_service_map")
|
||||||
public class TApiKeyServiceMapEntity {
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,36 +3,40 @@ package com.kri.common.auth.persistence.entity;
|
|||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Embeddable;
|
import jakarta.persistence.Embeddable;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Objects;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.hibernate.Hibernate;
|
import org.hibernate.Hibernate;
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@Embeddable
|
@Embeddable
|
||||||
public class TApiKeyServiceMapEntityId implements Serializable {
|
public class TApiKeyServiceMapEntityId implements Serializable {
|
||||||
@NotNull
|
|
||||||
@Column(name = "api_key", nullable = false, length = 256)
|
|
||||||
private String apiKey;
|
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Column(name = "service_code", nullable = false, length = 64)
|
@Column(name = "api_key", nullable = false, length = 256)
|
||||||
private String serviceCode;
|
private String apiKey;
|
||||||
|
|
||||||
@Override
|
@NotNull
|
||||||
public boolean equals(Object o) {
|
@Column(name = "service_code", nullable = false, length = 64)
|
||||||
if (this == o) return true;
|
private String serviceCode;
|
||||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
|
||||||
TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o;
|
@Override
|
||||||
return Objects.equals(this.apiKey, entity.apiKey) &&
|
public boolean equals(Object o) {
|
||||||
Objects.equals(this.serviceCode, entity.serviceCode);
|
if (this == o) {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
|
||||||
@Override
|
return false;
|
||||||
public int hashCode() {
|
|
||||||
return Objects.hash(apiKey, serviceCode);
|
|
||||||
}
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,21 @@
|
|||||||
package com.kri.common.auth.persistence.repository;
|
package com.kri.common.auth.persistence.repository;
|
||||||
|
|
||||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> {
|
public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> {
|
||||||
/** ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 */
|
|
||||||
@Query("""
|
/**
|
||||||
select a
|
* ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에
|
||||||
from TApiKeyEntity a
|
*/
|
||||||
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
|
@Query("""
|
||||||
where a.status = 1 and m.id.serviceCode = :serviceCode
|
select a
|
||||||
""")
|
from TApiKeyEntity a
|
||||||
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode")String serviceCode);
|
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
|
||||||
|
where a.status = 1 and m.id.serviceCode = :serviceCode
|
||||||
|
""")
|
||||||
|
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode") String serviceCode);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,115 +1,120 @@
|
|||||||
package com.kri.common.cache;
|
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.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
public abstract class AbstractListCache<T> {
|
public abstract class AbstractListCache<T> {
|
||||||
|
|
||||||
private List<T> list = List.of();
|
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
private List<T> list = List.of();
|
||||||
|
|
||||||
@EventListener(ApplicationReadyEvent.class)
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public void loadOnStartup() {
|
public void loadOnStartup() {
|
||||||
List<T> tempList = loadFromDb();
|
List<T> tempList = loadFromDb();
|
||||||
if(tempList != null) setList(tempList);
|
if (tempList != null) {
|
||||||
|
setList(tempList);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<T> getList() {
|
||||||
|
lock.readLock().lock();
|
||||||
|
try {
|
||||||
|
return list;
|
||||||
|
} finally {
|
||||||
|
lock.readLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setList(List<T> next) {
|
||||||
|
lock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
this.list = List.copyOf(next == null ? List.of() : next);
|
||||||
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<T> reload() {
|
||||||
|
List<T> tempList = loadFromDb();
|
||||||
|
if (tempList == null) {
|
||||||
|
throw new UnsupportedOperationException("This cache does not support reload().");
|
||||||
|
}
|
||||||
|
setList(tempList);
|
||||||
|
return getList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<T> clear() {
|
||||||
|
lock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
return list = List.of();
|
||||||
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addAll(List<T> items) {
|
||||||
|
if (items == null || items.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||||
|
merged.addAll(items);
|
||||||
|
this.list = List.copyOf(merged);
|
||||||
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addAll(int index, Collection<? extends T> items) {
|
||||||
|
if (items == null || items.isEmpty()) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<T> getList() {
|
lock.writeLock().lock();
|
||||||
lock.readLock().lock();
|
try {
|
||||||
try {
|
ArrayList<T> next = new ArrayList<>(this.list);
|
||||||
return list;
|
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
||||||
} finally {
|
next.addAll(i, new ArrayList<>(items));
|
||||||
lock.readLock().unlock();
|
this.list = List.copyOf(next);
|
||||||
}
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
public void add(T item) {
|
||||||
public List<T> reload() {
|
lock.writeLock().lock();
|
||||||
List<T> tempList = loadFromDb();
|
try {
|
||||||
if(tempList == null) {
|
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||||
throw new UnsupportedOperationException("This cache does not support reload().");
|
merged.add(item);
|
||||||
}
|
this.list = List.copyOf(merged);
|
||||||
setList(tempList);
|
} finally {
|
||||||
return getList();
|
lock.writeLock().unlock();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public List<T> clear() {
|
public void add(int index, T item) {
|
||||||
lock.writeLock().lock();
|
lock.writeLock().lock();
|
||||||
try{
|
|
||||||
return list = List.of();
|
try {
|
||||||
} finally {
|
ArrayList<T> next = new ArrayList<>(this.list);
|
||||||
lock.writeLock().unlock();
|
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<T> next) {
|
protected List<T> loadFromDb() {
|
||||||
lock.writeLock().lock();
|
return null;
|
||||||
try {
|
}
|
||||||
this.list = List.copyOf(next == null ? List.of() : next);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addAll(List<T> items) {
|
|
||||||
if (items == null || items.isEmpty()) return;
|
|
||||||
lock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
|
||||||
merged.addAll(items);
|
|
||||||
this.list = List.copyOf(merged);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addAll(int index, Collection<? extends T> items) {
|
|
||||||
if (items == null || items.isEmpty()) return;
|
|
||||||
|
|
||||||
lock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
ArrayList<T> next = new ArrayList<>(this.list);
|
|
||||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
|
||||||
next.addAll(i, new ArrayList<>(items));
|
|
||||||
this.list = List.copyOf(next);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void add(T item) {
|
|
||||||
lock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
|
||||||
merged.add(item);
|
|
||||||
this.list = List.copyOf(merged);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void add(int index, T item){
|
|
||||||
lock.writeLock().lock();
|
|
||||||
|
|
||||||
try{
|
|
||||||
ArrayList<T> next = new ArrayList<>(this.list);
|
|
||||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
|
||||||
next.add(i, item);
|
|
||||||
this.list = List.copyOf(next);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected List<T> loadFromDb() {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,110 +1,119 @@
|
|||||||
package com.kri.common.cache;
|
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.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
public abstract class AbstractMapCache<K, V> {
|
public abstract class AbstractMapCache<K, V> {
|
||||||
|
|
||||||
private Map<K, V> map = Map.of();
|
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
private Map<K, V> map = Map.of();
|
||||||
|
|
||||||
@EventListener(ApplicationReadyEvent.class)
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public void loadOnStartup() {
|
public void loadOnStartup() {
|
||||||
Map<K, V> tempMap = loadFromDb();
|
Map<K, V> tempMap = loadFromDb();
|
||||||
if(tempMap != null) setMap(tempMap);
|
if (tempMap != null) {
|
||||||
|
setMap(tempMap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<K, V> getMap() {
|
||||||
|
lock.readLock().lock();
|
||||||
|
try {
|
||||||
|
return map;
|
||||||
|
} finally {
|
||||||
|
lock.readLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 수동: 전체 교체(불변 스냅샷으로 보관)
|
||||||
|
*/
|
||||||
|
public void setMap(Map<K, V> next) {
|
||||||
|
lock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
this.map = Map.copyOf(next == null ? Map.of() : next);
|
||||||
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public V get(K key) {
|
||||||
|
lock.readLock().lock();
|
||||||
|
try {
|
||||||
|
return map.get(key);
|
||||||
|
} finally {
|
||||||
|
lock.readLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean containsKey(K key) {
|
||||||
|
lock.readLock().lock();
|
||||||
|
try {
|
||||||
|
return map.containsKey(key);
|
||||||
|
} finally {
|
||||||
|
lock.readLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Map<K, V> reload() {
|
||||||
|
Map<K, V> tempMap = loadFromDb();
|
||||||
|
if (tempMap == null) {
|
||||||
|
throw new UnsupportedOperationException("This cache does not support reload().");
|
||||||
|
}
|
||||||
|
setMap(tempMap);
|
||||||
|
return getMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void put(K key, V value) {
|
||||||
|
lock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
Map<K, V> merged = new HashMap<>(this.map);
|
||||||
|
merged.put(key, value);
|
||||||
|
this.map = Map.copyOf(merged);
|
||||||
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체)
|
||||||
|
*/
|
||||||
|
public void putAll(Map<K, V> entries) {
|
||||||
|
if (entries == null || entries.isEmpty()) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<K, V> getMap() {
|
lock.writeLock().lock();
|
||||||
lock.readLock().lock();
|
try {
|
||||||
try {
|
Map<K, V> merged = new HashMap<>(this.map);
|
||||||
return map;
|
merged.putAll(entries);
|
||||||
} finally {
|
this.map = Map.copyOf(merged);
|
||||||
lock.readLock().unlock();
|
} finally {
|
||||||
}
|
lock.writeLock().unlock();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public V get(K key) {
|
/**
|
||||||
lock.readLock().lock();
|
* clear: 완전 비우기
|
||||||
try {
|
*/
|
||||||
return map.get(key);
|
public void clear() {
|
||||||
} finally {
|
lock.writeLock().lock();
|
||||||
lock.readLock().unlock();
|
try {
|
||||||
}
|
this.map = Map.of();
|
||||||
|
} finally {
|
||||||
|
lock.writeLock().unlock();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public boolean containsKey(K key) {
|
// 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현
|
||||||
lock.readLock().lock();
|
protected Map<K, V> loadFromDb() {
|
||||||
try {
|
return null;
|
||||||
return map.containsKey(key);
|
}
|
||||||
} finally {
|
|
||||||
lock.readLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Map<K, V> reload() {
|
|
||||||
Map<K, V> tempMap = loadFromDb();
|
|
||||||
if(tempMap == null) {
|
|
||||||
throw new UnsupportedOperationException("This cache does not support reload().");
|
|
||||||
}
|
|
||||||
setMap(tempMap);
|
|
||||||
return getMap();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 수동: 전체 교체(불변 스냅샷으로 보관) */
|
|
||||||
public void setMap(Map<K, V> 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<K, V> merged = new HashMap<>(this.map);
|
|
||||||
merged.put(key, value);
|
|
||||||
this.map = Map.copyOf(merged);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체) */
|
|
||||||
public void putAll(Map<K, V> entries) {
|
|
||||||
if (entries == null || entries.isEmpty()) return;
|
|
||||||
|
|
||||||
lock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
Map<K, V> merged = new HashMap<>(this.map);
|
|
||||||
merged.putAll(entries);
|
|
||||||
this.map = Map.copyOf(merged);
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** clear: 완전 비우기 */
|
|
||||||
public void clear() {
|
|
||||||
lock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
this.map = Map.of();
|
|
||||||
} finally {
|
|
||||||
lock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현
|
|
||||||
protected Map<K, V> loadFromDb() {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,186 +1,273 @@
|
|||||||
package com.kri.common.datetime;
|
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.DateTimeFormatter;
|
||||||
import java.time.format.DateTimeParseException;
|
import java.time.format.DateTimeParseException;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
public final class DateTimeUtil {
|
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");
|
private DateTimeUtil() {
|
||||||
public static final ZoneId UTC = ZoneOffset.UTC;
|
}
|
||||||
|
|
||||||
/** 날짜+시간: 2025-11-28 15:00:14 */
|
/* =======================
|
||||||
public static final DateTimeFormatter DATETIME_FMT =
|
* Now (KST)
|
||||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
* ======================= */
|
||||||
|
|
||||||
/** 날짜: 2025-11-28 */
|
/**
|
||||||
public static final DateTimeFormatter DATE_FMT =
|
* 현재 KST 날짜+시간 문자열
|
||||||
DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
*/
|
||||||
|
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() {
|
* 현재 KST ZonedDateTime
|
||||||
return formatKst(Instant.now(), DATETIME_FMT);
|
*/
|
||||||
|
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 날짜 문자열 */
|
final String s = text.trim();
|
||||||
public static String nowKstDate() {
|
try {
|
||||||
return nowKstZoned().format(DATE_FMT);
|
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 */
|
return false;
|
||||||
public static ZonedDateTime nowKstZoned() {
|
}
|
||||||
return Instant.now().atZone(KST);
|
|
||||||
|
/* =======================
|
||||||
|
* Parse (String -> Instant)
|
||||||
|
* ======================= */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도)
|
||||||
|
*/
|
||||||
|
public static Instant parseToInstant(String text) {
|
||||||
|
if (text == null || text.isBlank()) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 현재 KST LocalDateTime */
|
final String s = text.trim();
|
||||||
public static LocalDateTime nowKstLocalDateTime() {
|
try {
|
||||||
return nowKstZoned().toLocalDateTime();
|
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 */
|
throw new DateTimeParseException("Unsupported datetime format", s, 0);
|
||||||
public static LocalDate nowKstLocalDate() {
|
}
|
||||||
return nowKstZoned().toLocalDate();
|
|
||||||
|
/**
|
||||||
|
* 커스텀 포맷 문자열을 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);
|
||||||
* Format (Instant -> String)
|
return ldt.atZone(KST).toInstant();
|
||||||
* ======================= */
|
}
|
||||||
|
|
||||||
/** Instant -> KST 날짜+시간 문자열 */
|
/**
|
||||||
public static String formatKstDateTime(Instant instant) {
|
* "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석
|
||||||
return formatKst(instant, DATETIME_FMT);
|
*/
|
||||||
|
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) {
|
* Convert / Helpers
|
||||||
return formatKst(instant, DATE_FMT);
|
* ======================= */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 LocalDate parseLocalDate(String text) {
|
||||||
public static String formatKst(Instant instant, DateTimeFormatter formatter) {
|
return tryParseLocalDate(text, DATE_FMT);
|
||||||
if (instant == null) return null;
|
}
|
||||||
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
|
|
||||||
return instant.atZone(KST).format(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);
|
||||||
* Validate
|
} catch (DateTimeParseException e) {
|
||||||
* ======================= */
|
return null;
|
||||||
|
|
||||||
/** "yyyy-MM-dd" 형태인지 */
|
|
||||||
public static boolean isDate(String text) {
|
|
||||||
return tryParseLocalDate(text, DATE_FMT) != null;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** "yyyy-MM-dd HH:mm:ss" 형태인지 */
|
private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) {
|
||||||
public static boolean isDateTime(String text) {
|
if (text == null || text.isBlank()) {
|
||||||
return tryParseLocalDateTime(text, DATETIME_FMT) != null;
|
return null;
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
/** ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지 */
|
return LocalDateTime.parse(text.trim(), fmt);
|
||||||
public static boolean isIsoDateTime(String text) {
|
} catch (DateTimeParseException e) {
|
||||||
if (text == null || text.isBlank()) return false;
|
return null;
|
||||||
|
|
||||||
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; }
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,8 +2,11 @@ package com.kri.common.datetime;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
|
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import java.lang.annotation.Documented;
|
||||||
import java.lang.annotation.*;
|
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})
|
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@@ -12,12 +15,12 @@ import java.lang.annotation.*;
|
|||||||
@JsonDeserialize(using = LenientLocalDateTimeDeserializer.class)
|
@JsonDeserialize(using = LenientLocalDateTimeDeserializer.class)
|
||||||
public @interface LenientLocalDateTime {
|
public @interface LenientLocalDateTime {
|
||||||
|
|
||||||
String[] patterns() default {
|
String[] patterns() default {
|
||||||
"yyyy-MM-dd",
|
"yyyy-MM-dd",
|
||||||
"yyyy-MM-dd HH",
|
"yyyy-MM-dd HH",
|
||||||
"yyyy-MM-dd HH:mm",
|
"yyyy-MM-dd HH:mm",
|
||||||
"yyyy-MM-dd HH:mm:ss",
|
"yyyy-MM-dd HH:mm:ss",
|
||||||
"yyyy-MM-dd'T'HH:mm",
|
"yyyy-MM-dd'T'HH:mm",
|
||||||
"yyyy-MM-dd'T'HH:mm:ss"
|
"yyyy-MM-dd'T'HH:mm:ss"
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.DeserializationContext;
|
|||||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||||
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
|
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
@@ -16,72 +15,79 @@ import java.time.temporal.ChronoField;
|
|||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
|
public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
|
||||||
implements ContextualDeserializer {
|
implements ContextualDeserializer {
|
||||||
|
|
||||||
private final DateTimeFormatter[] formatters;
|
private final DateTimeFormatter[] formatters;
|
||||||
|
|
||||||
public LenientLocalDateTimeDeserializer() {
|
public LenientLocalDateTimeDeserializer() {
|
||||||
this(new String[]{
|
this(new String[]{
|
||||||
"yyyy-MM-dd",
|
"yyyy-MM-dd",
|
||||||
"yyyy-MM-dd HH",
|
"yyyy-MM-dd HH",
|
||||||
"yyyy-MM-dd HH:mm",
|
"yyyy-MM-dd HH:mm",
|
||||||
"yyyy-MM-dd HH:mm:ss",
|
"yyyy-MM-dd HH:mm:ss",
|
||||||
"yyyy-MM-dd'T'HH:mm",
|
"yyyy-MM-dd'T'HH:mm",
|
||||||
"yyyy-MM-dd'T'HH:mm:ss"
|
"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) {
|
// 패턴에 분/초가 없으면 0으로 채움 (날짜만 와도 LocalDateTime으로 만들 수 있게)
|
||||||
this.formatters = Arrays.stream(patterns)
|
return b
|
||||||
.map(LenientLocalDateTimeDeserializer::withDefaultTimeParts)
|
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
|
||||||
.toArray(DateTimeFormatter[]::new);
|
.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) {
|
for (DateTimeFormatter f : formatters) {
|
||||||
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
|
try {
|
||||||
.appendPattern(pattern);
|
return LocalDateTime.parse(s, f);
|
||||||
|
} catch (DateTimeParseException ignored) {
|
||||||
// 초(ss)가 있는 패턴이면 ".밀리초(1~3자리)"를 옵션으로 허용
|
}
|
||||||
// 예: 2025-12-19T14:50:12.1 / .12 / .123
|
|
||||||
// (pattern 자체에 S가 들어간 경우는 중복 추가 방지)
|
|
||||||
if (pattern.contains("ss") && !pattern.contains("S")) {
|
|
||||||
b.optionalStart()
|
|
||||||
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 3, true) // true => '.' 포함
|
|
||||||
.optionalEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 패턴에 분/초가 없으면 0으로 채움 (날짜만 와도 LocalDateTime으로 만들 수 있게)
|
|
||||||
return b
|
|
||||||
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
|
|
||||||
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
|
|
||||||
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
|
|
||||||
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
|
|
||||||
.toFormatter();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
throw ctxt.weirdStringException(s, LocalDateTime.class,
|
||||||
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
"Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime");
|
||||||
String s = DateTimeUtil.trimToNull(p.getText());
|
}
|
||||||
if (s == null) return null;
|
|
||||||
|
|
||||||
for (DateTimeFormatter f : formatters) {
|
@Override
|
||||||
try {
|
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
|
||||||
return LocalDateTime.parse(s, f);
|
throws JsonMappingException {
|
||||||
} catch (DateTimeParseException ignored) {}
|
if (property == null) {
|
||||||
}
|
return this;
|
||||||
|
|
||||||
throw ctxt.weirdStringException(s, LocalDateTime.class,
|
|
||||||
"Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
|
||||||
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
|
if (ann == null) {
|
||||||
throws JsonMappingException {
|
ann = property.getContextAnnotation(LenientLocalDateTime.class);
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kri.common.enums;
|
package com.kri.common.enums;
|
||||||
|
|
||||||
public interface CodeEnum<T> {
|
public interface CodeEnum<T> {
|
||||||
T getCode();
|
|
||||||
|
T getCode();
|
||||||
}
|
}
|
||||||
@@ -2,19 +2,22 @@ package com.kri.common.enums;
|
|||||||
|
|
||||||
public final class CodeEnumUtils {
|
public final class CodeEnumUtils {
|
||||||
|
|
||||||
private CodeEnumUtils() {}
|
private CodeEnumUtils() {
|
||||||
|
}
|
||||||
|
|
||||||
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
|
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
|
||||||
if (code == null) return null;
|
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()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (E e : enumClass.getEnumConstants()) {
|
||||||
|
if (e.getCode().equals(code)) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Unknown code [" + code + "] for enum class " + enumClass.getName()
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,17 @@
|
|||||||
package com.kri.common.excel;
|
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)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@Target(ElementType.FIELD)
|
@Target(ElementType.FIELD)
|
||||||
public @interface ExcelColumn {
|
public @interface ExcelColumn {
|
||||||
String header(); // 엑셀 헤더 이름
|
|
||||||
int order() default 0; // 컬럼 순서
|
String header(); // 엑셀 헤더 이름
|
||||||
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
|
|
||||||
|
int order() default 0; // 컬럼 순서
|
||||||
|
|
||||||
|
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,37 +1,35 @@
|
|||||||
package com.kri.common.excel;
|
package com.kri.common.excel;
|
||||||
|
|
||||||
import org.apache.poi.ss.usermodel.*;
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
import org.apache.poi.ss.usermodel.DateUtil;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public final class ExcelUtil {
|
public final class ExcelUtil {
|
||||||
|
|
||||||
private ExcelUtil() {}
|
private ExcelUtil() {
|
||||||
|
}
|
||||||
|
|
||||||
public static String getStringCell(Cell cell) {
|
public static String getStringCell(Cell cell) {
|
||||||
if (cell == null) {
|
if (cell == null) {
|
||||||
return 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 등 나머지 타입
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 등 나머지 타입
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,52 +3,57 @@ package com.kri.common.file;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
public final class FileUtil {
|
public final class FileUtil {
|
||||||
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
|
|
||||||
|
|
||||||
/**
|
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
|
||||||
* 파일명에서 위험한 문자 제거
|
|
||||||
*/
|
|
||||||
public static String sanitizeFileName(String original) {
|
|
||||||
if (original == null || original.isBlank()) {
|
|
||||||
return "file";
|
|
||||||
}
|
|
||||||
String name = original.trim().replace("\\", "/");
|
|
||||||
int idx = name.lastIndexOf('/');
|
|
||||||
if (idx >= 0 && idx < name.length() - 1) {
|
|
||||||
name = name.substring(idx + 1);
|
|
||||||
}
|
|
||||||
name = FILENAME_SANITIZE.matcher(name).replaceAll("_");
|
|
||||||
// 너무 짧으면 기본값
|
|
||||||
if (name.isBlank()) {
|
|
||||||
return "file";
|
|
||||||
}
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String getExtension(String fileName) {
|
/**
|
||||||
if (fileName == null) return "";
|
* 파일명에서 위험한 문자 제거
|
||||||
int dot = fileName.lastIndexOf('.');
|
*/
|
||||||
if (dot < 0 || dot == fileName.length() - 1) {
|
public static String sanitizeFileName(String original) {
|
||||||
return "";
|
if (original == null || original.isBlank()) {
|
||||||
}
|
return "file";
|
||||||
return fileName.substring(dot + 1);
|
|
||||||
}
|
}
|
||||||
|
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) {
|
public static String getExtension(String fileName) {
|
||||||
if (pathLike == null || pathLike.isBlank()) return "";
|
if (fileName == null) {
|
||||||
String s = pathLike;
|
return "";
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,91 +9,94 @@ import java.time.Duration;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 간단한 외부 API 통신 모듈.
|
* 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. -
|
||||||
* - url, 추가 헤더, body를 받아 호출합니다.
|
* body는 문자열(JSON 등) 기준입니다.
|
||||||
* - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다.
|
|
||||||
* - body는 문자열(JSON 등) 기준입니다.
|
|
||||||
*/
|
*/
|
||||||
public class ExternalApiClient {
|
public class ExternalApiClient {
|
||||||
|
|
||||||
private final HttpClient httpClient;
|
private final HttpClient httpClient;
|
||||||
private final Duration requestTimeout;
|
private final Duration requestTimeout;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅)
|
* 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅)
|
||||||
*/
|
*/
|
||||||
public ExternalApiClient() {
|
public ExternalApiClient() {
|
||||||
this(HttpClient.newBuilder()
|
this(HttpClient.newBuilder()
|
||||||
.connectTimeout(Duration.ofSeconds(10))
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
.build(), Duration.ofSeconds(30));
|
.build(), Duration.ofSeconds(30));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 사용자 지정 HttpClient/요청 타임아웃으로 생성
|
||||||
|
*/
|
||||||
|
public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
|
||||||
|
// GET/DELETE 등 body 없는 메서드는 noBody 사용
|
||||||
|
if (body == null || body.isEmpty()) {
|
||||||
|
return switch (method) {
|
||||||
|
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
|
||||||
|
default -> HttpRequest.BodyPublishers.noBody();
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
return HttpRequest.BodyPublishers.ofString(body);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
public ExternalApiResponse get(String url, Map<String, String> headers) {
|
||||||
* 사용자 지정 HttpClient/요청 타임아웃으로 생성
|
return send("GET", url, headers, null);
|
||||||
*/
|
}
|
||||||
public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) {
|
|
||||||
this.httpClient = httpClient;
|
public ExternalApiResponse delete(String url, Map<String, String> headers) {
|
||||||
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
|
return send("DELETE", url, headers, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExternalApiResponse get(String url, Map<String, String> headers) {
|
public ExternalApiResponse post(String url, Map<String, String> headers, String body) {
|
||||||
return send("GET", url, headers, null);
|
return send("POST", url, headers, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExternalApiResponse delete(String url, Map<String, String> headers) {
|
public ExternalApiResponse put(String url, Map<String, String> headers, String body) {
|
||||||
return send("DELETE", url, headers, null);
|
return send("PUT", url, headers, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExternalApiResponse post(String url, Map<String, String> headers, String body) {
|
public ExternalApiResponse patch(String url, Map<String, String> headers, String body) {
|
||||||
return send("POST", url, headers, body);
|
return send("PATCH", url, headers, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExternalApiResponse put(String url, Map<String, String> headers, String body) {
|
private ExternalApiResponse send(String method, String url, Map<String, String> headers,
|
||||||
return send("PUT", url, headers, body);
|
String body) {
|
||||||
}
|
try {
|
||||||
|
HttpRequest.Builder builder = HttpRequest.newBuilder()
|
||||||
public ExternalApiResponse patch(String url, Map<String, String> headers, String body) {
|
.uri(URI.create(url))
|
||||||
return send("PATCH", url, headers, body);
|
.timeout(requestTimeout)
|
||||||
}
|
.method(method, buildBodyPublisher(method, body));
|
||||||
|
|
||||||
private ExternalApiResponse send(String method, String url, Map<String, String> headers, String body) {
|
// 추가 헤더 설정
|
||||||
try {
|
if (headers != null) {
|
||||||
HttpRequest.Builder builder = HttpRequest.newBuilder()
|
headers.forEach((k, v) -> {
|
||||||
.uri(URI.create(url))
|
if (k != null && v != null) {
|
||||||
.timeout(requestTimeout)
|
builder.header(k, v);
|
||||||
.method(method, buildBodyPublisher(method, body));
|
}
|
||||||
|
});
|
||||||
// 추가 헤더 설정
|
}
|
||||||
if (headers != null) {
|
|
||||||
headers.forEach((k, v) -> {
|
// body가 있고 Content-Type이 없다면 기본 application/json
|
||||||
if (k != null && v != null) builder.header(k, v);
|
if (body != null && (headers == null || !headers.keySet().stream()
|
||||||
});
|
.map(String::toLowerCase).anyMatch("content-type"::equals))) {
|
||||||
}
|
builder.header("Content-Type", "application/json; charset=utf-8");
|
||||||
|
}
|
||||||
// body가 있고 Content-Type이 없다면 기본 application/json
|
|
||||||
if (body != null && (headers == null || !headers.keySet().stream()
|
HttpRequest request = builder.build();
|
||||||
.map(String::toLowerCase).anyMatch("content-type"::equals))) {
|
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
builder.header("Content-Type", "application/json; charset=utf-8");
|
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
||||||
}
|
} catch (IOException | InterruptedException e) {
|
||||||
|
// 인터럽트 복원
|
||||||
HttpRequest request = builder.build();
|
if (e instanceof InterruptedException) {
|
||||||
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
Thread.currentThread().interrupt();
|
||||||
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
}
|
||||||
} catch (IOException | InterruptedException e) {
|
throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), 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);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,29 +8,30 @@ import java.util.Map;
|
|||||||
* 외부 API 호출 결과를 단순하게 담는 DTO.
|
* 외부 API 호출 결과를 단순하게 담는 DTO.
|
||||||
*/
|
*/
|
||||||
public class ExternalApiResponse {
|
public class ExternalApiResponse {
|
||||||
private final int statusCode;
|
|
||||||
private final Map<String, List<String>> headers;
|
|
||||||
private final String body;
|
|
||||||
|
|
||||||
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
|
private final int statusCode;
|
||||||
this.statusCode = statusCode;
|
private final Map<String, List<String>> headers;
|
||||||
this.headers = headers;
|
private final String body;
|
||||||
this.body = body;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getStatusCode() {
|
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
|
||||||
return statusCode;
|
this.statusCode = statusCode;
|
||||||
}
|
this.headers = headers;
|
||||||
|
this.body = body;
|
||||||
|
}
|
||||||
|
|
||||||
public Map<String, List<String>> getHeaders() {
|
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
||||||
return headers;
|
return new ExternalApiResponse(status, headers.map(), body);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getBody() {
|
public int getStatusCode() {
|
||||||
return body;
|
return statusCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
public Map<String, List<String>> getHeaders() {
|
||||||
return new ExternalApiResponse(status, headers.map(), body);
|
return headers;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getBody() {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,23 +5,23 @@ import com.kri.common.enums.CodeEnumUtils;
|
|||||||
import jakarta.persistence.AttributeConverter;
|
import jakarta.persistence.AttributeConverter;
|
||||||
|
|
||||||
public abstract class AbstractCodeEnumConverter<
|
public abstract class AbstractCodeEnumConverter<
|
||||||
E extends Enum<E> & CodeEnum<V>,
|
E extends Enum<E> & CodeEnum<V>,
|
||||||
V
|
V
|
||||||
> implements AttributeConverter<E, V> {
|
> implements AttributeConverter<E, V> {
|
||||||
|
|
||||||
private final Class<E> enumClass;
|
private final Class<E> enumClass;
|
||||||
|
|
||||||
protected AbstractCodeEnumConverter(Class<E> enumClass) {
|
protected AbstractCodeEnumConverter(Class<E> enumClass) {
|
||||||
this.enumClass = enumClass;
|
this.enumClass = enumClass;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public V convertToDatabaseColumn(E attribute) {
|
public V convertToDatabaseColumn(E attribute) {
|
||||||
return attribute == null ? null : attribute.getCode();
|
return attribute == null ? null : attribute.getCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public E convertToEntityAttribute(V dbData) {
|
public E convertToEntityAttribute(V dbData) {
|
||||||
return CodeEnumUtils.fromCode(enumClass, dbData);
|
return CodeEnumUtils.fromCode(enumClass, dbData);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,36 +2,41 @@ package com.kri.common.jpa;
|
|||||||
|
|
||||||
import jakarta.persistence.MappedSuperclass;
|
import jakarta.persistence.MappedSuperclass;
|
||||||
import jakarta.persistence.PrePersist;
|
import jakarta.persistence.PrePersist;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@MappedSuperclass
|
@MappedSuperclass
|
||||||
public abstract class BaseUuidEntity {
|
public abstract class BaseUuidEntity {
|
||||||
protected abstract String getId();
|
|
||||||
protected abstract void setId(String id);
|
|
||||||
|
|
||||||
/** 엔티티마다 컬럼 길이에 맞춰 오버라이드 */
|
private static String generateId(int length) {
|
||||||
protected int idLength() { return 32; }
|
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
|
||||||
|
|
||||||
@PrePersist
|
if (length <= 32) {
|
||||||
protected void prePersistId() {
|
return base.substring(0, length);
|
||||||
if (getId() == null || getId().isBlank()) {
|
|
||||||
setId(generateId(idLength()));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String generateId(int length) {
|
StringBuilder sb = new StringBuilder(length);
|
||||||
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
|
sb.append(base);
|
||||||
|
while (sb.length() < length) {
|
||||||
if (length <= 32) {
|
sb.append(UUID.randomUUID().toString().replace("-", ""));
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,122 +3,120 @@ package com.kri.common.json;
|
|||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.core.type.TypeReference;
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public final class JsonUtil {
|
public final class JsonUtil {
|
||||||
|
|
||||||
private JsonUtil() {
|
private JsonUtil() {
|
||||||
// 유틸 클래스 - 인스턴스 생성 방지
|
// 유틸 클래스 - 인스턴스 생성 방지
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 임의의 자바 객체를 Map으로 변환한다.
|
* 임의의 자바 객체를 Map으로 변환한다. 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는
|
||||||
* 주의: JSON 문자열(String)을 파싱하는 용도가 아니라,
|
* 용도이다.
|
||||||
* 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 용도이다.
|
*/
|
||||||
*/
|
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
|
||||||
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
|
if (source == null) {
|
||||||
if (source == null) {
|
return Collections.emptyMap();
|
||||||
return Collections.emptyMap();
|
|
||||||
}
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
Map<String, Object> map = objectMapper.convertValue(source, Map.class);
|
|
||||||
return map;
|
|
||||||
}
|
}
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> map = objectMapper.convertValue(source, Map.class);
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON 문자열을 Map으로 파싱한다.
|
* JSON 문자열을 Map으로 파싱한다.
|
||||||
*
|
*
|
||||||
* @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환)
|
* @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환)
|
||||||
*/
|
*/
|
||||||
public static Map<String, Object> parseJsonToMap(ObjectMapper objectMapper, String json) {
|
public static Map<String, Object> parseJsonToMap(ObjectMapper objectMapper, String json) {
|
||||||
if (json == null || json.isBlank()) {
|
if (json == null || json.isBlank()) {
|
||||||
return Collections.emptyMap();
|
return Collections.emptyMap();
|
||||||
}
|
|
||||||
try {
|
|
||||||
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
|
||||||
|
});
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 객체를 JSON 문자열로 직렬화한다.
|
* 객체를 JSON 문자열로 직렬화한다.
|
||||||
*/
|
*/
|
||||||
public static String toJson(ObjectMapper objectMapper, Object value) {
|
public static String toJson(ObjectMapper objectMapper, Object value) {
|
||||||
try {
|
try {
|
||||||
return objectMapper.writeValueAsString(value);
|
return objectMapper.writeValueAsString(value);
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
throw new IllegalArgumentException("객체를 JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
throw new IllegalArgumentException("객체를 JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 객체를 사람이 읽기 좋은 pretty JSON 문자열로 직렬화한다.
|
* 객체를 사람이 읽기 좋은 pretty JSON 문자열로 직렬화한다.
|
||||||
*/
|
*/
|
||||||
public static String toPrettyJson(ObjectMapper objectMapper, Object value) {
|
public static String toPrettyJson(ObjectMapper objectMapper, Object value) {
|
||||||
try {
|
try {
|
||||||
return objectMapper.writerWithDefaultPrettyPrinter()
|
return objectMapper.writerWithDefaultPrettyPrinter()
|
||||||
.writeValueAsString(value);
|
.writeValueAsString(value);
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
throw new IllegalArgumentException("객체를 pretty JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
throw new IllegalArgumentException("객체를 pretty JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON 문자열을 주어진 타입으로 역직렬화한다.
|
* JSON 문자열을 주어진 타입으로 역직렬화한다. ex) fromJson(mapper, json, UserInfoDto.class)
|
||||||
* ex) fromJson(mapper, json, UserInfoDto.class)
|
*/
|
||||||
*/
|
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
|
||||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
|
if (json == null || json.isBlank()) {
|
||||||
if (json == null || json.isBlank()) {
|
return null;
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return objectMapper.readValue(json, type);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, type);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.",
|
||||||
|
e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON 문자열을 제네릭 타입으로 역직렬화한다.
|
* JSON 문자열을 제네릭 타입으로 역직렬화한다. ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>()
|
||||||
* ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>() {})
|
* {})
|
||||||
*/
|
*/
|
||||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
|
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
|
||||||
if (json == null || json.isBlank()) {
|
if (json == null || json.isBlank()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
|
||||||
try {
|
|
||||||
return objectMapper.readValue(json, typeRef);
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, typeRef);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON 기반 deep copy (또는 타입 변환).
|
* JSON 기반 deep copy (또는 타입 변환). 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
|
||||||
* 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
|
* <p>
|
||||||
*
|
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
|
||||||
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
|
*/
|
||||||
*/
|
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
|
||||||
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
|
if (source == null) {
|
||||||
if (source == null) {
|
return null;
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return objectMapper.convertValue(source, targetType);
|
|
||||||
}
|
}
|
||||||
|
return objectMapper.convertValue(source, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
|
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
|
||||||
*
|
* <p>
|
||||||
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
|
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
|
||||||
*/
|
*/
|
||||||
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {
|
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {
|
||||||
if (source == null) {
|
if (source == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
|
||||||
return objectMapper.convertValue(source, targetType);
|
|
||||||
}
|
}
|
||||||
|
return objectMapper.convertValue(source, targetType);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
package com.kri.common.redis;
|
package com.kri.common.redis;
|
||||||
|
|
||||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
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.context.annotation.Bean;
|
||||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
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
|
@AutoConfiguration
|
||||||
@ConditionalOnClass(RedisTemplate.class)
|
@ConditionalOnClass(RedisTemplate.class)
|
||||||
@@ -12,11 +16,16 @@ import org.springframework.data.redis.core.*;
|
|||||||
@ConditionalOnBean(RedisConnectionFactory.class)
|
@ConditionalOnBean(RedisConnectionFactory.class)
|
||||||
public class CommonRedisAutoConfiguration {
|
public class CommonRedisAutoConfiguration {
|
||||||
|
|
||||||
@Bean @ConditionalOnMissingBean
|
@Bean
|
||||||
public StringRedisTemplate stringRedisTemplate(org.springframework.data.redis.connection.RedisConnectionFactory cf) {
|
@ConditionalOnMissingBean
|
||||||
return new StringRedisTemplate(cf);
|
public StringRedisTemplate stringRedisTemplate(
|
||||||
}
|
org.springframework.data.redis.connection.RedisConnectionFactory cf) {
|
||||||
|
return new StringRedisTemplate(cf);
|
||||||
|
}
|
||||||
|
|
||||||
@Bean @ConditionalOnMissingBean
|
@Bean
|
||||||
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { return new RedisQueueHelper(rt); }
|
@ConditionalOnMissingBean
|
||||||
|
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) {
|
||||||
|
return new RedisQueueHelper(rt);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,21 @@
|
|||||||
package com.kri.common.redis;
|
package com.kri.common.redis;
|
||||||
|
|
||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
|
||||||
public class RedisQueueHelper {
|
public class RedisQueueHelper {
|
||||||
private final StringRedisTemplate rt;
|
|
||||||
public RedisQueueHelper(StringRedisTemplate rt) { this.rt = rt; }
|
private final StringRedisTemplate 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); }
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,4 +7,6 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
|||||||
@AutoConfiguration
|
@AutoConfiguration
|
||||||
@EnableScheduling
|
@EnableScheduling
|
||||||
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false)
|
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||||
public class CommonSchedulingAutoConfiguration { }
|
public class CommonSchedulingAutoConfiguration {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -6,43 +6,42 @@ import jakarta.servlet.FilterChain;
|
|||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doFilterInternal(
|
protected void doFilterInternal(
|
||||||
HttpServletRequest request,
|
HttpServletRequest request,
|
||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
FilterChain filterChain
|
FilterChain filterChain
|
||||||
) throws ServletException, IOException {
|
) throws ServletException, IOException {
|
||||||
// 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음)
|
// 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음)
|
||||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||||
String header = request.getHeader("Authorization");
|
String header = request.getHeader("Authorization");
|
||||||
if (header != null && header.startsWith("Bearer ")) {
|
if (header != null && header.startsWith("Bearer ")) {
|
||||||
String token = header.substring("Bearer ".length());
|
String token = header.substring("Bearer ".length());
|
||||||
try {
|
try {
|
||||||
// ★ 오직 "정상 JWT" 만 처리
|
// ★ 오직 "정상 JWT" 만 처리
|
||||||
Authentication auth = jwtService.toAuthentication(token);
|
Authentication auth = jwtService.toAuthentication(token);
|
||||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
} catch (JwtException ex) {
|
} catch (JwtException ex) {
|
||||||
// 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고:
|
// 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고:
|
||||||
// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
// return;
|
// return;
|
||||||
//
|
//
|
||||||
// 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐
|
// 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
filterChain.doFilter(request, response);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package com.kri.common.security;
|
package com.kri.common.security;
|
||||||
|
|
||||||
import com.kri.common.auth.apikey.ApiKeyAuthFilter;
|
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.JwtProperties;
|
||||||
import com.kri.common.auth.jwt.JwtService;
|
import com.kri.common.auth.jwt.JwtService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -15,73 +13,74 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.security.config.Customizer;
|
import org.springframework.security.config.Customizer;
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
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.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;
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
|
||||||
@AutoConfiguration(before = SecurityAutoConfiguration.class)
|
@AutoConfiguration(before = SecurityAutoConfiguration.class)
|
||||||
@EnableConfigurationProperties({KriSecurityProperties.class, JwtProperties.class})
|
@EnableConfigurationProperties({KriSecurityProperties.class, JwtProperties.class})
|
||||||
@ConditionalOnProperty(prefix = "kri.security", name = "enabled", havingValue = "true", matchIfMissing = true)
|
@ConditionalOnProperty(prefix = "kri.security", name = "enabled", havingValue = "true", matchIfMissing = true)
|
||||||
@EnableMethodSecurity(
|
@EnableMethodSecurity(
|
||||||
jsr250Enabled = true,
|
jsr250Enabled = true,
|
||||||
prePostEnabled = true
|
prePostEnabled = true
|
||||||
)
|
)
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class KriSecurityAutoConfiguration {
|
public class KriSecurityAutoConfiguration {
|
||||||
|
|
||||||
private final KriSecurityProperties securityProperties;
|
private final KriSecurityProperties securityProperties;
|
||||||
private final JwtProperties jwtProperties;
|
private final JwtProperties jwtProperties;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public JwtService jwtService(JwtProperties properties) {
|
public JwtService jwtService(JwtProperties properties) {
|
||||||
return new JwtService(properties);
|
return new JwtService(properties);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) {
|
public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) {
|
||||||
return new JwtAuthenticationFilter(jwtService);
|
return new JwtAuthenticationFilter(jwtService);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면
|
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 이 기본 Security 구성이 적용된다.
|
||||||
* 이 기본 Security 구성이 적용된다.
|
*/
|
||||||
*/
|
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
@Bean
|
||||||
@Bean
|
@ConditionalOnMissingBean(SecurityFilterChain.class)
|
||||||
@ConditionalOnMissingBean(SecurityFilterChain.class)
|
public SecurityFilterChain kriSecurityFilterChain(
|
||||||
public SecurityFilterChain kriSecurityFilterChain(
|
HttpSecurity http,
|
||||||
HttpSecurity http,
|
ObjectProvider<ApiKeyAuthFilter> apiKeyAuthFilterProvider,
|
||||||
ObjectProvider<ApiKeyAuthFilter> apiKeyAuthFilterProvider,
|
JwtAuthenticationFilter jwtAuthenticationFilter
|
||||||
JwtAuthenticationFilter jwtAuthenticationFilter
|
) throws Exception {
|
||||||
) throws Exception {
|
|
||||||
|
|
||||||
http
|
http
|
||||||
.httpBasic(AbstractHttpConfigurer::disable)
|
.httpBasic(AbstractHttpConfigurer::disable)
|
||||||
.csrf(AbstractHttpConfigurer::disable)
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
.cors(Customizer.withDefaults())
|
.cors(Customizer.withDefaults())
|
||||||
.sessionManagement(session ->
|
.sessionManagement(session ->
|
||||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||||
)
|
)
|
||||||
.authorizeHttpRequests(auth -> {
|
.authorizeHttpRequests(auth -> {
|
||||||
// ✅ yaml에서 정의한 public-paths 전부 permitAll
|
// ✅ yaml에서 정의한 public-paths 전부 permitAll
|
||||||
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths().isEmpty()) {
|
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths()
|
||||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)).permitAll();
|
.isEmpty()) {
|
||||||
}
|
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
|
||||||
// ✅ 나머지는 전부 인증 필요
|
.permitAll();
|
||||||
auth.anyRequest().authenticated();
|
}
|
||||||
});
|
// ✅ 나머지는 전부 인증 필요
|
||||||
|
auth.anyRequest().authenticated();
|
||||||
|
});
|
||||||
|
|
||||||
// ✅ API Key 필터가 존재하면 먼저 태움
|
// ✅ API Key 필터가 존재하면 먼저 태움
|
||||||
apiKeyAuthFilterProvider.ifAvailable(filter ->
|
apiKeyAuthFilterProvider.ifAvailable(filter ->
|
||||||
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
|
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
|
||||||
);
|
);
|
||||||
// ✅ 그 다음 JWT 필터
|
// ✅ 그 다음 JWT 필터
|
||||||
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,28 +1,26 @@
|
|||||||
package com.kri.common.security;
|
package com.kri.common.security;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@ConfigurationProperties(prefix = "kri.security")
|
@ConfigurationProperties(prefix = "kri.security")
|
||||||
public class KriSecurityProperties {
|
public class KriSecurityProperties {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 이 자동구성 사용 여부
|
* 이 자동구성 사용 여부
|
||||||
*/
|
*/
|
||||||
private boolean enabled = true;
|
private boolean enabled = true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 인증 없이 허용할 URL 패턴들
|
* 인증 없이 허용할 URL 패턴들 서비스에서 application.yml로 오버라이드
|
||||||
* 서비스에서 application.yml로 오버라이드
|
*/
|
||||||
*/
|
private List<String> publicPaths = List.of(
|
||||||
private List<String> publicPaths = List.of(
|
"/v3/api-docs/**",
|
||||||
"/v3/api-docs/**",
|
"/swagger-ui.html",
|
||||||
"/swagger-ui.html",
|
"/swagger-ui/**"
|
||||||
"/swagger-ui/**"
|
);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -22,56 +22,56 @@ import org.springframework.context.annotation.Bean;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class KriSwaggerAutoConfiguration {
|
public class KriSwaggerAutoConfiguration {
|
||||||
|
|
||||||
private final KriSwaggerProperties properties;
|
private final KriSwaggerProperties properties;
|
||||||
private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해
|
private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public OpenAPI kriOpenAPI() {
|
public OpenAPI kriOpenAPI() {
|
||||||
|
|
||||||
// 🔐 JWT Bearer + API-Key 스키마 정의
|
// 🔐 JWT Bearer + API-Key 스키마 정의
|
||||||
Components components = new Components()
|
Components components = new Components()
|
||||||
.addSecuritySchemes("BearerAuth",
|
.addSecuritySchemes("BearerAuth",
|
||||||
new SecurityScheme()
|
new SecurityScheme()
|
||||||
.type(SecurityScheme.Type.HTTP)
|
.type(SecurityScheme.Type.HTTP)
|
||||||
.scheme("bearer")
|
.scheme("bearer")
|
||||||
.bearerFormat("JWT"))
|
.bearerFormat("JWT"))
|
||||||
.addSecuritySchemes("ApiKeyAuth",
|
.addSecuritySchemes("ApiKeyAuth",
|
||||||
new SecurityScheme()
|
new SecurityScheme()
|
||||||
.type(SecurityScheme.Type.APIKEY)
|
.type(SecurityScheme.Type.APIKEY)
|
||||||
.in(SecurityScheme.In.HEADER)
|
.in(SecurityScheme.In.HEADER)
|
||||||
.name(apiKeyProperties.getHeaderName())); // 예: X-API-Key
|
.name(apiKeyProperties.getHeaderName())); // 예: X-API-Key
|
||||||
|
|
||||||
// 🔐 기본적으로 두 보안 스키마를 전역에 적용
|
// 🔐 기본적으로 두 보안 스키마를 전역에 적용
|
||||||
SecurityRequirement securityRequirement = new SecurityRequirement()
|
SecurityRequirement securityRequirement = new SecurityRequirement()
|
||||||
.addList("BearerAuth")
|
.addList("BearerAuth")
|
||||||
.addList("ApiKeyAuth");
|
.addList("ApiKeyAuth");
|
||||||
|
|
||||||
return new OpenAPI()
|
return new OpenAPI()
|
||||||
.components(components)
|
.components(components)
|
||||||
.addSecurityItem(securityRequirement)
|
.addSecurityItem(securityRequirement)
|
||||||
.info(new Info()
|
.info(new Info()
|
||||||
.title(properties.getTitle())
|
.title(properties.getTitle())
|
||||||
.description(properties.getDescription())
|
.description(properties.getDescription())
|
||||||
.version(properties.getVersion())
|
.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")
|
return builder.build();
|
||||||
@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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -9,14 +9,14 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
|||||||
@ConfigurationProperties(prefix = "kri.swagger")
|
@ConfigurationProperties(prefix = "kri.swagger")
|
||||||
public class KriSwaggerProperties {
|
public class KriSwaggerProperties {
|
||||||
|
|
||||||
private boolean enabled = true;
|
private boolean enabled = true;
|
||||||
|
|
||||||
private String title = "KRI API";
|
private String title = "KRI API";
|
||||||
private String description = "KRI Common API Docs";
|
private String description = "KRI Common API Docs";
|
||||||
private String version = "v1";
|
private String version = "v1";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 문서화할 base package (null 이면 전체)
|
* 문서화할 base package (null 이면 전체)
|
||||||
*/
|
*/
|
||||||
private String basePackage;
|
private String basePackage;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,40 +4,44 @@ import java.util.UUID;
|
|||||||
|
|
||||||
public final class CommonUtil {
|
public final class CommonUtil {
|
||||||
|
|
||||||
public static String uuid32() {
|
public static String uuid32() {
|
||||||
return UUID.randomUUID().toString().replace("-", "");
|
return UUID.randomUUID().toString().replace("-", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isNumeric(String s) {
|
public static boolean isNumeric(String s) {
|
||||||
if (s == null || s.isBlank()) return false;
|
if (s == null || s.isBlank()) {
|
||||||
for (int i = 0; i < s.length(); i++) {
|
return false;
|
||||||
char c = s.charAt(i);
|
|
||||||
if (c < '0' || c > '9') return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
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) {
|
public static short safeParseShort(String s, short def) {
|
||||||
try {
|
try {
|
||||||
return Short.parseShort(s);
|
return Short.parseShort(s);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return def;
|
return def;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static int safeParseInt(String s, short def) {
|
public static int safeParseInt(String s, short def) {
|
||||||
try {
|
try {
|
||||||
return Integer.parseInt(s);
|
return Integer.parseInt(s);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return def;
|
return def;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static long safeParseLong(String s, short def) {
|
public static long safeParseLong(String s, short def) {
|
||||||
try {
|
try {
|
||||||
return Long.parseLong(s);
|
return Long.parseLong(s);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return def;
|
return def;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,105 +1,120 @@
|
|||||||
package com.kri.common.web;
|
package com.kri.common.web;
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
public class BusinessException extends RuntimeException {
|
public class BusinessException extends RuntimeException {
|
||||||
private final HttpStatus status;
|
|
||||||
private final String code;
|
|
||||||
private final Map<String, Object> extras;
|
|
||||||
|
|
||||||
private static String defaultCode(HttpStatus status) { return status.name(); } // 예: NOT_FOUND, CONFLICT …
|
private final HttpStatus status;
|
||||||
|
private final String code;
|
||||||
|
private final Map<String, Object> extras;
|
||||||
|
|
||||||
private BusinessException(HttpStatus status, String code, String message,
|
private BusinessException(HttpStatus status, String code, String message,
|
||||||
Map<String, Object> extras, Throwable cause) {
|
Map<String, Object> extras, Throwable cause) {
|
||||||
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
|
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
|
||||||
this.status = status;
|
this.status = status;
|
||||||
this.code = (code != null && !code.isBlank()) ? code : defaultCode(status); // 코드가 없으면 상태명으로 대체
|
this.code = (code != null && !code.isBlank()) ? code : defaultCode(status); // 코드가 없으면 상태명으로 대체
|
||||||
this.extras = extras == null ? Collections.emptyMap()
|
this.extras = extras == null ? Collections.emptyMap()
|
||||||
: Collections.unmodifiableMap(new HashMap<>(extras));
|
: Collections.unmodifiableMap(new HashMap<>(extras));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BusinessException of(HttpStatus status, String code, String message) {
|
private static String defaultCode(HttpStatus status) {
|
||||||
return new BusinessException(status, code, message, null, null);
|
return status.name();
|
||||||
}
|
} // 예: NOT_FOUND, CONFLICT …
|
||||||
public static BusinessException of(HttpStatus status, String code, String message, Map<String,Object> extras) {
|
|
||||||
return new BusinessException(status, code, message, extras, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 편의 생성자들
|
public static BusinessException of(HttpStatus status, String code, String message) {
|
||||||
// 400 Bad Request
|
return new BusinessException(status, code, message, null, null);
|
||||||
public static BusinessException badRequest(String code, String message) {
|
}
|
||||||
return of(HttpStatus.BAD_REQUEST, code, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static BusinessException badRequest(String message) {
|
public static BusinessException of(HttpStatus status, String code, String message,
|
||||||
return badRequest("BAD_REQUEST", message);
|
Map<String, Object> extras) {
|
||||||
}
|
return new BusinessException(status, code, message, extras, null);
|
||||||
|
}
|
||||||
|
|
||||||
// 401 Unauthorized
|
// 편의 생성자들
|
||||||
public static BusinessException unauthorized(String code, String message) {
|
// 400 Bad Request
|
||||||
return of(HttpStatus.UNAUTHORIZED, code, message);
|
public static BusinessException badRequest(String code, String message) {
|
||||||
}
|
return of(HttpStatus.BAD_REQUEST, code, message);
|
||||||
|
}
|
||||||
|
|
||||||
public static BusinessException unauthorized(String message) {
|
public static BusinessException badRequest(String message) {
|
||||||
return unauthorized("UNAUTHORIZED", message);
|
return badRequest("BAD_REQUEST", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 403 Forbidden
|
// 401 Unauthorized
|
||||||
public static BusinessException forbidden(String code, String message) {
|
public static BusinessException unauthorized(String code, String message) {
|
||||||
return of(HttpStatus.FORBIDDEN, code, message);
|
return of(HttpStatus.UNAUTHORIZED, code, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BusinessException forbidden(String message) {
|
public static BusinessException unauthorized(String message) {
|
||||||
return forbidden("FORBIDDEN", message);
|
return unauthorized("UNAUTHORIZED", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 404 Not Found
|
// 403 Forbidden
|
||||||
public static BusinessException notFound(String code, String message) {
|
public static BusinessException forbidden(String code, String message) {
|
||||||
return of(HttpStatus.NOT_FOUND, code, message);
|
return of(HttpStatus.FORBIDDEN, code, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BusinessException notFound(String message) {
|
public static BusinessException forbidden(String message) {
|
||||||
return notFound("NOT_FOUND", message);
|
return forbidden("FORBIDDEN", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 409 Conflict
|
// 404 Not Found
|
||||||
public static BusinessException conflict(String code, String message) {
|
public static BusinessException notFound(String code, String message) {
|
||||||
return of(HttpStatus.CONFLICT, code, message);
|
return of(HttpStatus.NOT_FOUND, code, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BusinessException conflict(String message) {
|
public static BusinessException notFound(String message) {
|
||||||
return conflict("CONFLICT", message);
|
return notFound("NOT_FOUND", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 422 Unprocessable Entity (검증 에러 등에 자주 사용)
|
// 409 Conflict
|
||||||
public static BusinessException validationError(String code, String message) {
|
public static BusinessException conflict(String code, String message) {
|
||||||
return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message);
|
return of(HttpStatus.CONFLICT, code, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BusinessException validationError(String message) {
|
public static BusinessException conflict(String message) {
|
||||||
return validationError("VALIDATION_ERROR", message);
|
return conflict("CONFLICT", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 500 Internal Server Error
|
// 422 Unprocessable Entity (검증 에러 등에 자주 사용)
|
||||||
public static BusinessException internalError(String code, String message) {
|
public static BusinessException validationError(String code, String message) {
|
||||||
return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message);
|
return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BusinessException internalError(String message) {
|
public static BusinessException validationError(String message) {
|
||||||
return internalError("INTERNAL_SERVER_ERROR", message);
|
return validationError("VALIDATION_ERROR", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public HttpStatus getStatus() { return status; }
|
// 500 Internal Server Error
|
||||||
public String getCode() { return code; }
|
public static BusinessException internalError(String code, String message) {
|
||||||
public Map<String, Object> getExtras() { return extras; }
|
return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message);
|
||||||
|
}
|
||||||
|
|
||||||
/** 편의: 체이닝으로 extras 추가 */
|
public static BusinessException internalError(String message) {
|
||||||
public BusinessException with(String key, Object value) {
|
return internalError("INTERNAL_SERVER_ERROR", message);
|
||||||
var map = new HashMap<>(this.extras);
|
}
|
||||||
map.put(key, value);
|
|
||||||
return new BusinessException(this.status, this.code, this.getMessage(), map, this.getCause());
|
public HttpStatus getStatus() {
|
||||||
}
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCode() {
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getExtras() {
|
||||||
|
return extras;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 편의: 체이닝으로 extras 추가
|
||||||
|
*/
|
||||||
|
public BusinessException with(String key, Object value) {
|
||||||
|
var map = new HashMap<>(this.extras);
|
||||||
|
map.put(key, value);
|
||||||
|
return new BusinessException(this.status, this.code, this.getMessage(), map, this.getCause());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,17 +2,23 @@ package com.kri.common.web;
|
|||||||
|
|
||||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.core.Ordered;
|
import org.springframework.core.Ordered;
|
||||||
|
|
||||||
@AutoConfiguration
|
@AutoConfiguration
|
||||||
@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
|
@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
|
||||||
public class CommonWebAutoConfiguration {
|
public class CommonWebAutoConfiguration {
|
||||||
@Bean public ErrorAdvice errorAdvice() { return new ErrorAdvice(); }
|
|
||||||
@Bean public FilterRegistrationBean<TraceFilter> traceFilter() {
|
@Bean
|
||||||
var reg = new FilterRegistrationBean<>(new TraceFilter());
|
public ErrorAdvice errorAdvice() {
|
||||||
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
|
return new ErrorAdvice();
|
||||||
return reg;
|
}
|
||||||
}
|
|
||||||
|
@Bean
|
||||||
|
public FilterRegistrationBean<TraceFilter> traceFilter() {
|
||||||
|
var reg = new FilterRegistrationBean<>(new TraceFilter());
|
||||||
|
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
|
||||||
|
return reg;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,11 @@ package com.kri.common.web;
|
|||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.validation.ConstraintViolationException;
|
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.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.slf4j.MDC;
|
import org.slf4j.MDC;
|
||||||
@@ -11,6 +16,8 @@ import org.springframework.http.HttpStatus;
|
|||||||
import org.springframework.http.ProblemDetail;
|
import org.springframework.http.ProblemDetail;
|
||||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
import org.springframework.web.ErrorResponseException;
|
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.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
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.method.annotation.MethodArgumentTypeMismatchException;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
|
||||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
|
||||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.*;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
public class ErrorAdvice {
|
public class ErrorAdvice {
|
||||||
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
|
|
||||||
|
|
||||||
// 기본값은 모두 false → 외부 응답엔 노출 안 함
|
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
|
||||||
@Value("${common.error.expose.handler:false}")
|
|
||||||
private boolean exposeHandler;
|
|
||||||
@Value("${common.error.expose.service:false}")
|
|
||||||
private boolean exposeService;
|
|
||||||
|
|
||||||
/* ---------- 공통 ProblemDetail 빌더 ---------- */
|
// 기본값은 모두 false → 외부 응답엔 노출 안 함
|
||||||
protected ProblemDetail pd(HttpStatus status, String code, String message,
|
@Value("${common.error.expose.handler:false}")
|
||||||
HttpServletRequest req, Map<String, Object> extras) {
|
private boolean exposeHandler;
|
||||||
ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message);
|
@Value("${common.error.expose.service:false}")
|
||||||
p.setTitle(status.getReasonPhrase());
|
private boolean exposeService;
|
||||||
p.setProperty("code", code);
|
|
||||||
p.setProperty("timestamp", Instant.now().toString());
|
|
||||||
p.setProperty("path", req.getRequestURI());
|
|
||||||
|
|
||||||
String traceId = MDC.get("traceId");
|
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
|
||||||
if (traceId != null) p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
|
Set<HttpMethod> 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
|
/* ---------- 공통 ProblemDetail 빌더 ---------- */
|
||||||
if (exposeHandler) {
|
protected ProblemDetail pd(HttpStatus status, String code, String message,
|
||||||
String handler = MDC.get("handler"); // Controller#method
|
HttpServletRequest req, Map<String, Object> extras) {
|
||||||
if (handler != null) p.setProperty("handler", handler);
|
ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message);
|
||||||
}
|
p.setTitle(status.getReasonPhrase());
|
||||||
if (exposeService) {
|
p.setProperty("code", code);
|
||||||
String service = MDC.get("service"); // Service#method (최초 진입)
|
p.setProperty("timestamp", Instant.now().toString());
|
||||||
if (service != null) p.setProperty("service", service);
|
p.setProperty("path", req.getRequestURI());
|
||||||
}
|
|
||||||
|
|
||||||
if (extras != null) extras.forEach(p::setProperty);
|
String traceId = MDC.get("traceId");
|
||||||
return p;
|
if (traceId != null) {
|
||||||
|
p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- Custom Exception ---------- */
|
// ↓↓↓ 외부로 숨기고 싶으면 기본 false
|
||||||
@ExceptionHandler(BusinessException.class)
|
if (exposeHandler) {
|
||||||
public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) {
|
String handler = MDC.get("handler"); // Controller#method
|
||||||
logBusiness(e, req); // ← 로그 먼저
|
if (handler != null) {
|
||||||
return pd(
|
p.setProperty("handler", handler);
|
||||||
e.getStatus(),
|
}
|
||||||
e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨)
|
}
|
||||||
e.getMessage(),
|
if (exposeService) {
|
||||||
req,
|
String service = MDC.get("service"); // Service#method (최초 진입)
|
||||||
e.getExtras().isEmpty() ? null : e.getExtras()
|
if (service != null) {
|
||||||
);
|
p.setProperty("service", service);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 상황별 로그 레벨/스택트레이스 정책 */
|
if (extras != null) {
|
||||||
private void logBusiness(BusinessException e, HttpServletRequest req) {
|
extras.forEach(p::setProperty);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
|
/* ---------- Custom Exception ---------- */
|
||||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
@ExceptionHandler(BusinessException.class)
|
||||||
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest req) {
|
public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) {
|
||||||
var fieldErrors = e.getBindingResult().getFieldErrors().stream()
|
logBusiness(e, req); // ← 로그 먼저
|
||||||
.map(fe -> Map.of(
|
return pd(
|
||||||
"field", fe.getField(),
|
e.getStatus(),
|
||||||
"message", Optional.ofNullable(fe.getDefaultMessage()).orElse("invalid"),
|
e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨)
|
||||||
"rejectedValue", String.valueOf(fe.getRejectedValue())
|
e.getMessage(),
|
||||||
))
|
req,
|
||||||
.collect(Collectors.toList());
|
e.getExtras().isEmpty() ? null : e.getExtras()
|
||||||
return pd(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "요청 데이터가 올바르지 않습니다.", req,
|
);
|
||||||
Map.of("errors", fieldErrors));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------- 400: 파라미터/타입 문제 ---------- */
|
/* 상황별 로그 레벨/스택트레이스 정책 */
|
||||||
@ExceptionHandler({
|
private void logBusiness(BusinessException e, HttpServletRequest req) {
|
||||||
MissingServletRequestParameterException.class,
|
int sc = e.getStatus().value();
|
||||||
HttpMessageNotReadableException.class
|
String traceId = MDC.get("traceId");
|
||||||
})
|
String path = req.getRequestURI();
|
||||||
public ProblemDetail handleBadRequest(RuntimeException e, HttpServletRequest req) {
|
String code = e.getCode();
|
||||||
String msg = (e instanceof HttpMessageNotReadableException)
|
var extras = e.getExtras();
|
||||||
? "요청 바디를 읽을 수 없습니다(형식 오류/잘못된 JSON)."
|
|
||||||
: e.getMessage();
|
|
||||||
return pd(HttpStatus.BAD_REQUEST, "BAD_REQUEST", msg, req, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
if (sc >= 500) {
|
||||||
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, HttpServletRequest req) {
|
// 5xx: 운영 이슈 → ERROR + 스택트레이스
|
||||||
String need = (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
|
log.error("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||||
String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need;
|
sc, code, path, traceId, extras, e);
|
||||||
return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null);
|
} 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) 제약 위반 ---------- */
|
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
|
||||||
@ExceptionHandler(ConstraintViolationException.class)
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
public ProblemDetail handleConstraintViolation(ConstraintViolationException e, HttpServletRequest req) {
|
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e,
|
||||||
var errors = e.getConstraintViolations().stream()
|
HttpServletRequest req) {
|
||||||
.map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage()))
|
var fieldErrors = e.getBindingResult().getFieldErrors().stream()
|
||||||
.collect(Collectors.toList());
|
.map(fe -> Map.of(
|
||||||
return pd(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", "요청 파라미터가 제약을 위반했습니다.", req,
|
"field", fe.getField(),
|
||||||
Map.of("errors", errors));
|
"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 등 표준 스프링 예외 ---------- */
|
/* ---------- 400: 파라미터/타입 문제 ---------- */
|
||||||
@ExceptionHandler(NoResourceFoundException.class)
|
@ExceptionHandler({
|
||||||
public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) {
|
MissingServletRequestParameterException.class,
|
||||||
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
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)
|
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||||
public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) {
|
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e,
|
||||||
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
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)
|
/* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */
|
||||||
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest req) {
|
@ExceptionHandler(ConstraintViolationException.class)
|
||||||
String supported = resolveSupportedMethods(e);
|
public ProblemDetail handleConstraintViolation(ConstraintViolationException e,
|
||||||
String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported;
|
HttpServletRequest req) {
|
||||||
// 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported)
|
var errors = e.getConstraintViolations().stream()
|
||||||
return pd(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", msg, req, null);
|
.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)
|
/* ---------- 404/405/415 등 표준 스프링 예외 ---------- */
|
||||||
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, HttpServletRequest req) {
|
@ExceptionHandler(NoResourceFoundException.class)
|
||||||
String supported = e.getSupportedMediaTypes().stream().map(Object::toString).collect(Collectors.joining(","));
|
public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) {
|
||||||
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
|
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
||||||
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
|
@ExceptionHandler(NoHandlerFoundException.class)
|
||||||
@ExceptionHandler({ ResponseStatusException.class, ErrorResponseException.class })
|
public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) {
|
||||||
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
|
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
||||||
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(HttpRequestMethodNotSupportedException.class)
|
||||||
@ExceptionHandler(Exception.class)
|
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e,
|
||||||
public ProblemDetail handleAny(Exception e, HttpServletRequest req) {
|
HttpServletRequest req) {
|
||||||
log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e);
|
String supported = resolveSupportedMethods(e);
|
||||||
return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null);
|
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) {
|
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||||
Set<HttpMethod> httpMethods = e.getSupportedHttpMethods();
|
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e,
|
||||||
if (httpMethods != null && !httpMethods.isEmpty()) {
|
HttpServletRequest req) {
|
||||||
// ✅ 핵심 수정: Enum::name 대신 HttpMethod::name
|
String supported = e.getSupportedMediaTypes().stream().map(Object::toString)
|
||||||
return httpMethods.stream()
|
.collect(Collectors.joining(","));
|
||||||
.map(HttpMethod::name)
|
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
|
||||||
.collect(Collectors.joining(", "));
|
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
|
||||||
}
|
}
|
||||||
String[] methods = e.getSupportedMethods(); // 구버전 호환용
|
|
||||||
if (methods != null && methods.length > 0) {
|
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
|
||||||
return String.join(", ", methods);
|
@ExceptionHandler({ResponseStatusException.class, ErrorResponseException.class})
|
||||||
}
|
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
|
||||||
return "N/A";
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +1,39 @@
|
|||||||
package com.kri.common.web;
|
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.slf4j.MDC;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.web.method.HandlerMethod;
|
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 {
|
public class MdcHandlerConfig {
|
||||||
@Bean
|
|
||||||
public WebMvcConfigurer mdcWebMvcConfigurer() {
|
@Bean
|
||||||
return new WebMvcConfigurer() {
|
public WebMvcConfigurer mdcWebMvcConfigurer() {
|
||||||
@Override
|
return new WebMvcConfigurer() {
|
||||||
public void addInterceptors(InterceptorRegistry registry) {
|
@Override
|
||||||
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
@Override
|
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
|
||||||
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
|
@Override
|
||||||
if (handler instanceof HandlerMethod hm) {
|
public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
|
||||||
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
|
Object handler) {
|
||||||
String method = hm.getMethod().getName(); // ex) create
|
if (handler instanceof HandlerMethod hm) {
|
||||||
MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create
|
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
|
||||||
}
|
String method = hm.getMethod().getName(); // ex) create
|
||||||
return true;
|
MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
|
|
||||||
MDC.remove("handler");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
};
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
|
||||||
|
Object handler, Exception ex) {
|
||||||
|
MDC.remove("handler");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,30 @@
|
|||||||
package com.kri.common.web;
|
package com.kri.common.web;
|
||||||
|
|
||||||
import org.aspectj.lang.ProceedingJoinPoint;
|
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.slf4j.MDC;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@Aspect
|
@Aspect
|
||||||
@Component
|
@Component
|
||||||
public class ServiceMdcAspect {
|
public class ServiceMdcAspect {
|
||||||
@Around("within(@org.springframework.stereotype.Service *)")
|
|
||||||
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
|
@Around("within(@org.springframework.stereotype.Service *)")
|
||||||
boolean first = (MDC.get("service") == null);
|
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
|
||||||
if (first) {
|
boolean first = (MDC.get("service") == null);
|
||||||
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
|
if (first) {
|
||||||
String mtd = pjp.getSignature().getName(); // ex) enqueue
|
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
|
||||||
MDC.put("service", cls + "#" + mtd); // ex) ExportService#enqueue
|
String mtd = pjp.getSignature().getName(); // ex) enqueue
|
||||||
}
|
MDC.put("service",
|
||||||
try {
|
cls + "#" + mtd); // ex) ExportService#enqueue
|
||||||
return pjp.proceed();
|
|
||||||
} finally {
|
|
||||||
if (first) MDC.remove("service");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
return pjp.proceed();
|
||||||
|
} finally {
|
||||||
|
if (first) {
|
||||||
|
MDC.remove("service");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,35 @@
|
|||||||
package com.kri.common.web;
|
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.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import org.slf4j.MDC;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import org.slf4j.MDC;
|
||||||
|
|
||||||
public class TraceFilter implements Filter {
|
public class TraceFilter implements Filter {
|
||||||
private static final String REQ_HEADER = "X-Request-Id";
|
|
||||||
private static final String MDC_KEY = "traceId";
|
|
||||||
|
|
||||||
@Override
|
private static final String REQ_HEADER = "X-Request-Id";
|
||||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
private static final String MDC_KEY = "traceId";
|
||||||
throws IOException, ServletException {
|
|
||||||
var httpReq = (HttpServletRequest) req;
|
|
||||||
var httpRes = (HttpServletResponse) res;
|
|
||||||
|
|
||||||
String id = httpReq.getHeader(REQ_HEADER);
|
@Override
|
||||||
if (id == null || id.isBlank()) id = UUID.randomUUID().toString();
|
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)) {
|
String id = httpReq.getHeader(REQ_HEADER);
|
||||||
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo
|
if (id == null || id.isBlank()) {
|
||||||
chain.doFilter(req, res);
|
id = UUID.randomUUID().toString();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
|
||||||
|
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo
|
||||||
|
chain.doFilter(req, res);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,33 +4,36 @@ import com.kri.common.enums.CodeEnum;
|
|||||||
import org.springframework.core.convert.converter.Converter;
|
import org.springframework.core.convert.converter.Converter;
|
||||||
import org.springframework.core.convert.converter.ConverterFactory;
|
import org.springframework.core.convert.converter.ConverterFactory;
|
||||||
|
|
||||||
public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
|
public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T extends CodeEnum> Converter<String, T> getConverter(Class<T> targetType) {
|
public <T extends CodeEnum> Converter<String, T> getConverter(Class<T> targetType) {
|
||||||
return source -> convert(source, targetType);
|
return source -> convert(source, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
|
||||||
|
if (source == null || source.isBlank()) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
|
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
|
||||||
if (source == null || source.isBlank()) return null;
|
if (targetType.isEnum()) {
|
||||||
|
for (T e : targetType.getEnumConstants()) {
|
||||||
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
|
if (((Enum<?>) e).name().equalsIgnoreCase(source)) {
|
||||||
if (targetType.isEnum()) {
|
return e;
|
||||||
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,19 +8,19 @@ import org.springframework.web.servlet.HandlerInterceptor;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class IpAccessControlInterceptor implements HandlerInterceptor {
|
public class IpAccessControlInterceptor implements HandlerInterceptor {
|
||||||
|
|
||||||
private final IpAccessControlService ipAccessControlService;
|
private final IpAccessControlService ipAccessControlService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean preHandle(HttpServletRequest request,
|
public boolean preHandle(HttpServletRequest request,
|
||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
Object handler) throws Exception {
|
Object handler) throws Exception {
|
||||||
|
|
||||||
String clientIpAddress = IpUtil.getClientIp(request);
|
String clientIpAddress = IpUtil.getClientIp(request);
|
||||||
if (!ipAccessControlService.isAccessible(clientIpAddress)) {
|
if (!ipAccessControlService.isAccessible(clientIpAddress)) {
|
||||||
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,20 +1,19 @@
|
|||||||
package com.kri.common.webmvc;
|
package com.kri.common.webmvc;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class IpAccessControlService {
|
public class IpAccessControlService {
|
||||||
|
|
||||||
private final KriIpAccessProperties properties;
|
private final KriIpAccessProperties properties;
|
||||||
|
|
||||||
public boolean isAccessible(String ipAddress) {
|
public boolean isAccessible(String ipAddress) {
|
||||||
List<String> cidrs = properties.getEffectiveCidrs();
|
List<String> cidrs = properties.getEffectiveCidrs();
|
||||||
|
|
||||||
return cidrs.stream()
|
return cidrs.stream()
|
||||||
.map(IpAddressMatcher::new)
|
.map(IpAddressMatcher::new)
|
||||||
.anyMatch(matcher -> matcher.matches(ipAddress));
|
.anyMatch(matcher -> matcher.matches(ipAddress));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,24 +4,24 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
|
|
||||||
public final class IpUtil {
|
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) {
|
// 2. 그 다음 X-Real-IP
|
||||||
// 1. Proxy 환경 고려: X-Forwarded-For 헤더 우선
|
String realIp = request.getHeader("X-Real-IP");
|
||||||
String xff = request.getHeader("X-Forwarded-For");
|
if (realIp != null && !realIp.isBlank()) {
|
||||||
if (xff != null && !xff.isBlank()) {
|
return realIp;
|
||||||
// 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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 3. 최후 fallback
|
||||||
|
return request.getRemoteAddr();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +1,41 @@
|
|||||||
package com.kri.common.webmvc;
|
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.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@ConfigurationProperties(prefix = "kri.webmvc.ip")
|
@ConfigurationProperties(prefix = "kri.webmvc.ip")
|
||||||
public class KriIpAccessProperties {
|
public class KriIpAccessProperties {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 공통에서 고정으로 들고 갈 기본 CIDR 들
|
* 공통에서 고정으로 들고 갈 기본 CIDR 들 → setter 없음 (외부에서 못 바꿈)
|
||||||
* → setter 없음 (외부에서 못 바꿈)
|
*/
|
||||||
*/
|
private final List<String> defaultCidrs = List.of(
|
||||||
private final List<String> defaultCidrs = List.of(
|
"127.0.0.1/32", // 로컬 IPv4
|
||||||
"127.0.0.1/32", // 로컬 IPv4
|
"::1/128", // 로컬 IPv6
|
||||||
"::1/128", // 로컬 IPv6
|
"10.10.13.0/24", //석오 내부망
|
||||||
"10.10.13.0/24", //석오 내부망
|
"211.254.145.128/25" //석오 내부망 외부 IP
|
||||||
"211.254.145.128/25" //석오 내부망 외부 IP
|
);
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 서비스에서 추가로 넣고 싶은 CIDR 목록
|
* 서비스에서 추가로 넣고 싶은 CIDR 목록 application.yml / properties 로 바인딩되는 리스트
|
||||||
* application.yml / properties 로 바인딩되는 리스트
|
* <p>
|
||||||
*
|
* 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16
|
||||||
* 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16
|
*/
|
||||||
*/
|
private List<String> additionalCidrs = new ArrayList<>();
|
||||||
private List<String> additionalCidrs = new ArrayList<>();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 기본 + 추가를 합친 최종 목록
|
* 기본 + 추가를 합친 최종 목록
|
||||||
*/
|
*/
|
||||||
public List<String> getEffectiveCidrs() {
|
public List<String> getEffectiveCidrs() {
|
||||||
return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream())
|
return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream())
|
||||||
.distinct()
|
.distinct()
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,70 +19,70 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class KriWebMvcAutoConfiguration {
|
public class KriWebMvcAutoConfiguration {
|
||||||
|
|
||||||
private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor)
|
private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor)
|
||||||
|
// 선택 주입: 있으면 쓰고, 없으면 안 씀
|
||||||
|
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) {
|
public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) {
|
||||||
return new IpAccessControlService(ipProps);
|
return new IpAccessControlService(ipProps);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) {
|
public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) {
|
||||||
return new IpAccessControlInterceptor(service);
|
return new IpAccessControlInterceptor(service);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 선택 주입: 있으면 쓰고, 없으면 안 씀
|
@Bean
|
||||||
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
|
@ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
public RequestUserContextArgumentResolver requestUserContextArgumentResolver(
|
||||||
|
JwtService jwtService
|
||||||
|
) {
|
||||||
|
return new RequestUserContextArgumentResolver(jwtService);
|
||||||
|
}
|
||||||
|
|
||||||
@Bean
|
/**
|
||||||
@ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작
|
* 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean
|
||||||
@ConditionalOnMissingBean
|
*/
|
||||||
public RequestUserContextArgumentResolver requestUserContextArgumentResolver(
|
@Bean
|
||||||
JwtService jwtService
|
public WebMvcConfigurer kriCommonWebMvcConfigurer(
|
||||||
) {
|
KriIpAccessProperties properties,
|
||||||
return new RequestUserContextArgumentResolver(jwtService);
|
ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider,
|
||||||
}
|
ObjectProvider<RequestUserContextArgumentResolver> requestUserContextArgumentResolverProvider
|
||||||
|
) {
|
||||||
|
return new WebMvcConfigurer() {
|
||||||
|
@Override
|
||||||
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
// 기본 CORS – 필요하면 나중에 조정
|
||||||
|
registry.addMapping("/**")
|
||||||
|
.allowedOriginPatterns("*")
|
||||||
|
.allowedMethods("*")
|
||||||
|
.allowedHeaders("*")
|
||||||
|
.allowCredentials(true);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
@Override
|
||||||
* 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
*/
|
ipAccessControlInterceptorProvider.ifAvailable(interceptor ->
|
||||||
@Bean
|
registry.addInterceptor(interceptor)
|
||||||
public WebMvcConfigurer kriCommonWebMvcConfigurer(
|
.order(1)
|
||||||
KriIpAccessProperties properties,
|
.addPathPatterns("/swagger-ui/**", "/v3/api-docs/**")
|
||||||
ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider,
|
);
|
||||||
ObjectProvider<RequestUserContextArgumentResolver> requestUserContextArgumentResolverProvider
|
}
|
||||||
) {
|
|
||||||
return new WebMvcConfigurer() {
|
|
||||||
@Override
|
|
||||||
public void addCorsMappings(CorsRegistry registry) {
|
|
||||||
// 기본 CORS – 필요하면 나중에 조정
|
|
||||||
registry.addMapping("/**")
|
|
||||||
.allowedOriginPatterns("*")
|
|
||||||
.allowedMethods("*")
|
|
||||||
.allowedHeaders("*")
|
|
||||||
.allowCredentials(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addInterceptors(InterceptorRegistry registry) {
|
public void addArgumentResolvers(
|
||||||
ipAccessControlInterceptorProvider.ifAvailable(interceptor ->
|
java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
|
||||||
registry.addInterceptor(interceptor)
|
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
|
||||||
.order(1)
|
}
|
||||||
.addPathPatterns("/swagger-ui/**", "/v3/api-docs/**")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addArgumentResolvers(java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
|
public void addFormatters(org.springframework.format.FormatterRegistry registry) {
|
||||||
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
|
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());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -7,15 +7,15 @@ import lombok.Value;
|
|||||||
@Builder
|
@Builder
|
||||||
public class RequestUserContext {
|
public class RequestUserContext {
|
||||||
|
|
||||||
String userId;
|
String userId;
|
||||||
String userCmpn;
|
String userCmpn;
|
||||||
String userTeam;
|
String userTeam;
|
||||||
String userName;
|
String userName;
|
||||||
Integer userRole;
|
Integer userRole;
|
||||||
|
|
||||||
String clientIp; // IpUtil 에서 가져온 값
|
String clientIp; // IpUtil 에서 가져온 값
|
||||||
|
|
||||||
public boolean isAuthenticated() {
|
public boolean isAuthenticated() {
|
||||||
return userId != null;
|
return userId != null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package com.kri.common.webmvc;
|
package com.kri.common.webmvc;
|
||||||
|
|
||||||
import com.kri.common.auth.jwt.JwtService;
|
|
||||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||||
|
import com.kri.common.auth.jwt.JwtService;
|
||||||
import io.jsonwebtoken.JwtException;
|
import io.jsonwebtoken.JwtException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -17,60 +17,60 @@ import org.springframework.web.method.support.ModelAndViewContainer;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver {
|
public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver {
|
||||||
|
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean supportsParameter(MethodParameter parameter) {
|
public boolean supportsParameter(MethodParameter parameter) {
|
||||||
return RequestUserContext.class.isAssignableFrom(parameter.getParameterType());
|
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
|
// 2) 현재 공통 JwtService 는 principal 을 userId(String) 로 쓰고 있으니까,
|
||||||
public Object resolveArgument(
|
// 필요하면 Authorization 헤더에서 직접 토큰 파싱
|
||||||
MethodParameter parameter,
|
if (claims == null && request != null) {
|
||||||
@Nullable ModelAndViewContainer mavContainer,
|
String authHeader = request.getHeader("Authorization");
|
||||||
NativeWebRequest webRequest,
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||||
@Nullable WebDataBinderFactory binderFactory
|
String token = authHeader.substring(7);
|
||||||
) {
|
try {
|
||||||
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
claims = jwtService.toUserClaimsDto(token);
|
||||||
|
} catch (JwtException ex) {
|
||||||
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
|
// 토큰 이상하면 그냥 anonymous 로 둠
|
||||||
|
|
||||||
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 로 둠
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,13 +8,14 @@ import lombok.Setter;
|
|||||||
@Setter
|
@Setter
|
||||||
@Schema(description = "페이지 검색 조건")
|
@Schema(description = "페이지 검색 조건")
|
||||||
public class PageRequestDto {
|
public class PageRequestDto {
|
||||||
@Schema(description = "페이지 번호")
|
|
||||||
private int pageIndex = 0; // 0-base
|
|
||||||
@Schema(description = "페이지 크기")
|
|
||||||
private int pageSize = 10;
|
|
||||||
|
|
||||||
@Schema(description = "정렬 기준")
|
@Schema(description = "페이지 번호")
|
||||||
private String sortBy = "prjctIdx"; // 가변
|
private int pageIndex = 0; // 0-base
|
||||||
@Schema(description = "오름차순/내림차순")
|
@Schema(description = "페이지 크기")
|
||||||
private String sortDir = "desc"; // asc/desc
|
private int pageSize = 10;
|
||||||
|
|
||||||
|
@Schema(description = "정렬 기준")
|
||||||
|
private String sortBy = "prjctIdx"; // 가변
|
||||||
|
@Schema(description = "오름차순/내림차순")
|
||||||
|
private String sortDir = "desc"; // asc/desc
|
||||||
}
|
}
|
||||||
@@ -1,35 +1,35 @@
|
|||||||
package com.kri.common.webmvc.page;
|
package com.kri.common.webmvc.page;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Builder
|
@Builder
|
||||||
public class PageResponseDto <T> {
|
public class PageResponseDto<T> {
|
||||||
private List<T> content;
|
|
||||||
private long totalElements;
|
|
||||||
private int totalPages;
|
|
||||||
private int pageIndex;
|
|
||||||
private int pageSize;
|
|
||||||
private int numberOfElements;
|
|
||||||
private boolean first;
|
|
||||||
private boolean last;
|
|
||||||
private boolean empty;
|
|
||||||
|
|
||||||
public static <T> PageResponseDto<T> from(Page<T> page) {
|
private List<T> content;
|
||||||
return PageResponseDto.<T>builder()
|
private long totalElements;
|
||||||
.content(page.getContent())
|
private int totalPages;
|
||||||
.totalElements(page.getTotalElements())
|
private int pageIndex;
|
||||||
.totalPages(page.getTotalPages())
|
private int pageSize;
|
||||||
.pageIndex(page.getNumber()) // ✅ 현재 페이지 index(0-base)
|
private int numberOfElements;
|
||||||
.pageSize(page.getSize())
|
private boolean first;
|
||||||
.numberOfElements(page.getNumberOfElements())
|
private boolean last;
|
||||||
.first(page.isFirst())
|
private boolean empty;
|
||||||
.last(page.isLast())
|
|
||||||
.empty(page.isEmpty())
|
public static <T> PageResponseDto<T> from(Page<T> page) {
|
||||||
.build();
|
return PageResponseDto.<T>builder()
|
||||||
}
|
.content(page.getContent())
|
||||||
|
.totalElements(page.getTotalElements())
|
||||||
|
.totalPages(page.getTotalPages())
|
||||||
|
.pageIndex(page.getNumber()) // ✅ 현재 페이지 index(0-base)
|
||||||
|
.pageSize(page.getSize())
|
||||||
|
.numberOfElements(page.getNumberOfElements())
|
||||||
|
.first(page.isFirst())
|
||||||
|
.last(page.isLast())
|
||||||
|
.empty(page.isEmpty())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,67 +1,77 @@
|
|||||||
package com.kri.common.webmvc.page;
|
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.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.domain.Sort;
|
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 {
|
public final class Pageables {
|
||||||
private Pageables() {}
|
|
||||||
|
|
||||||
public static Pageable of(PageRequestDto req, Class<?> sortType) {
|
private Pageables() {
|
||||||
int page = Math.max(req.getPageIndex(), 0);
|
}
|
||||||
int size = Math.max(req.getPageSize(), 1);
|
|
||||||
|
|
||||||
Sort sort = buildSort(req, sortType);
|
public static Pageable of(PageRequestDto req, Class<?> sortType) {
|
||||||
return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort);
|
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) {
|
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
|
||||||
String sortBy = req.getSortBy();
|
? Sort.Direction.ASC
|
||||||
if (sortBy == null || sortBy.isBlank()) return null;
|
: Sort.Direction.DESC;
|
||||||
|
|
||||||
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
|
Set<String> allowed = allowedProperties(sortType);
|
||||||
? Sort.Direction.ASC
|
|
||||||
: Sort.Direction.DESC;
|
|
||||||
|
|
||||||
Set<String> allowed = allowedProperties(sortType);
|
List<String> props = Arrays.stream(sortBy.split(","))
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(s -> !s.isBlank())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
List<String> props = Arrays.stream(sortBy.split(","))
|
// 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨)
|
||||||
.map(String::trim)
|
List<String> invalid = props.stream()
|
||||||
.filter(s -> !s.isBlank())
|
.filter(p -> !allowed.contains(p))
|
||||||
.collect(Collectors.toList());
|
.toList();
|
||||||
|
|
||||||
// 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨)
|
if (!invalid.isEmpty()) {
|
||||||
List<String> invalid = props.stream()
|
throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed);
|
||||||
.filter(p -> !allowed.contains(p))
|
}
|
||||||
.toList();
|
|
||||||
|
|
||||||
if (!invalid.isEmpty()) {
|
return Sort.by(dir, props.toArray(String[]::new));
|
||||||
throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed);
|
}
|
||||||
|
|
||||||
|
private static Set<String> allowedProperties(Class<?> sortType) {
|
||||||
|
try {
|
||||||
|
// getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적)
|
||||||
|
PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors();
|
||||||
|
Set<String> props = new HashSet<>();
|
||||||
|
for (PropertyDescriptor pd : pds) {
|
||||||
|
String name = pd.getName();
|
||||||
|
if ("class".equals(name)) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
if (pd.getReadMethod() == null) {
|
||||||
return Sort.by(dir, props.toArray(String[]::new));
|
continue;
|
||||||
}
|
|
||||||
|
|
||||||
private static Set<String> allowedProperties(Class<?> sortType) {
|
|
||||||
try {
|
|
||||||
// getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적)
|
|
||||||
PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors();
|
|
||||||
Set<String> props = new HashSet<>();
|
|
||||||
for (PropertyDescriptor pd : pds) {
|
|
||||||
String name = pd.getName();
|
|
||||||
if ("class".equals(name)) continue;
|
|
||||||
if (pd.getReadMethod() == null) continue;
|
|
||||||
props.add(name);
|
|
||||||
}
|
|
||||||
return props;
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
|
|
||||||
}
|
}
|
||||||
|
props.add(name);
|
||||||
|
}
|
||||||
|
return props;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,50 +1,50 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<configuration scan="true">
|
<configuration scan="true">
|
||||||
|
|
||||||
<!-- Spring property 사용 (없으면 기본값) -->
|
<!-- Spring property 사용 (없으면 기본값) -->
|
||||||
<springProperty scope="context" name="APP_NAME" source="app.name" defaultValue="app"/>
|
<appender class="ch.qos.logback.core.ConsoleAppender" name="CONSOLE">
|
||||||
<springProperty scope="context" name="LOG_DIR" source="logging.file.path" defaultValue="logs"/>
|
<encoder>
|
||||||
|
<!-- Spring Boot 확장 패턴도 사용할 수 있음: %clr(%level) 등 -->
|
||||||
|
<pattern>${LOG_PATTERN}</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
<appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="FILE">
|
||||||
|
<encoder>
|
||||||
|
<pattern>${LOG_PATTERN}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<file>${LOG_DIR}/${APP_NAME}.log</file>
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<fileNamePattern>${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz</fileNamePattern>
|
||||||
|
<maxHistory>14</maxHistory> <!-- 보관 일수 -->
|
||||||
|
</rollingPolicy>
|
||||||
|
</appender>
|
||||||
|
|
||||||
<!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
|
<!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
|
||||||
<property name="LOG_PATTERN"
|
<appender class="ch.qos.logback.classic.AsyncAppender" name="ASYNC_FILE">
|
||||||
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
|
<appender-ref ref="FILE"/>
|
||||||
|
<discardingThreshold>0</discardingThreshold>
|
||||||
|
<neverBlock>true</neverBlock>
|
||||||
|
<queueSize>8192</queueSize>
|
||||||
|
</appender>
|
||||||
|
|
||||||
<!-- 콘솔 -->
|
<!-- 콘솔 -->
|
||||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
<property name="LOG_PATTERN"
|
||||||
<encoder>
|
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
|
||||||
<!-- Spring Boot 확장 패턴도 사용할 수 있음: %clr(%level) 등 -->
|
|
||||||
<pattern>${LOG_PATTERN}</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<!-- 롤링 파일 (일 단위) -->
|
<!-- 롤링 파일 (일 단위) -->
|
||||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
<root level="INFO">
|
||||||
<file>${LOG_DIR}/${APP_NAME}.log</file>
|
<appender-ref ref="CONSOLE"/>
|
||||||
<encoder>
|
<appender-ref ref="ASYNC_FILE"/>
|
||||||
<pattern>${LOG_PATTERN}</pattern>
|
</root>
|
||||||
</encoder>
|
|
||||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
|
||||||
<fileNamePattern>${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz</fileNamePattern>
|
|
||||||
<maxHistory>14</maxHistory> <!-- 보관 일수 -->
|
|
||||||
</rollingPolicy>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 -->
|
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 -->
|
||||||
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
|
<springProperty defaultValue="logs" name="LOG_DIR" scope="context" source="logging.file.path"/>
|
||||||
<queueSize>8192</queueSize>
|
|
||||||
<discardingThreshold>0</discardingThreshold>
|
|
||||||
<neverBlock>true</neverBlock>
|
|
||||||
<appender-ref ref="FILE"/>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<!-- 패키지별 레벨(선택) -->
|
<!-- 패키지별 레벨(선택) -->
|
||||||
<!-- <logger name="com.kri" level="INFO" additivity="false">
|
<!-- <logger name="com.kri" level="INFO" additivity="false">
|
||||||
<appender-ref ref="CONSOLE"/>
|
<appender-ref ref="CONSOLE"/>
|
||||||
<appender-ref ref="ASYNC_FILE"/>
|
<appender-ref ref="ASYNC_FILE"/>
|
||||||
</logger> -->
|
</logger> -->
|
||||||
|
|
||||||
<root level="INFO">
|
<springProperty defaultValue="app" name="APP_NAME" scope="context" source="app.name"/>
|
||||||
<appender-ref ref="CONSOLE"/>
|
|
||||||
<appender-ref ref="ASYNC_FILE"/>
|
|
||||||
</root>
|
|
||||||
</configuration>
|
</configuration>
|
||||||
Reference in New Issue
Block a user