260109_01_ENH : PageRequest, PageResponse 이동, 유틸 생성, 코드 이넘 컨버터 추가 및 등록

This commit is contained in:
2026-01-09 14:22:05 +09:00
parent 6f6abdc385
commit 5c6439743b
8 changed files with 215 additions and 1 deletions

View File

@@ -4,7 +4,7 @@ plugins {
}
//버전 변경은 여기서
def commonVer = "beta.1.0.54"
def commonVer = "beta.1.0.60"
group = 'com.kri.common'
version = commonVer

View File

@@ -164,6 +164,14 @@ public final class DateTimeUtil {
return t.isEmpty() ? null : t;
}
public static LocalDate parseLocalDate(String text) {
return tryParseLocalDate(text, DATE_FMT);
}
public static LocalDateTime parseLocalDateTime(String text) {
return tryParseLocalDateTime(text, DATETIME_FMT);
}
private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) return null;
try { return LocalDate.parse(text.trim(), fmt); }

View File

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

View File

@@ -0,0 +1,36 @@
package com.kri.common.webmvc;
import com.kri.common.enums.CodeEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
@Override
public <T extends CodeEnum> Converter<String, T> getConverter(Class<T> targetType) {
return source -> convert(source, targetType);
}
private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
if (source == null || source.isBlank()) return null;
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
if (targetType.isEnum()) {
for (T e : targetType.getEnumConstants()) {
if (((Enum<?>) e).name().equalsIgnoreCase(source)) {
return e;
}
}
}
// 2) code로 시도 ("11" 등)
for (T e : targetType.getEnumConstants()) {
Object code = e.getCode();
if (code != null && source.equals(String.valueOf(code))) {
return e;
}
}
throw new IllegalArgumentException("Unknown enum value: " + source + " for " + targetType.getName());
}
}

View File

@@ -78,6 +78,11 @@ public class KriWebMvcAutoConfiguration {
public void addArgumentResolvers(java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
}
@Override
public void addFormatters(org.springframework.format.FormatterRegistry registry) {
registry.addConverterFactory(new com.kri.common.webmvc.CodeEnumConverter());
}
};
}
}

View File

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

View File

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

View File

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