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..8e32378f 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,22 @@ SprintBoot URL Shortener 구현 미션 Repository 입니다. ## 요구사항 각 요구사항을 모두 충족할 수 있도록 노력해봅시다. - [ ] URL 입력폼 제공 및 결과 출력 -- [ ] URL Shortening Key는 8 Character 이내로 생성 -- [ ] 단축된 URL 요청시 원래 URL로 리다이렉트 -- [ ] 단축된 URL에 대한 요청 수 정보저장 (optional) -- [ ] Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 (optional) +- [X] URL Shortening Key는 8 Character 이내로 생성 +- [X] 단축된 URL 요청시 원래 URL로 리다이렉트 +- [X] 단축된 URL에 대한 요청 수 정보저장 (optional) +- [X] Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 (optional) +## 구현 기능 +1. url -> short url 만들기 + - [X] url을 입력받는다. (localhost:8080/{url}) + - [X] url을 short url로 변환한다. + - [X] url과 short url을 db에 저장한다. +2. short url - > url + - [X] 호출이 일어나면 요청 수(count) 증가 저장 + - [X] short url을 토대로 db에서 url을 가져옴. + - [X] url을 리다이렉트 처리 + ## Short URL Service ### 읽으면 좋은 레퍼런스 - [Naver 단축 URL API](https://developers.naver.com/docs/utils/shortenurl/) diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..db48af76 --- /dev/null +++ b/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.0' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +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' + annotationProcessor 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} 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/settings.gradle b/settings.gradle new file mode 100644 index 00000000..e69de29b diff --git a/src/main/java/com/programmers/UrlApplication.java b/src/main/java/com/programmers/UrlApplication.java new file mode 100644 index 00000000..83a44ead --- /dev/null +++ b/src/main/java/com/programmers/UrlApplication.java @@ -0,0 +1,13 @@ +package com.programmers; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class UrlApplication { + + public static void main(String[] args) { + SpringApplication.run(UrlApplication.class, args); + } + +} diff --git a/src/main/java/com/programmers/component/DefaultUriGenerator.java b/src/main/java/com/programmers/component/DefaultUriGenerator.java new file mode 100644 index 00000000..a9d74704 --- /dev/null +++ b/src/main/java/com/programmers/component/DefaultUriGenerator.java @@ -0,0 +1,25 @@ +package com.programmers.component; + +import com.programmers.dto.ShortUriGenerateRequestDto; +import lombok.RequiredArgsConstructor; + +import java.util.Random; + +@RequiredArgsConstructor +public class DefaultUriGenerator implements ShortUriGenerator { + private final Random random = new Random(); + private static final int LENGTH = 7; + private final char[] wordlist = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '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'}; + + @Override + public String generate(ShortUriGenerateRequestDto requestDto) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < LENGTH; i++) { + int randomIndex = random.nextInt(wordlist.length); + sb.append(wordlist[randomIndex]); + } + return sb.toString(); + } +} diff --git a/src/main/java/com/programmers/component/IndexUriGenerator.java b/src/main/java/com/programmers/component/IndexUriGenerator.java new file mode 100644 index 00000000..f3506e55 --- /dev/null +++ b/src/main/java/com/programmers/component/IndexUriGenerator.java @@ -0,0 +1,29 @@ +package com.programmers.component; + +import com.programmers.dto.ShortUriGenerateRequestDto; + +import java.util.Random; + +public class IndexUriGenerator implements ShortUriGenerator { + private Random random = new Random(); + private static final int LENGTH = 7; + private final char[] wordlist = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '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'}; + + @Override + public String generate(ShortUriGenerateRequestDto requestDto) { + Long index = requestDto.index(); + StringBuilder sb = new StringBuilder(); + while (index % 62 > 0 || sb.isEmpty()) { + sb.append(wordlist[(int) (index % 62)]); + index /= 62; + } + + while (sb.length() < LENGTH) { + int randomIndex = random.nextInt(wordlist.length); + sb.append(wordlist[randomIndex]); + } + return sb.toString(); + } +} diff --git a/src/main/java/com/programmers/component/ShortUriGenerator.java b/src/main/java/com/programmers/component/ShortUriGenerator.java new file mode 100644 index 00000000..dbc6f737 --- /dev/null +++ b/src/main/java/com/programmers/component/ShortUriGenerator.java @@ -0,0 +1,7 @@ +package com.programmers.component; + +import com.programmers.dto.ShortUriGenerateRequestDto; + +public interface ShortUriGenerator { + String generate(ShortUriGenerateRequestDto requestDto); +} diff --git a/src/main/java/com/programmers/component/UriConverter.java b/src/main/java/com/programmers/component/UriConverter.java new file mode 100644 index 00000000..b3a735ba --- /dev/null +++ b/src/main/java/com/programmers/component/UriConverter.java @@ -0,0 +1,12 @@ +package com.programmers.component; + +import com.programmers.entity.UriEntity; +import com.programmers.model.CreateResponse; +import org.springframework.stereotype.Component; + +@Component +public class UriConverter { + public CreateResponse convertCreateResponseFrom(UriEntity uri) { + return new CreateResponse(uri.getShortUri(), uri.getCount()); + } +} diff --git a/src/main/java/com/programmers/controller/UriController.java b/src/main/java/com/programmers/controller/UriController.java new file mode 100644 index 00000000..99e604ef --- /dev/null +++ b/src/main/java/com/programmers/controller/UriController.java @@ -0,0 +1,40 @@ +package com.programmers.controller; + +import com.programmers.model.CreateRequest; +import com.programmers.model.CreateResponse; +import com.programmers.service.UriService; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +@RequiredArgsConstructor +@Controller +@RequestMapping("/") +public class UriController { + private final UriService uriService; + + @GetMapping + public String home(Model model) { + model.addAttribute("createRequest", new CreateRequest()); + return "home"; + } + + // shortUri -> uri redirect + @GetMapping("{shortUri}") + public String redirectShortUri(@PathVariable @NotBlank String shortUri) { + String originalUri = uriService.getOriginalUri(shortUri); + return "redirect:" + originalUri; + } + + // uri -> shortUri create + @PostMapping("api") + public String createShortUri(@ModelAttribute @Valid CreateRequest request, Model model) { + CreateResponse createResponse = uriService.createShortUri(request.getUri()); + model.addAttribute("shortUri", createResponse.getShortUri()); + model.addAttribute("count", createResponse.getCount()); + return "result"; + } +} diff --git a/src/main/java/com/programmers/controller/UriControllerAdvice.java b/src/main/java/com/programmers/controller/UriControllerAdvice.java new file mode 100644 index 00000000..ae7fb8d8 --- /dev/null +++ b/src/main/java/com/programmers/controller/UriControllerAdvice.java @@ -0,0 +1,13 @@ +package com.programmers.controller; + +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class UriControllerAdvice { + + @ExceptionHandler(Exception.class) + public String handle(Exception e) { + return "error"; + } +} diff --git a/src/main/java/com/programmers/dto/ShortUriGenerateRequestDto.java b/src/main/java/com/programmers/dto/ShortUriGenerateRequestDto.java new file mode 100644 index 00000000..f1d82a42 --- /dev/null +++ b/src/main/java/com/programmers/dto/ShortUriGenerateRequestDto.java @@ -0,0 +1,6 @@ +package com.programmers.dto; + +import lombok.Builder; +@Builder +public record ShortUriGenerateRequestDto(String originalUri, Long index) { +} diff --git a/src/main/java/com/programmers/entity/UriEntity.java b/src/main/java/com/programmers/entity/UriEntity.java new file mode 100644 index 00000000..4f2d444b --- /dev/null +++ b/src/main/java/com/programmers/entity/UriEntity.java @@ -0,0 +1,42 @@ +package com.programmers.entity; + +import jakarta.persistence.*; +import lombok.Getter; + +@Getter +@Entity +@Table(name = "URI") +public class UriEntity { + + @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "uri_entity_seq_generator") + @SequenceGenerator(name = "uri_entity_seq_generator", sequenceName = "uri_entity_seq", initialValue = 1000000) + private Long id; + + private String originalUri; + private String shortUri; + private int count = 0; + + public UriEntity() { + } + public UriEntity(String uri) { + this(null, uri, null); + } + + public UriEntity(Long id, String uri) { + this(id, uri, null); + } + + public UriEntity(Long id, String originalUri, String shortUri) { + this.id = id; + this.originalUri = originalUri; + this.shortUri = shortUri; + } + + public void initShortUri(String shortUri) { + this.shortUri = shortUri; + } + + public void increaseCount() { + this.count++; + } +} diff --git a/src/main/java/com/programmers/model/CreateRequest.java b/src/main/java/com/programmers/model/CreateRequest.java new file mode 100644 index 00000000..1622cf4d --- /dev/null +++ b/src/main/java/com/programmers/model/CreateRequest.java @@ -0,0 +1,14 @@ +package com.programmers.model; + +import jakarta.validation.constraints.NotBlank; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.validator.constraints.URL; + +@Getter +@Setter +public class CreateRequest { + @NotBlank(message = "URL 값이 필요합니다.") + @URL(message = "URL 형태가 아닙니다.") + private String uri; +} diff --git a/src/main/java/com/programmers/model/CreateResponse.java b/src/main/java/com/programmers/model/CreateResponse.java new file mode 100644 index 00000000..1da680b5 --- /dev/null +++ b/src/main/java/com/programmers/model/CreateResponse.java @@ -0,0 +1,11 @@ +package com.programmers.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class CreateResponse { + private String shortUri; + private int count; +} diff --git a/src/main/java/com/programmers/repository/UriRepository.java b/src/main/java/com/programmers/repository/UriRepository.java new file mode 100644 index 00000000..5b5f492e --- /dev/null +++ b/src/main/java/com/programmers/repository/UriRepository.java @@ -0,0 +1,11 @@ +package com.programmers.repository; + +import com.programmers.entity.UriEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UriRepository extends JpaRepository { + Optional findByShortUriEquals(String shortUri); + Optional findByOriginalUriEquals(String originalUri); +} diff --git a/src/main/java/com/programmers/service/UriService.java b/src/main/java/com/programmers/service/UriService.java new file mode 100644 index 00000000..dca2d478 --- /dev/null +++ b/src/main/java/com/programmers/service/UriService.java @@ -0,0 +1,66 @@ +package com.programmers.service; + +import com.programmers.component.IndexUriGenerator; +import com.programmers.component.ShortUriGenerator; +import com.programmers.component.UriConverter; +import com.programmers.dto.ShortUriGenerateRequestDto; +import com.programmers.entity.UriEntity; +import com.programmers.model.CreateResponse; +import com.programmers.repository.UriRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +@Transactional +public class UriService { + private final UriRepository uriRepository; + private final ShortUriGenerator uriGenerator; + private final UriConverter uriConverter; + + public UriService(UriRepository uriRepository, UriConverter uriConverter) { + this.uriRepository = uriRepository; + this.uriGenerator = new IndexUriGenerator(); + this.uriConverter = uriConverter; + } + + public CreateResponse createShortUri(String inputUri) { + Optional existingUriEntity = getExistingUriEntity(inputUri); + + if (existingUriEntity.isPresent()) { + return uriConverter.convertCreateResponseFrom(existingUriEntity.get()); + } + + UriEntity newUriEntity = createAndSaveUriEntity(inputUri); + + ShortUriGenerateRequestDto requestDto = buildShortUriRequestDto(newUriEntity); + String shortUri = uriGenerator.generate(requestDto); + + newUriEntity.initShortUri(shortUri); + return uriConverter.convertCreateResponseFrom(newUriEntity); + } + + public String getOriginalUri(String shortUri) { + UriEntity findUriEntity = uriRepository.findByShortUriEquals(shortUri).orElseThrow(); + findUriEntity.increaseCount(); + return findUriEntity.getOriginalUri(); + } + + private Optional getExistingUriEntity(String inputUri) { + return uriRepository.findByOriginalUriEquals(inputUri); + } + + private UriEntity createAndSaveUriEntity(String inputUri) { + return uriRepository.save(new UriEntity(inputUri)); + } + + private ShortUriGenerateRequestDto buildShortUriRequestDto(UriEntity uriEntity) { + return ShortUriGenerateRequestDto.builder() + .originalUri(uriEntity.getOriginalUri()) + .index(uriEntity.getId()) + .build(); + } + + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..3cf817fa --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,21 @@ +spring: + h2: + console: + enabled: true + path: /h2-console + + datasource: + url: jdbc:h2:tcp://localhost/~/shorturi + username: sa + password: + driver-class-name: org.h2.Driver + + jpa: + hibernate: + ddl-auto: create-drop + properties: + hibernate: + format_sql: true # 실행되는 query를 보여줌 + +logging.level: + org.hibernate.SQL: debug \ 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..95486b65 --- /dev/null +++ b/src/main/resources/templates/error.html @@ -0,0 +1,35 @@ + + + + + + + Error Page + + +
+
+
+
+
+

Error

+

An error occurred while processing your request.

+

Please check the URL and try again.

+
+
+
+
+
+ + + + + diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 00000000..f31e87bb --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,40 @@ + + + + + + Shorten URL + + + + +
+
+
+

Shorten URL

+
+
+
+
+ + +
+ +
+
+
+
+ + + + + + + diff --git a/src/main/resources/templates/result.html b/src/main/resources/templates/result.html new file mode 100644 index 00000000..fbf24750 --- /dev/null +++ b/src/main/resources/templates/result.html @@ -0,0 +1,32 @@ + + + + + Short URI Created + + + + + +
+
+

Short URI Details

+
+
+

Short URI:

+

Request Count:

+
+
+ + + + + + diff --git a/src/test/java/com/programmers/controller/UriControllerTest.java b/src/test/java/com/programmers/controller/UriControllerTest.java new file mode 100644 index 00000000..f39f93b1 --- /dev/null +++ b/src/test/java/com/programmers/controller/UriControllerTest.java @@ -0,0 +1,75 @@ +package com.programmers.controller; + +import com.programmers.model.CreateResponse; +import com.programmers.service.UriService; +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 java.util.NoSuchElementException; + +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.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +@WebMvcTest(UriController.class) +class UriControllerTest { + + @Autowired + private MockMvc mockMvc; + @MockBean + private UriService uriService; + + @DisplayName("생성되지 않은 shortUri로는 접근이 불가하다.") + @Test + void getUriUsingInvalidShortUri() throws Exception { + //Given + String falseShortUri = "28x8332"; + //When + when(uriService.getOriginalUri(falseShortUri)).thenThrow(NoSuchElementException.class); + //Then + mockMvc.perform(get("/{shortUri}", falseShortUri)) + .andExpect(status().isOk()) + .andExpect(view().name("error")); + } + + @DisplayName("처음 서버를 작동하면 초기 화면으로 이동한다.") + @Test + void startWithHomePage() throws Exception { + //Given //When + //Then + mockMvc.perform(get("")) + .andExpect(status().isOk()) + .andExpect(view().name("home")); + } + + @DisplayName("uri를 보내면 shortUri를 만들고 result 화면으로 이동한다.") + @Test + void makeShortUri() throws Exception { + //Given + String validUri = "https://www.naver.com"; + //When + when(uriService.createShortUri(validUri)).thenReturn(new CreateResponse("1234jdb", 0)); + + //Then + mockMvc.perform(post("/api").param("uri", validUri)) + .andExpect(status().isOk()) + .andExpect(view().name("result")); + } + + @DisplayName("잘못된 형식의 uri를 보내면 error가 발생한다.") + @Test + void makeShortUriUsingInvalidUri() throws Exception { + //Given + String invalidUri = "wwww.naver.com"; + //When //Then + mockMvc.perform(post("/api").param("uri", invalidUri)) + .andExpect(status().isOk()) + .andExpect(view().name("error")); + } +} \ No newline at end of file diff --git a/src/test/java/com/programmers/service/UriServiceTest.java b/src/test/java/com/programmers/service/UriServiceTest.java new file mode 100644 index 00000000..8d2b0334 --- /dev/null +++ b/src/test/java/com/programmers/service/UriServiceTest.java @@ -0,0 +1,70 @@ +package com.programmers.service; + +import com.programmers.component.UriConverter; +import com.programmers.entity.UriEntity; +import com.programmers.model.CreateResponse; +import com.programmers.repository.UriRepository; +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 java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UriServiceTest { + + @Mock + private UriRepository uriRepository; + + @Mock + private UriConverter uriConverter; + + @InjectMocks + private UriService uriService; + + @DisplayName("URI 형식의 문자열을 입력하면 short uri를 반환한다.") + @Test + void createShortUriTest() { + //Given + String inputUri = "https://www.naver.com"; + UriEntity resultEntity = new UriEntity(1L, inputUri); + + when(uriRepository.findByOriginalUriEquals(inputUri)).thenReturn(Optional.empty()); + when(uriRepository.save(any())).thenReturn(resultEntity); + when(uriConverter.convertCreateResponseFrom(any(UriEntity.class))) + .thenAnswer(invocation -> { + UriEntity argument = invocation.getArgument(0); + return new CreateResponse(argument.getShortUri(), argument.getCount()); + }); + //When + CreateResponse createResponse = uriService.createShortUri(inputUri); + + //Then + assertThat(createResponse.getShortUri()).isNotNull(); + assertThat(createResponse.getCount()).isEqualTo(0); + } + + @DisplayName("등록되어있는 shortUri를 통해 uri를 가져올 수 있다.") + @Test + void getOriginalUriTest() { + //Given + String shortUri = "0xabcde"; + String originalUri = "https://www.naver.com"; + UriEntity resultEntity = new UriEntity(1L, originalUri, shortUri); + when(uriRepository.findByShortUriEquals(shortUri)).thenReturn(Optional.of(resultEntity)); + + //When + String findOriginalUri = uriService.getOriginalUri(shortUri); + + //Then + assertThat(findOriginalUri).isEqualTo(originalUri); + } + +} \ No newline at end of file