diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.github/ISSUE_TEMPLATE/feat.md b/.github/ISSUE_TEMPLATE/feat.md new file mode 100644 index 0000000..7e8ca8c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feat.md @@ -0,0 +1,17 @@ +--- +name: "๐Ÿ› Feat Template" +about: ์‹ ๊ทœ ๊ธฐ๋Šฅ ๊ตฌํ˜„์„ ์œ„ํ•œ ์ด์Šˆ ํ…œํ”Œ๋ฆฟ์ž…๋‹ˆ๋‹ค. +title: "[Feat]: " +labels: "" +assignees: '' +--- + +**Issue** +- ์ด์Šˆ ๋‚ด์šฉ: `ex) ๋กœ๊ทธ์ธ ๊ด€๋ จ ๊ธฐ๋Šฅ` + +**Branch Name** +- ์ƒ์„ฑ ๋ธŒ๋žœ์น˜ ์ด๋ฆ„ : `ex) feat/login` + +**To-Do List** +- [ ] `ex) ๋กœ๊ทธ์ธ ๊ตฌํ˜„` +- [ ] `ex) ํšŒ์›๊ฐ€์ž… ๊ตฌํ˜„` diff --git a/.github/ISSUE_TEMPLATE/fix.md b/.github/ISSUE_TEMPLATE/fix.md new file mode 100644 index 0000000..1b1204f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/fix.md @@ -0,0 +1,17 @@ +--- +name: "๐Ÿ”จFix Template" +about: ๋ฒ„๊ทธ ์ˆ˜์ •์„ ์œ„ํ•œ ์ด์Šˆ ํ…œํ”Œ๋ฆฟ์ž…๋‹ˆ๋‹ค. +title: "[Fix]: " +labels: "" +assignees: '' +--- + +**Issue** +- ์ด์Šˆ ๋‚ด์šฉ: `ex) ๋กœ๊ทธ์ธ ๋ฒ„๊ทธ ์ˆ˜์ •` + +**Branch Name** +- ์ƒ์„ฑ ๋ธŒ๋žœ์น˜ ์ด๋ฆ„ : `ex) fix/login` + +**To-Do List** +- [ ] `ex) ๋กœ๊ทธ์ธ ๋ฒ„๊ทธ ์ˆ˜์ •` +- [ ] `ex) ํšŒ์›๊ฐ€์ž… ๋ฒ„๊ทธ ์ˆ˜์ •` diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..f36676c --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,25 @@ +## โœ… ์ด์Šˆ ๋ฒˆํ˜ธ + + + + + +## ๐Ÿ‘ฉโ€๐Ÿ’ป ๊ตฌํ˜„ ๋‚ด์šฉ + + + +- [ ] `๊ตฌํ˜„ ์‚ฌํ•ญ` + +## โœ ํ…Œ์ŠคํŠธ ๋ฐฉ๋ฒ• + + + +- [ ] `ํ…Œ์ŠคํŠธ ์‚ฌํ•ญ` + +## ๐Ÿ’ฌ ์ฝ”๋ฉ˜ํŠธ + + + +## ๐Ÿ’ญ ๊ณ ๋ คํ•œ ์  + + \ No newline at end of file diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml new file mode 100644 index 0000000..540aec5 --- /dev/null +++ b/.github/workflows/docker-image.yml @@ -0,0 +1,84 @@ +name: ๋Œ€ํ”ผ๋กœ Docker Image CI/CD + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +permissions: + contents: read + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + + steps: + - name: ๐Ÿงพ Checkout source + uses: actions/checkout@v4 + + - name: โ˜• Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + cache: gradle + + - name: โš™๏ธ Create application.yml + run: | + mkdir -p src/main/resources + cat < src/main/resources/application.yml + spring: + profiles: + active: \${PROFILES_ACTIVE} + EOF + + - name: ๐Ÿ›  Grant gradle permission + run: chmod +x gradlew + + - name: ๐Ÿงช Build with Gradle + run: ./gradlew clean build -x test + + - name: ๐Ÿณ Docker login + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: ๐Ÿ“ฆ Build & Push Docker Image + run: | + docker build -t ${{ secrets.DOCKER_REPOSITORY }}/${{ secrets.DOCKER_IMAGE }}:latest . + docker push ${{ secrets.DOCKER_REPOSITORY }}/${{ secrets.DOCKER_IMAGE }}:latest + + - name: ๐Ÿšš Upload deploy.sh to EC2 + uses: appleboy/scp-action@v0.1.7 + with: + host: ${{ secrets.AWS_HOST }} + username: ubuntu + key: ${{ secrets.AWS_KEY }} + port: ${{ secrets.AWS_PORT }} + source: "scripts/deploy.sh" + target: "/home/ubuntu/" + + - name: ๐Ÿšš Upload docker-compose.yml to EC2 + uses: appleboy/scp-action@v0.1.7 + with: + host: ${{ secrets.AWS_HOST }} + username: ubuntu + key: ${{ secrets.AWS_KEY }} + port: ${{ secrets.AWS_PORT }} + source: "docker-compose.yml" + target: "/home/ubuntu/" + + - name: ๐Ÿš€ Deploy on EC2 + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.AWS_HOST }} + username: ubuntu + key: ${{ secrets.AWS_KEY }} + port: ${{ secrets.AWS_PORT }} + script: | + sudo docker pull ${{ secrets.DOCKER_REPOSITORY }}/${{ secrets.DOCKER_IMAGE }}:latest + chmod +x /home/ubuntu/deploy.sh + sudo /home/ubuntu/deploy.sh + sudo docker image prune -f diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..559464a --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +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/ + +### Secret ### +src/main/resources/application.properties diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8286e56 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +# =============================== +# ๋Œ€ํ”ผ๋กœ Spring Boot Dockerfile +# Java 21 / Spring Boot 3.3.3 +# =============================== +FROM eclipse-temurin:21-jdk-jammy +ENV TZ=Asia/Seoul +WORKDIR /app +ARG JAR_FILE=build/libs/*.jar +COPY ${JAR_FILE} app.jar +EXPOSE 8080 +ENTRYPOINT ["java", "-jar", "/app/app.jar"] diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..b7cbe52 --- /dev/null +++ b/build.gradle @@ -0,0 +1,50 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.3' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'com.numberone' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + + // ====================================== prod ====================================== + // lombok + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' + + // db + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation "com.mysql:mysql-connector-j" + + // web + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // swagger + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' + + // ====================================== test ====================================== + // spring + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + // junit + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..c726803 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,25 @@ +version: "3.8" + +services: + daepiro: + image: ${DOCKER_REPOSITORY}/${DOCKER_IMAGE}:latest + container_name: daepiro + restart: always + ports: + - "8080:8080" + env_file: + - .env + environment: + PROFILES_ACTIVE: ${PROFILES_ACTIVE} + + DB_URL: ${DB_URL} + DB_USERNAME: ${DB_USERNAME} + DB_PASSWORD: ${DB_PASSWORD} + + JAVA_OPTS: > + -Xms256m + -Xmx512m + -Dfile.encoding=UTF-8 + + command: > + java $JAVA_OPTS -jar /app/app.jar diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 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 0000000..d4081da --- /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.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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/scripts/deploy.sh b/scripts/deploy.sh new file mode 100644 index 0000000..cb5ea5b --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,29 @@ +#!/bin/bash +set -e + +echo "๐Ÿš€ Daepiro prod deploy start" + +cd /home/ubuntu + +# 1๏ธโƒฃ ์šด์˜ ํ™˜๊ฒฝ ๊ณ ์ • +export PROFILES_ACTIVE=prod + +# 2๏ธโƒฃ .env ๋กœ๋“œ (DB, Docker ์ •๋ณด ๋“ฑ) +if [ -f .env ]; then + export $(grep -v '^#' .env | xargs) +fi + +# 3๏ธโƒฃ ์ตœ์‹  ์ด๋ฏธ์ง€ pull +docker-compose pull + +# 4๏ธโƒฃ ๊ธฐ์กด ์ปจํ…Œ์ด๋„ˆ ์ข…๋ฃŒ +docker-compose down + +# 5๏ธโƒฃ ์ปจํ…Œ์ด๋„ˆ ์žฌ๊ธฐ๋™ +docker-compose up -d + +# 6๏ธโƒฃ ํ—ฌ์Šค ์ฒดํฌ (EC2 ๋‚ด๋ถ€) +sleep 10 +curl -f http://localhost:8080/actuator/health + +echo "โœ… Prod deploy success" diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..701dd07 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'daepiro' \ No newline at end of file diff --git a/src/main/java/com/numberone/daepiro/DaepiroApplication.java b/src/main/java/com/numberone/daepiro/DaepiroApplication.java new file mode 100644 index 0000000..6a1a977 --- /dev/null +++ b/src/main/java/com/numberone/daepiro/DaepiroApplication.java @@ -0,0 +1,13 @@ +package com.numberone.daepiro; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DaepiroApplication { + + public static void main(String[] args) { + SpringApplication.run(DaepiroApplication.class, args); + } + +} diff --git a/src/main/java/com/numberone/daepiro/config/JpaAuditingConfig.java b/src/main/java/com/numberone/daepiro/config/JpaAuditingConfig.java new file mode 100644 index 0000000..f8f3309 --- /dev/null +++ b/src/main/java/com/numberone/daepiro/config/JpaAuditingConfig.java @@ -0,0 +1,9 @@ +package com.numberone.daepiro.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@EnableJpaAuditing +@Configuration +public class JpaAuditingConfig { +} diff --git a/src/main/java/com/numberone/daepiro/config/SwaggerConfig.java b/src/main/java/com/numberone/daepiro/config/SwaggerConfig.java new file mode 100644 index 0000000..5aa5267 --- /dev/null +++ b/src/main/java/com/numberone/daepiro/config/SwaggerConfig.java @@ -0,0 +1,69 @@ +package com.numberone.daepiro.config; + +import java.util.List; + +import org.springdoc.core.models.GroupedOpenApi; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpHeaders; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; + +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI() + .components(new Components().addSecuritySchemes("JWT", bearerAuth())) + .info(configurationInfo()) + .addSecurityItem(new SecurityRequirement().addList("JWT")) + .servers(List.of(new Server().url("/"))); + } + + @Bean + public GroupedOpenApi readyToUseGroup() { + return GroupedOpenApi.builder() + .group("1) ready to use") + .pathsToMatch("") + .build(); + } + + @Bean + public GroupedOpenApi readyForAdminGroup() { + return GroupedOpenApi.builder() + .group("2) ready for admin") + .pathsToMatch("") + .build(); + } + + @Bean + public GroupedOpenApi workInProgressGroup() { + return GroupedOpenApi.builder() + .group("3) work in progress") + .pathsToMatch("") + .build(); + } + + private SecurityScheme bearerAuth() { + return new SecurityScheme() + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT") + .in(SecurityScheme.In.HEADER) + .name(HttpHeaders.AUTHORIZATION); + } + + private Info configurationInfo() { + return new Info() + .title("๋Œ€ํ”ผ๋กœ ๋ฐฑ์—”๋“œ API") + .description("API Documentation") + .version("1.0.1"); + } + +} diff --git a/src/main/java/com/numberone/daepiro/domain/.gitkeep b/src/main/java/com/numberone/daepiro/domain/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/com/numberone/daepiro/domain/baseentity/PrimaryKeyEntity.java b/src/main/java/com/numberone/daepiro/domain/baseentity/PrimaryKeyEntity.java new file mode 100644 index 0000000..970b9ab --- /dev/null +++ b/src/main/java/com/numberone/daepiro/domain/baseentity/PrimaryKeyEntity.java @@ -0,0 +1,46 @@ +package com.numberone.daepiro.domain.baseentity; + +import java.time.LocalDateTime; + +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class PrimaryKeyEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @CreatedDate + @Column(nullable = false, updatable = false) + protected LocalDateTime createdAt; + + @LastModifiedDate + @Column(nullable = false) + protected LocalDateTime lastModifiedAt; + + @Column + protected LocalDateTime deletedAt; + + public boolean isDeleted() { + return deletedAt != null; + } + + public void delete() { + if (this.deletedAt == null) { + this.deletedAt = LocalDateTime.now(); + } + } +} diff --git a/src/main/java/com/numberone/daepiro/global/dto/ApiResult.java b/src/main/java/com/numberone/daepiro/global/dto/ApiResult.java new file mode 100644 index 0000000..a2ebc0d --- /dev/null +++ b/src/main/java/com/numberone/daepiro/global/dto/ApiResult.java @@ -0,0 +1,99 @@ +package com.numberone.daepiro.global.dto; + +import java.time.LocalDateTime; + +import org.springframework.http.HttpStatus; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.numberone.daepiro.global.exception.CustomErrorContext; + +public record ApiResult( + @JsonIgnore + HttpStatus httpStatus, + int code, + String message, + T data, + String path, + LocalDateTime timestamp +) { + + public ApiResult { + if (httpStatus == null) { + httpStatus = HttpStatus.OK; + } + if (timestamp == null) { + timestamp = LocalDateTime.now(); + } + if (message == null) { + message = ""; + } + if (path == null) { + path = ""; + } + } + + // == Success ๊ฒฐ๊ณผ == + public static ApiResult ok(T data, String path, String message) { + return new ApiResult<>( + HttpStatus.OK, + 1000, + message, + data, + path, + LocalDateTime.now() + ); + } + + public static ApiResult ok(T data, String path) { + return ok(data, path, "Success"); + } + + public static ApiResult ok(T data) { + return ok(data, "", "Success"); + } + + public static ApiResult ok() { + return ok(null, "", "Success"); + } + + // == No Content == + public static ApiResult noContent(String path, String message) { + return new ApiResult<>( + HttpStatus.OK, + 1000, + message, + null, + path, + LocalDateTime.now() + ); + } + + public static ApiResult noContent(String path) { + return noContent(path, "Success"); + } + + public static ApiResult noContent() { + return noContent("", "Success"); + } + + // == Error ๊ฒฐ๊ณผ == + public static ApiResult error(CustomErrorContext context, String path, String additionalMsg) { + String finalMessage = context.getMessage() + (additionalMsg != null ? additionalMsg : ""); + return new ApiResult<>( + context.getHttpStatus(), + context.getCode(), + finalMessage, + null, + path, + LocalDateTime.now() + ); + } + + public static ApiResult error(CustomErrorContext context, String path) { + return error(context, path, ""); + } + + public static ApiResult error(CustomErrorContext context) { + return error(context, "", ""); + } +} diff --git a/src/main/java/com/numberone/daepiro/global/exception/CustomErrorContext.java b/src/main/java/com/numberone/daepiro/global/exception/CustomErrorContext.java new file mode 100644 index 0000000..5dac5fa --- /dev/null +++ b/src/main/java/com/numberone/daepiro/global/exception/CustomErrorContext.java @@ -0,0 +1,37 @@ +package com.numberone.daepiro.global.exception; + +import org.springframework.http.HttpStatus; + +import lombok.Getter; + +@Getter +public enum CustomErrorContext { + + // 99xx: ๊ณตํ†ต ์˜ค๋ฅ˜ + INVALID_JSON_FORMAT(HttpStatus.BAD_REQUEST, 9001, "JSON ํ˜•์‹์ด ์ž˜๋ชป๋˜์—ˆ์Šต๋‹ˆ๋‹ค."), + INVALID_VALUE(HttpStatus.INTERNAL_SERVER_ERROR, 9002, "์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์ด ๋ฐœ๊ฒฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."), + INVALID_VALIDATION(HttpStatus.BAD_REQUEST, 9003, "๊ฐ’์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ์— ์‹คํŒจํ•˜์˜€์Šต๋‹ˆ๋‹ค."), + UNCAUGHT_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 9999, "์˜ˆ๊ธฐ์น˜ ์•Š์€ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค.", LogLevel.ERROR); + + private final HttpStatus httpStatus; + private final int code; + private final String message; + private final LogLevel logLevel; + + CustomErrorContext(HttpStatus httpStatus, int code, String message) { + this(httpStatus, code, message, LogLevel.DEBUG); + } + + CustomErrorContext(HttpStatus httpStatus, int code, String message, LogLevel logLevel) { + this.httpStatus = httpStatus; + this.code = code; + this.message = message; + this.logLevel = logLevel; + } + + public enum LogLevel { + ERROR, + DEBUG + } +} + diff --git a/src/main/java/com/numberone/daepiro/global/exception/CustomException.java b/src/main/java/com/numberone/daepiro/global/exception/CustomException.java new file mode 100644 index 0000000..d76d2d4 --- /dev/null +++ b/src/main/java/com/numberone/daepiro/global/exception/CustomException.java @@ -0,0 +1,28 @@ +package com.numberone.daepiro.global.exception; + +import lombok.Getter; + +@Getter +public class CustomException extends RuntimeException { + + private final CustomErrorContext context; + private final String additionalDetail; + + public CustomException(CustomErrorContext context) { + this(context, null); + } + + public CustomException(CustomErrorContext context, String additionalDetail) { + super(buildMessage(context, additionalDetail)); + this.context = context; + this.additionalDetail = additionalDetail; + } + + private static String buildMessage(CustomErrorContext context, String additionalDetail) { + if (additionalDetail == null || additionalDetail.isBlank()) { + return context.getMessage(); + } + return context.getMessage() + " " + additionalDetail; + } + +} diff --git a/src/main/java/com/numberone/daepiro/global/exception/GlobalExceptionHandler.java b/src/main/java/com/numberone/daepiro/global/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..893acb9 --- /dev/null +++ b/src/main/java/com/numberone/daepiro/global/exception/GlobalExceptionHandler.java @@ -0,0 +1,85 @@ +package com.numberone.daepiro.global.exception; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.numberone.daepiro.global.dto.ApiResult; + +import jakarta.servlet.http.HttpServletRequest; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(CustomException.class) + public ApiResult handleCustomException(CustomException exception) { + String endpoint = extractEndpoint(); + String additionalDetail = exception.getAdditionalDetail() != null + ? exception.getAdditionalDetail() + : ""; + return handle(exception.getContext(), exception, endpoint, additionalDetail); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ApiResult handleJsonException(HttpMessageNotReadableException exception) { + return handle(CustomErrorContext.INVALID_JSON_FORMAT, exception, extractEndpoint()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ApiResult handleValidationException(MethodArgumentNotValidException exception) { + String additionalMsg = " " + exception.getMessage(); + return handle(CustomErrorContext.INVALID_VALIDATION, exception, extractEndpoint(), additionalMsg); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ApiResult handleArgumentException(IllegalArgumentException exception) { + return handle(CustomErrorContext.INVALID_VALUE, exception, extractEndpoint()); + } + + @ExceptionHandler(Exception.class) + public ApiResult handleUnCaughtException(Exception exception) { + return handle(CustomErrorContext.UNCAUGHT_ERROR, exception, extractEndpoint()); + } + + private ApiResult handle( + CustomErrorContext context, + Throwable exception, + String endpoint + ) { + return handle(context, exception, endpoint, ""); + } + + private ApiResult handle( + CustomErrorContext context, + Throwable exception, + String endpoint, + String additionalMsg + ) { + switch (context.getLogLevel()) { + case DEBUG -> log.debug("Error occurs at {}", endpoint, exception); + case ERROR -> log.error("Error occurs at {}", endpoint, exception); + } + return ApiResult.error(context, endpoint, additionalMsg); + } + + private String extractEndpoint() { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if (!(requestAttributes instanceof ServletRequestAttributes servletRequestAttributes)) { + return "UNKNOWN_METHOD UNKNOWN_PATH"; + } + + HttpServletRequest request = servletRequestAttributes.getRequest(); + String path = request.getRequestURI() != null ? request.getRequestURI() : "UNKNOWN_PATH"; + String method = request.getMethod() != null ? request.getMethod() : "UNKNOWN_METHOD"; + + return method + " " + path; + } +} diff --git a/src/main/java/com/numberone/daepiro/global/utils/.gitkeep b/src/main/java/com/numberone/daepiro/global/utils/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/com/numberone/daepiro/infra/.gitkeep b/src/main/java/com/numberone/daepiro/infra/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..f2e4cb4 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,15 @@ +spring: + jpa: + hibernate: + ddl-auto: update + show-sql: false + + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: ${DB_URL} + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + +springdoc: + swagger-ui: + enabled: true diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml new file mode 100644 index 0000000..725dd29 --- /dev/null +++ b/src/main/resources/application-local.yml @@ -0,0 +1,15 @@ +spring: + jpa: + hibernate: + ddl-auto: update + show-sql: true + + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: ${DB_URL} + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + +springdoc: + swagger-ui: + enabled: true diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..d83689b --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,15 @@ +spring: + jpa: + hibernate: + ddl-auto: none + show-sql: false + + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: ${DB_URL} + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + +springdoc: + swagger-ui: + enabled: false diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..b007f00 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + profiles: + active: ${PROFILES_ACTIVE} + jpa: + properties: + hibernate: + format_sql: true + defer-datasource-initialization: true + +springdoc: + api-docs: + path: /api-docs # API ๋ฌธ์„œ์˜ ๊ธฐ๋ณธ ๊ฒฝ๋กœ ์„ค์ • + swagger-ui: + path: /swagger-ui.html # Swagger UI ๊ฒฝ๋กœ ์„ค์ • + operationsSorter: method # ๋ฉ”์„œ๋“œ ์ •๋ ฌ (get, post ์ˆœ) + + diff --git a/src/test/java/com/numberone/daepiro/DaepiroApplicationTests.java b/src/test/java/com/numberone/daepiro/DaepiroApplicationTests.java new file mode 100644 index 0000000..d94ef25 --- /dev/null +++ b/src/test/java/com/numberone/daepiro/DaepiroApplicationTests.java @@ -0,0 +1,13 @@ +package com.numberone.daepiro; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DaepiroApplicationTests { + + @Test + void contextLoads() { + } + +}