diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..617027d --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +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/ + +# Gradle 캐시 폴더 및 macOS 시스템 파일 제외 +.gradle/ +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md index 1445158..38bc4cb 100644 --- a/README.md +++ b/README.md @@ -71,34 +71,34 @@ pw : {별도제공} - DB 및 ORM 관련 라이브러리(Hibernate, Jdbc 등)는 자유롭게 사용하셔도 됩니다. ## 구현 필요 내용 상세 -### 필수: API 디자인 +### ✅ 필수: API 디자인 - API는 사용자 와의 계약입니다. - 배포 된 OPEN API 서비스를 변경한다는 건 쉽지 않은 작업입니다. - 따라서 확장성 있고, 서비스 전체적으로 일관성 있는 API 및 파라미터 설계에 처음부터 많은 노력이 필요합니다. - 변경이 불가피하게 필요 할 경우를 대비하여 API 버저닝이 고려된 API를 설계해 주시기 바랍니다. - 가능하다면 API 설계에 대한 철학을 **댓글** 에 작성해 주시기 바랍니다. 또한 작성 된 철학을 어떻게 녹여냈는지 코드와 함께 설명하기 바랍니다. -### 필수: API 응답 값 +### ✅ 필수: API 응답 값 - 호출되는 API와 마찬가지로 배포되어 리얼 서비스가 시작 된 경우 API의 응답 값도 역시도 변경하기가 쉽지 않습니다. - 따라서 처음부터 일관성 있는 공통 응답 포맷에 대한 설계가 중요합니다. - 성공 및 실패 모두에 대한 일관성 있는 응답 값을 설계해 주시기 바랍니다. - 특정 응답 값을 설계한 이유를 코드에 주석으로 달아 주시기 바랍니다. -### 필수: 유효성 검사 +### ✅ 필수: 유효성 검사 - 고객이 어떤 값을 요청에 포함시킬지 모릅니다. - 우리의 API는 고객이 직접 호출을 하게 됩니다. 호출하는 과정에서 어떤 실수를 했는지 상세히 작성해서 알려줘야 고객의 생산성을 해치지 않습니다. - 유효성 검사를 통해 고객에게 어떻게 호출해야 하는지 직간접적으로 안내할 수 있도록 합니다. -### 옵션: Test Code +### ✅ 옵션: Test Code - API 동작을 사용자의 관점에서 검증하는 단위 테스트, 통합 테스트를 작성해보세요. - Spring Boot Test, JUnit, MockMVC, RestAssured 등 원하는 라이브러리를 사용해도 좋습니다. - 필수 파라미터 누락, 유효성 검사, API 키 누락 등 다양한 케이스를 테스트해주세요. -### 옵션: 응답 형식 +### ✅ 옵션: 응답 형식 - 사용자에게 다앙햔 응답 포맷 옵션을 제공해 주는 것이 중요 할 수 있습니다. - API 호출 시, 확장자(예: `.json`, `.xml`)나 request parameter(예: `format=json`, `format=xml`)로 원하는 응답 방식을 제공해주면 좋습니다. -### 옵션: API Throttling +### ✅ 옵션: API Throttling - 사용자가 너무 많은 요청을 보내게 되면 API 서버 전체가 불안정해질 수 있습니다. - 따라서 대부분의 오픈 API 서버는 1초에 N건, 혹은 1분에 N건 등 요청을 제한하는 Quota를 설정 할 수 있습니다. - "특정 API 키"에 대한 호출을 10초에 10건으로 제한하는 Quota 기능을 구현해 주시기 바랍니다. (*여기서는 위에 제시된 API Key) @@ -110,7 +110,7 @@ pw : {별도제공} - 다양한 에러 상황(400, 403, 404, 500 등)을 구분하고 로그로 남길 수 있도록 설계해주세요. - log rotation 정책을 설정하고, 그 기준과 이유를 간단히 **PR 내 댓글**에 남겨주세요. -### 옵션: 배포 후 녹화 및 **댓글**에 적용 +### ✅ 옵션: 배포 후 녹화 및 **댓글**에 적용 - 코드 작성 완료 후 배포해주세요 - 어떤 방식으로 배포했는지 **PR 내 댓글**에 상세히 작성해주세요. - 배포하면서 신경쓴 점이 있다면 해당 부분도 함께 기술해주세요 diff --git a/be-dev/build.gradle b/be-dev/build.gradle new file mode 100644 index 0000000..ce0a6e5 --- /dev/null +++ b/be-dev/build.gradle @@ -0,0 +1,48 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.2' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'mysql:mysql-connector-java:8.0.33' + implementation 'jakarta.xml.bind:jakarta.xml.bind-api:4.0.0' + implementation 'org.glassfish.jaxb:jaxb-runtime:4.0.4' + implementation 'org.springframework:spring-context' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' // Spring Boot 기본 테스트 + testImplementation 'org.mockito:mockito-core' // Mockito 기본 + testImplementation 'org.mockito:mockito-junit-jupiter' // JUnit 5용 Mockito + testImplementation 'org.springframework.security:spring-security-test' // Spring Security 테스트 지원 + testImplementation 'org.springframework.boot:spring-boot-starter-webflux' // `MockMvc` 테스트 지원 + + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/be-dev/gradle/wrapper/gradle-wrapper.jar b/be-dev/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/be-dev/gradle/wrapper/gradle-wrapper.jar differ diff --git a/be-dev/gradle/wrapper/gradle-wrapper.properties b/be-dev/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..cea7a79 --- /dev/null +++ b/be-dev/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-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/be-dev/gradlew b/be-dev/gradlew new file mode 100755 index 0000000..f3b75f3 --- /dev/null +++ b/be-dev/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=$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/be-dev/gradlew.bat b/be-dev/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/be-dev/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/be-dev/settings.gradle b/be-dev/settings.gradle new file mode 100644 index 0000000..0a383dd --- /dev/null +++ b/be-dev/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/be-dev/src/main/java/com/example/demo/DemoApplication.java b/be-dev/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..779de94 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,14 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/be-dev/src/main/java/com/example/demo/config/SecurityConfig.java b/be-dev/src/main/java/com/example/demo/config/SecurityConfig.java new file mode 100644 index 0000000..4535948 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/config/SecurityConfig.java @@ -0,0 +1,29 @@ +package com.example.demo.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.SecurityFilterChain; + +/** + * Spring Security 기본 설정 클래스 + * - API 보안을 간단하게 유지하기 위해 모든 요청을 허용 + * - CSRF 보호 및 기본 인증, 폼 로그인을 비활성화 + */ + +@Configuration +public class SecurityConfig { + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(auth -> auth + .anyRequest().permitAll() // 모든 요청 허용 (특정 경로 제한 없음) + ) + .csrf(csrf -> csrf.disable()) // CSRF 보호 비활성화 (API 서버이므로 필요 없음) + .httpBasic(httpBasic -> httpBasic.disable()) // HTTP 기본 인증 비활성화 + .formLogin(formLogin -> formLogin.disable()); // 폼 로그인 활성화 + + return http.build(); + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/config/WebConfig.java b/be-dev/src/main/java/com/example/demo/config/WebConfig.java new file mode 100644 index 0000000..0ce35a5 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/config/WebConfig.java @@ -0,0 +1,36 @@ +package com.example.demo.config; + +import com.example.demo.security.ApiKeyInterceptor; +import com.example.demo.security.RateLimitInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * WebMvc 설정 클래스 + * - API Key 인증을 위해 `ApiKeyInterceptor`를 등록 + * - 요청 제한(Rate Limiting)을 위해 `RateLimitInterceptor`를 등록 + * - 특정 경로(`/api/**`)에 인터셉터를 적용하여 보안 강화 + */ +@Configuration +public class WebConfig implements WebMvcConfigurer { + + private final ApiKeyInterceptor apiKeyInterceptor; + private final RateLimitInterceptor rateLimitInterceptor; + + @Autowired + public WebConfig(ApiKeyInterceptor apiKeyInterceptor, RateLimitInterceptor rateLimitInterceptor) { + this.apiKeyInterceptor = apiKeyInterceptor; + this.rateLimitInterceptor = rateLimitInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(apiKeyInterceptor) + .addPathPatterns("/api/**"); // 모든 `/api/**` 경로에 API Key 인증 적용 + + registry.addInterceptor(rateLimitInterceptor) // 요청 제한 기능 추가 + .addPathPatterns("/api/**"); + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/controller/StockController.java b/be-dev/src/main/java/com/example/demo/controller/StockController.java new file mode 100644 index 0000000..5173287 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/controller/StockController.java @@ -0,0 +1,79 @@ +package com.example.demo.controller; + +import com.example.demo.dto.StockResponseDTO; +import com.example.demo.service.StockService; +import com.example.demo.dto.StockListResponseDTO; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.util.List; + +/** + * 주식 정보 조회 컨트롤러 + * - 특정 기업의 주식 종가 데이터를 조회하는 API 제공 + * - API 요청 시 API Key 인증이 필요 (Interceptor에서 처리됨) + */ +@RestController +@RequestMapping("/api/v1/stock") // API v1 +public class StockController { + + private final StockService stockService; + + /** + * StockService 의존성 주입 + * @param stockService 주식 데이터를 조회하는 서비스 + */ + public StockController(StockService stockService) { + this.stockService = stockService; + } + + /** + * 특정 기업의 주식 가격 조회 API + * - 회사 코드, 조회 시작 날짜, 종료 날짜를 기준으로 데이터를 조회 + * - API Key 인증 필요 + * - `format` 요청 파라미터 또는 `Accept` 헤더를 기반으로 JSON/XML 응답 제공 + * + * @param companyCode 조회할 기업 코드 (예: "AAPL") + * @param startDate 조회 시작 날짜 (yyyy-MM-dd) + * @param endDate 조회 종료 날짜 (yyyy-MM-dd) + * @param format 응답 포맷 (json 또는 xml) [선택 사항] + * @return 주식 종가 데이터 리스트 또는 400 Bad Request + */ + @GetMapping(value = "/{companyCode}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) + public ResponseEntity getStockPrices( + @PathVariable String companyCode, + @RequestParam String startDate, + @RequestParam String endDate, + @RequestParam(required = false) String format, + @RequestHeader(value = HttpHeaders.ACCEPT, required = false) String acceptHeader + ) { + // 날짜 형식 검증 + LocalDate start, end; + try { + start = LocalDate.parse(startDate); + end = LocalDate.parse(endDate); + } catch (Exception e) { + return ResponseEntity.badRequest().build(); // 400 Bad Request 반환 + } + + // 주식 데이터 조회 + List response = stockService.getStockPrices(companyCode, start, end); + + // 응답 포맷 결정 (format 파라미터 > Accept 헤더) + String responseFormat = (format != null) ? format : ((acceptHeader != null) ? acceptHeader : "json"); + + if ("xml".equals(responseFormat) || MediaType.APPLICATION_XML_VALUE.equals(responseFormat)) { + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_XML) + .body(new StockListResponseDTO(response)); + } + + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(response); + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/dto/StockListResponseDTO.java b/be-dev/src/main/java/com/example/demo/dto/StockListResponseDTO.java new file mode 100644 index 0000000..4197814 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/dto/StockListResponseDTO.java @@ -0,0 +1,18 @@ +package com.example.demo.dto; + +import com.example.demo.dto.StockResponseDTO; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "stocks") +public class StockListResponseDTO { + @XmlElement(name = "stock") + private List stocks; + + public StockListResponseDTO() {} // 기본 생성자 필요 + + public StockListResponseDTO(List stocks) { + this.stocks = stocks; + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/dto/StockRequestDTO.java b/be-dev/src/main/java/com/example/demo/dto/StockRequestDTO.java new file mode 100644 index 0000000..318de73 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/dto/StockRequestDTO.java @@ -0,0 +1,39 @@ +package com.example.demo.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import lombok.Getter; + +/** + * 주식 조회 요청 DTO + * - 사용자가 주식 데이터를 요청할 때 전달하는 데이터 객체 + * - 회사 코드, 시작 날짜, 종료 날짜를 포함 + * - 날짜 형식 검증 및 범위 유효성 검사 포함 + */ +@Getter +public class StockRequestDTO { + + @NotBlank(message = "company_code는 필수 입력 값입니다.") + private String companyCode; + + @NotBlank(message = "start_date는 필수 입력 값입니다.") + @Pattern(regexp = "\\d{4}-\\d{2}-\\d{2}", message = "start_date 형식이 올바르지 않습니다. (yyyy-MM-dd)") + private String startDate; + + @NotBlank(message = "end_date는 필수 입력 값입니다.") + @Pattern(regexp = "\\d{4}-\\d{2}-\\d{2}", message = "end_date 형식이 올바르지 않습니다. (yyyy-MM-dd)") + private String endDate; + + // 날짜 유효성 검사 로직 (start_date <= end_date) + public boolean isValidDateRange() { + try { + LocalDate start = LocalDate.parse(startDate); + LocalDate end = LocalDate.parse(endDate); + return !start.isAfter(end); // startDate가 endDate보다 이후면 false 반환 + } catch (DateTimeParseException e) { + return false; // 날짜 형식이 잘못되었을 경우 false 반환 + } + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/dto/StockResponseDTO.java b/be-dev/src/main/java/com/example/demo/dto/StockResponseDTO.java new file mode 100644 index 0000000..ed31ee7 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/dto/StockResponseDTO.java @@ -0,0 +1,32 @@ +package com.example.demo.dto; + +import lombok.Getter; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlElement; + + + +/** + * 주식 조회 응답 DTO + * - API 응답에서 반환되는 주식 데이터 객체 + * - 특정 기업의 종가(closingPrice) 및 거래 날짜(tradeDate)를 포함 + */ +@Getter +@NoArgsConstructor // XML 변환을 위해 기본 생성자 필요 +@AllArgsConstructor +@XmlRootElement(name = "stock") // XML 직렬화 +@XmlAccessorType(XmlAccessType.FIELD) +public class StockResponseDTO { + @XmlElement(name = "companyName") // XML에서 이 필드 포함 + private String companyName; // 응답 시 회사명 포함 + + @XmlElement(name = "tradeDate") + private String tradeDate; // yyyy-MM-dd 형식 유지 + + @XmlElement(name = "closingPrice") + private long closingPrice; // 종가 (tradePrice) +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/entity/StocksHistory.java b/be-dev/src/main/java/com/example/demo/entity/StocksHistory.java new file mode 100644 index 0000000..66b3860 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/entity/StocksHistory.java @@ -0,0 +1,56 @@ +package com.example.demo.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.time.LocalDate; + +/** + * 주식 거래 이력(StocksHistory) 엔터티 + * - 특정 기업의 주식 거래 내역을 저장하는 테이블과 매핑 + * - 기업 코드(company_code) + 거래 날짜(trade_date)를 복합 키로 설정 + */ +@Entity +@Table(name = "stocks_history") // 테이블 `stocks_history`와 매핑 +@Getter +@NoArgsConstructor +@IdClass(StocksHistory.PK.class) // PK 설정 +public class StocksHistory { + + @Id + @Column(name = "company_code", length = 10, nullable = false) + private String companyCode; + + @Id + @Column(name = "trade_date", nullable = false) + private LocalDate tradeDate; + + @Column(name = "open_price", nullable = false) + private float openPrice; + + @Column(name = "high_price", nullable = false) + private float highPrice; + + @Column(name = "low_price", nullable = false) + private float lowPrice; + + @Column(name = "close_price", nullable = false) + private float closingPrice; + + @Column(name = "volume", nullable = false) + private float volume; + + /** + * PK 클래스 (기업 코드 + 거래 날짜) + * - `company_code`와 `trade_date`를 PK로 사용하기 위해 선언 + * - JPA의 @IdClass를 사용할 때 Serializable이 필수! + */ + @Getter + @NoArgsConstructor + public static class PK implements Serializable { + private String companyCode; + private LocalDate tradeDate; + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/repository/StockHistoryRepository.java b/be-dev/src/main/java/com/example/demo/repository/StockHistoryRepository.java new file mode 100644 index 0000000..7e9232c --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/repository/StockHistoryRepository.java @@ -0,0 +1,16 @@ +package com.example.demo.repository; + +import com.example.demo.entity.StocksHistory; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.LocalDate; +import java.util.List; + +public interface StockHistoryRepository extends JpaRepository { + + List findByCompanyCodeAndTradeDateBetween( + String companyCode, + LocalDate startDate, + LocalDate endDate + ); +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/security/ApiKeyInterceptor.java b/be-dev/src/main/java/com/example/demo/security/ApiKeyInterceptor.java new file mode 100644 index 0000000..93eecf5 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/security/ApiKeyInterceptor.java @@ -0,0 +1,50 @@ +package com.example.demo.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.beans.factory.annotation.Value; + +import java.io.IOException; + +/** + * API Key 인증 인터셉터 + * - 모든 API 요청에 대해 유효한 API Key가 포함되었는지 검증 + * - API Key는 `application.properties`에서 설정 가능 + */ +@Component +public class ApiKeyInterceptor implements HandlerInterceptor { + + @Value("${api.key}") // application.properties에서 API 키 가져오기 + private String validApiKey; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String apiKey = request.getHeader("x-api-key"); // 헤더에서 API 키 가져오기 + if (apiKey == null) { + apiKey = request.getParameter("apikey"); // 쿼리 파라미터에서도 가져오기 + } + + if (apiKey == null) { + sendJsonResponse(response, HttpServletResponse.SC_BAD_REQUEST, "API Key가 필요합니다."); + return false; + } + + if (!apiKey.equals(validApiKey)) { // API 키가 일치하지 않으면 403 반환 + sendJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "잘못된 API Key입니다."); + return false; + } + + return true; // API Key 검증 통과 + } + + // JSON 응답을 반환 + private boolean sendJsonResponse(HttpServletResponse response, int status, String message) throws IOException { + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + response.setStatus(status); + response.getWriter().write(String.format("{\"message\": \"%s\", \"status\": %d}", message, status)); + return false; // API 요청 차단 (preHandle 종료) + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/security/RateLimitInterceptor.java b/be-dev/src/main/java/com/example/demo/security/RateLimitInterceptor.java new file mode 100644 index 0000000..942d390 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/security/RateLimitInterceptor.java @@ -0,0 +1,62 @@ +package com.example.demo.security; + +import org.springframework.stereotype.Component; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.HandlerInterceptor; + +import java.time.Instant; +import java.util.Deque; +import java.util.LinkedList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class RateLimitInterceptor implements HandlerInterceptor { + + private static final int REQUEST_LIMIT = 10; // 최대 요청 개수 + private static final long TIME_WINDOW = 10 * 1000; // 10초 (밀리초) + + // API 키별 요청 기록 저장 (메모리 기반) + private final Map> requestLogs = new ConcurrentHashMap<>(); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String apiKey = request.getHeader("x-api-key"); // API 키 가져오기 + + if (apiKey == null || apiKey.isEmpty()) { + response.sendError(HttpStatus.BAD_REQUEST.value(), "Missing API Key"); + return false; + } + + // 현재 시간 기준으로 요청 제한 검사 + long now = Instant.now().toEpochMilli(); + requestLogs.putIfAbsent(apiKey, new LinkedList<>()); + Deque timestamps = requestLogs.get(apiKey); + + synchronized (timestamps) { + // 10초보다 오래된 요청 제거 + while (!timestamps.isEmpty() && now - timestamps.peekFirst() > TIME_WINDOW) { + timestamps.pollFirst(); + } + + // 요청 개수 확인 + if (timestamps.size() >= REQUEST_LIMIT) { + long retryAfter = (timestamps.peekFirst() + TIME_WINDOW - now) / 1000; // 초 단위 변환 + response.setHeader("Retry-After", String.valueOf(retryAfter)); + response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(), "Rate limit exceeded. Try again in " + retryAfter + " seconds."); + return false; + } + + // 현재 요청 추가 + timestamps.addLast(now); + } + + return true; + } + + public synchronized void resetRateLimit() { + requestLogs.clear(); + } +} \ No newline at end of file diff --git a/be-dev/src/main/java/com/example/demo/service/StockService.java b/be-dev/src/main/java/com/example/demo/service/StockService.java new file mode 100644 index 0000000..d4758a2 --- /dev/null +++ b/be-dev/src/main/java/com/example/demo/service/StockService.java @@ -0,0 +1,39 @@ +package com.example.demo.service; + +import com.example.demo.dto.StockResponseDTO; +import com.example.demo.entity.StocksHistory; +import com.example.demo.repository.StockHistoryRepository; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class StockService { + + private final StockHistoryRepository stockHistoryRepository; + + public StockService(StockHistoryRepository stockHistoryRepository) { + this.stockHistoryRepository = stockHistoryRepository; + } + + /** + * 특정 기업의 주가 데이터를 조회 + * @param companyCode 조회할 기업 코드 + * @param startDate 조회 시작 날짜 + * @param endDate 조회 종료 날짜 + * @return `StockResponseDTO` 리스트 (해당 날짜 범위 내 데이터) + */ + public List getStockPrices(String companyCode, LocalDate startDate, LocalDate endDate) { + List stockList = stockHistoryRepository.findByCompanyCodeAndTradeDateBetween(companyCode, startDate, endDate); + + return stockList.stream() + .map(stock -> new StockResponseDTO( + stock.getCompanyCode(), // 기업 코드 반환 + stock.getTradeDate().toString(), // 날짜 변환 (yyyy-MM-dd) + (long) stock.getClosingPrice() // 종가 변환 float → long + )) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/be-dev/src/main/resources/application.properties b/be-dev/src/main/resources/application.properties new file mode 100644 index 0000000..73eea30 --- /dev/null +++ b/be-dev/src/main/resources/application.properties @@ -0,0 +1,25 @@ +# MySQL 데이터베이스 연결 설정 +spring.datasource.url=jdbc:mysql://ec2-3-36-99-237.ap-northeast-2.compute.amazonaws.com:13306/assignment +spring.datasource.username= +spring.datasource.password= +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +# JPA (Hibernate) 설정 +spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect +spring.jpa.hibernate.ddl-auto=none +# 실행되는 SQL 로그 출력 (디버깅 용도) +spring.jpa.show-sql=true +# SQL을 가독성 있게 출력 +spring.jpa.properties.hibernate.format_sql=true + +# HikariCP 커넥션 풀 설정 (max connection 5 이하로 제한) +spring.datasource.hikari.maximum-pool-size=5 +spring.datasource.hikari.minimum-idle=1 + +# API 키 +api.key=c18aa07f-f005-4c2f-b6db-dff8294e6b5e + +# 응답 JSON 인코딩 설정 (한글 깨짐 방지) +server.servlet.encoding.charset=UTF-8 +server.servlet.encoding.enabled=true +server.servlet.encoding.force=true diff --git a/be-dev/src/test/java/com/example/demo/DemoApplicationTests.java b/be-dev/src/test/java/com/example/demo/DemoApplicationTests.java new file mode 100644 index 0000000..2778a6a --- /dev/null +++ b/be-dev/src/test/java/com/example/demo/DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/be-dev/src/test/java/com/example/demo/controller/StockControllerTest.java b/be-dev/src/test/java/com/example/demo/controller/StockControllerTest.java new file mode 100644 index 0000000..d785791 --- /dev/null +++ b/be-dev/src/test/java/com/example/demo/controller/StockControllerTest.java @@ -0,0 +1,119 @@ +package com.example.demo.controller; + +import com.example.demo.service.StockService; +import com.example.demo.security.RateLimitInterceptor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +@SpringBootTest +@AutoConfigureMockMvc // MockMvc 자동 설정 +class StockControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private StockService stockService; // 실제 빈 대신 Mock 객체 사용 + + @Autowired + private RateLimitInterceptor rateLimitInterceptor; + + private static final String API_KEY = "c18aa07f-f005-4c2f-b6db-dff8294e6b5e"; + + @BeforeEach + void resetRateLimit() { + rateLimitInterceptor.resetRateLimit(); // 요청 기록 초기화 + } + + @Test + @DisplayName("정상 요청 - 200 OK") + void getStockPrices_Success() throws Exception { + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10") + .header("x-api-key", API_KEY)) + .andExpect(status().isOk()); + } + + @Test + @DisplayName("정상 요청 - JSON 응답") + void getStockPrices_JSON_Success() throws Exception { + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10") + .header("x-api-key", API_KEY) + .accept(MediaType.APPLICATION_JSON)) // JSON 응답 요청 + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)); // JSON 타입 확인 + } + + @Test + @DisplayName("정상 요청 - XML 응답") + void getStockPrices_XML_Success() throws Exception { + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10") + .header("x-api-key", API_KEY) + .accept(MediaType.APPLICATION_XML)) // XML 응답 요청 + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_XML)); // XML 타입 확인 + } + + @Test + @DisplayName("필수 파라미터 누락 - 400 Bad Request") + void getStockPrices_MissingParams() throws Exception { + mockMvc.perform(get("/api/v1/stock/AAPL") + .header("x-api-key", API_KEY)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("API 키 누락 - 400 Bad Request") + void getStockPrices_MissingApiKey() throws Exception { + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10")) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("잘못된 API 키 - 403 Forbidden") + void getStockPrices_InvalidApiKey() throws Exception { + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10") + .header("x-api-key", "invalid-key")) + .andExpect(status().isForbidden()); + } + + @Test + @DisplayName("Rate Limit 초과 시 429 Too Many Requests 반환") + void getStockPrices_TooManyRequests() throws Exception { + // 10초는 정상 응답이 반환됨 + for (int i = 0; i < 10; i++) { + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10") + .header("x-api-key", API_KEY)) + .andExpect(status().isOk()); // 정상 응답 + } + + // 11번째 요청 → Rate Limit 초과 → 429 반환 + mockMvc.perform(get("/api/v1/stock/AAPL") + .param("startDate", "2024-01-01") + .param("endDate", "2024-01-10") + .header("x-api-key", API_KEY)) + .andExpect(status().isTooManyRequests()); // 429 상태 코드 + } +} \ No newline at end of file