diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..4a12278f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +charset=utf-8 +end_of_line=lf +indent_style=space +indent_size=4 +insert_final_newline=true +disabled_rules=no-wildcard-imports,import-ordering,comment-spacing + +[*.{kt,kts}] +insert_final_newline=false +# enable trailing_comma +ij_kotlin_allow_trailing_comma=true \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..ae963a96 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +🎫 연관 티켓 +--- +#연관티켓이슈번호 + +🙏 작업 +---- +- 작업1 +- 작업2 + +💁‍♂️ 어떻게? +---- +- 작업1 어떻게? +- 작업2 어떻게? + +🙈 PR 참고 사항 +---- +- 질문? +- 추가 티켓 + +📸 스크린샷 +---- + +🤖 테스트 체크리스트 +---- +- [ ] 체크 미완료 +- [x] 체크 완료 diff --git a/.github/workflows/ecs_cd.yaml b/.github/workflows/ecs_cd.yaml new file mode 100644 index 00000000..cadefc5c --- /dev/null +++ b/.github/workflows/ecs_cd.yaml @@ -0,0 +1,80 @@ +name: DEV - Deploy to Amazon ECS + +on: + push: + branches: + - main + - traffic + workflow_dispatch: +env: + AWS_REGION: ap-northeast-2 + ECR_REPOSITORY: tf-ecr + ECS_SERVICE: tf-ecs-service + ECS_CLUSTER: tf-ecs-cluster + ECS_TASK_DEFINITION: task-definition.json + TASK_DEFINITION_NAME: tf-ecs-task + CONTAINER_NAME: tf-container + +jobs: + build-and-push-docker-image: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + cache: gradle + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v1 + with: + aws-access-key-id: ${{ secrets.DEV_AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.DEV_AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: Login to Amazon ECR + id: login-ecr + uses: aws-actions/amazon-ecr-login@v1 + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Build with Gradle bootBuildImage, tag, and push image to Amazon ECR + env: + ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} + run: | + GIT_HASH=$(git rev-parse --short HEAD) + ./gradlew buildDockerImage -PimageName=${ECR_REGISTRY}/${ECR_REPOSITORY}:latest + docker tag ${ECR_REGISTRY}/${ECR_REPOSITORY}:latest ${ECR_REGISTRY}/${ECR_REPOSITORY}:${GIT_HASH} + docker push ${ECR_REGISTRY}/${ECR_REPOSITORY} --all-tags + - name: Get ECR Repository image path + id: get-docker-image-path + env: + ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} + run: | + GIT_HASH=$(git rev-parse --short HEAD) + echo ${ECR_REGISTRY}/${ECR_REPOSITORY}:${GIT_HASH} + echo "::set-output name=image::${ECR_REGISTRY}/${ECR_REPOSITORY}:${GIT_HASH}" + - name: Download task definition + run: | + aws ecs describe-task-definition --task-definition ${TASK_DEFINITION_NAME} --query taskDefinition > task-definition.json + - name: Fill in the new image ID in the Amazon ECS task definition + id: task-definition + uses: aws-actions/amazon-ecs-render-task-definition@v1 + with: + task-definition: ${{ env.ECS_TASK_DEFINITION }} + container-name: ${{ env.CONTAINER_NAME }} + image: ${{ steps.get-docker-image-path.outputs.image }} + + - name: Deploy Amazon ECS task definition + id: ecs-deployment + uses: aws-actions/amazon-ecs-deploy-task-definition@v1 + with: + task-definition: ${{ steps.task-definition.outputs.task-definition }} + service: ${{ env.ECS_SERVICE }} + cluster: ${{ env.ECS_CLUSTER }} + wait-for-service-stability: true diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..753dcf1a --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,21 @@ +name: lint + +on: + pull_request: + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Test with Spotless + run: ./gradlew --info spotlessJavaCheck \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..5a979af6 --- /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/Dockerfile b/Dockerfile new file mode 100644 index 00000000..9a2a4588 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM openjdk:18-oracle + +RUN mkdir -p /logs + +ENV PROFILE default +ENV TZ=Asia/Seoul +EXPOSE 8080 + +ARG JAVA_OPTS + +ARG RELEASE_VERSION +ENV DD_VERSION=${RELEASE_VERSION} + +ARG JAR_FILE="build/libs/walking-traffic-0.0.1-SNAPSHOT.jar" +COPY ${JAR_FILE} app.jar + +ENTRYPOINT java -XX:MaxGCPauseMillis=100 -XX:InitialRAMPercentage=50.0 -XX:MaxRAMPercentage=80.0 -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 $JAVA_OPTS -jar app.jar diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..92828434 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,116 @@ +import java.util.* + +plugins { + id("org.springframework.boot") version "3.1.5" + id("io.spring.dependency-management") version "1.1.6" + + kotlin("jvm") version "1.9.25" + kotlin("plugin.spring") version "1.9.25" + kotlin("plugin.jpa") version "1.9.25" + kotlin("plugin.allopen") version "1.9.25" + kotlin("kapt") version "1.9.25" + idea + + id("org.jlleitschuh.gradle.ktlint") version "11.6.1" +} + +group = "com.walking" +version = "0.0.1-SNAPSHOT" + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +/** + * 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("javax.persistence.Entity") + annotation("javax.persistence.Embeddable") + annotation("javax.persistence.MappedSuperclass") +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-data-jpa") + implementation("org.springframework.boot:spring-boot-starter-validation") + implementation("org.springframework.boot:spring-boot-starter-actuator") + implementation("org.springframework.boot:spring-boot-starter-batch") + implementation("org.springframework.boot:spring-boot-starter-quartz") + + implementation("com.mysql:mysql-connector-j") + implementation("org.hibernate:hibernate-spatial:6.6.0.Final") + + implementation("org.quartz-scheduler:quartz") + + implementation("org.apache.httpcomponents.client5:httpclient5") + + implementation("org.jetbrains.kotlin:kotlin-reflect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-slf4j") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") + implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") + + implementation("com.fasterxml.jackson.core:jackson-databind") + implementation("com.fasterxml.jackson.core:jackson-core") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("com.fasterxml.jackson.module:jackson-module-parameter-names") + + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +kotlin { + compilerOptions { + freeCompilerArgs.addAll("-Xjsr305=strict") + } +} + +tasks.withType { + useJUnitPlatform() +} + +val imageName = project.hasProperty("imageName").let { + if (it) { + project.property("imageName") as String + } else { + "app:local" + } +} +val releaseVersion = project.hasProperty("releaseVersion").let { + if (it) { + project.property("releaseVersion") as String + } else { + Random().nextInt(90000) + 10000 + } +} + +tasks.register("buildDockerImage") { + dependsOn("bootJar") + + doLast { + exec { + workingDir(".") + commandLine( + "docker", + "build", + "-t", + imageName, + "--build-arg", + "RELEASE_VERSION=$releaseVersion", + '.' + ) + } + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..e6441136 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 00000000..a4413138 --- /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.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..b740cf13 --- /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 00000000..25da30db --- /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/resources/local-develop-environment/docker-compose.yml b/resources/local-develop-environment/docker-compose.yml new file mode 100644 index 00000000..db08823c --- /dev/null +++ b/resources/local-develop-environment/docker-compose.yml @@ -0,0 +1,26 @@ +version: '3.1' +services: + walking-mysql: + container_name: walking-mysql8 + image: mysql/mysql-server:8.0.27 + environment: + - MYSQL_ROOT_PASSWORD=root + - MYSQL_ROOT_HOST=% + - TZ=Asia/Seoul + command: [ "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci", "--lower_case_table_names=1", "--max_connections=2048", "--wait_timeout=3600" ] + ports: + - "13306:3306" + volumes: + - ./mysql-init.d:/docker-entrypoint-initdb.d + - ./sql:/bin/sql + - ../data:/var/lib/mysql-files + + walking-adminer: # mysql web admin + container_name: walking-adminer + image: adminer:4 + ports: + - "18080:8080" + environment: + - ADMINER_DEFAULT_SERVER=walking-mysql8 + - ADMINER_DESIGN=nette + - ADMINER_PLUGINS=tables-filter tinymce \ No newline at end of file diff --git a/resources/local-develop-environment/mysql-init.d/00_init.sql b/resources/local-develop-environment/mysql-init.d/00_init.sql new file mode 100644 index 00000000..7c2e5e39 --- /dev/null +++ b/resources/local-develop-environment/mysql-init.d/00_init.sql @@ -0,0 +1,12 @@ +CREATE + USER 'walking-local'@'localhost' IDENTIFIED BY 'walking-local'; +CREATE + USER 'walking-local'@'%' IDENTIFIED BY 'walking-local'; + +GRANT ALL PRIVILEGES ON *.* TO + 'walking-local'@'localhost'; +GRANT ALL PRIVILEGES ON *.* TO + 'walking-local'@'%'; + +CREATE + DATABASE api DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; \ No newline at end of file diff --git a/scripts/local-develop-setting b/scripts/local-develop-setting new file mode 100755 index 00000000..2de46fea --- /dev/null +++ b/scripts/local-develop-setting @@ -0,0 +1,6 @@ +#!/bin/sh + +cd ../resources/local-develop-environment +docker-compose down +docker-compose up -d +sleep 10 \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..f524b913 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "walking-traffic" \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/WalkingTrafficApplication.kt b/src/main/kotlin/com/walking/traffic/WalkingTrafficApplication.kt new file mode 100644 index 00000000..af2cb8f1 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/WalkingTrafficApplication.kt @@ -0,0 +1,11 @@ +package com.walking.traffic + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class WalkingTrafficApplication + +fun main(args: Array) { + runApplication(*args) +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/client/property/seoul/SeoulColorRequest.kt b/src/main/kotlin/com/walking/traffic/batch/client/property/seoul/SeoulColorRequest.kt new file mode 100644 index 00000000..06c6d0a6 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/client/property/seoul/SeoulColorRequest.kt @@ -0,0 +1,16 @@ +package com.walking.traffic.batch.client.property.seoul + +import org.springframework.beans.factory.annotation.Value +import org.springframework.stereotype.Component +import java.net.URL + +@Component +class SeoulColorRequest( + @Value("\${api.seoul.apiKey}") val apiKey: String, + @Value("\${api.seoul.baseUrl}") private val baseUrl: String, + @Value("\${api.seoul.colorPath}") private val trafficColorPath: String, +) { + fun getUrl(): URL { + return URL("$baseUrl$trafficColorPath") + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/client/property/seoul/SeoulLeftTimeRequest.kt b/src/main/kotlin/com/walking/traffic/batch/client/property/seoul/SeoulLeftTimeRequest.kt new file mode 100644 index 00000000..e67fd56b --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/client/property/seoul/SeoulLeftTimeRequest.kt @@ -0,0 +1,16 @@ +package com.walking.traffic.batch.client.property.seoul + +import org.springframework.beans.factory.annotation.Value +import org.springframework.stereotype.Component +import java.net.URL + +@Component +class SeoulLeftTimeRequest( + @Value("\${api.seoul.apiKey}") val apiKey: String, + @Value("\${api.seoul.baseUrl}") private val baseUrl: String, + @Value("\${api.seoul.leftTimePath}") private val trafficLeftTimePath: String, +) { + fun getUrl(): URL { + return URL("$baseUrl$trafficLeftTimePath") + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/SeoulColorClient.kt b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/SeoulColorClient.kt new file mode 100644 index 00000000..096b5c7c --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/SeoulColorClient.kt @@ -0,0 +1,28 @@ +package com.walking.traffic.batch.client.service.seoul + +import com.walking.traffic.batch.client.property.seoul.SeoulColorRequest +import com.walking.traffic.batch.client.service.seoul.dto.SeoulTrafficColorObject +import org.springframework.stereotype.Component +import org.springframework.util.LinkedMultiValueMap +import org.springframework.util.MultiValueMap +import org.springframework.web.client.RestTemplate +import org.springframework.web.util.UriComponentsBuilder +import java.util.* + +@Component +class SeoulColorClient( + private val restTemplate: RestTemplate, + private val colorRequestProperty: SeoulColorRequest, +) { + fun execute(): List { + val parameters: MultiValueMap = LinkedMultiValueMap() + parameters["apiKey"] = colorRequestProperty.apiKey + return restTemplate.getForObject( + UriComponentsBuilder.fromUriString(colorRequestProperty.getUrl().toString()) + .queryParams(parameters) + .build() + .toUri(), + Array::class.java + )!!.toList() + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/SeoulLeftTimeClient.kt b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/SeoulLeftTimeClient.kt new file mode 100644 index 00000000..32b72b74 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/SeoulLeftTimeClient.kt @@ -0,0 +1,29 @@ +package com.walking.traffic.batch.client.service.seoul + +import com.walking.traffic.batch.client.property.seoul.SeoulLeftTimeRequest +import com.walking.traffic.batch.client.service.seoul.dto.SeoulTrafficLeftTimeObject +import org.springframework.stereotype.Component +import org.springframework.util.LinkedMultiValueMap +import org.springframework.util.MultiValueMap +import org.springframework.web.client.RestTemplate +import org.springframework.web.util.UriComponentsBuilder +import java.util.* + +@Component +class SeoulLeftTimeClient( + private val restTemplate: RestTemplate, + private val leftTimeRequestProperty: SeoulLeftTimeRequest, +) { + + fun execute(): List { + val parameters: MultiValueMap = LinkedMultiValueMap() + parameters["apiKey"] = leftTimeRequestProperty.apiKey + return restTemplate.getForObject( + UriComponentsBuilder.fromUriString(leftTimeRequestProperty.getUrl().toString()) + .queryParams(parameters) + .build() + .toUri(), + Array::class.java + )!!.toList() + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/dto/SeoulTrafficColorObject.kt b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/dto/SeoulTrafficColorObject.kt new file mode 100644 index 00000000..177384bc --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/dto/SeoulTrafficColorObject.kt @@ -0,0 +1,18 @@ +package com.walking.traffic.batch.client.service.seoul.dto + +import com.fasterxml.jackson.annotation.JsonFormat +import java.time.LocalDateTime + +data class SeoulTrafficColorObject( + val itstId: Long, + val ntPdsgStatNm: String?, + val etPdsgStatNm: String?, + val stPdsgStatNm: String?, + val wtPdsgStatNm: String?, + val nePdsgStatNm: String?, + val sePdsgStatNm: String?, + val swPdsgStatNm: String?, + val nwPdsgStatNm: String?, + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") + val regDt: LocalDateTime, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/dto/SeoulTrafficLeftTimeObject.kt b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/dto/SeoulTrafficLeftTimeObject.kt new file mode 100644 index 00000000..78f2013c --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/client/service/seoul/dto/SeoulTrafficLeftTimeObject.kt @@ -0,0 +1,18 @@ +package com.walking.traffic.batch.client.service.seoul.dto + +import com.fasterxml.jackson.annotation.JsonFormat +import java.time.LocalDateTime + +data class SeoulTrafficLeftTimeObject( + val itstId: Long, + val ntPdsgRmdrCs: Double?, + val etPdsgRmdrCs: Double?, + val stPdsgRmdrCs: Double?, + val wtPdsgRmdrCs: Double?, + val nePdsgRmdrCs: Double?, + val sePdsgRmdrCs: Double?, + val swPdsgRmdrCs: Double?, + val nwPdsgRmdrCs: Double?, + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") + val regDt: LocalDateTime, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/config/BatchConfig.kt b/src/main/kotlin/com/walking/traffic/batch/config/BatchConfig.kt new file mode 100644 index 00000000..7178208c --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/config/BatchConfig.kt @@ -0,0 +1,26 @@ +package com.walking.traffic.batch.config + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing +import org.springframework.boot.autoconfigure.batch.BatchDataSourceScriptDatabaseInitializer +import org.springframework.boot.autoconfigure.batch.BatchProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.scheduling.annotation.EnableScheduling +import javax.sql.DataSource + +@EnableScheduling +@Configuration +@EnableBatchProcessing +class BatchConfig { + @Bean + fun batchProperties(): BatchProperties { + return BatchProperties() + } + + @Bean + fun batchDataSourceInitializer( + dataSource: DataSource, properties: BatchProperties, + ): BatchDataSourceScriptDatabaseInitializer { + return BatchDataSourceScriptDatabaseInitializer(dataSource, properties.jdbc) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeChunk.kt b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeChunk.kt new file mode 100644 index 00000000..45f1aecf --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeChunk.kt @@ -0,0 +1,12 @@ +package com.walking.traffic.batch.job.seoul + +import java.time.LocalDateTime + +data class SeoulLeftTimeChunk( + val itstId: Long, + val direction: String, + val color: String, + val leftTime: Double, + val colorRegDt: LocalDateTime, + val leftTimeRegDt: LocalDateTime, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeItemReader.kt b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeItemReader.kt new file mode 100644 index 00000000..298e1fb0 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeItemReader.kt @@ -0,0 +1,211 @@ +package com.walking.traffic.batch.job.seoul + +import com.walking.traffic.batch.client.service.seoul.SeoulColorClient +import com.walking.traffic.batch.client.service.seoul.SeoulLeftTimeClient +import com.walking.traffic.batch.client.service.seoul.dto.SeoulTrafficColorObject +import com.walking.traffic.batch.client.service.seoul.dto.SeoulTrafficLeftTimeObject +import org.springframework.batch.item.ItemReader +import java.time.LocalDateTime +import java.util.* + +private fun String.toColor(): String { + return when (this) { + "stop-And-Remain" -> "RED" + "protected-Movement-Allowed", "permissive-Movement-Allowed", "permissive-clearance" -> "GREEN" + "dark", "protected-clearance" -> "DARK" + else -> "UNKNOWN" + } +} + +class SeoulLeftTimeItemReader( + private val seoulLeftTimeClient: SeoulLeftTimeClient, + private val seoulColorClient: SeoulColorClient, +) : ItemReader { + + private var iterator: Iterator? = null + + override fun read(): SeoulLeftTimeChunk? { + if (Objects.isNull(iterator)) { + val leftTimeResponses: Iterable = + seoulLeftTimeClient.execute() + val leftTimeResponseMap: MutableMap = + HashMap() + + for (leftTimeResponse in leftTimeResponses) { + val seoulCarTrafficLeftTime = leftTimeResponseMap[leftTimeResponse.itstId] + seoulCarTrafficLeftTime?.regDt?.let { + if (it.isBefore(leftTimeResponse.regDt)) { + leftTimeResponseMap[leftTimeResponse.itstId] = leftTimeResponse + } + } ?: run { + leftTimeResponseMap[leftTimeResponse.itstId] = leftTimeResponse + } + } + + val colorResponses: Iterable = seoulColorClient.execute() + val colorResponseMap: MutableMap = + HashMap() + for (colorResponse in colorResponses) { + val seoulCarTrafficColor = colorResponseMap[colorResponse.itstId] + seoulCarTrafficColor?.regDt?.let { + if (it.isBefore(colorResponse.regDt)) { + colorResponseMap[colorResponse.itstId] = colorResponse + } + } ?: run { + colorResponseMap[colorResponse.itstId] = colorResponse + } + } + + val certificationIds = + if (colorResponseMap.size < leftTimeResponseMap.size) colorResponseMap.keys else leftTimeResponseMap.keys + val seoulTrafficDetails: MutableList = ArrayList() + for (certificationId in certificationIds) { + if (colorResponseMap.containsKey(certificationId) && leftTimeResponseMap.containsKey(certificationId)) { + generateActiveDetails(certificationId, colorResponseMap, leftTimeResponseMap).let { + seoulTrafficDetails.addAll(it) + } + } + } + iterator = seoulTrafficDetails.iterator() + } + + return if (iterator!!.hasNext()) { + iterator!!.next() + } else { + iterator = null + null + } + } + private fun generateActiveDetails( + certificationId: Long, + colorResponseMap: Map, + leftTimeResponseMap: Map, + ): List { + val details: MutableList = ArrayList() + val seoulCarTrafficColor = colorResponseMap[certificationId] + val seoulCarTrafficLeftTime = leftTimeResponseMap[certificationId] + + if (seoulCarTrafficColor?.ntPdsgStatNm != null && seoulCarTrafficLeftTime?.ntPdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "nt", + seoulCarTrafficColor.ntPdsgStatNm, + seoulCarTrafficLeftTime.ntPdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.etPdsgStatNm != null && seoulCarTrafficLeftTime?.etPdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "et", + seoulCarTrafficColor.etPdsgStatNm, + seoulCarTrafficLeftTime.etPdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.stPdsgStatNm != null && seoulCarTrafficLeftTime?.stPdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "st", + seoulCarTrafficColor.stPdsgStatNm, + seoulCarTrafficLeftTime.stPdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.wtPdsgStatNm != null && seoulCarTrafficLeftTime?.wtPdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "wt", + seoulCarTrafficColor.wtPdsgStatNm, + seoulCarTrafficLeftTime.wtPdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.nePdsgStatNm != null && seoulCarTrafficLeftTime?.nePdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "ne", + seoulCarTrafficColor.nePdsgStatNm, + seoulCarTrafficLeftTime.nePdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.sePdsgStatNm != null && seoulCarTrafficLeftTime?.sePdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "se", + seoulCarTrafficColor.sePdsgStatNm, + seoulCarTrafficLeftTime.sePdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.swPdsgStatNm != null && seoulCarTrafficLeftTime?.swPdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "sw", + seoulCarTrafficColor.swPdsgStatNm, + seoulCarTrafficLeftTime.swPdsgRmdrCs, + details + ) + } + + if (seoulCarTrafficColor?.nwPdsgStatNm != null && seoulCarTrafficLeftTime?.nwPdsgRmdrCs != null) { + doGenerateActiveTrafficDetail( + certificationId, + colorResponseMap[certificationId]!!.regDt, + leftTimeResponseMap[certificationId]!!.regDt, + "nw", + seoulCarTrafficColor.nwPdsgStatNm, + seoulCarTrafficLeftTime.nwPdsgRmdrCs, + details + ) + } + + return details + } + + private fun doGenerateActiveTrafficDetail( + itstId: Long, + colorRegDt: LocalDateTime, + leftTimeRegDt: LocalDateTime, + direction: String, + pdsgStatNm: String?, + pdsgRmdrCs: Double?, + detials: MutableList, + ) { + if (pdsgStatNm == null || pdsgRmdrCs == null) { + null + } else { + SeoulLeftTimeChunk( + itstId, + direction, + pdsgStatNm.toColor(), + pdsgRmdrCs, + colorRegDt, + leftTimeRegDt + ) + }?.let { + detials.add(it) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeItemWriter.kt b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeItemWriter.kt new file mode 100644 index 00000000..a6ba0044 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeItemWriter.kt @@ -0,0 +1,35 @@ +package com.walking.traffic.batch.job.seoul + +import org.springframework.batch.item.Chunk +import org.springframework.batch.item.ItemWriter +import org.springframework.jdbc.core.JdbcTemplate +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate +import org.springframework.transaction.PlatformTransactionManager +import org.springframework.transaction.support.DefaultTransactionDefinition + +class SeoulLeftTimeItemWriter(jdbcTemplate: JdbcTemplate, private val txm: PlatformTransactionManager) : + ItemWriter { + private val jdbcTemplate = NamedParameterJdbcTemplate(jdbcTemplate) + + override fun write(chunk: Chunk) { + val transactionDef = DefaultTransactionDefinition() + val status = txm.getTransaction(transactionDef) + + val bulkInsertParams = chunk.map { item -> + MapSqlParameterSource() + .addValue("itst_id", item.itstId) + .addValue("direction", item.direction) + .addValue("color", item.color) + .addValue("left_time", item.leftTime) + .addValue("reg_dt", item.leftTimeRegDt) + } + val sql = """ + INSERT INTO api.seoul_left_time(itst_id, direction, color, left_time, reg_dt, deleted) + VALUES (:itst_id, :direction, :color, :left_time, :reg_dt, false) + """.trimIndent() + jdbcTemplate.batchUpdate(sql, bulkInsertParams.toTypedArray()) + + txm.commit(status) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeJobConfig.kt b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeJobConfig.kt new file mode 100644 index 00000000..a36bade5 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/job/seoul/SeoulLeftTimeJobConfig.kt @@ -0,0 +1,55 @@ +package com.walking.traffic.batch.job.seoul + +import com.walking.traffic.batch.client.service.seoul.SeoulColorClient +import com.walking.traffic.batch.client.service.seoul.SeoulLeftTimeClient +import org.springframework.batch.core.Job +import org.springframework.batch.core.Step +import org.springframework.batch.core.job.builder.JobBuilder +import org.springframework.batch.core.launch.support.RunIdIncrementer +import org.springframework.batch.core.repository.JobRepository +import org.springframework.batch.core.step.builder.StepBuilder +import org.springframework.batch.item.ItemReader +import org.springframework.batch.item.ItemWriter +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.jdbc.core.JdbcTemplate +import org.springframework.transaction.PlatformTransactionManager + +@Configuration +class SeoulLeftTimeJobConfig( + @Value("\${spring.batch.chunk.size}") val chunkSize: Int, + private val jobRepository: JobRepository, + private val txm: PlatformTransactionManager, + private val jdbcTemplate: JdbcTemplate, + private val leftTimeClient: SeoulLeftTimeClient, + private val colorClient: SeoulColorClient, +) { + + @Bean + fun trafficDetailJob(): Job { + return JobBuilder("seoulLeftTimeJob", jobRepository) + .incrementer(RunIdIncrementer()) + .start(trafficDetailStep()) + .build() + } + + @Bean + fun trafficDetailStep(): Step { + return StepBuilder("seoulLeftTimeStep", jobRepository) + .chunk(chunkSize, txm) + .reader(trafficDetailItemReader()) + .writer(trafficDetailItemWriter()) + .build() + } + + @Bean + fun trafficDetailItemReader(): ItemReader { + return SeoulLeftTimeItemReader(leftTimeClient, colorClient) + } + + @Bean + fun trafficDetailItemWriter(): ItemWriter { + return SeoulLeftTimeItemWriter(jdbcTemplate, txm) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/scheduler/SeoulLeftTimeJob.kt b/src/main/kotlin/com/walking/traffic/batch/scheduler/SeoulLeftTimeJob.kt new file mode 100644 index 00000000..c29c35a1 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/scheduler/SeoulLeftTimeJob.kt @@ -0,0 +1,23 @@ +package com.walking.traffic.batch.scheduler + +import org.quartz.* +import org.springframework.batch.core.Job +import org.springframework.batch.core.JobParametersBuilder +import org.springframework.batch.core.launch.JobLauncher +import org.springframework.scheduling.quartz.QuartzJobBean +import org.springframework.stereotype.Component +import java.util.* + +@Component +class SeoulLeftTimeJob( + private val trafficDetailJob: Job, + private val jobLauncher: JobLauncher, +) : QuartzJobBean() { + + override fun executeInternal(context: JobExecutionContext) { + val jobParameters = JobParametersBuilder() + .addLong("id", Date().time) + .toJobParameters() + jobLauncher.run(trafficDetailJob, jobParameters) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/batch/scheduler/SeoulLeftTimeJobRunner.kt b/src/main/kotlin/com/walking/traffic/batch/scheduler/SeoulLeftTimeJobRunner.kt new file mode 100644 index 00000000..e34d6d1d --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/batch/scheduler/SeoulLeftTimeJobRunner.kt @@ -0,0 +1,42 @@ +package com.walking.traffic.batch.scheduler + +import org.quartz.* +import org.springframework.beans.factory.annotation.Value +import org.springframework.boot.ApplicationArguments +import org.springframework.boot.ApplicationRunner +import org.springframework.scheduling.annotation.Scheduled +import org.springframework.stereotype.Component + +@Component +class SeoulLeftTimeJobRunner( + @Value("\${api.seoul.interval}") private val interval: Int, + private val scheduler: Scheduler, +) : ApplicationRunner { + + override fun run(args: ApplicationArguments) { + runScheduledJob() + } + + @Scheduled(cron = "0 0 7 * * ?") + private fun runScheduledJob() { + val jobDetail = JobBuilder.newJob(SeoulLeftTimeJob::class.java) + .withIdentity("seoulLeftTimeJob", "batch") + .build() + + val trigger: Trigger = TriggerBuilder.newTrigger() + .withIdentity("seoulLeftTimeTrigger", "batch") + .startAt(DateBuilder.todayAt(0, 0, 0)) + .endAt(DateBuilder.todayAt(23, 59, 59)) + .withSchedule( + SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(interval) + .repeatForever() + ) + .build() + try { + scheduler.scheduleJob(jobDetail, trigger) + } catch (e: SchedulerException) { + e.printStackTrace() + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/config/ClientConfig.kt b/src/main/kotlin/com/walking/traffic/config/ClientConfig.kt new file mode 100644 index 00000000..c61cbdf4 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/config/ClientConfig.kt @@ -0,0 +1,25 @@ +package com.walking.traffic.config + +import org.apache.hc.client5.http.impl.DefaultRedirectStrategy +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory +import org.springframework.web.client.RestTemplate + +@Configuration +class ClientConfig { + @Bean + fun restTemplate(): RestTemplate { + val factory = HttpComponentsClientHttpRequestFactory() + HttpClientBuilder.create() + .setRedirectStrategy(DefaultRedirectStrategy()) + .build().let { + factory.setHttpClient(it) + } + + return RestTemplate().apply { + requestFactory = factory + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/controller/PedestrianLightController.kt b/src/main/kotlin/com/walking/traffic/controller/PedestrianLightController.kt new file mode 100644 index 00000000..14a9c45d --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/controller/PedestrianLightController.kt @@ -0,0 +1,52 @@ +package com.walking.traffic.controller + +import com.walking.traffic.usecase.BrowsePedestrianLightsUseCase +import com.walking.traffic.usecase.BrowseUpdatedLast10MinutesPedestrianLightsUseCase +import com.walking.traffic.usecase.ReadPedestrianLightUseCase +import com.walking.traffic.usecase.dto.BrowsePedestrianLightsUseCaseIn +import com.walking.traffic.usecase.dto.ReadPedestrianLightsUseCaseIn +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/api") +class PedestrianLightController( + private val browsePedestrianLightsUseCase: BrowsePedestrianLightsUseCase, + private val browseUpdatedLast10MinutesPedestrianLightsUseCase: BrowseUpdatedLast10MinutesPedestrianLightsUseCase, + private val readPedestrianLightUseCase: ReadPedestrianLightUseCase, +) { + + @GetMapping("?blLng={blLng}&blLat={blLat}&trLng={trLng}&trLat={trLat}") + fun browsePedestrianLights( + @RequestParam("blLng") blLng: Double, + @RequestParam("blLat") blLat: Double, + @RequestParam("trLng") trLng: Double, + @RequestParam("trLat") trLat: Double, + ) = browsePedestrianLightsUseCase.execute( + BrowsePedestrianLightsUseCaseIn( + blLng = blLng, + blLat = blLat, + trLng = trLng, + trLat = trLat + ) + ).let { + ResponseEntity.ok(it) + } + + @GetMapping("/latest") + fun browseUpdatedLast10MinutesPedestrianTrafficLights() = browseUpdatedLast10MinutesPedestrianLightsUseCase.execute().let { + ResponseEntity.ok(it) + } + + @GetMapping("/one/{id}") + fun readPedestrianTrafficLight(@PathVariable("id") id: Long) = + readPedestrianLightUseCase.execute( + ReadPedestrianLightsUseCaseIn(id) + ).let { + ResponseEntity.ok(it) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/entity/ApiSource.kt b/src/main/kotlin/com/walking/traffic/data/entity/ApiSource.kt new file mode 100644 index 00000000..3eea44a2 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/entity/ApiSource.kt @@ -0,0 +1,9 @@ +package com.walking.traffic.data.entity + +enum class ApiSource(private val source: String) { + /** + * 서울시 제공 API - 차량 신호등 + * - certificationId : itstId & direction + */ + SEOUL_CAR("seoul_car"), +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/entity/BaseEntity.kt b/src/main/kotlin/com/walking/traffic/data/entity/BaseEntity.kt new file mode 100644 index 00000000..61f3e0a9 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/entity/BaseEntity.kt @@ -0,0 +1,31 @@ +package com.walking.traffic.data.entity + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties +import jakarta.persistence.Column +import jakarta.persistence.EntityListeners +import jakarta.persistence.MappedSuperclass +import org.springframework.data.annotation.CreatedDate +import org.springframework.data.annotation.LastModifiedDate +import org.springframework.data.jpa.domain.support.AuditingEntityListener +import java.time.LocalDateTime + +@MappedSuperclass +@JsonIgnoreProperties(value = ["createdAt, modifiedAt"], allowGetters = true) +@EntityListeners(AuditingEntityListener::class) +abstract class BaseEntity { + /** 생성일 */ + @CreatedDate + @Column(name = "created_at", columnDefinition = "datetime default CURRENT_TIMESTAMP") + var createdAt: LocalDateTime = LocalDateTime.now() + + /** 수정일 */ + @LastModifiedDate + @Column( + name = "modified_at", + columnDefinition = "datetime default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" + ) + var modifiedAt: LocalDateTime = LocalDateTime.now() + + @Column(nullable = false, name = "deleted") + var deleted: Boolean = false +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/entity/PedestrianLightEntity.kt b/src/main/kotlin/com/walking/traffic/data/entity/PedestrianLightEntity.kt new file mode 100644 index 00000000..7f6973bc --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/entity/PedestrianLightEntity.kt @@ -0,0 +1,34 @@ +package com.walking.traffic.data.entity + +import jakarta.persistence.* +import org.hibernate.annotations.SQLDelete +import org.locationtech.jts.geom.Point + +@Entity +@Table( + name = "predestrian_light", + indexes = [Index(name = "location_point_idx", columnList = "location_point")] +) +@SQLDelete(sql = "UPDATE predestrian_light SET deleted=true where id=?") +class PedestrianLightEntity( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + val id: Long = -1, + /** 보행자 신호등 이름 */ + @Column(nullable = false, name = "location_name") + val locationName: String, + /** 보행자 신호등 위치 */ + @Column(columnDefinition = "POINT SRID 4326", nullable = false, name = "location_point") + val locationPoint: Point, + /** 보행자 녹색 신호등 주기 */ + @Column(nullable = true, name = "green_cycle") + val greenCycle: Double = 0.0, + /** 보행자 빨간색 신호등 주기 */ + @Column(nullable = true, name = "red_cycle") + val redCycle: Double = 0.0, + @Column(nullable = false, name = "source") + @Enumerated(EnumType.STRING) + val source: ApiSource, + @Column(nullable = false, columnDefinition = "JSON", name = "source_certification") + val sourceCertification: String, +) : BaseEntity() \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/entity/SeoulLeftTimeEntity.kt b/src/main/kotlin/com/walking/traffic/data/entity/SeoulLeftTimeEntity.kt new file mode 100644 index 00000000..62d21d30 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/entity/SeoulLeftTimeEntity.kt @@ -0,0 +1,37 @@ +package com.walking.traffic.data.entity + +import com.fasterxml.jackson.annotation.JsonFormat +import jakarta.persistence.* +import org.hibernate.annotations.SQLDelete +import java.time.LocalDateTime + +/** + * 차량 신호등 상세 정보 + * color와 leftTime 정보를 요청하는 API가 모두 성공하는 경우에만 저장 + */ +@Entity +@Table( + name = "seoul_left_time", + indexes = [Index(name = "certification_idx", columnList = "itst_id, direction")] +) +@SQLDelete(sql = "UPDATE seoul_left_time SET deleted=true where id=?") +class SeoulLeftTimeEntity( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + val id: Long = -1, + /** 서울시 제공 API의 차량 신호등 ID */ + @Column(nullable = false, name = "itst_id") + val itstId: String, + @Column(nullable = false, name = "direction") + val direction: String, + /** 보행자 신호등 색생 */ + @Enumerated(EnumType.STRING) + @Column(nullable = false, name = "color") + val trafficColor: TrafficColor, + /** 보행자 신호등 남은 시간 */ + @Column(nullable = false, name = "left_time") + val leftTime: Double, + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") + @Column(nullable = false, name = "reg_dt") + val regDt: LocalDateTime, +) : BaseEntity() \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/entity/TrafficColor.kt b/src/main/kotlin/com/walking/traffic/data/entity/TrafficColor.kt new file mode 100644 index 00000000..38ac528c --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/entity/TrafficColor.kt @@ -0,0 +1,9 @@ +package com.walking.traffic.data.entity + +enum class TrafficColor { + RED, + GREEN, + DARK, + UNKNOWN, + ; +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/repository/PedestrianLightRepository.kt b/src/main/kotlin/com/walking/traffic/data/repository/PedestrianLightRepository.kt new file mode 100644 index 00000000..afc19a2d --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/repository/PedestrianLightRepository.kt @@ -0,0 +1,44 @@ +package com.walking.traffic.data.repository + +import com.walking.traffic.data.entity.PedestrianLightEntity +import org.locationtech.jts.geom.Polygon +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.jpa.repository.Modifying +import org.springframework.data.jpa.repository.Query +import org.springframework.data.repository.query.Param +import org.springframework.stereotype.Repository +import java.time.LocalDateTime + +@Repository +interface PedestrianLightRepository : JpaRepository { + + @Query( + value = "SELECT * FROM predestrian_light WHERE ST_Contains(:polygon, point_value)", + nativeQuery = true + ) + fun findAllInBounds( + @Param("polygon") polygon: Polygon, + ): List + + @Modifying + @Query( + value = "UPDATE predestrian_light SET green_cycle = :greenCycle , updated_at = :updatedAt WHERE id = :id", + nativeQuery = true + ) + fun updateGreenCycle( + @Param("id") id: Long, + @Param("greenCycle") greenCycle: Double, + @Param("updatedAt") updatedAt: LocalDateTime, + ) + + @Modifying + @Query( + value = "UPDATE predestrian_light SET red_cycle = :redCycle , updated_at = :updatedAt WHERE id = :id", + nativeQuery = true + ) + fun updateRedCycle( + @Param("id") id: Long, + @Param("redCycle") redCycle: Double, + @Param("updatedAt") updatedAt: LocalDateTime, + ) +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/repository/SeoulLeftTimeRepository.kt b/src/main/kotlin/com/walking/traffic/data/repository/SeoulLeftTimeRepository.kt new file mode 100644 index 00000000..35988a51 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/repository/SeoulLeftTimeRepository.kt @@ -0,0 +1,19 @@ +package com.walking.traffic.data.repository + +import com.walking.traffic.data.entity.SeoulLeftTimeEntity +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.jpa.repository.Query +import org.springframework.stereotype.Repository + +@Repository +interface SeoulLeftTimeRepository : JpaRepository { + @Query( + value = "SELECT * FROM seoul_left_time WHERE seoul_left_time.itst_id = :itstId and seoul_left_time.direction = :direction ORDER BY seoul_left_time.reg_dt DESC LIMIT :limit", + nativeQuery = true + ) + fun findTopWhereTrafficIdOrderByRegDtDesc( + itstId: String, + direction: String, + limit: Int? = 10, + ): List +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/data/support/SeoulCarCertificationMapper.kt b/src/main/kotlin/com/walking/traffic/data/support/SeoulCarCertificationMapper.kt new file mode 100644 index 00000000..20c64e73 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/data/support/SeoulCarCertificationMapper.kt @@ -0,0 +1,22 @@ +package com.walking.traffic.data.support + +import com.fasterxml.jackson.databind.ObjectMapper +import org.springframework.stereotype.Component + +data class SeoulCarCertification( + val itstId: String, + val direction: String, +) + +@Component +class SeoulCarCertificationMapper( + private val objectMapper: ObjectMapper, +) { + fun toJson(seoulCarCertification: SeoulCarCertification): String { + return objectMapper.writeValueAsString(seoulCarCertification) + } + + fun toSeoulCertification(json: String): SeoulCarCertification { + return objectMapper.readValue(json, SeoulCarCertification::class.java) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/service/GeometryService.kt b/src/main/kotlin/com/walking/traffic/service/GeometryService.kt new file mode 100644 index 00000000..1dd36bf3 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/service/GeometryService.kt @@ -0,0 +1,14 @@ +package com.walking.traffic.service + +import org.locationtech.jts.geom.* +import org.springframework.stereotype.Service + +@Service +class GeometryService( + val geometryFactory: GeometryFactory = GeometryFactory(PrecisionModel(), 4326), +) { + + fun createPolygon(coordinates: Array): Polygon { + return geometryFactory.createPolygon(coordinates) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/BrowsePedestrianLightsUseCase.kt b/src/main/kotlin/com/walking/traffic/usecase/BrowsePedestrianLightsUseCase.kt new file mode 100644 index 00000000..9f3383d7 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/BrowsePedestrianLightsUseCase.kt @@ -0,0 +1,55 @@ +package com.walking.traffic.usecase + +import com.walking.traffic.data.entity.ApiSource +import com.walking.traffic.data.repository.PedestrianLightRepository +import com.walking.traffic.service.GeometryService +import com.walking.traffic.usecase.dto.BrowsePedestrianLightsUseCaseIn +import com.walking.traffic.usecase.dto.BrowsePedestrianLightsUseCaseOut +import com.walking.traffic.usecase.model.PredictStatus +import com.walking.traffic.usecase.service.SeoulLeftTimePedestrianLightService +import org.locationtech.jts.geom.Coordinate +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional + +@Service +class BrowsePedestrianLightsUseCase( + private val geometryService: GeometryService, + private val pedestrianLightRepository: PedestrianLightRepository, + private val seoulLeftTimePedestrianLightService: SeoulLeftTimePedestrianLightService, +) { + + @Transactional + fun execute(useCaseIn: BrowsePedestrianLightsUseCaseIn): BrowsePedestrianLightsUseCaseOut { + val bound = geometryService.createPolygon( + arrayOf( + Coordinate(useCaseIn.blLng, useCaseIn.blLat), + Coordinate(useCaseIn.blLng, useCaseIn.trLat), + Coordinate(useCaseIn.trLng, useCaseIn.trLat), + Coordinate(useCaseIn.trLng, useCaseIn.blLat), + Coordinate(useCaseIn.blLng, useCaseIn.blLat) + ) + ) + + val trafficInBounds = pedestrianLightRepository.findAllInBounds(bound) + + val sourceMappedTraffic = + trafficInBounds.groupBy(keySelector = { it.source }) + + val pedestrianTrafficLights = + seoulLeftTimePedestrianLightService.execute(sourceMappedTraffic[ApiSource.SEOUL_CAR]!!) + + pedestrianTrafficLights.filter { + it.greenCycle.status == PredictStatus.SUCCESS + }.forEach { + pedestrianLightRepository.updateGreenCycle(it.id, it.greenCycle.cycle, it.greenCycle.updateAt) + } + + pedestrianTrafficLights.filter { + it.redCycle.status == PredictStatus.SUCCESS + }.forEach { + pedestrianLightRepository.updateRedCycle(it.id, it.redCycle.cycle, it.redCycle.updateAt) + } + + return BrowsePedestrianLightsUseCaseOut(pedestrianTrafficLights) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/BrowseUpdatedLast10MinutesPedestrianLightsUseCase.kt b/src/main/kotlin/com/walking/traffic/usecase/BrowseUpdatedLast10MinutesPedestrianLightsUseCase.kt new file mode 100644 index 00000000..e85719bc --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/BrowseUpdatedLast10MinutesPedestrianLightsUseCase.kt @@ -0,0 +1,41 @@ +package com.walking.traffic.usecase + +import com.walking.traffic.data.entity.ApiSource +import com.walking.traffic.data.repository.PedestrianLightRepository +import com.walking.traffic.usecase.dto.BrowsePedestrianLightsUseCaseOut +import com.walking.traffic.usecase.model.PredictStatus +import com.walking.traffic.usecase.service.SeoulLeftTimePedestrianLightService +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.time.LocalDateTime + +@Service +class BrowseUpdatedLast10MinutesPedestrianLightsUseCase( + private val pedestrianLightRepository: PedestrianLightRepository, + private val seoulLeftTimePedestrianLightService: SeoulLeftTimePedestrianLightService, +) { + + @Transactional + fun execute(): BrowsePedestrianLightsUseCaseOut { + val trafficInBounds = pedestrianLightRepository.findAll() + + val sourceMappedTraffic = + trafficInBounds.groupBy { it.source } + + val pedestrianTrafficLights = + seoulLeftTimePedestrianLightService.execute( + sourceMappedTraffic[ApiSource.SEOUL_CAR]?.toList() ?: emptyList() + ) + + return pedestrianTrafficLights.asSequence().filter { + it.leftTime.updateAt.isAfter(LocalDateTime.now().minusMinutes(10)) + }.filter { + it.redCycle.status == PredictStatus.SUCCESS + }.filter { + it.greenCycle.status == PredictStatus.SUCCESS + }.toList() + .let { + BrowsePedestrianLightsUseCaseOut(it) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/ReadPedestrianLightUseCase.kt b/src/main/kotlin/com/walking/traffic/usecase/ReadPedestrianLightUseCase.kt new file mode 100644 index 00000000..9226f7a9 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/ReadPedestrianLightUseCase.kt @@ -0,0 +1,39 @@ +package com.walking.traffic.usecase + +import com.walking.traffic.data.repository.PedestrianLightRepository +import com.walking.traffic.usecase.dto.BrowsePedestrianLightsUseCaseOut +import com.walking.traffic.usecase.dto.ReadPedestrianLightsUseCaseIn +import com.walking.traffic.usecase.model.PredictStatus +import com.walking.traffic.usecase.service.SeoulLeftTimePedestrianLightService +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import kotlin.jvm.optionals.getOrNull + +@Service +class ReadPedestrianLightUseCase( + private val pedestrianLightRepository: PedestrianLightRepository, + private val seoulLeftTimePedestrianLightService: SeoulLeftTimePedestrianLightService, +) { + + @Transactional + fun execute(useCaseIn: ReadPedestrianLightsUseCaseIn): BrowsePedestrianLightsUseCaseOut { + val traffic = pedestrianLightRepository.findById(useCaseIn.id).getOrNull() ?: return BrowsePedestrianLightsUseCaseOut(emptyList()) + + val pedestrianTrafficLights = + seoulLeftTimePedestrianLightService.execute(listOf(traffic)) + + pedestrianTrafficLights.filter { + it.greenCycle.status == PredictStatus.SUCCESS + }.forEach { + pedestrianLightRepository.updateGreenCycle(it.id, it.greenCycle.cycle, it.greenCycle.updateAt) + } + + pedestrianTrafficLights.filter { + it.redCycle.status == PredictStatus.SUCCESS + }.forEach { + pedestrianLightRepository.updateRedCycle(it.id, it.redCycle.cycle, it.redCycle.updateAt) + } + + return BrowsePedestrianLightsUseCaseOut(pedestrianTrafficLights) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/dto/BrowsePedestrianLightsUseCaseIn.kt b/src/main/kotlin/com/walking/traffic/usecase/dto/BrowsePedestrianLightsUseCaseIn.kt new file mode 100644 index 00000000..3c7f1aa7 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/dto/BrowsePedestrianLightsUseCaseIn.kt @@ -0,0 +1,8 @@ +package com.walking.traffic.usecase.dto + +data class BrowsePedestrianLightsUseCaseIn( + val blLng: Double, + val blLat: Double, + val trLng: Double, + val trLat: Double, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/dto/BrowsePedestrianLightsUseCaseOut.kt b/src/main/kotlin/com/walking/traffic/usecase/dto/BrowsePedestrianLightsUseCaseOut.kt new file mode 100644 index 00000000..2848ad16 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/dto/BrowsePedestrianLightsUseCaseOut.kt @@ -0,0 +1,7 @@ +package com.walking.traffic.usecase.dto + +import com.walking.traffic.usecase.model.PedestrianTrafficLight + +data class BrowsePedestrianLightsUseCaseOut( + val pedestrianTrafficLights: List, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/dto/ReadPedestrianLightsUseCaseIn.kt b/src/main/kotlin/com/walking/traffic/usecase/dto/ReadPedestrianLightsUseCaseIn.kt new file mode 100644 index 00000000..ea91bce8 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/dto/ReadPedestrianLightsUseCaseIn.kt @@ -0,0 +1,5 @@ +package com.walking.traffic.usecase.dto + +data class ReadPedestrianLightsUseCaseIn( + val id: Long, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/model/PedestrianTrafficLight.kt b/src/main/kotlin/com/walking/traffic/usecase/model/PedestrianTrafficLight.kt new file mode 100644 index 00000000..6449e444 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/model/PedestrianTrafficLight.kt @@ -0,0 +1,34 @@ +package com.walking.traffic.usecase.model + +import java.time.LocalDateTime + +data class PedestrianTrafficLight( + val id: Long, + val name: String, + val point: PointDetail, + val redCycle: CycleDetail, + val greenCycle: CycleDetail, + val leftTime: LeftTimeDetail, + val color: ColorDetail, +) + +data class PointDetail( + val lat: Double, + val lng: Double, +) + +data class CycleDetail( + val cycle: Double, + val status: PredictStatus, + val updateAt: LocalDateTime = LocalDateTime.now(), +) + +data class LeftTimeDetail( + val time: Double, + val updateAt: LocalDateTime, +) + +data class ColorDetail( + val color: String, + val updateAt: LocalDateTime, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/model/PredictStatus.kt b/src/main/kotlin/com/walking/traffic/usecase/model/PredictStatus.kt new file mode 100644 index 00000000..89bd3a83 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/model/PredictStatus.kt @@ -0,0 +1,7 @@ +package com.walking.traffic.usecase.model + +enum class PredictStatus { + SUCCESS, + FAIL, + OLD, +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/model/left/PedestrianLeftTimeInfo.kt b/src/main/kotlin/com/walking/traffic/usecase/model/left/PedestrianLeftTimeInfo.kt new file mode 100644 index 00000000..53aa93da --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/model/left/PedestrianLeftTimeInfo.kt @@ -0,0 +1,11 @@ +package com.walking.traffic.usecase.model.left + +import com.walking.traffic.data.entity.TrafficColor +import java.time.LocalDateTime + +data class PedestrianLeftTimeInfo( + val id: String, + val color: TrafficColor, + val leftTime: Double, + val createdAt: LocalDateTime, +) \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/model/left/RecentPedestrianLeftTimes.kt b/src/main/kotlin/com/walking/traffic/usecase/model/left/RecentPedestrianLeftTimes.kt new file mode 100644 index 00000000..acccbd15 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/model/left/RecentPedestrianLeftTimes.kt @@ -0,0 +1,93 @@ +package com.walking.traffic.usecase.model.left + +import com.walking.traffic.data.entity.TrafficColor +import com.walking.traffic.data.entity.TrafficColor.* +import java.time.Duration +import java.time.LocalDateTime +import java.util.function.BiPredicate + +data class CalculateCycleResult( + val cycle: Double, + val updatedAt: LocalDateTime, +) + +class RecentPedestrianLeftTimes( + private val browseLeftTimeInterval: Int, + private val pedestrianLeftTimeInfos: List, + val latestLeftTimeTrafficColor: TrafficColor?, + val latestLeftTimeTrafficLeftTime: Double?, + val latestLeftTimeTrafficsRegisterTime: LocalDateTime?, +) { + companion object { + val INVALID_LEFT_TIMES = listOf(36001.0, 2550.0, 1229.0) + } + + constructor( + browseCarTrafficInterval: Int, + pedestrianLeftTimeInfos: List, + ) : this( + browseCarTrafficInterval, + pedestrianLeftTimeInfos, + pedestrianLeftTimeInfos.maxByOrNull { it.createdAt }?.color, + pedestrianLeftTimeInfos.maxByOrNull { it.createdAt }?.leftTime, + pedestrianLeftTimeInfos.maxByOrNull { it.createdAt }?.createdAt + ) + + fun predictGreenCycle(): CalculateCycleResult? { + return doPredict { + beforeData, afterData -> + beforeData.color == RED && afterData.color == GREEN + } + } + + fun predictRedCycle(): CalculateCycleResult? { + return doPredict { + beforeData, afterData -> + beforeData.color == GREEN && afterData.color == RED + } + } + + private fun doPredict(predicate: BiPredicate): CalculateCycleResult? { + pedestrianLeftTimeInfos.sortedBy { it.createdAt }.zipWithNext { beforeData, afterData -> + if (isValid(beforeData, afterData) && predicate.test(beforeData, afterData)) { + return calculateCycle(beforeData, afterData) + } + } + return null + } + + private fun isValid( + before: PedestrianLeftTimeInfo, + after: PedestrianLeftTimeInfo, + ): Boolean { + return isValidTime(before, after) && checkMissingDataBetween(before, after) + } + + private fun isValidTime( + before: PedestrianLeftTimeInfo, + after: PedestrianLeftTimeInfo, + ) = ( + /** Invalid leftTime Data */ + !INVALID_LEFT_TIMES.contains(before.leftTime) && + !INVALID_LEFT_TIMES.contains(after.leftTime) + ) + + private fun checkMissingDataBetween( + before: PedestrianLeftTimeInfo, + after: PedestrianLeftTimeInfo, + ): Boolean { + val interval = Duration.between(before.createdAt, after.createdAt).seconds + return interval in (1.. 0 } + ?.let { + CalculateCycleResult(it, after.createdAt) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/service/PedestrianLightService.kt b/src/main/kotlin/com/walking/traffic/usecase/service/PedestrianLightService.kt new file mode 100644 index 00000000..34870baa --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/service/PedestrianLightService.kt @@ -0,0 +1,8 @@ +package com.walking.traffic.usecase.service + +import com.walking.traffic.data.entity.PedestrianLightEntity +import com.walking.traffic.usecase.model.PedestrianTrafficLight + +interface PedestrianLightService { + fun execute(sources: List): List +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/service/SeoulLeftTimePedestrianLightService.kt b/src/main/kotlin/com/walking/traffic/usecase/service/SeoulLeftTimePedestrianLightService.kt new file mode 100644 index 00000000..630b93d1 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/service/SeoulLeftTimePedestrianLightService.kt @@ -0,0 +1,52 @@ +package com.walking.traffic.usecase.service + +import com.walking.traffic.data.entity.PedestrianLightEntity +import com.walking.traffic.data.repository.SeoulLeftTimeRepository +import com.walking.traffic.data.support.SeoulCarCertificationMapper +import com.walking.traffic.usecase.model.PedestrianTrafficLight +import com.walking.traffic.usecase.model.left.PedestrianLeftTimeInfo +import com.walking.traffic.usecase.model.left.RecentPedestrianLeftTimes +import com.walking.traffic.usecase.service.left.SeoulLeftTimeCalculateService +import org.springframework.beans.factory.annotation.Value +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional + +@Service +class SeoulLeftTimePedestrianLightService( + @Value("\${api.seoul.interval}") private val interval: Int, + private val seoulLeftTimeRepository: SeoulLeftTimeRepository, + private val seoulCertificationMapper: SeoulCarCertificationMapper, + private val seoulLeftTimeCalculateService: SeoulLeftTimeCalculateService, +) : PedestrianLightService { + + @Transactional(readOnly = true) + override fun execute(sources: List): List { + val idMappedSeoulLeftTime = sources.groupBy { + it.id + }.mapValues { it -> + val certification = + seoulCertificationMapper.toSeoulCertification(it.value.first().sourceCertification) + + seoulLeftTimeRepository.findTopWhereTrafficIdOrderByRegDtDesc( + itstId = certification.itstId, + direction = certification.direction + ) + .map { + PedestrianLeftTimeInfo( + id = it.itstId, + color = it.trafficColor, + leftTime = it.leftTime, + createdAt = it.createdAt + ) + } + .let { + RecentPedestrianLeftTimes(interval, it) + } + } + + return seoulLeftTimeCalculateService.execute( + sources, + idMappedSeoulLeftTime + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/service/left/CalculatePedestrianLightService.kt b/src/main/kotlin/com/walking/traffic/usecase/service/left/CalculatePedestrianLightService.kt new file mode 100644 index 00000000..921b5931 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/service/left/CalculatePedestrianLightService.kt @@ -0,0 +1,8 @@ +package com.walking.traffic.usecase.service.left + +import com.walking.traffic.data.entity.PedestrianLightEntity +import com.walking.traffic.usecase.model.PedestrianTrafficLight + +interface CalculatePedestrianLightService { + fun execute(sources: List, data: T): List +} \ No newline at end of file diff --git a/src/main/kotlin/com/walking/traffic/usecase/service/left/SeoulLeftTimeCalculateService.kt b/src/main/kotlin/com/walking/traffic/usecase/service/left/SeoulLeftTimeCalculateService.kt new file mode 100644 index 00000000..62d2fd30 --- /dev/null +++ b/src/main/kotlin/com/walking/traffic/usecase/service/left/SeoulLeftTimeCalculateService.kt @@ -0,0 +1,98 @@ +package com.walking.traffic.usecase.service.left + +import com.walking.traffic.data.entity.PedestrianLightEntity +import com.walking.traffic.data.entity.TrafficColor +import com.walking.traffic.data.repository.PedestrianLightRepository +import com.walking.traffic.usecase.model.* +import com.walking.traffic.usecase.model.left.RecentPedestrianLeftTimes +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.time.LocalDateTime +import java.util.function.Function +import java.util.function.Predicate + +@Service +class SeoulLeftTimeCalculateService( + private val pedestrianLightRepository: PedestrianLightRepository, +) : CalculatePedestrianLightService> { + + /** + * 1. 신호등 정보와 예측 정보를 매핑합니다. + * 2. 예측 정보가 없다면 가장 최근의 예측 정보를 가져옵니다. + * 3. 예측 정보를 반환합니다. + */ + @Transactional(readOnly = true) + override fun execute( + sources: List, + data: Map, + ): List { + val ids = sources.map { it.id } + val idMappedLocationName = sources.associateBy({ it.id }, { it.locationName }) + val idMappedPoint = sources.associateBy({ it.id }, { it.locationPoint }) + + val pedestrianTrafficLights = mutableListOf() + for (id in ids) { + val recentLeftTraffic = data[id] + val topLeftTrafficsRegisterTime: LocalDateTime = + recentLeftTraffic?.latestLeftTimeTrafficsRegisterTime ?: continue + + val topLeftTrafficColor = recentLeftTraffic.latestLeftTimeTrafficColor ?: TrafficColor.DARK + val topLeftTrafficLeftTime = recentLeftTraffic.latestLeftTimeTrafficLeftTime ?: 0.0 + + val greenCycle: CycleDetail = recentLeftTraffic.predictGreenCycle()?.let { + CycleDetail(it.cycle, PredictStatus.SUCCESS, it.updatedAt) + } ?: ifPredictFail( + id, + { it.greenCycle == 0.0 }, + { CycleDetail(it.greenCycle, PredictStatus.OLD, it.modifiedAt) } + ) + + val redCycle: CycleDetail = recentLeftTraffic.predictRedCycle()?.let { + CycleDetail(it.cycle, PredictStatus.SUCCESS, it.updatedAt) + } ?: ifPredictFail( + id, + { it.redCycle == 0.0 }, + { CycleDetail(it.redCycle, PredictStatus.OLD, it.modifiedAt) } + ) + + pedestrianTrafficLights.add( + PedestrianTrafficLight( + id = id, + name = idMappedLocationName[id]!!, + color = ColorDetail(topLeftTrafficColor.name, topLeftTrafficsRegisterTime), + leftTime = LeftTimeDetail(topLeftTrafficLeftTime, topLeftTrafficsRegisterTime), + point = PointDetail( + lat = idMappedPoint[id]!!.y, + lng = idMappedPoint[id]!!.x + ), + redCycle = redCycle, + greenCycle = greenCycle + ) + ) + } + + return pedestrianTrafficLights + } + + /** + * @param cycleNotUpdatePredict: 주기 예측이 업데이트 되지 않은 경우 + * @param oldUpdatedCycleFunction:주기 예측이 업데이트 된 경우 주기를 반환하는 함수 + */ + private fun ifPredictFail( + id: Long, + cycleNotUpdatePredict: Predicate, + oldUpdatedCycleFunction: Function, + ): CycleDetail { + return pedestrianLightRepository.findById(id).let { + if (it.isEmpty) { + CycleDetail(0.0, PredictStatus.FAIL) + } else { + if (cycleNotUpdatePredict.test(it.get())) { + CycleDetail(0.0, PredictStatus.FAIL) + } else { + oldUpdatedCycleFunction.apply(it.get()) + } + } + } + } +} \ No newline at end of file diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml new file mode 100644 index 00000000..926b4e13 --- /dev/null +++ b/src/main/resources/application-local.yml @@ -0,0 +1,39 @@ +server: + port: 8080 +spring: + datasource: + url: jdbc:mysql://localhost:13306/api?allowPublicKeyRetrieval=true&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull + username: root + password: root + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + format_sql: true + dialect: org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect + order_inserts: true + order_updates: true + jdbc: + batch_size: 50 + batch: + jdbc: + initialize-schema: always + job: + enabled: false + name: ${job.name:NONE} + chunk: + size: 1000 + +api: + seoul: + apiKey: b52c4b05-90b1-4d98-baf6-ac2812a1b9a1 + baseUrl: http://t-data.seoul.go.kr + colorPath: /apig/apiman-gateway/tapi/v2xSignalPhaseInformation/1.0 + leftTimePath: /apig/apiman-gateway/tapi/v2xSignalPhaseTimingInformation/1.0 + interval: 70 + +logging: + level: + root: debug diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..900a1c54 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,39 @@ +server: + port: 8080 +spring: + datasource: + url: ${DB_HOSTNAME}/api?allowPublicKeyRetrieval=true&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + format_sql: true + dialect: org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect + order_inserts: true + order_updates: true + jdbc: + batch_size: 50 + batch: + jdbc: + initialize-schema: always + job: + enabled: false + name: ${job.name:NONE} + chunk: + size: ${BATCH_CHUNK_SIZE:1000} + +api: + seoul: + apiKey: ${SEOUL_API_KEY} + baseUrl: https://t-data.seoul.go.kr + colorPath: /apig/apiman-gateway/tapi/v2xSignalPhaseInformation/1.0 + leftTimePath: /apig/apiman-gateway/tapi/v2xSignalPhaseTimingInformation/1.0 + interval: ${SCHEDULER_INTERVAL} + +logging: + level: + root: debug