diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..76d31bfb --- /dev/null +++ b/.gitignore @@ -0,0 +1,123 @@ +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/ + +## Window +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Created by https://www.toptal.com/developers/gitignore/api/macos +# Edit at https://www.toptal.com/developers/gitignore?templates=macos + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud +# Created by https://www.toptal.com/developers/gitignore/api/gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=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 + +### Gradle Patch ### +# Java heap dump +*.hprof + +application-*.yml +!application.yml +!application-test.yml diff --git a/README.md b/README.md index a557279f..3ab3f2d1 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ SprintBoot URL Shortener 구현 미션 Repository 입니다. ## 요구사항 각 요구사항을 모두 충족할 수 있도록 노력해봅시다. -- [ ] URL 입력폼 제공 및 결과 출력 -- [ ] URL Shortening Key는 8 Character 이내로 생성 -- [ ] 단축된 URL 요청시 원래 URL로 리다이렉트 -- [ ] 단축된 URL에 대한 요청 수 정보저장 (optional) +- [x] URL 입력폼 제공 및 결과 출력 +- [x] URL Shortening Key는 8 Character 이내로 생성 +- [x] 단축된 URL 요청시 원래 URL로 리다이렉트 +- [x] 단축된 URL에 대한 요청 수 정보저장 (optional) - [ ] Shortening Key를 생성하는 알고리즘 2개 이상 제공하며 애플리케이션 실행중 동적으로 변경 가능 (optional) diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..32865624 --- /dev/null +++ b/build.gradle @@ -0,0 +1,45 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'com.progms' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + + // Spring + implementation 'org.springframework.boot:spring-boot-starter-web' + + // Valid + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // jpa + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + + // db + runtimeOnly 'com.h2database:h2' + + // lombok + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + // Thymleaf + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + + // test + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..9f4197d5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..fcb6fca1 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..07dc400b --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'shorturl' diff --git a/src/main/java/com/progms/shorturl/SpringbootUrlShortenerApplication.java b/src/main/java/com/progms/shorturl/SpringbootUrlShortenerApplication.java new file mode 100644 index 00000000..656ac8a0 --- /dev/null +++ b/src/main/java/com/progms/shorturl/SpringbootUrlShortenerApplication.java @@ -0,0 +1,13 @@ +package com.progms.shorturl; + +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/progms/shorturl/application/ShortUrlService.java b/src/main/java/com/progms/shorturl/application/ShortUrlService.java new file mode 100644 index 00000000..4ef9b2ea --- /dev/null +++ b/src/main/java/com/progms/shorturl/application/ShortUrlService.java @@ -0,0 +1,47 @@ +package com.progms.shorturl.application; + +import com.progms.shorturl.dto.UrlRequest; +import com.progms.shorturl.dto.UrlResponse; +import com.progms.shorturl.entity.ShortUrl; +import com.progms.shorturl.repository.ShortUrlRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Transactional(readOnly = true) +@Service +@RequiredArgsConstructor +public class ShortUrlService { + + private final UrlGenerationService urlGenerationService; + private final ShortUrlRepository shortUrlRepository; + + @Transactional + public UrlResponse generateUrl(UrlRequest urlRequest) { + Optional optionalShortUrl = shortUrlRepository.findByOriginUrl(urlRequest.url()); + + if (optionalShortUrl.isPresent()) { + ShortUrl shortUrl = optionalShortUrl.get(); + shortUrl.updateView(); + return UrlResponse.from(shortUrl); + } + + ShortUrl shortUrl =urlRequest.toEntity(); + shortUrlRepository.save(shortUrl); + + String encodeUrl = urlGenerationService.parseBase62(shortUrl.getShortId()); + shortUrl.updateShortUrl(encodeUrl); + + return UrlResponse.from(shortUrl); + } + + public String regenerateUrl(String shortUrl) { + ShortUrl urlData = shortUrlRepository.findByShortUrl(shortUrl) + .orElseThrow(()->new IllegalArgumentException("Error")); + + urlData.updateView(); + return urlData.getOriginUrl(); + } +} diff --git a/src/main/java/com/progms/shorturl/application/UrlGenerationService.java b/src/main/java/com/progms/shorturl/application/UrlGenerationService.java new file mode 100644 index 00000000..125ab48f --- /dev/null +++ b/src/main/java/com/progms/shorturl/application/UrlGenerationService.java @@ -0,0 +1,22 @@ +package com.progms.shorturl.application; + +import org.springframework.stereotype.Service; + +import static com.progms.shorturl.util.ConstantURL.BASE62; +import static com.progms.shorturl.util.ConstantURL.BASE62_RAINBOW_TABLE; + +@Service +public class UrlGenerationService { + + public String parseBase62(long id) { + + StringBuilder parseData = new StringBuilder(); + + while (id > 0) { + parseData.append(BASE62_RAINBOW_TABLE[(int) (id % BASE62)]); + id /= BASE62; + } + + return parseData.reverse().toString(); + } +} diff --git a/src/main/java/com/progms/shorturl/controller/ApiShortUrlController.java b/src/main/java/com/progms/shorturl/controller/ApiShortUrlController.java new file mode 100644 index 00000000..004d1f25 --- /dev/null +++ b/src/main/java/com/progms/shorturl/controller/ApiShortUrlController.java @@ -0,0 +1,32 @@ +package com.progms.shorturl.controller; + +import com.progms.shorturl.application.ShortUrlService; +import com.progms.shorturl.dto.UrlRequest; +import com.progms.shorturl.dto.UrlResponse; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; + +@RestController +@RequiredArgsConstructor +public class ApiShortUrlController { + + private final ShortUrlService shortUrlService; + + @PostMapping("/url") + @ResponseStatus(HttpStatus.CREATED) + public UrlResponse createShortUrl(@RequestBody @Valid UrlRequest urlRequest) { + UrlResponse urlResponse =shortUrlService.generateUrl(urlRequest); + return urlResponse; + } + + @GetMapping("/url/{shortUrl}") + public void redirectUrl(@PathVariable(name = "shortUrl") String shortUrl, HttpServletResponse response) throws IOException { + String originUrl = shortUrlService.regenerateUrl(shortUrl); + response.sendRedirect(originUrl); + } +} diff --git a/src/main/java/com/progms/shorturl/dto/UrlRequest.java b/src/main/java/com/progms/shorturl/dto/UrlRequest.java new file mode 100644 index 00000000..8817a93b --- /dev/null +++ b/src/main/java/com/progms/shorturl/dto/UrlRequest.java @@ -0,0 +1,13 @@ +package com.progms.shorturl.dto; + +import com.progms.shorturl.entity.ShortUrl; +import jakarta.validation.constraints.NotBlank; + +public record UrlRequest( + @NotBlank String url +) { + + public ShortUrl toEntity() { + return ShortUrl.createShortUrl(url); + } +} diff --git a/src/main/java/com/progms/shorturl/dto/UrlResponse.java b/src/main/java/com/progms/shorturl/dto/UrlResponse.java new file mode 100644 index 00000000..dcc51f49 --- /dev/null +++ b/src/main/java/com/progms/shorturl/dto/UrlResponse.java @@ -0,0 +1,17 @@ +package com.progms.shorturl.dto; + +import com.progms.shorturl.entity.ShortUrl; +import lombok.Builder; + +@Builder +public record UrlResponse( + String shortUrl +) { + + public static UrlResponse from(ShortUrl shortUrl) { + return UrlResponse.builder() + .shortUrl(shortUrl.getShortUrl()) + .build(); + } +} + diff --git a/src/main/java/com/progms/shorturl/entity/ShortUrl.java b/src/main/java/com/progms/shorturl/entity/ShortUrl.java new file mode 100644 index 00000000..3cd3b646 --- /dev/null +++ b/src/main/java/com/progms/shorturl/entity/ShortUrl.java @@ -0,0 +1,45 @@ +package com.progms.shorturl.entity; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import static java.util.Objects.requireNonNull; + +@Getter +@Entity(name = "short_urls") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class ShortUrl { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "short_id") + private Long shortId; + + @Column(name = "origin_url") + private String originUrl; + + @Column(name = "short_url") + private String shortUrl; + + @Column(name = "views") + private long views; + + private ShortUrl(String originUrl) { + this.originUrl = requireNonNull(originUrl); + this.views = 0; + } + + public static ShortUrl createShortUrl(String originUrl) { + return new ShortUrl(originUrl); + } + + public void updateShortUrl(String shortenUrl) { + this.shortUrl = requireNonNull(shortenUrl); + } + + public void updateView() { + views++; + } +} diff --git a/src/main/java/com/progms/shorturl/global/handler/ApiExceptionHandler.java b/src/main/java/com/progms/shorturl/global/handler/ApiExceptionHandler.java new file mode 100644 index 00000000..ddd4eeb1 --- /dev/null +++ b/src/main/java/com/progms/shorturl/global/handler/ApiExceptionHandler.java @@ -0,0 +1,51 @@ +package com.progms.shorturl.global.handler; + +import com.progms.shorturl.global.model.ErrorResponse; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.List; + +@RestControllerAdvice +public class ApiExceptionHandler extends ResponseEntityExceptionHandler { + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(IllegalArgumentException.class) + public ErrorResponse handleException(IllegalArgumentException illegalArgumentException) { + return handleExceptionInternal(illegalArgumentException.getMessage()); + } + + @Override + protected ResponseEntity handleMethodArgumentNotValid( + MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { + + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(handleExceptionInternal(ex.getMessage(), ex.getFieldErrors())); + } + + private ErrorResponse handleExceptionInternal(String message) { + return ErrorResponse.builder() + .message(message) + .build(); + } + + private ErrorResponse handleExceptionInternal(String message, List fieldErrors) { + List errors = fieldErrors.stream() + .map(ErrorResponse.ErrorStatus::of) + .toList(); + + return ErrorResponse.builder() + .message(message) + .errors(errors) + .build(); + } +} diff --git a/src/main/java/com/progms/shorturl/global/model/ErrorResponse.java b/src/main/java/com/progms/shorturl/global/model/ErrorResponse.java new file mode 100644 index 00000000..5790de64 --- /dev/null +++ b/src/main/java/com/progms/shorturl/global/model/ErrorResponse.java @@ -0,0 +1,24 @@ +package com.progms.shorturl.global.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Builder; +import org.springframework.validation.FieldError; + +import java.util.List; + +@Builder +public record ErrorResponse( + String message, + @JsonInclude(JsonInclude.Include.NON_EMPTY) List errors +) { + + public record ErrorStatus( + String field, + String message + ) { + + public static ErrorStatus of(final FieldError fieldError) { + return new ErrorStatus(fieldError.getField(), fieldError.getDefaultMessage()); + } + } +} diff --git a/src/main/java/com/progms/shorturl/repository/ShortUrlRepository.java b/src/main/java/com/progms/shorturl/repository/ShortUrlRepository.java new file mode 100644 index 00000000..f2d69d42 --- /dev/null +++ b/src/main/java/com/progms/shorturl/repository/ShortUrlRepository.java @@ -0,0 +1,12 @@ +package com.progms.shorturl.repository; + +import com.progms.shorturl.entity.ShortUrl; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface ShortUrlRepository extends JpaRepository { + Optional findByShortUrl(String shortUrl); + + Optional findByOriginUrl(String originUrl); +} diff --git a/src/main/java/com/progms/shorturl/util/ConstantURL.java b/src/main/java/com/progms/shorturl/util/ConstantURL.java new file mode 100644 index 00000000..84302db6 --- /dev/null +++ b/src/main/java/com/progms/shorturl/util/ConstantURL.java @@ -0,0 +1,18 @@ +package com.progms.shorturl.util; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ConstantURL { + + public static final int BASE62 = 62; + public static final int ENCODE_SIZE = 8; + + public static final char[] BASE62_RAINBOW_TABLE = { + '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' + }; +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/src/main/resources/static/css/index.css b/src/main/resources/static/css/index.css new file mode 100644 index 00000000..d6c9bd2b --- /dev/null +++ b/src/main/resources/static/css/index.css @@ -0,0 +1,49 @@ +#Main-body { + display: flex; + justify-content: center; + align-items: center; + margin-top: 13rem; +} + +.input { + position: relative; + box-sizing: border-box; + height: auto; + padding: 10px; + font-size: 16px; + margin: 15px 0; + border-radius: 9px; +} + +#url-body { + display: flex; + flex-direction: column; + align-items: center; + padding-top: 60px; + padding-bottom: 20px; + background-color: #fff; + width: 80%; + border: 1px solid #ddd; + border-radius: 15px; + box-shadow: rgb(100 100 111 / 20%) 0px 7px 29px 0px; +} +.h1 { + align-items: center; +} + + + +.input-container { + margin-bottom: 10px; +} + +button { + background: #3498db; + border: none; + color: #fff; + font-size: 14px; + border-radius: 99px; + height: 34px; +} + + diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 00000000..2cb1d73f --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,40 @@ + + + + + Shrot Url Service + + + +
+

밥세공기 Short Url Service

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

+
+
+

바로 가기 =>

+
+

© 2023

+ + +
+ + + \ No newline at end of file diff --git a/src/main/resources/static/js/short-url.js b/src/main/resources/static/js/short-url.js new file mode 100644 index 00000000..e3df0d4e --- /dev/null +++ b/src/main/resources/static/js/short-url.js @@ -0,0 +1,46 @@ +const DOMAIN = "http://localhost:8080/" +const URL_API = "url/" +document.getElementById('form-shorturl').addEventListener('submit', + async function (e) { + e.preventDefault(); + + const urlApi = { + url: e.target.url.value + }; + + try { + const response = await fetch('/url', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(urlApi) + }); + + if (response.ok) { + const result = await response.json(); + console.log(result) + const url = DOMAIN + URL_API+ result.shortUrl + document.getElementById('result').value = url; + const urlElement = document.getElementById('url-result'); + urlElement.href = url; + urlElement.textContent = url; + } else { + console.log("error") + } + } catch(e) { + console.log(e); + } + }); + + +document.getElementById('shortUrl-copy').addEventListener('click', + async function (e) { + e.preventDefault(); + + const copyData = document.getElementById('result').value; + console.log(copyData) + window.navigator.clipboard.writeText(copyData).then(()=>{ + document.getElementById('copy-message').textContent = "복사되었습니다!"; + }) +}) \ No newline at end of file diff --git a/src/test/java/com/progms/shorturl/SpringbootUrlShortenerApplicationTests.java b/src/test/java/com/progms/shorturl/SpringbootUrlShortenerApplicationTests.java new file mode 100644 index 00000000..74169a4f --- /dev/null +++ b/src/test/java/com/progms/shorturl/SpringbootUrlShortenerApplicationTests.java @@ -0,0 +1,13 @@ +package com.progms.shorturl; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootUrlShortenerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/progms/shorturl/application/ShortUrlServiceTest.java b/src/test/java/com/progms/shorturl/application/ShortUrlServiceTest.java new file mode 100644 index 00000000..46abc3ea --- /dev/null +++ b/src/test/java/com/progms/shorturl/application/ShortUrlServiceTest.java @@ -0,0 +1,80 @@ +package com.progms.shorturl.application; + +import com.progms.shorturl.dto.UrlRequest; +import com.progms.shorturl.dto.UrlResponse; +import com.progms.shorturl.entity.ShortUrl; +import com.progms.shorturl.repository.ShortUrlRepository; +import org.junit.jupiter.api.BeforeEach; +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.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.*; + +@ExtendWith(MockitoExtension.class) +class ShortUrlServiceTest { + + @InjectMocks + ShortUrlService shortUrlService; + + @Spy + UrlGenerationService urlGenerationService; + + @Mock + ShortUrlRepository shortUrlRepository; + + UrlRequest urlRequest; + + @BeforeEach + void init() { + urlRequest = spy(new UrlRequest("https://test.com/testtesttesttesttesttesttesttest")); + } + + @DisplayName("url 변환 성공") + @Test + void generateUrl_success() { + // given + Long uniqueId = 1L; + String parseUrl = "1"; + + ShortUrl shortUrl = spy(urlRequest.toEntity()); + + given(urlRequest.toEntity()).willReturn(shortUrl); + given(shortUrl.getShortId()).willReturn(uniqueId); + + // when + UrlResponse urlResponse = shortUrlService.generateUrl(urlRequest); + + // then + assertThat(parseUrl).isEqualTo(urlResponse.shortUrl()); + verify(shortUrlRepository, times(1)).save(any(ShortUrl.class)); + } + + @DisplayName("") + @Test + void existedUrl_and_get_success() { + // given + Long uniqueId = 1L; + String parseUrl = "1"; + + UrlRequest urlRequest = spy(new UrlRequest("https://test.com/testtesttesttesttesttesttesttest")); + ShortUrl shortUrl = spy(urlRequest.toEntity()); + shortUrl.updateShortUrl(parseUrl); + + given(shortUrlRepository.findByOriginUrl(any(String.class))).willReturn(Optional.of(shortUrl)); + + // when + UrlResponse urlResponse = shortUrlService.generateUrl(urlRequest); + + // then + assertThat(urlResponse.shortUrl()).isEqualTo(parseUrl); + verify(shortUrl, times(1)).updateView(); + } +} \ No newline at end of file diff --git a/src/test/java/com/progms/shorturl/application/UrlGenerationServiceTest.java b/src/test/java/com/progms/shorturl/application/UrlGenerationServiceTest.java new file mode 100644 index 00000000..e3ad07d3 --- /dev/null +++ b/src/test/java/com/progms/shorturl/application/UrlGenerationServiceTest.java @@ -0,0 +1,27 @@ +package com.progms.shorturl.application; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + + +public class UrlGenerationServiceTest { + + UrlGenerationService urlGenerationService = new UrlGenerationService(); + + @DisplayName("URL Base62 파싱 성공") + @ParameterizedTest + @CsvSource({ + "1, 1", + "61, z", + "35, Z" + }) + void urlParsing_success(Long id, String result) { + // given, when + String predict = urlGenerationService.parseBase62(id); + + // then + Assertions.assertThat(predict).isEqualTo(result); + } +} diff --git a/src/test/java/com/progms/shorturl/domain/ShortUrlRepositoryTest.java b/src/test/java/com/progms/shorturl/domain/ShortUrlRepositoryTest.java new file mode 100644 index 00000000..208c4700 --- /dev/null +++ b/src/test/java/com/progms/shorturl/domain/ShortUrlRepositoryTest.java @@ -0,0 +1,44 @@ +package com.progms.shorturl.domain; + +import com.progms.shorturl.application.UrlGenerationService; +import com.progms.shorturl.entity.ShortUrl; +import com.progms.shorturl.repository.ShortUrlRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@DataJpaTest +public class ShortUrlRepositoryTest { + + @Autowired + ShortUrlRepository shortUrlRepository; + + UrlGenerationService urlGenerationService = new UrlGenerationService(); + + ShortUrl testShortUrl; + + @BeforeEach + void init() { + testShortUrl = ShortUrl.createShortUrl("https://test.com/testtesttesttesttesttesttesttest"); + } + + @DisplayName("DB connect 성공 테스트") + @Test + void repository_connect_success() { + assertThat(shortUrlRepository).isNotNull(); + } + + @DisplayName("Shroturl 저장 성공 테스트") + @Test + void shortUrl_save_success() { + // given, when + shortUrlRepository.save(testShortUrl); + + // then + assertThat(testShortUrl.getShortId()).isNotNull(); + } +}