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..efc42f79 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,8 @@ SprintBoot URL Shortener 구현 미션 Repository 입니다. ### Short URL의 동작 과정 예시로 bitly를 봅시다 -![image1](./image1.png) -![image2](./image2.png) +![image1](resources/image1.png) +![image2](resources/image2.png) 1. 원본 URL을 입력하고 Shorten 버튼을 클릭합니다. 2. Unique Key를 7문자 생성합니다. 3. Unique Key와 원본 URL을 DB에 저장합니다. diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..b6ee4542 --- /dev/null +++ b/build.gradle @@ -0,0 +1,39 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.0' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.programmers' +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' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-testcontainers' + testImplementation 'org.testcontainers:junit-jupiter' + testImplementation 'org.testcontainers:mysql' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..d64cd491 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..1af9e093 --- /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.5-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..1aa94a42 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && 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=SC2039,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=SC2039,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, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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/image1.png b/resources/image1.png similarity index 100% rename from image1.png rename to resources/image1.png diff --git a/image2.png b/resources/image2.png similarity index 100% rename from image2.png rename to resources/image2.png 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/programmers/springbooturlshortener/SpringbootUrlShortenerApplication.java b/src/main/java/com/programmers/springbooturlshortener/SpringbootUrlShortenerApplication.java new file mode 100644 index 00000000..384067cc --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/SpringbootUrlShortenerApplication.java @@ -0,0 +1,13 @@ +package com.programmers.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/programmers/springbooturlshortener/common/exception/ExceptionMessage.java b/src/main/java/com/programmers/springbooturlshortener/common/exception/ExceptionMessage.java new file mode 100644 index 00000000..88c2a9bd --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/common/exception/ExceptionMessage.java @@ -0,0 +1,13 @@ +package com.programmers.springbooturlshortener.common.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum ExceptionMessage { + NO_SUCH_URL_FOUND("일치하는 URL이 존재하지 않습니다."), + LONG_URL_FORMAT_MISMATCH("URL 포멧이 일치하지 않습니다."); + + private final String value; +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/application/UrlService.java b/src/main/java/com/programmers/springbooturlshortener/domain/application/UrlService.java new file mode 100644 index 00000000..1f9f7c1e --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/application/UrlService.java @@ -0,0 +1,35 @@ +package com.programmers.springbooturlshortener.domain.application; + +import com.programmers.springbooturlshortener.domain.dto.UrlServiceRequestDto; +import com.programmers.springbooturlshortener.domain.dto.UrlServiceResponseDto; +import com.programmers.springbooturlshortener.domain.entity.Url; +import com.programmers.springbooturlshortener.domain.exception.NoSuchUrlFoundException; +import com.programmers.springbooturlshortener.domain.infrastructure.UrlRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional +public class UrlService { + private final UrlRepository urlRepository; + + public UrlServiceResponseDto createShortUrl(UrlServiceRequestDto requestDto) { + String longUrl = requestDto.getLongUrl().getValue(); + Url url = urlRepository.findByLongUrlAndEncodeType(longUrl, requestDto.getEncodeType()) + .orElseGet(() -> urlRepository.save(Url.builder() + .longUrl(requestDto.getLongUrl().getValue()) + .shortUrl(requestDto.getEncodeType().encode(longUrl)) + .encodeType(requestDto.getEncodeType()) + .build()) + ); + return UrlServiceResponseDto.of(url); + } + + public UrlServiceResponseDto findLongUrl(UrlServiceRequestDto requestDto) { + Url url = urlRepository.findById(requestDto.getShortUrl()).orElseThrow(NoSuchUrlFoundException::new); + url.updateHit(); + return UrlServiceResponseDto.of(url); + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlControllerRequestDto.java b/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlControllerRequestDto.java new file mode 100644 index 00000000..7f5f2018 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlControllerRequestDto.java @@ -0,0 +1,12 @@ +package com.programmers.springbooturlshortener.domain.dto; + +import com.programmers.springbooturlshortener.domain.entity.EncodeType; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class UrlControllerRequestDto { + private final String longUrl; + private final EncodeType encodeType; +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlServiceRequestDto.java b/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlServiceRequestDto.java new file mode 100644 index 00000000..36be6c55 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlServiceRequestDto.java @@ -0,0 +1,23 @@ +package com.programmers.springbooturlshortener.domain.dto; + +import com.programmers.springbooturlshortener.domain.entity.EncodeType; +import com.programmers.springbooturlshortener.domain.entity.LongUrl; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class UrlServiceRequestDto { + private LongUrl longUrl; + private String shortUrl; + private EncodeType encodeType; + + @Builder + private UrlServiceRequestDto(LongUrl longUrl, String shortUrl, EncodeType encodeType) { + this.longUrl = longUrl; + this.shortUrl = shortUrl; + this.encodeType = encodeType; + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlServiceResponseDto.java b/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlServiceResponseDto.java new file mode 100644 index 00000000..0bbff9e8 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/dto/UrlServiceResponseDto.java @@ -0,0 +1,29 @@ +package com.programmers.springbooturlshortener.domain.dto; + +import com.programmers.springbooturlshortener.domain.entity.LongUrl; +import com.programmers.springbooturlshortener.domain.entity.Url; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class UrlServiceResponseDto { + private LongUrl longUrl; + private String shortUrl; + private long hit; + + private UrlServiceResponseDto(LongUrl longUrl, String shortUrl, long hit) { + this.longUrl = longUrl; + this.shortUrl = shortUrl; + this.hit = hit; + } + + public static UrlServiceResponseDto of(Url url) { + return new UrlServiceResponseDto( + LongUrl.from(url.getLongUrl()), + url.getShortUrl(), + url.getHit() + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/entity/EncodeType.java b/src/main/java/com/programmers/springbooturlshortener/domain/entity/EncodeType.java new file mode 100644 index 00000000..16048b0e --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/entity/EncodeType.java @@ -0,0 +1,20 @@ +package com.programmers.springbooturlshortener.domain.entity; + + +import com.programmers.springbooturlshortener.domain.infrastructure.utils.Base58; +import com.programmers.springbooturlshortener.domain.infrastructure.utils.Base62; + +import java.util.function.UnaryOperator; + +public enum EncodeType { + BASE62(Base62::encode), BASE58(Base58::encode); + private final UnaryOperator function; + + EncodeType(UnaryOperator function) { + this.function = function; + } + + public String encode(String url) { + return function.apply(url); + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/entity/LongUrl.java b/src/main/java/com/programmers/springbooturlshortener/domain/entity/LongUrl.java new file mode 100644 index 00000000..0064cb71 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/entity/LongUrl.java @@ -0,0 +1,42 @@ +package com.programmers.springbooturlshortener.domain.entity; + +import com.programmers.springbooturlshortener.domain.exception.LongUrlFormatMismatchException; +import lombok.Getter; + +import java.util.Objects; +import java.util.regex.Pattern; + +@Getter +public class LongUrl { + private static final Pattern PATTERN = Pattern.compile("[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?"); + private final String value; + + private LongUrl(String value) { + this.value = value; + } + + public static LongUrl from(String longUrl) { + if (!PATTERN.matcher(longUrl).matches()) { + throw new LongUrlFormatMismatchException(); + } + return new LongUrl(longUrl); + } + + @Override + public String toString() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + LongUrl longUrl = (LongUrl) o; + return Objects.equals(value, longUrl.value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/entity/Url.java b/src/main/java/com/programmers/springbooturlshortener/domain/entity/Url.java new file mode 100644 index 00000000..e2ba00b5 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/entity/Url.java @@ -0,0 +1,39 @@ +package com.programmers.springbooturlshortener.domain.entity; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Entity +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "url") +public class Url { + @Id + @Column(nullable = false, updatable = false, length = 7) + private String shortUrl; + + @Column(nullable = false) + private String longUrl; + + @Enumerated + @Column(name = "encode_type") + private EncodeType encodeType; + + @Column(nullable = false) + private Long hit = 0L; + + @Builder + private Url(String longUrl, String shortUrl, EncodeType encodeType) { + this.shortUrl = shortUrl; + this.longUrl = longUrl; + this.encodeType = encodeType; + } + + public void updateHit() { + hit += 1; + } + +} \ No newline at end of file diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/exception/LongUrlFormatMismatchException.java b/src/main/java/com/programmers/springbooturlshortener/domain/exception/LongUrlFormatMismatchException.java new file mode 100644 index 00000000..bd805693 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/exception/LongUrlFormatMismatchException.java @@ -0,0 +1,9 @@ +package com.programmers.springbooturlshortener.domain.exception; + +import static com.programmers.springbooturlshortener.common.exception.ExceptionMessage.LONG_URL_FORMAT_MISMATCH; + +public class LongUrlFormatMismatchException extends RuntimeException { + public LongUrlFormatMismatchException() { + super(LONG_URL_FORMAT_MISMATCH.getValue()); + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/exception/NoSuchUrlFoundException.java b/src/main/java/com/programmers/springbooturlshortener/domain/exception/NoSuchUrlFoundException.java new file mode 100644 index 00000000..03070b26 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/exception/NoSuchUrlFoundException.java @@ -0,0 +1,9 @@ +package com.programmers.springbooturlshortener.domain.exception; + +import static com.programmers.springbooturlshortener.common.exception.ExceptionMessage.NO_SUCH_URL_FOUND; + +public class NoSuchUrlFoundException extends RuntimeException{ + public NoSuchUrlFoundException() { + super(NO_SUCH_URL_FOUND.getValue()); + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/UrlRepository.java b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/UrlRepository.java new file mode 100644 index 00000000..d525d1bc --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/UrlRepository.java @@ -0,0 +1,14 @@ +package com.programmers.springbooturlshortener.domain.infrastructure; + +import com.programmers.springbooturlshortener.domain.entity.EncodeType; +import com.programmers.springbooturlshortener.domain.entity.Url; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UrlRepository extends JpaRepository { + + Optional findByLongUrlAndEncodeType(String longUrl, EncodeType encodeType); +} \ No newline at end of file diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/Base58.java b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/Base58.java new file mode 100644 index 00000000..fd0f099e --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/Base58.java @@ -0,0 +1,26 @@ +package com.programmers.springbooturlshortener.domain.infrastructure.utils; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import static com.programmers.springbooturlshortener.domain.infrastructure.utils.EncodeHelper.encoding; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class Base58 { + private static final char[] TOKENS = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', + 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', + '4', '5', '6', '7', '8', '9' + }; + + private static final String PREFIX = "-"; + private static final int HEX_LENGTH = 7; + private static final int TOKEN_LENGTH = TOKENS.length; + + public static String encode(String url) { + return encoding(url, HEX_LENGTH, TOKENS, TOKEN_LENGTH, PREFIX); + } + +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/Base62.java b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/Base62.java new file mode 100644 index 00000000..078696e4 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/Base62.java @@ -0,0 +1,24 @@ +package com.programmers.springbooturlshortener.domain.infrastructure.utils; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import static com.programmers.springbooturlshortener.domain.infrastructure.utils.EncodeHelper.encoding; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class Base62 { + private static final char[] TOKENS = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' + }; + private static final int TOKEN_LENGTH = TOKENS.length; + private static final int HEX_LENGTH = 10; + + public static String encode(String url) { + return encoding(url, HEX_LENGTH, TOKENS, TOKEN_LENGTH); + } + +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/EncodeHelper.java b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/EncodeHelper.java new file mode 100644 index 00000000..8c1a7340 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/EncodeHelper.java @@ -0,0 +1,48 @@ +package com.programmers.springbooturlshortener.domain.infrastructure.utils; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class EncodeHelper { + private static final String ALGORITHM = "SHA-256"; + + protected static String encoding(String url, int hexLength, char[] tokens, int tokenLength) { + StringBuilder result = new StringBuilder(); + try { + long src = hashingURL(url.getBytes(), hexLength); + do { + result.insert(0, tokens[(int) (src % tokenLength)]); + src /= tokenLength; + } while (src > 0); + } catch (NoSuchAlgorithmException ignored) { + } + return result.toString(); + } + + protected static String encoding(String url, int hexLength, char[] tokens, int tokenLength, String prefix) { + return prefix + encoding(url, hexLength, tokens, tokenLength); + } + + private static long hashingURL(byte[] bytes, int length) throws NoSuchAlgorithmException { + MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM); + messageDigest.update(bytes); + byte[] hashBytes = messageDigest.digest(); + return Long.parseLong(bytesToHex(hashBytes).substring(0, length), 16); + } + + private static String bytesToHex(byte[] bytes) { + final char[] hexDigits = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + StringBuilder sb = new StringBuilder(2 * bytes.length); + for (byte b : bytes) { + sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]); + } + return sb.toString(); + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/presentation/GlobalExceptionHandler.java b/src/main/java/com/programmers/springbooturlshortener/domain/presentation/GlobalExceptionHandler.java new file mode 100644 index 00000000..93a08285 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/presentation/GlobalExceptionHandler.java @@ -0,0 +1,14 @@ +package com.programmers.springbooturlshortener.domain.presentation; + +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(Exception.class) + public String handleException(Exception e, Model model) { + model.addAttribute("message", e.getMessage()); + return "error"; + } +} diff --git a/src/main/java/com/programmers/springbooturlshortener/domain/presentation/UrlController.java b/src/main/java/com/programmers/springbooturlshortener/domain/presentation/UrlController.java new file mode 100644 index 00000000..c6738f24 --- /dev/null +++ b/src/main/java/com/programmers/springbooturlshortener/domain/presentation/UrlController.java @@ -0,0 +1,46 @@ +package com.programmers.springbooturlshortener.domain.presentation; + +import com.programmers.springbooturlshortener.domain.application.UrlService; +import com.programmers.springbooturlshortener.domain.dto.UrlControllerRequestDto; +import com.programmers.springbooturlshortener.domain.dto.UrlServiceRequestDto; +import com.programmers.springbooturlshortener.domain.dto.UrlServiceResponseDto; +import com.programmers.springbooturlshortener.domain.entity.EncodeType; +import com.programmers.springbooturlshortener.domain.entity.LongUrl; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +@Controller +@RequiredArgsConstructor +@RequestMapping("/") +public class UrlController { + private final UrlService urlService; + private static final String SERVER_URL = "http://localhost:8080/"; + + @GetMapping + public String home(Model model) { + model.addAttribute("encodeTypes", EncodeType.values()); + return "home"; + } + + @PostMapping + public String createUrl(UrlControllerRequestDto requestDto, Model model) { + UrlServiceResponseDto responseDto = urlService.createShortUrl(UrlServiceRequestDto.builder() + .longUrl(LongUrl.from(requestDto.getLongUrl())) + .encodeType(requestDto.getEncodeType()) + .build() + ); + model.addAttribute("longUrl", requestDto.getLongUrl()); + model.addAttribute("shortUrl", SERVER_URL + responseDto.getShortUrl()); + model.addAttribute("encodeTypes", EncodeType.values()); + return "home"; + } + + + @GetMapping("{shortUrl}") + public String findUrl(@PathVariable String shortUrl) { + UrlServiceResponseDto responseDto = urlService.findLongUrl(UrlServiceRequestDto.builder().shortUrl(shortUrl).build()); + return "redirect:" + responseDto.getLongUrl(); + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 00000000..ec0d0d01 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,10 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/ShortUrl + username: root + password: root! + + jpa: + hibernate: + ddl-auto: update \ No newline at end of file diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html new file mode 100644 index 00000000..7c2f6255 --- /dev/null +++ b/src/main/resources/templates/error.html @@ -0,0 +1,20 @@ + + + + + + Short Url + + + +

Short Url

+

Exception Occur!!

+ +
+ +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 00000000..f07df2cf --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,52 @@ + + + + + + Short Url + + + +

Short Url

+
+
+
+
+
+ + +
+
+ + +
+
+ +
+
+
+
+
+
+
+
+
Link:
+
+
+
+
+
+
Convert To:
+
+
+
+
+
+
+ + \ No newline at end of file diff --git a/src/test/java/com/programmers/springbooturlshortener/domain/application/UrlServiceTest.java b/src/test/java/com/programmers/springbooturlshortener/domain/application/UrlServiceTest.java new file mode 100644 index 00000000..4365a02b --- /dev/null +++ b/src/test/java/com/programmers/springbooturlshortener/domain/application/UrlServiceTest.java @@ -0,0 +1,109 @@ +package com.programmers.springbooturlshortener.domain.application; + +import com.programmers.springbooturlshortener.domain.dto.UrlServiceRequestDto; +import com.programmers.springbooturlshortener.domain.dto.UrlServiceResponseDto; +import com.programmers.springbooturlshortener.domain.entity.EncodeType; +import com.programmers.springbooturlshortener.domain.entity.LongUrl; +import com.programmers.springbooturlshortener.domain.entity.Url; +import com.programmers.springbooturlshortener.domain.exception.NoSuchUrlFoundException; +import com.programmers.springbooturlshortener.domain.infrastructure.UrlRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static com.programmers.springbooturlshortener.common.exception.ExceptionMessage.NO_SUCH_URL_FOUND; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@SpringBootTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@DisplayName("Test UrlService") +@Transactional +@Testcontainers +class UrlServiceTest { + + @Autowired + private UrlRepository urlRepository; + @Autowired + private UrlService urlService; + + private final String longUrlValue = "https://google.com"; + private final LongUrl longUrl = LongUrl.from(longUrlValue); + private final EncodeType encodeType = EncodeType.BASE62; + + @DisplayName("Test create Short URL") + @Test + void testCreateShortUrl() { + // Arrange + UrlServiceRequestDto requestDto = UrlServiceRequestDto.builder() + .longUrl(longUrl) + .encodeType(encodeType) + .build(); + // Act + UrlServiceResponseDto actualResult = urlService.createShortUrl(requestDto); + // Assert + assertThat(actualResult).isNotNull(); + assertThat(actualResult.getLongUrl().getValue()).isEqualTo(longUrlValue); + assertThat(actualResult.getShortUrl()).isNotNull(); + assertThat(actualResult.getHit()).isZero(); + } + + @DisplayName("Test create Short URL if already Have") + @Test + void testCreateShortUrlDuplicated() { + // Arrange + Url expectedUrl = urlRepository.save(Url.builder() + .longUrl(longUrlValue) + .encodeType(encodeType) + .shortUrl(encodeType.encode(longUrlValue)) + .build()); + UrlServiceRequestDto requestDto = UrlServiceRequestDto.builder() + .longUrl(longUrl) + .encodeType(encodeType) + .build(); + // Act + UrlServiceResponseDto actualResult = urlService.createShortUrl(requestDto); + // Assert + assertThat(actualResult).isNotNull(); + assertThat(actualResult.getLongUrl().getValue()).isEqualTo(expectedUrl.getLongUrl()); + assertThat(actualResult.getShortUrl()).isEqualTo(expectedUrl.getShortUrl()); + assertThat(actualResult.getHit()).isZero(); + } + + @DisplayName("Test find Short URL Success") + @Test + void testFindShortUrlSuccess(){ + // Arrange + Url expectedUrl = urlRepository.save(Url.builder() + .longUrl(longUrlValue) + .encodeType(encodeType) + .shortUrl(encodeType.encode(longUrlValue)) + .build()); + UrlServiceRequestDto requestDto = UrlServiceRequestDto.builder() + .shortUrl(expectedUrl.getShortUrl()) + .build(); + // Act + UrlServiceResponseDto actualResult = urlService.findLongUrl(requestDto); + // Assert + assertThat(actualResult).isNotNull(); + assertThat(actualResult.getLongUrl().getValue()).isEqualTo(expectedUrl.getLongUrl()); + assertThat(actualResult.getShortUrl()).isEqualTo(expectedUrl.getShortUrl()); + assertThat(actualResult.getHit()).isNotZero(); + } + + @DisplayName("Test find Short URL Fail") + @Test + void testFindShortUrlFailWhenNoSuchShortUrl(){ + // Arrange + UrlServiceRequestDto requestDto = UrlServiceRequestDto.builder() + .shortUrl(encodeType.encode(longUrlValue)) + .build(); + // Act & Assert + Throwable actualResult = assertThrows(NoSuchUrlFoundException.class, () -> urlService.findLongUrl(requestDto)); + assertThat(actualResult).hasMessage(NO_SUCH_URL_FOUND.getValue()); + } +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbooturlshortener/domain/entity/LongUrlTest.java b/src/test/java/com/programmers/springbooturlshortener/domain/entity/LongUrlTest.java new file mode 100644 index 00000000..62740951 --- /dev/null +++ b/src/test/java/com/programmers/springbooturlshortener/domain/entity/LongUrlTest.java @@ -0,0 +1,32 @@ +package com.programmers.springbooturlshortener.domain.entity; + +import com.programmers.springbooturlshortener.domain.exception.LongUrlFormatMismatchException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static com.programmers.springbooturlshortener.common.exception.ExceptionMessage.LONG_URL_FORMAT_MISMATCH; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("Test LongUrl Value") +class LongUrlTest { + + @Test + void testCreateLongUrlSuccess() { + // Arrange + String expectedUrl = "https://google.com"; + // Act + LongUrl actualResult = LongUrl.from(expectedUrl); + // Assert + assertThat(actualResult.getValue()).isEqualTo(expectedUrl); + } + + @Test + void testCreateLongUrlFail() { + // Arrange + String expectedUrl = "temp"; + // Act & Assert + Throwable actualResult = assertThrows(LongUrlFormatMismatchException.class, () -> LongUrl.from(expectedUrl)); + assertThat(actualResult).hasMessage(LONG_URL_FORMAT_MISMATCH.getValue()); + } +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbooturlshortener/domain/entity/UrlTest.java b/src/test/java/com/programmers/springbooturlshortener/domain/entity/UrlTest.java new file mode 100644 index 00000000..3eb64a72 --- /dev/null +++ b/src/test/java/com/programmers/springbooturlshortener/domain/entity/UrlTest.java @@ -0,0 +1,48 @@ +package com.programmers.springbooturlshortener.domain.entity; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("Test Url Entity") +class UrlTest { + + private final String expectedLongUrl = "https://google.com"; + private final EncodeType expectedEncodeType = EncodeType.BASE62; + private final String expectedShortUrl = expectedEncodeType.encode(expectedLongUrl); + + @DisplayName("Test Create Url") + @Test + void testCreateUrl() { + // Act + Url actualResult = Url.builder() + .longUrl(expectedLongUrl) + .shortUrl(expectedShortUrl) + .encodeType(expectedEncodeType) + .build(); + // Assert + assertThat(actualResult).isNotNull(); + assertThat(actualResult.getLongUrl()).isEqualTo(expectedLongUrl); + assertThat(actualResult.getShortUrl()).isEqualTo(expectedShortUrl); + assertThat(actualResult.getEncodeType()).isEqualTo(expectedEncodeType); + assertThat(actualResult.getHit()).isZero(); + } + + @DisplayName("Test Update Hit") + @Test + void testUpdateHitSuccess() { + // Arrange + Url actualResult = Url.builder() + .longUrl(expectedLongUrl) + .shortUrl(expectedShortUrl) + .encodeType(expectedEncodeType) + .build(); + // Act + actualResult.updateHit(); + // Assert + assertThat(actualResult.getHit()).isNotZero(); + assertThat(actualResult.getHit()).isEqualTo(1L); + } + +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/EncoderTest.java b/src/test/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/EncoderTest.java new file mode 100644 index 00000000..02695e88 --- /dev/null +++ b/src/test/java/com/programmers/springbooturlshortener/domain/infrastructure/utils/EncoderTest.java @@ -0,0 +1,34 @@ +package com.programmers.springbooturlshortener.domain.infrastructure.utils; + +import com.programmers.springbooturlshortener.domain.entity.EncodeType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("Test Encoder {Base62, Base58}") +class EncoderTest { + + private static final String URL = "https://google.com"; + private static final int SHORT_URL_LENGTH = 7; + + @DisplayName("Test Base62 encode") + @Test + void testBase62Encode() { + // Act + String actualResult = EncodeType.BASE62.encode(URL); + // Assert + assertThat(actualResult.length()).isLessThanOrEqualTo(SHORT_URL_LENGTH); + } + + @DisplayName("Test Base58 encode") + @Test + void testBase58Encode() { + // Act + String actualResult = EncodeType.BASE58.encode(URL); + // Assert + assertThat(actualResult.length()).isLessThanOrEqualTo(SHORT_URL_LENGTH); + assertThat(actualResult).contains("-"); + } + +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbooturlshortener/domain/presentation/UrlControllerTest.java b/src/test/java/com/programmers/springbooturlshortener/domain/presentation/UrlControllerTest.java new file mode 100644 index 00000000..86e20b93 --- /dev/null +++ b/src/test/java/com/programmers/springbooturlshortener/domain/presentation/UrlControllerTest.java @@ -0,0 +1,76 @@ +package com.programmers.springbooturlshortener.domain.presentation; + +import com.programmers.springbooturlshortener.domain.application.UrlService; +import com.programmers.springbooturlshortener.domain.dto.UrlControllerRequestDto; +import com.programmers.springbooturlshortener.domain.dto.UrlServiceRequestDto; +import com.programmers.springbooturlshortener.domain.dto.UrlServiceResponseDto; +import com.programmers.springbooturlshortener.domain.entity.Url; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import static com.programmers.springbooturlshortener.domain.entity.EncodeType.BASE62; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@WebMvcTest(UrlController.class) +@DisplayName("Test UrlController") +class UrlControllerTest { + + @Autowired + private MockMvc mockMvc; + @MockBean + private UrlService urlService; + + @Test + void testHomeView() throws Exception { + // Arrange + var get = get("/"); + // Act & Assert + mockMvc.perform(get) + .andExpect(status().isOk()) + .andExpect(view().name("home")); + } + + @Test + void testPostMethod() throws Exception { + // Arrange + var post = post("/").flashAttr("UrlControllerRequestDto", new UrlControllerRequestDto("https://programmers.com", BASE62)); + // Act & Assert + mockMvc.perform(post) + .andExpect(status().isOk()); + } + + @Test + void testShortUrlRedirectSuccess() throws Exception { + // Arrange + Url url = Url.builder() + .longUrl("https://programmers.com") + .encodeType(BASE62) + .shortUrl(BASE62.encode("https://programmers.com")) + .build(); + when(urlService.findLongUrl(any(UrlServiceRequestDto.class))).thenReturn(UrlServiceResponseDto.of(url)); + var get = get("/{shortUrl}", url.getShortUrl()); + // Act & Assert + mockMvc.perform(get) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl(url.getLongUrl())); + } + + @Test + void testShortUrlRedirectFail() throws Exception { + // Arrange + var get = get("/{shortUrl}", "temp"); + // Act & Assert + mockMvc.perform(get) + .andExpect(status().isOk()) + .andExpect(view().name("error")); + } + +} \ No newline at end of file diff --git a/src/test/resources/application.yaml b/src/test/resources/application.yaml new file mode 100644 index 00000000..b4e42fd7 --- /dev/null +++ b/src/test/resources/application.yaml @@ -0,0 +1,8 @@ +spring: + datasource: + driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver + url: jdbc:tc:mysql:latest:///test-database + jpa: + hibernate: + ddl-auto: update + database: mysql \ No newline at end of file