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/.gitignore b/.gitignore new file mode 100644 index 0000000..48238f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +#application.xx +src/main/resources/*.yml + +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/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..64eae4b --- /dev/null +++ b/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.2' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.ktb' +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-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + // Validation + implementation 'com.google.code.findbugs:jsr305:3.0.2' + implementation 'org.springframework.boot:spring-boot-starter-validation' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradlew b/gradlew new file mode 100644 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..306ff4d --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'assignment' diff --git a/src/main/java/com/ktb/assignment/AssignmentApplication.java b/src/main/java/com/ktb/assignment/AssignmentApplication.java new file mode 100644 index 0000000..8078165 --- /dev/null +++ b/src/main/java/com/ktb/assignment/AssignmentApplication.java @@ -0,0 +1,13 @@ +package com.ktb.assignment; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AssignmentApplication { + + public static void main(String[] args) { + SpringApplication.run(AssignmentApplication.class, args); + } + +} diff --git a/src/main/java/com/ktb/assignment/config/WebConfig.java b/src/main/java/com/ktb/assignment/config/WebConfig.java new file mode 100644 index 0000000..2da8127 --- /dev/null +++ b/src/main/java/com/ktb/assignment/config/WebConfig.java @@ -0,0 +1,23 @@ +package com.ktb.assignment.config; + +import com.ktb.assignment.interceptor.pre.ApiKeyInterceptor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + private final ApiKeyInterceptor apiKeyInterceptor; + + public WebConfig(ApiKeyInterceptor apiKeyInterceptor) { + this.apiKeyInterceptor = apiKeyInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(apiKeyInterceptor) + .addPathPatterns("/api/**"); + } +} + diff --git a/src/main/java/com/ktb/assignment/constant/Constants.java b/src/main/java/com/ktb/assignment/constant/Constants.java new file mode 100644 index 0000000..c654e2b --- /dev/null +++ b/src/main/java/com/ktb/assignment/constant/Constants.java @@ -0,0 +1,6 @@ +package com.ktb.assignment.constant; + +public class Constants { + public static final int MAX_REQUESTS = 10; + public static final long TIME_WINDOW = 10_000; +} diff --git a/src/main/java/com/ktb/assignment/controller/StockController.java b/src/main/java/com/ktb/assignment/controller/StockController.java new file mode 100644 index 0000000..0563859 --- /dev/null +++ b/src/main/java/com/ktb/assignment/controller/StockController.java @@ -0,0 +1,28 @@ +package com.ktb.assignment.controller; + +import com.ktb.assignment.dto.ResponseDto; +import com.ktb.assignment.dto.stock.response.StockInfoResponseDto; +import com.ktb.assignment.service.StockService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.util.List; + +@RestController +@Slf4j +@RequiredArgsConstructor +@RequestMapping("/api/v1/stocks") +public class StockController { + + private final StockService stockService; + + @GetMapping("") + public ResponseDto> getStockHistory( + @RequestParam("company_code") String companyCode, + @RequestParam("start_date") LocalDate startDate, + @RequestParam("end_date") LocalDate endDate){ + return ResponseDto.ok(stockService.getStockHistory(companyCode, startDate, endDate)); + } +} diff --git a/src/main/java/com/ktb/assignment/domain/Company.java b/src/main/java/com/ktb/assignment/domain/Company.java new file mode 100644 index 0000000..72fd05c --- /dev/null +++ b/src/main/java/com/ktb/assignment/domain/Company.java @@ -0,0 +1,29 @@ +package com.ktb.assignment.domain; + + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; +import lombok.Builder; +import java.util.List; + +@Entity +@Table(name = "company") +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Company { + + @Id + @Column(name = "company_code", length = 10, nullable = false) + private String companyCode; + + @Column(name = "company_name", length = 100, nullable = false) + private String companyName; + + @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true) + private List stocksHistory; +} + diff --git a/src/main/java/com/ktb/assignment/domain/StocksHistory.java b/src/main/java/com/ktb/assignment/domain/StocksHistory.java new file mode 100644 index 0000000..174474f --- /dev/null +++ b/src/main/java/com/ktb/assignment/domain/StocksHistory.java @@ -0,0 +1,49 @@ +package com.ktb.assignment.domain; + + + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; +import lombok.Builder; + +import java.time.LocalDate; + + +@Entity +@Table(name = "stocks_history") +@IdClass(StocksHistoryId.class) // 복합 키 클래스 적용 +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +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; + + @ManyToOne + @JoinColumn(name = "company_code", insertable = false, updatable = false) + private Company company; + + @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 closePrice; + + @Column(name = "volume", nullable = false) + private float volume; +} diff --git a/src/main/java/com/ktb/assignment/domain/StocksHistoryId.java b/src/main/java/com/ktb/assignment/domain/StocksHistoryId.java new file mode 100644 index 0000000..139077c --- /dev/null +++ b/src/main/java/com/ktb/assignment/domain/StocksHistoryId.java @@ -0,0 +1,27 @@ +package com.ktb.assignment.domain; + + + +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.time.LocalDate; + + + +@EqualsAndHashCode +@NoArgsConstructor +public class StocksHistoryId implements Serializable { + + private String companyCode; + private LocalDate tradeDate; + + public StocksHistoryId(String companyCode, LocalDate tradeDate) { + this.companyCode = companyCode; + this.tradeDate = tradeDate; + } +} + + + diff --git a/src/main/java/com/ktb/assignment/dto/ArgumentNotValidExceptionDto.java b/src/main/java/com/ktb/assignment/dto/ArgumentNotValidExceptionDto.java new file mode 100644 index 0000000..294804d --- /dev/null +++ b/src/main/java/com/ktb/assignment/dto/ArgumentNotValidExceptionDto.java @@ -0,0 +1,34 @@ +package com.ktb.assignment.dto; + +import com.ktb.assignment.exception.ErrorCode; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import lombok.Getter; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; + +import java.util.HashMap; +import java.util.Map; + +@Getter +public class ArgumentNotValidExceptionDto extends ExceptionDto { + private final Map errorFields; + + public ArgumentNotValidExceptionDto(final MethodArgumentNotValidException methodArgumentNotValidException) { + super(ErrorCode.INVALID_PARAMETER); + + this.errorFields = new HashMap<>(); + methodArgumentNotValidException.getBindingResult() + .getAllErrors().forEach(e -> this.errorFields.put(((FieldError) e).getField(), e.getDefaultMessage())); + } + + public ArgumentNotValidExceptionDto(final ConstraintViolationException constraintViolationException) { + super(ErrorCode.INVALID_PARAMETER); + + this.errorFields = new HashMap<>(); + + for (ConstraintViolation constraintViolation : constraintViolationException.getConstraintViolations()) { + errorFields.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage()); + } + } +} diff --git a/src/main/java/com/ktb/assignment/dto/ExceptionDto.java b/src/main/java/com/ktb/assignment/dto/ExceptionDto.java new file mode 100644 index 0000000..908522e --- /dev/null +++ b/src/main/java/com/ktb/assignment/dto/ExceptionDto.java @@ -0,0 +1,15 @@ +package com.ktb.assignment.dto; + +import com.ktb.assignment.exception.ErrorCode; +import lombok.Getter; + +@Getter +public class ExceptionDto { + private final String code; + private final String message; + + public ExceptionDto(ErrorCode errorCode) { + this.code = errorCode.getCode(); + this.message = errorCode.getMessage(); + } +} diff --git a/src/main/java/com/ktb/assignment/dto/ResponseDto.java b/src/main/java/com/ktb/assignment/dto/ResponseDto.java new file mode 100644 index 0000000..be43290 --- /dev/null +++ b/src/main/java/com/ktb/assignment/dto/ResponseDto.java @@ -0,0 +1,29 @@ +package com.ktb.assignment.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.ktb.assignment.exception.CommonException; +import com.ktb.assignment.exception.ErrorCode; +import lombok.Builder; + +@Builder +@JsonInclude(JsonInclude.Include.NON_NULL) +public record ResponseDto( + boolean success, + T data, + ExceptionDto error +) { + // 성공 응답 + public static ResponseDto ok(T data) { + return new ResponseDto<>(true, data, null); + } + + // 실패 응답 (커스텀 예외) + public static ResponseDto fail(CommonException e) { + return new ResponseDto<>(false, null, new ExceptionDto(e.getErrorCode())); + } + + // 실패 응답 (기본 예외) + public static ResponseDto fail(ErrorCode errorCode) { + return new ResponseDto<>(false, null, new ExceptionDto(errorCode)); + } +} diff --git a/src/main/java/com/ktb/assignment/dto/stock/response/StockInfoResponseDto.java b/src/main/java/com/ktb/assignment/dto/stock/response/StockInfoResponseDto.java new file mode 100644 index 0000000..1472526 --- /dev/null +++ b/src/main/java/com/ktb/assignment/dto/stock/response/StockInfoResponseDto.java @@ -0,0 +1,25 @@ +package com.ktb.assignment.dto.stock.response; + + +import jakarta.validation.constraints.NotNull; +import lombok.Builder; + +@Builder +public record StockInfoResponseDto( + @NotNull + String companyName, + + @NotNull + String tradeDate, + + @NotNull + float closingPrice +) { + public static StockInfoResponseDto create(String companyName, String tradeDate, float closingPrice){ + return StockInfoResponseDto.builder() + .companyName(companyName) + .tradeDate(tradeDate) + .closingPrice(closingPrice) + .build(); + } +} diff --git a/src/main/java/com/ktb/assignment/exception/CommonException.java b/src/main/java/com/ktb/assignment/exception/CommonException.java new file mode 100644 index 0000000..221d6bc --- /dev/null +++ b/src/main/java/com/ktb/assignment/exception/CommonException.java @@ -0,0 +1,18 @@ +package com.ktb.assignment.exception; + +public class CommonException extends RuntimeException{ + private final ErrorCode errorCode; + + public CommonException(ErrorCode errorCode) { + this.errorCode = errorCode; + } + + public ErrorCode getErrorCode() { + return errorCode; + } + + @Override + public String getMessage() { + return errorCode.getMessage(); + } +} diff --git a/src/main/java/com/ktb/assignment/exception/ErrorCode.java b/src/main/java/com/ktb/assignment/exception/ErrorCode.java new file mode 100644 index 0000000..53c1bac --- /dev/null +++ b/src/main/java/com/ktb/assignment/exception/ErrorCode.java @@ -0,0 +1,32 @@ +package com.ktb.assignment.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum ErrorCode { + // 400 error + INVALID_PARAMETER("40000", HttpStatus.BAD_REQUEST, "유효하지 않는 파라미터입니다."), + MISSING_REQUEST_PARAMETER("40001", HttpStatus.BAD_REQUEST, "필수 파라미터가 누락되었습니다."), + MISSING_REQUEST_BODY("40002", HttpStatus.BAD_REQUEST, "요청 바디가 누락되었습니다."), + MISSING_API_KEY_PARAMETER("40003", HttpStatus.BAD_REQUEST, "API Key가 누락되었습니다."), + INVALID_DATE_FORMAT("40004", HttpStatus.BAD_REQUEST, "날짜 형식이 올바르지 않습니다. (yyyy-MM-dd) 형식을 사용하세요."), + + // 403 error + ACCESS_DENIED_ERROR("40300", HttpStatus.FORBIDDEN, "API Key가 일치하지 않습니다."), + + // 404 error + NOT_FOUND_END_POINT("40400", HttpStatus.NOT_FOUND, "존재하지 않는 엔드포인트입니다."), + + // 429 error + RATE_LIMIT_EXCEEDED("42900", HttpStatus.TOO_MANY_REQUESTS, "API Key 요청 제한 초과 (10초당 최대 10건)"), + + // 500 error + SERVER_ERROR("50000", HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부 오류입니다."); + + private final String code; + private final HttpStatus httpStatus; + private final String message; +} diff --git a/src/main/java/com/ktb/assignment/exception/GlobalExceptionHandler.java b/src/main/java/com/ktb/assignment/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..54dd5a1 --- /dev/null +++ b/src/main/java/com/ktb/assignment/exception/GlobalExceptionHandler.java @@ -0,0 +1,89 @@ +package com.ktb.assignment.exception; + +import com.ktb.assignment.dto.ResponseDto; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.multipart.support.MissingServletRequestPartException; +import org.springframework.web.servlet.NoHandlerFoundException; + +import java.time.LocalDate; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + // 존재하지 않는 API 요청 (404) + @ExceptionHandler({NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class}) + public ResponseEntity> handleNoPageFoundException(Exception e) { + log.error("handleNoPageFoundException: {}", e.getMessage()); + + CommonException exception = new CommonException(ErrorCode.NOT_FOUND_END_POINT); + return ResponseEntity + .status(exception.getErrorCode().getHttpStatus()) // ✅ HTTP 상태 코드 직접 설정 + .body(ResponseDto.fail(exception)); + } + + // 필수 요청 파라미터가 누락된 경우 (400) + @ExceptionHandler(MissingServletRequestPartException.class) + public ResponseEntity> handleServletRequestParameterException(MissingServletRequestPartException e) { + log.error("handleServletRequestParameterException: {}", e.getMessage()); + + CommonException exception = new CommonException(ErrorCode.MISSING_REQUEST_PARAMETER); + return ResponseEntity + .status(exception.getErrorCode().getHttpStatus()) + .body(ResponseDto.fail(exception)); + } + + // 요청 Body가 없는 경우 (400) + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> handleMessageNotReadableException(HttpMessageNotReadableException e) { + log.error("handleMessageNotReadableException: {}", e.getMessage()); + + CommonException exception = new CommonException(ErrorCode.MISSING_REQUEST_BODY); + return ResponseEntity + .status(exception.getErrorCode().getHttpStatus()) + .body(ResponseDto.fail(exception)); + } + + // API 요청 LocalDate 인자 타입이 틀린 경우 (400) + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity> handleArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) { + log.error("handleArgumentTypeMismatchException: {}", e.getMessage()); + + if (e.getRequiredType() != null && e.getRequiredType().equals(LocalDate.class)) { + return ResponseEntity + .status(ErrorCode.INVALID_DATE_FORMAT.getHttpStatus()) + .body(ResponseDto.fail(new CommonException(ErrorCode.INVALID_DATE_FORMAT))); + } + + return ResponseEntity + .status(ErrorCode.INVALID_PARAMETER.getHttpStatus()) + .body(ResponseDto.fail(new CommonException(ErrorCode.INVALID_PARAMETER))); + } + + // 개발자가 직접 정의한 커스텀 예외 + @ExceptionHandler(CommonException.class) + public ResponseEntity> handleApiException(CommonException e) { + log.error("handleApiException: {}", e.getMessage()); + + return ResponseEntity + .status(e.getErrorCode().getHttpStatus()) + .body(ResponseDto.fail(e)); + } + + // 서버 내부 오류 (500) + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException(Exception e) { + log.error("handleException: {}", e.getMessage(), e); + + CommonException exception = new CommonException(ErrorCode.SERVER_ERROR); + return ResponseEntity + .status(exception.getErrorCode().getHttpStatus()) + .body(ResponseDto.fail(exception)); + } +} diff --git a/src/main/java/com/ktb/assignment/interceptor/pre/ApiKeyInterceptor.java b/src/main/java/com/ktb/assignment/interceptor/pre/ApiKeyInterceptor.java new file mode 100644 index 0000000..7516a35 --- /dev/null +++ b/src/main/java/com/ktb/assignment/interceptor/pre/ApiKeyInterceptor.java @@ -0,0 +1,39 @@ +package com.ktb.assignment.interceptor.pre; + +import com.ktb.assignment.exception.CommonException; +import com.ktb.assignment.exception.ErrorCode; +import com.ktb.assignment.util.ApiRateLimiter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +@Component +@RequiredArgsConstructor +public class ApiKeyInterceptor implements HandlerInterceptor { + + @Value("${spring.api.key}") + private String API_KEY; + + private final ApiRateLimiter apiRateLimiter; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String apiKey = request.getHeader("x-api-key"); + + if (apiKey == null || apiKey.isEmpty()) { + apiKey = request.getParameter("apikey"); + } + + // API Key가 없는 경우 + if (apiKey == null || apiKey.isEmpty()) throw new CommonException(ErrorCode.MISSING_API_KEY_PARAMETER); + + // API Key 검증 + if (!API_KEY.equals(apiKey)) throw new CommonException(ErrorCode.ACCESS_DENIED_ERROR); + + apiRateLimiter.validateRequest(apiKey); + return true; + } +} diff --git a/src/main/java/com/ktb/assignment/repository/StocksHistoryRepository.java b/src/main/java/com/ktb/assignment/repository/StocksHistoryRepository.java new file mode 100644 index 0000000..e09ae58 --- /dev/null +++ b/src/main/java/com/ktb/assignment/repository/StocksHistoryRepository.java @@ -0,0 +1,20 @@ +package com.ktb.assignment.repository; + +import com.ktb.assignment.domain.StocksHistory; +import com.ktb.assignment.domain.StocksHistoryId; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.time.LocalDate; +import java.util.List; + +@Repository +public interface StocksHistoryRepository extends JpaRepository { + List findByCompany_CompanyCodeAndTradeDateBetween( + @Param("companyCode") String companyCode, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate + ); +} diff --git a/src/main/java/com/ktb/assignment/service/StockService.java b/src/main/java/com/ktb/assignment/service/StockService.java new file mode 100644 index 0000000..a0c13e6 --- /dev/null +++ b/src/main/java/com/ktb/assignment/service/StockService.java @@ -0,0 +1,34 @@ +package com.ktb.assignment.service; + +import com.ktb.assignment.domain.StocksHistory; +import com.ktb.assignment.dto.stock.response.StockInfoResponseDto; +import com.ktb.assignment.repository.StocksHistoryRepository; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@Slf4j +@RequiredArgsConstructor +public class StockService { + + private final StocksHistoryRepository stocksHistoryRepository; + + public List getStockHistory(String companyCode, LocalDate startDate, LocalDate endDate){ + + List stocksHistories = stocksHistoryRepository.findByCompany_CompanyCodeAndTradeDateBetween(companyCode, startDate, endDate); + + return stocksHistories.stream() + .map(stocksHistory -> new StockInfoResponseDto( + stocksHistory.getCompany().getCompanyName(), + stocksHistory.getTradeDate().toString(), + stocksHistory.getClosePrice() + )) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/com/ktb/assignment/util/ApiRateLimiter.java b/src/main/java/com/ktb/assignment/util/ApiRateLimiter.java new file mode 100644 index 0000000..06df6f0 --- /dev/null +++ b/src/main/java/com/ktb/assignment/util/ApiRateLimiter.java @@ -0,0 +1,38 @@ +package com.ktb.assignment.util; + +import com.ktb.assignment.constant.Constants; +import com.ktb.assignment.exception.CommonException; +import com.ktb.assignment.exception.ErrorCode; + +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.util.Deque; +import java.util.LinkedList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class ApiRateLimiter { + + private final Map> requestLogs = new ConcurrentHashMap<>(); + + public void validateRequest(String apiKey) { + long now = Instant.now().toEpochMilli(); + requestLogs.putIfAbsent(apiKey, new LinkedList<>()); + + Deque timestamps = requestLogs.get(apiKey); + + synchronized (timestamps) { + while (!timestamps.isEmpty() && (now - timestamps.peekFirst() > Constants.TIME_WINDOW)) { + timestamps.pollFirst(); + } + + if (timestamps.size() >= Constants.MAX_REQUESTS) { + throw new CommonException(ErrorCode.RATE_LIMIT_EXCEEDED); + } + + timestamps.addLast(now); + } + } +}