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..c73732ef 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,39 @@ # springboot-url-shortener -SprintBoot URL Shortener 구현 미션 Repository 입니다. - -## 요구사항 -각 요구사항을 모두 충족할 수 있도록 노력해봅시다. -- [ ] URL 입력폼 제공 및 결과 출력 -- [ ] URL Shortening Key는 8 Character 이내로 생성 -- [ ] 단축된 URL 요청시 원래 URL로 리다이렉트 -- [ ] 단축된 URL에 대한 요청 수 정보저장 (optional) -- [ ] Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 (optional) - - -## Short URL Service -### 읽으면 좋은 레퍼런스 -- [Naver 단축 URL API](https://developers.naver.com/docs/utils/shortenurl/) -- [짧게 줄인 URL의 실제 URL 확인 원리 및 방법](https://metalkin.tistory.com/50) -- [짧게 줄인 URL 알고리즘 고찰](https://metalkin.tistory.com/53) -- [단축 URL 원리 및 개발](https://blog.siyeol.com/26) - -### Short URL의 동작 과정 -예시로 bitly를 봅시다 -![image1](./image1.png) -![image2](./image2.png) -1. 원본 URL을 입력하고 Shorten 버튼을 클릭합니다. -2. Unique Key를 7문자 생성합니다. -3. Unique Key와 원본 URL을 DB에 저장합니다. -4. bitly.com/{Unique Key} 로 접근하면, DB를 조회하여 원본 URL로 redirect합니다. - -### Short URL의 특징 -단축 URL서비스는 간편하지만, 단점(위험성)이 있습니다. -링크를 클릭하는 사용자는 단축된 URL만 보고 클릭하기 때문에 어떤 곳으로 이동할지 알 수 없습니다. - -- Short URL 서비스는 주로 요청을 Redirect 시킵니다. (Redirect와 Forward의 차이점에 대해 검색해보세요.) -- 긴 URL을 짧은 URL로 압축할 수 있다. -- short url만으로는 어디에 연결되어있는 지 알 수 없다. 때문에 피싱 사이트 등의 보안에 취약하다. -- 광고를 본 뒤에 원본url로 넘겨주기도 한다. 이 과정에서 악성 광고가 나올 수 있다. -- 당연하지만 이미 존재하는 키를 입력하여 들어오는 사람이 존재할 수 있다. -- 기존의 원본 URL 변경되었더라도 단축 URL을 유지하여, 혼란을 방지할 수 있다. - -### 예시 사이트 -[https://url.kr/](https://url.kr/) + + + +사용자가 입력한 url에 대해 더 짧은 형태인 단축 url을 제공하는 서비스 입니다 + + + +- URL 입력폼 제공 및 결과 +- URL Shortening Key는 8 Character 이내로 생성 +- 단축된 URL 요청시 원래 URL로 리다이렉트 +- 단축된 URL에 대한 요청 수 정보저장 +- Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 + - (1) Base62 + - (2) 인덱스 번호 자체를 활용 +- IP 별 요청 횟수 제한 : Rate Limit Algorithm(Bucket4j) 사용 +- 배포 :~~https://shortenworld.kro.kr~~ + +https://github.com/prgrms-be-devcourse/springboot-url-shortener/assets/49016275/ee090c94-0845-46f3-a5ab-d3b8b652b9a0 + + + +- 초기 화면 + + +- 링크 단축하기 / 통계 버튼 클릭시 + + + +- 유효하지 않은 단축 url로 접속한 경우 + + + +- 같은 IP로 너무 많은 요청을 보낸 경우 + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..169dffff --- /dev/null +++ b/build.gradle @@ -0,0 +1,41 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'com.seungwon' +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' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'commons-codec:commons-codec:1.9' + implementation 'commons-validator:commons-validator:1.7' + implementation 'com.github.vladimir-bukhtoyarov:bucket4j-core:7.1.0' +} + +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 100755 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..6be9ab47 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springboot-url-shortener' diff --git a/src/main/java/com/seungwon/springbooturlshortener/SpringbootUrlShortenerApplication.java b/src/main/java/com/seungwon/springbooturlshortener/SpringbootUrlShortenerApplication.java new file mode 100644 index 00000000..0a5da973 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/SpringbootUrlShortenerApplication.java @@ -0,0 +1,13 @@ +package com.seungwon.springbooturlshortener; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootUrlShortenerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootUrlShortenerApplication.class, args); + } + +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/application/UrlService.java b/src/main/java/com/seungwon/springbooturlshortener/application/UrlService.java new file mode 100644 index 00000000..75edd01a --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/application/UrlService.java @@ -0,0 +1,20 @@ +package com.seungwon.springbooturlshortener.application; + +import org.springframework.stereotype.Service; + +import com.seungwon.springbooturlshortener.domain.EncoderType; +import com.seungwon.springbooturlshortener.domain.Url; +import com.seungwon.springbooturlshortener.domain.encoder.Encoder; + +@Service +public class UrlService { + + public void shorten(Url url, String type) { + Encoder encoder = EncoderType.getEncoder(type); + + long shortenCriteria = url.getId(); + String shortUrlKey = encoder.encode(shortenCriteria); + + url.saveShortUrlKey(shortUrlKey); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/application/UrlShortenerService.java b/src/main/java/com/seungwon/springbooturlshortener/application/UrlShortenerService.java new file mode 100644 index 00000000..bc14412b --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/application/UrlShortenerService.java @@ -0,0 +1,48 @@ +package com.seungwon.springbooturlshortener.application; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.seungwon.springbooturlshortener.application.dto.UrlCreateRequest; +import com.seungwon.springbooturlshortener.application.dto.UrlCreateResponse; +import com.seungwon.springbooturlshortener.domain.Url; +import com.seungwon.springbooturlshortener.exception.NotFoundException; +import com.seungwon.springbooturlshortener.infrastructure.UrlJpaRepository; + +import lombok.RequiredArgsConstructor; + +@Service +@Transactional +@RequiredArgsConstructor +public class UrlShortenerService { + + private final UrlJpaRepository urlJpaRepository; + + private final UrlService urlService; + + public UrlCreateResponse saveUrl(UrlCreateRequest urlCreateRequest) { + Url url = UrlCreateRequest.from(urlCreateRequest); + urlJpaRepository.save(url); + + String shortenType = urlCreateRequest.strategy(); + urlService.shorten(url, shortenType); + urlJpaRepository.save(url); + + return UrlCreateResponse.from(url); + } + + @Transactional(readOnly = true) + public String loadUrl(String shortUrlKey) { + Url url = urlJpaRepository.findByShortUrlKey(shortUrlKey) + .orElseThrow(NotFoundException::new); + + return url.getOriginalUrl(); + } + + @Transactional(readOnly = true) + public int countUrl(String originalUrl) { + int count = urlJpaRepository.countByOriginalUrl(originalUrl); + + return count; + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/application/dto/UrlCreateRequest.java b/src/main/java/com/seungwon/springbooturlshortener/application/dto/UrlCreateRequest.java new file mode 100644 index 00000000..59a08af5 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/application/dto/UrlCreateRequest.java @@ -0,0 +1,21 @@ +package com.seungwon.springbooturlshortener.application.dto; + +import org.hibernate.validator.constraints.URL; + +import com.seungwon.springbooturlshortener.domain.Url; + +import jakarta.validation.constraints.NotBlank; +import lombok.NonNull; + +public record UrlCreateRequest( + @NonNull + @NotBlank(message = "단축하고자 하는 URL을 입력하세요.") + @URL(message = "유효하지 않은 url 입니다.") + String originalUrl, + + String strategy +) { + public static Url from(UrlCreateRequest urlCreateRequest) { + return new Url(urlCreateRequest.originalUrl); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/application/dto/UrlCreateResponse.java b/src/main/java/com/seungwon/springbooturlshortener/application/dto/UrlCreateResponse.java new file mode 100644 index 00000000..c3860ff1 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/application/dto/UrlCreateResponse.java @@ -0,0 +1,11 @@ +package com.seungwon.springbooturlshortener.application.dto; + +import com.seungwon.springbooturlshortener.domain.Url; + +public record UrlCreateResponse( + String urlKey +) { + public static UrlCreateResponse from(Url url) { + return new UrlCreateResponse(url.getShortUrlKey()); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/domain/EncoderType.java b/src/main/java/com/seungwon/springbooturlshortener/domain/EncoderType.java new file mode 100644 index 00000000..08a508bc --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/domain/EncoderType.java @@ -0,0 +1,25 @@ +package com.seungwon.springbooturlshortener.domain; + +import java.util.function.Supplier; + +import com.seungwon.springbooturlshortener.domain.encoder.Base62encoder; +import com.seungwon.springbooturlshortener.domain.encoder.Encoder; +import com.seungwon.springbooturlshortener.domain.encoder.SequenceBaseEncoder; + +public enum EncoderType { + SEQUENCE(SequenceBaseEncoder::new), + BASE62(Base62encoder::new); + + private final Supplier encoder; + + EncoderType(Supplier encoder) { + this.encoder = encoder; + } + + public static Encoder getEncoder(String strategy) { + return EncoderType.valueOf(strategy) + .encoder + .get(); + } + +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/domain/RequestLimit.java b/src/main/java/com/seungwon/springbooturlshortener/domain/RequestLimit.java new file mode 100644 index 00000000..02ba56a4 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/domain/RequestLimit.java @@ -0,0 +1,28 @@ +package com.seungwon.springbooturlshortener.domain; + +import java.time.Duration; + +import org.springframework.stereotype.Component; + +import com.seungwon.springbooturlshortener.exception.ExcessiveRequestException; + +import io.github.bucket4j.Bandwidth; +import io.github.bucket4j.Bucket; + +@Component +public class RequestLimit { + private static final int CAPACITY = 10; + private static final int CONSUME_BUCKET_COUNT = 1; + private static final int DURATION = 1; + private final Bucket bucket = Bucket.builder() + .addLimit(Bandwidth.simple(CAPACITY, Duration.ofMinutes(DURATION))) + .build(); + + public void checkAvailability() { + if (bucket.tryConsume(CONSUME_BUCKET_COUNT)) { + return; + } + + throw new ExcessiveRequestException(); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/domain/Url.java b/src/main/java/com/seungwon/springbooturlshortener/domain/Url.java new file mode 100644 index 00000000..05ad5d02 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/domain/Url.java @@ -0,0 +1,53 @@ +package com.seungwon.springbooturlshortener.domain; + +import org.apache.commons.validator.routines.UrlValidator; + +import com.seungwon.springbooturlshortener.exception.InvalidUrlException; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Entity +@RequiredArgsConstructor +@Getter +public class Url { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String originalUrl; + + @Column(unique = true) + private String shortUrlKey; + + private static final int KEY_MAX_LENGTH = 7; + + public Url(String originalUrl) { + if (!isValid(originalUrl)) { + throw new InvalidUrlException(); + } + + this.originalUrl = originalUrl; + } + + public boolean isValid(String url) { + UrlValidator validator = new UrlValidator(); + + return validator.isValid(url); + } + + public void saveShortUrlKey(String shortUrlKey) { + if (shortUrlKey.length() > KEY_MAX_LENGTH) { + shortUrlKey = shortUrlKey.substring(0, KEY_MAX_LENGTH); + } + + this.shortUrlKey = shortUrlKey; + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/Base62encoder.java b/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/Base62encoder.java new file mode 100644 index 00000000..7894a489 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/Base62encoder.java @@ -0,0 +1,19 @@ +package com.seungwon.springbooturlshortener.domain.encoder; + +public class Base62encoder implements Encoder { + private static final int BASE = 62; + private static final char[] CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); + + @Override + public String encode(long originalValue) { + final StringBuilder encodedValue = new StringBuilder(); + + do { + int index = (int)originalValue % BASE; + encodedValue.append(CHARSET[index]); + originalValue /= BASE; + } while (originalValue > 0); + + return encodedValue.toString(); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/Encoder.java b/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/Encoder.java new file mode 100644 index 00000000..eb13bf24 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/Encoder.java @@ -0,0 +1,5 @@ +package com.seungwon.springbooturlshortener.domain.encoder; + +public interface Encoder { + String encode(long original); +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/SequenceBaseEncoder.java b/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/SequenceBaseEncoder.java new file mode 100644 index 00000000..c911100e --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/domain/encoder/SequenceBaseEncoder.java @@ -0,0 +1,8 @@ +package com.seungwon.springbooturlshortener.domain.encoder; + +public class SequenceBaseEncoder implements Encoder { + @Override + public String encode(long originalValue) { + return String.valueOf(originalValue + 1); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/exception/ExcessiveRequestException.java b/src/main/java/com/seungwon/springbooturlshortener/exception/ExcessiveRequestException.java new file mode 100644 index 00000000..040b0196 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/exception/ExcessiveRequestException.java @@ -0,0 +1,11 @@ +package com.seungwon.springbooturlshortener.exception; + +public class ExcessiveRequestException extends RuntimeException { + + public ExcessiveRequestException() { + } + + public ExcessiveRequestException(String message) { + super(message); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/exception/GlobalExceptionHandler.java b/src/main/java/com/seungwon/springbooturlshortener/exception/GlobalExceptionHandler.java new file mode 100644 index 00000000..3491a48b --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/exception/GlobalExceptionHandler.java @@ -0,0 +1,44 @@ +package com.seungwon.springbooturlshortener.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.View; +import org.springframework.web.servlet.view.InternalResourceView; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) { + return ResponseEntity.badRequest() + .body(exception.getFieldError().getDefaultMessage()); + } + + @ExceptionHandler(NotFoundException.class) + public View notFoundException(NotFoundException exception) { + return new InternalResourceView("error"); + } + + @ExceptionHandler(InvalidStrategyException.class) + public ResponseEntity invalidStrategyException(InvalidStrategyException exception) { + return ResponseEntity.badRequest() + .body("지원하지 않는 단축 방식입니다."); + } + + @ExceptionHandler(InvalidUrlException.class) + public ResponseEntity invalidUrlException(InvalidUrlException exception) { + return ResponseEntity.badRequest() + .body("유효하지 않은 url 입니다"); + } + + @ExceptionHandler(ExcessiveRequestException.class) + public ResponseEntity excessiveRequestException(ExcessiveRequestException exception) { + return ResponseEntity + .status(HttpStatus.TOO_MANY_REQUESTS) + .body("너무 많은 요청을 시도했습니다. 잠시 후에 다시 시도 바랍니다."); + } + +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/exception/InvalidStrategyException.java b/src/main/java/com/seungwon/springbooturlshortener/exception/InvalidStrategyException.java new file mode 100644 index 00000000..06d48d13 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/exception/InvalidStrategyException.java @@ -0,0 +1,10 @@ +package com.seungwon.springbooturlshortener.exception; + +public class InvalidStrategyException extends RuntimeException { + public InvalidStrategyException() { + } + + public InvalidStrategyException(String userInput) { + super(userInput); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/exception/InvalidUrlException.java b/src/main/java/com/seungwon/springbooturlshortener/exception/InvalidUrlException.java new file mode 100644 index 00000000..2bdc473a --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/exception/InvalidUrlException.java @@ -0,0 +1,11 @@ +package com.seungwon.springbooturlshortener.exception; + +public class InvalidUrlException extends RuntimeException { + public InvalidUrlException() { + super(); + } + + public InvalidUrlException(String message) { + super(message); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/exception/NotFoundException.java b/src/main/java/com/seungwon/springbooturlshortener/exception/NotFoundException.java new file mode 100644 index 00000000..3229f89f --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/exception/NotFoundException.java @@ -0,0 +1,10 @@ +package com.seungwon.springbooturlshortener.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException() { + } + + public NotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/infrastructure/UrlJpaRepository.java b/src/main/java/com/seungwon/springbooturlshortener/infrastructure/UrlJpaRepository.java new file mode 100644 index 00000000..c55455af --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/infrastructure/UrlJpaRepository.java @@ -0,0 +1,14 @@ +package com.seungwon.springbooturlshortener.infrastructure; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.seungwon.springbooturlshortener.domain.Url; + +public interface UrlJpaRepository extends JpaRepository { + + Optional findByShortUrlKey(String shortUrlKey); + + int countByOriginalUrl(String originalUrl); +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/presentation/UrlController.java b/src/main/java/com/seungwon/springbooturlshortener/presentation/UrlController.java new file mode 100644 index 00000000..bc953312 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/presentation/UrlController.java @@ -0,0 +1,53 @@ +package com.seungwon.springbooturlshortener.presentation; + +import java.net.URI; + +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +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.servlet.support.ServletUriComponentsBuilder; + +import com.seungwon.springbooturlshortener.application.UrlShortenerService; +import com.seungwon.springbooturlshortener.application.dto.UrlCreateRequest; +import com.seungwon.springbooturlshortener.application.dto.UrlCreateResponse; +import com.seungwon.springbooturlshortener.domain.RequestLimit; + +import lombok.RequiredArgsConstructor; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/urls") +public class UrlController { + + private final UrlShortenerService urlService; + + private final RequestLimit requestLimit; + + @PostMapping + public ResponseEntity urlSave(@Validated @RequestBody UrlCreateRequest urlCreateRequest) { + requestLimit.checkAvailability(); + + UrlCreateResponse urlCreateResponse = urlService.saveUrl(urlCreateRequest); + + URI uri = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{key}") + .buildAndExpand(urlCreateResponse.urlKey()) + .toUri(); + + return ResponseEntity.created(uri) + .body(urlCreateResponse); + } + + @GetMapping("/counts") + public ResponseEntity urlCount(@RequestParam String url) { + Integer count = urlService.countUrl(url); + + return ResponseEntity.ok(count); + } +} diff --git a/src/main/java/com/seungwon/springbooturlshortener/view/HomeViewController.java b/src/main/java/com/seungwon/springbooturlshortener/view/HomeViewController.java new file mode 100644 index 00000000..5b909894 --- /dev/null +++ b/src/main/java/com/seungwon/springbooturlshortener/view/HomeViewController.java @@ -0,0 +1,37 @@ +package com.seungwon.springbooturlshortener.view; + +import static org.springframework.http.HttpStatus.MOVED_PERMANENTLY; + +import java.net.URI; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import com.seungwon.springbooturlshortener.application.UrlShortenerService; + +import lombok.RequiredArgsConstructor; + +@Controller +@RequiredArgsConstructor +public class HomeViewController { + + private final UrlShortenerService urlService; + + @GetMapping + public String home() { + return "home"; + } + + @GetMapping("/{key}") + public ResponseEntity urlLoad(@PathVariable String key) { + String originalUrl = urlService.loadUrl(key); + + HttpHeaders httpHeader = new HttpHeaders(); + httpHeader.setLocation(URI.create(originalUrl)); + + return new ResponseEntity<>(httpHeader, MOVED_PERMANENTLY); + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1 @@ + diff --git a/src/main/resources/static/css/mainPage.css b/src/main/resources/static/css/mainPage.css new file mode 100644 index 00000000..e5833f27 --- /dev/null +++ b/src/main/resources/static/css/mainPage.css @@ -0,0 +1,22 @@ +.content { + position: absolute; + top: 40%; + left: 50%; + transform: translate(-50%, -50%); +} + +.title { + text-align: center; +} + +.buttonGroup { + align-content: center; + justify-content: center; + margin: 5px; +} + +.result { + text-align: center; + font-weight: bolder; + margin: 5px; +} diff --git a/src/main/resources/static/js/mainPage.js b/src/main/resources/static/js/mainPage.js new file mode 100644 index 00000000..5c25e2a4 --- /dev/null +++ b/src/main/resources/static/js/mainPage.js @@ -0,0 +1,78 @@ +function loadShortUrl() { + $("#t3-div-btn").remove(); + $("#info-button").remove(); + $("#statistics").text(""); + $(".shortUrl").text(""); + + const originalUrl = document.getElementById('originalUrl').value; + const strategy = document.getElementById('strategy').value; + + $.ajax({ + type: 'POST', + url: '/api/urls', + data: JSON.stringify({ + originalUrl: originalUrl, + strategy: strategy + }), + headers: { + 'Content-Type': 'application/json' + }, + success: function (data) { + $("#t3-div").text(window.location.href + data.urlKey); + const container = document.getElementById('buttonGroup'); + makeButton("t3-div-btn", "btn btn-secondary", "복사", container, () => copy("t3-div-btn")) + makeButton("info-button", "btn btn-secondary", "통계", container, () => loadInfo()); + }, + error: function (xhr, status, errorThrown) { + alert(xhr.responseText); + } + }); + + function loadInfo() { + + const originalUrl = document.getElementById('originalUrl').value; + + $.ajax({ + type: 'GET', + url: '/api/urls/counts?url=' + originalUrl, + + success: function (data) { + $("#statistics").text("해당 사이트에 대한 요청 횟수 : " + data); + }, + error: function () { + $("#statistics").text("조회에 실패했습니다. 재시도 바랍니다."); + } + }); + } +} + +function makeButton(id, className, innerText, parent, command) { + const button = document.createElement('button'); + button.id = id; + button.className = className; + button.innerText = innerText; + button.onclick = command; + button.style.cursor = 'pointer'; + button.style.margin = '5px'; + parent.appendChild(button); +} + + +function copy(btnID) { + const copyBtn = document.getElementById(btnID); + const textElement = document.getElementById(btnID.replace('-btn', '')); + let text = textElement.textContent; + + if (text) { + navigator.clipboard.writeText(text) + .then(() => { + if (copyBtn.textContent !== '완료') { + const originalText = copyBtn.textContent; + copyBtn.textContent = '완료'; + setTimeout(() => { + copyBtn.textContent = originalText; + }, 500); + } + }) + } +} diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html new file mode 100644 index 00000000..52a8cb75 --- /dev/null +++ b/src/main/resources/templates/error.html @@ -0,0 +1,24 @@ + + + + + + + + + + + + 해당 페이지를 찾지 못했습니다. + + + 단축 링크가 잘못되었거나 더 이상 제공되지 않는 페이지입니다. + + + 메인페이지로 이동 + + + diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 00000000..05e3ac58 --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,60 @@ + + + + + + URL Shortener + + + + + + + + + + + + + + + + URL SHORTENER + + + + + + + + + 단축할 긴 주소를 입력하세요 + + + + + + Base62 + Sequence + + 링크 단축 방식을 선택하세요 + + + 링크 단축하기 + + + + + + + + + + + + + + + diff --git a/src/test/java/com/seungwon/springbooturlshortener/SpringbootUrlShortenServiceApplicationTests.java b/src/test/java/com/seungwon/springbooturlshortener/SpringbootUrlShortenServiceApplicationTests.java new file mode 100644 index 00000000..11c11c79 --- /dev/null +++ b/src/test/java/com/seungwon/springbooturlshortener/SpringbootUrlShortenServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.seungwon.springbooturlshortener; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootUrlShortenServiceApplicationTests { + + @Test + void contextLoads() { + } + +}