diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..73281d9d --- /dev/null +++ b/.gitignore @@ -0,0 +1,170 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,intellij,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=java,intellij,gradle + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/java,intellij,gradle \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 00000000..ba15745e --- /dev/null +++ b/HELP.md @@ -0,0 +1,32 @@ +# Getting Started + +### Reference Documentation + +For further reference, please consider the following sections: + +* [Official Gradle documentation](https://docs.gradle.org) +* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.1.4/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.1.4/gradle-plugin/reference/html/#build-image) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.1.4/reference/htmlsingle/index.html#data.sql.jpa-and-spring-data) +* [Validation](https://docs.spring.io/spring-boot/docs/3.1.4/reference/htmlsingle/index.html#io.validation) +* [Spring Web](https://docs.spring.io/spring-boot/docs/3.1.4/reference/htmlsingle/index.html#web) +* [Spring REST Docs](https://docs.spring.io/spring-restdocs/docs/current/reference/html5/) +* [Spring Boot DevTools](https://docs.spring.io/spring-boot/docs/3.1.4/reference/htmlsingle/index.html#using.devtools) + +### Guides + +The following guides illustrate how to use some features concretely: + +* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) +* [Validation](https://spring.io/guides/gs/validating-form-input/) +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) + +### Additional Links + +These additional references should also help you: + +* [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) + diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..a31a1e5a --- /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' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.prgrmrs' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + runtimeOnly 'com.mysql:mysql-connector-j' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +tasks.named('asciidoctor') { + inputs.dir snippetsDir + dependsOn test +} 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/prgrmrs/urlshortener/SpringbootUrlShortenerApplication.java b/src/main/java/com/prgrmrs/urlshortener/SpringbootUrlShortenerApplication.java new file mode 100644 index 00000000..6ece930d --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/SpringbootUrlShortenerApplication.java @@ -0,0 +1,13 @@ +package com.prgrmrs.urlshortener; + +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/prgrmrs/urlshortener/business/UrlService.java b/src/main/java/com/prgrmrs/urlshortener/business/UrlService.java new file mode 100644 index 00000000..2accd16d --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/business/UrlService.java @@ -0,0 +1,37 @@ +package com.prgrmrs.urlshortener.business; + +import com.prgrmrs.urlshortener.implementation.UrlReader; +import com.prgrmrs.urlshortener.implementation.UrlStore; +import com.prgrmrs.urlshortener.model.UrlMapping; +import com.prgrmrs.urlshortener.model.vo.OriginalUrl; +import com.prgrmrs.urlshortener.util.Base62Encoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class UrlService { + + private final UrlStore store; + private final UrlReader reader; + + public UrlService(UrlStore store, UrlReader reader) { + this.store = store; + this.reader = reader; + } + + @Transactional + public UrlMapping shortenUrl(OriginalUrl originalUrl) { + UrlMapping initialUrlMapping = store.initializeUrlMapping(originalUrl); + String createdHash = Base62Encoder.encode(initialUrlMapping.getSequence()); + + return store.finalizeUrlMapping(initialUrlMapping, createdHash); + } + + @Transactional + public OriginalUrl redirectUrl(String hash) { + UrlMapping urlMapping = reader.retrieveUrlMapping(hash); + urlMapping.increaseViewCount(); + + return urlMapping.getOriginalUrl(); + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/exception/ErrorCode.java b/src/main/java/com/prgrmrs/urlshortener/exception/ErrorCode.java new file mode 100644 index 00000000..79e3d2cd --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/exception/ErrorCode.java @@ -0,0 +1,48 @@ +package com.prgrmrs.urlshortener.exception; + +import static org.springframework.http.HttpStatus.BAD_REQUEST; + +import java.util.StringJoiner; +import org.springframework.http.HttpStatus; + +public enum ErrorCode { + + // global + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "050", "Internal Server Error (서버 내부 에러입니다.)"), + + // urlMapping + BLANK_ORIGINAL_URL(BAD_REQUEST, "040", "Validation failed (유효성 검증에 실패하였습니다.)"), + URL_NOT_FOUND(BAD_REQUEST, "040", "Validation failed (유효성 검증에 실패하였습니다.)"); + + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + ErrorCode(HttpStatus httpStatus, String code, String message) { + this.httpStatus = httpStatus; + this.code = code; + this.message = message; + } + + public HttpStatus getHttpStatus() { + return httpStatus; + } + + public String getCode() { + return code; + } + + public String getMessage() { + return message; + } + + @Override + public String toString() { + return new StringJoiner(", ", ErrorCode.class.getSimpleName() + "[", "]") + .add("httpStatus=" + httpStatus) + .add("code='" + code + "'") + .add("message='" + message + "'") + .toString(); + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/exception/UrlShortenerException.java b/src/main/java/com/prgrmrs/urlshortener/exception/UrlShortenerException.java new file mode 100644 index 00000000..ddcff389 --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/exception/UrlShortenerException.java @@ -0,0 +1,14 @@ +package com.prgrmrs.urlshortener.exception; + +public class UrlShortenerException extends RuntimeException { + + private final ErrorCode errorCode; + + public UrlShortenerException(ErrorCode errorCode) { + this.errorCode = errorCode; + } + + public ErrorCode getErrorCode() { + return errorCode; + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/global/ErrorResponse.java b/src/main/java/com/prgrmrs/urlshortener/global/ErrorResponse.java new file mode 100644 index 00000000..54300746 --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/global/ErrorResponse.java @@ -0,0 +1,10 @@ +package com.prgrmrs.urlshortener.global; + +import com.prgrmrs.urlshortener.exception.ErrorCode; + +public record ErrorResponse(String errorCode, String errorMessage) { + + public static ErrorResponse of(ErrorCode errorCode) { + return new ErrorResponse(errorCode.getCode(), errorCode.getMessage()); + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/global/GlobalExceptionHandler.java b/src/main/java/com/prgrmrs/urlshortener/global/GlobalExceptionHandler.java new file mode 100644 index 00000000..771192a1 --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/global/GlobalExceptionHandler.java @@ -0,0 +1,41 @@ +package com.prgrmrs.urlshortener.global; + +import static com.prgrmrs.urlshortener.exception.ErrorCode.INTERNAL_SERVER_ERROR; + +import com.prgrmrs.urlshortener.exception.ErrorCode; +import com.prgrmrs.urlshortener.exception.UrlShortenerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(UrlShortenerException.class) + public ResponseEntity placeExceptionHandler(UrlShortenerException exception) { + ErrorCode errorCode = exception.getErrorCode(); + ErrorResponse errorResponse = ErrorResponse.of(errorCode); + + logger.error("UrlShortenerException: {}", errorResponse); + + return ResponseEntity + .status(errorCode.getHttpStatus()) + .body(errorResponse); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity internalServerErrorExceptionHandler(Exception exception) { + ErrorCode errorCode = INTERNAL_SERVER_ERROR; + ErrorResponse errorResponse = ErrorResponse.of(errorCode); + + logger.error("Exception: {}", errorResponse); + + return ResponseEntity + .status(errorCode.getHttpStatus()) + .body(errorResponse); + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrmrs/urlshortener/implementation/UrlReader.java b/src/main/java/com/prgrmrs/urlshortener/implementation/UrlReader.java new file mode 100644 index 00000000..bebd6336 --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/implementation/UrlReader.java @@ -0,0 +1,23 @@ +package com.prgrmrs.urlshortener.implementation; + +import static com.prgrmrs.urlshortener.exception.ErrorCode.URL_NOT_FOUND; + +import com.prgrmrs.urlshortener.exception.UrlShortenerException; +import com.prgrmrs.urlshortener.model.UrlMapping; +import com.prgrmrs.urlshortener.repository.UrlRepository; +import org.springframework.stereotype.Component; + +@Component +public class UrlReader { + + private final UrlRepository repository; + + public UrlReader(UrlRepository repository) { + this.repository = repository; + } + + public UrlMapping retrieveUrlMapping(String hash) { + return repository.findByHash(hash) + .orElseThrow(() -> new UrlShortenerException(URL_NOT_FOUND)); + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/implementation/UrlStore.java b/src/main/java/com/prgrmrs/urlshortener/implementation/UrlStore.java new file mode 100644 index 00000000..f00ba9de --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/implementation/UrlStore.java @@ -0,0 +1,26 @@ +package com.prgrmrs.urlshortener.implementation; + +import com.prgrmrs.urlshortener.model.UrlMapping; +import com.prgrmrs.urlshortener.model.vo.OriginalUrl; +import com.prgrmrs.urlshortener.repository.UrlRepository; +import org.springframework.stereotype.Component; + +@Component +public class UrlStore { + + private final UrlRepository repository; + + public UrlStore(UrlRepository repository) { + this.repository = repository; + } + + public UrlMapping initializeUrlMapping(OriginalUrl originalUrl) { + return repository.save(new UrlMapping(originalUrl)); + } + + public UrlMapping finalizeUrlMapping(UrlMapping savingUrlMapping, String createdHash) { + savingUrlMapping.embedHash(createdHash); + + return savingUrlMapping; + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/model/UrlMapping.java b/src/main/java/com/prgrmrs/urlshortener/model/UrlMapping.java new file mode 100644 index 00000000..b648702d --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/model/UrlMapping.java @@ -0,0 +1,56 @@ +package com.prgrmrs.urlshortener.model; + +import com.prgrmrs.urlshortener.model.vo.OriginalUrl; +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(name = "url_mapping") +public class UrlMapping { + + @Embedded + private OriginalUrl originalUrl; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "hash") + private String hash; + + @Column(name = "view_count") + private Long viewCount; + + public UrlMapping(OriginalUrl originalUrl) { + this.originalUrl = originalUrl; + this.viewCount = 0L; + } + + protected UrlMapping() { + } + + public void embedHash(String createdHash) { + this.hash = createdHash; + } + + public OriginalUrl getOriginalUrl() { + return originalUrl; + } + + public String getHash() { + return hash; + } + + public Long getSequence() { + return id; + } + + public void increaseViewCount() { + this.viewCount += 1; + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrmrs/urlshortener/model/vo/OriginalUrl.java b/src/main/java/com/prgrmrs/urlshortener/model/vo/OriginalUrl.java new file mode 100644 index 00000000..1f18d99c --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/model/vo/OriginalUrl.java @@ -0,0 +1,30 @@ +package com.prgrmrs.urlshortener.model.vo; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; + +@Embeddable +public class OriginalUrl { + + @NotBlank + @Pattern(regexp = "^(http://|https://).+") + @Column(name = "original_url", nullable = false) + private String url; + + public OriginalUrl(String url) { + this.url = url; + } + + public OriginalUrl() { + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUrl() { + return url; + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/presentation/UrlRestController.java b/src/main/java/com/prgrmrs/urlshortener/presentation/UrlRestController.java new file mode 100644 index 00000000..65486e6c --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/presentation/UrlRestController.java @@ -0,0 +1,58 @@ +package com.prgrmrs.urlshortener.presentation; + +import static com.prgrmrs.urlshortener.exception.ErrorCode.BLANK_ORIGINAL_URL; + +import com.prgrmrs.urlshortener.business.UrlService; +import com.prgrmrs.urlshortener.exception.UrlShortenerException; +import com.prgrmrs.urlshortener.model.UrlMapping; +import com.prgrmrs.urlshortener.model.vo.OriginalUrl; +import com.prgrmrs.urlshortener.presentation.dto.ShortenUrlResponse; +import jakarta.validation.Valid; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +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.RestController; + +@RestController +@RequestMapping(path = "/v1/url") +public class UrlRestController { + + private final UrlService service; + + public UrlRestController(UrlService service) { + this.service = service; + } + + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity shortenUrl( + @RequestBody @Valid OriginalUrl originalUrl, + BindingResult bindingResult) { + if (bindingResult.hasErrors()) { + throw new UrlShortenerException(BLANK_ORIGINAL_URL); + } + + UrlMapping retrievedUrlMapping = service.shortenUrl(originalUrl); + + return ResponseEntity + .status(HttpStatus.CREATED) + .body(ShortenUrlResponse.to(retrievedUrlMapping)); + } + + @GetMapping("/{hash}") + public ResponseEntity redirectURL(@PathVariable String hash) { + OriginalUrl originalUrl = service.redirectUrl(hash); + + return ResponseEntity + .status(HttpStatus.MOVED_PERMANENTLY) + .header(HttpHeaders.LOCATION, originalUrl.getUrl()) + .build(); + } + +} diff --git a/src/main/java/com/prgrmrs/urlshortener/presentation/UrlThymeleafController.java b/src/main/java/com/prgrmrs/urlshortener/presentation/UrlThymeleafController.java new file mode 100644 index 00000000..62210fe6 --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/presentation/UrlThymeleafController.java @@ -0,0 +1,53 @@ +package com.prgrmrs.urlshortener.presentation; + +import com.prgrmrs.urlshortener.business.UrlService; +import com.prgrmrs.urlshortener.model.UrlMapping; +import com.prgrmrs.urlshortener.model.vo.OriginalUrl; +import com.prgrmrs.urlshortener.presentation.dto.ShortenUrlResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; + +@Controller +public class UrlThymeleafController { + + private final UrlService service; + + public UrlThymeleafController(UrlService service) { + this.service = service; + } + + @GetMapping("/url-shortener") + public String showForm() { + return "url-shortener"; + } + + @PostMapping("/submit-url") + public String handleSubmit( + @ModelAttribute @Valid OriginalUrl originalUrl, + BindingResult bindingResult, + Model model, + HttpServletRequest request + ) { + if (bindingResult.hasErrors()) { + model.addAttribute("errors", bindingResult.getAllErrors()); + + return "url-shortener"; + } + + UrlMapping urlMapping = service.shortenUrl(originalUrl); + ShortenUrlResponse response = ShortenUrlResponse.to(urlMapping); + + String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); + String fullShortenedUrl = baseUrl + "/v1/url/" + response.hash(); + + model.addAttribute("shortened_url", fullShortenedUrl); + + return "display-result"; + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrmrs/urlshortener/presentation/dto/ShortenUrlResponse.java b/src/main/java/com/prgrmrs/urlshortener/presentation/dto/ShortenUrlResponse.java new file mode 100644 index 00000000..4ded376d --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/presentation/dto/ShortenUrlResponse.java @@ -0,0 +1,10 @@ +package com.prgrmrs.urlshortener.presentation.dto; + +import com.prgrmrs.urlshortener.model.UrlMapping; + +public record ShortenUrlResponse(String hash, String originalUrl) { + + public static ShortenUrlResponse to(UrlMapping urlMapping) { + return new ShortenUrlResponse(urlMapping.getHash(), urlMapping.getOriginalUrl().getUrl()); + } +} diff --git a/src/main/java/com/prgrmrs/urlshortener/repository/UrlRepository.java b/src/main/java/com/prgrmrs/urlshortener/repository/UrlRepository.java new file mode 100644 index 00000000..31fe0b5f --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/repository/UrlRepository.java @@ -0,0 +1,10 @@ +package com.prgrmrs.urlshortener.repository; + +import com.prgrmrs.urlshortener.model.UrlMapping; +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UrlRepository extends JpaRepository { + + Optional findByHash(String hash); +} diff --git a/src/main/java/com/prgrmrs/urlshortener/util/Base62Encoder.java b/src/main/java/com/prgrmrs/urlshortener/util/Base62Encoder.java new file mode 100644 index 00000000..c654d12a --- /dev/null +++ b/src/main/java/com/prgrmrs/urlshortener/util/Base62Encoder.java @@ -0,0 +1,21 @@ +package com.prgrmrs.urlshortener.util; + +public class Base62Encoder { + + static final char[] BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); + + private Base62Encoder() { + // on purpose + } + + public static String encode(Long sequence) { + final StringBuilder sb = new StringBuilder(); + do { + int i = (int) (sequence % 62); + sb.insert(0, BASE62[i]); // Prepend the character + sequence /= 62; + } while (sequence > 0); + return sb.toString(); + } + +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..757ed2c2 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:mysql://localhost:3306/url_shortener_db + username: root + password: root + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: create + properties: + hibernate: + show_sql: true + format_sql: true + dialect: org.hibernate.dialect.MySQLDialect + open-in-view: false + + logging: + level: + root: DEBUG \ No newline at end of file diff --git a/src/main/resources/templates/display-result.html b/src/main/resources/templates/display-result.html new file mode 100644 index 00000000..eb492eb8 --- /dev/null +++ b/src/main/resources/templates/display-result.html @@ -0,0 +1,11 @@ + + + + URL Result + + +

URL Result

+

Shortened URL:

+Back + + \ No newline at end of file diff --git a/src/main/resources/templates/url-shortener.html b/src/main/resources/templates/url-shortener.html new file mode 100644 index 00000000..c3a757fb --- /dev/null +++ b/src/main/resources/templates/url-shortener.html @@ -0,0 +1,21 @@ + + + + URL Shortener + + + +
+
    +
  • +
+
+ +
+ + + + +
+ + \ No newline at end of file diff --git a/src/test/java/com/prgrmrs/urlshortener/model/vo/OriginalUrlTest.java b/src/test/java/com/prgrmrs/urlshortener/model/vo/OriginalUrlTest.java new file mode 100644 index 00000000..8c65718f --- /dev/null +++ b/src/test/java/com/prgrmrs/urlshortener/model/vo/OriginalUrlTest.java @@ -0,0 +1,71 @@ +package com.prgrmrs.urlshortener.model.vo; + +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validator; +import java.util.Set; +import java.util.stream.Stream; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; + +class OriginalUrlTest { + + private Validator validator; + + @BeforeEach + public void setUp() { + validator = new LocalValidatorFactoryBean(); + ((LocalValidatorFactoryBean) validator).afterPropertiesSet(); + } + + @ParameterizedTest + + @MethodSource("provideSuccessOriginalUrl") + void OriginalUrl_CreatedSuccessfully(String url) { + // given + OriginalUrl originalUrl = new OriginalUrl(url); + + // when + Set> violations = validator.validate(originalUrl); + + // then + Assertions.assertThat(violations).isEmpty(); + Assertions.assertThat(originalUrl.getUrl()).isEqualTo(url); + } + + @ParameterizedTest + + @MethodSource("provideFailOriginalUrl") + void OriginalUrl_FailCreation(String url) { + // given + OriginalUrl originalUrl = new OriginalUrl(url); + + // when + Set> violations = validator.validate(originalUrl); + + // then + Assertions.assertThat(violations).isNotEmpty(); + } + + static Stream provideSuccessOriginalUrl() { + return Stream.of( + Arguments.of("https://www.naver.com"), + Arguments.of("http://www.naver.com"), + Arguments.of("https://www.daum.net"), + Arguments.of("https://www.google.com") + ); + } + + static Stream provideFailOriginalUrl() { + return java.util.stream.Stream.of( + Arguments.of("htt://www.naver.com"), + Arguments.of("httpss://www.naver.com"), + Arguments.of("www.daum.net"), + Arguments.of("https:/www.google.com") + ); + } + +} diff --git a/src/test/java/com/prgrmrs/urlshortener/presentation/UrlControllerTest.java b/src/test/java/com/prgrmrs/urlshortener/presentation/UrlControllerTest.java new file mode 100644 index 00000000..ec1a294d --- /dev/null +++ b/src/test/java/com/prgrmrs/urlshortener/presentation/UrlControllerTest.java @@ -0,0 +1,68 @@ +package com.prgrmrs.urlshortener.presentation; + +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.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.prgrmrs.urlshortener.business.UrlService; +import com.prgrmrs.urlshortener.model.UrlMapping; +import com.prgrmrs.urlshortener.model.vo.OriginalUrl; +import com.prgrmrs.urlshortener.presentation.dto.ShortenUrlResponse; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@AutoConfigureMockMvc +@SpringBootTest +class UrlControllerTest { + + @Autowired + MockMvc mockMvc; + + @Autowired + UrlService service; + + ObjectMapper objectMapper = new ObjectMapper(); + + private static final String BASE_URL = "/v1/url"; + private static final String TEST_URL = "https://www.google.com"; + + + @Test + void shortenUrl() throws Exception { + // given + OriginalUrl originalUrl = new OriginalUrl(TEST_URL); + + // when & then + mockMvc.perform(post(BASE_URL) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(originalUrl))) + .andDo(print()) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.originalUrl").exists()) + .andExpect(jsonPath("$.hash").exists()); + } + + @Test + void redirectUrl() throws Exception { + // given + OriginalUrl originalUrl = new OriginalUrl(TEST_URL); + UrlMapping mapping = service.shortenUrl(originalUrl); + String hash = mapping.getHash(); + + // when & then + mockMvc.perform(get(BASE_URL + "/" + hash)) + .andDo(print()) + .andExpect(status().isMovedPermanently()); + } + +} + + + diff --git a/src/test/java/com/prgrmrs/urlshortener/util/Base62EncoderTest.java b/src/test/java/com/prgrmrs/urlshortener/util/Base62EncoderTest.java new file mode 100644 index 00000000..c9db72a4 --- /dev/null +++ b/src/test/java/com/prgrmrs/urlshortener/util/Base62EncoderTest.java @@ -0,0 +1,30 @@ +package com.prgrmrs.urlshortener.util; + +import java.util.stream.Stream; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class Base62EncoderTest { + + @ParameterizedTest + @MethodSource("provideEncodeTestData") + void Encode_SuccessfullyConverted(Long seq, String hash) { + // given & when + String encoded = Base62Encoder.encode(seq); + + // then + Assertions.assertThat(encoded).isEqualTo(hash); + } + + private static Stream provideEncodeTestData() { + return Stream.of( + Arguments.of(0L, "A"), + Arguments.of(1L, "B"), + Arguments.of(61L, "9"), + Arguments.of(1234567890L, "BViHfU") + ); + } + +} \ No newline at end of file