├── .gitignore ├── LICENSE.md ├── Procfile ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── dev │ │ └── camila │ │ └── url │ │ └── shortener │ │ └── preview │ │ ├── UrlShortenerPreviewApplication.java │ │ ├── configuration │ │ └── Swagger3Config.java │ │ ├── exceptions │ │ ├── BusinessException.java │ │ ├── ExceptionDetails.java │ │ └── RestExceptionHandler.java │ │ ├── model │ │ └── Url.java │ │ ├── repository │ │ └── UrlRepository.java │ │ ├── resource │ │ └── UrlResource.java │ │ └── service │ │ └── UrlService.java └── resources │ ├── application-dev.yml │ └── application-railway.yml └── test ├── java └── dev │ └── camila │ └── url │ └── shortener │ └── preview │ ├── UrlShortenerPreviewApplicationTests.java │ ├── repository │ └── UrlRepositoryTest.java │ ├── resource │ └── UrlResourceTest.java │ └── service │ └── UrlServiceTest.java └── resources └── application-test.properties /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Camila Cavalcante 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java -jar build/libs/url-shortener-preview-0.0.1-SNAPSHOT.jar -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

url-shortener

2 |

O URL Shortener é um projeto que oferece um serviço de encurtamento de URLs. Destaca-se pela funcionalidade de redirect eficiente, persistência de dados confiável, testes abrangentes (unidade e integração), hospedagem em nuvem pública e documentação.

3 |

4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |

29 | 30 | ## Configuração 31 | 32 | Essas instruções fornecerão aos usuários as etapas necessárias para clonar o repositório e iniciar a aplicação em 33 | diferentes ambientes (Unix e Windows) com o perfil de desenvolvimento ativado. 34 | 35 | 1. Clone o repositório: git clone https://github.com/cami-la/url-shortener.git 36 | 2. Inicie a aplicação no ambiente Unix: `./gradlew bootrun --args='--spring.profiles.active=dev'` 37 | 3. Inicie a aplicação no ambiente Windows: `gradle.bat bootrun --args='--spring.profiles.active=dev'` 38 | 39 | ## Uso da API 40 | 41 | > Request da requisição 42 | 43 | ### Criar uma URL curta 44 | 45 | POST / 46 | 47 | - Descrição: Cria uma URL curta a partir de uma URL original. 48 | - Parâmetros da solicitação: 49 | - `originalUrl` (obrigatório): A URL original a ser encurtada. 50 | - Exemplo de solicitação: 51 | 52 | POST /?originalUrl=https://www.example.com 53 | 54 | ### Redirecionar para a URL original 55 | 56 | GET /{shortUrl} 57 | 58 | - Descrição: Redireciona para a URL original com base no código de URL encurtada. 59 | - Exemplo de solicitação: 60 | 61 | GET /abc123 62 | 63 | > Response da requisição 64 | 65 | ### Exemplos de Respostas 66 | 67 | - Resposta bem-sucedida para criação de URL curta (POST): 68 | 69 | HTTP/1.1 201 Created 70 | Content-Type: application/json 71 | 72 | { 73 | "id": "12345", 74 | "originalUrl": "https://www.example.com", 75 | "shortUrl": "abc123" 76 | } 77 | 78 | - Resposta bem-sucedida para redirecionamento (GET): 79 | 80 | HTTP/1.1 301 Moved Permanently 81 | Location: https://www.example.com 82 | 83 | - Resposta mal-sucedida para redirecionamento (GET): 84 | 85 | HTTP/1.1 404 Not Found 86 | Content-Type: application/json 87 | 88 | { 89 | "message": "URL Not Found", 90 | "timestamp": "2023-05-18T10:30:00", 91 | "status": 404, 92 | "error": "class dev.camila.url.shortener.exception.BusinessException", 93 | "details": { 94 | "Cause": "'abc123' not found" 95 | } 96 | } 97 | 98 | ## Documentação do Swagger 99 | 100 | A documentação da API pode ser encontrada no Swagger. Para visualizá-la, 101 | acesse: [Documentação do Swagger](http://localhost:8080/swagger-ui/index.html#/). 102 | 103 | ## Hospedagem no Railway.app 104 | 105 | Este projeto está hospedado no Railway.app. Para acessar a aplicação, 106 | acesse: [URL da Aplicação](https://sua-url-de-hospedagem-aqui). 107 |
Nota: Este projeto não está mais hospedado no https://railway.app/ devido a questões financeiras. No 108 | entanto, a aplicação e o banco de dados estão prontos para serem hospedados no Railway.app. Se você estiver interessado 109 | em vê-los hospedados, por favor, me avise e farei a implantação rapidamente para você. (:
110 | 111 | ## Possíveis Melhorias 112 | 113 | - Utilizar Migrations com Flyway para gerenciar as alterações no banco de dados de forma controlada e versionada. 114 | - Trocar o Banco de Dados PostgreSQL pelo MongoDB, aproveitando as características e benefícios oferecidos pelo MongoDB. 115 | - Criar um Dockerfile e docker-compose para facilitar o processo de implantação e execução do aplicativo em um ambiente 116 | de contêiner. 117 | - Configurar CI/CD no GitHub Actions ou no próprio Railway.app para automatizar o processo de construção, testes e 118 | implantação do aplicativo. 119 | 120 | ## Contribuição 121 | 122 | Contribuições são bem-vindas! Se você encontrar algum problema ou tiver sugestões de melhoria, fique à vontade para 123 | abrir uma issue ou enviar um pull request. 124 | 125 | ## Licença 126 | 127 | Este projeto está licenciado sob a licença MIT. Consulte o 128 | arquivo (LICENSE) para obter. 129 | 130 |
131 | 132 |

Autor

133 | 134 | 135 | 136 |
137 | Camila Cavalcante
138 | 139 | Feito com ❤️ por Cami-la 👋🏽 Entre em contato! 140 | 141 | [![Linkedin Badge](https://img.shields.io/badge/-Camila-blue?style=flat-square&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/in/cami-la/)](https://www.linkedin.com/in/cami-la/) 142 | [![Gmail Badge](https://img.shields.io/badge/-camiladsantoscavalcante@gmail.com-c14438?style=flat-square&logo=Gmail&logoColor=white&link=mailto:camiladsantoscavalcante@gmail.com)](mailto:camiladsantoscavalcante@gmail.com) 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.0.6' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'dev.camila' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '17' 10 | 11 | configurations { 12 | compileOnly { 13 | extendsFrom annotationProcessor 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | dependencies { 22 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 23 | implementation 'org.springframework.boot:spring-boot-starter-validation' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | implementation 'com.google.guava:guava:30.1.1-jre' 26 | implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' 27 | compileOnly 'org.projectlombok:lombok' 28 | runtimeOnly 'com.h2database:h2' 29 | runtimeOnly 'org.postgresql:postgresql' 30 | annotationProcessor 'org.projectlombok:lombok' 31 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 32 | } 33 | 34 | tasks.jar { 35 | manifest { 36 | attributes["Main-Class"] = "dev.camila.url.shortener.preview.UrlShortenerPreviewApplication" 37 | } 38 | } 39 | 40 | tasks.named('test') { 41 | useJUnitPlatform() 42 | } 43 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cami-la/url-shortener-preview/31e154d85cf87b0759b89ccb259db3acce34d2b2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'url-shortener-preview' 2 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/UrlShortenerPreviewApplication.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class UrlShortenerPreviewApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(UrlShortenerPreviewApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/configuration/Swagger3Config.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.configuration; 2 | 3 | import org.springdoc.core.models.GroupedOpenApi; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class Swagger3Config { 9 | @Bean 10 | public GroupedOpenApi publicApi() { 11 | return GroupedOpenApi.builder() 12 | .group("springshortenerurl-public") 13 | .pathsToMatch("/**") 14 | .build(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/exceptions/BusinessException.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.exceptions; 2 | 3 | public class BusinessException extends RuntimeException { 4 | public BusinessException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/exceptions/ExceptionDetails.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.exceptions; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.Map; 5 | 6 | public record ExceptionDetails( 7 | String title, 8 | LocalDateTime timestamp, 9 | int status, 10 | String exception, 11 | Map details 12 | ) { 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/exceptions/RestExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.exceptions; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.bind.annotation.RestControllerAdvice; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.Map; 10 | 11 | @RestControllerAdvice 12 | public class RestExceptionHandler { 13 | 14 | @ExceptionHandler(BusinessException.class) 15 | public ResponseEntity businessException(BusinessException ex) { 16 | return ResponseEntity 17 | .status(HttpStatus.NOT_FOUND) 18 | .body( 19 | new ExceptionDetails( 20 | "Bad Request! Consult the documentation", 21 | LocalDateTime.now(), 22 | HttpStatus.BAD_REQUEST.value(), 23 | ex.getClass().toString(), 24 | Map.of("Cause", ex.getMessage()) 25 | )); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/model/Url.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.GeneratedValue; 6 | import jakarta.persistence.GenerationType; 7 | import jakarta.persistence.Id; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | import java.util.UUID; 14 | 15 | @AllArgsConstructor 16 | @Builder 17 | @Entity 18 | @NoArgsConstructor 19 | @Data 20 | public class Url { 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.UUID) 23 | private UUID id; 24 | private String originalUrl; 25 | private String shortUrl; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/repository/UrlRepository.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.repository; 2 | 3 | import dev.camila.url.shortener.preview.model.Url; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.Optional; 8 | import java.util.UUID; 9 | 10 | @Repository 11 | public interface UrlRepository extends JpaRepository { 12 | Optional findByShortUrl(String shortUrl); 13 | Optional findByOriginalUrl(String originalUrl); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/resource/UrlResource.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.resource; 2 | 3 | import dev.camila.url.shortener.preview.model.Url; 4 | import dev.camila.url.shortener.preview.service.UrlService; 5 | import io.swagger.v3.oas.annotations.tags.Tag; 6 | import org.springframework.http.HttpHeaders; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.net.URI; 12 | import java.net.URISyntaxException; 13 | 14 | 15 | @RestController 16 | @RequestMapping("/") 17 | @Tag(name = "UrlResource") 18 | public record UrlResource( 19 | UrlService urlService 20 | ) { 21 | 22 | @GetMapping("/{shortUrl}") 23 | public ResponseEntity redirectToOriginalUrl(@PathVariable String shortUrl) throws URISyntaxException { 24 | Url urlByShortUrl = this.urlService.getOriginalUrlByShortUrl(shortUrl); 25 | String redirectTo = urlByShortUrl.getOriginalUrl(); 26 | HttpHeaders httpHeaders = new HttpHeaders(); 27 | httpHeaders.setLocation(new URI(redirectTo)); 28 | return new ResponseEntity<>(httpHeaders, HttpStatus.MOVED_PERMANENTLY); 29 | } 30 | 31 | @PostMapping 32 | public ResponseEntity returnShortUrlFromOriginalUrl(@RequestParam(value = "originalUrl") String originalUrl) { 33 | Url url = this.urlService.findOrSaveUrl(originalUrl); 34 | return ResponseEntity.status(HttpStatus.CREATED).body(url); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/dev/camila/url/shortener/preview/service/UrlService.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.service; 2 | 3 | import com.google.common.hash.Hashing; 4 | import dev.camila.url.shortener.preview.exceptions.BusinessException; 5 | import dev.camila.url.shortener.preview.model.Url; 6 | import dev.camila.url.shortener.preview.repository.UrlRepository; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.nio.charset.StandardCharsets; 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import java.util.Optional; 13 | 14 | @Service 15 | public record UrlService( 16 | UrlRepository urlRepository 17 | ) { 18 | private static final List ALLOWED_CHARS = Arrays.asList( 19 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 20 | 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 21 | 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 22 | 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/', '+' 23 | ); 24 | 25 | /** 26 | * Método responsável por encontrar a URL correspondente da URL encurtada 27 | * 28 | * @param shortUrl "URL encurtada que será pesquisada no banco de dados" 29 | * @return uma String contendo a URL original 30 | */ 31 | public Url getOriginalUrlByShortUrl(String shortUrl) { 32 | return this.urlRepository.findByShortUrl(shortUrl) 33 | .orElseThrow(() -> new BusinessException(String.format("'%s' not found", shortUrl))); 34 | } 35 | 36 | /** 37 | * Método responsável por encontrar o objeto ou salvá-lo e retornar o mesmo. 38 | * 39 | * @param originalUrl "Url que será encontrada ou atualizada" 40 | * @return O objeto URL salvo no banco de dados 41 | */ 42 | public Url findOrSaveUrl(String originalUrl) { 43 | Url url; 44 | Optional optionalUrl = this.urlRepository().findByOriginalUrl(originalUrl); 45 | if (optionalUrl.isPresent()) { 46 | url = optionalUrl.get(); 47 | } else { 48 | Url urlToSave = Url.builder() 49 | .originalUrl(originalUrl) 50 | .shortUrl(generateShortUrl(originalUrl)) 51 | .build(); 52 | url = this.urlRepository.save(urlToSave); 53 | } 54 | return url; 55 | } 56 | 57 | /** 58 | * Método responsável por gerar o hash da URL encurtada 59 | * 60 | * @param originalUrl "Url a qual será encurtada" 61 | * @return Um hash referente a originalUrl que foi convertida usando sha256 62 | * @see "https://github.com/google/guava/wiki/HashingExplained" 63 | * @see "https://www.freecodecamp.org/portuguese/news/md5-x-sha-1-x-sha-2-qual-e-o-hash-de-criptografia-mais-seguro-e-como-verifica-lo/" 64 | */ 65 | public static String generateShortUrl(String originalUrl) { 66 | byte[] hash = Hashing.sha256() 67 | .hashString(originalUrl, StandardCharsets.UTF_8) 68 | .asBytes(); 69 | StringBuilder shortUrl = new StringBuilder(); 70 | for (int i = 0; i < 6; i++) { 71 | int index = hash[i] & 0xFF; 72 | shortUrl.append(ALLOWED_CHARS.get(index % ALLOWED_CHARS.size())); 73 | } 74 | return shortUrl.toString(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | driverClassName: org.h2.Driver 4 | url: jdbc:h2:mem:url_shortener 5 | username: cami 6 | password: 7 | jpa: 8 | show-sql: true 9 | hibernate: 10 | ddl-auto: update 11 | properties: 12 | hibernate: 13 | format_sql: true 14 | h2: 15 | console: 16 | enabled: true 17 | path: /h2-console 18 | settings: 19 | trace: false 20 | web-allow-others: false 21 | springdoc: 22 | swagger-ui: 23 | path: /swagger-ui.html 24 | 25 | # https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/common-application-properties.html 26 | 27 | # spring.profiles.active=dev 28 | -------------------------------------------------------------------------------- /src/main/resources/application-railway.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:postgresql://${RAILWAY_DB_HOST:containers-us-west-169.railway.app}:${RAILWAY_DB_PORT:6620}/${RAILWAY_DB_NAME:railway} 4 | username: ${RAILWAY_DB_USERNAME:postgres} 5 | password: ${RAILWAY_DB_PASSWORD:g58P3ewfjx2rHuhblNp4} 6 | jpa: 7 | show-sql: true 8 | hibernate: 9 | ddl-auto: update 10 | properties: 11 | hibernate: 12 | format_sql: true 13 | dialect: org.hibernate.dialect.PostgreSQLDialect 14 | springdoc: 15 | swagger-ui: 16 | path: /swagger-ui.html -------------------------------------------------------------------------------- /src/test/java/dev/camila/url/shortener/preview/UrlShortenerPreviewApplicationTests.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class UrlShortenerPreviewApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/dev/camila/url/shortener/preview/repository/UrlRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.repository; 2 | 3 | import dev.camila.url.shortener.preview.model.Url; 4 | import org.junit.jupiter.api.*; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 7 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 8 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 9 | import org.springframework.test.context.ActiveProfiles; 10 | 11 | import java.util.Optional; 12 | 13 | @ActiveProfiles("test") 14 | @DataJpaTest 15 | @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) 16 | public class UrlRepositoryTest { 17 | @Autowired 18 | private UrlRepository urlRepository; 19 | 20 | @Autowired 21 | private TestEntityManager testEntityManager; 22 | 23 | private Url url1; 24 | private Url url2; 25 | 26 | @BeforeEach 27 | void setUp() { 28 | url1 = testEntityManager.persistAndFlush(Url.builder() 29 | .originalUrl("https://www.linkedin.com/in/cami-la/") 30 | .shortUrl("abc123") 31 | .build()); 32 | url2 = testEntityManager.persistAndFlush(Url.builder() 33 | .originalUrl("https://github.com/cami-la") 34 | .shortUrl("xyz123") 35 | .build()); 36 | } 37 | 38 | @AfterEach 39 | void tearDown() { 40 | testEntityManager.clear(); 41 | } 42 | 43 | @Test 44 | void shouldFindUrlByShortUrl() { 45 | //given 46 | String shortUrl = "abc123"; 47 | //when 48 | Optional optionalActual = this.urlRepository.findByShortUrl("abc123"); 49 | String actual = optionalActual.get().getOriginalUrl(); 50 | //then 51 | String expected = "https://www.linkedin.com/in/cami-la/"; 52 | Assertions.assertEquals(expected, actual); 53 | } 54 | 55 | @Test 56 | void shouldReturnOptionalEmptyWhenShortUrlNotFound() { 57 | //given 58 | String shortUrl = "abc124"; 59 | //when 60 | Optional optionalUrl = this.urlRepository.findByShortUrl(shortUrl); 61 | // then 62 | Assertions.assertTrue(optionalUrl.isEmpty()); 63 | } 64 | 65 | @Test 66 | void shouldfindUrlByOriginalUrl() { 67 | //given 68 | String originalUrl = "https://github.com/cami-la"; 69 | //when 70 | Optional optionalActual = this.urlRepository.findByOriginalUrl(originalUrl); 71 | String actual = optionalActual.get().getShortUrl(); 72 | //then 73 | String expected = "xyz123"; 74 | Assertions.assertEquals(expected, actual); 75 | } 76 | 77 | @Test 78 | void shouldReturnOptionalEmptyWhenOriginalUrlNotFound(){ 79 | //given 80 | String originalUrl = "https://github.com/cami-la2"; 81 | //when 82 | Optional optionalUrl = this.urlRepository.findByOriginalUrl(originalUrl); 83 | // then 84 | Assertions.assertTrue(optionalUrl.isEmpty()); 85 | } 86 | } -------------------------------------------------------------------------------- /src/test/java/dev/camila/url/shortener/preview/resource/UrlResourceTest.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.resource; 2 | 3 | import dev.camila.url.shortener.preview.model.Url; 4 | import dev.camila.url.shortener.preview.repository.UrlRepository; 5 | import dev.camila.url.shortener.preview.service.UrlService; 6 | import org.junit.jupiter.api.AfterEach; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Test; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.test.context.ActiveProfiles; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 16 | import org.springframework.test.web.servlet.result.MockMvcResultHandlers; 17 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 18 | 19 | 20 | @SpringBootTest 21 | @ActiveProfiles("test") 22 | @AutoConfigureMockMvc 23 | public class UrlResourceTest { 24 | @Autowired 25 | private MockMvc mockMvc; 26 | @Autowired 27 | private UrlService urlService; 28 | @Autowired 29 | private UrlRepository urlRepository; 30 | private static String URL = "/"; 31 | 32 | private Url url1; 33 | private Url url2; 34 | 35 | @BeforeEach 36 | void setUp() { 37 | urlRepository.deleteAll(); 38 | } 39 | 40 | @AfterEach 41 | void tearDown() { 42 | urlRepository.deleteAll(); 43 | } 44 | 45 | @Test 46 | void shouldCreateShortUrlAndReturn201StatusCode() throws Exception { 47 | //given 48 | String originalUrl = "https://www.linkedin.com/in/cami-la/"; 49 | //when 50 | //then 51 | mockMvc.perform( 52 | MockMvcRequestBuilders.post(URL) 53 | .contentType(MediaType.APPLICATION_FORM_URLENCODED) 54 | .param("originalUrl", originalUrl) 55 | ).andExpect(MockMvcResultMatchers.status().isCreated()) 56 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty()) 57 | .andExpect(MockMvcResultMatchers.jsonPath("$.originalUrl").value(originalUrl)) 58 | .andExpect(MockMvcResultMatchers.jsonPath("$.shortUrl").isNotEmpty()) 59 | .andDo(MockMvcResultHandlers.print()); 60 | } 61 | 62 | @Test 63 | void shouldUpdateOriginalUrlAndReturn201StatusCode() throws Exception { 64 | //given 65 | urlRepository.saveAndFlush(Url.builder() 66 | .originalUrl("https://www.linkedin.com/in/cami-la/") 67 | .shortUrl("abc123") 68 | .build()); 69 | String originalUrl = "https://www.linkedin.com/in/cami-la/"; 70 | //when 71 | //then 72 | mockMvc.perform( 73 | MockMvcRequestBuilders.post(URL) 74 | .contentType(MediaType.APPLICATION_FORM_URLENCODED) 75 | .param("originalUrl", originalUrl) 76 | ).andExpect(MockMvcResultMatchers.status().isCreated()) 77 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty()) 78 | .andExpect(MockMvcResultMatchers.jsonPath("$.originalUrl").value(originalUrl)) 79 | .andExpect(MockMvcResultMatchers.jsonPath("$.shortUrl").value("abc123")) 80 | .andDo(MockMvcResultHandlers.print()); 81 | } 82 | 83 | @Test 84 | void shouldRedirectToOriginalUrl() throws Exception { 85 | //given 86 | urlRepository.saveAndFlush(Url.builder() 87 | .originalUrl("https://www.linkedin.com/in/cami-la/") 88 | .shortUrl("abc123") 89 | .build()); 90 | String shorlUrl = "abc123"; 91 | //when 92 | //then 93 | mockMvc.perform(MockMvcRequestBuilders.get(URL + "{shortUrl}", shorlUrl)) 94 | .andExpect(MockMvcResultMatchers.status().isMovedPermanently()) 95 | .andDo(MockMvcResultHandlers.print()); 96 | } 97 | 98 | @Test 99 | void shouldReturnNotFoundWhenRedirectingToInvalidShortUrl() throws Exception { 100 | //given 101 | String shorlUrl = "abc122"; 102 | //when 103 | //then 104 | mockMvc.perform(MockMvcRequestBuilders.get(URL + "{shortUrl}", shorlUrl)) 105 | .andExpect(MockMvcResultMatchers.status().isNotFound()) 106 | .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Bad Request! Consult the documentation")) 107 | .andExpect(MockMvcResultMatchers.jsonPath("$.timestamp").exists()) 108 | .andExpect(MockMvcResultMatchers.jsonPath("$.status").value(400)) 109 | .andExpect( 110 | MockMvcResultMatchers.jsonPath("$.exception") 111 | .value("class dev.camila.url.shortener.preview.exceptions.BusinessException") 112 | ) 113 | .andExpect(MockMvcResultMatchers.jsonPath("$.details[*]").isNotEmpty()) 114 | .andDo(MockMvcResultHandlers.print()); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/test/java/dev/camila/url/shortener/preview/service/UrlServiceTest.java: -------------------------------------------------------------------------------- 1 | package dev.camila.url.shortener.preview.service; 2 | 3 | import dev.camila.url.shortener.preview.model.Url; 4 | import dev.camila.url.shortener.preview.repository.UrlRepository; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.extension.ExtendWith; 8 | import org.mockito.ArgumentMatchers; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | import org.mockito.Mockito; 12 | import org.mockito.junit.jupiter.MockitoExtension; 13 | 14 | import java.util.Optional; 15 | 16 | 17 | @ExtendWith(MockitoExtension.class) 18 | public class UrlServiceTest { 19 | @Mock 20 | private UrlRepository urlRepository; 21 | @InjectMocks 22 | private UrlService urlService; 23 | 24 | @Test 25 | void shouldGetOriginalUrlByShortUrl() { 26 | //given 27 | String originalUrl = "https://www.example.com/"; 28 | String shortUrl = "xyz123"; 29 | Url expected = Url.builder() 30 | .originalUrl(originalUrl) 31 | .shortUrl(shortUrl) 32 | .build(); 33 | Mockito.when(this.urlRepository.findByShortUrl(shortUrl)) 34 | .thenReturn(Optional.of(expected)); 35 | //when 36 | Url actual = this.urlService.getOriginalUrlByShortUrl(shortUrl); 37 | //then 38 | Assertions.assertEquals(expected, actual); 39 | } 40 | 41 | @Test 42 | void shouldThrowExceptionWhenShortUrlNotFound() { 43 | // given 44 | String shortUrl = "xyz123"; 45 | Mockito.when(this.urlRepository.findByShortUrl(shortUrl)) 46 | .thenReturn(Optional.empty()); 47 | // when + then 48 | RuntimeException actual = Assertions.assertThrows(RuntimeException.class, 49 | () -> this.urlService.getOriginalUrlByShortUrl(shortUrl)); 50 | Assertions.assertEquals(String.format("'%s' not found", shortUrl), actual.getMessage()); 51 | } 52 | 53 | @Test 54 | void shouldFindOrSaveUrlWhenUrlExistsInDatabase() { 55 | //given 56 | String originalUrl = "https://www.example.com/"; 57 | String shortUrl = "xyz123"; 58 | Url expected = Url.builder() 59 | .originalUrl(originalUrl) 60 | .shortUrl(shortUrl) 61 | .build(); 62 | Mockito.when(this.urlRepository.findByOriginalUrl(ArgumentMatchers.eq(originalUrl))) 63 | .thenReturn(Optional.of(expected)); 64 | //when 65 | Url actual = this.urlService.findOrSaveUrl(originalUrl); 66 | //then 67 | Assertions.assertEquals(expected, actual); 68 | } 69 | 70 | @Test 71 | void shouldFindOrSaveUrlWhenUrlDoesNotExistInDatabase() { 72 | //given 73 | String originalUrl = "https://www.example.com/"; 74 | String shortUrl = "xyz123"; 75 | Url expected = Url.builder() 76 | .originalUrl(originalUrl) 77 | .shortUrl(shortUrl) 78 | .build(); 79 | Mockito.when(this.urlRepository.findByOriginalUrl(ArgumentMatchers.eq(originalUrl))) 80 | .thenReturn(Optional.empty()); 81 | Mockito.when(this.urlRepository.save(ArgumentMatchers.any(Url.class))) 82 | .thenReturn(expected); 83 | //when 84 | Url actual = this.urlService.findOrSaveUrl(originalUrl); 85 | //then 86 | Assertions.assertEquals(expected, actual); 87 | } 88 | 89 | @Test 90 | void shouldGenerateHashToShortUrl() { 91 | //given 92 | String originalUrl = "https://www.example.com/"; 93 | //when 94 | String actual = UrlService.generateShortUrl(originalUrl); 95 | //then 96 | int expected = 6; 97 | Assertions.assertEquals(expected, actual.length()); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 2 | spring.datasource.username=sa 3 | spring.datasource.password= 4 | spring.datasource.driver-class-name=org.h2.Driver 5 | spring.datasource.initialization-mode=always 6 | 7 | spring.jpa.show-sql=true 8 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect 9 | spring.jpa.properties.hibernate.format_sql=true 10 | 11 | spring.flyway.enabled=false --------------------------------------------------------------------------------