260615_01_ENH: excel upload 추가 및 short code(기존 uuid) 생성 방법 수정
This commit is contained in:
@@ -45,6 +45,8 @@ dependencies {
|
|||||||
//MySQL
|
//MySQL
|
||||||
runtimeOnly "com.mysql:mysql-connector-j"
|
runtimeOnly "com.mysql:mysql-connector-j"
|
||||||
|
|
||||||
|
implementation 'org.apache.poi:poi-ooxml:5.5.1'
|
||||||
|
|
||||||
compileOnly 'org.projectlombok:lombok'
|
compileOnly 'org.projectlombok:lombok'
|
||||||
annotationProcessor 'org.projectlombok:lombok'
|
annotationProcessor 'org.projectlombok:lombok'
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,29 @@
|
|||||||
package com.kri.shorturl.controller;
|
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.datetime.DateTimeUtil;
|
||||||
import com.kri.common.feature.web.RequestUserContext;
|
import com.kri.common.feature.web.RequestUserContext;
|
||||||
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
|
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
|
||||||
import com.kri.shorturl.service.ShortUrlService;
|
import com.kri.shorturl.service.ShortUrlService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.util.MultiValueMap;
|
import org.springframework.util.MultiValueMap;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
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.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/short-url")
|
@RequestMapping("/api/v1/short-url")
|
||||||
@@ -56,7 +62,26 @@ public class ShortUrlController {
|
|||||||
@RequestBody ShortUrlCreateRequestDto req,
|
@RequestBody ShortUrlCreateRequestDto req,
|
||||||
RequestUserContext ctx
|
RequestUserContext ctx
|
||||||
) {
|
) {
|
||||||
LocalDateTime regDt = DateTimeUtil.nowKstLocalDateTime();
|
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||||
return shortUrlService.createShortUrl(req, ctx.getUserId(), regDt);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
package com.kri.shorturl.dto;
|
package com.kri.shorturl.dto;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Builder
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
@Schema(description = "단축 URL 생성 요청 DTO")
|
@Schema(description = "단축 URL 생성 요청 DTO")
|
||||||
public class ShortUrlCreateRequestDto {
|
public class ShortUrlCreateRequestDto {
|
||||||
|
|
||||||
@@ -15,4 +21,11 @@ public class ShortUrlCreateRequestDto {
|
|||||||
@Schema(description = "파라미터 사용 여부")
|
@Schema(description = "파라미터 사용 여부")
|
||||||
private boolean useParam;
|
private boolean useParam;
|
||||||
|
|
||||||
|
public static ShortUrlCreateRequestDto of(String orgUrl, boolean useParam) {
|
||||||
|
return ShortUrlCreateRequestDto.builder()
|
||||||
|
.orgUrl(orgUrl)
|
||||||
|
.useParam(useParam)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
24
src/main/java/com/kri/shorturl/dto/excel/UrlUploadDto.java
Normal file
24
src/main/java/com/kri/shorturl/dto/excel/UrlUploadDto.java
Normal 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;
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ package com.kri.shorturl.persistence.entity;
|
|||||||
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
|
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
import jakarta.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
@@ -15,7 +17,9 @@ import lombok.NoArgsConstructor;
|
|||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
|
||||||
@Getter @Setter @Builder
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Entity
|
@Entity
|
||||||
@@ -23,11 +27,16 @@ import org.hibernate.annotations.ColumnDefault;
|
|||||||
public class TShortUrlEntity {
|
public class TShortUrlEntity {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@Size(max = 32)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(name = "uuid", nullable = false, length = 32)
|
@Column(name = "id", nullable = false, updatable = false)
|
||||||
private String uuid;
|
private Long id;
|
||||||
|
|
||||||
|
@Size(max = 8)
|
||||||
|
@Column(name = "short_code", length = 8, unique = true)
|
||||||
|
private String shortCode;
|
||||||
|
|
||||||
@Size(max = 2048)
|
@Size(max = 2048)
|
||||||
|
@NotNull
|
||||||
@Column(name = "org_url", nullable = false, length = 2048)
|
@Column(name = "org_url", nullable = false, length = 2048)
|
||||||
private String orgUrl;
|
private String orgUrl;
|
||||||
|
|
||||||
@@ -45,9 +54,8 @@ public class TShortUrlEntity {
|
|||||||
@Column(name = "reg_dt", nullable = false, updatable = false)
|
@Column(name = "reg_dt", nullable = false, updatable = false)
|
||||||
private LocalDateTime regDt;
|
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()
|
return TShortUrlEntity.builder()
|
||||||
.uuid(uuid)
|
|
||||||
.orgUrl(req.getOrgUrl())
|
.orgUrl(req.getOrgUrl())
|
||||||
.useParam(req.isUseParam())
|
.useParam(req.isUseParam())
|
||||||
.regUser(regUser)
|
.regUser(regUser)
|
||||||
@@ -55,4 +63,8 @@ public class TShortUrlEntity {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void applyShortCode(String shortCode) {
|
||||||
|
this.shortCode = shortCode;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -6,10 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
|||||||
|
|
||||||
public interface ShortUrlRepository extends JpaRepository<TShortUrlEntity, String> {
|
public interface ShortUrlRepository extends JpaRepository<TShortUrlEntity, String> {
|
||||||
|
|
||||||
Optional<TShortUrlEntity> findByUuid(String uuid);
|
Optional<TShortUrlEntity> findByShortCode(String shortCode);
|
||||||
|
|
||||||
Optional<TShortUrlEntity> findByOrgUrlAndUseParam(String orgUrl, Boolean useParam);
|
Optional<TShortUrlEntity> findByOrgUrlAndUseParam(String orgUrl, Boolean useParam);
|
||||||
|
|
||||||
Boolean existsByUuid(String uuid);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,26 @@
|
|||||||
package com.kri.shorturl.service;
|
package com.kri.shorturl.service;
|
||||||
|
|
||||||
import static com.kri.shorturl.common.consts.ShortUrlConstat.BASE_URL;
|
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.common.feature.web.BusinessException;
|
||||||
|
import com.kri.shorturl.common.util.ShortCodeGenerator;
|
||||||
import com.kri.shorturl.dto.ShortUrlCreateRequestDto;
|
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.entity.TShortUrlEntity;
|
||||||
import com.kri.shorturl.persistence.repository.ShortUrlRepository;
|
import com.kri.shorturl.persistence.repository.ShortUrlRepository;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
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.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.util.MultiValueMap;
|
import org.springframework.util.MultiValueMap;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
import org.springframework.web.util.UriComponentsBuilder;
|
import org.springframework.web.util.UriComponentsBuilder;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -23,43 +29,83 @@ public class ShortUrlService {
|
|||||||
|
|
||||||
private final ShortUrlRepository shortUrlRepository;
|
private final ShortUrlRepository shortUrlRepository;
|
||||||
|
|
||||||
|
@Value("${kri.short-url.salt}")
|
||||||
|
private String shortUrlSalt;
|
||||||
|
|
||||||
@Transactional(transactionManager = "transactionManager")
|
@Transactional(transactionManager = "transactionManager")
|
||||||
public String createShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
|
public String createShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
|
||||||
if (!req.getOrgUrl().startsWith("http://") && !req.getOrgUrl().startsWith("https://")) {
|
req.setOrgUrl(normalizeUrl(req.getOrgUrl()));
|
||||||
req.setOrgUrl("https://" + req.getOrgUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
return shortUrlRepository.findByOrgUrlAndUseParam(req.getOrgUrl(), req.isUseParam())
|
return shortUrlRepository.findByOrgUrlAndUseParam(req.getOrgUrl(), req.isUseParam())
|
||||||
.map(entity -> makeShortUrl(entity.getUuid()))
|
.map(entity -> makeShortUrl(entity.getShortCode()))
|
||||||
.orElseGet(() -> createNewShortUrl(req, regUser, regDt));
|
.orElseGet(() -> createNewShortUrl(req, regUser, regDt));
|
||||||
}
|
}
|
||||||
|
|
||||||
private String createNewShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
|
@Transactional(transactionManager = "transactionManager")
|
||||||
String uuid = generateUniqueUuid();
|
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);
|
List<UrlUploadDto> rows;
|
||||||
shortUrlRepository.save(entity);
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
public URI getRedirectUri(String uuid, MultiValueMap<String, String> params){
|
for (UrlUploadDto row : rows) {
|
||||||
|
row.setShortUrl(
|
||||||
|
createShortUrl(
|
||||||
|
ShortUrlCreateRequestDto.of(row.getOrgUrl(), useParam),
|
||||||
|
regUser,
|
||||||
|
regDt
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
TShortUrlEntity entity = shortUrlRepository.findByUuid(uuid)
|
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", "엑셀 결과 파일 생성 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createNewShortUrl(ShortUrlCreateRequestDto req, String regUser, LocalDateTime regDt) {
|
||||||
|
TShortUrlEntity entity = TShortUrlEntity.create(req, regUser, regDt);
|
||||||
|
|
||||||
|
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(() ->
|
.orElseThrow(() ->
|
||||||
BusinessException.notFound("NOT_FOUND","uuid에 해당하는 데이터가 없습니다.")
|
BusinessException.notFound("NOT_FOUND", "short_code에 해당하는 데이터가 없습니다.")
|
||||||
.with("uuid", uuid)
|
.with("shortCode", shortCode)
|
||||||
);
|
);
|
||||||
|
|
||||||
String targetUrl = entity.getOrgUrl();
|
String targetUrl = normalizeUrl(entity.getOrgUrl());
|
||||||
|
|
||||||
if (!targetUrl.startsWith("http://") && !targetUrl.startsWith("https://")) {
|
|
||||||
targetUrl = "https://" + targetUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(targetUrl);
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(targetUrl);
|
||||||
|
|
||||||
if(entity.getUseParam() && params != null) {
|
if (Boolean.TRUE.equals(entity.getUseParam()) && params != null) {
|
||||||
params.forEach((key, values) -> {
|
params.forEach((key, values) -> {
|
||||||
for (String value : values) {
|
for (String value : values) {
|
||||||
builder.queryParam(key, value);
|
builder.queryParam(key, value);
|
||||||
@@ -70,22 +116,24 @@ public class ShortUrlService {
|
|||||||
return builder.build(true).toUri();
|
return builder.build(true).toUri();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String makeShortUrl(String uuid){
|
private String makeShortUrl(String shortCode) {
|
||||||
return BASE_URL + "/" + uuid;
|
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(
|
throw BusinessException.internalError(
|
||||||
"SHORT_URL_KEY_GENERATION_FAILED",
|
"INVALID_URL",
|
||||||
"Failed to generate short URL key."
|
"URL이 비어 있습니다."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String trimmedUrl = url.trim();
|
||||||
|
|
||||||
|
if (!trimmedUrl.startsWith("http://") && !trimmedUrl.startsWith("https://")) {
|
||||||
|
return "https://" + trimmedUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmedUrl;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ server:
|
|||||||
|
|
||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: ShortUrl
|
name: short-url
|
||||||
jpa:
|
jpa:
|
||||||
properties:
|
properties:
|
||||||
hibernate:
|
hibernate:
|
||||||
@@ -55,6 +55,10 @@ kri:
|
|||||||
version: "v1.0.0"
|
version: "v1.0.0"
|
||||||
base-package: "com.kri.shorturl"
|
base-package: "com.kri.shorturl"
|
||||||
|
|
||||||
|
short-url:
|
||||||
|
salt: KricShortUrlSecret2026
|
||||||
|
|
||||||
|
|
||||||
web:
|
web:
|
||||||
enabled: true # 공통 Web 구성 사용 여부 (기본 true)
|
enabled: true # 공통 Web 구성 사용 여부 (기본 true)
|
||||||
redis:
|
redis:
|
||||||
|
|||||||
Reference in New Issue
Block a user