diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c2065bc2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/README.md b/README.md index a557279f..3fa0a66a 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,11 @@ SprintBoot URL Shortener 구현 미션 Repository 입니다. ## 요구사항 각 요구사항을 모두 충족할 수 있도록 노력해봅시다. -- [ ] URL 입력폼 제공 및 결과 출력 -- [ ] URL Shortening Key는 8 Character 이내로 생성 -- [ ] 단축된 URL 요청시 원래 URL로 리다이렉트 -- [ ] 단축된 URL에 대한 요청 수 정보저장 (optional) -- [ ] Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 (optional) +- [x] URL 입력폼 제공 및 결과 출력 +- [x] URL Shortening Key는 8 Character 이내로 생성 +- [x] 단축된 URL 요청시 원래 URL로 리다이렉트 +- [x] 단축된 URL에 대한 요청 수 정보저장 (optional) +- [x] Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 (optional) ## Short URL Service diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..0f2c2763 --- /dev/null +++ b/build.gradle @@ -0,0 +1,38 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'com.young-url' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..9f4197d5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..fcb6fca1 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..136770f8 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'shortenerURL' diff --git a/src/main/java/com/young/shortenerurl/ShortenerUrlApplication.java b/src/main/java/com/young/shortenerurl/ShortenerUrlApplication.java new file mode 100644 index 00000000..fa32d465 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/ShortenerUrlApplication.java @@ -0,0 +1,13 @@ +package com.young.shortenerurl; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ShortenerUrlApplication { + + public static void main(String[] args) { + SpringApplication.run(ShortenerUrlApplication.class, args); + } + +} diff --git a/src/main/java/com/young/shortenerurl/global/CustomAsyncExceptionHandler.java b/src/main/java/com/young/shortenerurl/global/CustomAsyncExceptionHandler.java new file mode 100644 index 00000000..93feba14 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/CustomAsyncExceptionHandler.java @@ -0,0 +1,16 @@ +package com.young.shortenerurl.global; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; + +import java.lang.reflect.Method; + +@Slf4j +public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler { + + @Override + public void handleUncaughtException(Throwable ex, Method method, Object... params) { + log.warn("Async Exception: ", ex.fillInStackTrace()); + } + +} diff --git a/src/main/java/com/young/shortenerurl/global/ErrorResponse.java b/src/main/java/com/young/shortenerurl/global/ErrorResponse.java new file mode 100644 index 00000000..13100c36 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/ErrorResponse.java @@ -0,0 +1,20 @@ +package com.young.shortenerurl.global; + +import java.time.LocalDateTime; + +public record ErrorResponse( + String detail, + String instance, + String time) { + + public static ErrorResponse of( + String detail, + String instance) { + + return new ErrorResponse( + detail, + instance, + LocalDateTime.now().toString()); + } + +} diff --git a/src/main/java/com/young/shortenerurl/global/GlobalApiExceptionHandler.java b/src/main/java/com/young/shortenerurl/global/GlobalApiExceptionHandler.java new file mode 100644 index 00000000..a567ca0f --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/GlobalApiExceptionHandler.java @@ -0,0 +1,59 @@ +package com.young.shortenerurl.global; + +import jakarta.persistence.EntityNotFoundException; +import jakarta.servlet.http.HttpServletRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindException; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +@Slf4j +public class GlobalApiExceptionHandler { + + @ExceptionHandler(BindException.class) + public ResponseEntity handleBindException(HttpServletRequest request, BindException e) { + StringBuilder detailMessage = getDetailMessage(e); + ErrorResponse errorResponse = ErrorResponse.of(detailMessage.toString(), request.getRequestURI()); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(HttpServletRequest request, IllegalArgumentException e) { + ErrorResponse errorResponse = ErrorResponse.of(e.getMessage(), request.getRequestURI()); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse); + } + + @ExceptionHandler(EntityNotFoundException.class) + public ResponseEntity handleEntityNotFoundException(HttpServletRequest request, EntityNotFoundException e) { + ErrorResponse errorResponse = ErrorResponse.of(e.getMessage(), request.getRequestURI()); + + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(HttpServletRequest request, Exception e) { + log.error("Sever Exception Request URI {}: ", request.getRequestURI(), e); + + return ResponseEntity.internalServerError().build(); + } + + private static StringBuilder getDetailMessage(BindException e) { + BindingResult bindingResult = e.getBindingResult(); + StringBuilder stringBuilder = new StringBuilder(); + + for (FieldError fieldError : bindingResult.getFieldErrors()) { + stringBuilder.append(fieldError.getField()).append(":"); + stringBuilder.append(fieldError.getDefaultMessage()); + stringBuilder.append(", "); + } + return stringBuilder; + } + +} diff --git a/src/main/java/com/young/shortenerurl/global/config/AsyncConfig.java b/src/main/java/com/young/shortenerurl/global/config/AsyncConfig.java new file mode 100644 index 00000000..53814504 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/config/AsyncConfig.java @@ -0,0 +1,34 @@ +package com.young.shortenerurl.global.config; + +import com.young.shortenerurl.global.CustomAsyncExceptionHandler; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@EnableAsync +@Configuration +public class AsyncConfig implements AsyncConfigurer { + + @Override + @Bean(name = "asyncExecutor") + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(8); + executor.setMaxPoolSize(8); + executor.setQueueCapacity(500); + executor.setThreadNamePrefix("url-shortener-async"); + executor.initialize(); + return executor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new CustomAsyncExceptionHandler(); + } + +} diff --git a/src/main/java/com/young/shortenerurl/global/generator/Sequence.java b/src/main/java/com/young/shortenerurl/global/generator/Sequence.java new file mode 100644 index 00000000..79f6fd87 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/generator/Sequence.java @@ -0,0 +1,21 @@ +package com.young.shortenerurl.global.generator; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "sequence") +@Getter +@NoArgsConstructor +public class Sequence { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + +} diff --git a/src/main/java/com/young/shortenerurl/global/generator/SequenceRepository.java b/src/main/java/com/young/shortenerurl/global/generator/SequenceRepository.java new file mode 100644 index 00000000..2ddb5e52 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/generator/SequenceRepository.java @@ -0,0 +1,6 @@ +package com.young.shortenerurl.global.generator; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SequenceRepository extends JpaRepository { +} diff --git a/src/main/java/com/young/shortenerurl/global/generator/SequenceUniqueKeyGenerator.java b/src/main/java/com/young/shortenerurl/global/generator/SequenceUniqueKeyGenerator.java new file mode 100644 index 00000000..af56318c --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/generator/SequenceUniqueKeyGenerator.java @@ -0,0 +1,20 @@ +package com.young.shortenerurl.global.generator; + +import org.springframework.stereotype.Component; + +@Component +public class SequenceUniqueKeyGenerator implements UniqueKeyGenerator { + + private final SequenceRepository sequenceRepository; + + public SequenceUniqueKeyGenerator(SequenceRepository sequenceRepository) { + this.sequenceRepository = sequenceRepository; + } + + @Override + public Long generateKey() { + return sequenceRepository.save(new Sequence()) + .getId(); + } + +} diff --git a/src/main/java/com/young/shortenerurl/global/generator/UniqueKeyGenerator.java b/src/main/java/com/young/shortenerurl/global/generator/UniqueKeyGenerator.java new file mode 100644 index 00000000..bf9d29fa --- /dev/null +++ b/src/main/java/com/young/shortenerurl/global/generator/UniqueKeyGenerator.java @@ -0,0 +1,6 @@ +package com.young.shortenerurl.global.generator; + +public interface UniqueKeyGenerator { + + Long generateKey(); +} diff --git a/src/main/java/com/young/shortenerurl/url/application/EncodingExecutor.java b/src/main/java/com/young/shortenerurl/url/application/EncodingExecutor.java new file mode 100644 index 00000000..1943e83d --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/application/EncodingExecutor.java @@ -0,0 +1,34 @@ +package com.young.shortenerurl.url.application; + +import com.young.shortenerurl.global.generator.UniqueKeyGenerator; +import com.young.shortenerurl.url.model.EncodingType; +import com.young.shortenerurl.url.util.Encoder; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class EncodingExecutor { + + private final Map encoders; + private final UniqueKeyGenerator uniqueKeyGenerator; + + public EncodingExecutor(UniqueKeyGenerator uniqueKeyGenerator) { + this.encoders = Stream.of(EncodingType.values()) + .collect(Collectors.toMap(Enum::name, EncodingType::getEncoder)); + + this.uniqueKeyGenerator = uniqueKeyGenerator; + } + + public String encode(EncodingType encodingType) { + Assert.notNull(encodingType, "encodingType은 null이 들어오면 안됩니다."); + + Encoder encoder = encoders.get(encodingType.name()); + + return encoder.encode(uniqueKeyGenerator.generateKey()); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/application/UrlService.java b/src/main/java/com/young/shortenerurl/url/application/UrlService.java new file mode 100644 index 00000000..36645952 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/application/UrlService.java @@ -0,0 +1,54 @@ +package com.young.shortenerurl.url.application; + +import com.young.shortenerurl.url.application.dto.UrlCreateRequest; +import com.young.shortenerurl.url.application.dto.UrlInfoFindResponse; +import com.young.shortenerurl.url.handler.dto.OriginUrlFindEvent; +import com.young.shortenerurl.url.infrastructures.UrlRepository; +import com.young.shortenerurl.url.model.EncodedUrl; +import com.young.shortenerurl.url.model.Url; +import lombok.RequiredArgsConstructor; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@RequiredArgsConstructor +@Service +public class UrlService { + + private final UrlRepository urlRepository; + private final EncodingExecutor encodingExecutor; + private final ApplicationEventPublisher eventPublisher; + + @Transactional + public String createUrl(UrlCreateRequest request) { + String encodedUrl = encodingExecutor.encode(request.encodingType()); + + if (urlRepository.existsByOriginUrl(request.originUrl())) { + Url url = urlRepository.getByOriginUrl(request.originUrl()); + + return url.getEncodedUrl(); + } + + Url savedUrl = request.toUrl(encodedUrl); + return urlRepository.save(savedUrl).getEncodedUrl(); + } + + @Transactional(readOnly = true) + public String findOriginUrl(String encodedUrl) { + Url url = urlRepository.getByEncodedUrl(encodedUrl); + + eventPublisher.publishEvent( + OriginUrlFindEvent.from(url.getId()) + ); + + return url.getOriginUrl(); + } + + @Transactional(readOnly = true) + public UrlInfoFindResponse findUrlInfoByEncodedUrl(String encodedUrl) { + Url findUrl = urlRepository.getByEncodedUrl(encodedUrl); + + return UrlInfoFindResponse.from(findUrl); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/application/dto/UrlCreateRequest.java b/src/main/java/com/young/shortenerurl/url/application/dto/UrlCreateRequest.java new file mode 100644 index 00000000..5f517590 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/application/dto/UrlCreateRequest.java @@ -0,0 +1,16 @@ +package com.young.shortenerurl.url.application.dto; + +import com.young.shortenerurl.url.model.EncodedUrl; +import com.young.shortenerurl.url.model.EncodingType; +import com.young.shortenerurl.url.model.Url; + +public record UrlCreateRequest( + String originUrl, + EncodingType encodingType +) { + public Url toUrl(String encodedUrl) { + return new Url( + originUrl, + new EncodedUrl(encodedUrl, encodingType)); + } +} diff --git a/src/main/java/com/young/shortenerurl/url/application/dto/UrlInfoFindResponse.java b/src/main/java/com/young/shortenerurl/url/application/dto/UrlInfoFindResponse.java new file mode 100644 index 00000000..579f43bc --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/application/dto/UrlInfoFindResponse.java @@ -0,0 +1,15 @@ +package com.young.shortenerurl.url.application.dto; + +import com.young.shortenerurl.url.model.Url; + +public record UrlInfoFindResponse( + String originUrl, + String encodedUrl, + Long visitCount) { + public static UrlInfoFindResponse from(Url url) { + return new UrlInfoFindResponse( + url.getOriginUrl(), + url.getEncodedUrl(), + url.getVisitCount()); + } +} diff --git a/src/main/java/com/young/shortenerurl/url/handler/UrlEventHandler.java b/src/main/java/com/young/shortenerurl/url/handler/UrlEventHandler.java new file mode 100644 index 00000000..c3088d8b --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/handler/UrlEventHandler.java @@ -0,0 +1,25 @@ +package com.young.shortenerurl.url.handler; + +import com.young.shortenerurl.url.handler.dto.OriginUrlFindEvent; +import com.young.shortenerurl.url.infrastructures.UrlRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.event.TransactionPhase; +import org.springframework.transaction.event.TransactionalEventListener; + +@RequiredArgsConstructor +@Component +public class UrlEventHandler { + + private final UrlRepository urlRepository; + + @Async + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void handleFindOriginUrlEvent(OriginUrlFindEvent event) { + urlRepository.increaseVisitCount(event.urlId()); + } +} diff --git a/src/main/java/com/young/shortenerurl/url/handler/dto/OriginUrlFindEvent.java b/src/main/java/com/young/shortenerurl/url/handler/dto/OriginUrlFindEvent.java new file mode 100644 index 00000000..8ae440fa --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/handler/dto/OriginUrlFindEvent.java @@ -0,0 +1,9 @@ +package com.young.shortenerurl.url.handler.dto; + +public record OriginUrlFindEvent( + Long urlId +) { + public static OriginUrlFindEvent from(Long urlId) { + return new OriginUrlFindEvent(urlId); + } +} diff --git a/src/main/java/com/young/shortenerurl/url/infrastructures/UrlJpaRepository.java b/src/main/java/com/young/shortenerurl/url/infrastructures/UrlJpaRepository.java new file mode 100644 index 00000000..0068589c --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/infrastructures/UrlJpaRepository.java @@ -0,0 +1,25 @@ +package com.young.shortenerurl.url.infrastructures; + +import com.young.shortenerurl.url.model.Url; +import jakarta.persistence.LockModeType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Optional; + +public interface UrlJpaRepository extends JpaRepository { + + @Query("SELECT u FROM Url u WHERE u.encodedUrl.encodedUrl = :encodedUrl") + Optional findByEncodedUrl(@Param(value = "encodedUrl") String encodedUrl); + + Optional findUrlByOriginUrl(String originUrl); + + Boolean existsByOriginUrl(String originUrl); + + @Modifying(clearAutomatically = true) + @Query(value = "UPDATE urls SET visit_count = visit_count + 1 WHERE id = :urlId", nativeQuery = true) + void increaseVisitCount(Long urlId); +} diff --git a/src/main/java/com/young/shortenerurl/url/infrastructures/UrlRepository.java b/src/main/java/com/young/shortenerurl/url/infrastructures/UrlRepository.java new file mode 100644 index 00000000..e96e507e --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/infrastructures/UrlRepository.java @@ -0,0 +1,17 @@ +package com.young.shortenerurl.url.infrastructures; + +import com.young.shortenerurl.url.model.Url; + +import java.util.Optional; + +public interface UrlRepository { + Url save(Url url); + + Url getByEncodedUrl(String encodedUrl); + + Boolean existsByOriginUrl(String originUrl); + + Url getByOriginUrl(String originUrl); + + void increaseVisitCount(Long urlId); +} diff --git a/src/main/java/com/young/shortenerurl/url/infrastructures/UrlRepositoryImpl.java b/src/main/java/com/young/shortenerurl/url/infrastructures/UrlRepositoryImpl.java new file mode 100644 index 00000000..20fc111c --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/infrastructures/UrlRepositoryImpl.java @@ -0,0 +1,45 @@ +package com.young.shortenerurl.url.infrastructures; + +import com.young.shortenerurl.url.model.Url; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public class UrlRepositoryImpl implements UrlRepository { + + private final UrlJpaRepository urlJpaRepository; + + public UrlRepositoryImpl(UrlJpaRepository urlJpaRepository) { + this.urlJpaRepository = urlJpaRepository; + } + + @Override + public Url save(Url url) { + return urlJpaRepository.save(url); + } + + @Override + public Url getByEncodedUrl(String encodedUrl) { + return urlJpaRepository.findByEncodedUrl(encodedUrl) + .orElseThrow(() -> new EntityNotFoundException("해당 encodedUrl를 가진 url을 찾을 수 없습니다.")); + } + + @Override + public Url getByOriginUrl(String originUrl) { + return urlJpaRepository.findUrlByOriginUrl(originUrl) + .orElseThrow(() -> new EntityNotFoundException("해당 originUrl를 가진 url을 찾을 수 없습니다.")); + } + + @Override + public void increaseVisitCount(Long urlId) { + urlJpaRepository.increaseVisitCount(urlId); + } + + @Override + public Boolean existsByOriginUrl(String originUrl) { + return urlJpaRepository.existsByOriginUrl(originUrl); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/model/EncodedUrl.java b/src/main/java/com/young/shortenerurl/url/model/EncodedUrl.java new file mode 100644 index 00000000..73d2415c --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/model/EncodedUrl.java @@ -0,0 +1,37 @@ +package com.young.shortenerurl.url.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.util.Assert; + +@Getter +@Embeddable +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class EncodedUrl { + private static final int MAX_URL_LENGTH = 8; + + @Column(nullable = false, name = "encoded_url") + private String encodedUrl; + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private EncodingType encodingType; + + public EncodedUrl(String encodedUrl, EncodingType encodingType) { + Assert.notNull(encodedUrl, "변환된 url은 null이 될 수 없습니다."); + Assert.notNull(encodingType, "encodingType은 null이 될 수 없습니다."); + + if (encodedUrl.length() > MAX_URL_LENGTH) { + throw new IllegalArgumentException("변환된 url의 길이는 8이상 될 수 없습니다."); + } + + this.encodedUrl = encodedUrl; + this.encodingType = encodingType; + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/model/EncodingType.java b/src/main/java/com/young/shortenerurl/url/model/EncodingType.java new file mode 100644 index 00000000..66713515 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/model/EncodingType.java @@ -0,0 +1,23 @@ +package com.young.shortenerurl.url.model; + +import com.young.shortenerurl.url.util.Base64EncoderV2; +import com.young.shortenerurl.url.util.Encoder; +import com.young.shortenerurl.url.util.Base64EncoderV1; + +import java.util.function.Supplier; + +public enum EncodingType { + BASE_64_V1(Base64EncoderV1::new), + BASE_64_V2(Base64EncoderV2::new); + + private final Supplier supplier; + + EncodingType(Supplier supplier) { + this.supplier = supplier; + } + + public Encoder getEncoder() { + return supplier.get(); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/model/Url.java b/src/main/java/com/young/shortenerurl/url/model/Url.java new file mode 100644 index 00000000..83d7859d --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/model/Url.java @@ -0,0 +1,58 @@ +package com.young.shortenerurl.url.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.util.Assert; + +@Entity +@Table(name = "urls", uniqueConstraints = { + @UniqueConstraint( + name = "encoded_url_unique", + columnNames = {"encoded_url"} + ) +}) +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Url { + private static final int MAX_ORIGIN_URL_LENGTH = 2083; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(length = MAX_ORIGIN_URL_LENGTH, nullable = false, updatable = false) + private String originUrl; + + @Embedded + private EncodedUrl encodedUrl; + + @Column(nullable = false) + private Long visitCount; + + public Url(String originUrl, EncodedUrl encodedUrl) { + Assert.notNull(originUrl, "originUrl은 null값이 들어올 수 없습니다."); + Assert.notNull(encodedUrl, "encodedUrl은 null값이 들어올 수 없습니다."); + + this.originUrl = originUrl; + this.encodedUrl = encodedUrl; + this.visitCount = 0L; + } + + public String getEncodedUrl() { + return encodedUrl.getEncodedUrl(); + } + + public void increaseVisitCount() { + visitCount++; + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/presentation/UrlRestController.java b/src/main/java/com/young/shortenerurl/url/presentation/UrlRestController.java new file mode 100644 index 00000000..c13c7b59 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/presentation/UrlRestController.java @@ -0,0 +1,64 @@ +package com.young.shortenerurl.url.presentation; + +import com.young.shortenerurl.url.application.UrlService; +import com.young.shortenerurl.url.application.dto.UrlInfoFindResponse; +import com.young.shortenerurl.url.presentation.dto.UrlCreateApiRequest; +import com.young.shortenerurl.url.presentation.dto.UrlCreateApiResponse; +import com.young.shortenerurl.url.presentation.dto.UrlInfoFindApiResponse; +import com.young.shortenerurl.url.presentation.mapper.UrlApiMapper; + +import jakarta.validation.Valid; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; + +@RestController +@RequestMapping("/api/urls") +public class UrlRestController { + private static final String URL_PRE_FIX = "http://localhost:8080/api/urls/"; + + private final UrlService urlService; + private final UrlApiMapper mapper; + + public UrlRestController(UrlService urlService, UrlApiMapper mapper) { + this.urlService = urlService; + this.mapper = mapper; + } + + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity createUrl(@RequestBody @Valid UrlCreateApiRequest request) { + String encodedUrl = urlService.createUrl(mapper.toUrlCreateRequest(request)); + String apiResponseUrl = URL_PRE_FIX + encodedUrl; + + UrlCreateApiResponse apiResponse = UrlCreateApiResponse.from(apiResponseUrl); + + return ResponseEntity + .created(URI.create(apiResponseUrl)) + .body(apiResponse); + } + + @GetMapping(value = "/{encodedUrl}") + public ResponseEntity redirectUrl(@PathVariable String encodedUrl) { + String originUrl = urlService.findOriginUrl(encodedUrl); + + return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY) + .location(URI.create(originUrl)) + .build(); + } + + @GetMapping( + value = "/encodedUrl/{encodedUrl}", + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity findUrlInfo(@PathVariable String encodedUrl) { + UrlInfoFindResponse response = urlService.findUrlInfoByEncodedUrl(encodedUrl); + + UrlInfoFindApiResponse apiResponse = UrlInfoFindApiResponse.of(response, URL_PRE_FIX); + + return ResponseEntity.ok(apiResponse); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/presentation/UrlViewController.java b/src/main/java/com/young/shortenerurl/url/presentation/UrlViewController.java new file mode 100644 index 00000000..caa6989b --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/presentation/UrlViewController.java @@ -0,0 +1,14 @@ +package com.young.shortenerurl.url.presentation; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class UrlViewController { + + @GetMapping + public String getIndexPage() { + return "index"; + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlCreateApiRequest.java b/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlCreateApiRequest.java new file mode 100644 index 00000000..e7b57fd5 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlCreateApiRequest.java @@ -0,0 +1,10 @@ +package com.young.shortenerurl.url.presentation.dto; + +import com.young.shortenerurl.url.model.EncodingType; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public record UrlCreateApiRequest( + @NotBlank(message = "originUrl은 빈값이 들어올 수 없습니다.") String originUrl, + @NotNull(message = "encodingType은 null이 들어올 수 없습니다.") EncodingType encodingType) { +} diff --git a/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlCreateApiResponse.java b/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlCreateApiResponse.java new file mode 100644 index 00000000..f6c830ae --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlCreateApiResponse.java @@ -0,0 +1,8 @@ +package com.young.shortenerurl.url.presentation.dto; + +public record UrlCreateApiResponse(String encodedUrl) { + + public static UrlCreateApiResponse from(String encodedUrl) { + return new UrlCreateApiResponse(encodedUrl); + } +} diff --git a/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlInfoFindApiResponse.java b/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlInfoFindApiResponse.java new file mode 100644 index 00000000..48247366 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/presentation/dto/UrlInfoFindApiResponse.java @@ -0,0 +1,16 @@ +package com.young.shortenerurl.url.presentation.dto; + +import com.young.shortenerurl.url.application.dto.UrlInfoFindResponse; + +public record UrlInfoFindApiResponse( + String originUrl, + String encodedUrl, + Long visitCount) { + public static UrlInfoFindApiResponse of(UrlInfoFindResponse response, String urlPreFix) { + return new UrlInfoFindApiResponse( + response.originUrl(), + urlPreFix + response.encodedUrl(), + response.visitCount()); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/presentation/mapper/UrlApiMapper.java b/src/main/java/com/young/shortenerurl/url/presentation/mapper/UrlApiMapper.java new file mode 100644 index 00000000..ab25202b --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/presentation/mapper/UrlApiMapper.java @@ -0,0 +1,16 @@ +package com.young.shortenerurl.url.presentation.mapper; + +import com.young.shortenerurl.url.application.dto.UrlCreateRequest; +import com.young.shortenerurl.url.presentation.dto.UrlCreateApiRequest; +import org.springframework.stereotype.Component; + +@Component +public class UrlApiMapper { + + public UrlCreateRequest toUrlCreateRequest(UrlCreateApiRequest request) { + return new UrlCreateRequest( + request.originUrl(), + request.encodingType()); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/util/Base64EncoderV1.java b/src/main/java/com/young/shortenerurl/url/util/Base64EncoderV1.java new file mode 100644 index 00000000..f0de5682 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/util/Base64EncoderV1.java @@ -0,0 +1,24 @@ +package com.young.shortenerurl.url.util; + +import org.springframework.stereotype.Component; + +@Component +public class Base64EncoderV1 extends Encoder { + private static final int BASE64 = 64; + private static final String BASE64_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; + + @Override + public String encode(long index) { + StringBuilder sb = new StringBuilder(); + while (index > 0) { + sb.append(BASE64_CHAR.charAt((int) (index % BASE64))); + index /= BASE64; + } + + if (sb.length() > MAX_LENGTH) { + throw new IllegalArgumentException("변환된 url은 8자리를 넘어갈 수 없습니다."); + } + return sb.toString(); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/util/Base64EncoderV2.java b/src/main/java/com/young/shortenerurl/url/util/Base64EncoderV2.java new file mode 100644 index 00000000..8ccb1262 --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/util/Base64EncoderV2.java @@ -0,0 +1,24 @@ +package com.young.shortenerurl.url.util; + +import org.springframework.stereotype.Component; + +@Component +public class Base64EncoderV2 extends Encoder { + private static final int BASE62 = 64; + private static final String BASE62_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.~"; + + @Override + public String encode(long index) { + StringBuilder sb = new StringBuilder(); + while (index > 0) { + sb.append(BASE62_CHAR.charAt((int) (index % BASE62))); + index /= BASE62; + } + + if (sb.length() > MAX_LENGTH) { + throw new IllegalArgumentException("변환된 url은 8자리를 넘어갈 수 없습니다."); + } + return sb.toString(); + } + +} diff --git a/src/main/java/com/young/shortenerurl/url/util/Encoder.java b/src/main/java/com/young/shortenerurl/url/util/Encoder.java new file mode 100644 index 00000000..666b2c8c --- /dev/null +++ b/src/main/java/com/young/shortenerurl/url/util/Encoder.java @@ -0,0 +1,10 @@ +package com.young.shortenerurl.url.util; + +public abstract class Encoder { + protected final Integer MAX_LENGTH = 8; + + protected Encoder() { + } + + public abstract String encode(long index); +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..a3654b42 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,14 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/shortener_url?serverTimezone=Asia/Seoul + username: root + password: 12345! + hikari: + maximum-pool-size: 40 + + jpa: + open-in-view: false + hibernate: + ddl-auto: update + show-sql: true \ No newline at end of file diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html new file mode 100644 index 00000000..b7315e1a --- /dev/null +++ b/src/main/resources/templates/index.html @@ -0,0 +1,127 @@ + + + + + + + + + + + URL-SHORTENER + + + +
+
+

Shortener URL

+
+
+ +
+
+ + + +
+ +
+
+

Shortened URL is :

+ + +
+

Find Shortened URL INFO

+
+
+ + + +
+

Original URL is :

+

Encoded URL is :

+

Visit count is :

+
+
+ +
+ + + + + + + diff --git a/src/test/java/com/young/shortenerurl/ShortenerUrlApplicationTests.java b/src/test/java/com/young/shortenerurl/ShortenerUrlApplicationTests.java new file mode 100644 index 00000000..6be55f62 --- /dev/null +++ b/src/test/java/com/young/shortenerurl/ShortenerUrlApplicationTests.java @@ -0,0 +1,13 @@ +package com.young.shortenerurl; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ShortenerUrlApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/young/shortenerurl/support/AsyncTestConfig.java b/src/test/java/com/young/shortenerurl/support/AsyncTestConfig.java new file mode 100644 index 00000000..b296c115 --- /dev/null +++ b/src/test/java/com/young/shortenerurl/support/AsyncTestConfig.java @@ -0,0 +1,27 @@ +package com.young.shortenerurl.support; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.core.task.SyncTaskExecutor; + +@TestConfiguration +public class AsyncTestConfig { + + @Bean + public AsyncExecutorPostProcessor asyncExecutorPostProcessor() { + return new AsyncExecutorPostProcessor(); + } + + static class AsyncExecutorPostProcessor implements BeanPostProcessor { + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (beanName.equals("asyncExecutor")) { + return new SyncTaskExecutor(); + } + return bean; + } + } +} diff --git a/src/test/java/com/young/shortenerurl/support/IntegrationTest.java b/src/test/java/com/young/shortenerurl/support/IntegrationTest.java new file mode 100644 index 00000000..e2b8f2de --- /dev/null +++ b/src/test/java/com/young/shortenerurl/support/IntegrationTest.java @@ -0,0 +1,11 @@ +package com.young.shortenerurl.support; + +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; + +@ActiveProfiles("test") +@SpringBootTest +@Import({AsyncTestConfig.class}) +public class IntegrationTest { +} diff --git a/src/test/java/com/young/shortenerurl/url/application/EncodingExecutorTest.java b/src/test/java/com/young/shortenerurl/url/application/EncodingExecutorTest.java new file mode 100644 index 00000000..10fd6922 --- /dev/null +++ b/src/test/java/com/young/shortenerurl/url/application/EncodingExecutorTest.java @@ -0,0 +1,50 @@ +package com.young.shortenerurl.url.application; + +import com.young.shortenerurl.global.generator.UniqueKeyGenerator; +import com.young.shortenerurl.url.model.EncodingType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +@ExtendWith(MockitoExtension.class) +class EncodingExecutorTest { + + @InjectMocks + private EncodingExecutor encodingExecutor; + + @Mock + private UniqueKeyGenerator uniqueKeyGenerator; + + @Test + @DisplayName("파라미터로 받은 base64V1 인코딩 알고리즘에 맞는 인코딩 값을 반환 한다.") + void encode_base64V1() { + //given + given(uniqueKeyGenerator.generateKey()).willReturn(63L); + + //when + String encodedUrl = encodingExecutor.encode(EncodingType.BASE_64_V1); + + //then + assertThat(encodedUrl).isEqualTo("-"); + } + + @Test + @DisplayName("파라미터로 받은 base64V2 인코딩 알고리즘에 맞는 인코딩 값을 반환 한다.") + void encode_base64V2() { + //given + given(uniqueKeyGenerator.generateKey()).willReturn(63L); + + //when + String encodedUrl = encodingExecutor.encode(EncodingType.BASE_64_V2); + + //then + assertThat(encodedUrl).isEqualTo("~"); + } + +} \ No newline at end of file diff --git a/src/test/java/com/young/shortenerurl/url/application/UrlServiceTest.java b/src/test/java/com/young/shortenerurl/url/application/UrlServiceTest.java new file mode 100644 index 00000000..ace91a25 --- /dev/null +++ b/src/test/java/com/young/shortenerurl/url/application/UrlServiceTest.java @@ -0,0 +1,160 @@ +package com.young.shortenerurl.url.application; + +import com.young.shortenerurl.global.generator.SequenceRepository; +import com.young.shortenerurl.support.IntegrationTest; +import com.young.shortenerurl.url.application.dto.UrlCreateRequest; +import com.young.shortenerurl.url.application.dto.UrlInfoFindResponse; +import com.young.shortenerurl.url.infrastructures.UrlJpaRepository; +import com.young.shortenerurl.url.model.EncodedUrl; +import com.young.shortenerurl.url.model.EncodingType; +import com.young.shortenerurl.url.model.Url; +import com.young.shortenerurl.url.util.Encoder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.assertj.core.api.Assertions.assertThat; + +class UrlServiceTest extends IntegrationTest { + + @Autowired + private UrlService urlService; + + @Autowired + private UrlJpaRepository urlJpaRepository; + + @Autowired + private SequenceRepository sequenceRepository; + + private Url setupUrl; + + @BeforeEach + void setup() { + Encoder encoder = EncodingType.BASE_64_V2.getEncoder(); + String originUrl = "setup-url1"; + + Url url = new Url( + originUrl, + new EncodedUrl(encoder.encode(5), EncodingType.BASE_64_V2) + ); + + setupUrl = urlJpaRepository.save(url); + } + + @AfterEach + void tearDown(){ + urlJpaRepository.deleteAll(); + sequenceRepository.deleteAll(); + } + + @Test + @DisplayName("originUrl과 Base64V2을 통해 인코딩된 url을 생성할 수 있다.") + void createUrl_Base64V2() { + //given + UrlCreateRequest request = new UrlCreateRequest("test-orgin-url", EncodingType.BASE_64_V2); + + //when + String encodedUrl = urlService.createUrl(request); + + //then + Url url = urlJpaRepository.findByEncodedUrl(encodedUrl).get(); + assertThat(url.getOriginUrl()).isEqualTo("test-orgin-url"); + } + + @Test + @DisplayName("originUrl과 Base64V1을 통해 인코딩된 url을 생성할 수 있다.") + void createUrl_Base64V1() { + //given + UrlCreateRequest request = new UrlCreateRequest("test-orgin-url", EncodingType.BASE_64_V1); + + //when + String encodedUrl = urlService.createUrl(request); + + //then + Url url = urlJpaRepository.findByEncodedUrl(encodedUrl).get(); + assertThat(url.getOriginUrl()).isEqualTo("test-orgin-url"); + } + + @Test + @DisplayName("url 저장 시 동일한 originUrl이 이미 존재한다면 존재하는 Url의 인코딩 url을 반환한다.") + void createUrl_alreadyExistUrl() { + //given + UrlCreateRequest request = new UrlCreateRequest("setup-url1", EncodingType.BASE_64_V2); + + //when + String encodedUrl = urlService.createUrl(request); + + //then + assertThat(encodedUrl).isEqualTo(setupUrl.getEncodedUrl()); + } + + @Test + @DisplayName("인코딩된 단축 URL을 통해 원본 URL을 조회할 수 있으며 조회수는 1씩 증가한다.") + void findOriginUrl() { + //given + String savedEncodedUrl = setupUrl.getEncodedUrl(); + String savedOriginUrl = setupUrl.getOriginUrl(); + + //when + String originUrl = urlService.findOriginUrl(savedEncodedUrl); + + //then + Url url = urlJpaRepository.findByEncodedUrl(savedEncodedUrl).get(); + + assertThat(originUrl).isEqualTo(savedOriginUrl); + assertThat(url.getVisitCount()).isEqualTo(1); + } + + @Test + @DisplayName("인코딩된 단축 URL을 통해 해당 URL의 방문 수를 확인할 수 있다.") + void findUrlVisitCount() { + //given + urlService.findOriginUrl(setupUrl.getEncodedUrl()); + urlService.findOriginUrl(setupUrl.getEncodedUrl()); + + //when + UrlInfoFindResponse response = urlService.findUrlInfoByEncodedUrl(setupUrl.getEncodedUrl()); + + //then + assertThat(response.originUrl()).isEqualTo(setupUrl.getOriginUrl()); + assertThat(response.encodedUrl()).isEqualTo(setupUrl.getEncodedUrl()); + assertThat(response.visitCount()).isEqualTo(2); + } + + @Test + @DisplayName("originUrl 조회 시 조회수 동시성 테스트") + void findOriginUrl_concurrencyTest() throws InterruptedException { + //given + int threadCount = 100; + ExecutorService executorService = Executors.newFixedThreadPool(32); + CountDownLatch latch = new CountDownLatch(threadCount); + + //when + for (int i = 0; i < threadCount; i++){ + executorService.submit(() -> { + try { + urlService.findOriginUrl(setupUrl.getEncodedUrl()); + } finally { + latch.countDown(); + } + }); + } + + latch.await(); + + //then + Url url = urlJpaRepository.findById(setupUrl.getId()) + .orElseThrow(); + + assertThat(url.getVisitCount()).isEqualTo(100L); + } + +} \ No newline at end of file diff --git a/src/test/resources/application-test.yml b/src/test/resources/application-test.yml new file mode 100644 index 00000000..1081ad80 --- /dev/null +++ b/src/test/resources/application-test.yml @@ -0,0 +1,12 @@ +spring: + datasource: + url: jdbc:h2:mem:refund_helper + driverClassName: org.h2.Driver + username: sa + password: + + jpa: + open-in-view: false + hibernate: + ddl-auto: create-drop + show-sql: true \ No newline at end of file