diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..abc11c5 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,36 @@ +# Gradle +.gradle/ +gradlew +gradlew.bat +gradle/ + +# Build outputs +build/ +!build/libs/*.jar +out/ + +# IDE specific +.idea/ +.vscode/ +*.iml +*.iws +*.ipr +.settings/ +.project +.classpath + +# Logs +logs/ +*.log + +# OS specific +.DS_Store +Thumbs.db + +# Git +.git/ +.gitignore + +# Others +README.md +LICENSE \ No newline at end of file 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/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..0336b07 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,64 @@ +name: Spring Boot Deployment + +on: + push: + branches: [ feature ] # feature 브랜치 push 할 때 실행 + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }}/teddy-assignment + +jobs: + build-and-push: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 23 + uses: actions/setup-java@v4 + with: + java-version: '23' + distribution: 'temurin' + + - name: Build with Gradle + uses: gradle/gradle-build-action@v2 + with: + arguments: build -x test + + - name: Login to Github Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push Docker image + uses: docker/build-push-action@v5 + with: + context: . + push: true + tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest + + - name: Deploy to EC2 + uses: appleboy/ssh-action@master + with: + host: ${{ secrets.EC2_HOST }} + username: ${{ secrets.EC2_USERNAME }} + key: ${{ secrets.EC2_SSH_KEY }} + script: | + # Github Container Registry 로그인 + echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin + + # 이전 컨테이너 중지 및 삭제 + docker stop teddy-assignment || true + docker rm teddy-assignment || true + + # 최신 이미지 풀 + docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest + + # 새 컨테이너 실행 + docker run -d --name teddy-assignment -p 8080:8080 -e DB_URL="${{ secrets.DB_URL }}" -e DB_USER="${{ secrets.DB_USER }}" -e DB_PASS="${{ secrets.DB_PASS }}" -e API_KEY="${{ secrets.API_KEY }}" ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aae62ce --- /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/ + +### yml 추가 ### +src/main/resources/application-dev.yml \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6438fa6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,9 @@ +FROM eclipse-temurin:23-jdk-alpine AS build + +WORKDIR /app + +COPY build/libs/*.jar app.jar + +EXPOSE 8080 + +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..b92d628 --- /dev/null +++ b/build.gradle @@ -0,0 +1,54 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.2' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'org.ktb' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(23) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + // 스타터 + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-web' + + // API 문서화 + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.4' + + // 데이터 포맷 + implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.18.2' + + // rate-limit + implementation 'com.bucket4j:bucket4j-core:8.10.1' + + // 롬복 + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + // 데이터베이스 + runtimeOnly 'com.mysql:mysql-connector-j' + + // 테스트 + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 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..e18bc25 --- /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.12.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/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 +' "$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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /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=%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 0000000..d54bfee --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'stock' diff --git a/src/main/java/org/ktb/stock/StockApplication.java b/src/main/java/org/ktb/stock/StockApplication.java new file mode 100644 index 0000000..9bf4792 --- /dev/null +++ b/src/main/java/org/ktb/stock/StockApplication.java @@ -0,0 +1,13 @@ +package org.ktb.stock; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StockApplication { + + public static void main(String[] args) { + SpringApplication.run(StockApplication.class, args); + } + +} diff --git a/src/main/java/org/ktb/stock/config/BucketConfig.java b/src/main/java/org/ktb/stock/config/BucketConfig.java new file mode 100644 index 0000000..03a0e1b --- /dev/null +++ b/src/main/java/org/ktb/stock/config/BucketConfig.java @@ -0,0 +1,28 @@ +package org.ktb.stock.config; + +import io.github.bucket4j.Bucket; +import org.springframework.context.annotation.Configuration; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Configuration +public class BucketConfig { + // API 키별 버킷 저장소 + private final Map buckets = new ConcurrentHashMap<>(); + + // 버킷 생성 설정 + public Bucket createBucket() { + return Bucket.builder() + .addLimit(limit -> limit + .capacity(10) + .refillIntervally(10, Duration.ofSeconds(10))) + .build(); + } + + // API 키에 대한 버킷 가져오기 + public Bucket resolveBucket(String apiKey) { + return buckets.computeIfAbsent(apiKey, k -> createBucket()); + } +} diff --git a/src/main/java/org/ktb/stock/config/SwaggerConfig.java b/src/main/java/org/ktb/stock/config/SwaggerConfig.java new file mode 100644 index 0000000..a578828 --- /dev/null +++ b/src/main/java/org/ktb/stock/config/SwaggerConfig.java @@ -0,0 +1,18 @@ +package org.ktb.stock.config; + + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; +import org.springframework.context.annotation.Configuration; + + +@OpenAPIDefinition( + info = @Info( + title = "주식 정보 조회 API", + description = "주식 정보를 조회하는 API 입니다.", + version = "v1.0" + ) +) +@Configuration +public class SwaggerConfig { +} \ No newline at end of file diff --git a/src/main/java/org/ktb/stock/controller/StockController.java b/src/main/java/org/ktb/stock/controller/StockController.java new file mode 100644 index 0000000..5aaa562 --- /dev/null +++ b/src/main/java/org/ktb/stock/controller/StockController.java @@ -0,0 +1,192 @@ +package org.ktb.stock.controller; + +import io.github.bucket4j.Bucket; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.ktb.stock.config.BucketConfig; +import org.ktb.stock.dto.StockRequestDto; +import org.ktb.stock.dto.StockResponseDto; +import org.ktb.stock.dto.StockServiceDto; +import org.ktb.stock.global.common.CommonResponse; +import org.ktb.stock.global.error.code.ErrorCode; +import org.ktb.stock.global.error.exception.BusinessException; +import org.ktb.stock.service.StockService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.List; + +@Tag(name = "주식 API", description = "주식 시세 정보를 조회해주는 API 입니다.") +@RestController +@RequiredArgsConstructor +@Slf4j +@RequestMapping("/api/v1") +public class StockController { + private final StockService stockService; + private final BucketConfig bucketConfig; + + @Value("${api.key}") + private String apiKey; + + @Operation( + summary = "주식 시세 정보 조회", + description = "회사 코드와 기간(조회 시작 기간, 조회 종료 기간)으로 주식 시세 정보를 조회합니다." + ) + @ApiResponses({ + @ApiResponse( + responseCode = "200", + description = "조회 성공", + content = { + @Content(mediaType = "application/json",schema = @Schema(implementation = CommonResponse.class)), + @Content(mediaType = "application/xml", schema = @Schema(implementation = CommonResponse.class)) + } + ), + @ApiResponse( + responseCode = "400", + description = "잘못된 요청 파라미터", + content = { + @Content(mediaType = "application/json",schema = @Schema(implementation = CommonResponse.class)), + @Content(mediaType = "application/xml", schema = @Schema(implementation = CommonResponse.class)) + } + ), + @ApiResponse( + responseCode = "403", + description = "API 키 검증 실패", + content = { + @Content(mediaType = "application/json",schema = @Schema(implementation = CommonResponse.class)), + @Content(mediaType = "application/xml", schema = @Schema(implementation = CommonResponse.class)) + } + ), + @ApiResponse( + responseCode = "404", + description = "데이터가 존재하지 않음", + content = { + @Content(mediaType = "application/json",schema = @Schema(implementation = CommonResponse.class)), + @Content(mediaType = "application/xml", schema = @Schema(implementation = CommonResponse.class)) + } + ), + @ApiResponse( + responseCode = "429", + description = "너무 많은 요청을 보냈음", + content = { + @Content(mediaType = "application/json",schema = @Schema(implementation = CommonResponse.class)), + @Content(mediaType = "application/xml", schema = @Schema(implementation = CommonResponse.class)) + } + ), + @ApiResponse( + responseCode = "500", + description = "서버 오류", + content = { + @Content(mediaType = "application/json",schema = @Schema(implementation = CommonResponse.class)), + @Content(mediaType = "application/xml", schema = @Schema(implementation = CommonResponse.class)) + } + ) + }) + @PostMapping("/stocks") + public ResponseEntity>> getStocks( + @Valid @RequestBody StockRequestDto stockRequestDto, + @RequestHeader(name = "x-api-key") String requestApiKey, + @RequestHeader(name = "Accept", required = false) String acceptHeader) { + + validateApiKey(requestApiKey); + validateRateLimit(requestApiKey); + validateRequestDto(stockRequestDto); + if(!stockService.getCompany(stockRequestDto.getCompanyCode())) throw new BusinessException(ErrorCode.INVALID_COMPANY_CODE); + + MediaType mediaType = getValidMediaType(acceptHeader); + + StockServiceDto stockServiceDto = convertToServiceDto(stockRequestDto); + List result = stockService.getStocks(stockServiceDto); + return CommonResponse.success(result, mediaType); + } + + // API KEY 검증 로직 + private void validateApiKey(String requestApiKey) { + if(!StringUtils.hasText(requestApiKey)) { + log.info("api 키가 누락되었습니다."); + throw new BusinessException(ErrorCode.MISSING_API_KEY); + } + + if(!requestApiKey.equals(apiKey)) { + log.info("api 키가 일치하지 않습니다."); + throw new BusinessException(ErrorCode.INVALID_API_KEY); + } + } + + // Rate-limit 검증 로직 + private void validateRateLimit(String requestApiKey) { + Bucket bucket = bucketConfig.resolveBucket(requestApiKey); + if (!bucket.tryConsume(1)) { + log.warn("Rate limit exceeded for API key: {}", requestApiKey); + throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS); + } + } + + // 사용자 요청 검증 로직 + private void validateRequestDto(StockRequestDto stockRequestDto) { + // 필수 입력 값이 없을 때 + if(!StringUtils.hasText(stockRequestDto.getCompanyCode()) + || !StringUtils.hasText(stockRequestDto.getStartDate()) + || !StringUtils.hasText(stockRequestDto.getEndDate())) { + log.info("필수 입력 값이 누락되었습니다."); + throw new BusinessException(ErrorCode.INVALID_REQUEST_PARAMETER); + } + + // 날짜 형식 및 범위 검증 + try { + LocalDate startDate = LocalDate.parse(stockRequestDto.getStartDate()); + LocalDate endDate = LocalDate.parse(stockRequestDto.getEndDate()); + + if (startDate.isAfter(endDate)) { + log.info("시작일자가 종료일자보다 늦습니다. startDate: {}, endDate: {}", + stockRequestDto.getStartDate(), stockRequestDto.getEndDate()); + throw new BusinessException(ErrorCode.INVALID_DATE_RANGE); + } + } catch (DateTimeParseException e) { + log.info("날짜 형식이 올바르지 않습니다. startDate: {}, endDate: {}", + stockRequestDto.getStartDate(), stockRequestDto.getEndDate()); + throw new BusinessException(ErrorCode.INVALID_DATE_FORMAT); + } + } + + // 미디어 타입 검증 로직 + private MediaType getValidMediaType(String acceptHeader) { + // null 또는 */* 처리 + if (acceptHeader == null || acceptHeader.contains("*/*")) { + return MediaType.APPLICATION_JSON; // 기본값을 JSON으로 설정 + } + + // JSON 또는 XML만 지원 + if (acceptHeader.contains(MediaType.APPLICATION_JSON_VALUE)) { + return MediaType.APPLICATION_JSON; + } + if (acceptHeader.contains(MediaType.APPLICATION_XML_VALUE)) { + return MediaType.APPLICATION_XML; + } + + // JSON, XML 외의 값이 들어오면 예외 처리 + throw new BusinessException(ErrorCode.UNSUPPORTED_MEDIA_TYPE); + } + + + // StockRequestDto -> StockServiceDto + private StockServiceDto convertToServiceDto(StockRequestDto requestDto) { + return new StockServiceDto( + requestDto.getCompanyCode(), + LocalDate.parse(requestDto.getStartDate()), + LocalDate.parse(requestDto.getEndDate()) + ); + } +} diff --git a/src/main/java/org/ktb/stock/dto/StockRequestDto.java b/src/main/java/org/ktb/stock/dto/StockRequestDto.java new file mode 100644 index 0000000..3f06519 --- /dev/null +++ b/src/main/java/org/ktb/stock/dto/StockRequestDto.java @@ -0,0 +1,28 @@ +package org.ktb.stock.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Schema(description = "주식 조회 요청 DTO") +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class StockRequestDto { + @Schema(description = "회사 코드", example = "AAPL") + @JsonProperty("company_code") + private String companyCode; + + @Schema(description = "조회 시작 날짜", example = "2020-01-01") + @JsonProperty("start_date") + @Pattern(regexp = "\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])") + private String startDate; + + @Schema(description = "조회 종료 날짜", example = "2020-01-31") + @JsonProperty("end_date") + @Pattern(regexp = "\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])") + private String endDate; +} diff --git a/src/main/java/org/ktb/stock/dto/StockResponseDto.java b/src/main/java/org/ktb/stock/dto/StockResponseDto.java new file mode 100644 index 0000000..d44143d --- /dev/null +++ b/src/main/java/org/ktb/stock/dto/StockResponseDto.java @@ -0,0 +1,26 @@ +package org.ktb.stock.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlRootElement; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.time.LocalDate; + +@Schema(description = "주식 조회 응답 DTO") +@XmlRootElement(name = "StockResponse") +@XmlAccessorType(XmlAccessType.FIELD) +@Getter +@AllArgsConstructor +public class StockResponseDto { + @Schema(description = "회사명", example = "Apple Inc.") + private String companyName; + + @Schema(description = "거래 날짜", example = "2020-01-15") + private LocalDate tradeDate; + + @Schema(description = "종가", example = "72.7161") + private float closingPrice; +} diff --git a/src/main/java/org/ktb/stock/dto/StockServiceDto.java b/src/main/java/org/ktb/stock/dto/StockServiceDto.java new file mode 100644 index 0000000..9141efd --- /dev/null +++ b/src/main/java/org/ktb/stock/dto/StockServiceDto.java @@ -0,0 +1,14 @@ +package org.ktb.stock.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.time.LocalDate; + +@Getter +@AllArgsConstructor +public class StockServiceDto { + private String companyCode; + private LocalDate startDate; + private LocalDate endDate; +} diff --git a/src/main/java/org/ktb/stock/global/common/CommonResponse.java b/src/main/java/org/ktb/stock/global/common/CommonResponse.java new file mode 100644 index 0000000..ad384db --- /dev/null +++ b/src/main/java/org/ktb/stock/global/common/CommonResponse.java @@ -0,0 +1,47 @@ +package org.ktb.stock.global.common; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlRootElement; +import lombok.*; +import org.ktb.stock.global.error.code.ErrorCode; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +import java.util.List; + +@Getter +@XmlRootElement(name = "CommonResponse") +@XmlAccessorType(XmlAccessType.FIELD) +@Builder +@AllArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class CommonResponse{ + private boolean success; // 요청의 성공 여부를 나타내기 위함 + private String message; // 사용자나 개발자가 확인할 수 있는 설명을 제공하기 위함 + private T data; // 데이터를 실제로 담는 필드 + + public static ResponseEntity> success(T data, MediaType mediaType) { + String message = (data instanceof List && ((List) data).isEmpty()) + ? "해당 기간에 조회된 주식 데이터가 없습니다." + : "주식 데이터를 성공적으로 조회했습니다."; + CommonResponse response = CommonResponse.builder() + .success(true) + .message(message) + .data(data) + .build(); + return ResponseEntity.ok() + .contentType(mediaType) + .body(response); + } + + public static ResponseEntity> error(ErrorCode errorCode, MediaType mediaType) { + CommonResponse response = CommonResponse.builder() + .success(false) + .message(errorCode.getMessage()) + .build(); + return ResponseEntity.status(errorCode.getStatus()) + .contentType(mediaType) + .body(response); + } +} diff --git a/src/main/java/org/ktb/stock/global/error/code/ErrorCode.java b/src/main/java/org/ktb/stock/global/error/code/ErrorCode.java new file mode 100644 index 0000000..e62baa9 --- /dev/null +++ b/src/main/java/org/ktb/stock/global/error/code/ErrorCode.java @@ -0,0 +1,57 @@ +package org.ktb.stock.global.error.code; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ErrorCode { + // API KEY가 잘못된 경우 + MISSING_API_KEY(HttpStatus.BAD_REQUEST.value(), "API Key가 없습니다."), + INVALID_API_KEY(HttpStatus.FORBIDDEN.value(), "API Key가 일치하지 않습니다."), + + // 잘못된 요청이 올 경우 + INVALID_REQUEST_PARAMETER(HttpStatus.BAD_REQUEST.value(), "필수 요청 값이 누락되었습니다."), + INVALID_COMPANY_CODE(HttpStatus.BAD_REQUEST.value(), "존재하지 않는 회사 코드입니다."), + INVALID_DATE_FORMAT(HttpStatus.BAD_REQUEST.value(), "날짜는 yyyy-MM-dd 형식이어야 합니다"), + INVALID_DATE_RANGE(HttpStatus.BAD_REQUEST.value(), "시작 날짜가 종료 날짜보다 늦습니다."), + + // Content Negotiation 관련 에러 + UNSUPPORTED_MEDIA_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "지원하지 않는 미디어 타입입니다. (지원: application/json, application/xml)"), + + // 리소스를 찾을 수 없는 경우 + NOT_FOUND_API(HttpStatus.NOT_FOUND.value(), "호출한 API가 존재하지 않습니다."), + NOT_FOUND_STOCK_DATA(HttpStatus.NOT_FOUND.value(), "해당 기간의 주식 데이터를 찾을 수 없습니다."), + + // 너무 많은 요청이 온 경우 + TOO_MANY_REQUESTS(HttpStatus.TOO_MANY_REQUESTS.value(), "API 호출은 10초에 10건만 가능합니다."), + + // 서버 오류 + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버 내부 오류가 발생했습니다."); + + private final int status; + private final String message; + + public boolean isServerError() { + return this.status == HttpStatus.INTERNAL_SERVER_ERROR.value(); + } +} + +/** + * 헤더 API 키 시나리오 + * 1. 요청 헤더에 API 키 누락 (400) + * 2. 요청 헤더로 온 API 키 값이 서비스 API 키 값과 불일치 (403) + * + * 사용자 요청 에러 시나리오 + * 1. 필수 파라미터 누락 (400) + * 2. 존재하지 않는 회사 코드 입력 (400) + * 3. 잘못된 날짜 형식 (400) + * 4. 시작 날짜가 종료 날 보다 늦는 경우 (400) + * + * 리소스가 없을 때 + * 1. 해당 기간 동안 주식 데이터가 없음 + * 2. 호출한 API 없음 + * 서버 오류 + * 1. 500 에러 반환 + */ diff --git a/src/main/java/org/ktb/stock/global/error/exception/BusinessException.java b/src/main/java/org/ktb/stock/global/error/exception/BusinessException.java new file mode 100644 index 0000000..32960d2 --- /dev/null +++ b/src/main/java/org/ktb/stock/global/error/exception/BusinessException.java @@ -0,0 +1,14 @@ +package org.ktb.stock.global.error.exception; + +import lombok.Getter; +import org.ktb.stock.global.error.code.ErrorCode; + +@Getter +public class BusinessException extends RuntimeException { + private final ErrorCode errorCode; + + public BusinessException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} diff --git a/src/main/java/org/ktb/stock/global/error/exception/GlobalExceptionHandler.java b/src/main/java/org/ktb/stock/global/error/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..94a244d --- /dev/null +++ b/src/main/java/org/ktb/stock/global/error/exception/GlobalExceptionHandler.java @@ -0,0 +1,84 @@ +package org.ktb.stock.global.error.exception; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.extern.slf4j.Slf4j; +import org.ktb.stock.global.common.CommonResponse; +import org.ktb.stock.global.error.code.ErrorCode; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MissingRequestHeaderException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.resource.NoResourceFoundException; + +@RestControllerAdvice +@Slf4j +public class GlobalExceptionHandler { + + @ExceptionHandler(BusinessException.class) + public ResponseEntity> handleBusinessException( + BusinessException e, HttpServletRequest request) { + ErrorCode errorCode = e.getErrorCode(); + MediaType mediaType = getMediaType(request); + + if (errorCode.isServerError()) { + log.error("BusinessException: {}", e.getMessage(), e); + } else { + log.warn("BusinessException: {}", e.getMessage(), e); + } + + return CommonResponse.error(errorCode, mediaType); + } + + // x-api-key 요청 헤더가 오지 않을 때 + @ExceptionHandler(MissingRequestHeaderException.class) + public ResponseEntity> handleMissingRequestHeaderException( + MissingRequestHeaderException e, HttpServletRequest request) { + MediaType mediaType = getMediaType(request); + log.warn("Missing header: {}", e.getMessage()); + return CommonResponse.error(ErrorCode.MISSING_API_KEY, mediaType); + } + + // 존재하지 않는 엔드포인트로 요청이 들어왔을 때 + @ExceptionHandler(NoResourceFoundException.class) + public ResponseEntity> handleNoResourceFoundException( + NoResourceFoundException e, HttpServletRequest request) { + MediaType mediaType = getMediaType(request); + log.warn("No resource found: {}", e.getMessage()); + return CommonResponse.error(ErrorCode.NOT_FOUND_API, mediaType); + } + + // 회사 코드로 있는 회사인지 확인하는 중 단건 조회 에러가 났을 때 + @ExceptionHandler(EmptyResultDataAccessException.class) + public ResponseEntity> handleEmptyResultDataAccessException( + EmptyResultDataAccessException e, HttpServletRequest request) { + MediaType mediaType = getMediaType(request); + log.warn("No data found: {}", e.getMessage()); + return CommonResponse.error(ErrorCode.INVALID_COMPANY_CODE, mediaType); + } + + // 예상치 못한 서버 에러 + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException( + Exception e, HttpServletRequest request) { + MediaType mediaType = getMediaType(request); + log.error("Exception: {}", e.getMessage(), e); + return CommonResponse.error(ErrorCode.INTERNAL_SERVER_ERROR, mediaType); + } + + // request -> MediaType + private MediaType getMediaType(HttpServletRequest request) { + String acceptHeader = request.getHeader("Accept"); + + if (acceptHeader == null || acceptHeader.contains("*/*")) { + return MediaType.APPLICATION_JSON; // 기본값 JSON + } + + if (acceptHeader.contains(MediaType.APPLICATION_XML_VALUE)) { + return MediaType.APPLICATION_XML; + } + + return MediaType.APPLICATION_JSON; + } +} diff --git a/src/main/java/org/ktb/stock/repository/StockRepository.java b/src/main/java/org/ktb/stock/repository/StockRepository.java new file mode 100644 index 0000000..4b344c4 --- /dev/null +++ b/src/main/java/org/ktb/stock/repository/StockRepository.java @@ -0,0 +1,49 @@ +package org.ktb.stock.repository; + +import lombok.RequiredArgsConstructor; +import org.ktb.stock.dto.StockResponseDto; +import org.ktb.stock.dto.StockServiceDto; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +@RequiredArgsConstructor +public class StockRepository { + private final JdbcTemplate jdbcTemplate; + + // 원하는 반환 결과 값으로 매핑 + private final RowMapper stockResponseDtoRowMapper = (rs, rowNum) -> + new StockResponseDto( + rs.getString("company_name"), + rs.getDate("trade_date").toLocalDate(), + rs.getFloat("close_price") + ); + + // 사용자가 입력한 회사 코드, 조회 시작 기간, 조회 종료 기간에 해당하는 주식 정보 가져오는 로직 + public List findStocks(StockServiceDto stockServiceDto) { + String sql = "SELECT c.company_name, sh.trade_date, sh.close_price FROM company c " + + "JOIN stocks_history sh " + + "ON c.company_code = sh.company_code " + + "WHERE c.company_code = ? AND sh.trade_date BETWEEN ? AND ?"; + + return jdbcTemplate.query( + sql, + stockResponseDtoRowMapper, + stockServiceDto.getCompanyCode(), + stockServiceDto.getStartDate(), + stockServiceDto.getEndDate() + ); + } + + // 입력 받은 회사코드가 있는 회사인지 확인 + public boolean findCompany(String companyCode) { + String sql = "SELECT company_name FROM company WHERE company_code = ?"; + + jdbcTemplate.queryForObject(sql, String.class, companyCode); + + return true; + } +} diff --git a/src/main/java/org/ktb/stock/service/StockService.java b/src/main/java/org/ktb/stock/service/StockService.java new file mode 100644 index 0000000..7d7aff6 --- /dev/null +++ b/src/main/java/org/ktb/stock/service/StockService.java @@ -0,0 +1,25 @@ +package org.ktb.stock.service; + +import lombok.RequiredArgsConstructor; +import org.ktb.stock.dto.StockResponseDto; +import org.ktb.stock.dto.StockServiceDto; +import org.ktb.stock.repository.StockRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class StockService { + private final StockRepository stockRepository; + + public List getStocks(StockServiceDto stockServiceDto) { + return stockRepository.findStocks(stockServiceDto); + } + + public boolean getCompany(String companyCode) { + return stockRepository.findCompany(companyCode); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..bc69a49 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,8 @@ +server: + port: 8080 + +spring: + application: + name: stock + profiles: + active: dev diff --git a/src/test/java/org/ktb/stock/StockApplicationTests.java b/src/test/java/org/ktb/stock/StockApplicationTests.java new file mode 100644 index 0000000..090a5f0 --- /dev/null +++ b/src/test/java/org/ktb/stock/StockApplicationTests.java @@ -0,0 +1,13 @@ +package org.ktb.stock; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class StockApplicationTests { + + @Test + void contextLoads() { + } + +}