260615_01_ENH: excel upload 추가 및 short code(기존 uuid) 생성 방법 수정

This commit is contained in:
2026-06-15 09:12:59 +09:00
parent 87ddfa5100
commit 429ae52085
10 changed files with 315 additions and 53 deletions

View File

@@ -45,6 +45,8 @@ dependencies {
//MySQL
runtimeOnly "com.mysql:mysql-connector-j"
implementation 'org.apache.poi:poi-ooxml:5.5.1'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

View File

@@ -0,0 +1,22 @@
package com.kri.shorturl.common.util;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@NoArgsConstructor
public final class ExcelResponseBuilder {
public static ResponseEntity<byte[]> buildExcelResponse(String fileName, byte[] bytes) {
String contentDisposition = "attachment; filename*=UTF-8''" +
URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
}

View File

@@ -0,0 +1,114 @@
package com.kri.shorturl.common.util;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public final class ShortCodeGenerator {
private static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
private static final int CODE_LENGTH = 8;
private static final int HALF_BITS = 21;
private static final int ROUNDS = 6;
private static final long DOMAIN_SIZE = pow(36, CODE_LENGTH);
private static final long BLOCK_SIZE = 1L << (HALF_BITS * 2);
private static final long HALF_MASK = (1L << HALF_BITS) - 1;
private ShortCodeGenerator() {
}
public static String generate(Long id, String salt) {
if (id == null || id < 0 || id >= DOMAIN_SIZE) {
throw new IllegalArgumentException("short_code 생성 범위를 초과했습니다.");
}
long encodedNumber = permute(id, salt);
return toBase36(encodedNumber);
}
private static long permute(long value, String salt) {
long current = value;
do {
current = feistel(current, salt);
} while (current >= DOMAIN_SIZE);
return current;
}
private static long feistel(long value, String salt) {
if (value < 0 || value >= BLOCK_SIZE) {
throw new IllegalArgumentException("Feistel 입력 범위를 초과했습니다.");
}
long left = (value >>> HALF_BITS) & HALF_MASK;
long right = value & HALF_MASK;
for (int round = 0; round < ROUNDS; round++) {
long nextLeft = right;
long nextRight = (left ^ roundFunction(right, round, salt)) & HALF_MASK;
left = nextLeft;
right = nextRight;
}
return ((left & HALF_MASK) << HALF_BITS) | (right & HALF_MASK);
}
private static long roundFunction(long value, int round, String salt) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec keySpec = new SecretKeySpec(
salt.getBytes(StandardCharsets.UTF_8),
"HmacSHA256"
);
mac.init(keySpec);
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + Integer.BYTES);
buffer.putLong(value);
buffer.putInt(round);
byte[] hash = mac.doFinal(buffer.array());
long result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) | (hash[i] & 0xffL);
}
return result & HALF_MASK;
} catch (Exception e) {
throw new IllegalStateException("short_code 생성 중 오류가 발생했습니다.", e);
}
}
private static String toBase36(long value) {
StringBuilder sb = new StringBuilder();
long current = value;
do {
int index = (int) (current % 36);
sb.append(ALPHABET.charAt(index));
current = current / 36;
} while (current > 0);
while (sb.length() < CODE_LENGTH) {
sb.append('0');
}
return sb.reverse().toString();
}
private static long pow(int base, int exponent) {
long result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
}

View File

@@ -1,23 +1,29 @@
package com.kri.shorturl.controller;
import static com.kri.shorturl.common.util.ExcelResponseBuilder.buildExcelResponse;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
import com.kri.shorturl.service.ShortUrlService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.net.URI;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/short-url")
@@ -56,7 +62,26 @@ public class ShortUrlController {
@RequestBody ShortUrlCreateRequestDto req,
RequestUserContext ctx
) {
LocalDateTime regDt = DateTimeUtil.nowKstLocalDateTime();
return shortUrlService.createShortUrl(req, ctx.getUserId(), regDt);
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
return shortUrlService.createShortUrl(req, ctx.getUserId(), now);
}
@Operation(summary = "단축 URL 일괄 생성(엑셀 업로드)")
@PostMapping(value = "/excel/upload/{useParam}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<byte[]> createShortUrlsFromExcel(
@PathVariable boolean useParam,
@RequestParam("file") MultipartFile file,
RequestUserContext ctx
) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
String fileName = file.getOriginalFilename();
String resultFileName = fileName != null && fileName.endsWith(".xlsx")
? fileName.substring(0, fileName.length() - 5) + "_result.xlsx"
: fileName + "_result.xlsx";
byte[] bytes = shortUrlService.createShortUrlsFromExcel(useParam, file, ctx.getUserId(), now);
return buildExcelResponse(resultFileName, bytes);
}
}

View File

@@ -1,11 +1,17 @@
package com.kri.shorturl.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "단축 URL 생성 요청 DTO")
public class ShortUrlCreateRequestDto {
@@ -15,4 +21,11 @@ public class ShortUrlCreateRequestDto {
@Schema(description = "파라미터 사용 여부")
private boolean useParam;
public static ShortUrlCreateRequestDto of(String orgUrl, boolean useParam) {
return ShortUrlCreateRequestDto.builder()
.orgUrl(orgUrl)
.useParam(useParam)
.build();
}
}

View File

@@ -0,0 +1,24 @@
package com.kri.shorturl.dto.excel;
import com.kri.common.feature.excel.ExcelColumn;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UrlUploadDto {
@ExcelColumn(header = "원본 URL", order = 0, width = 20)
@Schema(description = "원본 URL")
private String orgUrl;
@ExcelColumn(header = "단축 URL", order = 1, width = 20)
@Schema(description = "단축 URL")
private String shortUrl;
}

View File

@@ -3,6 +3,8 @@ package com.kri.shorturl.persistence.entity;
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
@@ -15,7 +17,9 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@@ -23,11 +27,16 @@ import org.hibernate.annotations.ColumnDefault;
public class TShortUrlEntity {
@Id
@Size(max = 32)
@Column(name = "uuid", nullable = false, length = 32)
private String uuid;
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Long id;
@Size(max = 8)
@Column(name = "short_code", length = 8, unique = true)
private String shortCode;
@Size(max = 2048)
@NotNull
@Column(name = "org_url", nullable = false, length = 2048)
private String orgUrl;
@@ -45,9 +54,8 @@ public class TShortUrlEntity {
@Column(name = "reg_dt", nullable = false, updatable = false)
private LocalDateTime regDt;
public static TShortUrlEntity create(String uuid, ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
public static TShortUrlEntity create(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
return TShortUrlEntity.builder()
.uuid(uuid)
.orgUrl(req.getOrgUrl())
.useParam(req.isUseParam())
.regUser(regUser)
@@ -55,4 +63,8 @@ public class TShortUrlEntity {
.build();
}
public void applyShortCode(String shortCode) {
this.shortCode = shortCode;
}
}

View File

@@ -6,10 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
public interface ShortUrlRepository extends JpaRepository<TShortUrlEntity, String> {
Optional<TShortUrlEntity> findByUuid(String uuid);
Optional<TShortUrlEntity> findByShortCode(String shortCode);
Optional<TShortUrlEntity> findByOrgUrlAndUseParam(String orgUrl, Boolean useParam);
Boolean existsByUuid(String uuid);
}

View File

@@ -1,20 +1,26 @@
package com.kri.shorturl.service;
import static com.kri.shorturl.common.consts.ShortUrlConstat.BASE_URL;
import static com.kri.shorturl.common.consts.ShortUrlConstat.MAX_UUID_GENERATION_ATTEMPTS;
import static com.kri.shorturl.common.consts.ShortUrlConstat.UUID_LENGTH;
import com.kri.common.feature.util.CommonUtil;
import com.kri.common.feature.excel.ExcelMapper;
import com.kri.common.feature.web.BusinessException;
import com.kri.shorturl.common.util.ShortCodeGenerator;
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
import com.kri.shorturl.dto.excel.UrlUploadDto;
import com.kri.shorturl.persistence.entity.TShortUrlEntity;
import com.kri.shorturl.persistence.repository.ShortUrlRepository;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;
@Service
@@ -23,43 +29,83 @@ public class ShortUrlService {
private final ShortUrlRepository shortUrlRepository;
@Value("${kri.short-url.salt}")
private String shortUrlSalt;
@Transactional(transactionManager = "transactionManager")
public String createShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
if (!req.getOrgUrl().startsWith("http://") && !req.getOrgUrl().startsWith("https://")) {
req.setOrgUrl("https://" + req.getOrgUrl());
}
req.setOrgUrl(normalizeUrl(req.getOrgUrl()));
return shortUrlRepository.findByOrgUrlAndUseParam(req.getOrgUrl(), req.isUseParam())
.map(entity -> makeShortUrl(entity.getUuid()))
.map(entity -> makeShortUrl(entity.getShortCode()))
.orElseGet(() -> createNewShortUrl(req, regUser, regDt));
}
private String createNewShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
String uuid = generateUniqueUuid();
@Transactional(transactionManager = "transactionManager")
public byte[] createShortUrlsFromExcel(
boolean useParam,
MultipartFile file,
String regUser,
LocalDateTime regDt
) {
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
}
String fileName = file.getOriginalFilename();
TShortUrlEntity entity = TShortUrlEntity.create(uuid, req, regUser, regDt);
shortUrlRepository.save(entity);
List<UrlUploadDto> rows;
try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
rows = ExcelMapper.readFromWorkbook(workbook, UrlUploadDto.class);
return makeShortUrl(uuid);
} catch (Exception e) {
throw BusinessException.badRequest("INVALID_EXCEL", "엑셀 파일을 읽는 중 오류가 발생했습니다.")
.with("fileName", fileName);
}
for (UrlUploadDto row : rows) {
row.setShortUrl(
createShortUrl(
ShortUrlCreateRequestDto.of(row.getOrgUrl(), useParam),
regUser,
regDt
)
);
}
try (Workbook workbook =
ExcelMapper.writeToWorkbook(rows, UrlUploadDto.class);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
throw BusinessException.internalError("EXCEL_WRITE_FAILED", "엑셀 결과 파일 생성 중 오류가 발생했습니다.");
}
}
public URI getRedirectUri(String uuid, MultiValueMap<String, String> params){
private String createNewShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
TShortUrlEntity entity = TShortUrlEntity.create(req, regUser, regDt);
TShortUrlEntity entity = shortUrlRepository.findByUuid(uuid)
TShortUrlEntity saved = shortUrlRepository.saveAndFlush(entity);
String shortCode = ShortCodeGenerator.generate(saved.getId(), shortUrlSalt);
saved.applyShortCode(shortCode);
return makeShortUrl(shortCode);
}
@Transactional(readOnly = true, transactionManager = "transactionManager")
public URI getRedirectUri(String shortCode, MultiValueMap<String, String> params) {
TShortUrlEntity entity = shortUrlRepository.findByShortCode(shortCode)
.orElseThrow(() ->
BusinessException.notFound("NOT_FOUND","uuid에 해당하는 데이터가 없습니다.")
.with("uuid", uuid)
BusinessException.notFound("NOT_FOUND", "short_code에 해당하는 데이터가 없습니다.")
.with("shortCode", shortCode)
);
String targetUrl = entity.getOrgUrl();
if (!targetUrl.startsWith("http://") && !targetUrl.startsWith("https://")) {
targetUrl = "https://" + targetUrl;
}
String targetUrl = normalizeUrl(entity.getOrgUrl());
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(targetUrl);
if(entity.getUseParam() && params != null) {
if (Boolean.TRUE.equals(entity.getUseParam()) && params != null) {
params.forEach((key, values) -> {
for (String value : values) {
builder.queryParam(key, value);
@@ -70,22 +116,24 @@ public class ShortUrlService {
return builder.build(true).toUri();
}
private String makeShortUrl(String uuid){
return BASE_URL + "/" + uuid;
private String makeShortUrl(String shortCode) {
return BASE_URL + "/" + shortCode;
}
private String generateUniqueUuid() {
for (int attempt = 0; attempt < MAX_UUID_GENERATION_ATTEMPTS; attempt++) {
String uuid = CommonUtil.uuid(UUID_LENGTH);
if (!Boolean.TRUE.equals(shortUrlRepository.existsByUuid(uuid))) {
return uuid;
}
private String normalizeUrl(String url) {
if (url == null || url.isBlank()) {
throw BusinessException.internalError(
"INVALID_URL",
"URL이 비어 있습니다."
);
}
throw BusinessException.internalError(
"SHORT_URL_KEY_GENERATION_FAILED",
"Failed to generate short URL key."
);
String trimmedUrl = url.trim();
if (!trimmedUrl.startsWith("http://") && !trimmedUrl.startsWith("https://")) {
return "https://" + trimmedUrl;
}
return trimmedUrl;
}
}

View File

@@ -7,7 +7,7 @@ server:
spring:
application:
name: ShortUrl
name: short-url
jpa:
properties:
hibernate:
@@ -55,9 +55,13 @@ kri:
version: "v1.0.0"
base-package: "com.kri.shorturl"
web:
enabled: true # 공통 Web 구성 사용 여부 (기본 true)
redis:
enabled: false # RedisQueueHelper 사용 시 true
scheduling:
enabled: false # @Scheduled 사용 시 true
short-url:
salt: KricShortUrlSecret2026
web:
enabled: true # 공통 Web 구성 사용 여부 (기본 true)
redis:
enabled: false # RedisQueueHelper 사용 시 true
scheduling:
enabled: false # @Scheduled 사용 시 true