diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a979af --- /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/ + +### Kotlin ### +.kotlin diff --git a/README.md b/README.md new file mode 100644 index 0000000..c69f50f --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# hero-alignlab-api + +> 자세공작소 \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..ac3aa7a --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,129 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + extra.apply { + } +} + +plugins { + val kotlinVersion = "1.9.24" + + id("org.springframework.boot") version "3.3.1" + id("io.spring.dependency-management") version "1.1.5" + kotlin("jvm") version kotlinVersion + kotlin("plugin.spring") version kotlinVersion + kotlin("plugin.jpa") version kotlinVersion + kotlin("plugin.allopen") version kotlinVersion + kotlin("kapt") version kotlinVersion + + idea +} + +group = "com.hero" + +java { + sourceCompatibility = JavaVersion.VERSION_17 +} + +repositories { + mavenCentral() +} + +idea { + module { + val kaptMain = file("build/generated/source/kapt/main") + sourceDirs.add(kaptMain) + generatedSourceDirs.add(kaptMain) + } +} + +/** + * https://kotlinlang.org/docs/reference/compiler-plugins.html#spring-support + * automatically supported annotation + * @Component, @Async, @Transactional, @Cacheable, @SpringBootTest, + * @Configuration, @Controller, @RestController, @Service, @Repository. + * jpa meta-annotations not automatically opened through the default settings of the plugin.spring + */ +allOpen { + annotation("jakarta.persistence.Entity") + annotation("jakarta.persistence.MappedSuperclass") + annotation("jakarta.persistence.Embeddable") +} + +dependencies { + /** spring starter */ + implementation("org.springframework.boot:spring-boot-starter-webflux") + implementation("org.springframework.boot:spring-boot-starter-actuator") + implementation("org.springframework.boot:spring-boot-starter-validation") + implementation("org.springframework.boot:spring-boot-starter-data-jpa") + implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive") + kapt("org.springframework.boot:spring-boot-configuration-processor") + + /** kotlin */ + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") + implementation("org.jetbrains.kotlin:kotlin-reflect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") + + /** arrow-kt */ + implementation("io.arrow-kt:arrow-core:${DependencyVersion.ARROW_FX}") + implementation("io.arrow-kt:arrow-fx-coroutines:${DependencyVersion.ARROW_FX}") + implementation("io.arrow-kt:arrow-fx-stm:${DependencyVersion.ARROW_FX}") + + /** swagger */ + implementation("org.springdoc:springdoc-openapi-starter-webflux-ui:${DependencyVersion.SPRINGDOC}") + runtimeOnly("com.github.therapi:therapi-runtime-javadoc-scribe:${DependencyVersion.JAVADOC_SCRIBE}") + kapt("com.github.therapi:therapi-runtime-javadoc-scribe:${DependencyVersion.JAVADOC_SCRIBE}") + + /** logger */ + implementation("io.github.oshai:kotlin-logging-jvm:${DependencyVersion.KOTLIN_LOGGING}") + implementation("net.logstash.logback:logstash-logback-encoder:${DependencyVersion.LOGBACK_ENCODER}") + + /** database */ + runtimeOnly("com.mysql:mysql-connector-j") + + /** test */ + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("io.projectreactor:reactor-test") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.testcontainers:mysql:${DependencyVersion.TEST_CONTAINER_MYSQL}") + testImplementation("com.github.gavlyukovskiy:p6spy-spring-boot-starter:${DependencyVersion.P6SPY_LOG}") + testImplementation("ch.qos.logback:logback-classic:${DependencyVersion.LOGBACK_CLASSIC}") + testImplementation("io.mockk:mockk:${DependencyVersion.MOCKK}") + + /** kotest */ + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test") + testImplementation("io.kotest:kotest-runner-junit5:${DependencyVersion.KOTEST}") + testImplementation("io.kotest:kotest-assertions-core:${DependencyVersion.KOTEST}") + testImplementation("io.kotest:kotest-property:${DependencyVersion.KOTEST}") + testImplementation("io.kotest:kotest-framework-datatest-jvm:${DependencyVersion.KOTEST}") + testImplementation("io.kotest.extensions:kotest-extensions-spring:${DependencyVersion.KOTEST_EXTENSION}") +} + +defaultTasks("bootRun") + +springBoot.buildInfo { properties { } } + +configurations.all { + resolutionStrategy.cacheChangingModulesFor(0, "seconds") +} + +tasks.getByName("jar") { + enabled = false +} + +tasks.withType { + kotlinOptions { + freeCompilerArgs += "-Xjsr305=strict" + jvmTarget = "17" + } +} + +tasks.withType { + gradleVersion = "8.7" +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..876c922 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + `kotlin-dsl` +} + +repositories { + mavenCentral() +} diff --git a/buildSrc/src/main/kotlin/DependencyVersion.kt b/buildSrc/src/main/kotlin/DependencyVersion.kt new file mode 100644 index 0000000..4d4f8f1 --- /dev/null +++ b/buildSrc/src/main/kotlin/DependencyVersion.kt @@ -0,0 +1,20 @@ +object DependencyVersion { + /** external */ + const val ARROW_FX = "1.2.4" + const val KOTLIN_LOGGING = "6.0.9" + const val LOGBACK_ENCODER = "7.4" + + /** springdoc */ + const val SPRINGDOC = "2.3.0" + const val JAVADOC_SCRIBE = "0.15.0" + + /** test */ + const val TEST_CONTAINER_MYSQL = "1.24.0" + const val P6SPY_LOG = "1.9.1" + const val LOGBACK_CLASSIC = "1.5.6" + const val MOCKK = "1.13.11" + + /** kotest */ + const val KOTEST = "5.9.0" + const val KOTEST_EXTENSION = "1.1.3" +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2b46360 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +version = "0.0.1-SNAPSHOT" +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 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..b82aa23 --- /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.7-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..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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. +# + +############################################################################## +# +# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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..7101f8e --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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 + +@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.kts b/settings.gradle.kts new file mode 100644 index 0000000..b083ef4 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "hero-alignlab-api" diff --git a/sql/DDL.sql b/sql/DDL.sql new file mode 100644 index 0000000..e03286c --- /dev/null +++ b/sql/DDL.sql @@ -0,0 +1,2 @@ +-- scheme +CREATE DATABASE hero CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; \ No newline at end of file diff --git a/src/main/kotlin/com/hero/alignlab/Application.kt b/src/main/kotlin/com/hero/alignlab/Application.kt new file mode 100644 index 0000000..85ebcc7 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/Application.kt @@ -0,0 +1,38 @@ +package com.hero.alignlab + +import com.hero.alignlab.extension.Zone +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.context.event.ApplicationReadyEvent +import org.springframework.boot.info.BuildProperties +import org.springframework.boot.runApplication +import org.springframework.context.ApplicationListener +import org.springframework.core.env.Environment +import org.springframework.scheduling.annotation.EnableScheduling +import java.util.* + +@EnableScheduling +@SpringBootApplication +class Application( + private val buildProperties: BuildProperties, + private val environment: Environment, +) : ApplicationListener { + private val logger = KotlinLogging.logger { } + + override fun onApplicationEvent(event: ApplicationReadyEvent) { + val application = buildProperties.name + val profiles = environment.activeProfiles.contentToString() + logger.info { "$application applicationReady, profiles=$profiles" } + } +} + +fun main(args: Array) { + /** Initialize jvm level configuration */ + init() + runApplication(*args) +} + +fun init() { + /** Setting the Default TimeZone */ + TimeZone.setDefault(TimeZone.getTimeZone(Zone.KST)) +} diff --git a/src/main/kotlin/com/hero/alignlab/config/JacksonConfig.kt b/src/main/kotlin/com/hero/alignlab/config/JacksonConfig.kt new file mode 100644 index 0000000..42c4846 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/JacksonConfig.kt @@ -0,0 +1,23 @@ +package com.hero.alignlab.config + +import com.fasterxml.jackson.annotation.JsonInclude +import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder + +@Configuration +class JacksonConfig { + /** + * this Bean can customize spring boot auto-configured ObjectMapper. + * you can also customize via yml configuration. spring.jackson.x + */ + @Bean + fun customizeJson(): Jackson2ObjectMapperBuilderCustomizer { + return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder -> + builder + .failOnUnknownProperties(false) + .serializationInclusion(JsonInclude.Include.NON_ABSENT) + } + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/database/HeroDatabaseConfig.kt b/src/main/kotlin/com/hero/alignlab/config/database/HeroDatabaseConfig.kt new file mode 100644 index 0000000..15f7f9c --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/database/HeroDatabaseConfig.kt @@ -0,0 +1,94 @@ +package com.hero.alignlab.config.database + +import com.zaxxer.hikari.HikariDataSource +import jakarta.persistence.EntityManagerFactory +import org.hibernate.cfg.AvailableSettings +import org.springframework.beans.factory.annotation.Qualifier +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties +import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties +import org.springframework.boot.context.properties.ConfigurationProperties +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Primary +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor +import org.springframework.data.jpa.repository.config.EnableJpaRepositories +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate +import org.springframework.orm.hibernate5.SpringBeanContainer +import org.springframework.orm.jpa.JpaTransactionManager +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean +import org.springframework.transaction.PlatformTransactionManager +import org.springframework.transaction.annotation.EnableTransactionManagement +import javax.sql.DataSource + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories( + basePackages = [ + "com.hero.alignlab.domain" + ], + entityManagerFactoryRef = "heroEntityManager", + transactionManagerRef = "heroTransactionManager" +) +class HeroDatabaseConfig { + @Bean + @Primary + @ConfigurationProperties(prefix = "hero.master.datasource") + fun heroMasterDataSourceProperties(): DataSourceProperties { + return DataSourceProperties() + } + + @Bean + @Primary + @ConfigurationProperties(prefix = "hero.master.datasource.hikari") + fun heroMasterHikariDataSource( + @Qualifier("heroMasterDataSourceProperties") masterProperty: DataSourceProperties, + ): HikariDataSource { + return masterProperty + .initializeDataSourceBuilder() + .type(HikariDataSource::class.java) + .build() + } + + @Bean + fun heroNamedParameterJdbcTemplate( + @Qualifier("heroMasterHikariDataSource") dataSource: DataSource, + ): NamedParameterJdbcTemplate { + return NamedParameterJdbcTemplate(dataSource) + } + + @Bean + @Primary + @ConfigurationProperties(prefix = "hero.jpa") + fun heroJpaProperties(): JpaProperties { + return JpaProperties() + } + + @Bean + @Primary + fun heroEntityManager( + entityManagerFactoryBuilder: EntityManagerFactoryBuilder, + configurableListableBeanFactory: ConfigurableListableBeanFactory, + @Qualifier("heroMasterHikariDataSource") heroDataSource: DataSource, + ): LocalContainerEntityManagerFactoryBean { + return entityManagerFactoryBuilder + .dataSource(heroDataSource) + .packages("com.hero.alignlab.domain") + .properties(mapOf(AvailableSettings.BEAN_CONTAINER to SpringBeanContainer(configurableListableBeanFactory))) + .build() + } + + @Bean + @Primary + fun heroTransactionManager( + @Qualifier("heroEntityManager") heroEntityManager: EntityManagerFactory, + ): PlatformTransactionManager { + return JpaTransactionManager(heroEntityManager) + } + + @Bean + fun persistenceExceptionTranslationPostProcessor(): PersistenceExceptionTranslationPostProcessor { + return PersistenceExceptionTranslationPostProcessor() + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/database/PersistentConfig.kt b/src/main/kotlin/com/hero/alignlab/config/database/PersistentConfig.kt new file mode 100644 index 0000000..62f3e79 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/database/PersistentConfig.kt @@ -0,0 +1,8 @@ +package com.hero.alignlab.config.database + +import org.springframework.context.annotation.Configuration +import org.springframework.data.jpa.repository.config.EnableJpaAuditing + +@Configuration +@EnableJpaAuditing +class PersistentConfig diff --git a/src/main/kotlin/com/hero/alignlab/config/database/TransactionTemplates.kt b/src/main/kotlin/com/hero/alignlab/config/database/TransactionTemplates.kt new file mode 100644 index 0000000..ee57660 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/database/TransactionTemplates.kt @@ -0,0 +1,13 @@ +package com.hero.alignlab.config.database + +import org.springframework.stereotype.Component +import org.springframework.transaction.PlatformTransactionManager +import org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW +import org.springframework.transaction.support.TransactionTemplate + +@Component +class TransactionTemplates(transactionManager: PlatformTransactionManager) { + val writer = TransactionTemplate(transactionManager) + val newTxWriter = TransactionTemplate(transactionManager).apply { propagationBehavior = PROPAGATION_REQUIRES_NEW } + val reader = TransactionTemplate(transactionManager).apply { isReadOnly = true } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/environment/EnvironmentType.kt b/src/main/kotlin/com/hero/alignlab/config/environment/EnvironmentType.kt new file mode 100644 index 0000000..38c6c79 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/environment/EnvironmentType.kt @@ -0,0 +1,7 @@ +package com.hero.alignlab.config.environment + +object EnvironmentType { + const val PROFILE_PROD = "prod" + const val PROFILE_STAGING = "staging" + const val PROFILE_TEST = "test" +} diff --git a/src/main/kotlin/com/hero/alignlab/config/reactor/ReactorSchedulerConfig.kt b/src/main/kotlin/com/hero/alignlab/config/reactor/ReactorSchedulerConfig.kt new file mode 100644 index 0000000..7037553 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/reactor/ReactorSchedulerConfig.kt @@ -0,0 +1,14 @@ +package com.hero.alignlab.config.reactor + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import reactor.core.scheduler.Scheduler +import reactor.core.scheduler.Schedulers + +@Configuration +class ReactorSchedulerConfig { + @Bean + fun ioScheduler(): Scheduler { + return Schedulers.boundedElastic() + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/redis/RedisConfig.kt b/src/main/kotlin/com/hero/alignlab/config/redis/RedisConfig.kt new file mode 100644 index 0000000..e03c027 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/redis/RedisConfig.kt @@ -0,0 +1,43 @@ +package com.hero.alignlab.config.redis + +import org.springframework.boot.autoconfigure.data.redis.RedisProperties +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Primary +import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory +import org.springframework.data.redis.core.ReactiveRedisTemplate +import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer +import org.springframework.data.redis.serializer.RedisSerializationContext +import org.springframework.data.redis.serializer.StringRedisSerializer + +@Configuration +@EnableConfigurationProperties(RedisProperties::class) +class RedisConfig( + private val properties: RedisProperties, +) { + /** + * Redis Config + * - non-cluster-mode + */ + @Bean + @Primary + fun reactiveRedisConnectionFactory(): ReactiveRedisConnectionFactory { + return LettuceConnectionFactory(properties.host, properties.port) + } + + @Bean + fun reactiveRedisTemplate(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate { + val jdkSerializationRedisSerializer = JdkSerializationRedisSerializer() + val stringRedisSerializer = StringRedisSerializer.UTF_8 + + val redisSerializationContext = RedisSerializationContext + .newSerializationContext(jdkSerializationRedisSerializer) + .key(stringRedisSerializer) + .value(stringRedisSerializer) + .build() + + return ReactiveRedisTemplate(factory, redisSerializationContext) + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/swagger/SpringDocConfig.kt b/src/main/kotlin/com/hero/alignlab/config/swagger/SpringDocConfig.kt new file mode 100644 index 0000000..2d89632 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/swagger/SpringDocConfig.kt @@ -0,0 +1,44 @@ +package com.hero.alignlab.config.swagger + +import io.swagger.v3.oas.models.OpenAPI +import io.swagger.v3.oas.models.info.Info +import io.swagger.v3.oas.models.servers.Server +import org.springdoc.core.utils.SpringDocUtils +import org.springframework.boot.info.BuildProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.result.view.RequestContext +import org.springframework.web.server.WebSession + +/** + * **Swagger** + * + * Provide detailed explanations based on comments. + * + * [Local Swagger UI](http://localhost:8080/webjars/swagger-ui/index.html) + */ +@Configuration +class SpringDocConfig( + private val buildProperties: BuildProperties, +) { + init { + SpringDocUtils + .getConfig() + .addRequestWrapperToIgnore( + WebSession::class.java, + RequestContext::class.java + ) + } + + @Bean + fun openApi(): OpenAPI { + return OpenAPI() + .addServersItem(Server().url("/")) + .info( + Info() + .title(buildProperties.name) + .version(buildProperties.version) + .description("Alignlab Rest API Docs") + ) + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/validation/CoroutinesLocalValidatorFactoryBean.kt b/src/main/kotlin/com/hero/alignlab/config/validation/CoroutinesLocalValidatorFactoryBean.kt new file mode 100644 index 0000000..c99bdfb --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/validation/CoroutinesLocalValidatorFactoryBean.kt @@ -0,0 +1,59 @@ +package com.hero.alignlab.config.validation + +import jakarta.validation.ClockProvider +import jakarta.validation.ParameterNameProvider +import org.hibernate.validator.internal.engine.DefaultClockProvider +import org.springframework.core.KotlinReflectionParameterNameDiscoverer +import org.springframework.core.ParameterNameDiscoverer +import org.springframework.core.PrioritizedParameterNameDiscoverer +import org.springframework.core.StandardReflectionParameterNameDiscoverer +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean +import java.lang.reflect.Constructor +import java.lang.reflect.Method +import kotlin.reflect.jvm.kotlinFunction + +class CoroutinesLocalValidatorFactoryBean : LocalValidatorFactoryBean() { + override fun getClockProvider(): ClockProvider { + return DefaultClockProvider.INSTANCE + } + + override fun postProcessConfiguration(configuration: jakarta.validation.Configuration<*>) { + super.postProcessConfiguration(configuration) + + val discoverer = PrioritizedParameterNameDiscoverer().apply { + this.addDiscoverer(SuspendAwareKotlinParameterNameDiscoverer()) + this.addDiscoverer(StandardReflectionParameterNameDiscoverer()) + } + + val defaultProvider = configuration.defaultParameterNameProvider + configuration.parameterNameProvider(object : ParameterNameProvider { + override fun getParameterNames(constructor: Constructor<*>): List { + val paramNames: Array? = discoverer.getParameterNames(constructor) + return paramNames?.toList() ?: defaultProvider.getParameterNames(constructor) + } + + override fun getParameterNames(method: Method): List { + val paramNames: Array? = discoverer.getParameterNames(method) + return paramNames?.toList() ?: defaultProvider.getParameterNames(method) + } + }) + } +} + +class SuspendAwareKotlinParameterNameDiscoverer : ParameterNameDiscoverer { + private val defaultProvider = KotlinReflectionParameterNameDiscoverer() + + override fun getParameterNames(constructor: Constructor<*>): Array? { + return defaultProvider.getParameterNames(constructor) + } + + override fun getParameterNames(method: Method): Array? { + val defaultNames = defaultProvider.getParameterNames(method) ?: return null + val function = method.kotlinFunction + + return when { + function != null && function.isSuspend -> defaultNames + "" + else -> defaultNames + } + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/validation/ValidatorConfig.kt b/src/main/kotlin/com/hero/alignlab/config/validation/ValidatorConfig.kt new file mode 100644 index 0000000..b2514bc --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/validation/ValidatorConfig.kt @@ -0,0 +1,30 @@ +package com.hero.alignlab.config.validation + +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.boot.validation.MessageInterpolatorFactory +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Primary +import org.springframework.context.annotation.Role +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean + +@Configuration(proxyBeanMethods = false) +class ValidatorConfig { + /** + * This bean definition is part of the workaround for a bug in hibernate-validation. + * + * It replaces the default validator factory bean with ours that uses the customized parameter name discoverer. + * + * See: + * * Spring issue: https://github.com/spring-projects/spring-framework/issues/23499 + * * Hibernate issue: https://hibernate.atlassian.net/browse/HV-1638 + */ + @Primary + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun defaultValidator(): LocalValidatorFactoryBean { + val factoryBean = CoroutinesLocalValidatorFactoryBean() + factoryBean.messageInterpolator = MessageInterpolatorFactory().getObject() + return factoryBean + } +} diff --git a/src/main/kotlin/com/hero/alignlab/config/web/WebFluxConfig.kt b/src/main/kotlin/com/hero/alignlab/config/web/WebFluxConfig.kt new file mode 100644 index 0000000..29ea531 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/config/web/WebFluxConfig.kt @@ -0,0 +1,61 @@ +package com.hero.alignlab.config.web + +import com.fasterxml.jackson.databind.ObjectMapper +import org.springframework.context.annotation.Configuration +import org.springframework.core.ReactiveAdapterRegistry +import org.springframework.data.web.ReactivePageableHandlerMethodArgumentResolver +import org.springframework.data.web.ReactiveSortHandlerMethodArgumentResolver +import org.springframework.format.FormatterRegistry +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar +import org.springframework.http.codec.ServerCodecConfigurer +import org.springframework.http.codec.json.Jackson2JsonDecoder +import org.springframework.http.codec.json.Jackson2JsonEncoder +import org.springframework.util.MimeType +import org.springframework.web.cors.CorsConfiguration +import org.springframework.web.reactive.config.CorsRegistry +import org.springframework.web.reactive.config.WebFluxConfigurer +import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer +import java.nio.charset.Charset + +@Configuration +class WebFluxConfig( + private val objectMapper: ObjectMapper +) : WebFluxConfigurer { + override fun addCorsMappings(registry: CorsRegistry) { + registry.addMapping("/**") + .allowedOriginPatterns(CorsConfiguration.ALL) + .allowedMethods(CorsConfiguration.ALL) + .allowedHeaders(CorsConfiguration.ALL) + .allowCredentials(true) + .maxAge(3600) + } + + override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) { + val mimeTypes = arrayOf( + MimeType("application", "json"), + MimeType("application", "*+json"), + MimeType("application", "json", Charset.forName("UTF-8")) + ) + + configurer.defaultCodecs().jackson2JsonEncoder(Jackson2JsonEncoder(objectMapper, *mimeTypes)) + configurer.defaultCodecs().jackson2JsonDecoder(Jackson2JsonDecoder(objectMapper)) + } + + override fun configureArgumentResolvers(configurer: ArgumentResolverConfigurer) { + val registry = ReactiveAdapterRegistry() + val serverCodecConfigurer = ServerCodecConfigurer.create() + configureHttpMessageCodecs(serverCodecConfigurer) + + configurer.addCustomResolver( + ReactiveSortHandlerMethodArgumentResolver(), + ReactivePageableHandlerMethodArgumentResolver() + ) + } + + override fun addFormatters(registry: FormatterRegistry) { + val registrar = DateTimeFormatterRegistrar() + registrar.setUseIsoFormat(true) + registrar.registerFormatters(registry) + super.addFormatters(registry) + } +} diff --git a/src/main/kotlin/com/hero/alignlab/domain/health/model/response/HealthResponse.kt b/src/main/kotlin/com/hero/alignlab/domain/health/model/response/HealthResponse.kt new file mode 100644 index 0000000..d48a153 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/domain/health/model/response/HealthResponse.kt @@ -0,0 +1,15 @@ +package com.hero.alignlab.domain.health.model.response + +import java.time.LocalDateTime + +data class HealthResponse( + val env: String, + val dateTime: LocalDateTime = LocalDateTime.now(), + val message: String = "Health Good!" +) { + companion object { + fun from(env: String): HealthResponse { + return HealthResponse(env = env) + } + } +} diff --git a/src/main/kotlin/com/hero/alignlab/domain/health/resource/HealthResource.kt b/src/main/kotlin/com/hero/alignlab/domain/health/resource/HealthResource.kt new file mode 100644 index 0000000..8fa7184 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/domain/health/resource/HealthResource.kt @@ -0,0 +1,22 @@ +package com.hero.alignlab.domain.health.resource + +import com.hero.alignlab.domain.health.model.response.HealthResponse +import com.hero.alignlab.extension.wrapOk +import io.swagger.v3.oas.annotations.tags.Tag +import org.springframework.core.env.Environment +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController + +@Tag(name = "health check") +@RestController +@RequestMapping(produces = [MediaType.APPLICATION_JSON_VALUE]) +class HealthResource( + private val environment: Environment +) { + @GetMapping("/api/v1/health") + suspend fun healthCheckV1() = environment.activeProfiles.first() + .run { HealthResponse.from(this) } + .wrapOk() +} diff --git a/src/main/kotlin/com/hero/alignlab/dto/AlignlabPageRequest.kt b/src/main/kotlin/com/hero/alignlab/dto/AlignlabPageRequest.kt new file mode 100644 index 0000000..c82d89b --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/dto/AlignlabPageRequest.kt @@ -0,0 +1,39 @@ +package com.hero.alignlab.dto + +import org.springframework.data.domain.PageRequest +import org.springframework.data.domain.Pageable +import org.springframework.data.domain.Sort + +data class AlignlabPageRequest( + /** page, 0부터 시작 */ + val page: Int?, + /** size, default is 10 */ + val size: Int?, + /** + * **정렬조건** + * - ex: createdAt, desc + * - 각 api의 정렬 조건에 맞추어 진행 + */ + val sort: String?, +) { + fun toDefault(): Pageable { + val page = this.page ?: 0 + val size = this.size ?: 10 + val sort = this.sort.parsingSort() + + return PageRequest.of(page, size, sort) + } + + fun String?.parsingSort(): Sort { + val sortSpec = (this ?: "createdAt,desc").trim().split(",") + + if (sortSpec.size != 2) { + return Sort.by("createdAt").descending() + } + + val requestedSortField = Sort.Order.by(sortSpec[0].trim()) + val direction = Sort.Direction.fromString(sortSpec[1].trim()) + + return Sort.by(requestedSortField.with(direction)) + } +} diff --git a/src/main/kotlin/com/hero/alignlab/dto/ErrorResponse.kt b/src/main/kotlin/com/hero/alignlab/dto/ErrorResponse.kt new file mode 100644 index 0000000..cfd9fab --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/dto/ErrorResponse.kt @@ -0,0 +1,64 @@ +package com.hero.alignlab.dto + +import com.hero.alignlab.exception.ErrorCode +import jakarta.validation.ConstraintViolationException +import kotlinx.coroutines.CancellationException +import org.springframework.core.codec.DecodingException +import org.springframework.web.bind.support.WebExchangeBindException +import org.springframework.web.server.ServerWebInputException + +data class ErrorResponse( + val errorCode: String, + val reason: String, + val extra: Map? = null, +) { + companion object { + fun of(e: WebExchangeBindException): ErrorResponse { + return ErrorResponse( + errorCode = ErrorCode.BAD_REQUEST_ERROR.name, + reason = e.fieldErrors + .joinToString(" ") { error -> "[${error.field}] ${error.defaultMessage}." } + .ifBlank { "fail to validate" } + ) + } + + fun of(e: DecodingException): ErrorResponse { + val errorCode = ErrorCode.BAD_REQUEST_ERROR + return ErrorResponse( + errorCode = errorCode.name, + reason = e.message ?: errorCode.description + ) + } + + fun of(e: ConstraintViolationException): ErrorResponse { + return ErrorResponse( + errorCode = ErrorCode.BAD_REQUEST_ERROR.name, + reason = e.constraintViolations.firstOrNull()?.messageTemplate + ?: "fail to validate" + ) + } + + fun of(e: ServerWebInputException): ErrorResponse { + return ErrorResponse( + errorCode = ErrorCode.BAD_REQUEST_ERROR.name, + reason = e.reason ?: "fail to validate" + ) + } + + fun of(e: CancellationException): ErrorResponse { + val errorCode = ErrorCode.COROUTINE_CANCELLATION_ERROR + return ErrorResponse( + errorCode = errorCode.name, + reason = e.message ?: errorCode.description + ) + } + + fun of(e: Exception): ErrorResponse { + val errorCode = ErrorCode.INTERNAL_SERVER_ERROR + return ErrorResponse( + errorCode = errorCode.name, + reason = e.message ?: errorCode.description + ) + } + } +} diff --git a/src/main/kotlin/com/hero/alignlab/dto/PageResponseDto.kt b/src/main/kotlin/com/hero/alignlab/dto/PageResponseDto.kt new file mode 100644 index 0000000..8f6372e --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/dto/PageResponseDto.kt @@ -0,0 +1,22 @@ +package com.hero.alignlab.dto + +import org.springframework.data.domain.Page +import org.springframework.data.domain.Sort + +data class PageResponseDto( + val data: List, + val page: Int?, + val size: Int?, + val totalPage: Int, + val totalCount: Long, + val sort: Sort, +) { + constructor(page: Page) : this( + data = page.content, + page = page.pageable.pageNumber, + size = page.size, + totalPage = page.totalPages, + totalCount = page.totalElements, + sort = page.sort + ) +} diff --git a/src/main/kotlin/com/hero/alignlab/dto/SliceResponseDto.kt b/src/main/kotlin/com/hero/alignlab/dto/SliceResponseDto.kt new file mode 100644 index 0000000..23ca672 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/dto/SliceResponseDto.kt @@ -0,0 +1,20 @@ +package com.hero.alignlab.dto + +import org.springframework.data.domain.Slice +import org.springframework.data.domain.Sort + +data class SliceResponseDto( + val data: List, + val page: Int?, + val size: Int?, + val sort: Sort, + val hasNext: Boolean, +) { + constructor(slice: Slice) : this( + data = slice.content, + page = slice.pageable.pageNumber, + size = slice.size, + sort = slice.sort, + hasNext = slice.hasNext() + ) +} diff --git a/src/main/kotlin/com/hero/alignlab/exception/AlignlabException.kt b/src/main/kotlin/com/hero/alignlab/exception/AlignlabException.kt new file mode 100644 index 0000000..26c5132 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/exception/AlignlabException.kt @@ -0,0 +1,21 @@ +package com.hero.alignlab.exception + +open class AlignlabException( + val errorCode: ErrorCode, + override val message: String? = errorCode.description, + val extra: Map? = null, +) : RuntimeException(message ?: errorCode.description) + +class NotFoundException(errorCode: ErrorCode) : AlignlabException(errorCode) + +class InvalidTokenException(errorCode: ErrorCode) : AlignlabException(errorCode) + +class InvalidRequestException(errorCode: ErrorCode) : AlignlabException(errorCode) + +class FailToCreateException(errorCode: ErrorCode) : AlignlabException(errorCode) + +class AlreadyException(errorCode: ErrorCode) : AlignlabException(errorCode) + +class NoAuthorityException(errorCode: ErrorCode) : AlignlabException(errorCode) + +class FailToExecuteException(errorCode: ErrorCode) : AlignlabException(errorCode) diff --git a/src/main/kotlin/com/hero/alignlab/exception/ErrorCode.kt b/src/main/kotlin/com/hero/alignlab/exception/ErrorCode.kt new file mode 100644 index 0000000..2f59d1d --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/exception/ErrorCode.kt @@ -0,0 +1,21 @@ +package com.hero.alignlab.exception + +import org.springframework.http.HttpStatus + +enum class ErrorCode(val status: HttpStatus, val description: String) { + /** Common Error Code */ + BAD_REQUEST_ERROR(HttpStatus.BAD_REQUEST, "bad request"), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 오류, 관리자에게 문의하세요"), + INVALID_INPUT_VALUE_ERROR(HttpStatus.BAD_REQUEST, "input is invalid value"), + INVALID_TYPE_VALUE_ERROR(HttpStatus.BAD_REQUEST, "invalid type value"), + METHOD_NOT_ALLOWED_ERROR(HttpStatus.METHOD_NOT_ALLOWED, "Method type is invalid"), + INVALID_MEDIA_TYPE_ERROR(HttpStatus.BAD_REQUEST, "invalid media type"), + QUERY_DSL_NOT_EXISTS_ERROR(HttpStatus.NOT_FOUND, "not found query dsl"), + COROUTINE_CANCELLATION_ERROR(HttpStatus.BAD_REQUEST, "coroutine cancellation error"), + FAIL_TO_TRANSACTION_TEMPLATE_EXECUTE_ERROR(HttpStatus.BAD_REQUEST, "fail to tx-templates execute error"), + FAIL_TO_REDIS_EXECUTE_ERROR(HttpStatus.BAD_REQUEST, "fail to redis execute error"), + + /** short url */ + NOT_FOUND_SHORT_URL(HttpStatus.NOT_FOUND, "not found short url"), + ; +} diff --git a/src/main/kotlin/com/hero/alignlab/exception/advice/AlignlabExceptionHandler.kt b/src/main/kotlin/com/hero/alignlab/exception/advice/AlignlabExceptionHandler.kt new file mode 100644 index 0000000..9a00c2b --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/exception/advice/AlignlabExceptionHandler.kt @@ -0,0 +1,27 @@ +package com.hero.alignlab.exception.advice + +import com.hero.alignlab.dto.ErrorResponse +import com.hero.alignlab.exception.AlignlabException +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.core.Ordered +import org.springframework.core.annotation.Order +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.ExceptionHandler +import org.springframework.web.bind.annotation.RestControllerAdvice + +@RestControllerAdvice +@Order(Ordered.HIGHEST_PRECEDENCE) +class AlignlabExceptionHandler { + private val logger = KotlinLogging.logger { } + + @ExceptionHandler(AlignlabException::class) + protected fun handleAlignlabException(e: AlignlabException): ResponseEntity { + logger.warn { "AlignlabException ${e.message}" } + val response = ErrorResponse( + errorCode = e.errorCode.name, + reason = e.message ?: e.errorCode.description, + extra = e.extra + ) + return ResponseEntity(response, e.errorCode.status) + } +} diff --git a/src/main/kotlin/com/hero/alignlab/exception/advice/ExceptionHandler.kt b/src/main/kotlin/com/hero/alignlab/exception/advice/ExceptionHandler.kt new file mode 100644 index 0000000..788444f --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/exception/advice/ExceptionHandler.kt @@ -0,0 +1,109 @@ +package com.hero.alignlab.exception.advice + +import com.hero.alignlab.dto.ErrorResponse +import io.github.oshai.kotlinlogging.KotlinLogging +import jakarta.validation.ConstraintViolationException +import kotlinx.coroutines.CancellationException +import org.springframework.beans.TypeMismatchException +import org.springframework.core.codec.DecodingException +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.ExceptionHandler +import org.springframework.web.bind.annotation.RestControllerAdvice +import org.springframework.web.bind.support.WebExchangeBindException +import org.springframework.web.server.ServerWebExchange +import org.springframework.web.server.ServerWebInputException + +@RestControllerAdvice +class ExceptionHandler { + private val logger = KotlinLogging.logger { } + + @ExceptionHandler(WebExchangeBindException::class) + protected fun handleWebExchangeBindException( + e: WebExchangeBindException, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "WebExchangeBindException ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } + + @ExceptionHandler(DecodingException::class) + protected fun handleDecodingException( + e: DecodingException, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "DecodingException ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } + + @ExceptionHandler(ConstraintViolationException::class) + protected fun handleConstraintViolationException( + e: ConstraintViolationException, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "ConstraintViolationException ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } + + @ExceptionHandler(ServerWebInputException::class) + protected fun handleServerWebInputException( + e: ServerWebInputException, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "ServerWebInputException ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } + + @ExceptionHandler(TypeMismatchException::class) + protected fun handleTypeMismatchException( + e: TypeMismatchException, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "TypeMismatchException ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } + + /** + * Coroutines Cancellation + * - [Kotlin Docs](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.cancellation/) + */ + @ExceptionHandler(CancellationException::class) + protected fun handleCancellationException( + e: CancellationException, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "CancellationException ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } + + @ExceptionHandler(Exception::class) + protected fun handleException( + e: Exception, + exchange: ServerWebExchange, + ): ResponseEntity { + logger.warn { "Exception ${e.message}, requestUri=${exchange.request.uri}" } + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .contentType(MediaType.APPLICATION_JSON) + .body(ErrorResponse.of(e)) + } +} diff --git a/src/main/kotlin/com/hero/alignlab/extension/DateExtension.kt b/src/main/kotlin/com/hero/alignlab/extension/DateExtension.kt new file mode 100644 index 0000000..54965c2 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/extension/DateExtension.kt @@ -0,0 +1,42 @@ +package com.hero.alignlab.extension + +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter + +object Zone { + val KST: ZoneId = ZoneId.of("Asia/Seoul") + val UTC: ZoneId = ZoneId.of("UTC") +} + +fun LocalDateTime.toInstant(): Instant { + return this.toInstant(ZoneOffset.of("+09:00")) +} + +fun LocalDateTime.equalsFromYearToSec(otherTime: LocalDateTime): Boolean { + return this.year == otherTime.year && + this.month == otherTime.month && + this.dayOfMonth == otherTime.dayOfMonth && + this.hour == otherTime.hour && + this.minute == otherTime.minute && + this.second == otherTime.second +} + +fun LocalDateTime.format(format: String): String { + val formatter = DateTimeFormatter.ofPattern(format) + return this.format(formatter) +} + +fun LocalDate.yearMonth(): String { + val year = this.year + val month = if (this.monthValue >= 10) { + this.monthValue + } else { + "0${this.monthValue}" + } + + return "$year$month" +} diff --git a/src/main/kotlin/com/hero/alignlab/extension/JsonExtension.kt b/src/main/kotlin/com/hero/alignlab/extension/JsonExtension.kt new file mode 100644 index 0000000..4f53f03 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/extension/JsonExtension.kt @@ -0,0 +1,40 @@ +package com.hero.alignlab.extension + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule +import com.fasterxml.jackson.module.kotlin.KotlinFeature +import com.fasterxml.jackson.module.kotlin.KotlinModule +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef + +val mapper: ObjectMapper = jacksonObjectMapper() + .setSerializationInclusion(JsonInclude.Include.NON_NULL) + .registerModule(JavaTimeModule()) + .registerModule( + KotlinModule.Builder() + .withReflectionCacheSize(512) + .configure(KotlinFeature.NullToEmptyCollection, false) + .configure(KotlinFeature.NullToEmptyMap, false) + .configure(KotlinFeature.NullIsSameAsDefault, false) + .configure(KotlinFeature.SingletonSupport, false) + .configure(KotlinFeature.StrictNullChecks, false) + .build() + ) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + +val includeNullMapper: ObjectMapper = jacksonObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .registerModule(JavaTimeModule()) + +fun R.toJson(): String = mapper.writeValueAsString(this) + +fun R.toJsonWithNull(): String = includeNullMapper.writeValueAsString(this) + +inline fun String.readJson(typeRef: TypeReference = jacksonTypeRef()): R { + return mapper.readValue(this, typeRef) +} diff --git a/src/main/kotlin/com/hero/alignlab/extension/LoggerExtension.kt b/src/main/kotlin/com/hero/alignlab/extension/LoggerExtension.kt new file mode 100644 index 0000000..d7d85a1 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/extension/LoggerExtension.kt @@ -0,0 +1,13 @@ +package com.hero.alignlab.extension + +import io.github.oshai.kotlinlogging.KLogger +import kotlinx.coroutines.CancellationException + +fun KLogger.resolveCancellation(name: String, throwable: Throwable, other: (KLogger.() -> Unit)? = null) { + when (throwable) { + is CancellationException -> debug { "[$name] Job was cancelled." } + else -> { + other?.let { it() } ?: error(throwable) { "$name Job Error ${throwable.message}" } + } + } +} diff --git a/src/main/kotlin/com/hero/alignlab/extension/ResponseExtension.kt b/src/main/kotlin/com/hero/alignlab/extension/ResponseExtension.kt new file mode 100644 index 0000000..63edaca --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/extension/ResponseExtension.kt @@ -0,0 +1,26 @@ +package com.hero.alignlab.extension + +import com.hero.alignlab.dto.PageResponseDto +import org.springframework.data.domain.Page +import org.springframework.http.HttpHeaders +import org.springframework.http.HttpStatus +import org.springframework.http.ResponseEntity +import java.net.URI + +/** Wrap Response Page */ +fun Page.wrapPage() = PageResponseDto(this) + +/** Wrap Response Ok */ +fun T.wrapOk() = ResponseEntity.ok(this) + +/** Wrap Response Created */ +fun T.wrapCreated() = ResponseEntity.status(HttpStatus.CREATED).body(this) + +/** Wrap Response Void */ +fun Unit.wrapVoid() = ResponseEntity.noContent().build() + +fun String.wrapRedirected(): ResponseEntity { + val headers = HttpHeaders() + headers.location = URI.create(this) + return ResponseEntity(headers, HttpStatus.PERMANENT_REDIRECT) +} diff --git a/src/main/kotlin/com/hero/alignlab/extension/ServerHttpExtension.kt b/src/main/kotlin/com/hero/alignlab/extension/ServerHttpExtension.kt new file mode 100644 index 0000000..f8a53e6 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/extension/ServerHttpExtension.kt @@ -0,0 +1,10 @@ +package com.hero.alignlab.extension + +import org.springframework.http.server.reactive.ServerHttpRequest + +val ServerHttpRequest.remoteIp + get() = headers.getFirst("X-Forwarded-For") + ?.split(",") + ?.firstOrNull()?.trim() + ?: this.remoteAddress?.address?.hostAddress + ?: "" diff --git a/src/main/kotlin/com/hero/alignlab/extension/TransactionTemplateExtension.kt b/src/main/kotlin/com/hero/alignlab/extension/TransactionTemplateExtension.kt new file mode 100644 index 0000000..e133210 --- /dev/null +++ b/src/main/kotlin/com/hero/alignlab/extension/TransactionTemplateExtension.kt @@ -0,0 +1,28 @@ +package com.hero.alignlab.extension + +import com.hero.alignlab.exception.ErrorCode +import com.hero.alignlab.exception.FailToExecuteException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.springframework.transaction.support.TransactionCallback +import org.springframework.transaction.support.TransactionTemplate + +suspend fun TransactionTemplate.coExecute( + actions: TransactionCallback, +): RETURN { + val transactionTemplate: TransactionTemplate = this + + return withContext(Dispatchers.IO) { + transactionTemplate.execute(actions) + } ?: throw FailToExecuteException(ErrorCode.FAIL_TO_TRANSACTION_TEMPLATE_EXECUTE_ERROR) +} + +suspend fun TransactionTemplate.coExecuteOrNull( + actions: TransactionCallback, +): RETURN? { + val transactionTemplate: TransactionTemplate = this + + return withContext(Dispatchers.IO) { + transactionTemplate.execute(actions) + } +} diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml new file mode 100644 index 0000000..ceff65a --- /dev/null +++ b/src/main/resources/config/application-dev.yml @@ -0,0 +1,52 @@ +# =================================================================== +# Spring Boot Configuration for the dev profile +# =================================================================== + +# SERVER +server: + error: + include-exception: true # Include the "exception" attribute. + include-stacktrace: always # When to include a "stacktrace" attribute. + whitelabel.enabled: true + +# LOGGING +logging: + level: + root: INFO + com.alignlab: DEBUG + org.hibernate.SQL: DEBUG + org.hibernate.type.descriptor.sql.BasicBinder: TRACE + org.springframework.jdbc.core.JdbcTemplate: DEBUG + org.springframework.jdbc.core.StatementCreatorUtils: TRACE + org.springframework.orm.jpa.JpaTransactionManager: DEBUG + org.springframework.web.server.adapter.HttpWebHandlerAdapter: DEBUG + reactor.netty.http.client: DEBUG + +# SPRING +spring: + jackson: + serialization: + indent_output: true + write-null-map-values: true + data: + redis: + host: localhost + port: 6379 + +# DEV-DATABASE-COMMON +datasource: &dev-datasource + url: jdbc:mysql://localhost:3306/hero?useUnicode=true&charset=utf8mb4&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull + username: root + password: + hikari: + minimum-idle: 2 + maximum-pool-size: 2 + +# DATABASE +hero: + master.datasource: *dev-datasource + jpa: + properties: + hibernate.format_sql: true + hibernate.hbm2ddl.auto: none + maximum-jdbc-thread-pool-size: diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml new file mode 100644 index 0000000..d232b92 --- /dev/null +++ b/src/main/resources/config/application.yml @@ -0,0 +1,46 @@ +# =================================================================== +# Spring Boot Configuration for the default profile +# =================================================================== + +# SERVER +server: + port: 8080 + http2: + enabled: true + shutdown: graceful # timeout configuration property : spring.lifecycle.timeout-per-shutdown-phase + +logging: + level: + root: INFO + +# SPRING +spring: + lifecycle: + timeout-per-shutdown-phase: 5s # format : https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-conversion-duration + application: + name: hero-alignlab-api + data: + redis: + repositories: + enabled: false + + +# DATABASE +hero: + master: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + properties: + hibernate.default_batch_fetch_size: 10 + hibernate.cache.use_second_level_cache: false + hibernate.cache.use_query_cache: false + hibernate.order_inserts: true + hibernate.order_updates: true + hibrenate.jdbc.batch_size: 50 + hibernate.jdbc.batch_versioned_data: true + hibernate.jdbc.time_zone: Asia/Seoul + hibernate.hbm2ddl.auto: none + show-sql: false + database: mysql + database-platform: org.hibernate.dialect.MySQLDialect diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..fcfaa74 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,24 @@ + + + + + + + + true + + + + + + + + + + + + + + + + diff --git a/src/test/kotlin/com/hero/alignlab/ApplicationTests.kt b/src/test/kotlin/com/hero/alignlab/ApplicationTests.kt new file mode 100644 index 0000000..b58feb5 --- /dev/null +++ b/src/test/kotlin/com/hero/alignlab/ApplicationTests.kt @@ -0,0 +1,11 @@ +package com.hero.alignlab + +import org.junit.jupiter.api.Test +import org.springframework.boot.test.context.SpringBootTest + +@SpringBootTest +class ApplicationTests { + @Test + fun contextLoads() { + } +}