From cf50d427c49ea807186ff0dd6777a5db5c49a734 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 1 Dec 2025 16:56:24 +0900 Subject: [PATCH] =?UTF-8?q?251201=5F01=5FENH=20:=20JWT=20=EC=88=98?= =?UTF-8?q?=EC=A0=95,=20RequestUserContext=20=EC=B6=94=EA=B0=80,=20?= =?UTF-8?q?=EC=97=91=EC=85=80=20=EB=A7=A4=ED=8D=BC=20=EB=B0=8F=20=EC=9C=A0?= =?UTF-8?q?=ED=8B=B8,=20Json=20=EC=9C=A0=ED=8B=B8,=20DateTime=20=EC=9C=A0?= =?UTF-8?q?=ED=8B=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + build.gradle | 7 +- .../com/kri/common/auth/jwt/JwtService.java | 5 +- .../kri/common/auth/jwt/JwtUserClaimsDto.java | 3 + .../com/kri/common/datetime/DateTimeUtil.java | 178 ++++++ .../com/kri/common/excel/ExcelColumn.java | 11 + .../com/kri/common/excel/ExcelMapper.java | 558 ++++++++++++++++++ .../java/com/kri/common/excel/ExcelUtil.java | 37 ++ .../java/com/kri/common/json/JsonUtil.java | 124 ++++ .../com/kri/common/web/BusinessException.java | 58 +- .../java/com/kri/common/web/ErrorAdvice.java | 7 + .../webmvc/KriWebMvcAutoConfiguration.java | 22 +- .../kri/common/webmvc/RequestUserContext.java | 21 + .../RequestUserContextArgumentResolver.java | 76 +++ 14 files changed, 1103 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/kri/common/datetime/DateTimeUtil.java create mode 100644 src/main/java/com/kri/common/excel/ExcelColumn.java create mode 100644 src/main/java/com/kri/common/excel/ExcelMapper.java create mode 100644 src/main/java/com/kri/common/excel/ExcelUtil.java create mode 100644 src/main/java/com/kri/common/json/JsonUtil.java create mode 100644 src/main/java/com/kri/common/webmvc/RequestUserContext.java create mode 100644 src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java diff --git a/README.md b/README.md index f9b0a32..32a34c5 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ public class ExampleApiKeyUserClaimsProvider implements com.kri.common.auth.apik return java.util.Optional.of( com.kri.common.auth.jwt.JwtUserClaimsDto.builder() .userId("external") + .userCmpn("outbound") .userTeam("EXT") .userName("외부") .role(9) diff --git a/build.gradle b/build.gradle index 8b2a88a..c1abeb0 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } //버전 변경은 여기서 -def commonVer = "1.0.21" +def commonVer = "beta.1.0.32" group = 'com.kri.common' version = commonVer @@ -51,6 +51,11 @@ dependencies { compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' + //Json Util + implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.0' + //Excel Util + implementation 'org.apache.poi:poi-ooxml:5.2.5' + // ConfigurationProperties 메타데이터 annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' compileOnly 'org.springframework.boot:spring-boot-autoconfigure' diff --git a/src/main/java/com/kri/common/auth/jwt/JwtService.java b/src/main/java/com/kri/common/auth/jwt/JwtService.java index 031e238..feb3175 100644 --- a/src/main/java/com/kri/common/auth/jwt/JwtService.java +++ b/src/main/java/com/kri/common/auth/jwt/JwtService.java @@ -58,6 +58,7 @@ public class JwtService { Map claims = new HashMap<>(); // 필요한 항목만 골라서 claim에 넣어줌 claims.put("userId", dto.getUserId()); + claims.put("userCmpn", dto.getUserCmpn()); claims.put("userTeam", dto.getUserTeam()); claims.put("userName", dto.getUserName()); claims.put("role", dto.getUserRole()); @@ -71,7 +72,7 @@ public class JwtService { * JwtUserClaimsDto 기반 Access Token 생성 * - subject = userId * - claims: - * userId, userTeam, userName, role + * userId, userCmpn, userTeam, userName, role */ public String generateAccessToken(JwtUserClaimsDto userClaims) { Map claims = buildClaims(userClaims); @@ -125,6 +126,7 @@ public class JwtService { userId = claims.getSubject(); } + String userCmpn = claims.get("userCmpn", String.class); String userTeam = claims.get("userTeam", String.class); String userName = claims.get("userName", String.class); @@ -134,6 +136,7 @@ public class JwtService { return JwtUserClaimsDto.builder() .userId(userId) + .userCmpn(userCmpn) .userTeam(userTeam) .userName(userName) .userRole(userRole) diff --git a/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java b/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java index e315fc3..307778f 100644 --- a/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java +++ b/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java @@ -15,6 +15,9 @@ public class JwtUserClaimsDto { @Schema(description = "사용자 ID") String userId; + @Schema(description = "사용자 소속 회사") + String userCmpn; + @Schema(description = "팀 코드") String userTeam; diff --git a/src/main/java/com/kri/common/datetime/DateTimeUtil.java b/src/main/java/com/kri/common/datetime/DateTimeUtil.java new file mode 100644 index 0000000..b0baaf7 --- /dev/null +++ b/src/main/java/com/kri/common/datetime/DateTimeUtil.java @@ -0,0 +1,178 @@ +package com.kri.common.datetime; + +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Objects; + +public final class DateTimeUtil { + + private DateTimeUtil() {} + + public static final ZoneId KST = ZoneId.of("Asia/Seoul"); + public static final ZoneId UTC = ZoneOffset.UTC; + + /** 날짜+시간: 2025-11-28 15:00:14 */ + public static final DateTimeFormatter DATETIME_FMT = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** 날짜: 2025-11-28 */ + public static final DateTimeFormatter DATE_FMT = + DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + /* ======================= + * Now (KST) + * ======================= */ + + /** 현재 KST 날짜+시간 문자열 */ + public static String nowKstDateTime() { + return formatKst(Instant.now(), DATETIME_FMT); + } + + /** 현재 KST 날짜 문자열 */ + public static String nowKstDate() { + return nowKstZoned().format(DATE_FMT); + } + + /** 현재 KST ZonedDateTime */ + public static ZonedDateTime nowKstZoned() { + return Instant.now().atZone(KST); + } + + /** 현재 KST LocalDateTime */ + public static LocalDateTime nowKstLocalDateTime() { + return nowKstZoned().toLocalDateTime(); + } + + /** 현재 KST LocalDate */ + public static LocalDate nowKstLocalDate() { + return nowKstZoned().toLocalDate(); + } + + /* ======================= + * Format (Instant -> String) + * ======================= */ + + /** Instant -> KST 날짜+시간 문자열 */ + public static String formatKstDateTime(Instant instant) { + return formatKst(instant, DATETIME_FMT); + } + + /** Instant -> KST 날짜 문자열 */ + public static String formatKstDate(Instant instant) { + return formatKst(instant, DATE_FMT); + } + + /** Instant -> KST 문자열 (커스텀 포맷) */ + public static String formatKst(Instant instant, DateTimeFormatter formatter) { + if (instant == null) return null; + final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT; + return instant.atZone(KST).format(fmt); + } + + /* ======================= + * Validate + * ======================= */ + + /** "yyyy-MM-dd" 형태인지 */ + public static boolean isDate(String text) { + return tryParseLocalDate(text, DATE_FMT) != null; + } + + /** "yyyy-MM-dd HH:mm:ss" 형태인지 */ + public static boolean isDateTime(String text) { + return tryParseLocalDateTime(text, DATETIME_FMT) != null; + } + + /** ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지 */ + public static boolean isIsoDateTime(String text) { + if (text == null || text.isBlank()) return false; + + final String s = text.trim(); + try { Instant.parse(s); return true; } catch (DateTimeParseException ignored) {} + try { OffsetDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {} + try { ZonedDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {} + + return false; + } + + /* ======================= + * Parse (String -> Instant) + * ======================= */ + + /** ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도) */ + public static Instant parseToInstant(String text) { + if (text == null || text.isBlank()) return null; + + final String s = text.trim(); + try { return Instant.parse(s); } catch (DateTimeParseException ignored) {} + try { return OffsetDateTime.parse(s).toInstant(); } catch (DateTimeParseException ignored) {} + try { return ZonedDateTime.parse(s).toInstant(); } catch (DateTimeParseException ignored) {} + + throw new DateTimeParseException("Unsupported datetime format", s, 0); + } + + /** + * 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환 + * 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT + */ + public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) { + if (text == null || text.isBlank()) return null; + Objects.requireNonNull(formatter, "formatter"); + + LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter); + return ldt.atZone(KST).toInstant(); + } + + /** "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석 */ + public static Instant parseKstDateTimeToInstant(String text) { + return parseKstToInstant(text, DATETIME_FMT); + } + + /** "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석 */ + public static Instant parseKstDateToInstant(String text) { + if (text == null || text.isBlank()) return null; + LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT); + return ld.atStartOfDay(KST).toInstant(); + } + + /* ======================= + * Convert / Helpers + * ======================= */ + + /** Instant -> KST ZonedDateTime */ + public static ZonedDateTime toKstZoned(Instant instant) { + return instant == null ? null : instant.atZone(KST); + } + + /** Instant -> KST LocalDateTime */ + public static LocalDateTime toKstLocalDateTime(Instant instant) { + ZonedDateTime zdt = toKstZoned(instant); + return zdt == null ? null : zdt.toLocalDateTime(); + } + + /** Instant -> KST LocalDate */ + public static LocalDate toKstLocalDate(Instant instant) { + ZonedDateTime zdt = toKstZoned(instant); + return zdt == null ? null : zdt.toLocalDate(); + } + + /** null/blank 안전 trim */ + public static String trimToNull(String s) { + if (s == null) return null; + String t = s.trim(); + return t.isEmpty() ? null : t; + } + + private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) { + if (text == null || text.isBlank()) return null; + try { return LocalDate.parse(text.trim(), fmt); } + catch (DateTimeParseException e) { return null; } + } + + private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) { + if (text == null || text.isBlank()) return null; + try { return LocalDateTime.parse(text.trim(), fmt); } + catch (DateTimeParseException e) { return null; } + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/excel/ExcelColumn.java b/src/main/java/com/kri/common/excel/ExcelColumn.java new file mode 100644 index 0000000..7e20236 --- /dev/null +++ b/src/main/java/com/kri/common/excel/ExcelColumn.java @@ -0,0 +1,11 @@ +package com.kri.common.excel; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ExcelColumn { + String header(); // 엑셀 헤더 이름 + int order() default 0; // 컬럼 순서 + int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로 +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/excel/ExcelMapper.java b/src/main/java/com/kri/common/excel/ExcelMapper.java new file mode 100644 index 0000000..c95d366 --- /dev/null +++ b/src/main/java/com/kri/common/excel/ExcelMapper.java @@ -0,0 +1,558 @@ +package com.kri.common.excel; + +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.eventusermodel.XSSFReader; +import org.apache.poi.xssf.model.SharedStringsTable; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; +import org.xml.sax.helpers.XMLReaderFactory; + +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.*; + +/** + * Excel <-> 객체/맵 변환 유틸리티 + * + * 전제: + * - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다. + * - 셀 값 파싱은 ExcelUtil.getStringCell(Cell) 사용. + */ +public final class ExcelMapper { + + private ExcelMapper() { + // 유틸 클래스 - 인스턴스 생성 방지 + } + + /* ========================================================= + * 1. List -> XSSFWorkbook (in-memory 쓰기) + * ========================================================= */ + + public static Workbook writeToWorkbook(List data, Class clazz) { + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Sheet1"); + + // 1) @ExcelColumn 기반 메타 수집 + List fields = getExcelFields(clazz); + + // 2) 헤더 작성 + Row headerRow = sheet.createRow(0); + for (ExcelFieldMeta meta : fields) { + Cell cell = headerRow.createCell(meta.order()); + cell.setCellValue(meta.header()); + } + + // 3) 데이터 작성 + int rowIndex = 1; + if (data != null) { + for (T item : data) { + Row row = sheet.createRow(rowIndex++); + for (ExcelFieldMeta meta : fields) { + Cell cell = row.createCell(meta.order()); + Object value = meta.getValue(item); + cell.setCellValue(value != null ? value.toString() : ""); + } + } + } + + // 4) 자동 너비 조정 + for (ExcelFieldMeta meta : fields) { + if (meta.width() > 0) { + sheet.setColumnWidth(meta.order(), meta.width() * 256); + } else { + sheet.autoSizeColumn(meta.order()); + } + } + + return workbook; + } + + /* ========================================================= + * 2. Workbook -> List (in-memory 읽기) + * ========================================================= */ + + public static List readFromWorkbook(Workbook workbook, Class clazz) { + Sheet sheet = workbook.getSheetAt(0); + + // 1) 헤더 행 + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + return List.of(); + } + + Map headerIndexMap = new HashMap<>(); + short lastCellNum = headerRow.getLastCellNum(); + for (int c = 0; c < lastCellNum; c++) { + Cell cell = headerRow.getCell(c); + if (cell != null) { + String headerName = cell.getStringCellValue(); + headerIndexMap.put(headerName, c); + } + } + + // 2) DTO 필드 메타 + List fields = getExcelFields(clazz); + + // 3) 데이터 행 -> DTO + List result = new ArrayList<>(); + int lastRowNum = sheet.getLastRowNum(); + + for (int r = 1; r <= lastRowNum; r++) { + Row row = sheet.getRow(r); + if (row == null) continue; + + try { + T instance = clazz.getDeclaredConstructor().newInstance(); + + for (ExcelFieldMeta meta : fields) { + Integer colIdx = headerIndexMap.get(meta.header()); + if (colIdx == null) continue; + + Cell cell = row.getCell(colIdx); + String cellValue = ExcelUtil.getStringCell(cell); + + if (cellValue != null) { + setFieldValue(instance, meta.field(), cellValue); + } + } + + result.add(instance); + } catch (Exception e) { + throw new RuntimeException("엑셀 파싱 중 오류 (row=" + (r + 1) + ")", e); + } + } + + return result; + } + + /* ========================================================= + * 3. Workbook -> List> (in-memory 읽기) + * ========================================================= */ + + public static List> readAsMapList(Workbook workbook) { + Sheet sheet = workbook.getSheetAt(0); + + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + return List.of(); + } + + int lastCol = headerRow.getLastCellNum(); + List headers = new ArrayList<>(lastCol); + + for (int c = 0; c < lastCol; c++) { + Cell cell = headerRow.getCell(c); + String headerName = (cell != null) ? cell.getStringCellValue() : ("COL_" + c); + headers.add(headerName); + } + + List> result = new ArrayList<>(); + int lastRow = sheet.getLastRowNum(); + + for (int r = 1; r <= lastRow; r++) { + Row row = sheet.getRow(r); + if (row == null) continue; + + Map rowMap = new LinkedHashMap<>(); + boolean allBlank = true; + + for (int c = 0; c < lastCol; c++) { + Cell cell = row.getCell(c); + String v = ExcelUtil.getStringCell(cell); + if (v != null && !v.isBlank()) { + allBlank = false; + } + rowMap.put(headers.get(c), v); + } + + if (!allBlank) { + result.add(rowMap); + } + } + + return result; + } + + /* ========================================================= + * 4. List> -> Workbook (in-memory 쓰기) + * ========================================================= */ + + public static Workbook writeFromMapList(List> rows) { + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Sheet1"); + + if (rows == null || rows.isEmpty()) { + return workbook; + } + + // 전체 헤더 집합 (순서 유지) + Set headerSet = new LinkedHashSet<>(); + for (Map row : rows) { + if (row != null) { + headerSet.addAll(row.keySet()); + } + } + + List headers = new ArrayList<>(headerSet); + + // 헤더 + Row headerRow = sheet.createRow(0); + for (int c = 0; c < headers.size(); c++) { + Cell cell = headerRow.createCell(c); + cell.setCellValue(headers.get(c)); + } + + // 데이터 + int rowIndex = 1; + for (Map rowMap : rows) { + Row row = sheet.createRow(rowIndex++); + if (rowMap == null) continue; + + for (int c = 0; c < headers.size(); c++) { + String key = headers.get(c); + Object value = rowMap.get(key); + if (value != null) { + row.createCell(c).setCellValue(value.toString()); + } + } + } + + // 자동 컬럼 너비 + for (int c = 0; c < headers.size(); c++) { + sheet.autoSizeColumn(c); + } + + return workbook; + } + + /* ========================================================= + * 5. Streaming Write (SXSSFWorkbook) - DTO 기반 + * ========================================================= */ + + /** + * 대용량 쓰기를 위한 스트리밍 버전. + * + * @param data 엑셀에 쓸 DTO 리스트 (이미 메모리에 있음) + * @param clazz DTO 타입 + * @param rowAccessWindowSize SXSSFWorkbook row window (예: 100, 500 등) + */ + public static SXSSFWorkbook writeStreaming(List data, + Class clazz, + int rowAccessWindowSize) { + SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); + Sheet sheet = workbook.createSheet("Sheet1"); + + // 1) 메타 수집 + List fields = getExcelFields(clazz); + + // 2) 헤더 + Row headerRow = sheet.createRow(0); + for (ExcelFieldMeta meta : fields) { + Cell cell = headerRow.createCell(meta.order()); + cell.setCellValue(meta.header()); + } + + // 3) 데이터 + int rowIndex = 1; + if (data != null) { + for (T item : data) { + Row row = sheet.createRow(rowIndex++); + + for (ExcelFieldMeta meta : fields) { + Cell cell = row.createCell(meta.order()); + Object value = meta.getValue(item); + if (value != null) { + cell.setCellValue(value.toString()); + } else { + cell.setBlank(); + } + } + } + } + + // autoSizeColumn은 대용량에서는 비추천 (메모리 많이 씀) -> 필요하면 호출 + // for (ExcelFieldMeta meta : fields) { + // sheet.autoSizeColumn(meta.order()); + // } + + return workbook; + } + + /* ========================================================= + * 6. Streaming Write (SXSSFWorkbook) - Map 기반 + * ========================================================= */ + + public static SXSSFWorkbook writeStreamingFromMap(List> rows, + int rowAccessWindowSize) { + SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); + Sheet sheet = workbook.createSheet("Sheet1"); + + if (rows == null || rows.isEmpty()) { + return workbook; + } + + // 전체 헤더 집합 + Set headerSet = new LinkedHashSet<>(); + for (Map row : rows) { + if (row != null) { + headerSet.addAll(row.keySet()); + } + } + List headers = new ArrayList<>(headerSet); + + // 헤더 + Row headerRow = sheet.createRow(0); + for (int c = 0; c < headers.size(); c++) { + headerRow.createCell(c).setCellValue(headers.get(c)); + } + + // 데이터 + int rowIndex = 1; + for (Map rowMap : rows) { + Row row = sheet.createRow(rowIndex++); + if (rowMap == null) continue; + + for (int c = 0; c < headers.size(); c++) { + String key = headers.get(c); + Object value = rowMap.get(key); + if (value != null) { + row.createCell(c).setCellValue(value.toString()); + } + } + } + + return workbook; + } + + /* ========================================================= + * 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler + * ========================================================= */ + + @FunctionalInterface + public interface RowMapHandler { + /** + * @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터) + * @param rowIndex 엑셀 실제 행 번호 (1-based) + */ + void handleRow(Map row, int rowIndex); + } + + /** + * XSSFReader + SAX 기반 스트리밍 읽기. + * - 첫 번째 시트만 읽음. + * - 1행은 헤더, 2행부터 데이터로 가정. + */ + public static void readStreaming(InputStream inputStream, RowMapHandler handler) { + try { + OPCPackage pkg = OPCPackage.open(inputStream); + XSSFReader reader = new XSSFReader(pkg); + SharedStringsTable sst = (SharedStringsTable) reader.getSharedStringsTable(); + + XMLReader parser = XMLReaderFactory.createXMLReader(); + SheetToMapHandler sheetHandler = new SheetToMapHandler(sst, handler); + parser.setContentHandler(sheetHandler); + + Iterator sheets = reader.getSheetsData(); + if (sheets.hasNext()) { + try (InputStream sheetIS = sheets.next()) { + InputSource sheetSource = new InputSource(sheetIS); + parser.parse(sheetSource); + } + } + + pkg.close(); + } catch (Exception e) { + throw new RuntimeException("Streaming 엑셀 읽기 중 오류", e); + } + } + + /** + * SAX 핸들러: 한 행을 Map 으로 만들어 RowMapHandler에 전달. + */ + private static class SheetToMapHandler extends DefaultHandler { + private final SharedStringsTable sst; + private final RowMapHandler handler; + + private int currentRowNum; + private String currentCellRef; + private String currentCellType; + private StringBuilder currentValue; + private boolean isValueOpen; + + private final Map cellMap = new HashMap<>(); + private List headers = new ArrayList<>(); + private boolean headerProcessed = false; + + SheetToMapHandler(SharedStringsTable sst, RowMapHandler handler) { + this.sst = sst; + this.handler = handler; + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) { + if ("row".equals(qName)) { + String r = attributes.getValue("r"); + if (r != null) { + currentRowNum = Integer.parseInt(r); + } else { + currentRowNum++; + } + cellMap.clear(); + } else if ("c".equals(qName)) { + currentCellRef = attributes.getValue("r"); + currentCellType = attributes.getValue("t"); // "s"면 shared string + } else if ("v".equals(qName) || "t".equals(qName)) { + currentValue = new StringBuilder(); + isValueOpen = true; + } + } + + @Override + public void characters(char[] ch, int start, int length) { + if (isValueOpen && currentValue != null) { + currentValue.append(ch, start, length); + } + } + + @Override + public void endElement(String uri, String localName, String qName) { + if ("v".equals(qName) || "t".equals(qName)) { + String raw = currentValue != null ? currentValue.toString() : ""; + String resolved = resolveCellValue(raw, currentCellType); + + if (currentCellRef != null) { + int colIdx = new CellReference(currentCellRef).getCol(); + cellMap.put(colIdx, resolved); + } + + isValueOpen = false; + currentValue = null; + } else if ("row".equals(qName)) { + // 1행: 헤더 + if (!headerProcessed) { + if (!cellMap.isEmpty()) { + int maxCol = cellMap.keySet().stream().max(Integer::compareTo).orElse(-1); + headers = new ArrayList<>(maxCol + 1); + for (int c = 0; c <= maxCol; c++) { + String header = cellMap.getOrDefault(c, "COL_" + c); + headers.add(header); + } + } + headerProcessed = true; + } else { + if (headers == null || headers.isEmpty()) return; + + Map rowMap = new LinkedHashMap<>(); + boolean allBlank = true; + + for (int c = 0; c < headers.size(); c++) { + String v = cellMap.get(c); + if (v != null && !v.isBlank()) { + allBlank = false; + } + rowMap.put(headers.get(c), v); + } + + if (!allBlank) { + handler.handleRow(rowMap, currentRowNum); + } + } + } + } + + private String resolveCellValue(String raw, String cellType) { + if ("s".equals(cellType)) { + try { + int idx = Integer.parseInt(raw); + RichTextString rich = sst.getItemAt(idx); // 또는 getEntryAt(idx) 인 버전도 있음 + return (rich != null) ? rich.getString() : ""; + } catch (Exception e) { + return raw; + } + } + return raw; + } + } + + /* ========================================================= + * 8. 내부 메타 수집 & 필드 세터 + * ========================================================= */ + + private static List getExcelFields(Class clazz) { + List result = new ArrayList<>(); + + for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + ExcelColumn ann = field.getAnnotation(ExcelColumn.class); + if (ann == null) continue; + + field.setAccessible(true); + result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width())); + } + } + + result.sort(Comparator.comparingInt(ExcelFieldMeta::order)); + return result; + } + + private static void setFieldValue(Object target, Field field, String value) throws IllegalAccessException { + Class type = field.getType(); + + // 1) null 또는 공백 처리 + if (value == null || value.isBlank()) { + // primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴 + if (type.isPrimitive()) { + return; + } + // 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅 + field.set(target, null); + 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); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/excel/ExcelUtil.java b/src/main/java/com/kri/common/excel/ExcelUtil.java new file mode 100644 index 0000000..d17cc42 --- /dev/null +++ b/src/main/java/com/kri/common/excel/ExcelUtil.java @@ -0,0 +1,37 @@ +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.*; + +public final class ExcelUtil { + + private ExcelUtil() {} + + public static String getStringCell(Cell cell) { + if (cell == null) { + return null; + } + + return switch (cell.getCellType()) { + case STRING -> cell.getStringCellValue(); + case NUMERIC -> { + if (DateUtil.isCellDateFormatted(cell)) { + yield cell.getDateCellValue().toString(); + } else { + double d = cell.getNumericCellValue(); + if (d == Math.rint(d)) { + yield String.valueOf((long) d); + } + yield String.valueOf(d); + } + } + case BOOLEAN -> String.valueOf(cell.getBooleanCellValue()); + case FORMULA -> cell.getCellFormula(); + case BLANK -> null; + default -> null; // ERROR, _NONE 등 나머지 타입 + }; + } +} diff --git a/src/main/java/com/kri/common/json/JsonUtil.java b/src/main/java/com/kri/common/json/JsonUtil.java new file mode 100644 index 0000000..5947ca7 --- /dev/null +++ b/src/main/java/com/kri/common/json/JsonUtil.java @@ -0,0 +1,124 @@ +package com.kri.common.json; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.Collections; +import java.util.Map; + +public final class JsonUtil { + + private JsonUtil() { + // 유틸 클래스 - 인스턴스 생성 방지 + } + + /** + * 임의의 자바 객체를 Map으로 변환한다. + * 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, + * 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 용도이다. + */ + public static Map toMap(ObjectMapper objectMapper, T source) { + if (source == null) { + return Collections.emptyMap(); + } + @SuppressWarnings("unchecked") + Map map = objectMapper.convertValue(source, Map.class); + return map; + } + + /** + * JSON 문자열을 Map으로 파싱한다. + * + * @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환) + */ + public static Map parseJsonToMap(ObjectMapper objectMapper, String json) { + if (json == null || json.isBlank()) { + return Collections.emptyMap(); + } + try { + return objectMapper.readValue(json, new TypeReference>() {}); + } catch (IOException e) { + throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e); + } + } + + /** + * 객체를 JSON 문자열로 직렬화한다. + */ + public static String toJson(ObjectMapper objectMapper, Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("객체를 JSON 문자열로 변환하는 중 오류가 발생했습니다.", e); + } + } + + /** + * 객체를 사람이 읽기 좋은 pretty JSON 문자열로 직렬화한다. + */ + public static String toPrettyJson(ObjectMapper objectMapper, Object value) { + try { + return objectMapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("객체를 pretty JSON 문자열로 변환하는 중 오류가 발생했습니다.", e); + } + } + + /** + * JSON 문자열을 주어진 타입으로 역직렬화한다. + * ex) fromJson(mapper, json, UserInfoDto.class) + */ + public static T fromJson(ObjectMapper objectMapper, String json, Class type) { + if (json == null || json.isBlank()) { + return null; + } + try { + return objectMapper.readValue(json, type); + } catch (IOException e) { + throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.", e); + } + } + + /** + * JSON 문자열을 제네릭 타입으로 역직렬화한다. + * ex) fromJson(mapper, json, new TypeReference>() {}) + */ + public static T fromJson(ObjectMapper objectMapper, String json, TypeReference typeRef) { + if (json == null || json.isBlank()) { + return null; + } + try { + return objectMapper.readValue(json, typeRef); + } catch (IOException e) { + throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e); + } + } + + /** + * JSON 기반 deep copy (또는 타입 변환). + * 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다. + * + * ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class); + */ + public static T deepCopy(ObjectMapper objectMapper, T source, Class targetType) { + if (source == null) { + return null; + } + return objectMapper.convertValue(source, targetType); + } + + /** + * 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용. + * + * ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class); + */ + public static T convert(ObjectMapper objectMapper, S source, Class targetType) { + if (source == null) { + return null; + } + return objectMapper.convertValue(source, targetType); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/web/BusinessException.java b/src/main/java/com/kri/common/web/BusinessException.java index abb528b..deb13fc 100644 --- a/src/main/java/com/kri/common/web/BusinessException.java +++ b/src/main/java/com/kri/common/web/BusinessException.java @@ -27,15 +27,69 @@ public class BusinessException extends RuntimeException { public static BusinessException of(HttpStatus status, String code, String message, Map extras) { return new BusinessException(status, code, message, extras, null); } + // 편의 생성자들 + // 400 Bad Request + public static BusinessException badRequest(String code, String message) { + return of(HttpStatus.BAD_REQUEST, code, message); + } + + public static BusinessException badRequest(String message) { + return badRequest("BAD_REQUEST", message); + } + + // 401 Unauthorized + public static BusinessException unauthorized(String code, String message) { + return of(HttpStatus.UNAUTHORIZED, code, message); + } + + public static BusinessException unauthorized(String message) { + return unauthorized("UNAUTHORIZED", message); + } + + // 403 Forbidden + public static BusinessException forbidden(String code, String message) { + return of(HttpStatus.FORBIDDEN, code, message); + } + + public static BusinessException forbidden(String message) { + return forbidden("FORBIDDEN", message); + } + + // 404 Not Found public static BusinessException notFound(String code, String message) { return of(HttpStatus.NOT_FOUND, code, message); } + + public static BusinessException notFound(String message) { + return notFound("NOT_FOUND", message); + } + + // 409 Conflict public static BusinessException conflict(String code, String message) { return of(HttpStatus.CONFLICT, code, message); } - public static BusinessException forbidden(String code, String message) { - return of(HttpStatus.FORBIDDEN, code, message); + + public static BusinessException conflict(String message) { + return conflict("CONFLICT", message); + } + + // 422 Unprocessable Entity (검증 에러 등에 자주 사용) + public static BusinessException validationError(String code, String message) { + return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message); + } + + public static BusinessException validationError(String message) { + return validationError("VALIDATION_ERROR", message); + } + + // 500 Internal Server Error + public static BusinessException internalError(String code, String message) { + return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message); + } + + public static BusinessException internalError(String message) { + return internalError("INTERNAL_SERVER_ERROR", message); } public HttpStatus getStatus(){ return status; } diff --git a/src/main/java/com/kri/common/web/ErrorAdvice.java b/src/main/java/com/kri/common/web/ErrorAdvice.java index 7f9a40d..b7597c4 100644 --- a/src/main/java/com/kri/common/web/ErrorAdvice.java +++ b/src/main/java/com/kri/common/web/ErrorAdvice.java @@ -20,6 +20,7 @@ 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.*; @@ -141,6 +142,11 @@ public class ErrorAdvice { } /* ---------- 404/405/415 등 표준 스프링 예외 ---------- */ + @ExceptionHandler(NoResourceFoundException.class) + public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) { + return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null); + } + @ExceptionHandler(NoHandlerFoundException.class) public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) { return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null); @@ -180,6 +186,7 @@ public class ErrorAdvice { /* ---------- 마지막: 예상 못한 예외는 500 ---------- */ @ExceptionHandler(Exception.class) public ProblemDetail handleAny(Exception e, HttpServletRequest req) { + log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e); return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null); } diff --git a/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java b/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java index 9501f7e..96e5f05 100644 --- a/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java +++ b/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java @@ -1,8 +1,10 @@ package com.kri.common.webmvc; +import com.kri.common.auth.jwt.JwtService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -34,11 +36,24 @@ public class KriWebMvcAutoConfiguration { // 선택 주입: 있으면 쓰고, 없으면 안 씀 private final ObjectProvider ipAccessControlInterceptorProvider; + @Bean + @ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작 + @ConditionalOnMissingBean + public RequestUserContextArgumentResolver requestUserContextArgumentResolver( + JwtService jwtService + ) { + return new RequestUserContextArgumentResolver(jwtService); + } + /** * 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean */ @Bean - public WebMvcConfigurer kriCommonWebMvcConfigurer() { + public WebMvcConfigurer kriCommonWebMvcConfigurer( + KriIpAccessProperties properties, + ObjectProvider ipAccessControlInterceptorProvider, + ObjectProvider requestUserContextArgumentResolverProvider + ) { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { @@ -58,6 +73,11 @@ public class KriWebMvcAutoConfiguration { .addPathPatterns("/swagger-ui/**", "/v3/api-docs/**") ); } + + @Override + public void addArgumentResolvers(java.util.List resolvers) { + requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add); + } }; } } \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/RequestUserContext.java b/src/main/java/com/kri/common/webmvc/RequestUserContext.java new file mode 100644 index 0000000..c5de3ac --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/RequestUserContext.java @@ -0,0 +1,21 @@ +package com.kri.common.webmvc; + +import lombok.Builder; +import lombok.Value; + +@Value +@Builder +public class RequestUserContext { + + String userId; + String userCmpn; + String userTeam; + String userName; + Integer userRole; + + String clientIp; // IpUtil 에서 가져온 값 + + public boolean isAuthenticated() { + return userId != null; + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java b/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java new file mode 100644 index 0000000..4b00207 --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/RequestUserContextArgumentResolver.java @@ -0,0 +1,76 @@ +package com.kri.common.webmvc; + +import com.kri.common.auth.jwt.JwtService; +import com.kri.common.auth.jwt.JwtUserClaimsDto; +import io.jsonwebtoken.JwtException; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.core.MethodParameter; +import org.springframework.lang.Nullable; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +@RequiredArgsConstructor +public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver { + + private final JwtService jwtService; + + @Override + public boolean supportsParameter(MethodParameter parameter) { + return RequestUserContext.class.isAssignableFrom(parameter.getParameterType()); + } + + @Override + public Object resolveArgument( + MethodParameter parameter, + @Nullable ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, + @Nullable WebDataBinderFactory binderFactory + ) { + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); + + String clientIp = request != null ? IpUtil.getClientIp(request) : null; + + JwtUserClaimsDto claims = null; + + // 1) SecurityContext 에 이미 JwtUserClaimsDto 가 principal 로 들어있는 경우 + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getPrincipal() instanceof JwtUserClaimsDto jwtDto) { + claims = jwtDto; + } + + // 2) 현재 공통 JwtService 는 principal 을 userId(String) 로 쓰고 있으니까, + // 필요하면 Authorization 헤더에서 직접 토큰 파싱 + if (claims == null && request != null) { + String authHeader = request.getHeader("Authorization"); + if (authHeader != null && authHeader.startsWith("Bearer ")) { + String token = authHeader.substring(7); + try { + claims = jwtService.toUserClaimsDto(token); + } catch (JwtException ex) { + // 토큰 이상하면 그냥 anonymous 로 둠 + } + } + } + + if (claims == null) { + // 비인증 상태: IP만 채운 빈 컨텍스트 + return RequestUserContext.builder() + .clientIp(clientIp) + .build(); + } + + return RequestUserContext.builder() + .userId(claims.getUserId()) + .userCmpn(claims.getUserCmpn()) + .userTeam(claims.getUserTeam()) + .userName(claims.getUserName()) + .userRole(claims.getUserRole()) + .clientIp(clientIp) + .build(); + } +}