260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용
This commit is contained in:
67
README.md
67
README.md
@@ -20,6 +20,7 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
|
||||
- 주요 클래스: `ExternalApiClient`, `ExternalApiResponse`
|
||||
|
||||
지원 메서드(문자열 body 기반)
|
||||
|
||||
- `ExternalApiResponse get(String url, Map<String,String> headers)`
|
||||
- `ExternalApiResponse post(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)`
|
||||
|
||||
기본 동작
|
||||
|
||||
- 연결 타임아웃: 10초, 요청 타임아웃: 30초
|
||||
- body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정
|
||||
- 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원
|
||||
|
||||
응답 객체(`ExternalApiResponse`)
|
||||
|
||||
- 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String)
|
||||
- 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)`
|
||||
|
||||
@@ -77,6 +80,7 @@ ExternalApiClient client = new ExternalApiClient(httpClient, Duration.ofSeconds(
|
||||
```
|
||||
|
||||
주의사항
|
||||
|
||||
- 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요.
|
||||
- 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요.
|
||||
|
||||
@@ -264,6 +268,7 @@ kri:
|
||||
- com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용)
|
||||
|
||||
권장 의존 방향(순환 금지):
|
||||
|
||||
- auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸)
|
||||
- security → auth.* 에 의존(필터 순서/체인 구성)
|
||||
- web, webmvc → spring-web 중심, security에 의존하지 않음
|
||||
@@ -272,25 +277,33 @@ kri:
|
||||
|
||||
### 0.2 AutoConfiguration 로딩과 오버라이드 전략
|
||||
|
||||
자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음 순서/특징을 가집니다.
|
||||
자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음
|
||||
순서/특징을 가집니다.
|
||||
|
||||
1) com.kri.common.auth.jwt.JwtAutoConfiguration
|
||||
|
||||
- JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공
|
||||
|
||||
2) com.kri.common.security.KriSecurityAutoConfiguration
|
||||
|
||||
- SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입
|
||||
- before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입
|
||||
|
||||
3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration
|
||||
|
||||
- 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터
|
||||
|
||||
4) com.kri.common.swagger.KriSwaggerAutoConfiguration
|
||||
|
||||
- OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록
|
||||
|
||||
5) com.kri.common.redis.CommonRedisAutoConfiguration, com.kri.common.scheduling.CommonSchedulingAutoConfiguration
|
||||
5) com.kri.common.redis.CommonRedisAutoConfiguration,
|
||||
com.kri.common.scheduling.CommonSchedulingAutoConfiguration
|
||||
|
||||
- 선택 기능: RedisQueueHelper, @EnableScheduling
|
||||
|
||||
오버라이드 규칙:
|
||||
|
||||
- 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선
|
||||
- 프로퍼티로 on/off 토글(@ConditionalOnProperty)
|
||||
|
||||
@@ -389,7 +402,7 @@ KriCommon은 다음 AutoConfiguration 들을 제공합니다.
|
||||
모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다.
|
||||
|
||||
| 클래스 | 역할 요약 |
|
||||
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
|---------------------------------------------------------------|---------------------------------------------------------------------------------------|
|
||||
| `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 |
|
||||
| `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` |
|
||||
| `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 |
|
||||
@@ -499,7 +512,7 @@ public class JwtProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| --------------------------------------------- | ------ | ------------ | -------------------------------------- |
|
||||
|-----------------------------------------------|--------|--------------|----------------------------------------|
|
||||
| `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) |
|
||||
| `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 |
|
||||
| `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) |
|
||||
@@ -600,7 +613,7 @@ public class ApiKeyProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| ----------------------------- | ------- | ----------- | ----------------------- |
|
||||
|-------------------------------|---------|-------------|-------------------------|
|
||||
| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 |
|
||||
| `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 |
|
||||
|
||||
@@ -677,7 +690,7 @@ public class KriSecurityProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 (일부) | 설명 |
|
||||
| --------------------------- | ------------ | ---------------- | -------------------------- |
|
||||
|-----------------------------|--------------|------------------|----------------------------|
|
||||
| `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 |
|
||||
| `kri.security.public-paths` | List<String> | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 |
|
||||
|
||||
@@ -866,7 +879,7 @@ public class KriIpAccessProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 설명 |
|
||||
| -------------------------------- | ------------ | --------------------------------- |
|
||||
|----------------------------------|--------------|-----------------------------------|
|
||||
| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off |
|
||||
| `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 CIDR 목록에 *추가*할 CIDR 리스트 |
|
||||
|
||||
@@ -944,7 +957,7 @@ public class CommonRedisAutoConfiguration {
|
||||
**프로퍼티**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| ---------------------- | ------- | ----- | ---------------------- |
|
||||
|------------------------|---------|-------|------------------------|
|
||||
| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 |
|
||||
|
||||
#### 4.6.2. RedisQueueHelper 사용 예시
|
||||
@@ -980,7 +993,7 @@ public class CommonSchedulingAutoConfiguration { }
|
||||
**프로퍼티**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| --------------------------- | ------- | ----- | -------------------------- |
|
||||
|-----------------------------|---------|-------|----------------------------|
|
||||
| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 |
|
||||
|
||||
서비스 쪽에서는 단순히:
|
||||
@@ -1022,7 +1035,6 @@ common:
|
||||
|
||||
**던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다.
|
||||
|
||||
|
||||
#### 4.9.2. 기본 사용 패턴
|
||||
|
||||
* 4.9.2.1. Not Found (404)
|
||||
@@ -1040,12 +1052,14 @@ public User getUserOrThrow(String userId) {
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- HTTP 상태: 404
|
||||
- code: "USER_NOT_FOUND"
|
||||
- message: "해당 사용자를 찾을 수 없습니다."
|
||||
- extras: { "userId": "..." }
|
||||
|
||||
* 4.9.2.2. Conflict (409)
|
||||
|
||||
```
|
||||
if (userRepository.existsByLoginId(loginId)) {
|
||||
throw BusinessException.conflict(
|
||||
@@ -1056,6 +1070,7 @@ if (userRepository.existsByLoginId(loginId)) {
|
||||
```
|
||||
|
||||
* 4.9.2.3. Forbidden (403)
|
||||
|
||||
```
|
||||
if (!currentUser.canAccess(targetProject)) {
|
||||
throw BusinessException.forbidden(
|
||||
@@ -1066,7 +1081,9 @@ if (!currentUser.canAccess(targetProject)) {
|
||||
```
|
||||
|
||||
#### 4.9.3. 임의 상태 코드 지정: of(...)
|
||||
|
||||
of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다.
|
||||
|
||||
```
|
||||
throw BusinessException.of(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
@@ -1075,7 +1092,9 @@ throw BusinessException.of(
|
||||
).with("param", "startDate");
|
||||
|
||||
```
|
||||
|
||||
추가 정보를 한 번에 넘기고 싶으면:
|
||||
|
||||
```
|
||||
Map<String, Object> extras = Map.of(
|
||||
"param", "startDate",
|
||||
@@ -1089,21 +1108,27 @@ throw BusinessException.of(
|
||||
extras
|
||||
);
|
||||
```
|
||||
|
||||
> 실제 구현에는 of(status, code, message, Map<String,Object>) 시그니처가 존재합니다.
|
||||
|
||||
#### 4.9.4. extras 체이닝: with(...) 활용
|
||||
|
||||
with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다.
|
||||
|
||||
```
|
||||
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||
.with("userId", userId)
|
||||
.with("searchType", "INTRANET");
|
||||
```
|
||||
|
||||
* 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다.
|
||||
|
||||
#### 4.9.5. Service / Controller에서의 사용 위치
|
||||
|
||||
Service에서 던지고, Controller는 깔끔하게 유지
|
||||
|
||||
Service 예시
|
||||
Service 예시
|
||||
|
||||
```
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -1124,6 +1149,7 @@ public class UserService {
|
||||
```
|
||||
|
||||
Controller 예시
|
||||
|
||||
```
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
@@ -1145,12 +1171,15 @@ public class UserController {
|
||||
* ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리
|
||||
|
||||
#### 4.9.6. 실제 응답 JSON 예시
|
||||
|
||||
```
|
||||
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||
.with("userId", "u-123");
|
||||
|
||||
```
|
||||
|
||||
요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "about:blank",
|
||||
@@ -1166,6 +1195,7 @@ throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없
|
||||
"userId": "u-123"
|
||||
}
|
||||
```
|
||||
|
||||
> 이 포맷은 ErrorAdvice에서 공통으로 생성합니다.
|
||||
|
||||
#### 4.9.7. 로그 출력 정책
|
||||
@@ -1187,6 +1217,7 @@ ErrorAdvice 내부 로깅 정책(요약):
|
||||
#### 4.9.8. 에러 코드 enum으로 관리하기 (선택)
|
||||
|
||||
서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다.
|
||||
|
||||
```
|
||||
public enum UserErrorCodes {
|
||||
USER_NOT_FOUND,
|
||||
@@ -1199,6 +1230,7 @@ throw BusinessException.notFound(
|
||||
"사용자를 찾을 수 없습니다."
|
||||
).with("userId", userId);
|
||||
```
|
||||
|
||||
#### 4.9.9. 요약
|
||||
|
||||
1. 던지는 쪽 (Service)
|
||||
@@ -1215,6 +1247,7 @@ throw BusinessException.notFound(
|
||||
* FE에서는 code 기준으로 에러 분기 처리하면 됨
|
||||
|
||||
---
|
||||
|
||||
## 5. example-service 적용 요약
|
||||
|
||||
1. **의존성 추가**
|
||||
@@ -1273,7 +1306,8 @@ throw BusinessException.notFound(
|
||||
|
||||
- Swagger 페이지가 접근 불가(403/404)
|
||||
- 원인: 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가 동작하지 않음
|
||||
- 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false`
|
||||
@@ -1284,13 +1318,16 @@ throw BusinessException.notFound(
|
||||
## 8. FAQ
|
||||
|
||||
- Q. API Key와 JWT는 어떻게 같이 쓰나요?
|
||||
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 권장합니다.
|
||||
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를
|
||||
권장합니다.
|
||||
|
||||
- Q. ROLE 매핑은 어디서 바꾸나요?
|
||||
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 오버라이드하거나 래핑하십시오.
|
||||
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를
|
||||
오버라이드하거나 래핑하십시오.
|
||||
|
||||
- Q. 기본 Security를 전면 교체할 수 있나요?
|
||||
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 적용됩니다.
|
||||
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선
|
||||
적용됩니다.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -10,4 +10,5 @@ import org.springframework.context.annotation.Import;
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
||||
@Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록
|
||||
public class ApiKeyAdminAutoConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.kri.common.auth.apikey;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||
@@ -11,13 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/internal/apikey")
|
||||
@ConditionalOnProperty(prefix="kri.auth.apikey", name="admin-api-enabled", havingValue="true")
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
||||
public class ApiKeyAdminController {
|
||||
|
||||
private final ApiKeyProperties props;
|
||||
private final PreloadedApiKeyUserClaimsProvider provider;
|
||||
private final List<IpAddressMatcher> allow;
|
||||
@@ -35,7 +35,9 @@ public class ApiKeyAdminController {
|
||||
return new ReloadResult(count);
|
||||
}
|
||||
|
||||
/** 현재 캐시 상태(키는 마스킹) */
|
||||
/**
|
||||
* 현재 캐시 상태(키는 마스킹)
|
||||
*/
|
||||
@GetMapping("/cache")
|
||||
public List<CachedKeyView> cache(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
@@ -46,19 +48,32 @@ public class ApiKeyAdminController {
|
||||
}
|
||||
|
||||
private void assertAllowed(HttpServletRequest req) {
|
||||
if (!props.isAdminApiEnabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
if (!props.isAdminApiEnabled()) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
String remote = req.getRemoteAddr();
|
||||
boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
|
||||
if (!ok) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
||||
if (!ok) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
||||
}
|
||||
}
|
||||
|
||||
private String mask(String raw) {
|
||||
if (raw == null) return "";
|
||||
if (raw == null) {
|
||||
return "";
|
||||
}
|
||||
int n = raw.length();
|
||||
if (n <= 8) return raw.charAt(0) + "****";
|
||||
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 ReloadResult(int cachedKeyCount) {
|
||||
|
||||
}
|
||||
|
||||
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,18 +5,16 @@ import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터.
|
||||
* - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임.
|
||||
* - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
|
||||
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. -
|
||||
* 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class ApiKeyAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
@@ -2,6 +2,9 @@ package com.kri.common.auth.apikey;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
@@ -19,10 +22,6 @@ import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/*
|
||||
* @Primary 절대 금지
|
||||
* 메인 JPA와 완전히 분리
|
||||
@@ -59,9 +58,10 @@ public class ApiKeyJpaAutoConfiguration {
|
||||
ds.setDriverClassName(db.getDriverClassName());
|
||||
return ds;
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식
|
||||
* - intranet-extension처럼 HibernateJpaAutoConfiguration을 exclude 해도 동작
|
||||
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - intranet-extension처럼 HibernateJpaAutoConfiguration을
|
||||
* exclude 해도 동작
|
||||
*/
|
||||
@Bean(name = "apiKeyEntityManagerFactory")
|
||||
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
|
||||
@@ -101,9 +101,8 @@ public class ApiKeyJpaAutoConfiguration {
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서
|
||||
* 'jpaMappingContext'가 없을 때만 보완해준다.
|
||||
*
|
||||
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 'jpaMappingContext'가 없을 때만 보완해준다.
|
||||
* <p>
|
||||
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
|
||||
*/
|
||||
@Bean(name = "jpaMappingContext")
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.auth.apikey")
|
||||
@@ -17,41 +16,60 @@ public class ApiKeyProperties {
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* API Key 를 읽어올 헤더 이름
|
||||
* 예: X-API-Key, X-EXTERNAL-KEY 등
|
||||
* API Key 를 읽어올 헤더 이름 예: X-API-Key, X-EXTERNAL-KEY 등
|
||||
*/
|
||||
private String headerName = "X-API-Key";
|
||||
|
||||
/** 이 서비스의 코드 (서비스별 preload 범위 결정) */
|
||||
/**
|
||||
* 이 서비스의 코드 (서비스별 preload 범위 결정)
|
||||
*/
|
||||
private String serviceCode;
|
||||
|
||||
/** 기동 시 preload 할지 */
|
||||
/**
|
||||
* 기동 시 preload 할지
|
||||
*/
|
||||
private boolean preloadOnStartup = false;
|
||||
|
||||
/** 내부 관리 API(리로드/조회) 노출 여부 */
|
||||
/**
|
||||
* 내부 관리 API(리로드/조회) 노출 여부
|
||||
*/
|
||||
private boolean adminApiEnabled = false;
|
||||
|
||||
/** 내부 관리 API 접근 허용 IP(CIDR) */
|
||||
/**
|
||||
* 내부 관리 API 접근 허용 IP(CIDR)
|
||||
*/
|
||||
private List<String> adminAllowIps = List.of("127.0.0.1/32");
|
||||
|
||||
/** apikey 전용 DB 설정(기본값 포함) */
|
||||
/**
|
||||
* apikey 전용 DB 설정(기본값 포함)
|
||||
*/
|
||||
private Db db = new Db();
|
||||
|
||||
/** apikey 전용 JPA 옵션 */
|
||||
/**
|
||||
* apikey 전용 JPA 옵션
|
||||
*/
|
||||
private Jpa jpa = new Jpa();
|
||||
|
||||
@Getter @Setter
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Jpa {
|
||||
/** hibernate.show_sql */
|
||||
|
||||
/**
|
||||
* hibernate.show_sql
|
||||
*/
|
||||
private boolean showSql = false;
|
||||
|
||||
/** hibernate.format_sql */
|
||||
/**
|
||||
* hibernate.format_sql
|
||||
*/
|
||||
private boolean formatSql = false;
|
||||
}
|
||||
|
||||
|
||||
@Getter @Setter
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Db {
|
||||
|
||||
//내부 통신용 url
|
||||
private String url =
|
||||
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
|
||||
|
||||
@@ -4,8 +4,8 @@ import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스.
|
||||
* 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다.
|
||||
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면
|
||||
* 된다.
|
||||
*/
|
||||
public interface ApiKeyUserClaimsProvider {
|
||||
|
||||
|
||||
@@ -3,23 +3,25 @@ package com.kri.common.auth.apikey;
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||
import com.kri.common.auth.persistence.repository.ApiKeyRepository;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
|
||||
public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider, ApplicationRunner {
|
||||
public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider,
|
||||
ApplicationRunner {
|
||||
|
||||
private final ApiKeyProperties props;
|
||||
private final ApiKeyRepository repo;
|
||||
|
||||
/** 캐시를 통째로 교체(swap)하기 위한 AtomicReference */
|
||||
/**
|
||||
* 캐시를 통째로 교체(swap)하기 위한 AtomicReference
|
||||
*/
|
||||
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
|
||||
new AtomicReference<>(Collections.emptyMap());
|
||||
|
||||
@@ -28,22 +30,34 @@ public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvid
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
/** 런타임에는 DB 조회 금지: 캐시만 조회 */
|
||||
/**
|
||||
* 런타임에는 DB 조회 금지: 캐시만 조회
|
||||
*/
|
||||
@Override
|
||||
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
||||
if (!StringUtils.hasText(apiKey)) return Optional.empty();
|
||||
if (!StringUtils.hasText(apiKey)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(cacheRef.get().get(apiKey));
|
||||
}
|
||||
|
||||
/** 기동 시 preload */
|
||||
/**
|
||||
* 기동 시 preload
|
||||
*/
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (!props.isEnabled()) return;
|
||||
if (!props.isPreloadOnStartup()) return;
|
||||
if (!props.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (!props.isPreloadOnStartup()) {
|
||||
return;
|
||||
}
|
||||
reloadFromDb();
|
||||
}
|
||||
|
||||
/** 운영용: DB에서 다시 읽어 캐시 전체 교체 */
|
||||
/**
|
||||
* 운영용: DB에서 다시 읽어 캐시 전체 교체
|
||||
*/
|
||||
public synchronized int reloadFromDb() {
|
||||
if (!StringUtils.hasText(props.getServiceCode())) {
|
||||
// serviceCode 없으면 preload 불가 → 안전하게 빈 캐시
|
||||
@@ -68,7 +82,9 @@ public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvid
|
||||
return next.size();
|
||||
}
|
||||
|
||||
/** Admin 조회용(마스킹은 컨트롤러에서) */
|
||||
/**
|
||||
* Admin 조회용(마스킹은 컨트롤러에서)
|
||||
*/
|
||||
public Map<String, JwtUserClaimsDto> snapshot() {
|
||||
return cacheRef.get();
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ public class JwtAutoConfiguration {
|
||||
}
|
||||
|
||||
/**
|
||||
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성.
|
||||
* (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행)
|
||||
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서
|
||||
* addFilterBefore 로 수행)
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.kri.common.auth.jwt;
|
||||
|
||||
import lombok.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
package com.kri.common.auth.jwt;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.crypto.SecretKey;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 공통 JWT 유틸 서비스
|
||||
* - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱
|
||||
* - 일반 JWT + 내부 고정 토큰 둘 다 지원
|
||||
* 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class JwtService {
|
||||
@@ -31,7 +37,8 @@ public class JwtService {
|
||||
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
|
||||
String secret = properties.getSecret();
|
||||
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
|
||||
throw new IllegalStateException("kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256");
|
||||
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));
|
||||
@@ -69,11 +76,10 @@ public class JwtService {
|
||||
// ======================================================
|
||||
// 토큰 생성 (DTO 기반)
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* JwtUserClaimsDto 기반 Access Token 생성
|
||||
* - subject = userId
|
||||
* - claims:
|
||||
* userId, userCmpn, userTeam, userName, role
|
||||
* JwtUserClaimsDto 기반 Access Token 생성 - subject = userId - claims: userId, userCmpn, userTeam,
|
||||
* userName, role
|
||||
*/
|
||||
public String generateAccessToken(JwtUserClaimsDto userClaims) {
|
||||
Map<String, Object> claims = buildClaims(userClaims);
|
||||
@@ -157,11 +163,8 @@ public class JwtService {
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* DTO → Spring Security Authentication 변환
|
||||
* 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성.
|
||||
* ex) role = 1 → "ROLE_1"
|
||||
* 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면,
|
||||
* 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
|
||||
* DTO → Spring Security Authentication 변환 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. ex) role =
|
||||
* 1 → "ROLE_1" 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면, 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
|
||||
*/
|
||||
public Authentication toAuthentication(JwtUserClaimsDto dto) {
|
||||
String principal = dto.getUserId();
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
package com.kri.common.auth.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "t_api_key")
|
||||
public class TApiKeyEntity {
|
||||
|
||||
@Id
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
/** 1=ACTIVE, 0=REVOKED */
|
||||
/**
|
||||
* 1=ACTIVE, 0=REVOKED
|
||||
*/
|
||||
@Column(name = "status", nullable = false)
|
||||
@ColumnDefault("1")
|
||||
private Short status;
|
||||
|
||||
@@ -11,10 +11,15 @@ import lombok.Setter;
|
||||
@Entity
|
||||
@Table(name = "t_api_key_service_map")
|
||||
public class TApiKeyServiceMapEntity {
|
||||
|
||||
@EmbeddedId
|
||||
private TApiKeyServiceMapEntityId id;
|
||||
|
||||
public String getApiKey() { return id.getApiKey(); }
|
||||
public String getApiKey() {
|
||||
return id.getApiKey();
|
||||
}
|
||||
|
||||
public String getServiceCode() { return id.getServiceCode(); }
|
||||
public String getServiceCode() {
|
||||
return id.getServiceCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,17 +3,17 @@ package com.kri.common.auth.persistence.entity;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.Hibernate;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Embeddable
|
||||
public class TApiKeyServiceMapEntityId implements Serializable {
|
||||
|
||||
@NotNull
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
@@ -24,8 +24,12 @@ public class TApiKeyServiceMapEntityId implements Serializable {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
|
||||
return false;
|
||||
}
|
||||
TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o;
|
||||
return Objects.equals(this.apiKey, entity.apiKey) &&
|
||||
Objects.equals(this.serviceCode, entity.serviceCode);
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
package com.kri.common.auth.persistence.repository;
|
||||
|
||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> {
|
||||
/** ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 */
|
||||
|
||||
/**
|
||||
* ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에
|
||||
*/
|
||||
@Query("""
|
||||
select a
|
||||
from TApiKeyEntity a
|
||||
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
|
||||
where a.status = 1 and m.id.serviceCode = :serviceCode
|
||||
""")
|
||||
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode")String serviceCode);
|
||||
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode") String serviceCode);
|
||||
}
|
||||
|
||||
@@ -1,24 +1,25 @@
|
||||
package com.kri.common.cache;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
public abstract class AbstractListCache<T> {
|
||||
|
||||
private List<T> list = List.of();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private List<T> list = List.of();
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional(readOnly = true)
|
||||
public void loadOnStartup() {
|
||||
List<T> tempList = loadFromDb();
|
||||
if(tempList != null) setList(tempList);
|
||||
if (tempList != null) {
|
||||
setList(tempList);
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
@@ -30,25 +31,6 @@ public abstract class AbstractListCache<T> {
|
||||
}
|
||||
}
|
||||
|
||||
@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 setList(List<T> next) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
@@ -58,8 +40,29 @@ public abstract class AbstractListCache<T> {
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
if (items == null || items.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||
@@ -71,7 +74,9 @@ public abstract class AbstractListCache<T> {
|
||||
}
|
||||
|
||||
public void addAll(int index, Collection<? extends T> items) {
|
||||
if (items == null || items.isEmpty()) return;
|
||||
if (items == null || items.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
@@ -95,10 +100,10 @@ public abstract class AbstractListCache<T> {
|
||||
}
|
||||
}
|
||||
|
||||
public void add(int index, T item){
|
||||
public void add(int index, T item) {
|
||||
lock.writeLock().lock();
|
||||
|
||||
try{
|
||||
try {
|
||||
ArrayList<T> next = new ArrayList<>(this.list);
|
||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
||||
next.add(i, item);
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
package com.kri.common.cache;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
public abstract class AbstractMapCache<K, V> {
|
||||
|
||||
private Map<K, V> map = Map.of();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private Map<K, V> map = Map.of();
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional(readOnly = true)
|
||||
public void loadOnStartup() {
|
||||
Map<K, V> tempMap = loadFromDb();
|
||||
if(tempMap != null) setMap(tempMap);
|
||||
if (tempMap != null) {
|
||||
setMap(tempMap);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<K, V> getMap() {
|
||||
@@ -29,6 +30,18 @@ public abstract class AbstractMapCache<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 수동: 전체 교체(불변 스냅샷으로 보관)
|
||||
*/
|
||||
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 {
|
||||
@@ -50,23 +63,13 @@ public abstract class AbstractMapCache<K, V> {
|
||||
@Transactional(readOnly = true)
|
||||
public Map<K, V> reload() {
|
||||
Map<K, V> tempMap = loadFromDb();
|
||||
if(tempMap == null) {
|
||||
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 {
|
||||
@@ -78,9 +81,13 @@ public abstract class AbstractMapCache<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체) */
|
||||
/**
|
||||
* 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체)
|
||||
*/
|
||||
public void putAll(Map<K, V> entries) {
|
||||
if (entries == null || entries.isEmpty()) return;
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
@@ -92,7 +99,9 @@ public abstract class AbstractMapCache<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
/** clear: 완전 비우기 */
|
||||
/**
|
||||
* clear: 완전 비우기
|
||||
*/
|
||||
public void clear() {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
|
||||
@@ -1,50 +1,69 @@
|
||||
package com.kri.common.datetime;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DateTimeUtil {
|
||||
|
||||
private DateTimeUtil() {}
|
||||
|
||||
public static final ZoneId KST = ZoneId.of("Asia/Seoul");
|
||||
public static final ZoneId UTC = ZoneOffset.UTC;
|
||||
|
||||
/** 날짜+시간: 2025-11-28 15:00:14 */
|
||||
/**
|
||||
* 날짜+시간: 2025-11-28 15:00:14
|
||||
*/
|
||||
public static final DateTimeFormatter DATETIME_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
/** 날짜: 2025-11-28 */
|
||||
/**
|
||||
* 날짜: 2025-11-28
|
||||
*/
|
||||
public static final DateTimeFormatter DATE_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
private DateTimeUtil() {
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Now (KST)
|
||||
* ======================= */
|
||||
|
||||
/** 현재 KST 날짜+시간 문자열 */
|
||||
/**
|
||||
* 현재 KST 날짜+시간 문자열
|
||||
*/
|
||||
public static String nowKstDateTime() {
|
||||
return formatKst(Instant.now(), DATETIME_FMT);
|
||||
}
|
||||
|
||||
/** 현재 KST 날짜 문자열 */
|
||||
/**
|
||||
* 현재 KST 날짜 문자열
|
||||
*/
|
||||
public static String nowKstDate() {
|
||||
return nowKstZoned().format(DATE_FMT);
|
||||
}
|
||||
|
||||
/** 현재 KST ZonedDateTime */
|
||||
/**
|
||||
* 현재 KST ZonedDateTime
|
||||
*/
|
||||
public static ZonedDateTime nowKstZoned() {
|
||||
return Instant.now().atZone(KST);
|
||||
}
|
||||
|
||||
/** 현재 KST LocalDateTime */
|
||||
/**
|
||||
* 현재 KST LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime nowKstLocalDateTime() {
|
||||
return nowKstZoned().toLocalDateTime();
|
||||
}
|
||||
|
||||
/** 현재 KST LocalDate */
|
||||
/**
|
||||
* 현재 KST LocalDate
|
||||
*/
|
||||
public static LocalDate nowKstLocalDate() {
|
||||
return nowKstZoned().toLocalDate();
|
||||
}
|
||||
@@ -53,19 +72,27 @@ public final class DateTimeUtil {
|
||||
* Format (Instant -> String)
|
||||
* ======================= */
|
||||
|
||||
/** Instant -> KST 날짜+시간 문자열 */
|
||||
/**
|
||||
* Instant -> KST 날짜+시간 문자열
|
||||
*/
|
||||
public static String formatKstDateTime(Instant instant) {
|
||||
return formatKst(instant, DATETIME_FMT);
|
||||
}
|
||||
|
||||
/** Instant -> KST 날짜 문자열 */
|
||||
/**
|
||||
* Instant -> KST 날짜 문자열
|
||||
*/
|
||||
public static String formatKstDate(Instant instant) {
|
||||
return formatKst(instant, DATE_FMT);
|
||||
}
|
||||
|
||||
/** Instant -> KST 문자열 (커스텀 포맷) */
|
||||
/**
|
||||
* Instant -> KST 문자열 (커스텀 포맷)
|
||||
*/
|
||||
public static String formatKst(Instant instant, DateTimeFormatter formatter) {
|
||||
if (instant == null) return null;
|
||||
if (instant == null) {
|
||||
return null;
|
||||
}
|
||||
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
|
||||
return instant.atZone(KST).format(fmt);
|
||||
}
|
||||
@@ -74,24 +101,44 @@ public final class DateTimeUtil {
|
||||
* Validate
|
||||
* ======================= */
|
||||
|
||||
/** "yyyy-MM-dd" 형태인지 */
|
||||
/**
|
||||
* "yyyy-MM-dd" 형태인지
|
||||
*/
|
||||
public static boolean isDate(String text) {
|
||||
return tryParseLocalDate(text, DATE_FMT) != null;
|
||||
}
|
||||
|
||||
/** "yyyy-MM-dd HH:mm:ss" 형태인지 */
|
||||
/**
|
||||
* "yyyy-MM-dd HH:mm:ss" 형태인지
|
||||
*/
|
||||
public static boolean isDateTime(String text) {
|
||||
return tryParseLocalDateTime(text, DATETIME_FMT) != null;
|
||||
}
|
||||
|
||||
/** ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지 */
|
||||
/**
|
||||
* ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지
|
||||
*/
|
||||
public static boolean isIsoDateTime(String text) {
|
||||
if (text == null || text.isBlank()) return false;
|
||||
if (text == null || text.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final String s = text.trim();
|
||||
try { Instant.parse(s); return true; } catch (DateTimeParseException ignored) {}
|
||||
try { OffsetDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {}
|
||||
try { ZonedDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {}
|
||||
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;
|
||||
}
|
||||
@@ -100,38 +147,58 @@ public final class DateTimeUtil {
|
||||
* Parse (String -> Instant)
|
||||
* ======================= */
|
||||
|
||||
/** ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도) */
|
||||
/**
|
||||
* ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도)
|
||||
*/
|
||||
public static Instant parseToInstant(String text) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
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) {}
|
||||
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
|
||||
* 커스텀 포맷 문자열을 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;
|
||||
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로 해석 */
|
||||
/**
|
||||
* "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)으로 해석 */
|
||||
/**
|
||||
* "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석
|
||||
*/
|
||||
public static Instant parseKstDateToInstant(String text) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT);
|
||||
return ld.atStartOfDay(KST).toInstant();
|
||||
}
|
||||
@@ -140,26 +207,36 @@ public final class DateTimeUtil {
|
||||
* Convert / Helpers
|
||||
* ======================= */
|
||||
|
||||
/** Instant -> KST ZonedDateTime */
|
||||
/**
|
||||
* Instant -> KST ZonedDateTime
|
||||
*/
|
||||
public static ZonedDateTime toKstZoned(Instant instant) {
|
||||
return instant == null ? null : instant.atZone(KST);
|
||||
}
|
||||
|
||||
/** Instant -> KST LocalDateTime */
|
||||
/**
|
||||
* Instant -> KST LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime toKstLocalDateTime(Instant instant) {
|
||||
ZonedDateTime zdt = toKstZoned(instant);
|
||||
return zdt == null ? null : zdt.toLocalDateTime();
|
||||
}
|
||||
|
||||
/** Instant -> KST LocalDate */
|
||||
/**
|
||||
* Instant -> KST LocalDate
|
||||
*/
|
||||
public static LocalDate toKstLocalDate(Instant instant) {
|
||||
ZonedDateTime zdt = toKstZoned(instant);
|
||||
return zdt == null ? null : zdt.toLocalDate();
|
||||
}
|
||||
|
||||
/** null/blank 안전 trim */
|
||||
/**
|
||||
* null/blank 안전 trim
|
||||
*/
|
||||
public static String trimToNull(String s) {
|
||||
if (s == null) return null;
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
String t = s.trim();
|
||||
return t.isEmpty() ? null : t;
|
||||
}
|
||||
@@ -173,14 +250,24 @@ public final class DateTimeUtil {
|
||||
}
|
||||
|
||||
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; }
|
||||
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; }
|
||||
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.databind.annotation.JsonDeserialize;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
@@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -62,12 +61,15 @@ public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDate
|
||||
@Override
|
||||
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
String s = DateTimeUtil.trimToNull(p.getText());
|
||||
if (s == null) return null;
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (DateTimeFormatter f : formatters) {
|
||||
try {
|
||||
return LocalDateTime.parse(s, f);
|
||||
} catch (DateTimeParseException ignored) {}
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
throw ctxt.weirdStringException(s, LocalDateTime.class,
|
||||
@@ -77,10 +79,14 @@ public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDate
|
||||
@Override
|
||||
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
|
||||
throws JsonMappingException {
|
||||
if (property == null) return this;
|
||||
if (property == null) {
|
||||
return this;
|
||||
}
|
||||
|
||||
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
|
||||
if (ann == null) ann = property.getContextAnnotation(LenientLocalDateTime.class);
|
||||
if (ann == null) {
|
||||
ann = property.getContextAnnotation(LenientLocalDateTime.class);
|
||||
}
|
||||
|
||||
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kri.common.enums;
|
||||
|
||||
public interface CodeEnum<T> {
|
||||
|
||||
T getCode();
|
||||
}
|
||||
@@ -2,10 +2,13 @@ package com.kri.common.enums;
|
||||
|
||||
public final class CodeEnumUtils {
|
||||
|
||||
private CodeEnumUtils() {}
|
||||
private CodeEnumUtils() {
|
||||
}
|
||||
|
||||
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)) {
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
package com.kri.common.excel;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface ExcelColumn {
|
||||
|
||||
String header(); // 엑셀 헤더 이름
|
||||
|
||||
int order() default 0; // 컬럼 순서
|
||||
|
||||
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
|
||||
}
|
||||
@@ -1,7 +1,25 @@
|
||||
package com.kri.common.excel;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.apache.poi.openxml4j.opc.OPCPackage;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.RichTextString;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.util.CellReference;
|
||||
import org.apache.poi.xssf.eventusermodel.XSSFReader;
|
||||
import org.apache.poi.xssf.model.SharedStringsTable;
|
||||
@@ -13,18 +31,11 @@ import org.xml.sax.XMLReader;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
import org.xml.sax.helpers.XMLReaderFactory;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Excel <-> 객체/맵 변환 유틸리티
|
||||
*
|
||||
* 전제:
|
||||
* - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다.
|
||||
* - 셀 값 파싱은 ExcelUtil.getStringCell(Cell) 사용.
|
||||
* <p>
|
||||
* 전제: - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다. - 셀 값 파싱은
|
||||
* ExcelUtil.getStringCell(Cell) 사용.
|
||||
*/
|
||||
public final class ExcelMapper {
|
||||
|
||||
@@ -107,14 +118,18 @@ public final class ExcelMapper {
|
||||
|
||||
for (int r = 1; r <= lastRowNum; r++) {
|
||||
Row row = sheet.getRow(r);
|
||||
if (row == null) continue;
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
T instance = clazz.getDeclaredConstructor().newInstance();
|
||||
|
||||
for (ExcelFieldMeta meta : fields) {
|
||||
Integer colIdx = headerIndexMap.get(meta.header());
|
||||
if (colIdx == null) continue;
|
||||
if (colIdx == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Cell cell = row.getCell(colIdx);
|
||||
String cellValue = ExcelUtil.getStringCell(cell);
|
||||
@@ -159,7 +174,9 @@ public final class ExcelMapper {
|
||||
|
||||
for (int r = 1; r <= lastRow; r++) {
|
||||
Row row = sheet.getRow(r);
|
||||
if (row == null) continue;
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Map<String, String> rowMap = new LinkedHashMap<>();
|
||||
boolean allBlank = true;
|
||||
@@ -214,7 +231,9 @@ public final class ExcelMapper {
|
||||
int rowIndex = 1;
|
||||
for (Map<String, ?> rowMap : rows) {
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
if (rowMap == null) continue;
|
||||
if (rowMap == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int c = 0; c < headers.size(); c++) {
|
||||
String key = headers.get(c);
|
||||
@@ -291,7 +310,8 @@ public final class ExcelMapper {
|
||||
* 5-1. Streaming Append Writer (SXSSFWorkbook) - DTO 기반 (chunk 지원)
|
||||
* ========================================================= */
|
||||
|
||||
public static <T> StreamingWriter<T> openStreamingWriter(Class<T> clazz, int rowAccessWindowSize) {
|
||||
public static <T> StreamingWriter<T> openStreamingWriter(Class<T> clazz,
|
||||
int rowAccessWindowSize) {
|
||||
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
|
||||
Sheet sheet = workbook.createSheet("Sheet1");
|
||||
|
||||
@@ -311,60 +331,6 @@ public final class ExcelMapper {
|
||||
return new StreamingWriter<>(workbook, sheet, fields, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* chunk 단위로 append 가능한 SXSSF Writer
|
||||
* - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush
|
||||
* - 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성
|
||||
*/
|
||||
public static final class StreamingWriter<T> implements AutoCloseable {
|
||||
private final SXSSFWorkbook workbook;
|
||||
private final Sheet sheet;
|
||||
private final List<ExcelFieldMeta> fields;
|
||||
private int rowIndex;
|
||||
|
||||
private StreamingWriter(SXSSFWorkbook workbook, Sheet sheet, List<ExcelFieldMeta> fields, int rowIndex) {
|
||||
this.workbook = workbook;
|
||||
this.sheet = sheet;
|
||||
this.fields = fields;
|
||||
this.rowIndex = rowIndex;
|
||||
}
|
||||
|
||||
public void append(T item) {
|
||||
if (item == null) return;
|
||||
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
for (ExcelFieldMeta meta : fields) {
|
||||
Cell cell = row.createCell(meta.order());
|
||||
Object value = meta.getValue(item);
|
||||
if (value != null) cell.setCellValue(value.toString());
|
||||
else cell.setBlank();
|
||||
}
|
||||
}
|
||||
|
||||
public void appendAll(Collection<T> items) {
|
||||
if (items == null || items.isEmpty()) return;
|
||||
for (T item : items) append(item);
|
||||
}
|
||||
|
||||
/** XLSX는 마지막에 한 번 write 해야 파일이 완성됩니다. */
|
||||
public void writeTo(OutputStream out) throws IOException {
|
||||
workbook.write(out);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
// SXSSF temp 파일 제거
|
||||
workbook.dispose();
|
||||
workbook.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* =========================================================
|
||||
* 6. Streaming Write (SXSSFWorkbook) - Map 기반
|
||||
* ========================================================= */
|
||||
|
||||
public static SXSSFWorkbook writeStreamingFromMap(List<? extends Map<String, ?>> rows,
|
||||
int rowAccessWindowSize) {
|
||||
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
|
||||
@@ -393,7 +359,9 @@ public final class ExcelMapper {
|
||||
int rowIndex = 1;
|
||||
for (Map<String, ?> rowMap : rows) {
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
if (rowMap == null) continue;
|
||||
if (rowMap == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int c = 0; c < headers.size(); c++) {
|
||||
String key = headers.get(c);
|
||||
@@ -407,23 +375,13 @@ public final class ExcelMapper {
|
||||
return workbook;
|
||||
}
|
||||
|
||||
|
||||
/* =========================================================
|
||||
* 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler
|
||||
* 6. Streaming Write (SXSSFWorkbook) - Map 기반
|
||||
* ========================================================= */
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RowMapHandler {
|
||||
/**
|
||||
* @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터)
|
||||
* @param rowIndex 엑셀 실제 행 번호 (1-based)
|
||||
*/
|
||||
void handleRow(Map<String, String> row, int rowIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* XSSFReader + SAX 기반 스트리밍 읽기.
|
||||
* - 첫 번째 시트만 읽음.
|
||||
* - 1행은 헤더, 2행부터 데이터로 가정.
|
||||
* XSSFReader + SAX 기반 스트리밍 읽기. - 첫 번째 시트만 읽음. - 1행은 헤더, 2행부터 데이터로 가정.
|
||||
*/
|
||||
public static void readStreaming(InputStream inputStream, RowMapHandler handler) {
|
||||
try {
|
||||
@@ -449,20 +407,163 @@ public final class ExcelMapper {
|
||||
}
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler
|
||||
* ========================================================= */
|
||||
|
||||
private static List<ExcelFieldMeta> getExcelFields(Class<?> clazz) {
|
||||
List<ExcelFieldMeta> result = new ArrayList<>();
|
||||
|
||||
for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) {
|
||||
for (Field field : c.getDeclaredFields()) {
|
||||
ExcelColumn ann = field.getAnnotation(ExcelColumn.class);
|
||||
if (ann == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
field.setAccessible(true);
|
||||
result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width()));
|
||||
}
|
||||
}
|
||||
|
||||
result.sort(Comparator.comparingInt(ExcelFieldMeta::order));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void setFieldValue(Object target, Field field, String value)
|
||||
throws IllegalAccessException {
|
||||
Class<?> type = field.getType();
|
||||
|
||||
// 1) null 또는 공백 처리
|
||||
if (value == null || value.isBlank()) {
|
||||
// primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴
|
||||
if (type.isPrimitive()) {
|
||||
return;
|
||||
}
|
||||
// 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅
|
||||
field.set(target, null);
|
||||
return;
|
||||
}
|
||||
|
||||
String trimmed = value.trim();
|
||||
|
||||
try {
|
||||
if (type == String.class) {
|
||||
field.set(target, trimmed);
|
||||
|
||||
} else if (type == Integer.class || type == int.class) {
|
||||
field.set(target, Integer.parseInt(trimmed));
|
||||
|
||||
} else if (type == Long.class || type == long.class) {
|
||||
field.set(target, Long.parseLong(trimmed));
|
||||
|
||||
} else if (type == Boolean.class || type == boolean.class) {
|
||||
// "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능
|
||||
field.set(target, Boolean.parseBoolean(trimmed));
|
||||
|
||||
} else {
|
||||
// TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장
|
||||
field.set(target, trimmed);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
// 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함
|
||||
throw new RuntimeException(
|
||||
"엑셀 값 파싱 실패: field=" + field.getName() +
|
||||
", type=" + type.getSimpleName() +
|
||||
", value='" + value + "'",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RowMapHandler {
|
||||
|
||||
/**
|
||||
* @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터)
|
||||
* @param rowIndex 엑셀 실제 행 번호 (1-based)
|
||||
*/
|
||||
void handleRow(Map<String, String> row, int rowIndex);
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 8. 내부 메타 수집 & 필드 세터
|
||||
* ========================================================= */
|
||||
|
||||
/**
|
||||
* chunk 단위로 append 가능한 SXSSF Writer - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush -
|
||||
* 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성
|
||||
*/
|
||||
public static final class StreamingWriter<T> implements AutoCloseable {
|
||||
|
||||
private final SXSSFWorkbook workbook;
|
||||
private final Sheet sheet;
|
||||
private final List<ExcelFieldMeta> fields;
|
||||
private int rowIndex;
|
||||
|
||||
private StreamingWriter(SXSSFWorkbook workbook, Sheet sheet, List<ExcelFieldMeta> fields,
|
||||
int rowIndex) {
|
||||
this.workbook = workbook;
|
||||
this.sheet = sheet;
|
||||
this.fields = fields;
|
||||
this.rowIndex = rowIndex;
|
||||
}
|
||||
|
||||
public void append(T item) {
|
||||
if (item == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
for (ExcelFieldMeta meta : fields) {
|
||||
Cell cell = row.createCell(meta.order());
|
||||
Object value = meta.getValue(item);
|
||||
if (value != null) {
|
||||
cell.setCellValue(value.toString());
|
||||
} else {
|
||||
cell.setBlank();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void appendAll(Collection<T> items) {
|
||||
if (items == null || items.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (T item : items) {
|
||||
append(item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* XLSX는 마지막에 한 번 write 해야 파일이 완성됩니다.
|
||||
*/
|
||||
public void writeTo(OutputStream out) throws IOException {
|
||||
workbook.write(out);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
// SXSSF temp 파일 제거
|
||||
workbook.dispose();
|
||||
workbook.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SAX 핸들러: 한 행을 Map<String,String> 으로 만들어 RowMapHandler에 전달.
|
||||
*/
|
||||
private static class SheetToMapHandler extends DefaultHandler {
|
||||
|
||||
private final SharedStringsTable sst;
|
||||
private final RowMapHandler handler;
|
||||
|
||||
private final Map<Integer, String> cellMap = new HashMap<>();
|
||||
private int currentRowNum;
|
||||
private String currentCellRef;
|
||||
private String currentCellType;
|
||||
private StringBuilder currentValue;
|
||||
private boolean isValueOpen;
|
||||
|
||||
private final Map<Integer, String> cellMap = new HashMap<>();
|
||||
private List<String> headers = new ArrayList<>();
|
||||
private boolean headerProcessed = false;
|
||||
|
||||
@@ -523,7 +624,9 @@ public final class ExcelMapper {
|
||||
}
|
||||
headerProcessed = true;
|
||||
} else {
|
||||
if (headers == null || headers.isEmpty()) return;
|
||||
if (headers == null || headers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, String> rowMap = new LinkedHashMap<>();
|
||||
boolean allBlank = true;
|
||||
@@ -557,73 +660,8 @@ public final class ExcelMapper {
|
||||
}
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 8. 내부 메타 수집 & 필드 세터
|
||||
* ========================================================= */
|
||||
|
||||
private static List<ExcelFieldMeta> getExcelFields(Class<?> clazz) {
|
||||
List<ExcelFieldMeta> result = new ArrayList<>();
|
||||
|
||||
for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) {
|
||||
for (Field field : c.getDeclaredFields()) {
|
||||
ExcelColumn ann = field.getAnnotation(ExcelColumn.class);
|
||||
if (ann == null) continue;
|
||||
|
||||
field.setAccessible(true);
|
||||
result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width()));
|
||||
}
|
||||
}
|
||||
|
||||
result.sort(Comparator.comparingInt(ExcelFieldMeta::order));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void setFieldValue(Object target, Field field, String value) throws IllegalAccessException {
|
||||
Class<?> type = field.getType();
|
||||
|
||||
// 1) null 또는 공백 처리
|
||||
if (value == null || value.isBlank()) {
|
||||
// primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴
|
||||
if (type.isPrimitive()) {
|
||||
return;
|
||||
}
|
||||
// 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅
|
||||
field.set(target, null);
|
||||
return;
|
||||
}
|
||||
|
||||
String trimmed = value.trim();
|
||||
|
||||
try {
|
||||
if (type == String.class) {
|
||||
field.set(target, trimmed);
|
||||
|
||||
} else if (type == Integer.class || type == int.class) {
|
||||
field.set(target, Integer.parseInt(trimmed));
|
||||
|
||||
} else if (type == Long.class || type == long.class) {
|
||||
field.set(target, Long.parseLong(trimmed));
|
||||
|
||||
} else if (type == Boolean.class || type == boolean.class) {
|
||||
// "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능
|
||||
field.set(target, Boolean.parseBoolean(trimmed));
|
||||
|
||||
} else {
|
||||
// TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장
|
||||
field.set(target, trimmed);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
// 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함
|
||||
throw new RuntimeException(
|
||||
"엑셀 값 파싱 실패: field=" + field.getName() +
|
||||
", type=" + type.getSimpleName() +
|
||||
", value='" + value + "'",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private record ExcelFieldMeta(Field field, String header, int order, int width) {
|
||||
|
||||
Object getValue(Object target) {
|
||||
try {
|
||||
return field.get(target);
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
package com.kri.common.excel;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
|
||||
public final class ExcelUtil {
|
||||
|
||||
private ExcelUtil() {}
|
||||
private ExcelUtil() {
|
||||
}
|
||||
|
||||
public static String getStringCell(Cell cell) {
|
||||
if (cell == null) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.kri.common.file;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class FileUtil {
|
||||
|
||||
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
|
||||
|
||||
/**
|
||||
@@ -26,7 +27,9 @@ public final class FileUtil {
|
||||
}
|
||||
|
||||
public static String getExtension(String fileName) {
|
||||
if (fileName == null) return "";
|
||||
if (fileName == null) {
|
||||
return "";
|
||||
}
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
if (dot < 0 || dot == fileName.length() - 1) {
|
||||
return "";
|
||||
@@ -35,7 +38,9 @@ public final class FileUtil {
|
||||
}
|
||||
|
||||
public static String extractFileNameFromPath(String pathLike) {
|
||||
if (pathLike == null || pathLike.isBlank()) return "";
|
||||
if (pathLike == null || pathLike.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String s = pathLike;
|
||||
int q = s.indexOf('?');
|
||||
if (q >= 0) {
|
||||
|
||||
@@ -9,10 +9,8 @@ import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 간단한 외부 API 통신 모듈.
|
||||
* - url, 추가 헤더, body를 받아 호출합니다.
|
||||
* - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다.
|
||||
* - body는 문자열(JSON 등) 기준입니다.
|
||||
* 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. -
|
||||
* body는 문자열(JSON 등) 기준입니다.
|
||||
*/
|
||||
public class ExternalApiClient {
|
||||
|
||||
@@ -36,6 +34,17 @@ public class ExternalApiClient {
|
||||
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
|
||||
}
|
||||
|
||||
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
|
||||
// GET/DELETE 등 body 없는 메서드는 noBody 사용
|
||||
if (body == null || body.isEmpty()) {
|
||||
return switch (method) {
|
||||
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
|
||||
default -> HttpRequest.BodyPublishers.noBody();
|
||||
};
|
||||
}
|
||||
return HttpRequest.BodyPublishers.ofString(body);
|
||||
}
|
||||
|
||||
public ExternalApiResponse get(String url, Map<String, String> headers) {
|
||||
return send("GET", url, headers, null);
|
||||
}
|
||||
@@ -56,7 +65,8 @@ public class ExternalApiClient {
|
||||
return send("PATCH", url, headers, body);
|
||||
}
|
||||
|
||||
private ExternalApiResponse send(String method, String url, Map<String, String> headers, String body) {
|
||||
private ExternalApiResponse send(String method, String url, Map<String, String> headers,
|
||||
String body) {
|
||||
try {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
@@ -66,7 +76,9 @@ public class ExternalApiClient {
|
||||
// 추가 헤더 설정
|
||||
if (headers != null) {
|
||||
headers.forEach((k, v) -> {
|
||||
if (k != null && v != null) builder.header(k, v);
|
||||
if (k != null && v != null) {
|
||||
builder.header(k, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -81,19 +93,10 @@ public class ExternalApiClient {
|
||||
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
||||
} catch (IOException | InterruptedException e) {
|
||||
// 인터럽트 복원
|
||||
if (e instanceof InterruptedException) Thread.currentThread().interrupt();
|
||||
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,6 +8,7 @@ import java.util.Map;
|
||||
* 외부 API 호출 결과를 단순하게 담는 DTO.
|
||||
*/
|
||||
public class ExternalApiResponse {
|
||||
|
||||
private final int statusCode;
|
||||
private final Map<String, List<String>> headers;
|
||||
private final String body;
|
||||
@@ -18,6 +19,10 @@ public class ExternalApiResponse {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
||||
return new ExternalApiResponse(status, headers.map(), body);
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
@@ -29,8 +34,4 @@ public class ExternalApiResponse {
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
||||
return new ExternalApiResponse(status, headers.map(), body);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,23 +2,10 @@ package com.kri.common.jpa;
|
||||
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.PrePersist;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseUuidEntity {
|
||||
protected abstract String getId();
|
||||
protected abstract void setId(String id);
|
||||
|
||||
/** 엔티티마다 컬럼 길이에 맞춰 오버라이드 */
|
||||
protected int idLength() { return 32; }
|
||||
|
||||
@PrePersist
|
||||
protected void prePersistId() {
|
||||
if (getId() == null || getId().isBlank()) {
|
||||
setId(generateId(idLength()));
|
||||
}
|
||||
}
|
||||
|
||||
private static String generateId(int length) {
|
||||
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
|
||||
@@ -34,4 +21,22 @@ public abstract class BaseUuidEntity {
|
||||
}
|
||||
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,7 +3,6 @@ package com.kri.common.json;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
@@ -15,9 +14,8 @@ public final class JsonUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* 임의의 자바 객체를 Map으로 변환한다.
|
||||
* 주의: JSON 문자열(String)을 파싱하는 용도가 아니라,
|
||||
* 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 용도이다.
|
||||
* 임의의 자바 객체를 Map으로 변환한다. 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는
|
||||
* 용도이다.
|
||||
*/
|
||||
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
|
||||
if (source == null) {
|
||||
@@ -38,7 +36,8 @@ public final class JsonUtil {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
@@ -68,8 +67,7 @@ public final class JsonUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 문자열을 주어진 타입으로 역직렬화한다.
|
||||
* ex) fromJson(mapper, json, UserInfoDto.class)
|
||||
* JSON 문자열을 주어진 타입으로 역직렬화한다. ex) fromJson(mapper, json, UserInfoDto.class)
|
||||
*/
|
||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
|
||||
if (json == null || json.isBlank()) {
|
||||
@@ -78,13 +76,14 @@ public final class JsonUtil {
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.",
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 문자열을 제네릭 타입으로 역직렬화한다.
|
||||
* ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>() {})
|
||||
* JSON 문자열을 제네릭 타입으로 역직렬화한다. ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>()
|
||||
* {})
|
||||
*/
|
||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
|
||||
if (json == null || json.isBlank()) {
|
||||
@@ -98,9 +97,8 @@ public final class JsonUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 기반 deep copy (또는 타입 변환).
|
||||
* 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
|
||||
*
|
||||
* JSON 기반 deep copy (또는 타입 변환). 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
|
||||
* <p>
|
||||
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
|
||||
*/
|
||||
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
|
||||
@@ -112,7 +110,7 @@ public final class JsonUtil {
|
||||
|
||||
/**
|
||||
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
|
||||
*
|
||||
* <p>
|
||||
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
|
||||
*/
|
||||
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package com.kri.common.redis;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.*;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.*;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
@AutoConfiguration
|
||||
@ConditionalOnClass(RedisTemplate.class)
|
||||
@@ -12,11 +16,16 @@ import org.springframework.data.redis.core.*;
|
||||
@ConditionalOnBean(RedisConnectionFactory.class)
|
||||
public class CommonRedisAutoConfiguration {
|
||||
|
||||
@Bean @ConditionalOnMissingBean
|
||||
public StringRedisTemplate stringRedisTemplate(org.springframework.data.redis.connection.RedisConnectionFactory cf) {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public StringRedisTemplate stringRedisTemplate(
|
||||
org.springframework.data.redis.connection.RedisConnectionFactory cf) {
|
||||
return new StringRedisTemplate(cf);
|
||||
}
|
||||
|
||||
@Bean @ConditionalOnMissingBean
|
||||
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { return new RedisQueueHelper(rt); }
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) {
|
||||
return new RedisQueueHelper(rt);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
package com.kri.common.redis;
|
||||
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import java.time.Duration;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
public class RedisQueueHelper {
|
||||
|
||||
private final StringRedisTemplate rt;
|
||||
public RedisQueueHelper(StringRedisTemplate rt) { this.rt = rt; }
|
||||
public void enqueue(String key, String value) { rt.opsForList().rightPush(key, value); }
|
||||
public String blockingDequeue(String key, Duration timeout) { return rt.opsForList().leftPop(key, timeout); }
|
||||
|
||||
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
|
||||
@EnableScheduling
|
||||
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||
public class CommonSchedulingAutoConfiguration { }
|
||||
public class CommonSchedulingAutoConfiguration {
|
||||
|
||||
}
|
||||
@@ -6,13 +6,12 @@ import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.kri.common.security;
|
||||
|
||||
import com.kri.common.auth.apikey.ApiKeyAuthFilter;
|
||||
import com.kri.common.auth.apikey.ApiKeyProperties;
|
||||
import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider;
|
||||
import com.kri.common.auth.jwt.JwtProperties;
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -15,10 +13,10 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@AutoConfiguration(before = SecurityAutoConfiguration.class)
|
||||
@@ -47,8 +45,7 @@ public class KriSecurityAutoConfiguration {
|
||||
}
|
||||
|
||||
/**
|
||||
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면
|
||||
* 이 기본 Security 구성이 적용된다.
|
||||
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 이 기본 Security 구성이 적용된다.
|
||||
*/
|
||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||
@Bean
|
||||
@@ -68,8 +65,10 @@ public class KriSecurityAutoConfiguration {
|
||||
)
|
||||
.authorizeHttpRequests(auth -> {
|
||||
// ✅ yaml에서 정의한 public-paths 전부 permitAll
|
||||
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths().isEmpty()) {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)).permitAll();
|
||||
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths()
|
||||
.isEmpty()) {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
|
||||
.permitAll();
|
||||
}
|
||||
// ✅ 나머지는 전부 인증 필요
|
||||
auth.anyRequest().authenticated();
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package com.kri.common.security;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.security")
|
||||
@@ -17,8 +16,7 @@ public class KriSecurityProperties {
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* 인증 없이 허용할 URL 패턴들
|
||||
* 서비스에서 application.yml로 오버라이드
|
||||
* 인증 없이 허용할 URL 패턴들 서비스에서 application.yml로 오버라이드
|
||||
*/
|
||||
private List<String> publicPaths = List.of(
|
||||
"/v3/api-docs/**",
|
||||
|
||||
@@ -9,10 +9,14 @@ public final class CommonUtil {
|
||||
}
|
||||
|
||||
public static boolean isNumeric(String s) {
|
||||
if (s == null || s.isBlank()) return false;
|
||||
if (s == null || s.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (c < '0' || c > '9') return false;
|
||||
if (c < '0' || c > '9') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private final HttpStatus status;
|
||||
private final String code;
|
||||
private final Map<String, Object> extras;
|
||||
|
||||
private static String defaultCode(HttpStatus status) { return status.name(); } // 예: NOT_FOUND, CONFLICT …
|
||||
|
||||
private BusinessException(HttpStatus status, String code, String message,
|
||||
Map<String, Object> extras, Throwable cause) {
|
||||
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
|
||||
@@ -21,10 +20,16 @@ public class BusinessException extends RuntimeException {
|
||||
: Collections.unmodifiableMap(new HashMap<>(extras));
|
||||
}
|
||||
|
||||
private static String defaultCode(HttpStatus status) {
|
||||
return status.name();
|
||||
} // 예: NOT_FOUND, CONFLICT …
|
||||
|
||||
public static BusinessException of(HttpStatus status, String code, String message) {
|
||||
return new BusinessException(status, code, message, null, null);
|
||||
}
|
||||
public static BusinessException of(HttpStatus status, String code, String message, Map<String,Object> extras) {
|
||||
|
||||
public static BusinessException of(HttpStatus status, String code, String message,
|
||||
Map<String, Object> extras) {
|
||||
return new BusinessException(status, code, message, extras, null);
|
||||
}
|
||||
|
||||
@@ -92,11 +97,21 @@ public class BusinessException extends RuntimeException {
|
||||
return internalError("INTERNAL_SERVER_ERROR", message);
|
||||
}
|
||||
|
||||
public HttpStatus getStatus() { return status; }
|
||||
public String getCode() { return code; }
|
||||
public Map<String, Object> getExtras() { return extras; }
|
||||
public HttpStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
/** 편의: 체이닝으로 extras 추가 */
|
||||
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);
|
||||
|
||||
@@ -2,15 +2,21 @@ package com.kri.common.web;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
@AutoConfiguration
|
||||
@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
|
||||
public class CommonWebAutoConfiguration {
|
||||
@Bean public ErrorAdvice errorAdvice() { return new ErrorAdvice(); }
|
||||
@Bean public FilterRegistrationBean<TraceFilter> traceFilter() {
|
||||
|
||||
@Bean
|
||||
public ErrorAdvice errorAdvice() {
|
||||
return new ErrorAdvice();
|
||||
}
|
||||
|
||||
@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.validation.ConstraintViolationException;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
@@ -11,6 +16,8 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ProblemDetail;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.ErrorResponseException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
@@ -18,16 +25,11 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class ErrorAdvice {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
|
||||
|
||||
// 기본값은 모두 false → 외부 응답엔 노출 안 함
|
||||
@@ -36,6 +38,21 @@ public class ErrorAdvice {
|
||||
@Value("${common.error.expose.service:false}")
|
||||
private boolean exposeService;
|
||||
|
||||
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
|
||||
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";
|
||||
}
|
||||
|
||||
/* ---------- 공통 ProblemDetail 빌더 ---------- */
|
||||
protected ProblemDetail pd(HttpStatus status, String code, String message,
|
||||
HttpServletRequest req, Map<String, Object> extras) {
|
||||
@@ -46,19 +63,27 @@ public class ErrorAdvice {
|
||||
p.setProperty("path", req.getRequestURI());
|
||||
|
||||
String traceId = MDC.get("traceId");
|
||||
if (traceId != null) p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
|
||||
if (traceId != null) {
|
||||
p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
|
||||
}
|
||||
|
||||
// ↓↓↓ 외부로 숨기고 싶으면 기본 false
|
||||
if (exposeHandler) {
|
||||
String handler = MDC.get("handler"); // Controller#method
|
||||
if (handler != null) p.setProperty("handler", handler);
|
||||
if (handler != null) {
|
||||
p.setProperty("handler", handler);
|
||||
}
|
||||
}
|
||||
if (exposeService) {
|
||||
String service = MDC.get("service"); // Service#method (최초 진입)
|
||||
if (service != null) p.setProperty("service", service);
|
||||
if (service != null) {
|
||||
p.setProperty("service", service);
|
||||
}
|
||||
}
|
||||
|
||||
if (extras != null) extras.forEach(p::setProperty);
|
||||
if (extras != null) {
|
||||
extras.forEach(p::setProperty);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@@ -100,7 +125,8 @@ public class ErrorAdvice {
|
||||
|
||||
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest req) {
|
||||
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e,
|
||||
HttpServletRequest req) {
|
||||
var fieldErrors = e.getBindingResult().getFieldErrors().stream()
|
||||
.map(fe -> Map.of(
|
||||
"field", fe.getField(),
|
||||
@@ -125,15 +151,18 @@ public class ErrorAdvice {
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, HttpServletRequest req) {
|
||||
String need = (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
|
||||
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e,
|
||||
HttpServletRequest req) {
|
||||
String need =
|
||||
(e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
|
||||
String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need;
|
||||
return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null);
|
||||
}
|
||||
|
||||
/* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ProblemDetail handleConstraintViolation(ConstraintViolationException e, HttpServletRequest req) {
|
||||
public ProblemDetail handleConstraintViolation(ConstraintViolationException e,
|
||||
HttpServletRequest req) {
|
||||
var errors = e.getConstraintViolations().stream()
|
||||
.map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage()))
|
||||
.collect(Collectors.toList());
|
||||
@@ -153,7 +182,8 @@ public class ErrorAdvice {
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest req) {
|
||||
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e,
|
||||
HttpServletRequest req) {
|
||||
String supported = resolveSupportedMethods(e);
|
||||
String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported;
|
||||
// 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported)
|
||||
@@ -161,14 +191,16 @@ public class ErrorAdvice {
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, HttpServletRequest req) {
|
||||
String supported = e.getSupportedMediaTypes().stream().map(Object::toString).collect(Collectors.joining(","));
|
||||
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e,
|
||||
HttpServletRequest req) {
|
||||
String supported = e.getSupportedMediaTypes().stream().map(Object::toString)
|
||||
.collect(Collectors.joining(","));
|
||||
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
|
||||
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
|
||||
}
|
||||
|
||||
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
|
||||
@ExceptionHandler({ ResponseStatusException.class, ErrorResponseException.class })
|
||||
@ExceptionHandler({ResponseStatusException.class, ErrorResponseException.class})
|
||||
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
|
||||
HttpStatus status;
|
||||
String reason;
|
||||
@@ -178,7 +210,8 @@ public class ErrorAdvice {
|
||||
} 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());
|
||||
reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail)
|
||||
.orElse(status.getReasonPhrase());
|
||||
}
|
||||
return pd(status, "ERROR", reason, req, null);
|
||||
}
|
||||
@@ -189,19 +222,4 @@ public class ErrorAdvice {
|
||||
log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e);
|
||||
return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null);
|
||||
}
|
||||
|
||||
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import jakarta.servlet.http.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.config.annotation.*;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
public class MdcHandlerConfig {
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer mdcWebMvcConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@@ -14,7 +17,8 @@ public class MdcHandlerConfig {
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
|
||||
public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
|
||||
Object handler) {
|
||||
if (handler instanceof HandlerMethod hm) {
|
||||
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
|
||||
String method = hm.getMethod().getName(); // ex) create
|
||||
@@ -22,8 +26,10 @@ public class MdcHandlerConfig {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
|
||||
public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
|
||||
Object handler, Exception ex) {
|
||||
MDC.remove("handler");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.*;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
public class ServiceMdcAspect {
|
||||
|
||||
@Around("within(@org.springframework.stereotype.Service *)")
|
||||
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
|
||||
boolean first = (MDC.get("service") == null);
|
||||
if (first) {
|
||||
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
|
||||
String mtd = pjp.getSignature().getName(); // ex) enqueue
|
||||
MDC.put("service", cls + "#" + mtd); // ex) ExportService#enqueue
|
||||
MDC.put("service",
|
||||
cls + "#" + mtd); // ex) ExportService#enqueue
|
||||
}
|
||||
try {
|
||||
return pjp.proceed();
|
||||
} finally {
|
||||
if (first) MDC.remove("service");
|
||||
if (first) {
|
||||
MDC.remove("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.ServletRequest;
|
||||
import jakarta.servlet.ServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
public class TraceFilter implements Filter {
|
||||
|
||||
private static final String REQ_HEADER = "X-Request-Id";
|
||||
private static final String MDC_KEY = "traceId";
|
||||
|
||||
@@ -18,7 +23,9 @@ public class TraceFilter implements Filter {
|
||||
var httpRes = (HttpServletResponse) res;
|
||||
|
||||
String id = httpReq.getHeader(REQ_HEADER);
|
||||
if (id == null || id.isBlank()) id = UUID.randomUUID().toString();
|
||||
if (id == null || id.isBlank()) {
|
||||
id = UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
|
||||
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo
|
||||
|
||||
@@ -12,7 +12,9 @@ public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
|
||||
}
|
||||
|
||||
private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
|
||||
if (source == null || source.isBlank()) return null;
|
||||
if (source == null || source.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
|
||||
if (targetType.isEnum()) {
|
||||
@@ -31,6 +33,7 @@ public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unknown enum value: " + source + " for " + targetType.getName());
|
||||
throw new IllegalArgumentException(
|
||||
"Unknown enum value: " + source + " for " + targetType.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class IpAccessControlService {
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -15,8 +14,7 @@ import java.util.stream.Stream;
|
||||
public class KriIpAccessProperties {
|
||||
|
||||
/**
|
||||
* 공통에서 고정으로 들고 갈 기본 CIDR 들
|
||||
* → setter 없음 (외부에서 못 바꿈)
|
||||
* 공통에서 고정으로 들고 갈 기본 CIDR 들 → setter 없음 (외부에서 못 바꿈)
|
||||
*/
|
||||
private final List<String> defaultCidrs = List.of(
|
||||
"127.0.0.1/32", // 로컬 IPv4
|
||||
@@ -26,9 +24,8 @@ public class KriIpAccessProperties {
|
||||
);
|
||||
|
||||
/**
|
||||
* 서비스에서 추가로 넣고 싶은 CIDR 목록
|
||||
* application.yml / properties 로 바인딩되는 리스트
|
||||
*
|
||||
* 서비스에서 추가로 넣고 싶은 CIDR 목록 application.yml / properties 로 바인딩되는 리스트
|
||||
* <p>
|
||||
* 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16
|
||||
*/
|
||||
private List<String> additionalCidrs = new ArrayList<>();
|
||||
|
||||
@@ -20,6 +20,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
public class KriWebMvcAutoConfiguration {
|
||||
|
||||
private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor)
|
||||
// 선택 주입: 있으면 쓰고, 없으면 안 씀
|
||||
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@@ -33,9 +35,6 @@ public class KriWebMvcAutoConfiguration {
|
||||
return new IpAccessControlInterceptor(service);
|
||||
}
|
||||
|
||||
// 선택 주입: 있으면 쓰고, 없으면 안 씀
|
||||
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작
|
||||
@ConditionalOnMissingBean
|
||||
@@ -75,7 +74,8 @@ public class KriWebMvcAutoConfiguration {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
|
||||
public void addArgumentResolvers(
|
||||
java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
|
||||
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@@ -8,6 +8,7 @@ import lombok.Setter;
|
||||
@Setter
|
||||
@Schema(description = "페이지 검색 조건")
|
||||
public class PageRequestDto {
|
||||
|
||||
@Schema(description = "페이지 번호")
|
||||
private int pageIndex = 0; // 0-base
|
||||
@Schema(description = "페이지 크기")
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package com.kri.common.webmvc.page;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class PageResponseDto <T> {
|
||||
public class PageResponseDto<T> {
|
||||
|
||||
private List<T> content;
|
||||
private long totalElements;
|
||||
private int totalPages;
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
package com.kri.common.webmvc.page;
|
||||
|
||||
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class Pageables {
|
||||
private Pageables() {}
|
||||
|
||||
private Pageables() {
|
||||
}
|
||||
|
||||
public static Pageable of(PageRequestDto req, Class<?> sortType) {
|
||||
int page = Math.max(req.getPageIndex(), 0);
|
||||
@@ -23,7 +27,9 @@ public final class Pageables {
|
||||
|
||||
private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
|
||||
String sortBy = req.getSortBy();
|
||||
if (sortBy == null || sortBy.isBlank()) return null;
|
||||
if (sortBy == null || sortBy.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
|
||||
? Sort.Direction.ASC
|
||||
@@ -55,8 +61,12 @@ public final class Pageables {
|
||||
Set<String> props = new HashSet<>();
|
||||
for (PropertyDescriptor pd : pds) {
|
||||
String name = pd.getName();
|
||||
if ("class".equals(name)) continue;
|
||||
if (pd.getReadMethod() == null) continue;
|
||||
if ("class".equals(name)) {
|
||||
continue;
|
||||
}
|
||||
if (pd.getReadMethod() == null) {
|
||||
continue;
|
||||
}
|
||||
props.add(name);
|
||||
}
|
||||
return props;
|
||||
|
||||
@@ -2,49 +2,49 @@
|
||||
<configuration scan="true">
|
||||
|
||||
<!-- Spring property 사용 (없으면 기본값) -->
|
||||
<springProperty scope="context" name="APP_NAME" source="app.name" defaultValue="app"/>
|
||||
<springProperty scope="context" name="LOG_DIR" source="logging.file.path" defaultValue="logs"/>
|
||||
|
||||
<!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
|
||||
<property name="LOG_PATTERN"
|
||||
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
|
||||
|
||||
<!-- 콘솔 -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<appender class="ch.qos.logback.core.ConsoleAppender" name="CONSOLE">
|
||||
<encoder>
|
||||
<!-- Spring Boot 확장 패턴도 사용할 수 있음: %clr(%level) 등 -->
|
||||
<pattern>${LOG_PATTERN}</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 롤링 파일 (일 단위) -->
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_DIR}/${APP_NAME}.log</file>
|
||||
<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>
|
||||
|
||||
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 -->
|
||||
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>8192</queueSize>
|
||||
<!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
|
||||
<appender class="ch.qos.logback.classic.AsyncAppender" name="ASYNC_FILE">
|
||||
<appender-ref ref="FILE"/>
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<neverBlock>true</neverBlock>
|
||||
<appender-ref ref="FILE"/>
|
||||
<queueSize>8192</queueSize>
|
||||
</appender>
|
||||
|
||||
<!-- 콘솔 -->
|
||||
<property name="LOG_PATTERN"
|
||||
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
|
||||
|
||||
<!-- 롤링 파일 (일 단위) -->
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="ASYNC_FILE"/>
|
||||
</root>
|
||||
|
||||
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 -->
|
||||
<springProperty defaultValue="logs" name="LOG_DIR" scope="context" source="logging.file.path"/>
|
||||
|
||||
<!-- 패키지별 레벨(선택) -->
|
||||
<!-- <logger name="com.kri" level="INFO" additivity="false">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="ASYNC_FILE"/>
|
||||
</logger> -->
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="ASYNC_FILE"/>
|
||||
</root>
|
||||
<springProperty defaultValue="app" name="APP_NAME" scope="context" source="app.name"/>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user