diff --git a/.idea/workspace.xml b/.idea/workspace.xml deleted file mode 100644 index 2ce08640..00000000 --- a/.idea/workspace.xml +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - - - - - - - - - { - "associatedIndex": 0 -} - - - - - - - - - - - - - - - 1705971685494 - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/README.md b/README.md index 15cd5bb7..573a4216 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ - + @@ -42,7 +42,7 @@ 김회창

팀장

Back-end

매칭서버 개발

Problem Solving API 개발

인프라 구축

김정현

팀원

Back-end

아레나 게임서버 개발

알림 & 게시판 API 개발

화면공유 시스템 관리

이귀현

팀원

Front-end

아레나 컴포넌트 개발

- 장세정

팀원

Front-end

알림 & 게시판 컴포넌트 개발

회원 컴포넌트 개발

+ 장세정

팀원

Front-end

알림 & 게시판 컴포넌트 개발

회원 컴포넌트 개발

오승현

팀원

Back-end

채점서버 개발

회원관리 API 개발

양건우

팀원

Front-end

Problem Solving 컴포넌트 개발

화면 공유 컴포넌트 개발

@@ -144,139 +144,139 @@ https://www.erdcloud.com/d/nrfqSDdChRWJpanzz ![Architecture](/asset/img/Architecture.png) -## 🎬 Figma Design - -### Main - -![Main](/asset/img/figma-main.png) -
-


-### Login +## 💻 주요 기능 소개 -![Main](/asset/img/Figma-Login.png) -
-
-
-
+### 메인 화면 -### Community +- 코드아레나를 대표하는 메인 페이지입니다. +- 메인페이지에서 다양한 페이지로 접근할 수 있습니다. +- 코드아레나에 대해 소개하고, 최신 문제와 인기 질문을 소개합니다. -![Main](/asset/img/figma-community.png) +![Main](/asset/gif/mainpage.gif) -
-
-
-
-### Problem Solving +### 회원가입 -![Main](/asset/img/figma-ps1.png) +- 이메일을 통한 회원가입을 진행합니다. -
-
-
+![Main](/asset/gif/signup.gif) -![Main](/asset/img/figma-ps2.png) -
-
-
+### 로그인 -![Main](/asset/img/figma-ps3.png) +- 쉽고 간편한 로그인을 진행합니다. -
-
-
-
+![Main](/asset/gif/login.gif) -### Arena Main -![Main](/asset/img/figma-arena.png) +### 문제 풀이 페이지 -
-
-
-
+- 온라인 저지 사이트와 같이 스스로 문제 해결 능력을 기를 수 있도록 장려합니다. -### MyPage +![Main](/asset/gif/goProblem.gif) -![Main](/asset/img/figma-profile.png) -
-
-
-
+### 문제 풀기 -### Matching +- 알고리즘 문제를 풀었다면 제출 후, 제출 현황을 확인할 수 있습니다. +- 만약 문제를 틀렸다면, 어떤 테스트 케이스에서 틀렸는지 확인할 수 있습니다. +- 문제에 대한 질문게시판과 문제 수정 요청을 제공합니다. -![Main](/asset/img/figma-matching.png) +![Main](/asset/gif/solvingProblem.gif) + -
-
-
-
+### 문제 카테고리 -### INGAME +- 다양한 알고리즘 문제를 카테고리별로 제공합니다. -![Main](/asset/img/figma-arena-ingame-1.png) +![Main](/asset/gif/problemCategory.gif) -
-
-
-
-### SPECTATORS +### 문제 생성 -![Main](/asset/img/figma-arena-spec.png) +- 알고리즘 문제 해결을 위한 새로운 문제를 생성합니다. +- 문제의 내용부터 입출력 예제를 입력하고, 컴파일을 시도한 후에 제출할 수 있습니다. +- 사이트 관리자측에서 문제를 검수하고 새로운 알고리즘 문제에 대해 업로드합니다. -
-
-
-
+![Main](/asset/gif/createProblem.gif) -### RESULT -![Main](/asset/img/figma-game-result.png) +### 마이 페이지 -
-
-
-
+- 간편한 회원 정보 수정을 제공합니다. +- 자신의 푼 문제와 레이팅 점수 등을 확인할 수 있습니다. -## 주요 기능 +![Main](/asset/gif/profile.gif) -### 메인 화면 -![Main](/asset/gif/Main.gif) +### 커뮤니티 게시판 -### 문제 풀이 +- 어려운 문제에 대해 이야기를 나눌 수 있는 커뮤니티를 제공합니다. -![Main](/asset/gif/ps.gif) +![Main](/asset/gif/community.gif) -### 마이 페이지 -![Main](/asset/gif/Mypage.gif) +- 누구나 자유롭게 질문 글을 작성할 수 있습니다. + +![Main](/asset/gif/question.gif) + + +### 아레나 메인페이지 + +- 아레나를 즐길 수 있는 페이지로 이동합니다. +- 경쟁을 매칭하거나, 방을 찾아 다른 사람의 게임을 관전할 수 있습니다. +- 인기 Hot Match 방을 소개합니다. +- 각 모드별 랭킹을 제공하고, 본인의 전적을 확인할 수 있습니다. + +![Main](/asset/gif/arenaMain.gif) + + +### 아레나 메칭 시스템 + +- 비슷한 Rating 점수를 가진 플레이어끼리 랜덤 매칭을 실시합니다. +- 유저는 원하는 언어, 모드를 선택하고 수락을 누르면 게임 방이 생성되어 이동합니다. + +![Main](/asset/gif/arena_match.gif) + + +### 아레나 스피드전 모드 + +- 아레나 스피드전 모드를 제공합니다. +- 먼저 제출해서 맞추는 사람이 승리하는 방식입니다. +- 시간이 모두 소요될 때까지 정답자가 나오지않는다면 무승부로 처리됩니다. + +![Main](/asset/gif/speed.gif) + + +### 아레나 효율전 모드 + +- 아레나 효율전 모드를 제공합니다. +- 먼저 제출해서 맞추는 사람이 승리하는 방식과는 달리 +- 제출한 코드 중 메모리와 시간이 가장 효율적인 코드를 제출한 사람이 승리합니다. +- 중간 채점 현황을 확인할 수 있도록 제공합니다. -### 아레나 통계 +![Main](/asset/gif/eff.gif) -![Main](/asset/gif/arena_main.gif) +![Main](/asset/gif/eff_ans.gif) -### 매칭 진행 -![Main](/asset/gif/매칭진행.gif) +### 아레나 게임 관전 -### 스피드전 진행, 화면공유 그리고 결과 +- 아레나 게임을 플레이하고있는 방을 관전할 수 있습니다. +- 플레이어의 화면 공유를 통하여 코딩 작성을 확인할 수 있습니다. +- 관전자들의 자유로운 소통을 위한 채팅을 제공합니다. -![Main](/asset/gif/스피드전진행.gif) +![Main](/asset/gif/observe.gif) -### 효율전 진행, 중간 채점현황 -![Main](/asset/gif/효율게임진행.gif) +### 아레나 게임 배팅 -### 관전자 배팅 및 채팅 +- 다른 플레이어들의 코딩 배틀을 관전하면서 포인트를 배팅할 수 있습니다. +- 자기가 건 플레이어가 승리한다면 포인트를 더욱 얻을 수 있습니다. +- 포인트 비율 참고 : 배팅 후 금액 + (배팅 금액 * (우승한 유저의 점수 + 1)) -![Main](/asset/gif/관전자,베팅.gif) \ No newline at end of file +![Main](/asset/gif/batting.gif) \ No newline at end of file diff --git a/asset/gif/Login.gif b/asset/gif/Login.gif index 89813fe7..52dd86ac 100644 Binary files a/asset/gif/Login.gif and b/asset/gif/Login.gif differ diff --git a/asset/gif/Main.gif b/asset/gif/Main.gif deleted file mode 100644 index 1de382ef..00000000 Binary files a/asset/gif/Main.gif and /dev/null differ diff --git a/asset/gif/Mypage.gif b/asset/gif/Mypage.gif deleted file mode 100644 index 1d0e6cf0..00000000 Binary files a/asset/gif/Mypage.gif and /dev/null differ diff --git a/asset/gif/arenaMain.gif b/asset/gif/arenaMain.gif new file mode 100644 index 00000000..de3c0b5c Binary files /dev/null and b/asset/gif/arenaMain.gif differ diff --git a/asset/gif/arena_main.gif b/asset/gif/arena_main.gif deleted file mode 100644 index 2c69d2a0..00000000 Binary files a/asset/gif/arena_main.gif and /dev/null differ diff --git a/asset/gif/arena_match.gif b/asset/gif/arena_match.gif new file mode 100644 index 00000000..9596bfda Binary files /dev/null and b/asset/gif/arena_match.gif differ diff --git a/asset/gif/batting.gif b/asset/gif/batting.gif new file mode 100644 index 00000000..35d99a35 Binary files /dev/null and b/asset/gif/batting.gif differ diff --git a/asset/gif/community.gif b/asset/gif/community.gif new file mode 100644 index 00000000..fee09366 Binary files /dev/null and b/asset/gif/community.gif differ diff --git a/asset/gif/createProblem.gif b/asset/gif/createProblem.gif new file mode 100644 index 00000000..0da26037 Binary files /dev/null and b/asset/gif/createProblem.gif differ diff --git a/asset/gif/eff.gif b/asset/gif/eff.gif new file mode 100644 index 00000000..9d191504 Binary files /dev/null and b/asset/gif/eff.gif differ diff --git a/asset/gif/eff_ans.gif b/asset/gif/eff_ans.gif new file mode 100644 index 00000000..de9ce421 Binary files /dev/null and b/asset/gif/eff_ans.gif differ diff --git a/asset/gif/goProblem.gif b/asset/gif/goProblem.gif new file mode 100644 index 00000000..1f9cf76e Binary files /dev/null and b/asset/gif/goProblem.gif differ diff --git a/asset/gif/mainpage.gif b/asset/gif/mainpage.gif new file mode 100644 index 00000000..61a21c95 Binary files /dev/null and b/asset/gif/mainpage.gif differ diff --git a/asset/gif/observe.gif b/asset/gif/observe.gif new file mode 100644 index 00000000..f84a2138 Binary files /dev/null and b/asset/gif/observe.gif differ diff --git a/asset/gif/problemCategory.gif b/asset/gif/problemCategory.gif new file mode 100644 index 00000000..d743f76a Binary files /dev/null and b/asset/gif/problemCategory.gif differ diff --git a/asset/gif/profile.gif b/asset/gif/profile.gif new file mode 100644 index 00000000..097f4d56 Binary files /dev/null and b/asset/gif/profile.gif differ diff --git a/asset/gif/ps.gif b/asset/gif/ps.gif deleted file mode 100644 index 392f5f43..00000000 Binary files a/asset/gif/ps.gif and /dev/null differ diff --git a/asset/gif/question.gif b/asset/gif/question.gif new file mode 100644 index 00000000..5df8d7e8 Binary files /dev/null and b/asset/gif/question.gif differ diff --git a/asset/gif/signup.gif b/asset/gif/signup.gif new file mode 100644 index 00000000..0b0cbdfa Binary files /dev/null and b/asset/gif/signup.gif differ diff --git a/asset/gif/solvingProblem.gif b/asset/gif/solvingProblem.gif new file mode 100644 index 00000000..43bf6e36 Binary files /dev/null and b/asset/gif/solvingProblem.gif differ diff --git a/asset/gif/speed.gif b/asset/gif/speed.gif new file mode 100644 index 00000000..9da80267 Binary files /dev/null and b/asset/gif/speed.gif differ diff --git "a/asset/gif/\352\264\200\354\240\204\354\236\220,\353\262\240\355\214\205.gif" "b/asset/gif/\352\264\200\354\240\204\354\236\220,\353\262\240\355\214\205.gif" deleted file mode 100644 index e5b88447..00000000 Binary files "a/asset/gif/\352\264\200\354\240\204\354\236\220,\353\262\240\355\214\205.gif" and /dev/null differ diff --git "a/asset/gif/\353\247\244\354\271\255\354\247\204\355\226\211.gif" "b/asset/gif/\353\247\244\354\271\255\354\247\204\355\226\211.gif" deleted file mode 100644 index 170c81a1..00000000 Binary files "a/asset/gif/\353\247\244\354\271\255\354\247\204\355\226\211.gif" and /dev/null differ diff --git "a/asset/gif/\354\212\244\355\224\274\353\223\234\354\240\204\354\247\204\355\226\211.gif" "b/asset/gif/\354\212\244\355\224\274\353\223\234\354\240\204\354\247\204\355\226\211.gif" deleted file mode 100644 index 1eafe0c4..00000000 Binary files "a/asset/gif/\354\212\244\355\224\274\353\223\234\354\240\204\354\247\204\355\226\211.gif" and /dev/null differ diff --git "a/asset/gif/\355\232\250\354\234\250\352\262\214\354\236\204\354\247\204\355\226\211.gif" "b/asset/gif/\355\232\250\354\234\250\352\262\214\354\236\204\354\247\204\355\226\211.gif" deleted file mode 100644 index aca7ae7d..00000000 Binary files "a/asset/gif/\355\232\250\354\234\250\352\262\214\354\236\204\354\247\204\355\226\211.gif" and /dev/null differ diff --git a/asset/img/Architecture.png b/asset/img/Architecture.png index 4ee07771..67707f34 100644 Binary files a/asset/img/Architecture.png and b/asset/img/Architecture.png differ diff --git a/back-end/Chatting/.gitignore b/back-end/Chatting/.gitignore deleted file mode 100644 index c2065bc2..00000000 --- a/back-end/Chatting/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -HELP.md -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/**/build/ -!**/src/test/**/build/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr -out/ -!**/src/main/**/out/ -!**/src/test/**/out/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ diff --git a/back-end/Chatting/Dockerfile b/back-end/Chatting/Dockerfile deleted file mode 100644 index d8c766e4..00000000 --- a/back-end/Chatting/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM openjdk:17-jdk-alpine -# FROM : 이미지 레이어의 최상단, alpine리눅스에 jdk 17을 사용한단 의미 - -WORKDIR /app -# WORKDIR : 스프링 부트 컨테이너 OS내에 어떤 디렉토리에서 jar을 실행 할 것인지 - -ARG JAR_FILE=build/libs/Chatting-0.0.1-SNAPSHOT.jar -# ARG : 변수지정, 변수에 적혀진 의미는 빌드 결과물 위치 - -COPY ${JAR_FILE} test.jar -# Auto Exctraction으로 압축된 파일을 해제하여 test.jar에 그 내용을 복사, 결국 스프링부트를 실행하는 컨테이너 내에는 test.jar가 있게 됨 - -ENTRYPOINT ["java", "-jar","test.jar","--encryptor.key=${ENV_KEY}"] -# ENTRYPOINT : 해당 컨테이너 시작할때 무조건 실행할 명령어 지정 \ No newline at end of file diff --git a/back-end/Chatting/build.gradle b/back-end/Chatting/build.gradle deleted file mode 100644 index 2a152768..00000000 --- a/back-end/Chatting/build.gradle +++ /dev/null @@ -1,46 +0,0 @@ -plugins { - id 'java' - id 'org.springframework.boot' version '3.2.2' - id 'io.spring.dependency-management' version '1.1.4' -} - -group = 'com.ssafy.codearena' -version = '0.0.1-SNAPSHOT' - -java { - sourceCompatibility = '17' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - implementation 'org.springframework.boot:spring-boot-starter-websocket' - implementation 'org.springframework.boot:spring-boot-devtools' - compileOnly 'org.projectlombok:lombok' - annotationProcessor 'org.projectlombok:lombok' -// implementation 'org.springframework.boot:spring-boot-starter-data-redis' - implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '3.0.3' - implementation group: 'com.mysql', name: 'mysql-connector-j', version: '8.0.33' - implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' //jasypt - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' //Swagger - //Openvidu - implementation group: 'io.openvidu', name: 'openvidu-java-client', version: '2.29.0' - implementation 'com.google.code.gson:gson:2.10.1' //gson - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '3.2.2'// webflux - - // jaxb 는 jwt를 사용하기 위한 의존성 - // com.sun.xml.bind - implementation 'com.sun.xml.bind:jaxb-impl:4.0.1' - implementation 'com.sun.xml.bind:jaxb-core:4.0.1' - // javax.xml.bind - implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359' - implementation 'io.jsonwebtoken:jjwt:0.9.1' -} - -tasks.named('test') { - useJUnitPlatform() -} diff --git a/back-end/Chatting/gradle/wrapper/gradle-wrapper.jar b/back-end/Chatting/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/back-end/Chatting/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/back-end/Chatting/gradle/wrapper/gradle-wrapper.properties b/back-end/Chatting/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1af9e093..00000000 --- a/back-end/Chatting/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/back-end/Chatting/gradlew b/back-end/Chatting/gradlew deleted file mode 100644 index 1aa94a42..00000000 --- a/back-end/Chatting/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/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/subprojects/plugins/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/back-end/Chatting/gradlew.bat b/back-end/Chatting/gradlew.bat deleted file mode 100644 index 93e3f59f..00000000 --- a/back-end/Chatting/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@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. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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/back-end/Chatting/settings.gradle b/back-end/Chatting/settings.gradle deleted file mode 100644 index c371f16e..00000000 --- a/back-end/Chatting/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'Chatting' diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/ChattingApplication.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/ChattingApplication.java deleted file mode 100644 index 495597f2..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/ChattingApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.codearena.Chatting; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -public class ChattingApplication { - - public static void main(String[] args) { - SpringApplication.run(ChattingApplication.class, args); - } - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/DataBaseConfiguration.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/DataBaseConfiguration.java deleted file mode 100644 index af8eeacf..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/DataBaseConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.ssafy.codearena.Chatting.config; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -import javax.sql.DataSource; - -@Configuration -@PropertySource("classpath:/application.properties") -@MapperScan(basePackages = {"com.ssafy.codearena.*.mapper"}) -public class DataBaseConfiguration { - - final ApplicationContext applicationContext; - // mapper.xml 위치를 Resource객체 로 들고오기 위해 - - public DataBaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - // ApplicationContext이 Bean을 관리하는 역할을 수행하고 - // SpringBootApplication이 실행될 때 @Configuration 어노테이션이 붙은 java파일을 설정정보로 등록한다. - // 이 때 @Bean으로 등록된 메서드들을 기반으로 빈 목록을 생성한다. - @ConfigurationProperties(prefix = "spring.datasource.hikari") - public HikariConfig hikariConfig() { - // application.properties 파일에서 spring.datasource.hikari로 시작하는 설정 값들을 가져와 Hikari 설정 객체를 반환한다. - return new HikariConfig(); - } - - @Bean - public DataSource dataSource() { - // HikariDataSource를 사용하기 위해 Hikari 설정 객체를 생성자로 넣은 HikariDataSource 객체 반환 - return new HikariDataSource(hikariConfig()); - } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { - // SqlSessionFactory는 Mybatis-spring 때 처럼 SqlSessionFactoryBean을 통해 생성되는데 - // 각종 typeAliase(DTO), mapperLocation(xml위치), DB접속정보(datasource)를 property를 통해 추가한다. - // 즉 setter를 통해 추가된다. - - SqlSessionFactoryBean session = new SqlSessionFactoryBean(); - session.setDataSource(dataSource); - session.setMapperLocations(applicationContext.getResources("classpath:mapper/**/*.xml")); - session.setTypeAliasesPackage("com.ssafy.codearena.*.dto"); - return session.getObject(); - } - - @Bean - public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { - // SqlSessionTemplate은 SqlSession인터페이스 타입의 객체이며 - // 결국 SqlSessionFactory의 각종 설정 정보를 통해 만들어지므로 생성자로 넣게 된다. - return new SqlSessionTemplate(sqlSessionFactory); - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/JasyptConfig.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/JasyptConfig.java deleted file mode 100644 index 48338467..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/JasyptConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ssafy.codearena.Chatting.config; - - -import org.jasypt.encryption.StringEncryptor; -import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class JasyptConfig { - - @Value("${encryptor.key}") - String KEY; - - private static final String ALGORITHM = "PBEWithMD5AndDES"; - - @Bean(name = "jasyptStringEncryptor") - public StringEncryptor stringEncryptor() { - PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); - SimpleStringPBEConfig config = new SimpleStringPBEConfig(); - - config.setPassword(KEY); //암호화 시 사용할 키 -> 이 키를 가지고 암호화 복호화 진행 - config.setAlgorithm(ALGORITHM); //사용할 알고리즘 - config.setKeyObtentionIterations("1000"); //반복할 해싱 회수 - config.setPoolSize("1"); //pool 크기 - config.setProviderName("SunJCE"); //사용할 암호화 라이브러리 - config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); //salt 생성 클래스 - config.setStringOutputType("base64"); //인코딩 방식 - encryptor.setConfig(config); //설정 주입 - - return encryptor; - - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/SwaggerConfig.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/SwaggerConfig.java deleted file mode 100644 index a35785f8..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/SwaggerConfig.java +++ /dev/null @@ -1,23 +0,0 @@ - -package com.ssafy.codearena.Chatting.config; -import io.swagger.v3.oas.models.Components; -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.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -@Configuration // 스프링 실행시 설정파일 읽어드리기 위한 어노테이션 -public class SwaggerConfig { - @Bean - public OpenAPI openAPI() { - return new OpenAPI().addServersItem(new Server().url("/")) - .components(new Components()) - .info(apiInfo()); - } - private Info apiInfo() { - return new Info() - .title("GameServer Swagger") - .description("채팅 및 openvidu 관련 게임 진행을 위한 서버") - .version("1.0.0"); - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/WebConfig.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/WebConfig.java deleted file mode 100644 index 05d16932..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/WebConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ssafy.codearena.Chatting.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebConfig implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOriginPatterns("*") - .allowCredentials(true) - .allowedMethods("GET", "POST", "PUT", "DELETE") - .allowedHeaders("Authorization", "Content-Type") - .exposedHeaders("Custom-Header", "Authorization") - .maxAge(3600); - } -} \ No newline at end of file diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/WebSockConfig.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/WebSockConfig.java deleted file mode 100644 index 43824e2e..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/config/WebSockConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ssafy.codearena.Chatting.config; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Configuration; -import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; -import org.springframework.web.socket.config.annotation.StompEndpointRegistry; -import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; - -@Slf4j -@Configuration -@EnableWebSocketMessageBroker -public class WebSockConfig implements WebSocketMessageBrokerConfigurer { - - - @Override - public void configureMessageBroker(MessageBrokerRegistry config) { - config.enableSimpleBroker("/sub"); - config.setApplicationDestinationPrefixes("/pub"); - } - - - @Override - public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/ws-stomp").setAllowedOriginPatterns("*").withSockJS(); - } - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/BattingController.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/BattingController.java deleted file mode 100644 index 04ad8a2e..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/BattingController.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.ssafy.codearena.Chatting.controller; - - -import com.ssafy.codearena.Chatting.dto.BatStatusDto; -import com.ssafy.codearena.Chatting.service.BattingService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -@RestController -@RequestMapping("/batting") -@RequiredArgsConstructor -public class BattingController { - - private final BattingService battingService; - - @Operation(summary = "배팅 API", description = "특정 유저에게 N금액만큼 배팅하는 로직") - @Parameters(value = { - @Parameter(name = "gameId", description = "게임방 ID"), - @Parameter(name = "userId", description = "배팅하는 유저 ID"), - @Parameter(name = "playerId", description = "배팅하려는 플레이어 ID"), - @Parameter(name = "batCoin", description = "배팅하려는 금액") - }) - @PostMapping("/player") - public ResponseEntity batPlayer(@RequestBody Map map) { - - return new ResponseEntity<>(battingService.batPlayer(map), HttpStatus.OK); - } - - @Operation(summary = "배팅 현황 조회 API", description = "게임방의 배팅 현황 조회 API") - @Parameters(value = { - @Parameter(name = "gameId", description = "게임방 ID"), - @Parameter(name = "player1Id", description = "플레이어1 ID"), - @Parameter(name = "player2Id", description = "플레이어2 ID") - }) - @ApiResponse(content = @Content(schema = @Schema(implementation = BatStatusDto.class))) - @GetMapping("/status") - public ResponseEntity getBatStatus(@RequestParam Map map) { - - return new ResponseEntity<>(battingService.getBatStatus(map), HttpStatus.OK); - } - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/ChatController.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/ChatController.java deleted file mode 100644 index a4167eb0..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/ChatController.java +++ /dev/null @@ -1,296 +0,0 @@ -package com.ssafy.codearena.Chatting.controller; -import com.ssafy.codearena.Chatting.dto.*; -import com.ssafy.codearena.Chatting.service.ChatService; -import io.swagger.v3.oas.annotations.Operation; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.messaging.handler.annotation.MessageMapping; -import org.springframework.messaging.simp.SimpMessageSendingOperations; -import org.springframework.stereotype.Controller; -import java.util.Objects; - -@Slf4j -@RequiredArgsConstructor -@Controller -public class ChatController { - private final SimpMessageSendingOperations messagingTemplate; - private final ChatService chatService; - @MessageMapping("chat/message") - public void message(ChatMessage message) { - String gameId = message.getGameId(); - log.info("메시지 수신"); - //관전 채팅방 참여 - if(message.getType() == ChatMessage.MessageType.ENTER) { - log.info(message.getSender() + "님이 " + message.getGameId() + "방에 참여했습니다."); - chatService.plusParticipants(gameId); - } - //관전 채팅방 대화 Publishing - else if (message.getType() == ChatMessage.MessageType.TALK) { - log.info("-----------TALK 타입으로 메시지 수신---------"); - log.info(message.getGameId()); - log.info(String.valueOf(message)); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), message); - } - //관전 채팅방 퇴장 REST API로 대체 -// else if(message.getType() == ChatMessage.MessageType.EXIT) { -// log.info(message.getSender() + "님이 " + message.getGameId() + "방에서 퇴장했습니다."); -// chatService.minusParticipants(gameId); -// } - - } - - @MessageMapping("chat/private/message") - public void privateMessage(ChatMessage message) { - String gameId = message.getGameId(); - log.info("메시지 수신"); - //관전 채팅방 참여 REST API로 대체 -// if(message.getType() == ChatMessage.MessageType.ENTER) { -// log.info(message.getSender() + "님이 " + message.getGameId() + "방에 참여했습니다."); -// message.setMessage(message.getSender() + "님이 " + message.getGameId() + "방에 참여했습니다."); -// chatService.plusCandidates(gameId, message.getSender()); -// -// messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), message); -// } - //관전 채팅방 대화 Publishing - if (message.getType() == ChatMessage.MessageType.TALK) { - log.info("-----------TALK 타입으로 메시지 수신---------"); - log.info(message.getGameId()); - log.info(String.valueOf(message)); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), message); - } - //사설 게임방 시작 타입 - else if(message.getType() == ChatMessage.MessageType.START) { - log.info(message.getGameId() + "방의 게임시작 요청이 도착했습니다"); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), chatService.startPrivateGame(message.getGameId())); - } - //관전 채팅방 퇴장 REST API로 대체 -// else if(message.getType() == ChatMessage.MessageType.EXIT) { -// log.info(message.getSender() + "님이 " + message.getGameId() + "방에서 퇴장했습니다."); -// chatService.minusParticipants(gameId); -// } - - } - - @MessageMapping("chat/private/kick") - public void playerKick(PlayerKickMessage message) { - - if(message.getType() == PlayerKickMessage.MessageType.KICK) { - chatService.minusCandidates(message.getGameId(), message.getUserId()); - } - - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), message.getUserId() + "님이 추방당하셨습니다."); - } - - @MessageMapping("chat/leave") - public void leave(ChatLeaveMessage message) { - log.info("메시지 수신"); - - SubmitResultMessage submitResultDto = new SubmitResultMessage(); - submitResultDto.setGameId(message.getGameId()); - - //유저 도중 퇴장 - if(message.getType() == ChatLeaveMessage.MessageType.PLAYER_EXIT) { - //두 명의 유저의 게임진행유무를 판별하고 - //두 사람 모두 나갔다면 TERMINATED - //한 사람만 나갔다면 경기 속행 - boolean flag = chatService.playerLeaveEvent(message.getGameId(), message.getUserId()); - - log.info(String.valueOf(flag)); - - //두 사람 모두 탈주한 경우 - if(flag) { - log.info("두 사람 모두 탈주하였습니다!!"); - //스피드전의 경우 무승부 처리 - if(message.getMode().equals("0")) { - - log.info("무승부 처리"); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(""); - submitResultDto.setResult("무승부 처리 되었습니다."); - terminateGame(message.getGameId(), ""); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - - //효율전의 경우 승패분기 탐색 - else if(message.getMode().equals("1")) { - //winner 탐색 - WinnerInfoDto winnerInfoDto = chatService.findWinner(message.getGameId()); - - if(Objects.isNull(winnerInfoDto)) { - terminateGame(message.getGameId(), ""); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(""); - submitResultDto.setResult("무승부 처리 되었습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - else { - terminateGame(message.getGameId(), winnerInfoDto.getUserNickname()); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(winnerInfoDto.getUserNickname()); - submitResultDto.setResult(winnerInfoDto.getUserNickname() + "님이 승리하였습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - } - return; - } - - //한 사람만 탈주한 경우 - log.info("한 사람만 탈주했습니다!!"); - submitResultDto.setType(SubmitResultMessage.resultType.CONTINUE); - submitResultDto.setWinner(""); - submitResultDto.setResult(message.getSender() + "님이 퇴장하였습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - //타임아웃 - else if(message.getType() == ChatLeaveMessage.MessageType.TERMINATED) { - - terminateGame(message.getGameId(), ""); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), message); - } - } - - - @MessageMapping("chat/leave/private") - public void leavePrivate(ChatLeaveMessage message) { - log.info("메시지 수신"); - - SubmitResultMessage submitResultDto = new SubmitResultMessage(); - submitResultDto.setGameId(message.getGameId()); - - //유저 도중 퇴장 - if(message.getType() == ChatLeaveMessage.MessageType.PLAYER_EXIT) { - // 유저의 게임진행유무를 판별하고 - // 사람이 모두 나갔다면 TERMINATED - // 한 사람이라도 남아있다면 경기 속행 - boolean flag = chatService.playerLeaveEvent(message.getGameId(), message.getSender()); - - // 모두 탈주한 경우 - if(flag) { - - //스피드전의 경우 무승부 처리 - if(message.getMode().equals("0")) { - - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(""); - submitResultDto.setResult("무승부 처리 되었습니다."); - terminateGame(message.getGameId(), ""); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - - //효율전의 경우 승패분기 탐색 - else if(message.getMode().equals("1")) { - //winner 탐색 - WinnerInfoDto winnerInfoDto = chatService.findWinner(message.getGameId()); - - if(Objects.isNull(winnerInfoDto)) { - terminateGame(message.getGameId(), ""); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(message.getSender()); - submitResultDto.setResult("무승부 처리 되었습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - else { - terminateGame(message.getGameId(), winnerInfoDto.getUserId()); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(message.getSender()); - submitResultDto.setResult(winnerInfoDto.getUserNickname() + "님이 승리하였습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - } - return; - } - - //한 사람만 탈주한 경우 - - submitResultDto.setType(SubmitResultMessage.resultType.CONTINUE); - submitResultDto.setWinner(""); - submitResultDto.setResult(message.getSender() + "님이 퇴장하였습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - //타임아웃 - else if(message.getType() == ChatLeaveMessage.MessageType.TERMINATED) { - log.info("타임아웃 메시지 도착"); - if(message.getMode().equals("0")) { - log.info("스피드전 타임아웃 메시지 도착"); - - terminateGame(message.getGameId(), ""); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), message); - } - //효율전의 경우 승패분기 탐색 - else if(message.getMode().equals("1")) { - log.info("효율전 메시지 도착"); - - //winner 탐색 - WinnerInfoDto winnerInfoDto = chatService.findWinner(message.getGameId()); - - if(Objects.isNull(winnerInfoDto)) { - terminateGame(message.getGameId(), ""); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(""); - submitResultDto.setResult("무승부 처리 되었습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - else { - terminateGame(message.getGameId(), winnerInfoDto.getUserId()); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setWinner(message.getSender()); - submitResultDto.setResult(winnerInfoDto.getUserNickname() + "님이 승리하였습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - } - } - } - - - @Operation(summary = "플레이어 제출 결과에 따른 분기") - @MessageMapping("chat/submit") - public void submit(ChatSubmitMessage message) { - String gameId = message.getGameId(); - log.info("메시지 수신"); - - log.info(String.valueOf(message)); - - //스피드전 - if(message.getMode() == ChatSubmitMessage.MessageType.SPEED) { - //승패 분기 - if(message.getResult().equals("맞았습니다")) { - SubmitResultMessage submitResultDto = new SubmitResultMessage(); - submitResultDto.setType(SubmitResultMessage.resultType.END); - submitResultDto.setGameId(message.getGameId()); - submitResultDto.setWinner(message.getSender()); - submitResultDto.setResult(message.getSender() + "님이 승리하였습니다."); - terminateGame(message.getGameId(), message.getSender()); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - //경기 속행 시 별다른 메시지는 보내지 않음. - else { - - SubmitResultMessage submitResultDto = new SubmitResultMessage(); - submitResultDto.setType(SubmitResultMessage.resultType.CONTINUE); - submitResultDto.setGameId(message.getGameId()); - submitResultDto.setWinner(message.getSender()); - submitResultDto.setResult(message.getSender() + "님이 제출하였지만 틀렸습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - } - } - - //효율전 - else if(message.getMode() == ChatSubmitMessage.MessageType.EFFI){ - SubmitResultMessage submitResultDto = new SubmitResultMessage(); - submitResultDto.setType(SubmitResultMessage.resultType.CONTINUE); - submitResultDto.setGameId(message.getGameId()); - submitResultDto.setWinner(message.getSender()); - submitResultDto.setResult(message.getSender() + "님이 코드를 제출하였습니다."); - messagingTemplate.convertAndSend("/sub/chat/room/" + message.getGameId(), submitResultDto); - - } - - } - - public void terminateGame(String gameId, String winner) { - //winner는 승자의 ID값 - - chatService.terminateGame(gameId, winner); - } - -} \ No newline at end of file diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/ChatRoomController.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/ChatRoomController.java deleted file mode 100644 index 79418c1e..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/ChatRoomController.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.ssafy.codearena.Chatting.controller; -import com.ssafy.codearena.Chatting.dto.*; -import com.ssafy.codearena.Chatting.service.ChatService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.coyote.Response; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import java.util.*; - -@Tag(name = "채팅방 REST API", description = "채팅방 조회 및 생성 등 API") -@RequiredArgsConstructor -@RestController -@Slf4j -@RequestMapping("/chat") -public class ChatRoomController { - private final ChatService chatService; - //특정 채팅방 반환 - @Operation(summary = "특정 게임방 상세조회 API") - @Parameters(value = { - @Parameter(name = "gameId", description = "게임방 ID"), - }) - @GetMapping("/room") - public ResponseEntity room(@RequestParam String gameId) { -// log.info(gameId); - return new ResponseEntity(chatService.findRoomById(gameId), HttpStatus.OK); - } - //모든 채팅방 목록 반환 - @GetMapping("/rooms") - public ResponseEntity room(@RequestParam Map map) { - log.info(map.get("key")); - return new ResponseEntity(chatService.findAllRoom(map), HttpStatus.OK); - } - - @GetMapping("/exit") - public ResponseEntity exit(@RequestParam String gameId) { - - chatService.minusParticipants(gameId); - return new ResponseEntity("퇴장", HttpStatus.OK); - } - - @GetMapping("/enter") - public ResponseEntity enter(@RequestParam String gameId) { - - chatService.plusParticipants(gameId); - return new ResponseEntity<>("입장", HttpStatus.OK); - } - @GetMapping("/exit/private") - public ResponseEntity exitPrivate(@RequestParam String gameId, String userId) { - - chatService.minusCandidates(gameId, userId); - return new ResponseEntity("퇴장", HttpStatus.OK); - } - //관전 채팅방 생성 - //매칭 서버에서 요청받는 엔드포인트 - //받는 데이터로는 RandomUUID 두 유저의 ID값, 게임 타입, 사용 언어 - //응답 데이터 : - @Operation(summary = "경쟁 게임방 생성 API") - @Parameters(value = { - @Parameter(name = "gameId", description = "매칭 ID", example = "Random.UUID"), - @Parameter(name = "title", description = "게임방 제목", example = "player1닉네임 vs player2닉네임"), - @Parameter(name = "userRed", description = "Player1 ID"), - @Parameter(name = "userBlue", description = "Player2 ID"), - @Parameter(name = "gameMode", description = "게임 모드 2가지", example = "1 : 스피드전, 2 : 효율전"), - @Parameter(name = "language", description = "게임 사용 언어", example = "java") - }) - @ApiResponse(description = "두 유저에게 전달될 응답 값", content = @Content(schema = @Schema(implementation = CreateCompetitiveResultDto.class))) - @PostMapping("/gameroom") - public GameResultDto createGameRoom(@RequestBody GameCreateDto gameCreateDto) { - return chatService.createCompetitiveRoom(gameCreateDto); - } - - @Operation(summary = "사설 게임방 생성 API") - @Parameters(value = { - @Parameter(name = "gameId", description = "매칭 ID", example = "Random.UUID"), - @Parameter(name = "title", description = "게임방 제목", example = "알고리즘 고수들 모여라"), - @Parameter(name = "userId", description = "방장 ID"), - @Parameter(name = "gameMode", description = "게임 모드 2가지", example = "1 : 스피드전, 2 : 효율전"), - @Parameter(name = "language", description = "게임 사용 언어", example = "java"), - }) - @ApiResponse(description = "두 유저에게 전달될 응답 값", content = @Content(schema = @Schema(implementation = CreateCompetitiveResultDto.class))) - @PostMapping("/gameroom/private") - public GameResultDto createPrivateGameRoom(@RequestBody PrivateGameCreateDto privateGameCreateDto) { - return chatService.createPrivateRoom(privateGameCreateDto); - } - - @GetMapping("/hotmatch") - public List getTopMatch() { - List list = chatService.getTopFiveMatch(); - - return list; - - } - - @Operation(summary = "사설 게임방 입장 가능 여부 조회 API") - @Parameter(name = "gameId", description = "참여하려는 게임방의 ID") - @ApiResponse(content = @Content(schema = @Schema(implementation = RestResultDto.class))) - @GetMapping("/enter/room") - public ResponseEntity isEnter(@RequestParam String gameId) { - - return new ResponseEntity(chatService.getCandidates(gameId), HttpStatus.OK); - } - - @Operation(summary = "경쟁 게임방 결과 조회 API") - @Parameter(name = "gameId") - @GetMapping("/result") - public ResponseEntity whoWinner(@RequestParam String gameId) { - - return new ResponseEntity(chatService.whoWinner(gameId), HttpStatus.OK); - } - -} \ No newline at end of file diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/GameRestController.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/GameRestController.java deleted file mode 100644 index d85e72c7..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/GameRestController.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.ssafy.codearena.Chatting.controller; - -import com.ssafy.codearena.Chatting.dto.CompetitiveResultDto; -import com.ssafy.codearena.Chatting.dto.GameResultDto; -import com.ssafy.codearena.Chatting.dto.RestResultDto; -import com.ssafy.codearena.Chatting.dto.SubmitDto; -import com.ssafy.codearena.Chatting.service.RestService; -import jakarta.servlet.http.HttpServletRequest; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import lombok.RequiredArgsConstructor; -import org.apache.coyote.Response; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -@org.springframework.web.bind.annotation.RestController -@RequestMapping("/rest") -@RequiredArgsConstructor -public class GameRestController { - - private final RestService service; - @PostMapping("/submit") - ResponseEntity submitEff(@RequestBody SubmitDto submitDto) { - // roomType 0 : 경쟁, roomType : 1 사설 - RestResultDto resultDto = service.insertSubmit(submitDto); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @GetMapping("/rank") - ResponseEntity getRanking() { - RestResultDto resultDto = service.getRanking(); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @GetMapping("/user/record") - ResponseEntity getRecords(HttpServletRequest request){ - RestResultDto resultDto = service.getMyRecord(request); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @Operation(summary = "경쟁전 게임결과 조회 API", description = "스피드전 효율전 상관없이 gameId로 해당 정보 조회") - @Parameter(name = "gameId", description = "결과 조회하려는 게임방 ID") - @ApiResponse(responseCode = "200", description = "두 플레이어에 대한 정보까지 한번에 조회", content = @Content(schema = @Schema(implementation = CompetitiveResultDto.class))) - @GetMapping("/competitive/result/{gameId}") - ResponseEntity getCompetitiveResult(@PathVariable String gameId) { - - return new ResponseEntity(service.getCompetitiveResult(gameId), HttpStatus.OK); - } - - @GetMapping("/effi/list") - ResponseEntity getEffiSubmitList(@RequestParam Map map) { - - return new ResponseEntity(service.getEffiSubmitList(map), HttpStatus.OK); - } - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/OpenviduController.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/OpenviduController.java deleted file mode 100644 index 29fac784..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/controller/OpenviduController.java +++ /dev/null @@ -1,101 +0,0 @@ - -package com.ssafy.codearena.Chatting.controller; -import io.openvidu.java.client.*; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.annotation.PostConstruct; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -//import io.openvidu.java.client.Session; -import java.util.HashMap; -import java.util.Map; -@Tag(name = "Openvidu 사용을 위한 컨트롤러", description = "Openvidu 세션 생성 및 연결요청 API") -@Slf4j -@RestController -@RequestMapping("/vidu") -public class OpenviduController { - @Value("${OPENVIDU_URL}") - private String OPENVIDU_URL; - @Value("${OPENVIDU_SECRET}") - private String OPENVIDU_SECRET; - private OpenVidu openvidu; - @PostConstruct - public void init() { - this.openvidu = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET); - } - /** - * @param params The Session properties - * @return The Session ID - */ - @Operation(summary = "방 생성", description = "파라메터로 받은 customSessionId 값을 기준으로 방 생성") - @Parameter(name = "customSessionId", description = "생성하고자 하는 방의 커스텀 세션 ID값") - @PostMapping("/sessions") - public ResponseEntity initializeSession(@RequestBody(required = false) Map params) - throws OpenViduJavaClientException, OpenViduHttpException { - SessionProperties properties = SessionProperties.fromJson(params).build(); - - log.info(String.valueOf(properties)); - try { - Session session = openvidu.createSession(properties); - return new ResponseEntity<>(session.getSessionId(), HttpStatus.OK); - } - catch (Exception e) { - log.error("Exception Msg", e); - return new ResponseEntity<>("이미 존재하는 게임방 ID입니다.", HttpStatus.OK); - } - - } - /** - * @param sessionId The Session in which to create the Connection - * @param params The Connection properties - * @return The Token associated to the Connection - */ - @Operation(summary = "방 입장", description = "해당하는 세션ID를 가진 방에 입장") - @Parameters(value = { - @Parameter(name = "sessionId", description = "PathVariable"), - @Parameter(name = "Connection Properties", description = "연결에 필요한 설정값") - }) - @ApiResponse(responseCode = "200", description = "The Token associated to the Connection") - @PostMapping("/sessions/{sessionId}/connections") - public ResponseEntity createConnection(@PathVariable("sessionId") String sessionId, - @RequestBody(required = false) Map params) - throws OpenViduJavaClientException, OpenViduHttpException { - Session session = null; - - try { - - session = openvidu.getActiveSession(sessionId); - } - catch (Exception e) { - - log.info("세션을 가져오는 과정에서 문제가 발생했습니다."); - log.error("Exception Msg", e); - return new ResponseEntity<>("입장코드를 통해 세션을 불러오는 과정에서 예기치 못한 오류가 발생했습니다.", HttpStatus.OK); - } - - if (session == null) { - return new ResponseEntity<>("해당하는 방이 존재하지 않습니다.", HttpStatus.NOT_FOUND); - } - - ConnectionProperties properties = ConnectionProperties.fromJson(params).build(); - - Connection connection = null; - try { - - connection = session.createConnection(properties); - } - catch (Exception e) { - - log.info("스트리밍 세션에 접속하는 과정에서 예기치 못한 오류가 발생했습니다."); - log.error("Exception Msg", e); - return new ResponseEntity<>("스트리밍 세션에 접속하는 과정에서 예기치 못한 오류가 발생했습니다.", HttpStatus.OK); - } - return new ResponseEntity<>(connection.getToken(), HttpStatus.OK); - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ArenaProblemDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ArenaProblemDto.java deleted file mode 100644 index 75789985..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ArenaProblemDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class ArenaProblemDto { - String problemId; - String problemTitle; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatPlayerCountDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatPlayerCountDto.java deleted file mode 100644 index 0588ba93..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatPlayerCountDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class BatPlayerCountDto { - private int player1Count; - private int player2Count; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatStatusDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatStatusDto.java deleted file mode 100644 index 12336859..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatStatusDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -public class BatStatusDto { - @Schema(description = "플레이어1에 대한 배팅 비율") - private String player1Ratio; - @Schema(description = "플레이어2에 대한 배팅 비율") - private String player2Ratio; - @Schema(description = "플레이어1에 투자한 사람의 총합") - private String player1BatPeople; - @Schema(description = "플레이어2에 투자한 사람의 총합") - private String player2BatPeople; - @Schema(description = "플레이어1에 대한 배팅 최고 금액") - private String player1MaxCoin; - @Schema(description = "플레이어2에 대한 배팅 최고 금액") - private String player2MaxCoin; - @Schema(description = "플레이어1에 대한 최고 금액을 배팅한 유저의 닉네임") - private String player1MaxUserNickname; - @Schema(description = "플레이어2에 대한 최고 금액을 배팅한 유저의 닉네임") - private String player2MaxUserNickname; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatUserCoinDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatUserCoinDto.java deleted file mode 100644 index 661caa6c..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/BatUserCoinDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class BatUserCoinDto { - private String userId; - private String userCoin; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatLeaveMessage.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatLeaveMessage.java deleted file mode 100644 index 74e7d102..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatLeaveMessage.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class ChatLeaveMessage { - public enum MessageType { - PLAYER_EXIT, TERMINATED; - } - - private MessageType type; - private String gameId; - private String mode; - private String userId; - private String sender; - private String message; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatMessage.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatMessage.java deleted file mode 100644 index 17f4160f..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatMessage.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class ChatMessage { - - public enum MessageType { - ENTER, TALK, START, EXIT; - } - - private MessageType type; - private String gameId; - private String sender; - private String message; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatSubmitMessage.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatSubmitMessage.java deleted file mode 100644 index 1eb6a549..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/ChatSubmitMessage.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class ChatSubmitMessage { - - public enum MessageType { - SPEED, EFFI; - } - - private MessageType mode; - private String gameId; - private String sender; - private String result; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveGameResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveGameResultDto.java deleted file mode 100644 index 2a27ac90..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveGameResultDto.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class CompetitiveGameResultDto { - private String winnerId; - private String winnerRating; - private String winnerSsumnail; - private String loserId; - private String loserRating; - private String loserSsumnail; - private List list; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveGameSubmitDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveGameSubmitDto.java deleted file mode 100644 index 43a7a01b..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveGameSubmitDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class CompetitiveGameSubmitDto { - private String submitNo; - private String userId; - private String userNickname; - private String problemId; - private String gameType; - private String submitLang; - private String submitStatus; - private String timeComplexity; - private String memory; - private String submitDate; - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveManageDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveManageDto.java deleted file mode 100644 index 67c50419..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveManageDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class CompetitiveManageDto implements Comparable{ - private String gameId; - private int Participants; - private String player1; - private String player2; - private String roomType; - private String gamemode; - private boolean player1_leave; - private boolean player2_leave; - - @Override - public int compareTo(CompetitiveManageDto competitiveManageDto) { - return (competitiveManageDto.getParticipants() - this.Participants); - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveResultDto.java deleted file mode 100644 index 602da65d..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveResultDto.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Schema(description = "경쟁 게임 결과 조회 DTO") -@Data -public class CompetitiveResultDto { - @Schema(description = "게임방 ID") - private String gameId; - @Schema(description = "문제 번호") - private String problemId; - @Schema(description = "게임방 제목") - private String gameTitle; - @Schema(description = "시작 시각") - private String startTime; - @Schema(description = "종료 시각") - private String endTime; - @Schema(description = "게임 모드 2가지 ( 0 : 스피드전, 1 : 효율전") - private String gameMode; - @Schema(description = "게임 진행 언어") - private String gameLang; - @Schema(description = "이긴 사람의 닉네임, 무승부 시 '무승부' String값 반환") - private String winner; - @Schema(description = "게임방 종류 2가지 ( 0 : 경쟁, 1 : 사설") - private String roomType; - @Schema(description = "플레이어 1 ID값(int)") - private String player1Id; - @Schema(description = "플레이어 2 ID값(int)") - private String player2Id; - @Schema(description = "플레이어 1 썸네일") - private String player1Ssumnail; - @Schema(description = "플레이어 2 썸네일") - private String player2Ssumnail; - @Schema(description = "플레이어 1 닉네임") - private String player1Nickname; - @Schema(description = "플레이어 2 닉네임") - private String player2Nickname; - - @Schema(description = "플레이어 1 레이팅 (게임 모드에 따른 레이팅값") - private String player1Rating; - @Schema(description = "플레이어 2 레이팅 (게임 모드에 따른 레이팅값") - private String player2Rating; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveTopMatchResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveTopMatchResultDto.java deleted file mode 100644 index c6328bfd..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveTopMatchResultDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class CompetitiveTopMatchResultDto { - private String gameId; - private String player1Nickname; - private String player2Nickname; - private String player1Rating; - private String player2Rating; - private String player1Ssumnail; - private String player2Ssumnail; - private int Participants; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveUserInfoDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveUserInfoDto.java deleted file mode 100644 index 25e73945..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveUserInfoDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class CompetitiveUserInfoDto { - private String userNickname; - private String userSsumnail; - private String userRating; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveWinnerInfoDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveWinnerInfoDto.java deleted file mode 100644 index 174ca5d3..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CompetitiveWinnerInfoDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class CompetitiveWinnerInfoDto { - private String player1; - private String player2; - private String winner; - private String game_mode; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CreateCompetitiveResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CreateCompetitiveResultDto.java deleted file mode 100644 index f57ea6cc..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/CreateCompetitiveResultDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class CreateCompetitiveResultDto { - private String gameId; - private String problemId; - private String viduSession; - private String startTime; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/EffiSubmitListDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/EffiSubmitListDto.java deleted file mode 100644 index 0b610db9..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/EffiSubmitListDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class EffiSubmitListDto { - private int currentPage; - private int totalPageCount; - private List list; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameCreateDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameCreateDto.java deleted file mode 100644 index 3381ed00..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameCreateDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class GameCreateDto { - private String gameId; //게임방 ID - private String title; //게임방 제목 - private String userRed; //플레이어 1 - private String userBlue; //플레이어 2 - private String problemId; //배정된 랜덤 문제 번호 - private String roomType; //방 타입 2가지 (경쟁, 사설) - private String gameMode; //게임 모드 2가지 (스피드전, 효율전) - private String language; //게임 사용 언어 -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameInfoDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameInfoDto.java deleted file mode 100644 index d12a2522..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameInfoDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class GameInfoDto { - private String gameId; //게임방 ID - private String title; //게임방 제목 - private String userRed; //플레이어 1 - private String userBlue; //플레이어 2 - private String userRedNickname; //플레이어 1 닉네임 - private String userBlueNickname; //플레이어 2 닉네임 - private String userRedSsumnail; //플레이어 1 썸네일 - private String userBlueSsumnail; //플레이어 2 썸네일 - private String userRedSpeedRating; //플레이어 1 스피드레이팅점수 - private String userBlueSpeedRating; //플레이어 1 스피드레이팅점수 - private String userRedEffiRating; //플레이어 1 효율레이팅점수 - private String userBlueEffiRating; //플레이어 2 효율레이팅점수 - private String problemId; //배정된 랜덤 문제 번호 - private String gameMode; //게임 모드 2가지 (스피드전, 효율전) - private int participants; //채팅 참여자 수 - private String startTime; //게임 시작 시간 - private String language; //게임 사용 언어 - private String roomType; //게임 방 타입 2가지 (경쟁전, 사설) -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameListDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameListDto.java deleted file mode 100644 index 33712ad1..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameListDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class GameListDto { - private List gameRooms; - private int CurrentPage; - private int TotalPageCount; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GamePlayerDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GamePlayerDto.java deleted file mode 100644 index af5c56e0..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GamePlayerDto.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class GamePlayerDto { - String userId; - String userNickname; - String effRating; - String speedRating; - String point; - UserRecordDto record; - List recentMatches; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameRecordDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameRecordDto.java deleted file mode 100644 index 9507d2fd..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameRecordDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class GameRecordDto { - String gameId; - String problemId; - String problemTitle; - String player1; - String player2; - String player3; - String player4; - String gameMode; - String winner; - String roomType; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameResultDto.java deleted file mode 100644 index 6f24c5f0..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/GameResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class GameResultDto { - private String status; - private String msg; - private Object data; -} \ No newline at end of file diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/MaxBatUserInfoDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/MaxBatUserInfoDto.java deleted file mode 100644 index 27106891..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/MaxBatUserInfoDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class MaxBatUserInfoDto { - private String userNickname; - private String userCoin; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PlayerKickMessage.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PlayerKickMessage.java deleted file mode 100644 index 305385f6..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PlayerKickMessage.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class PlayerKickMessage { - public enum MessageType { - KICK; - } - private MessageType type; - private String gameId; - private String userId; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PrivateGameCreateDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PrivateGameCreateDto.java deleted file mode 100644 index 6236af64..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PrivateGameCreateDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class PrivateGameCreateDto { - private String gameId; //게임방 ID - private String title; //게임방 제목 - private String userId; //방장 ID - private String gameMode; //게임 모드 2가지 (스피드전, 효율전) - private String language; //게임 사용 언어 - private String roomType; //방 타입 2가지 (경쟁, 사설) - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PrivateManageDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PrivateManageDto.java deleted file mode 100644 index b481abb7..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/PrivateManageDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class PrivateManageDto implements Comparable{ - private String gameId; - private int Participants; - private String player1; - private String player2; - private String player3; - private String player4; - private String roomType; - private String gamemode; - private boolean player1_leave; - private boolean player2_leave; - private boolean player3_leave; - private boolean player4_leave; - - @Override - public int compareTo(PrivateManageDto privateManageDto) { - return (privateManageDto.getParticipants() - this.Participants); - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/RestResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/RestResultDto.java deleted file mode 100644 index 8c15b0ee..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/RestResultDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class RestResultDto { - String status; - String msg; - Object data; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/SubmitDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/SubmitDto.java deleted file mode 100644 index 55e493f7..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/SubmitDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class SubmitDto { - // submit_no, user_id, game_id, problem_id, submit_lang, code, submit_status, time_complexity, memory, submit_date - String submitNo; - String userId; - String gameId; - String problemId; - String submitLang; - String code; - String submitStatus; - String timeComplexity; - String memory; - String submitDate; - String gameType; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/SubmitResultMessage.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/SubmitResultMessage.java deleted file mode 100644 index 3477c856..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/SubmitResultMessage.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class SubmitResultMessage { - public enum resultType { - CONTINUE, END; - } - - private resultType type; - private String gameId; - private String winner; - private String result; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/Top5RatingResultDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/Top5RatingResultDto.java deleted file mode 100644 index 884ef466..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/Top5RatingResultDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -import java.util.List; - - -@Data -public class Top5RatingResultDto { - List effRank; - List speedRank; - List pointRank; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/UserDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/UserDto.java deleted file mode 100644 index ee1239a6..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/UserDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class UserDto { - String userId; - String userNickname; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/UserRecordDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/UserRecordDto.java deleted file mode 100644 index 92dbaa96..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/UserRecordDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - - -import lombok.Data; - -@Data -public class UserRecordDto { - int defeatCount; - int winCount; - int drawCount; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/WinnerInfoDto.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/WinnerInfoDto.java deleted file mode 100644 index 17be3417..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/dto/WinnerInfoDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.Chatting.dto; - -import lombok.Data; - -@Data -public class WinnerInfoDto { - private String userId; - private String userNickname; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/BattingMapper.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/BattingMapper.java deleted file mode 100644 index cf479fb7..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/BattingMapper.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.codearena.Chatting.mapper; - -import com.ssafy.codearena.Chatting.dto.BatPlayerCountDto; -import com.ssafy.codearena.Chatting.dto.BatUserCoinDto; -import com.ssafy.codearena.Chatting.dto.MaxBatUserInfoDto; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.jdbc.SQL; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -@Mapper -public interface BattingMapper { - public int getUserCoin(String userId) throws Exception; - public void updateUserCoin(String userId, String coin) throws Exception; - public void updateUserPlusCoin(String userId, int coin) throws Exception; - public void batPlayer(Map map) throws Exception; - public BatPlayerCountDto getPlayerCount(Map map) throws Exception; - public List getUserBatCoin(String gameId, String winner) throws SQLException; - public MaxBatUserInfoDto getMaxBatUser(String gameId, String playerId) throws SQLException; - public int getPlayerSumPeople(String gameId, String playerId) throws SQLException; - public int getUserBatStatus(String gameId, String userId) throws SQLException; - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/GameMapper.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/GameMapper.java deleted file mode 100644 index 0108881f..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/GameMapper.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ssafy.codearena.Chatting.mapper; - -import com.ssafy.codearena.Chatting.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -@Mapper -public interface GameMapper { - public int findProblemById() throws Exception; - public GameInfoDto findRoomById(String gameId) throws Exception; - public List findAllRoom(Map map) throws Exception; - public int getTotalGameCount(Map map) throws Exception; - public void createCompetitiveRoom(GameCreateDto gameCreateDto) throws Exception; - public void createPrivateRoom(PrivateGameCreateDto privateGameCreateDto) throws Exception; - public void terminateGame(String gameId, String winner) throws Exception; - public int passProblem(String gameId, String player1, String player2) throws Exception; - public WinnerInfoDto winnerSearch(String gameId) throws Exception; - public int isRating(Map param) throws Exception; - public void refreshRating(String userId, String rating, String gamemode) throws Exception; - public CompetitiveUserInfoDto getUserInfo(String userId, String gamemode) throws Exception; - public void startPrivateGame(Map param) throws Exception; - public CompetitiveWinnerInfoDto whoWinner(String gameId) throws Exception; - public List getSubmitList(String gameId) throws Exception; - public String getUserNickname(String userId) throws Exception; - public String getStartTime(String gameId) throws Exception; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/RestMapper.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/RestMapper.java deleted file mode 100644 index 7545b21e..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/mapper/RestMapper.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ssafy.codearena.Chatting.mapper; - - -import com.ssafy.codearena.Chatting.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -@Mapper -public interface RestMapper { - void insertSubmit(SubmitDto submitDto) throws SQLException; - List getEffRankingbyRating() throws SQLException; - List getSpeedRankingByRating() throws SQLException; - - List getPointRankingByPoint() throws SQLException; - - GamePlayerDto getUserRecordByUserId(String userId) throws SQLException; - - CompetitiveResultDto getGameInfo(String gameId) throws Exception; - CompetitiveUserInfoDto getPlayerInfo(String userId, String gameMode) throws Exception; - List getRecordsByUserId(String userId) throws SQLException; - List getEffiSubmitList(Map param) throws Exception; - int getTotalSubmitCount(Map param) throws Exception; -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/BattingService.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/BattingService.java deleted file mode 100644 index f45cd0ee..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/BattingService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.Chatting.service; - -import com.ssafy.codearena.Chatting.dto.BatStatusDto; -import com.ssafy.codearena.Chatting.dto.RestResultDto; - -import java.util.Map; - -public interface BattingService { - public RestResultDto batPlayer(Map map); - public RestResultDto getBatStatus(Map map); -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/BattingServiceImpl.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/BattingServiceImpl.java deleted file mode 100644 index b2ffb2cb..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/BattingServiceImpl.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.ssafy.codearena.Chatting.service; - -import com.ssafy.codearena.Chatting.dto.*; -import com.ssafy.codearena.Chatting.mapper.BattingMapper; -import com.ssafy.codearena.Chatting.mapper.GameMapper; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Service -@Slf4j -@RequiredArgsConstructor -public class BattingServiceImpl implements BattingService{ - - private final BattingMapper battingMapper; - - @Override - public RestResultDto batPlayer(Map map) { - - RestResultDto resultDto = new RestResultDto(); - resultDto.setStatus("201"); - resultDto.setMsg("배팅 성공"); - resultDto.setData(null); - - try { - - log.info("유저가 배팅 시도를 했습니다!"); - log.info(map.get("userId")); - log.info(map.get("gameId")); - - //유저가 배팅한 기록이 있는지 조회 - int cnt = battingMapper.getUserBatStatus(map.get("gameId"), map.get("userId")); - - if(cnt > 0) { - - throw new Error("배팅을 1회이상 시도하였습니다."); - } - - int userCoin = battingMapper.getUserCoin(map.get("userId")); //해당 유저의 현재 코인 조회 - - //가지고 있는 금액보다 높게 배팅할 시 - if(Integer.parseInt(map.get("batCoin")) > userCoin) { - - throw new Error("Error : 현재 보유중인 코인보다 높은 배팅"); - } - // 차감된 유저 코인 금액 적용 - String batCoin = map.get("batCoin"); - String changeCoin = Integer.toString(userCoin - Integer.parseInt(batCoin)); - battingMapper.updateUserCoin(map.get("userId"), changeCoin); - - // 배팅 기록 - battingMapper.batPlayer(map); - } - catch (Error e) { - - log.error("Exception Msg", e); - resultDto.setStatus("500"); - resultDto.setMsg(String.valueOf(e)); - resultDto.setData(null); - } - - catch (Exception e) { - - resultDto.setStatus("500"); - resultDto.setMsg("Server Internal Error"); - log.error("Exception Msg", e); - } - - return resultDto; - } - - - @Override - public RestResultDto getBatStatus(Map map) { - - RestResultDto resultDto = new RestResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("배팅현황 조회 성공"); - - try { - //배팅 현황 필요 데이터 : - //각각 플레이어의 투자인원 조회 - BatStatusDto batStatusDto = new BatStatusDto(); - - BatPlayerCountDto batPlayerCountDto = battingMapper.getPlayerCount(map); - - //총 투자 인원 - double sum = batPlayerCountDto.getPlayer1Count() + batPlayerCountDto.getPlayer2Count(); //115명 - - double player1_ratio = (double)1 - ((double) batPlayerCountDto.getPlayer2Count()/sum); //1 -> 0.3 >> 30% - double player2_ratio = (double)1 - ((double) batPlayerCountDto.getPlayer1Count()/sum); //1 -> 0.3 >> 30% - - int player1Ratio = (int) Math.round(player1_ratio*100); - int player2Ratio = (int) Math.round(player2_ratio*100); - - log.info("플레이어 1의 비율 : " + player1_ratio); - log.info("플레이어 2의 비율 : " + player2_ratio); - batStatusDto.setPlayer1Ratio(String.valueOf(player1Ratio)); - batStatusDto.setPlayer2Ratio(String.valueOf(player2Ratio)); - - //최고 금액 투자한 유저 조회 - MaxBatUserInfoDto playerInfo = battingMapper.getMaxBatUser(map.get("gameId"), map.get("player1Id")); - - if(playerInfo != null) { - batStatusDto.setPlayer1MaxUserNickname(playerInfo.getUserNickname()); - batStatusDto.setPlayer1MaxCoin(playerInfo.getUserCoin()); - } - - playerInfo = battingMapper.getMaxBatUser(map.get("gameId"), map.get("player2Id")); - if(playerInfo != null) { - batStatusDto.setPlayer2MaxUserNickname(playerInfo.getUserNickname()); - batStatusDto.setPlayer2MaxCoin(playerInfo.getUserCoin()); - } - - //각 플레이어에게 건 사람의 총합 조회 - int player1Cnt = battingMapper.getPlayerSumPeople(map.get("gameId"), map.get("player1Id")); - batStatusDto.setPlayer1BatPeople(String.valueOf(player1Cnt)); - - int player2Cnt = battingMapper.getPlayerSumPeople(map.get("gameId"), map.get("player2Id")); - batStatusDto.setPlayer2BatPeople(String.valueOf(player2Cnt)); - - resultDto.setData(batStatusDto); - } - catch (Exception e) { - - log.error("Exception Msg", e); - resultDto.setStatus("500"); - resultDto.setMsg("Server Internal Error"); - resultDto.setData(null); - - } - - return resultDto; - } - - -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/ChatService.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/ChatService.java deleted file mode 100644 index a579a831..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/ChatService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.codearena.Chatting.service; -import com.ssafy.codearena.Chatting.dto.*; - -import java.util.List; -import java.util.Map; - -public interface ChatService { - public GameResultDto findAllRoom(Map map); - public GameResultDto findRoomById(String gameId); - public GameResultDto createCompetitiveRoom(GameCreateDto gameCreateDto); - public GameResultDto createPrivateRoom(PrivateGameCreateDto privateGameCreateDto); - public void plusParticipants(String gameId); - public void minusParticipants(String gameId); - public boolean playerLeaveEvent(String gameId, String playerId); - public boolean PrivateplayerLeaveEvent(String gameId, String playerId); - public void plusCandidates(String gameId, String userId); - public void minusCandidates(String gameId, String userId); - public String terminateGame(String gameId, String winner); - public WinnerInfoDto findWinner(String gameId); - public List getTopFiveMatch(); - public RestResultDto getCandidates(String gameId); - public GameResultDto startPrivateGame(String gameId); - public GameResultDto whoWinner(String gameId); - -} \ No newline at end of file diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/ChatServiceImpl.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/ChatServiceImpl.java deleted file mode 100644 index 58f57777..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/ChatServiceImpl.java +++ /dev/null @@ -1,773 +0,0 @@ -package com.ssafy.codearena.Chatting.service; -import com.ssafy.codearena.Chatting.controller.OpenviduController; -import com.ssafy.codearena.Chatting.dto.*; -import com.ssafy.codearena.Chatting.mapper.BattingMapper; -import com.ssafy.codearena.Chatting.mapper.GameMapper; -import io.openvidu.java.client.OpenVidu; -import io.openvidu.java.client.Session; -import io.openvidu.java.client.SessionProperties; -import jakarta.annotation.PostConstruct; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import java.util.*; - -@RequiredArgsConstructor -@Slf4j -@Service -public class ChatServiceImpl implements ChatService{ - private final int coinWeight = 1; - private Map gameManage; //경쟁방 (Redis로 관리) - private Map privateGameManage; //사설방 - private Map privateGameParticipaints; //사설방 참여자 수 관리 리소스 - - private final GameMapper gameMapper; - private final BattingMapper battingMapper; - private final OpenviduController openviduController; - private final int weight = 30; - - @Value("${OPENVIDU_URL}") - private String OPENVIDU_URL; - @Value("${OPENVIDU_SECRET}") - private String OPENVIDU_SECRET; - private OpenVidu openvidu; - - @PostConstruct - private void init() { - gameManage = new LinkedHashMap<>(); - privateGameManage = new LinkedHashMap<>(); - privateGameParticipaints = new LinkedHashMap<>(); - this.openvidu = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET); - } - /* - * 모든 방 리스트 찾기 - * */ - @Override - public GameResultDto findAllRoom(Map map) { - //결과값 세팅 - GameResultDto gameResultDto = new GameResultDto(); - gameResultDto.setStatus("200"); - gameResultDto.setMsg("게임 방 목록 조회 성공"); - Map param = new HashMap(); //쿼리 매개변수 - param.put("word", map.get("word") == null ? "" : map.get("word")); //검색 필터 값 - param.put("gameMode", map.get("gameMode") == null ? "" : map.get("gameMode")); //게임 모드 필터 - param.put("roomType", map.get("roomType") == null ? "0" : map.get("roomType")); //방 타입 필터 - param.put("langType", map.get("langType") == null ? "" : map.get("langType")); //언어 필터 - int currentPage = Integer.parseInt(map.get("pgno") == null ? "1" : map.get("pgno")); //특정 페이지 번호 요청이 없다면 1번 - int sizePerPage = Integer.parseInt(map.get("spp") == null ? "15" : map.get("spp")); - int start = currentPage * sizePerPage - sizePerPage; //쿼리로 불러올 인덱스 번호 지정 - param.put("start", start); - param.put("listSize", sizePerPage); - String key = map.get("key"); //검색조건 : 문제번호 or 유저 닉네임 - param.put("key", key == null ? "" : key); - param.put("sortType", map.get("sortType") == null ? "" : map.get("sortType")); //정렬 조건 - log.info(map.get("sortType")); - log.info((String) param.get("sortType")); - - try { - List list = gameMapper.findAllRoom(param); - int totalGameCount = gameMapper.getTotalGameCount(param); - int totalPageCount = (totalGameCount - 1) / sizePerPage + 1; - /* - * 참여자 수 세팅 - * */ - for(GameInfoDto gameInfo : list) { - String curId = gameInfo.getGameId(); - if(gameManage.get(curId) == null) { - gameInfo.setParticipants(0); - } - else { - gameInfo.setParticipants(gameManage.get(gameInfo.getGameId()).getParticipants()); - } - } - GameListDto gameListDto = new GameListDto(); - gameListDto.setGameRooms(list); - gameListDto.setCurrentPage(totalGameCount); - gameListDto.setTotalPageCount(totalPageCount); - gameResultDto.setData(gameListDto); - } - catch (Exception e) { - - log.error("Exception Msg", e); - gameResultDto.setStatus("500"); - gameResultDto.setMsg("Server Internal Error"); - gameResultDto.setData(null); - } - return gameResultDto; - } - /* - * 특정 방 찾기 - * */ - @Override - public GameResultDto findRoomById(String gameId) { - GameResultDto gameResultDto = new GameResultDto(); - gameResultDto.setStatus("200"); - gameResultDto.setMsg("게임방 조회 성공"); - try { - -// log.info(gameId); - GameInfoDto gameInfoDto = gameMapper.findRoomById(gameId); - //참여자 수 조회 - gameInfoDto.setParticipants(gameManage.get(gameInfoDto.getGameId()).getParticipants()); - gameResultDto.setData(gameInfoDto); - } - catch (Exception e) { - - log.error("Exception Msg", e); - gameResultDto.setStatus("500"); - gameResultDto.setMsg("Server Internal Error"); - gameResultDto.setData(null); - } - return gameResultDto; - } - @Override - public GameResultDto createCompetitiveRoom(GameCreateDto gameCreateDto) { - GameResultDto gameResultDto = new GameResultDto(); - gameResultDto.setStatus("200"); - gameResultDto.setMsg("성공적으로 1:1 게임방이 생성되었습니다."); - gameResultDto.setData(null); - try { - - //랜덤 문제 배정 - CreateCompetitiveResultDto createCompetitiveResultDto = new CreateCompetitiveResultDto(); - int randomProblem = gameMapper.findProblemById(); - createCompetitiveResultDto.setProblemId(Integer.toString(randomProblem)); //응답객체 값 저장 - createCompetitiveResultDto.setGameId(gameCreateDto.getGameId()); //응답객체 값 저장 - - gameCreateDto.setProblemId(Integer.toString(randomProblem)); - gameCreateDto.setRoomType("0"); - - gameMapper.createCompetitiveRoom(gameCreateDto); //DB I/O - - String startTime = gameMapper.getStartTime(gameCreateDto.getGameId()); //시작시간 I/O - - if(startTime != null && !startTime.isEmpty()) { - createCompetitiveResultDto.setStartTime(startTime); - } - //게임 매니저 객체 생성 및 내부 리소스 추가 - CompetitiveManageDto competitiveManageDto = new CompetitiveManageDto(); - competitiveManageDto.setGameId(gameCreateDto.getGameId()); - competitiveManageDto.setParticipants(0); - competitiveManageDto.setPlayer1(gameCreateDto.getUserRed()); - competitiveManageDto.setPlayer2(gameCreateDto.getUserBlue()); - competitiveManageDto.setPlayer1_leave(false); - competitiveManageDto.setPlayer2_leave(false); - competitiveManageDto.setGamemode(gameCreateDto.getGameMode()); - competitiveManageDto.setRoomType("0"); - log.info(String.valueOf(competitiveManageDto)); - gameManage.put(gameCreateDto.getGameId(), competitiveManageDto); - - Map map = new HashMap<>(); - map.put("CustomId", String.valueOf(gameCreateDto.getGameId())); - SessionProperties properties = SessionProperties.fromJson(map).build(); - Session session = openvidu.createSession(properties); - createCompetitiveResultDto.setViduSession(session.getSessionId()); //Session Id 저장 - - gameResultDto.setData(createCompetitiveResultDto); //배정된 게임방ID, vidu 세션 ID, 랜덤 문제번호 - - } - catch (Exception e) { - gameResultDto.setStatus("500"); - gameResultDto.setMsg("Server Internal Error"); - log.error("Exception Msg", e); - } - return gameResultDto; - } - - - @Override - public GameResultDto createPrivateRoom(PrivateGameCreateDto privateGameCreateDto) { - GameResultDto gameResultDto = new GameResultDto(); - gameResultDto.setStatus("200"); - gameResultDto.setMsg("성공적으로 사설 게임방이 생성되었습니다."); - gameResultDto.setData(null); - try { - UUID uuid = UUID.randomUUID(); - log.info(String.valueOf(uuid)); - privateGameCreateDto.setGameId(String.valueOf(uuid)); - privateGameCreateDto.setRoomType("1"); - - gameMapper.createPrivateRoom(privateGameCreateDto); //DB I/O - - //생성되는 게임에 대한 정보 입력 - PrivateManageDto privateManageDto = new PrivateManageDto(); - privateManageDto.setGameId(privateGameCreateDto.getGameId()); - privateManageDto.setPlayer1(privateGameCreateDto.getUserId()); //방장 - privateManageDto.setRoomType(privateGameCreateDto.getRoomType()); - privateManageDto.setGamemode(privateGameCreateDto.getGameMode()); - - privateGameManage.put(privateManageDto.getGameId(), privateManageDto); - - //사설 게임방 참여자 수 관리 리소스 생성 - privateGameParticipaints.put(String.valueOf(uuid), 1); - - Map map = new HashMap<>(); - map.put("CustomId", String.valueOf(uuid)); - SessionProperties properties = SessionProperties.fromJson(map).build(); - Session session = openvidu.createSession(properties); - - log.info(String.valueOf(session.getSessionId())); - gameResultDto.setData(uuid); //방 번호 - - } - catch (Exception e) { - gameResultDto.setStatus("500"); - gameResultDto.setMsg("Server Internal Error"); - log.error("Exception Msg", e); - } - - return gameResultDto; - } - - @Override - public void plusParticipants(String gameId) { - CompetitiveManageDto competitiveManageDto = gameManage.get(gameId); - competitiveManageDto.setParticipants(competitiveManageDto.getParticipants() + 1); - log.info("참여 이벤트 발생 : " + String.valueOf(gameManage.get(gameId).getParticipants())); - } - @Override - public void minusParticipants(String gameId) { - CompetitiveManageDto competitiveManageDto = gameManage.get(gameId); - if((competitiveManageDto.getParticipants() - 1) > 0) { - competitiveManageDto.setParticipants(competitiveManageDto.getParticipants() - 1); - } - log.info("퇴장 이벤트 발생 : " + String.valueOf(gameManage.get(gameId).getParticipants())); - } - - @Override - public void plusCandidates(String gameId, String userId) { - - //참여자 수 1증가 - int cnt = privateGameParticipaints.get(gameId); - privateGameParticipaints.put(gameId, ++cnt); - - //참여자 세팅 - PrivateManageDto privateManageDto = privateGameManage.get(gameId); - if(privateManageDto.getPlayer2() == null || privateManageDto.getPlayer2().isEmpty()) { - privateManageDto.setPlayer2(userId); - return; - } - else if(privateManageDto.getPlayer3() == null || privateManageDto.getPlayer3().isEmpty()) { - privateManageDto.setPlayer3(userId); - return; - } - else if(privateManageDto.getPlayer4() == null || privateManageDto.getPlayer4().isEmpty()) { - privateManageDto.setPlayer4(userId); - return; - } - // - log.info("참여 이벤트 발생 : " + String.valueOf(privateGameManage.get(gameId).getParticipants())); - } - - @Override - public void minusCandidates(String gameId, String userId) { - int cnt = privateGameParticipaints.get(gameId); - privateGameParticipaints.put(gameId, --cnt); - - //참여자 세팅 - PrivateManageDto privateManageDto = privateGameManage.get(gameId); - if(privateManageDto.getPlayer2().equals(userId)) { - privateManageDto.setPlayer2(null); - return; - } - else if(privateManageDto.getPlayer3().equals(userId)) { - privateManageDto.setPlayer3(null); - return; - } - else if(privateManageDto.getPlayer4().equals(userId)) { - privateManageDto.setPlayer4(null); - return; - } - - log.info("퇴장 이벤트 발생 : " + String.valueOf(gameManage.get(gameId).getParticipants())); - } - - @Override - public boolean playerLeaveEvent(String gameId, String playerId) { - - CompetitiveManageDto competitiveManageDto = gameManage.get(gameId); - if(competitiveManageDto.getPlayer1().equals(playerId)) { - competitiveManageDto.setPlayer1_leave(true); - } - else { - competitiveManageDto.setPlayer2_leave(true); - } - - log.info("탈주 이벤트 발생! : "); - log.info(playerId); - log.info("player1 : " + competitiveManageDto.isPlayer1_leave()); - log.info("player2 : " + competitiveManageDto.isPlayer2_leave()); - return competitiveManageDto.isPlayer1_leave() && competitiveManageDto.isPlayer2_leave(); - } - - @Override - public boolean PrivateplayerLeaveEvent(String gameId, String playerId) { - - PrivateManageDto privateManageDto = privateGameManage.get(gameId); - if(privateManageDto.getPlayer1().equals(playerId)) { - privateManageDto.setPlayer1_leave(true); - } - else if(privateManageDto.getPlayer2().equals(playerId)){ - privateManageDto.setPlayer2_leave(true); - } - else if(privateManageDto.getPlayer3().equals(playerId)){ - privateManageDto.setPlayer3_leave(true); - } - else if(privateManageDto.getPlayer4().equals(playerId)){ - privateManageDto.setPlayer4_leave(true); - } - - if(privateManageDto.isPlayer1_leave() && privateManageDto.isPlayer2_leave() && privateManageDto.isPlayer3_leave() && privateManageDto.isPlayer4_leave()) { - return true; - } - - return false; - } - - @Override - public String terminateGame(String gameId, String winner) { - - CompetitiveManageDto competitiveManageDto = gameManage.get(gameId); - if(competitiveManageDto == null) { - log.info("이미 종료된 게임방입니다."); - return "종료"; - } - log.info(String.valueOf(competitiveManageDto)); - String player1 = competitiveManageDto.getPlayer1(); - String player2 = competitiveManageDto.getPlayer2(); - String player1Nickname = ""; - String player2Nickname = ""; - - try { - - //플레이어 닉네임 조회 - player1Nickname = gameMapper.getUserNickname(player1); - player2Nickname = gameMapper.getUserNickname(player2); - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - int player1_rating = 0; - int player2_rating = 0; - - Map param = new HashMap<>(); - param.put("player", player1); - param.put("gamemode", competitiveManageDto.getGamemode()); - - // 두 유저의 레이팅 점수 탐색 - try { - - player1_rating = gameMapper.isRating(param); - param.put("player", player2); - player2_rating = gameMapper.isRating(param); - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - - log.info(String.valueOf(player1_rating)); - log.info(String.valueOf(player2_rating)); - - //최종 레이팅 계산 - int player1_result = 0; - int player2_result = 0; - //player1이 이겼을 경우 - if(winner.equals(player1Nickname)) { - log.info("플레이어 1 우승"); - player1_result = CaluRating(player1_rating, player2_rating, "승리"); - player2_result = CaluRating(player2_rating, player1_rating, "패배"); - } - //player2가 이겼을 경우 - else if(winner.equals(player2Nickname)) { - log.info("플레이어 2 우승"); - player1_result = CaluRating(player1_rating, player2_rating, "패배"); - player2_result = CaluRating(player2_rating, player1_rating, "승리"); - } - //무승부 - else if(winner.equals("")) { - log.info("무승부"); - player1_result = CaluRating(player1_rating, player2_rating, "무승부"); - player2_result = CaluRating(player2_rating, player1_rating, "무승부"); - } - - log.info(String.valueOf(player1_result)); - log.info(String.valueOf(player2_result)); - - - try { //종료시간 및 승자 DB I/O - - gameMapper.terminateGame(gameId, winner); - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - - try { //레이팅 갱신 - - gameMapper.refreshRating(player1, Integer.toString(player1_result), competitiveManageDto.getGamemode()); - gameMapper.refreshRating(player2, Integer.toString(player2_result), competitiveManageDto.getGamemode()); - } - catch (Exception e) { - log.error("Exception Msg", e); - } - - - //배팅 결과 적용 - try { - //두 플레이어 아이디 탈취 - Map params = new HashMap<>(); - params.put("gameId", gameId); - params.put("player1Id", player1); - params.put("player2Id", player2); - BatPlayerCountDto batPlayerCountDto = battingMapper.getPlayerCount(params); - - //총 투자 인원 - double sum = batPlayerCountDto.getPlayer1Count() + batPlayerCountDto.getPlayer2Count(); //115명 - - double player1_ratio = (double)1 - ((double) batPlayerCountDto.getPlayer2Count()/sum); //1 -> 0.3 >> 30% - double player2_ratio = (double)1 - ((double) batPlayerCountDto.getPlayer1Count()/sum); //1 -> 0.3 >> 30% - - - log.info("플레이어 1의 비율 : " + player1_ratio); - log.info("플레이어 2의 비율 : " + player2_ratio); - - - if(winner.isEmpty()) { - - log.info("무승부입니다."); - //승자가 없을 경우 - //배팅 금액만큼 다 돌려줘야됨. - List list = battingMapper.getUserBatCoin(gameId, winner); - - for(BatUserCoinDto dto : list) { - - battingMapper.updateUserPlusCoin(dto.getUserId(), Integer.parseInt(dto.getUserCoin())); - } - - } - else if(winner.equals(player1Nickname) || winner.equals(player2Nickname)){ - - //승자가 있을 경우 - //승자에게 배팅한 유저들 조회 - //for문 돌면서 한 유저당 기존 코인 꺼내오고 비율 * 배팅금액 한거 더해서 추가 - List list = battingMapper.getUserBatCoin(gameId, winner); - - for(BatUserCoinDto dto : list) { - //한명씩 비율과 계산한 후 갱신 - //이긴 유저 한명 당 기존 coin 조회 - int coin = battingMapper.getUserCoin(dto.getUserId()); - - if(player1Nickname.equals(winner)) { - - log.info("player1이 우승 시 배팅 정산"); - int newCoin = (int) (coin + Integer.parseInt(dto.getUserCoin()) * (player1_ratio + 1)); - battingMapper.updateUserCoin(dto.getUserId(), String.valueOf(newCoin)); - } - else if(player2Nickname.equals(winner)){ - - log.info("player2가 우승 시 배팅 정산"); - int newCoin = (int) (coin + Integer.parseInt(dto.getUserCoin()) * (player2_ratio + 1)); - battingMapper.updateUserCoin(dto.getUserId(), String.valueOf(newCoin)); - } - else { - - log.info("ChatServiceImpl.terminateGame : winner값에 이상한 값이 들어왔습니다."); - break; - } - } - - } - else { - - log.error("winner 닉네임과 현재 게임방에 속한 플레이어의 닉네임과 일치하지 않습니다."); - } - - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - - //객체 제거 - gameManage.remove(gameId); - - return "플레이어 1 : " + player1_result + " AND " + "플레이어 2 : " + player2_result; - - } - - //ELO 레이팅 계산 로직 - private int CaluRating(int myRating, int diffRating, String result) { - float powValue = (float) (diffRating - myRating) / 400; - float winRatio = (float) (1 / (Math.pow(10, powValue) + 1)); - - int rating = 0; - if(result.equals("승리")) { - rating = (int) (myRating + weight * (1 - winRatio)); - } - else if(result.equals("패배")) { - rating = (int) (myRating + weight * (0 - winRatio)); - } - else if(result.equals("무승부")) { - rating = (int) (myRating + weight * (0.5 - winRatio)); - } - - - return rating; - } - - @Override - public WinnerInfoDto findWinner(String gameId) { - CompetitiveManageDto competitiveManageDto = gameManage.get(gameId); - String player1 = competitiveManageDto.getPlayer1(); - String player2 = competitiveManageDto.getPlayer2(); - int result = 0; - //player1, player2의 '맞았습니다' 결과 개수 탐색 - try { - - result = gameMapper.passProblem(gameId, player1, player2); - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - - WinnerInfoDto winnerInfoDto = new WinnerInfoDto(); - if(result > 0) { - //승자 탐색 - try { - winnerInfoDto = gameMapper.winnerSearch(gameId); - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - } - else { - winnerInfoDto = null; - } - //두 유저 모두 '맞았습니다.' 결과가 존재할 경우 승자 탐색 - - - return winnerInfoDto; - } - - @Override - public List getTopFiveMatch() { - - //Map 데이터 정렬 - List list = new ArrayList<>(gameManage.values()); - Collections.sort(list); - - List topMatch = new ArrayList<>(); - - //Top 5 - if(gameManage.size() >= 5) { - for (int i = 0; i < 5; i++) { - CompetitiveManageDto competitiveManageDto = list.get(i); - log.info(String.valueOf(competitiveManageDto)); - try { - CompetitiveTopMatchResultDto competitiveTopMatchResultDto = new CompetitiveTopMatchResultDto(); - - //두 유저의 정보 조회 - CompetitiveUserInfoDto player1Info = gameMapper.getUserInfo(competitiveManageDto.getPlayer1(), competitiveManageDto.getGamemode()); - CompetitiveUserInfoDto player2Info = gameMapper.getUserInfo(competitiveManageDto.getPlayer2(), competitiveManageDto.getGamemode()); - - competitiveTopMatchResultDto.setPlayer1Nickname(player1Info.getUserNickname()); - competitiveTopMatchResultDto.setPlayer1Rating(player1Info.getUserRating()); - competitiveTopMatchResultDto.setPlayer1Ssumnail(player1Info.getUserSsumnail()); - competitiveTopMatchResultDto.setPlayer2Nickname(player2Info.getUserNickname()); - competitiveTopMatchResultDto.setPlayer2Rating(player2Info.getUserRating()); - competitiveTopMatchResultDto.setPlayer2Ssumnail(player2Info.getUserSsumnail()); - competitiveTopMatchResultDto.setGameId(competitiveManageDto.getGameId()); - competitiveTopMatchResultDto.setParticipants(competitiveManageDto.getParticipants()); - - topMatch.add(competitiveTopMatchResultDto); - } catch (Exception e) { - - log.error("Exception Msg", e); - break; - } - } - } - //진행중인 게임이 5미만이라면 방 개수만큼 탐색 - else { - - for (int i = 0; i < list.size(); i++) { - CompetitiveManageDto competitiveManageDto = list.get(i); - log.info(String.valueOf(competitiveManageDto)); - - try { - CompetitiveTopMatchResultDto competitiveTopMatchResultDto = new CompetitiveTopMatchResultDto(); - - CompetitiveUserInfoDto player1Info = gameMapper.getUserInfo(competitiveManageDto.getPlayer1(), competitiveManageDto.getGamemode()); - CompetitiveUserInfoDto player2Info = gameMapper.getUserInfo(competitiveManageDto.getPlayer2(), competitiveManageDto.getGamemode()); - - competitiveTopMatchResultDto.setPlayer1Nickname(player1Info.getUserNickname()); - competitiveTopMatchResultDto.setPlayer1Rating(player1Info.getUserRating()); - competitiveTopMatchResultDto.setPlayer1Ssumnail(player1Info.getUserSsumnail()); - competitiveTopMatchResultDto.setPlayer2Nickname(player2Info.getUserNickname()); - competitiveTopMatchResultDto.setPlayer2Rating(player2Info.getUserRating()); - competitiveTopMatchResultDto.setPlayer2Ssumnail(player2Info.getUserSsumnail()); - competitiveTopMatchResultDto.setGameId(competitiveManageDto.getGameId()); - competitiveTopMatchResultDto.setParticipants(competitiveManageDto.getParticipants()); - - topMatch.add(competitiveTopMatchResultDto); - } catch (Exception e) { - - log.error("Exception Msg", e); - break; - } - } - } - - return topMatch; - } - - @Override - public RestResultDto getCandidates(String gameId) { - - RestResultDto resultDto = new RestResultDto(); - resultDto.setData("200"); - resultDto.setMsg("참여 가능한 게임방입니다."); - resultDto.setData(null); - try { - if (privateGameParticipaints.get(gameId) == 4) { - - resultDto.setStatus("500"); - resultDto.setMsg("대기열이 가득찼습니다."); - } - } - catch (Exception e) { - - log.error("Exception Msg", e); - } - - return resultDto; - } - - @Override - public GameResultDto startPrivateGame(String gameId) { - - GameResultDto gameResultDto = new GameResultDto(); - gameResultDto.setStatus("200"); - gameResultDto.setMsg("게임 시작 성공"); - - PrivateManageDto privateManageDto = privateGameManage.get(gameId); - - Map params = new HashMap<>(); - params.put("gameId", gameId); - params.put("player2", privateManageDto.getPlayer2()); - params.put("player3", privateManageDto.getPlayer3()); - params.put("player4", privateManageDto.getPlayer4()); - - try { - - //랜덤 문제 배정 - int randomProblem = gameMapper.findProblemById(); - params.put("problemId", String.valueOf(randomProblem)); - gameResultDto.setData(randomProblem); - - gameMapper.startPrivateGame(params); - } - catch (Exception e) { - - log.error("Exception Msg", e); - gameResultDto.setStatus("500"); - gameResultDto.setMsg("Server Internal Error"); - gameResultDto.setData(null); - } - - return gameResultDto; - } - - @Override - public GameResultDto whoWinner(String gameId) { - - GameResultDto gameResultDto = new GameResultDto(); - gameResultDto.setStatus("200"); - gameResultDto.setMsg("성공적으로 결과 조회했습니다."); - - CompetitiveGameResultDto competitiveGameResultDto = new CompetitiveGameResultDto(); - - try { - - //player1, player2, winner 조회 - CompetitiveWinnerInfoDto competitiveWinnerInfoDto = new CompetitiveWinnerInfoDto(); - competitiveWinnerInfoDto = gameMapper.whoWinner(gameId); - if( competitiveWinnerInfoDto.getWinner() == null) competitiveWinnerInfoDto.setWinner(""); - - log.info("승자 : " + competitiveWinnerInfoDto.getWinner()); - - if(competitiveWinnerInfoDto.getWinner().isEmpty()) { - log.info("DRAW"); - //draw - //두 유저의 변동된 점수 조회 - CompetitiveUserInfoDto player = gameMapper.getUserInfo(competitiveWinnerInfoDto.getPlayer1(), competitiveWinnerInfoDto.getGame_mode()); - competitiveGameResultDto.setWinnerId(player.getUserNickname()); - competitiveGameResultDto.setWinnerRating(player.getUserRating()); - competitiveGameResultDto.setWinnerSsumnail(player.getUserSsumnail()); - - player = gameMapper.getUserInfo(competitiveWinnerInfoDto.getPlayer2(), competitiveWinnerInfoDto.getGame_mode()); - competitiveGameResultDto.setLoserId(player.getUserNickname()); - competitiveGameResultDto.setLoserRating(player.getUserRating()); - competitiveGameResultDto.setLoserSsumnail(player.getUserSsumnail()); - } - else if(competitiveWinnerInfoDto.getWinner().equals(competitiveWinnerInfoDto.getPlayer1())) { - log.info("플레이어1 우승"); - - //두 유저의 변동된 점수 조회 - CompetitiveUserInfoDto player = gameMapper.getUserInfo(competitiveWinnerInfoDto.getPlayer1(), competitiveWinnerInfoDto.getGame_mode()); - competitiveGameResultDto.setWinnerId(player.getUserNickname()); - competitiveGameResultDto.setWinnerRating(player.getUserRating()); - competitiveGameResultDto.setWinnerSsumnail(player.getUserSsumnail()); - - - player = gameMapper.getUserInfo(competitiveWinnerInfoDto.getPlayer2(), competitiveWinnerInfoDto.getGame_mode()); - competitiveGameResultDto.setLoserId(player.getUserNickname()); - competitiveGameResultDto.setLoserRating(player.getUserRating()); - competitiveGameResultDto.setLoserSsumnail(player.getUserSsumnail()); - - } - else if(competitiveWinnerInfoDto.getWinner().equals(competitiveWinnerInfoDto.getPlayer2())) { - log.info("플레이어2 우승"); - //두 유저의 변동된 점수 조회 - CompetitiveUserInfoDto player = gameMapper.getUserInfo(competitiveWinnerInfoDto.getPlayer2(), competitiveWinnerInfoDto.getGame_mode()); - competitiveGameResultDto.setWinnerId(player.getUserNickname()); - competitiveGameResultDto.setWinnerRating(player.getUserRating()); - competitiveGameResultDto.setWinnerSsumnail(player.getUserSsumnail()); - - - player = gameMapper.getUserInfo(competitiveWinnerInfoDto.getPlayer1(), competitiveWinnerInfoDto.getGame_mode()); - competitiveGameResultDto.setLoserId(player.getUserNickname()); - competitiveGameResultDto.setLoserRating(player.getUserRating()); - competitiveGameResultDto.setLoserSsumnail(player.getUserSsumnail()); - - } - - - //채점현황 리스트 조회 - - List list = new ArrayList<>(); - list = gameMapper.getSubmitList(gameId); - - competitiveGameResultDto.setList(list); - - gameResultDto.setData(competitiveGameResultDto); - } - catch (Exception e) { - - log.error("Exception e", e); - gameResultDto.setStatus("500"); - gameResultDto.setMsg("Server Internal Error"); - gameResultDto.setData(null); - } - - return gameResultDto; - } - - -} \ No newline at end of file diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/RestService.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/RestService.java deleted file mode 100644 index 987728fb..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/RestService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ssafy.codearena.Chatting.service; - -import com.ssafy.codearena.Chatting.dto.EffiSubmitListDto; -import com.ssafy.codearena.Chatting.dto.GameResultDto; -import com.ssafy.codearena.Chatting.dto.RestResultDto; -import com.ssafy.codearena.Chatting.dto.SubmitDto; -import jakarta.servlet.http.HttpServletRequest; - -import java.util.Map; - -public interface RestService { - RestResultDto insertSubmit(SubmitDto submitDto); - RestResultDto getRanking(); - RestResultDto getMyRecord(HttpServletRequest request); - RestResultDto getCompetitiveResult(String gameId); - GameResultDto getEffiSubmitList(Map map); -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/RestServiceImpl.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/RestServiceImpl.java deleted file mode 100644 index 1ecd4dda..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/service/RestServiceImpl.java +++ /dev/null @@ -1,291 +0,0 @@ -package com.ssafy.codearena.Chatting.service; - - -import com.ssafy.codearena.Chatting.dto.GamePlayerDto; -import com.ssafy.codearena.Chatting.dto.CompetitiveResultDto; -import com.ssafy.codearena.Chatting.dto.CompetitiveUserInfoDto; -import com.ssafy.codearena.Chatting.dto.RestResultDto; -import com.ssafy.codearena.Chatting.dto.SubmitDto; -import com.ssafy.codearena.Chatting.dto.Top5RatingResultDto; -import com.ssafy.codearena.Chatting.dto.*; -import com.ssafy.codearena.Chatting.mapper.RestMapper; -import com.ssafy.codearena.Chatting.util.JWTUtil; -import io.jsonwebtoken.JwtException; -import jakarta.servlet.http.HttpServletRequest; -import lombok.NoArgsConstructor; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.reactive.function.client.WebClient; - -import javax.security.sasl.AuthenticationException; -import java.time.Duration; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeoutException; - -@Service -@Slf4j -@RequiredArgsConstructor -public class RestServiceImpl implements RestService { - - private final RestMapper mapper; - - @Value("${judge.java.url}") - private String judgejava; - @Value("${judge.cpp.url}") - private String judgecpp; - @Value("${judge.python.url}") - private String judgepython; - - @Value("${rest.url}") - private String restUrl; - - @Autowired - private JWTUtil jwtUtil; - - private WebClient getSumbitClient(String lang){ - switch(lang){ - case "java": - return WebClient.create(judgejava); - case "cpp": - return WebClient.create(judgecpp); - default: - return WebClient.create(judgepython); - } - } - - private WebClient getRestClient(String url){ - return WebClient.create(url); - } - - @Override - public RestResultDto insertSubmit(SubmitDto submitDto) { - RestResultDto resultDto = new RestResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("채점서버로 전송되었습니다."); - try{ - // /judge/arena - submitDto.setSubmitStatus("채점중"); - mapper.insertSubmit(submitDto); - WebClient client = getSumbitClient(submitDto.getSubmitLang()); - HashMap params = new HashMap<>(); - params.put("submitNo", submitDto.getSubmitNo()); - params.put("problemId", submitDto.getProblemId()); - params.put("code", submitDto.getCode()); - params.put("gameType", submitDto.getGameType()); - log.debug("params : {} ", params); - client.post().uri("/judge/arena").contentType(MediaType.APPLICATION_JSON).bodyValue(params).retrieve().bodyToMono(HashMap.class).subscribe(); - }catch(Exception e){ - log.debug("exception : {}", e); - resultDto.setMsg("채점서버로 전송 중 에러가 발생하였습니다."); - resultDto.setStatus("500"); - }finally{ - return resultDto; - } - } - - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public RestResultDto getRanking() { - RestResultDto resultDto = new RestResultDto(); - Top5RatingResultDto rank = new Top5RatingResultDto(); - List effRanking = Collections.EMPTY_LIST; - List speedRanking = Collections.EMPTY_LIST; - List pointRanking = Collections.EMPTY_LIST; - resultDto.setStatus("200"); - resultDto.setMsg("순위조회에 성공했습니다."); - try{ - effRanking = mapper.getEffRankingbyRating(); - speedRanking = mapper.getSpeedRankingByRating(); - pointRanking = mapper.getPointRankingByPoint(); - if(effRanking == null && speedRanking == null && pointRanking == null) throw new Exception("랭크 조회 에러"); - if(effRanking == null) effRanking = Collections.EMPTY_LIST; - if(speedRanking == null) speedRanking = Collections.EMPTY_LIST; - if(pointRanking == null) pointRanking = Collections.EMPTY_LIST; - }catch(Exception e){ - log.debug("exception : {}", e); - resultDto.setStatus("500"); - resultDto.setMsg("순위조회 도중 에러가 발생했습니다."); - }finally{ - rank.setSpeedRank(speedRanking); - rank.setEffRank(effRanking); - rank.setPointRank(pointRanking); - resultDto.setData(rank); - return resultDto; - } - } - - @Override - public RestResultDto getMyRecord(HttpServletRequest request) { - RestResultDto restResultDto = new RestResultDto(); - restResultDto.setStatus("200"); - restResultDto.setMsg("조회에 성공하였습니다."); - GamePlayerDto playerData = new GamePlayerDto(); - try{ - String token = request.getHeader("Authorization"); - - if(token == null || "".equals(token)) throw new NullPointerException("토큰이 비었음"); - WebClient client = getRestClient(restUrl); - HashMap authResult = client.get().uri("/auth").header("Authorization", token).retrieve().bodyToMono(HashMap.class).block(Duration.ofMillis(10000)); - if(authResult == null) throw new TimeoutException("회원 인증 connection timeout"); - String status = authResult.get("status"); - if("302".equals(status)) throw new AuthenticationException("회원 인증 오류"); - log.debug(token); - String userId = jwtUtil.getUserId(token); - playerData = mapper.getUserRecordByUserId(userId); - log.debug("result : {}",playerData.getRecord()); - if(playerData.getUserId() == null) throw new DataIntegrityViolationException("존재하지 않는 PK"); - }catch(TimeoutException e){ - log.debug("exception : {}", e); - restResultDto.setMsg("인증 서버로부터 응답이 없습니다."); - restResultDto.setStatus("400"); - playerData = null; - } catch(NullPointerException e){ - log.debug("exception : {}", e); - restResultDto.setMsg("토큰 데이터가 없습니다."); - restResultDto.setStatus("403"); - playerData = null; - } catch(AuthenticationException e){ - log.debug("exception : {}", e); - restResultDto.setMsg("회원 인증오류, 토큰 갱신이 필요합니다."); - restResultDto.setStatus("302"); - playerData = null; - } catch(DataIntegrityViolationException e){ - log.debug("exception : {}", e); - restResultDto.setMsg("존재하지 않는 회원입니다."); - restResultDto.setStatus("404"); - playerData = null; - } catch(Exception e){ - log.debug("exception : {} ", e); - restResultDto.setMsg("알수없는 에러가 발생했습니다."); - restResultDto.setStatus("500"); - playerData = null; - } finally{ - restResultDto.setData(playerData); - return restResultDto; - } - } - @Override - public RestResultDto getCompetitiveResult(String gameId) { - - RestResultDto resultDto = new RestResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg(gameId + "게임에 대한 결과가 조회되었습니다."); - - CompetitiveResultDto competitiveResultDto = new CompetitiveResultDto(); - competitiveResultDto.setGameId(gameId); - - //arena_record에서 gameId에 해당하는 방에 대한 정보 조회 - try { - competitiveResultDto = mapper.getGameInfo(gameId); - } - catch (Exception e) { - - log.error("Exception Msg", e); - resultDto.setStatus("500"); - resultDto.setMsg("게임방 정보 조회 시 에러가 발생했습니다."); - resultDto.setData(null); - return resultDto; - } - - //user에서 각 유저에 대한 정보 조회 - try { - //player1, DTO 재활용 - CompetitiveUserInfoDto competitiveUserInfoDto = mapper.getPlayerInfo(competitiveResultDto.getPlayer1Id(), competitiveResultDto.getGameMode()); - competitiveResultDto.setPlayer1Nickname(competitiveUserInfoDto.getUserNickname()); - competitiveResultDto.setPlayer1Rating(competitiveUserInfoDto.getUserRating()); - competitiveResultDto.setPlayer1Ssumnail(competitiveUserInfoDto.getUserSsumnail()); - //player2, DTO 재활용 - competitiveUserInfoDto = mapper.getPlayerInfo(competitiveResultDto.getPlayer2Id(), competitiveResultDto.getGameMode()); - competitiveResultDto.setPlayer2Nickname(competitiveUserInfoDto.getUserNickname()); - competitiveResultDto.setPlayer2Rating(competitiveUserInfoDto.getUserRating()); - competitiveResultDto.setPlayer2Ssumnail(competitiveUserInfoDto.getUserSsumnail()); - - resultDto.setData(competitiveResultDto); - } - catch (Exception e) { - - log.error("Exception Msg", e); - resultDto.setStatus("500"); - resultDto.setMsg("플레이어 정보 조회 시 에러가 발생했습니다."); - resultDto.setData(null); - } - - //winner 닉네임으로 대체 - if(competitiveResultDto.getPlayer1Id().equals(competitiveResultDto.getWinner())) { - competitiveResultDto.setWinner(competitiveResultDto.getPlayer1Nickname()); - } - else if(competitiveResultDto.getPlayer2Id().equals(competitiveResultDto.getWinner())) { - competitiveResultDto.setWinner(competitiveResultDto.getPlayer2Nickname()); - } - else { - //무승부 - competitiveResultDto.setWinner("무승부"); - } - - return resultDto; - - } - - @Override - public GameResultDto getEffiSubmitList(Map map) { - - GameResultDto resultDto = new GameResultDto(); - - Map param = new HashMap(); //쿼리 매개변수 - - param.put("word", map.get("word") == null ? "" : map.get("word")); //검색조건 있다면 put - param.put("gameId", map.get("gameId")); - int currentPage = Integer.parseInt(map.get("pgno") == null ? "1" : map.get("pgno")); //특정 페이지 번호 요청이 없다면 1번 - int sizePerPage = Integer.parseInt(map.get("spp") == null ? "15" : map.get("spp")); - - int start = currentPage * sizePerPage - sizePerPage; //쿼리로 불러올 인덱스 번호 지정 - - param.put("start", start); - param.put("listSize", sizePerPage); - - - String key = map.get("key"); - param.put("key", key == null ? "" : key); - - - try { - List list = mapper.getEffiSubmitList(param); - int totalSubmitCount = mapper.getTotalSubmitCount(param); - int totalPageCount = 1; - - if(totalSubmitCount > sizePerPage) { - totalPageCount = (totalSubmitCount - 1) / sizePerPage + 1; - } - - EffiSubmitListDto effiSubmitListDto = new EffiSubmitListDto(); - effiSubmitListDto.setCurrentPage(currentPage); - effiSubmitListDto.setTotalPageCount(totalPageCount); - effiSubmitListDto.setList(list); - - resultDto.setStatus("200"); - resultDto.setMsg("채점현황 불러오기 성공"); - resultDto.setData(effiSubmitListDto); - - } - catch (Exception e) { - - log.error("Exception Msg", e); - resultDto.setStatus("500"); - resultDto.setMsg("Server Internal Error"); - resultDto.setData(null); - } - - return resultDto; - } -} diff --git a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/util/JWTUtil.java b/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/util/JWTUtil.java deleted file mode 100644 index 8ada68da..00000000 --- a/back-end/Chatting/src/main/java/com/ssafy/codearena/Chatting/util/JWTUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ssafy.codearena.Chatting.util; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import io.jsonwebtoken.*; -import java.util.Map; - - - - -@Component -@Slf4j -public class JWTUtil { - - @Value("${jwt.salt}") - private String salt; - - @Value("${jwt.access-token.expiretime}") - private long accessTokenExpireTiem; - - @Value("${jwt.refresh-token.expiretime}") - private long refreshTokenExpireTime; - - - private Claims decodeToken(String token){ - Claims claims = null; - try{ - claims = Jwts.parser().setSigningKey(salt.getBytes()) - .parseClaimsJws(token) - .getBody(); - - }catch(SecurityException | MalformedJwtException | SignatureException e) { - claims = null; - log.error("유효하지 않는 JWT signature 입니다."); - } catch (ExpiredJwtException e) { - claims = null; - log.error("만료된 JWT 토큰입니다."); - } catch (UnsupportedJwtException e) { - claims = null; - log.error("지원되지 않는 JWT 토큰입니다."); - } catch (IllegalArgumentException e) { - claims = null; - log.error("잘못된 JWT 토큰입니다."); - } - return claims; - } - - public String getUserId(String token){ - Claims claims = decodeToken(token); - return (String) claims.get("userId"); - } -} diff --git a/back-end/Chatting/src/main/resources/application.properties b/back-end/Chatting/src/main/resources/application.properties deleted file mode 100644 index c523f7b5..00000000 --- a/back-end/Chatting/src/main/resources/application.properties +++ /dev/null @@ -1,42 +0,0 @@ -server.servlet.context-path=/game -server.port=8080 - -spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver -spring.datasource.hikari.jdbc-url=ENC(r+KIqwS3XI4nTVEmANgQwemhBBII5uHmoPV3GOKV532QevjvuzOteIOacGXym5nwtG4gyAlIxTrVGpjlXjIGVz1HoaH+wpDhplhSugS2s67XTXv8XX8MLz4Aa4WVmzUHgm7OZnstSOfRObspUGNPFQ==) -spring.datasource.hikari.username=ENC(u2pZ0ldKEDL6po+p2UuafA==) -spring.datasource.hikari.password=ENC(OS7bgMIA05vs5uQMjRm7p4p+5G8tsJzv) -spring.datasource.hikari.pool-name=Hikari Connection Pool -# hikariCP property setting -spring.datasource.hikari.maximum-pool-size=50 -spring.datasource.hikari.minimum-idle=50 -spring.datasource.hikari.connection-timeout=5000 -spring.datasource.hikari.connection-init-sql=SELECT 1 -spring.datasource.hikari.idle-timeout=600000 -spring.datasource.hikari.max-lifetime=1800000 -spring.datasource.hikari.auto-commit=true - -logging.level.com.ssafy.codearena=debug - -# Openvidu -server.ssl.enabled: false - -OPENVIDU_URL: ENC(ff67WgR7XiH8e5tM1CpGNwXOmf/GemNN/x5BbzH7oGw+wUybRsgvyg==) -OPENVIDU_SECRET: ENC(UV58O7+kwNtv3PaY3MMSITuQ9rDx1fTw) - -#Swagger URL -springdoc.swagger-ui.path=/swagger-ui.html - -# jwt setting -jwt.salt=ENC(N1Nr7S7EZmI3UL3I/ohGdav3Jfqrm5T4) -# 4 hours -jwt.access-token.expiretime=14400000 -# 10 days -jwt.refresh-token.expiretime=864000000 - -# judge url -judge.java.url=ENC(rA8+zCVuz8dO5RkRRQPZTG/flo+IgIODBxpj2DLTJzREFHcvT8cLFQ==) -judge.cpp.url=ENC(R1yTOmx3cX5nznk5WDuTvBxhxRvlg4ld4wXhkf6x4eJ359qlhI4nvQ==) -judge.python.url=ENC(oQj2PW8iUHRgUbw0VON4DjrfkR6yK/vnoAewSn1g07YdoUkCoueHuA==) -# rest url -rest.url=ENC(14lWfg8pkDykcuHhdo6jfREd/E8I/Z30Mjveo39NCeYy/wFA+7vFQg==) - diff --git a/back-end/Chatting/src/main/resources/mapper/Batting.xml b/back-end/Chatting/src/main/resources/mapper/Batting.xml deleted file mode 100644 index 3b6a417b..00000000 --- a/back-end/Chatting/src/main/resources/mapper/Batting.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - AND bat_player_id = (SELECT user_id FROM user WHERE user_nickname = #{winner}) - - - - - - - - - - SELECT user_coin - FROM user - WHERE user_id = #{userId} - - UPDATE user - SET user_coin = #{userCoin} + ${coin} - WHERE user_id = #{userId}; - - - - - UPDATE user - SET user_coin = #{coin} - WHERE user_id = #{userId}; - - - - - INSERT INTO batting(game_id, bat_user_id, bat_player_id, bat_coin, bat_date) - VALUES(#{gameId}, #{userId}, #{playerId}, #{batCoin}, now()); - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/back-end/Chatting/src/main/resources/mapper/Mapper.xml b/back-end/Chatting/src/main/resources/mapper/Mapper.xml deleted file mode 100644 index 306ffc1e..00000000 --- a/back-end/Chatting/src/main/resources/mapper/Mapper.xml +++ /dev/null @@ -1,264 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - AND (player1 IN (SELECT user_id FROM user WHERE user_nickname LIKE CONCAT('%', #{word}, '%')) or player2 IN (SELECT user_id FROM user WHERE user_nickname LIKE CONCAT('%', #{word}, '%')) or player3 IN (SELECT user_id FROM user WHERE user_nickname LIKE CONCAT('%', #{word}, '%')) or player4 IN (SELECT user_id FROM user WHERE user_nickname LIKE CONCAT('%', #{word}, '%'))) - - - AND ${key} = #{word} - - - AND ${key} LIKE CONCAT('%', #{word}, '%') - - - - - - - - AND game_mode = #{gameMode} - - - - - - ORDER BY start_time DESC - - - ORDER BY start_time ASC - - - - - - - AND game_language LIKE CONCAT('%', #{langType}, '%') - - - - - - - , winner = (SELECT user_id FROM user WHERE user_nickname = #{winner}) - - - - - - - SELECT speed_rating - - - SELECT effi_rating - - - - - - - speed_rating = #{rating} - - - effi_rating = #{rating} - - - - - - - AND room_type = #{roomType} - - - - - - - - - - - INSERT INTO arena_record(game_id, game_title, player1, player2, problem_id, game_mode, game_language, room_type) - VALUES(#{gameId}, #{title}, #{userRed}, #{userBlue}, #{problemId}, #{gameMode}, #{language}, #{roomType}); - - - - - INSERT INTO arena_record(game_id, game_title, player1, game_mode, game_language, room_type) - VALUES(#{gameId}, #{title}, #{userId}, #{gameMode}, #{language}, #{roomType}); - - - - - - - - - - UPDATE arena_record - - end_time = now() - - - WHERE game_id = #{gameId}; - - - - - - - - - - UPDATE user - - WHERE user_id = #{userId}; - - - - - - UPDATE arena_record - SET problem_id = #{problemId}, player2 = #{player2}, player3 = #{player3}, player4 = #{player4}, start_time = now() - WHERE game_id = #{gameId}; - - - - - - - - - - - \ No newline at end of file diff --git a/back-end/Chatting/src/main/resources/mapper/Rest.xml b/back-end/Chatting/src/main/resources/mapper/Rest.xml deleted file mode 100644 index 9466b862..00000000 --- a/back-end/Chatting/src/main/resources/mapper/Rest.xml +++ /dev/null @@ -1,172 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 검색조건에 관한 동적쿼리문 --> - - - - AND ${key} = #{word} - - - - - - insert into - arena_submit_status - (user_id, game_id, problem_id, submit_lang, code, submit_status) - values( - '${userId}', '${gameId}', '${problemId}', '${submitLang}', #{code}, '${submitStatus}' - ) - - select last_insert_id() - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/back-end/Chatting/src/test/java/com/ssafy/codearena/Chatting/ChattingApplicationTests.java b/back-end/Chatting/src/test/java/com/ssafy/codearena/Chatting/ChattingApplicationTests.java deleted file mode 100644 index ee1da0de..00000000 --- a/back-end/Chatting/src/test/java/com/ssafy/codearena/Chatting/ChattingApplicationTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.Chatting; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -class ChattingApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/back-end/README.md b/back-end/README.md deleted file mode 100644 index edf95127..00000000 --- a/back-end/README.md +++ /dev/null @@ -1 +0,0 @@ -## Back-end \ No newline at end of file diff --git a/back-end/codearena/.gitignore b/back-end/codearena/.gitignore deleted file mode 100644 index c2065bc2..00000000 --- a/back-end/codearena/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -HELP.md -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/**/build/ -!**/src/test/**/build/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr -out/ -!**/src/main/**/out/ -!**/src/test/**/out/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ diff --git a/back-end/codearena/Dockerfile b/back-end/codearena/Dockerfile deleted file mode 100644 index a5d73edb..00000000 --- a/back-end/codearena/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM openjdk:17-jdk-alpine -# FROM : 이미지 레이어의 최상단, alpine리눅스에 jdk 17을 사용한단 의미 - -WORKDIR /app -# WORKDIR : 스프링 부트 컨테이너 OS내에 어떤 디렉토리에서 jar을 실행 할 것인지 - -ARG JAR_FILE=build/libs/codearena-0.0.1-SNAPSHOT.jar -# ARG : 변수지정, 변수에 적혀진 의미는 빌드 결과물 위치 - -COPY ${JAR_FILE} test.jar -# Auto Exctraction으로 압축된 파일을 해제하여 test.jar에 그 내용을 복사, 결국 스프링부트를 실행하는 컨테이너 내에는 test.jar가 있게 됨 - -ENTRYPOINT ["java", "-jar","test.jar","--encryptor.key=${ENV_KEY}"] -# ENTRYPOINT : 해당 컨테이너 시작할때 무조건 실행할 명령어 지정 \ No newline at end of file diff --git a/back-end/codearena/build.gradle b/back-end/codearena/build.gradle deleted file mode 100644 index 50567bb2..00000000 --- a/back-end/codearena/build.gradle +++ /dev/null @@ -1,54 +0,0 @@ -plugins { - id 'java' - id 'org.springframework.boot' version '3.2.2' - id 'io.spring.dependency-management' version '1.1.4' -} - -group = 'com.ssafy' -version = '0.0.1-SNAPSHOT' - -java { - sourceCompatibility = '17' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - developmentOnly 'org.springframework.boot:spring-boot-devtools' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - implementation group: 'com.mysql', name: 'mysql-connector-j', version: '8.0.33' - implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '3.0.3' - // SMTP 를 위한 mail 의존성 - implementation 'org.springframework.boot:spring-boot-starter-mail' - compileOnly 'org.projectlombok:lombok:1.18.30' - annotationProcessor 'org.projectlombok:lombok:1.18.30' - implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' //jasypt - testCompileOnly 'org.projectlombok:lombok:1.18.30' - testAnnotationProcessor 'org.projectlombok:lombok:1.18.30' - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' //Swagger - // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '3.2.2' - - // https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt - jwt 토큰 의존성 - implementation 'io.jsonwebtoken:jjwt:0.9.1' - - // jaxb 는 jwt를 사용하기 위한 의존성 - // com.sun.xml.bind - implementation 'com.sun.xml.bind:jaxb-impl:4.0.1' - implementation 'com.sun.xml.bind:jaxb-core:4.0.1' - // javax.xml.bind - implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359' - - implementation("com.amazonaws:aws-java-sdk-s3:1.12.174") - - // https://mvnrepository.com/artifact/org.mindrot/jbcrypt - implementation group: 'org.mindrot', name: 'jbcrypt', version: '0.4' - -} - -tasks.named('test') { - useJUnitPlatform() -} diff --git a/back-end/codearena/gradle/wrapper/gradle-wrapper.jar b/back-end/codearena/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/back-end/codearena/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/back-end/codearena/gradle/wrapper/gradle-wrapper.properties b/back-end/codearena/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1af9e093..00000000 --- a/back-end/codearena/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/back-end/codearena/gradlew b/back-end/codearena/gradlew deleted file mode 100644 index 1aa94a42..00000000 --- a/back-end/codearena/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/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/subprojects/plugins/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/back-end/codearena/gradlew.bat b/back-end/codearena/gradlew.bat deleted file mode 100644 index 93e3f59f..00000000 --- a/back-end/codearena/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@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. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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/back-end/codearena/settings.gradle b/back-end/codearena/settings.gradle deleted file mode 100644 index 8dadd2b0..00000000 --- a/back-end/codearena/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'codearena' diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/CodearenaApplication.java b/back-end/codearena/src/main/java/com/ssafy/codearena/CodearenaApplication.java deleted file mode 100644 index 40de1f21..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/CodearenaApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.codearena; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class CodearenaApplication { - - public static void main(String[] args) { - SpringApplication.run(CodearenaApplication.class, args); - } - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/controller/AlarmController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/controller/AlarmController.java deleted file mode 100644 index 409b14db..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/controller/AlarmController.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.ssafy.codearena.alarm.controller; - -import com.ssafy.codearena.alarm.dto.AlarmReceiveDto; -import com.ssafy.codearena.alarm.dto.AlarmResultDto; -import com.ssafy.codearena.alarm.dto.AlarmSendDto; -import com.ssafy.codearena.alarm.service.AlarmService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.tags.Tag; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - - -@RestController -@RequiredArgsConstructor -@RequestMapping("/alarm") -public class AlarmController implements AlarmControllerDocs{ - - private final AlarmService alarmService; - - - @GetMapping("/receive") - public ResponseEntity receive(@RequestParam String userId) { - - //알람조회 서비스 호출 - return new ResponseEntity(alarmService.receive(userId),HttpStatus.OK); - } - - @GetMapping("/send/list") - public ResponseEntity sendList(@RequestParam String userId) { - - return new ResponseEntity(alarmService.sendList(userId), HttpStatus.OK); - } - - - @PostMapping("/send") - public ResponseEntity send(@RequestBody AlarmSendDto alarmSendDto) { - - return new ResponseEntity(alarmService.send(alarmSendDto), HttpStatus.OK); - } - - - @PutMapping("readChange") - public ResponseEntity readChange(@RequestParam String alarmId) { - - return new ResponseEntity(alarmService.readChange(alarmId), HttpStatus.OK); - } - - - @GetMapping("detail") - public ResponseEntity detail(@RequestParam String alarmId) { - - return new ResponseEntity(alarmService.detail(alarmId), HttpStatus.OK); - } - - @PutMapping("statusChange") - public ResponseEntity statusChange(@RequestParam String alarmId, String alarmStatus) { - - return new ResponseEntity(alarmService.statusChange(alarmId, alarmStatus), HttpStatus.OK); - } - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/controller/AlarmControllerDocs.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/controller/AlarmControllerDocs.java deleted file mode 100644 index acf58e75..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/controller/AlarmControllerDocs.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.ssafy.codearena.alarm.controller; - -import com.ssafy.codearena.alarm.dto.AlarmReceiveDto; -import com.ssafy.codearena.alarm.dto.AlarmResultDto; -import com.ssafy.codearena.alarm.dto.AlarmSendDto; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.headers.Header; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestParam; - -import static org.springframework.http.HttpHeaders.AUTHORIZATION; - -@Tag(name = "알림 API", description = "알림에 관한 Controller **알림 타입 = 1 : 문제 생성 요청, 2 : 문제 수정 요청, 3 : 게임 초대, 4 : 공지사항 **") -public interface AlarmControllerDocs { - - @Operation(summary = "수신함 리스트", description = "파라미터로 받은 유저가 수신한 알림 목록을 최신순으로 정렬하여 전달") - @Parameters(value = { - @Parameter(name = "userId", description = "수신함 조회를 위한 유저 아이디") - }) - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "수신함 조회 성공", content = @Content(schema = @Schema(implementation = AlarmReceiveDto.class))), - }) - public ResponseEntity receive(@RequestParam String userId); - - - @Operation(summary = "송신함 리스트", description = "파라미터로 받은 유저가 송신한 알림 목록을 최신순으로 정렬하여 전달") - @Parameter(name = "userId", description = "송신함 조회를 위한 유저 아이디") - public ResponseEntity sendList(@RequestParam String userId); - - - @Operation(summary = "읽음 처리", description = "파라미터로 받은 알림ID에 해당하는 알림의 읽음여부 true 처리") - @Parameter(name = "alarmId", description = "읽음처리 시킬 알림의 번호") - public ResponseEntity readChange(@RequestParam String alarmId); - - - @Operation(summary = "알림 상세 내용 조회", description = "파라미터로 받은 알림ID에 해당하는 상세 내용 전달") - @Parameter(name = "alarmId", description = "조회할 알림의 번호") - public ResponseEntity detail(@RequestParam String alarmId); - - @Operation(summary = "알림 상태 변경", description = "요청 파라미터 : 알림ID, 변경할 상태 명 || 상태 명의 경우 String으로 프론트 프로토콜을 따라감") - @Parameter(name = "alarmId", description = "상태 변경 할 알림의 번호") - @Parameter(name = "alarmStatus", description = "처리할 상태의 값") - public ResponseEntity statusChange(@RequestParam String alarmId, String alarmStatus); - - @Parameters(value = { - @Parameter(name = "alarmType", description = "보내는 알림의 타입"), - @Parameter(name = "toId", description = "받는 유저의 아이디"), - @Parameter(name = "fromId", description = "보내는 유저의 아이디"), - @Parameter(name = "alarmMsg", description = "알림의 내용"), - @Parameter(name = "alarmStatus", description = "알림의 처리상태, Required = false || 요청 시 보내지 않아도 자동 처리됨.") - }) - @Operation(summary = "알림 송신", description = "필요 파라미터 : 알림타입, 수신자ID, 송신자ID, 알림내용 || 알림타입이 1 또는 2라면 status=요청 대기, 3,4라면 status=처리 완료") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "알림 송신 완료", content = @Content(schema = @Schema(implementation = AlarmSendDto.class))) - }) - public ResponseEntity send(AlarmSendDto alarmSendDto); -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmReceiveDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmReceiveDto.java deleted file mode 100644 index f30847db..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmReceiveDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.ssafy.codearena.alarm.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "수신함 조회 시 사용되는 DTO") -public class AlarmReceiveDto { - - @Schema(description = "알림 번호") - private int alarmId; - - @Schema(description = "알림 타입 >> 1 : 문제 생성 요청, 2 : 문제 수정 요청, 3 : 게임 초대, 4 : 공지사항") - private int alarmType; - - @Schema(description = "수신자 닉네임") - private String toNickname; - - @Schema(description = "송신자 닉네임") - private String fromNickname; - - @Schema(description = "알림 내용") - private String alarmMsg; - - @Schema(description = "읽음 여부", requiredMode = Schema.RequiredMode.NOT_REQUIRED) - private String isRead; - - @Schema(description = "알림 송신 날짜", requiredMode = Schema.RequiredMode.NOT_REQUIRED) - private String alarmDate; - - @Schema(description = "알림 상태", requiredMode = Schema.RequiredMode.NOT_REQUIRED) - private String alarmStatus; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmResultDto.java deleted file mode 100644 index cda8c6ed..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmResultDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ssafy.codearena.alarm.dto; - - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "API 응답 형식") -public class AlarmResultDto { - - @Schema(description = "상태 코드") - private String status; - - @Schema(description = "응답 메시지") - private String msg; - - @Schema(description = "응답 객체") - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmSendDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmSendDto.java deleted file mode 100644 index 0f230d37..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/dto/AlarmSendDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ssafy.codearena.alarm.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "알림 송신 DTO") -public class AlarmSendDto { - - @Schema(description = "알림 타입 >> 1 : 문제 생성 요청, 2 : 문제 수정 요청, 3 : 게임 초대, 4 : 공지사항") - private int alarmType; - - @Schema(description = "수신자 ID") - private int toId; - - @Schema(description = "송신자 ID") - private int fromId; - - @Schema(description = "보내는 내용") - private String alarmMsg; - - @Schema(description = "알림 상태", defaultValue = "요청 대기", requiredMode = Schema.RequiredMode.NOT_REQUIRED) - private String alarmStatus; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/mapper/AlarmMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/mapper/AlarmMapper.java deleted file mode 100644 index c0a19975..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/mapper/AlarmMapper.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ssafy.codearena.alarm.mapper; - -import com.ssafy.codearena.alarm.dto.AlarmReceiveDto; -import com.ssafy.codearena.alarm.dto.AlarmSendDto; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; - -@Mapper -public interface AlarmMapper { - List receive(String userId) throws Exception; - List sendList(String userId) throws Exception; - void send(AlarmSendDto alarmSendDto) throws Exception; - AlarmReceiveDto detail(String alarmId) throws Exception; - void readChange(String alarmId) throws Exception; - void statusChange(String alarmId, String alarmStatus) throws Exception; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/service/AlarmService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/service/AlarmService.java deleted file mode 100644 index 5f9490d1..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/service/AlarmService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ssafy.codearena.alarm.service; - -import com.ssafy.codearena.alarm.dto.AlarmReceiveDto; -import com.ssafy.codearena.alarm.dto.AlarmResultDto; -import com.ssafy.codearena.alarm.dto.AlarmSendDto; - -import java.util.List; - -public interface AlarmService { - AlarmResultDto receive(String userId); - AlarmResultDto sendList(String userId); - AlarmResultDto send(AlarmSendDto alarmSendDto); - AlarmResultDto detail(String alarmId); - AlarmResultDto readChange(String alarmId); - AlarmResultDto statusChange(String alarmId, String alarmStatus); - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/service/AlarmServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/service/AlarmServiceImpl.java deleted file mode 100644 index a0d86dde..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/alarm/service/AlarmServiceImpl.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.ssafy.codearena.alarm.service; - -import com.ssafy.codearena.alarm.dto.AlarmReceiveDto; -import com.ssafy.codearena.alarm.dto.AlarmResultDto; -import com.ssafy.codearena.alarm.dto.AlarmSendDto; -import com.ssafy.codearena.alarm.mapper.AlarmMapper; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.GetMapping; - -import java.util.List; - -@Service -@RequiredArgsConstructor -public class AlarmServiceImpl implements AlarmService{ - - private final AlarmMapper alarmMapper; - - @Override - public AlarmResultDto receive(String userId) { - - AlarmResultDto alarmResultDto = new AlarmResultDto(); - - alarmResultDto.setStatus("200"); - alarmResultDto.setMsg("수신함 조회 성공"); - alarmResultDto.setData(null); - - try { - List alarmReceiveDtoList = alarmMapper.receive(userId); - alarmResultDto.setData(alarmReceiveDtoList); - } - catch (Exception e) { - alarmResultDto.setStatus("500"); - alarmResultDto.setMsg("조회 실패"); - } - - - return alarmResultDto; - } - - @Override - public AlarmResultDto sendList(String userId) { - - AlarmResultDto alarmResultDto = new AlarmResultDto(); - - alarmResultDto.setStatus("200"); - alarmResultDto.setMsg("송신함 조회 성공"); - alarmResultDto.setData(null); - - try { - List alarmReceiveDtoList = alarmMapper.sendList(userId); - alarmResultDto.setData(alarmReceiveDtoList); - } - catch (Exception e) { - alarmResultDto.setStatus("500"); - alarmResultDto.setMsg("조회 실패"); - } - - - return alarmResultDto; - - } - - @Override - public AlarmResultDto send(AlarmSendDto alarmSendDto) { - - AlarmResultDto alarmResultDto = new AlarmResultDto(); - - alarmResultDto.setStatus("201"); - alarmResultDto.setMsg("알림 송신 성공"); - alarmResultDto.setData(null); - - try { - if(alarmSendDto.getAlarmType() == 1 || alarmSendDto.getAlarmType() == 2) { - alarmSendDto.setAlarmStatus("요청 대기"); - } - else { - alarmSendDto.setAlarmStatus("처리 완료"); - } - - alarmMapper.send(alarmSendDto); - - } - catch (Exception e) { - alarmResultDto.setStatus("500"); - alarmResultDto.setMsg("송신 실패"); - } - - - return alarmResultDto; - - } - - @Override - public AlarmResultDto detail(String alarmId) { - - AlarmResultDto alarmResultDto = new AlarmResultDto(); - - alarmResultDto.setStatus("200"); - alarmResultDto.setMsg("알림 상세 내용 조회 성공"); - alarmResultDto.setData(null); - - try { - - AlarmReceiveDto alarmReceiveDto = alarmMapper.detail(alarmId); - alarmResultDto.setData(alarmReceiveDto); - - } - catch (Exception e) { - alarmResultDto.setStatus("500"); - alarmResultDto.setMsg("조회 실패"); - } - - - return alarmResultDto; - - } - - @Override - public AlarmResultDto readChange(String alarmId) { - AlarmResultDto alarmResultDto = new AlarmResultDto(); - - alarmResultDto.setStatus("201"); - alarmResultDto.setMsg("알림 읽음처리 성공"); - alarmResultDto.setData(null); - - try { - - alarmMapper.readChange(alarmId); - - } - catch (Exception e) { - alarmResultDto.setStatus("500"); - alarmResultDto.setMsg("변경 실패"); - } - - - return alarmResultDto; - - } - - @Override - public AlarmResultDto statusChange(String alarmId, String alarmStatus) { - - AlarmResultDto alarmResultDto = new AlarmResultDto(); - - alarmResultDto.setStatus("201"); - alarmResultDto.setMsg("알림 상태변경 성공"); - alarmResultDto.setData(null); - - try { - - alarmMapper.statusChange(alarmId, alarmStatus); - - } - catch (Exception e) { - alarmResultDto.setStatus("500"); - alarmResultDto.setMsg("변경 실패"); - } - - - return alarmResultDto; - - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/controller/AuthController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/controller/AuthController.java deleted file mode 100644 index a9082950..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/controller/AuthController.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ssafy.codearena.auth.controller; - -import com.ssafy.codearena.auth.dto.AuthResultDto; -import com.ssafy.codearena.auth.dto.RenewTokenDto; -import com.ssafy.codearena.auth.service.AuthService; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@Slf4j -@RestController -@RequiredArgsConstructor -@RequestMapping("/auth") -public class AuthController { - - private final AuthService authService; - - @GetMapping - public ResponseEntity checkToken(HttpServletRequest request) { - return new ResponseEntity<>(authService.check(request), HttpStatus.OK); - } - - @PostMapping("/renew") - public ResponseEntity renewAccessToken(HttpServletResponse response, @RequestBody RenewTokenDto renewTokenDto) { - return new ResponseEntity<>(authService.renewAccessToken(response, renewTokenDto), HttpStatus.OK); - } - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/AccessTokenDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/AccessTokenDto.java deleted file mode 100644 index f6ec8a62..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/AccessTokenDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.auth.dto; - -import lombok.Data; - -@Data -public class AccessTokenDto { - private String userId; - private String userEmail; - private String userNickname; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/AuthResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/AuthResultDto.java deleted file mode 100644 index ef36fd8b..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/AuthResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.auth.dto; - -import lombok.Data; - -@Data -public class AuthResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/RenewTokenDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/RenewTokenDto.java deleted file mode 100644 index 72d25c14..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/dto/RenewTokenDto.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ssafy.codearena.auth.dto; - -import lombok.Data; - -@Data -public class RenewTokenDto { - private String refreshToken; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/mapper/AuthMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/mapper/AuthMapper.java deleted file mode 100644 index 544ebecf..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/mapper/AuthMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ssafy.codearena.auth.mapper; - -import com.ssafy.codearena.auth.dto.AccessTokenDto; -import com.ssafy.codearena.user.dto.TokenDataDto; - -public interface AuthMapper { - TokenDataDto checkRefreshToken(String refreshToken); -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/service/AuthService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/service/AuthService.java deleted file mode 100644 index 40592e8b..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/service/AuthService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.auth.service; - -import com.ssafy.codearena.auth.dto.AuthResultDto; -import com.ssafy.codearena.auth.dto.RenewTokenDto; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -public interface AuthService { - AuthResultDto check(HttpServletRequest request); - AuthResultDto renewAccessToken(HttpServletResponse response, RenewTokenDto renewTokenDto); -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/service/AuthServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/auth/service/AuthServiceImpl.java deleted file mode 100644 index 4912f84d..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/auth/service/AuthServiceImpl.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.ssafy.codearena.auth.service; - -import com.ssafy.codearena.auth.dto.AccessTokenDto; -import com.ssafy.codearena.auth.dto.AuthResultDto; -import com.ssafy.codearena.auth.dto.RenewTokenDto; -import com.ssafy.codearena.auth.mapper.AuthMapper; -import com.ssafy.codearena.user.dto.TokenDataDto; -import com.ssafy.codearena.user.dto.UserResultDto; -import com.ssafy.codearena.util.JwtUtil; -import io.jsonwebtoken.*; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseCookie; -import org.springframework.stereotype.Service; - -@Service -@Slf4j -@RequiredArgsConstructor -public class AuthServiceImpl implements AuthService { - - private final AuthMapper mapper; - private final JwtUtil jwtUtil; - private final String HEADER_AUTH = "Authorization"; - - - @Override - public AuthResultDto check(HttpServletRequest request) { - - AuthResultDto authResultDto = new AuthResultDto(); - authResultDto.setStatus("200"); - authResultDto.setMsg("토큰 사용 가능"); - authResultDto.setData(null); - - String token = request.getHeader(HEADER_AUTH); - - System.out.println("token = " + token); - - if ("".equals(token) || !jwtUtil.checkToken(token)) { - authResultDto.setStatus("302"); - authResultDto.setMsg("토큰 사용 불가 재발급 요청 필요"); - authResultDto.setData(null); - } - - return authResultDto; - } - - @Override - public AuthResultDto renewAccessToken(HttpServletResponse response, RenewTokenDto renewTokenDto) { - AuthResultDto authResultDto = new AuthResultDto(); - - authResultDto.setStatus("200"); - authResultDto.setMsg("토큰 재발급 완료"); - authResultDto.setData(null); - - String refreshToken = renewTokenDto.getRefreshToken(); - // 재발급 요청이 들어오면 우선 refresh 토큰을 찾아서 확인 - - // 해당 토큰이 사용 가능한지 확인 - if (jwtUtil.checkToken(refreshToken)) { - // 토큰을 가지고 있는 사람이 있는지 확인 - TokenDataDto result = mapper.checkRefreshToken(refreshToken); - - // 해당 토큰을 가진 사람이 있다면 - if (result != null) { - // access 토큰 재발급 해서 보내주기 - String accessToken = jwtUtil.createAccessToken(result); - - response.setHeader(HEADER_AUTH, accessToken); - - } else { - // 해당 refresh 토큰을 가진 사람이 없다면 - authResultDto.setStatus("404"); - authResultDto.setMsg("해당 토큰의 사용자 없음"); - } - } else { - // 토큰이 사용 불가하다면 재 로그인 요청 - authResultDto.setStatus("302"); - authResultDto.setMsg("refreshToken 사용 불가. 로그인 필요"); - } - - return authResultDto; - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/BoardController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/BoardController.java deleted file mode 100644 index 26b2fb82..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/BoardController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ssafy.codearena.board.controller; - - -import com.ssafy.codearena.board.dto.BoardDetailDto; -import com.ssafy.codearena.board.dto.BoardResultDto; -import com.ssafy.codearena.board.dto.BoardUpdateDto; -import com.ssafy.codearena.board.dto.BoardWriteDto; -import com.ssafy.codearena.board.service.BoardService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.sql.SQLException; -import java.util.Map; - - -@RequiredArgsConstructor -@Slf4j -@RestController -@RequestMapping("/board") -public class BoardController implements BoardControllerDocs{ - - private final BoardService boardService; - - - @Override - @GetMapping("/detail/{boardId}") - public ResponseEntity boardDetail(@PathVariable String boardId, HttpServletRequest request) { - - return new ResponseEntity(boardService.boardDetail(boardId, request), HttpStatus.OK); - } - - @Override - @PostMapping("/write") - public ResponseEntity boardWrite(@RequestBody BoardWriteDto boardWriteDto) { - - return new ResponseEntity(boardService.boardWrite(boardWriteDto), HttpStatus.OK); - } - - @Override - @DeleteMapping("/delete/{boardId}") - public ResponseEntity boardDelete(@PathVariable String boardId) { - - return new ResponseEntity(boardService.boardDelete(boardId), HttpStatus.OK); - } - - @Override - @PatchMapping("/update") - public ResponseEntity boardUpdate(@RequestBody BoardUpdateDto boardUpdateDto) { - - return new ResponseEntity(boardService.boardUpdate(boardUpdateDto), HttpStatus.OK); - } - - @GetMapping("/list") - public ResponseEntity boardList(@RequestParam Map map) { - - return new ResponseEntity(boardService.boardList(map), HttpStatus.OK); - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/BoardControllerDocs.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/BoardControllerDocs.java deleted file mode 100644 index 50600257..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/BoardControllerDocs.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ssafy.codearena.board.controller; - -import com.ssafy.codearena.board.dto.BoardDetailDto; -import com.ssafy.codearena.board.dto.BoardUpdateDto; -import com.ssafy.codearena.board.dto.BoardWriteDto; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.servlet.http.HttpServletRequest; -import org.springframework.http.ResponseEntity; - -import java.util.Map; - -@Tag(name = "게시판 API", description = "게시판 관련 API") -public interface BoardControllerDocs { - - @Operation(summary = "게시판 상세조회") - @Parameter(name = "boardId", description = "상세보기 할 게시글의 번호", required = true) - @ApiResponse(responseCode = "200", description = "게시글 상세 조회 성공", content = @Content(schema = @Schema(implementation = BoardDetailDto.class))) - public ResponseEntity boardDetail(String boardId, HttpServletRequest request); - - - @Operation(summary = "게시판 글쓰기") - @Parameter(name = "Object", description = "boardWriteDto", content = @Content(schema = @Schema(implementation = BoardWriteDto.class))) - @ApiResponse(responseCode = "201", description = "게시글 글쓰기 성공") - public ResponseEntity boardWrite(BoardWriteDto boardWriteDto); - - @Operation(summary = "게시판 삭제") - @Parameter(name = "boardId", description = "삭제할 게시글의 번호", required = true) - @ApiResponse(responseCode = "200", description = "게시글 삭제 성공") - public ResponseEntity boardDelete(String boardId); - - //제목, 내용, 코드, 스포방지여부 - @Operation(summary = "게시글 수정") - @Parameter(name = "Object", description = "boardUpdateDto", content = @Content(schema = @Schema(implementation = BoardUpdateDto.class))) - @ApiResponse(responseCode = "200", description = "게시글 수정 성공") - public ResponseEntity boardUpdate(BoardUpdateDto boardUpdateDto); - - @Operation(summary = "게시글 리스트") - @Parameters(value = { - @Parameter(name = "pano", description = "조회할 페이지 번호"), - @Parameter(name = "spp", description = "한 페이지 당 게시글 수 지정"), - @Parameter(name = "boardType", description = "질문 타입", example = "1 : 질문, 2 : 시간복잡도, 3 : 공간복잡도, 4 : 반례 요청, 5 : 반례"), - @Parameter(name = "sortType", description = "정렬 기준", example = "time : 최신순, hit : 조회수순, default : time"), - @Parameter(name = "key", description = "검색 조건", example = "board_title : 제목 기준, problem_id : 문제번호 기준 || DB컬럼명과 똑같이 사용"), - @Parameter(name = "word", description = "검색 조건 기준으로 검색할 내용") - }) - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "게시글 객체", content = @Content(schema = @Schema(implementation = BoardDetailDto.class))) - }) - public ResponseEntity boardList(Map map); - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/CommentController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/CommentController.java deleted file mode 100644 index 0c3aa4d1..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/CommentController.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ssafy.codearena.board.controller; - -import com.ssafy.codearena.board.dto.CommentResultDto; -import com.ssafy.codearena.board.dto.CommentUpdateDto; -import com.ssafy.codearena.board.dto.CommentWriteDto; -import com.ssafy.codearena.board.service.CommentService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RequiredArgsConstructor -@Slf4j -@RestController -@RequestMapping("/comment") -public class CommentController implements CommentControllerDocs{ - - private final CommentService commentService; - - @Override - @PostMapping("/write") - public ResponseEntity commentWrite(@RequestBody CommentWriteDto commentWriteDto) { - - log.info(String.valueOf(commentWriteDto)); - return new ResponseEntity(commentService.commentWrite(commentWriteDto), HttpStatus.OK); - } - - @Override - @GetMapping("/list") - public ResponseEntity commentList(@RequestParam String articleNo) { - - return new ResponseEntity(commentService.commentList(articleNo), HttpStatus.OK); - } - - @Override - @DeleteMapping("/delete") - public ResponseEntity commentDelete(@RequestParam String commentId) { - - return new ResponseEntity(commentService.commentDelete(commentId), HttpStatus.OK); - } - - @Override - @PutMapping("/update") - public ResponseEntity commentUpdate(@RequestBody CommentUpdateDto commentUpdateDto) { - - return new ResponseEntity(commentService.commentUpdate(commentUpdateDto), HttpStatus.OK); - } - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/CommentControllerDocs.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/CommentControllerDocs.java deleted file mode 100644 index 4a3b8b09..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/controller/CommentControllerDocs.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ssafy.codearena.board.controller; - -import com.ssafy.codearena.board.dto.CommentListDto; -import com.ssafy.codearena.board.dto.CommentResultDto; -import com.ssafy.codearena.board.dto.CommentUpdateDto; -import com.ssafy.codearena.board.dto.CommentWriteDto; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestParam; - -@Tag(name = "답글 API", description = "답글 관련 API") -public interface CommentControllerDocs { - - - @Operation(summary = "답글 작성") - @Parameter(description = "답글 작성 시 필요한 파라미터", content = @Content(schema = @Schema(implementation = CommentWriteDto.class))) - @ApiResponse(responseCode = "201", description = "답글 쓰기 성공") - public ResponseEntity commentWrite(CommentWriteDto commentWriteDto); - - @Operation(summary = "답글 조회") - @Parameter(description = "답글 조회 시 필요한 파라미터", content = @Content(schema = @Schema(implementation = CommentListDto.class))) - @ApiResponse(responseCode = "200", description = "답글 조회 성공", content = @Content(schema = @Schema(implementation = CommentListDto.class))) - public ResponseEntity commentList(String articleNo); - - @Operation(summary = "답글 삭제") - @Parameter(description = "답글 삭제 시 필요한 답글 번호") - @ApiResponse(responseCode = "200", description = "답글 삭제 성공") - public ResponseEntity commentDelete(String commentId); - - @Operation(summary = "답글 수정") - @Parameter(description = "답글 수정 시 쓰기와 같이 모든 값이 필수입니다.", content = @Content(schema = @Schema(implementation = CommentWriteDto.class))) - @ApiResponse(responseCode = "200", description = "답글 삭제 성공") - public ResponseEntity commentUpdate(CommentUpdateDto commentUpdateDto); - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardDetailDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardDetailDto.java deleted file mode 100644 index dbdea517..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardDetailDto.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ssafy.codearena.board.dto; - - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "보드 상세조회 DTO") -public class BoardDetailDto { - - @Schema(description = "게시글 번호") - private String articleNo; - - @Schema(description = "작성자 ID") - private String userId; - - @Schema(description = "작성자 닉네임") - private String nickName; - - @Schema(description = "관련 문제 번호") - private String problemId; - - @Schema(description = "제목") - private String title; - - @Schema(description = "질문 타입", example = "1 : 질문, 2 : 시간복잡도, 3 : 공간복잡도, 4 : 반례 요청, 5 : 반례") - private String type; - - @Schema(description = "질문 언어") - private String lang; - - @Schema(description = "게시글 내용") - private String content; - - @Schema(description = "코드") - private String code; - - @Schema(description = "조회수") - private String hit; - - @Schema(description = "스포방지 여부", example = "0 : 전체공개, 1 : 스포방지") - private int spoiler; - - @Schema(description = "문제 풀이 여부", example = "0 : 미풀이, 1 : 풀이") - private String isSolved; - - @Schema(description = "게시 날짜") - private String date; - -} \ No newline at end of file diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardListDto.java deleted file mode 100644 index 28da1e6d..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardListDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -import java.util.List; - -@Data -@Schema(description = "게시글 리스트 조회 DTO") -public class BoardListDto { - - @Schema(description = "게시글 목록") - private List articles; - - @Schema(description = "현재 페이지 번호") - private int currentPage; - - @Schema(description = "전체 페이지 개수") - private int totalPageCount; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardResultDto.java deleted file mode 100644 index 728b807f..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardResultDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ssafy.codearena.board.dto; - - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "API 응답 형식") -public class BoardResultDto { - - @Schema(description = "상태 코드") - private String status; - - @Schema(description = "응답 메시지") - private String msg; - - @Schema(description = "응답 객체") - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardUpdateDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardUpdateDto.java deleted file mode 100644 index 60f87052..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardUpdateDto.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "게시글 수정 DTO") -public class BoardUpdateDto { - @Schema(description = "게시글 번호") - private String articleNo; - - @Schema(description = "작성자 ID") - private String userId; - - @Schema(description = "관련 문제 번호") - private String problemId; - - @Schema(description = "제목") - private String title; - - @Schema(description = "질문 언어") - private String lang; - - @Schema(description = "게시글 내용") - private String content; - - @Schema(description = "코드") - private String code; - - @Schema(description = "스포방지 여부", example = "1 : 스포방지, 2 : 전체공개") - private int spoiler; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardWriteDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardWriteDto.java deleted file mode 100644 index b5b10659..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/BoardWriteDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "게시글 작성 DTO") -public class BoardWriteDto { -// private String articleNo; - - @Schema(description = "작성자 ID") - private String userId; - - @Schema(description = "문제 ID") - private String problemId; - - @Schema(description = "제목") - private String title; - - @Parameter(description = "질문 타입", example = "1 : 질문, 2 : 시간복잡도, 3 : 공간복잡도, 4 : 반례 요청, 5 : 반례") - private String type; - - @Schema(description = "사용 언어", example = "python, c++, java") - private String lang; - - @Schema(description = "질문 내용") - private String content; - - @Schema(description = "코드") - private String code; - - @Schema(description = "스포 방지 여부", example = "1 : 스포방지, 2 : 전체공개") - private int spoiler; - -// private String hit; -// private String date; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentListDto.java deleted file mode 100644 index 1eb87d32..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentListDto.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "해당하는 게시글의 답글 목록을 불러올 때 사용하는 DTO") -public class CommentListDto { - - @Schema(description = "답글 번호") - private String commentId; - - @Schema(description = "게시글 번호") - private String articleNo; - - @Schema(description = "작성자 ID") - private String writerId; - - @Schema(description = "작성자 닉네임") - private String writerNickname; - - @Schema(description = "답글 내용") - private String comment; - - @Schema(description = "답글 코드 블럭") - private String code; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentResultDto.java deleted file mode 100644 index a1d049c2..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentResultDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "API 응답 형식") -public class CommentResultDto { - - @Schema(description = "상태 코드") - private String status; - - @Schema(description = "응답 메시지") - private String msg; - - @Schema(description = "응답 객체") - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentUpdateDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentUpdateDto.java deleted file mode 100644 index 50957bd9..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentUpdateDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "답글 수정을 위한 DTO") -public class CommentUpdateDto { - - @Schema(description = "해당 답글 번호") - private String commentId; - - @Schema(description = "댓글 내용") - private String comment; - - @Schema(description = "답글 코드블럭") - private String code; - - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentWriteDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentWriteDto.java deleted file mode 100644 index 9818a362..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/dto/CommentWriteDto.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ssafy.codearena.board.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "답글 작성을 위한 DTO") -public class CommentWriteDto { - - @Schema(description = "해당 게시글 번호") - private String articleNo; - - @Schema(description = "작성자 ID") - private String userId; - - @Schema(description = "댓글 내용") - private String comment; - - @Schema(description = "답글 코드블럭") - private String code; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/mapper/BoardMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/mapper/BoardMapper.java deleted file mode 100644 index 19154041..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/mapper/BoardMapper.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ssafy.codearena.board.mapper; - -import com.ssafy.codearena.board.dto.BoardDetailDto; -import com.ssafy.codearena.board.dto.BoardListDto; -import com.ssafy.codearena.board.dto.BoardUpdateDto; -import com.ssafy.codearena.board.dto.BoardWriteDto; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -@Mapper -public interface BoardMapper { - public BoardDetailDto boardDetail(String boardId) throws Exception; - public void boardWrite(BoardWriteDto boardWriteDto) throws Exception; - public void boardDelete(String boardId) throws Exception; - public int boardUpdate(BoardUpdateDto boardUpdateDto) throws Exception; - public List boardList(Map param) throws Exception; - public int getTotalBoardCount(Map param) throws Exception; - public void hitUpdate(String boardId) throws Exception; - public int isSolved(String userId, String problemId) throws Exception; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/mapper/CommentMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/mapper/CommentMapper.java deleted file mode 100644 index f8d3e755..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/mapper/CommentMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.codearena.board.mapper; - -import com.ssafy.codearena.board.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; - -@Mapper -public interface CommentMapper { - public void commentWrite(CommentWriteDto commentWriteDto) throws Exception; - public List commentList(String articleNo) throws Exception; - public void commentDelete(String commentId) throws Exception; - public void commentUpdate(CommentUpdateDto commentUpdateDto) throws Exception; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/BoardService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/BoardService.java deleted file mode 100644 index bfb7b611..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/BoardService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ssafy.codearena.board.service; - - -import com.ssafy.codearena.board.dto.BoardDetailDto; -import com.ssafy.codearena.board.dto.BoardResultDto; -import com.ssafy.codearena.board.dto.BoardUpdateDto; -import com.ssafy.codearena.board.dto.BoardWriteDto; -import jakarta.servlet.http.HttpServletRequest; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -public interface BoardService { - public BoardResultDto boardDetail(String boardId, HttpServletRequest request); - public BoardResultDto boardList(Map map); - public BoardResultDto boardWrite(BoardWriteDto boardWriteDto); - public BoardResultDto boardUpdate(BoardUpdateDto boardUpdateDto); - public BoardResultDto boardDelete(String boardId); - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/BoardServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/BoardServiceImpl.java deleted file mode 100644 index 5e3c8e7a..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/BoardServiceImpl.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.ssafy.codearena.board.service; - -import com.ssafy.codearena.board.dto.*; -import com.ssafy.codearena.board.mapper.BoardMapper; -import com.ssafy.codearena.util.JwtUtil; -import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@RequiredArgsConstructor -@Slf4j -@Service -public class BoardServiceImpl implements BoardService{ - - private final BoardMapper boardMapper; - private final JwtUtil jwtUtil; - - @Override - public BoardResultDto boardDetail(String boardId, HttpServletRequest request) { - - BoardResultDto boardResultDto = new BoardResultDto(); - - boardResultDto.setStatus("200"); - boardResultDto.setMsg("조회 성공"); - - String userId = jwtUtil.getUserId(request.getHeader("Authorization")); - - try { - - BoardDetailDto boardDetailDto = boardMapper.boardDetail(boardId); - boardDetailDto.setIsSolved("0"); - - boardMapper.hitUpdate(boardId); //조회수 증가 - - int cnt = boardMapper.isSolved(userId, boardDetailDto.getProblemId()); - - if(cnt > 0) { - //풀이한 문제 - boardDetailDto.setIsSolved("1"); - } - - boardResultDto.setData(boardDetailDto); - - } - catch (Exception e) { - - boardResultDto.setStatus("500"); - boardResultDto.setMsg("Server Internal Error"); - } - - return boardResultDto; - } - - @Override - public BoardResultDto boardList(Map map) { - - BoardResultDto boardResultDto = new BoardResultDto(); - - Map param = new HashMap(); //쿼리 매개변수 - param.put("word", map.get("word") == null ? "" : map.get("word")); //검색조건 있다면 put - param.put("boardType", map.get("boardType") == null ? "" : map.get("boardType")); //질문 타입도 검색조건 default : 1 - param.put("langType", map.get("langType") == null ? "" : map.get("langType")); //언어 타입도 검색조건 - - int currentPage = Integer.parseInt(map.get("pgno") == null ? "1" : map.get("pgno")); //특정 페이지 번호 요청이 없다면 1번 - int sizePerPage = Integer.parseInt(map.get("spp") == null ? "15" : map.get("spp")); - - - int start = currentPage * sizePerPage - sizePerPage; //쿼리로 불러올 인덱스 번호 지정 - - param.put("start", start); - param.put("listSize", sizePerPage); - - - String key = map.get("key"); - param.put("key", key == null ? "" : key); -// if("userId".equals(key)) { -// param.put("key", key == null ? "" : "userId"); -// } - - map.get("sortType"); - param.put("sortType", map.get("sortType")); - - -// log.info(map.get("key") + " : " + map.get("word")); - - try { - List list = boardMapper.boardList(param); - int totalBoardCount = boardMapper.getTotalBoardCount(param); - int totalPageCount = (totalBoardCount - 1) / sizePerPage + 1; - - BoardListDto boardListDto = new BoardListDto(); - boardListDto.setArticles(list); - boardListDto.setCurrentPage(currentPage); - boardListDto.setTotalPageCount(totalPageCount); - - boardResultDto.setStatus("200"); - boardResultDto.setMsg("게시글 목록 불러오기 성공"); - boardResultDto.setData(boardListDto); - } - catch (Exception e) { - - boardResultDto.setStatus("500"); - boardResultDto.setMsg("Server Internal Error"); - boardResultDto.setData(null); - - } - - return boardResultDto; - - } - - @Override - public BoardResultDto boardWrite(BoardWriteDto boardWriteDto) { - - BoardResultDto boardResultDto = new BoardResultDto(); - - boardResultDto.setStatus("201"); - boardResultDto.setMsg("게시판 글쓰기 성공"); - - try { - - log.info(String.valueOf(boardWriteDto)); - boardMapper.boardWrite(boardWriteDto); - boardResultDto.setData(null); - } - catch (Exception e) { - - boardResultDto.setStatus("500"); - boardResultDto.setMsg("Server Internal Error"); - } - - return boardResultDto; - } - - - @Override - public BoardResultDto boardUpdate(BoardUpdateDto boardUpdateDto) { - - BoardResultDto boardResultDto = new BoardResultDto(); - - boardResultDto.setStatus("200"); - boardResultDto.setMsg("게시글 수정 성공"); - boardResultDto.setData(null); - - try { - - int cnt = boardMapper.boardUpdate(boardUpdateDto); - if(cnt == 0) { - - boardResultDto.setStatus("404"); - boardResultDto.setMsg("게시글 번호 혹은 유저 아이디 재확인 필요"); - } - } - catch (Exception e) { - boardResultDto.setStatus("500"); - boardResultDto.setMsg("Server Internal Error"); - } - - return boardResultDto; - } - - @Override - public BoardResultDto boardDelete(String boardId) { - - BoardResultDto boardResultDto = new BoardResultDto(); - - boardResultDto.setStatus("200"); - boardResultDto.setMsg("게시글 삭제 성공"); - boardResultDto.setData(null); - - try { - - boardMapper.boardDelete(boardId); - } - catch (Exception e) { - boardResultDto.setStatus("500"); - boardResultDto.setData("Server Internal Error"); - } - - return boardResultDto; - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/CommentService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/CommentService.java deleted file mode 100644 index e5113f80..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/CommentService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.board.service; - -import com.ssafy.codearena.board.dto.CommentResultDto; -import com.ssafy.codearena.board.dto.CommentUpdateDto; -import com.ssafy.codearena.board.dto.CommentWriteDto; - -public interface CommentService { - public CommentResultDto commentWrite(CommentWriteDto commentWriteDto); - public CommentResultDto commentList(String articleNo); - public CommentResultDto commentDelete(String commentId); - public CommentResultDto commentUpdate(CommentUpdateDto commentUpdateDto); -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/CommentServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/CommentServiceImpl.java deleted file mode 100644 index 0089d1e9..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/board/service/CommentServiceImpl.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.ssafy.codearena.board.service; - -import com.ssafy.codearena.board.dto.CommentListDto; -import com.ssafy.codearena.board.dto.CommentResultDto; -import com.ssafy.codearena.board.dto.CommentUpdateDto; -import com.ssafy.codearena.board.dto.CommentWriteDto; -import com.ssafy.codearena.board.mapper.CommentMapper; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.util.List; - -@RequiredArgsConstructor -@Slf4j -@Service -public class CommentServiceImpl implements CommentService{ - - private final CommentMapper commentMapper; - - @Override - public CommentResultDto commentWrite(CommentWriteDto commentWriteDto) { - - CommentResultDto commentResultDto = new CommentResultDto(); - - commentResultDto.setStatus("201"); - commentResultDto.setMsg("답글 작성 성공"); - commentResultDto.setData(null); - - try { - - log.info(String.valueOf(commentWriteDto)); - commentMapper.commentWrite(commentWriteDto); - } - catch (Exception e) { - e.printStackTrace(); - commentResultDto.setStatus("500"); - commentResultDto.setMsg("Server Internal Error"); - } - - return commentResultDto; - } - - @Override - public CommentResultDto commentList(String articleNo) { - - CommentResultDto commentResultDto = new CommentResultDto(); - - commentResultDto.setStatus("200"); - commentResultDto.setMsg("답글 조회 성공"); - - try { - - List list = commentMapper.commentList(articleNo); - commentResultDto.setData(list); - } - catch (Exception e) { - - commentResultDto.setStatus("500"); - commentResultDto.setMsg("Server Internal Error"); - commentResultDto.setData(null); - } - - - return commentResultDto; - } - - @Override - public CommentResultDto commentDelete(String commentId) { - - CommentResultDto commentResultDto = new CommentResultDto(); - - commentResultDto.setStatus("200"); - commentResultDto.setMsg("답글 삭제 성공"); - commentResultDto.setData(null); - - try { - - commentMapper.commentDelete(commentId); - } - catch (Exception e) { - - commentResultDto.setStatus("500"); - commentResultDto.setMsg("Server Internal Error"); - } - - return commentResultDto; - } - - @Override - public CommentResultDto commentUpdate(CommentUpdateDto commentUpdateDto) { - - CommentResultDto commentResultDto = new CommentResultDto(); - - commentResultDto.setStatus("200"); - commentResultDto.setMsg("답글 수정 성공"); - commentResultDto.setData(null); - try { - - commentMapper.commentUpdate(commentUpdateDto); - } - catch (Exception e) { - - commentResultDto.setStatus("500"); - commentResultDto.setMsg("Server Internal Error"); - } - - return commentResultDto; - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/config/AmazonS3Config.java b/back-end/codearena/src/main/java/com/ssafy/codearena/config/AmazonS3Config.java deleted file mode 100644 index ee9aca92..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/config/AmazonS3Config.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ssafy.codearena.config; - -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.AmazonS3ClientBuilder; -import jakarta.validation.Valid; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class AmazonS3Config{ - - @Value("${cloud.aws.credentials.accessKey}") - private String accessKey; - - @Value("${cloud.aws.credentials.secretKey}") - private String secretKey; - - @Value("${cloud.aws.region.static}") - private String region; - - @Bean - public AmazonS3 getClient() { - - return AmazonS3ClientBuilder - .standard() - .withCredentials( - new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey,secretKey)) - ) - .withRegion(region) - .build(); - } -} \ No newline at end of file diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/config/DataBaseConfiguration.java b/back-end/codearena/src/main/java/com/ssafy/codearena/config/DataBaseConfiguration.java deleted file mode 100644 index d466c088..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/config/DataBaseConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.ssafy.codearena.config; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -import javax.sql.DataSource; - -@Configuration -@PropertySource("classpath:/application.properties") -@MapperScan(basePackages = {"com.ssafy.codearena.*.mapper"}) -public class DataBaseConfiguration{ - - final ApplicationContext applicationContext; - // mapper.xml 위치를 Resource객체 로 들고오기 위해 - - public DataBaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - // ApplicationContext이 Bean을 관리하는 역할을 수행하고 - // SpringBootApplication이 실행될 때 @Configuration 어노테이션이 붙은 java파일을 설정정보로 등록한다. - // 이 때 @Bean으로 등록된 메서드들을 기반으로 빈 목록을 생성한다. - @ConfigurationProperties(prefix = "spring.datasource.hikari") - public HikariConfig hikariConfig() { - // application.properties 파일에서 spring.datasource.hikari로 시작하는 설정 값들을 가져와 Hikari 설정 객체를 반환한다. - return new HikariConfig(); - } - - @Bean - public DataSource dataSource() { - // HikariDataSource를 사용하기 위해 Hikari 설정 객체를 생성자로 넣은 HikariDataSource 객체 반환 - return new HikariDataSource(hikariConfig()); - } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { - // SqlSessionFactory는 Mybatis-spring 때 처럼 SqlSessionFactoryBean을 통해 생성되는데 - // 각종 typeAliase(DTO), mapperLocation(xml위치), DB접속정보(datasource)를 property를 통해 추가한다. - // 즉 setter를 통해 추가된다. - - SqlSessionFactoryBean session = new SqlSessionFactoryBean(); - session.setDataSource(dataSource); - session.setMapperLocations(applicationContext.getResources("classpath:mapper/**/*.xml")); - session.setTypeAliasesPackage("com.ssafy.codearena.*.dto"); - return session.getObject(); - } - - @Bean - public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { - // SqlSessionTemplate은 SqlSession인터페이스 타입의 객체이며 - // 결국 SqlSessionFactory의 각종 설정 정보를 통해 만들어지므로 생성자로 넣게 된다. - return new SqlSessionTemplate(sqlSessionFactory); - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/config/JasyptConfig.java b/back-end/codearena/src/main/java/com/ssafy/codearena/config/JasyptConfig.java deleted file mode 100644 index 959cc11c..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/config/JasyptConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ssafy.codearena.config; - - -import org.jasypt.encryption.StringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class JasyptConfig { - - @Value("${encryptor.key}") - String KEY; - - private static final String ALGORITHM = "PBEWithMD5AndDES"; - - @Bean(name = "jasyptStringEncryptor") - public StringEncryptor stringEncryptor() { - PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); - SimpleStringPBEConfig config = new SimpleStringPBEConfig(); - - config.setPassword(KEY); //암호화 시 사용할 키 -> 이 키를 가지고 암호화 복호화 진행 - config.setAlgorithm(ALGORITHM); //사용할 알고리즘 - config.setKeyObtentionIterations("1000"); //반복할 해싱 회수 - config.setPoolSize("1"); //pool 크기 - config.setProviderName("SunJCE"); //사용할 암호화 라이브러리 - config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); //salt 생성 클래스 - config.setStringOutputType("base64"); //인코딩 방식 - encryptor.setConfig(config); //설정 주입 - - return encryptor; - - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/config/SwaggerConfig.java b/back-end/codearena/src/main/java/com/ssafy/codearena/config/SwaggerConfig.java deleted file mode 100644 index 8f834b38..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/config/SwaggerConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.codearena.config; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration // 스프링 실행시 설정파일 읽어드리기 위한 어노테이션 -public class SwaggerConfig { - - @Bean - public OpenAPI openAPI() { - return new OpenAPI() - .components(new Components()) - .info(apiInfo()); - } - - private Info apiInfo() { - return new Info() - .title("CodeArena Swagger") - .description("CodeArena 유저 및 인증 , ps, 알림에 관한 REST API") - .version("1.0.0"); - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/config/WebMvcConfiguration.java b/back-end/codearena/src/main/java/com/ssafy/codearena/config/WebMvcConfiguration.java deleted file mode 100644 index e52e5f8b..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/config/WebMvcConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ssafy.codearena.config; - -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@RequiredArgsConstructor -public class WebMvcConfiguration implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry - .addMapping("/**") -// .allowedOrigins("http://192.168.0.29:3000") - .allowedOriginPatterns("*") -// .allowedOrigins("http://localhost:5173", "http://localhost:5174") - .allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), - HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(), - HttpMethod.PATCH.name()) -// .allowedHeaders("Authorization") -// .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD") - .allowCredentials(true) - .exposedHeaders("Authorization") - .maxAge(1800); // Pre-flight Caching - } - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/controller/ProblemController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/controller/ProblemController.java deleted file mode 100644 index e9709f18..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/controller/ProblemController.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.ssafy.codearena.problem.controller; - - -import com.ssafy.codearena.problem.dto.ProblemDetailDto; -import com.ssafy.codearena.problem.dto.ProblemForInsertDto; -import com.ssafy.codearena.problem.dto.ResultDto; -import com.ssafy.codearena.problem.dto.SubmitDto; -import com.ssafy.codearena.problem.service.ProblemService; -import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import javax.xml.transform.Result; -import java.util.HashMap; - -@RestController -@RequestMapping("/problem") -@RequiredArgsConstructor -@Slf4j -public class ProblemController { - - private final ProblemService service; - @GetMapping - private ResponseEntity getProblemList(@RequestParam HashMap map){ - ResultDto resultDto = service.getProblemList(map); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @PostMapping - private ResponseEntity insertProblem(@RequestBody ProblemForInsertDto problemForInsertDto){ - log.debug("params : {}", problemForInsertDto); - ResultDto resultDto = service.insertProblem(problemForInsertDto); - - - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @DeleteMapping("{problemId}") - private ResponseEntity deleteProblem(@PathVariable String problemId){ - log.debug("params : {}", problemId); - ResultDto resultDto = service.deleteProblem(problemId); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - @PutMapping("{problemId}") - private ResponseEntity updateProblem(@RequestBody ProblemForInsertDto problemForInsertDto){ - log.debug("params : {}", problemForInsertDto); - ResultDto resultDto = service.updateProblem(problemForInsertDto); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @GetMapping("{problemId}/modify") - private ResponseEntity getProblemForUpdate(@PathVariable String problemId){ - log.debug("params : ", problemId); - ResultDto resultDto = service.getProblemDetailForUpdate(problemId); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @GetMapping("/category") - private ResponseEntity getAllCategories(){ - ResultDto resultDto = service.getTagCategory(); - return new ResponseEntity(resultDto, HttpStatus.OK); - } - @GetMapping("{problemId}") - private ResponseEntity getProblemDetail(@PathVariable String problemId, HttpServletRequest request){ - ResultDto resultDto = service.getProblemDetail(problemId, request); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - @GetMapping("{problemId}/testcase") - private ResponseEntity getTestCase(@PathVariable String problemId){ - ResultDto resultDto = service.getTestCase(problemId); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @PostMapping("{problemId}/submit") - private ResponseEntity submitCode(@PathVariable String problemId, @RequestBody SubmitDto submitDto){ - ResultDto resultDto = service.insertSubmit(problemId, submitDto); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @GetMapping("/submit") - private ResponseEntity getSubmitList(@RequestParam HashMap params){ - ResultDto resultDto = service.getSubmitList(params); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - @GetMapping("{problemId}/submit/statistics") - private ResponseEntity getStatistics(@PathVariable String problemId, @RequestParam HashMap params){ - ResultDto resultDto = service.getSubmitStatistics(problemId, params); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } - - @PutMapping("{problemId}/status") - private ResponseEntity changeStatus(@PathVariable String problemId, @RequestBody HashMap params, HttpServletRequest request){ - log.debug("param : {}", params); - ResultDto resultDto = service.updateProblemStatus(problemId, params, request); - return new ResponseEntity<>(resultDto, HttpStatus.OK); - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/controller/ProblemControllerDocs.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/controller/ProblemControllerDocs.java deleted file mode 100644 index 5edc2910..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/controller/ProblemControllerDocs.java +++ /dev/null @@ -1,2 +0,0 @@ -package com.ssafy.codearena.problem.controller;public interface ProblemControllerDocs { -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/AvgByLangDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/AvgByLangDto.java deleted file mode 100644 index 6b6f3ee0..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/AvgByLangDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -@Data -public class AvgByLangDto { - int cpp; - int java; - int python; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemDetailDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemDetailDto.java deleted file mode 100644 index 50a34f0d..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemDetailDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class ProblemDetailDto { - private String problemTitle; - private String problemContent; - private String problemId; - private String submitCount; - private String acceptCount; - private String percentage; - private String userId; - private String userNickname; - private String problemInputDesc; - private String problemOutputDesc; - private String problemTime; - private String problemMem; - private String problemExInput; - private String problemExOutput; - private String problemVisibility; - private List tagList; - private Boolean isSolve; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemForInsertDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemForInsertDto.java deleted file mode 100644 index c0b17238..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemForInsertDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class ProblemForInsertDto { - private String userId; - private Integer problemId; - private String problemTitle; - private String problemContent; - private String problemInputDesc; - private String problemOutputDesc; - private String problemValidationCode; - private String problemValidationLang; - private String problemExInput; - private String problemExOutput; - private String problemTime; - private String problemMem; - private Integer problemRating; - private List testCase; - private List tagList; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemListDto.java deleted file mode 100644 index 51e47f5b..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemListDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.codearena.problem.dto; - -import lombok.Data; - -import java.util.List; - - -@Data -public class ProblemListDto { - private int itemCount; - private int pageCount; - private List problemWithSearch; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemWithSearchDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemWithSearchDto.java deleted file mode 100644 index 409c5c75..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ProblemWithSearchDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -@Data -public class ProblemWithSearchDto { - String problemId; - String userNickname; - String problemTitle; - String problemRating; - String submitCount; - String acceptCount; - String percentage; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/RatioOfAlgoDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/RatioOfAlgoDto.java deleted file mode 100644 index 17d64057..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/RatioOfAlgoDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -@Data -public class RatioOfAlgoDto { - String tagName; - String count; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ResultDto.java deleted file mode 100644 index 6662a173..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/ResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.problem.dto; - -import lombok.Data; - -@Data -public class ResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SearchDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SearchDto.java deleted file mode 100644 index fcba9ede..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SearchDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -@Data -public class SearchDto { - private String cate; - private String pgno; - private String spp; - private String word; - private String orderBy; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SolveAndUnsolveDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SolveAndUnsolveDto.java deleted file mode 100644 index 4ec7c886..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SolveAndUnsolveDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.codearena.problem.dto; - -import lombok.Data; - -import java.util.List; - - -@Data -public class SolveAndUnsolveDto { - private int solveCount; - private int unSolveCount; - private List solveList; - private List unSolveList; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitDto.java deleted file mode 100644 index 16d50ae3..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitDto.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class SubmitDto { - Integer submitNo; - Integer tid; - String userId; - String userNickname; - String problemId; - String submitLang; - String code; - String submitStatus; - String timeComplexity; - String memory; - String submitDate; - TestCaseDto testCase; - List tagList; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitListDto.java deleted file mode 100644 index e5341c85..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitListDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class SubmitListDto { - private int itemCount; - private int pageCount; - private List submitList; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitStatisticDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitStatisticDto.java deleted file mode 100644 index cca9a397..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitStatisticDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class SubmitStatisticDto { - AvgByLangDto avgByLang; - List ratioOfAlgo; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitTagDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitTagDto.java deleted file mode 100644 index f76b04aa..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitTagDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.problem.dto; - -import lombok.Data; - -@Data -public class SubmitTagDto { - private String submitNo; - private String tagName; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitTagListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitTagListDto.java deleted file mode 100644 index e51dc1a9..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/SubmitTagListDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -import java.util.List; - -@Data -public class SubmitTagListDto { - private Integer submitNo; - private List tagList; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TCListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TCListDto.java deleted file mode 100644 index 0ac3413e..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TCListDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.problem.dto; - -import lombok.Data; - -import java.util.List; - - -@Data -public class TCListDto { - private Integer problemId; - private List testCase; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TagDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TagDto.java deleted file mode 100644 index 32592616..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TagDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -@Data -public class TagDto { - String tagId; - String tagName; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TagListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TagListDto.java deleted file mode 100644 index f8e76123..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TagListDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.problem.dto; - -import lombok.Data; - -import java.util.List; - - -@Data -public class TagListDto { - private Integer problemId; - private List tagList; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TestCaseDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TestCaseDto.java deleted file mode 100644 index b2f3098b..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/dto/TestCaseDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.problem.dto; - - -import lombok.Data; - -@Data -public class TestCaseDto { - private Integer tid; - private String input; - private String output; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/mapper/ProblemMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/mapper/ProblemMapper.java deleted file mode 100644 index 76d39e33..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/mapper/ProblemMapper.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ssafy.codearena.problem.mapper; - - -import com.ssafy.codearena.problem.dto.*; -import com.ssafy.codearena.user.dto.UserProblemCateDto; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; - -@Mapper -public interface ProblemMapper { - List selectProblemList(HashMap hashMap) throws SQLException; - int problemCount(HashMap hashMap) throws SQLException; - void insertProblem(ProblemForInsertDto problemForInsertDto) throws SQLException; - void insertTestCase(TCListDto tcListDto) throws SQLException; - void insertProblemTagList(TagListDto tagListDto) throws SQLException; - void deleteProblem(String problemId) throws SQLException; - List getAllTagNames() throws SQLException; - ProblemDetailDto getProblemDetailByProblemId(String problemId) throws SQLException; - List getTestCasesByProblemId(String problemId) throws SQLException; - void insertSubmit(SubmitDto submitDto) throws SQLException; - void insertSubmitTags(SubmitTagListDto submitTagListDto) throws SQLException; - List getSubmitList(HashMap params) throws SQLException; - int getSubmitCount(HashMap params) throws SQLException; - - AvgByLangDto getAvgByLang(String problemId) throws SQLException; - - List getRatioOfAlgo(String problemId) throws SQLException; - - int isAccept(HashMap params) throws SQLException; - - ProblemForInsertDto getProblemDetailForUpdateByProblemId(String problemId) throws SQLException; - - void deleteProblemTagsByProblemId(int problemId) throws SQLException; - - int updateProblemByProblemId(ProblemForInsertDto problemForInsertDto) throws SQLException; - - int updateProblemStatusByProblemId(HashMap params) throws SQLException; - - List getSolveListByUserNickname(String nickName) throws SQLException; - List getUnsolveListByUserNickname(String nickName) throws SQLException; - - List getProblemCateByNickname(String nickName) throws SQLException; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/service/ProblemService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/service/ProblemService.java deleted file mode 100644 index 6651c106..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/service/ProblemService.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ssafy.codearena.problem.service; - -import com.ssafy.codearena.problem.dto.*; -import com.ssafy.codearena.user.dto.UserProblemCateDto; -import jakarta.servlet.http.HttpServletRequest; - -import java.util.HashMap; -import java.util.List; - -public interface ProblemService { - ResultDto getProblemList(HashMap map); - - ResultDto insertProblem(ProblemForInsertDto problemForInsertDto); - - ResultDto deleteProblem(String problemId); - - ResultDto getTagCategory(); - ResultDto getProblemDetail(String problemId, HttpServletRequest request); - ResultDto getTestCase(String problemId); - ResultDto insertSubmit(String problemId, SubmitDto submitDto); - ResultDto getSubmitList(HashMap params); - ResultDto getSubmitStatistics(String problemId, HashMap params); - ResultDto getProblemDetailForUpdate(String problemId); - ResultDto updateProblem(ProblemForInsertDto problemForInsertDto); - ResultDto updateProblemStatus(String problemId, HashMap params, HttpServletRequest request); - SolveAndUnsolveDto getSolveAndUnsolveList(String nickName) throws Exception; - List getProblemCateList(String nickName) throws Exception; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/service/ProblemServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/problem/service/ProblemServiceImpl.java deleted file mode 100644 index 1e0787bd..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/problem/service/ProblemServiceImpl.java +++ /dev/null @@ -1,558 +0,0 @@ -package com.ssafy.codearena.problem.service; - - -import com.ssafy.codearena.alarm.dto.AlarmSendDto; -import com.ssafy.codearena.alarm.mapper.AlarmMapper; -import com.ssafy.codearena.alarm.service.AlarmService; -import com.ssafy.codearena.problem.dto.*; -import com.ssafy.codearena.problem.mapper.ProblemMapper; -import com.ssafy.codearena.user.dto.UserProblemCateDto; -import com.ssafy.codearena.util.JwtUtil; -import jakarta.mail.AuthenticationFailedException; -import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.ibatis.transaction.Transaction; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.dao.DataAccessResourceFailureException; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.web.reactive.function.client.WebClient; - -import javax.xml.transform.Result; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -@Service -@RequiredArgsConstructor -@Slf4j -public class ProblemServiceImpl implements ProblemService{ - - private final ProblemMapper mapper; - - private final AlarmService alarmService; - private final JwtUtil jwtUtil; - private static final int ADMIN_ID = 1; - - private static final int ALARM_TYPE = 1; - private static final int BASIC_SPP = 15; - private static final int BASIC_PGNO = 1; - - @Value("${judge.java.url}") - private String judgeJava; - - @Value("${judge.cpp.url}") - private String judgecpp; - - @Value("${judge.python.url}") - private String judgepython; - - - @Override - public ResultDto getProblemList(HashMap map) { - ResultDto resultDto = new ResultDto(); - HashMap hashMap = new HashMap<>(); - ProblemListDto problemListDto = new ProblemListDto(); - try{ - int spp = BASIC_SPP; - String sppParam = ""; - int pgno = BASIC_PGNO; - String pgnoParam = ""; - if(map.containsKey("spp")) { - sppParam = map.get("spp"); - } - if(sppParam!=null && !"".equals(sppParam)){ - spp = Integer.parseInt(sppParam); - } - if(map.containsKey("pgno")){ - pgnoParam = map.get("pgno"); - } - if(pgnoParam!=null && !"".equals(pgnoParam)){ - pgno = Integer.parseInt(pgnoParam); - } - String cate = ""; - if(map.containsKey("cate")){ - cate = map.get("cate"); - } - switch(cate) { - case "problemTitle": - cate = "problem_title"; - break; - case "problemId": - cate = "problem_id"; - break; - case "userNickname": - cate = "user_nickname"; - break; - } - hashMap.put("cate", cate); - String word = ""; - if(map.containsKey("word")){ - word = map.get("word"); - } - hashMap.put("word", word); - String tag = ""; - if(map.containsKey("tag")){ - tag = map.get("tag"); - } - hashMap.put("tag", tag); - int totalItemCount = mapper.problemCount(hashMap); - int totalPageCount = 1; - if(totalItemCount > spp) totalPageCount = (totalItemCount%spp) == 0 ? totalItemCount/spp : totalItemCount/spp+1; - - - if(pgno > totalPageCount) pgno = totalPageCount; - String orderBy = ""; - if(map.containsKey("orderBy")){ - orderBy = map.get("orderBy"); - } - switch(orderBy){ - case "date": - orderBy = "problem_date"; - break; - case "submit": - orderBy = "submit_count"; - break; - case "accept": - orderBy = "accept_count"; - break; - default: - orderBy = "percentage"; - break; - } - hashMap.put("orderBy", orderBy); - hashMap.put("start", String.valueOf((pgno-1) * spp)); - hashMap.put("offset", String.valueOf(spp)); - List list = mapper.selectProblemList(hashMap); - problemListDto.setProblemWithSearch(list); - problemListDto.setItemCount(totalItemCount); - problemListDto.setPageCount(totalPageCount); - resultDto.setStatus("200"); - resultDto.setMsg("검색 결과가 "+problemListDto.getItemCount()+"건 존재합니다."); - if(problemListDto.getItemCount() == 0){ - resultDto.setStatus("202"); - } - resultDto.setData(problemListDto); - }catch(Exception e){ - resultDto.setStatus("500"); - resultDto.setMsg("검색중 문제가 발생하였습니다."); - e.printStackTrace(); - }finally{ - return resultDto; - } - } - - @Override - public ResultDto insertProblem(ProblemForInsertDto problemForInsertDto) { - ResultDto resultDto = new ResultDto(); - try{ - mapper.insertProblem(problemForInsertDto); - TCListDto tcListDto = new TCListDto(); - tcListDto.setProblemId(problemForInsertDto.getProblemId()); - tcListDto.setTestCase(problemForInsertDto.getTestCase()); - log.debug("testcase : {}",tcListDto); - mapper.insertTestCase(tcListDto); - TagListDto tagListDto = new TagListDto(); - tagListDto.setProblemId(problemForInsertDto.getProblemId()); - tagListDto.setTagList(problemForInsertDto.getTagList()); - mapper.insertProblemTagList(tagListDto); - - resultDto.setStatus("201"); - resultDto.setMsg("문제 임시 생성 및 요청이 성공적으로 보내졌습니다."); - AlarmSendDto alarmSendDto = new AlarmSendDto(); - - alarmSendDto.setAlarmMsg("문제 확인 부탁드립니다. 문제번호 : "+ problemForInsertDto.getProblemId()); - alarmSendDto.setAlarmType(ALARM_TYPE); - alarmSendDto.setAlarmStatus("요청 대기"); - alarmSendDto.setFromId(Integer.parseInt(problemForInsertDto.getUserId())); - alarmSendDto.setToId(ADMIN_ID); - alarmService.send(alarmSendDto); - }catch(Exception e){ - log.error("exception : {}", e); - resultDto.setStatus("500"); - resultDto.setMsg("문제 생성 로직 중 문제가 발생하였습니다."); - }finally{ - return resultDto; - } - - } - - @Override - public ResultDto deleteProblem(String problemId) { - ResultDto resultDto = new ResultDto(); - resultDto.setMsg("해당 문제가 성공적으로 삭제되었습니다."); - resultDto.setStatus("200"); - try{ - mapper.deleteProblem(problemId); - }catch(Exception e){ - log.error("exceptino : {}", e); - resultDto.setStatus("500"); - resultDto.setMsg("삭제 도중 에러가 발생하였습니다."); - }finally{ - return resultDto; - } - } - - @Override - public ResultDto getTagCategory() { - ResultDto resultDto = new ResultDto(); - try{ - List tagList = mapper.getAllTagNames(); - resultDto.setStatus("200"); - resultDto.setMsg("태그 목록을 불러오는데 성공하였습니다."); - resultDto.setData(tagList); - }catch(Exception e){ - log.error("exception : {}", e); - resultDto.setData(null); - resultDto.setStatus("500"); - resultDto.setMsg("태그 목록을 불러오는 도중 에러가 발생하였습니다."); - }finally{ - return resultDto; - } - } - - @Override - public ResultDto getProblemDetail(String problemId, HttpServletRequest request) { - ResultDto resultDto = new ResultDto(); - ProblemDetailDto problemDetail = new ProblemDetailDto(); - resultDto.setMsg("문제 번호 "+problemId+"에 대한 정보를 조회하는데 성공했습니다."); - resultDto.setData(problemDetail); - resultDto.setStatus("200"); - try{ - HashMap params = new HashMap<>(); - params.put("problemId", problemId); - String token = request.getHeader("Authorization"); - log.debug("token : {}",token); - problemDetail = mapper.getProblemDetailByProblemId(problemId); - //log.debug("{}",jwtUtil.isAdmin(token)); - String userId = ""; - problemDetail.setIsSolve(true); - if("0".equals(problemDetail.getProblemVisibility()) && (token==null || "".equals(token) || !jwtUtil.isAdmin(token))) throw new AuthenticationFailedException("권한 없음"); - if("1".equals(problemDetail.getProblemVisibility()) && (token==null || "".equals(token))) problemDetail.setIsSolve(false); - else userId = jwtUtil.getUserId(token); - if(userId !=null && !"".equals(userId)){ - params.put("userId", userId); - int isAccept = mapper.isAccept(params); - problemDetail.setIsSolve((isAccept >= 1)); - } - }catch(AuthenticationFailedException e){ - log.debug("exception : {}", e); - resultDto.setStatus("403"); - resultDto.setMsg("접근 권한이 없습니다."); - problemDetail =null; - }catch(Exception e){ - log.debug("exception : {}", e); - resultDto.setStatus("500"); - resultDto.setMsg("문제 번호 "+problemId+"에 대한 정보를 조회하는데 에러가 발생하였습니다."); - problemDetail = null; - }finally{ - resultDto.setData(problemDetail); - return resultDto; - } - } - - @Override - public ResultDto getTestCase(String problemId) { - ResultDto resultDto = new ResultDto(); - List testcase = Collections.EMPTY_LIST; - resultDto.setStatus("202"); - resultDto.setMsg("문제번호 : "+problemId+"에 대한 테스트케이스가 비었습니다."); - try{ - testcase = mapper.getTestCasesByProblemId(problemId); - if(!testcase.isEmpty()){ - resultDto.setStatus("200"); - resultDto.setMsg("문제번호 : "+problemId+"에 대한 테스트케이스 조회에 성공했습니다."); - } - }catch(Exception e){ - testcase = Collections.EMPTY_LIST; - resultDto.setMsg("문제번호 : "+problemId+" 에 대한 테스트케이스 조회 중 에러가 발생하였습니다."); - }finally{ - resultDto.setData(testcase); - return resultDto; - } - } - private WebClient getClient(String lang){ - switch(lang){ - case "java": - return WebClient.create(judgeJava); - - case "cpp": - return WebClient.create(judgecpp); - - default: - return WebClient.create(judgepython); - - } - } - @Override - public ResultDto insertSubmit(String problemId, SubmitDto submitDto) { - ResultDto resultDto = new ResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("성공적으로 채점서버에 제출되었습니다."); - submitDto.setSubmitStatus("채점중"); - submitDto.setProblemId(problemId); - log.debug("params : {}", submitDto); - try{ - mapper.insertSubmit(submitDto); - WebClient client = getClient(submitDto.getSubmitLang()); - Integer submitNo = submitDto.getSubmitNo(); - HashMap params = new HashMap<>(); - params.put("submitNo", String.valueOf(submitNo)); - params.put("userId", null); - params.put("problemId", submitDto.getProblemId()); - params.put("code", submitDto.getCode()); - SubmitTagListDto listDto = new SubmitTagListDto(); - listDto.setSubmitNo(submitDto.getSubmitNo()); - listDto.setTagList(submitDto.getTagList()); - if(!listDto.getTagList().isEmpty()){ - mapper.insertSubmitTags(listDto); - } - client.post().uri("/judge/normal").contentType(MediaType.APPLICATION_JSON).bodyValue(params).retrieve().bodyToMono(HashMap.class).subscribe(); - - }catch(Exception e){ - log.debug("exception {}", e); - resultDto.setStatus("500"); - resultDto.setMsg("채점 시도 중 에러가 발생하였습니다."); - }finally{ - return resultDto; - } - - } - - @Override - public ResultDto getSubmitList(HashMap params) { - log.debug("from client parasm : {}", params); - ResultDto resultDto = new ResultDto(); - SubmitListDto list = new SubmitListDto(); - List submitList = new ArrayList<>(); - list.setItemCount(0); - list.setPageCount(BASIC_PGNO); - resultDto.setStatus("202"); - - try{ - int spp = BASIC_SPP; - String problemId = ""; - String userNickname = ""; - String lang = ""; - String orderBy= ""; - String pgnoParam = ""; - String sppParam = ""; - boolean onlySolve = false; - int pgno = BASIC_PGNO; - if(params.containsKey("spp") && Integer.parseInt(params.get("spp")) > 0){ - sppParam = params.get("spp"); - } - if(params.containsKey("problemId")){ - problemId = params.get("problemId"); - } - if(params.containsKey("userNickname")){ - userNickname = params.get("userNickname"); - } - if(params.containsKey("lang")){ - lang = params.get("lang"); - } - if(params.containsKey("orderBy")){ - orderBy = params.get("orderBy"); - log.debug("orderBy params : {}", orderBy); - } - if("timeComplexity".equals(orderBy)){ - onlySolve = true; - log.debug("onlySolve : {}", params.get("onlySolve")); - } - if(params.containsKey("pgno")){ - pgnoParam = params.get("pgno"); - } - if(pgnoParam != null && !"".equals(pgnoParam)){ - pgno = Integer.parseInt(pgnoParam); - } - if(sppParam != null && !"".equals(sppParam)){ - spp = Integer.parseInt(sppParam); - } - params = new HashMap<>(); - if(onlySolve) params.put("onlySolve", "1"); - params.put("problemId", problemId); - params.put("userNickname", userNickname); - params.put("lang", lang); - log.debug("count params : {}", params); - int itemCount = mapper.getSubmitCount(params); - int pageCount = BASIC_PGNO; - if(itemCount > spp) pageCount = (itemCount%spp) == 0 ? itemCount/spp : itemCount/spp+1; - if(pageCount < pgno){ - pgno = BASIC_PGNO; - } - resultDto.setMsg("검색 결과 "+itemCount+"건 검색되었습니다."); - if(itemCount > 0){ - params.put("start", String.valueOf((pgno-1) * spp)); - params.put("offset", String.valueOf(spp)); - switch(orderBy){ - case "timeComplexity": - orderBy = "time_complexity"; - break; - default : - orderBy = "submit_date"; - break; - } - params.put("orderBy", orderBy); - resultDto.setStatus("200"); - submitList = mapper.getSubmitList(params); - list.setPageCount(pageCount); - list.setItemCount(itemCount); - } - - }catch(Exception e){ - log.debug("exception {}", e); - submitList = Collections.EMPTY_LIST; - resultDto.setMsg("채점 현황 조회 중 에러가 발생하였습니다."); - resultDto.setStatus("500"); - }finally{ - list.setSubmitList(submitList); - resultDto.setData(list); - return resultDto; - } - } - - @Override - public ResultDto getSubmitStatistics(String problemId, HashMap params) { - SubmitStatisticDto submitStatistic = null; - ResultDto resultDto = new ResultDto(); - resultDto.setStatus("403"); - resultDto.setMsg("권한이 없습니다."); - params.put("problemId", problemId); - try{ - String userId = ""; - boolean isAccept = false; - if(params.containsKey("userId")){ - userId = params.get("userId"); - } - if(!"".equals(userId)){ - params.put("userId", userId); - isAccept = mapper.isAccept(params) >= 1; - } - if(isAccept){ - AvgByLangDto avgByLangDto = mapper.getAvgByLang(problemId); - List ratioOfAlgoDto = mapper.getRatioOfAlgo(problemId); - submitStatistic = new SubmitStatisticDto(); - submitStatistic.setAvgByLang(avgByLangDto); - submitStatistic.setRatioOfAlgo(ratioOfAlgoDto); - resultDto.setMsg("통계 데이터 조회에 성공했습니다."); - resultDto.setStatus("200"); - } - }catch(Exception e){ - log.debug("exception : {}", e); - resultDto.setMsg("통계 데이터를 불러오는 중 에러가 발생했습니다."); - resultDto.setStatus("500"); - }finally{ - resultDto.setData(submitStatistic); - return resultDto; - } - } - - @Override - public ResultDto getProblemDetailForUpdate(String problemId) { - ResultDto resultDto = new ResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("문제 업데이트를 위한 정보 불러오기에 성공했습니다."); - ProblemForInsertDto problem = new ProblemForInsertDto(); - try{ - problem = mapper.getProblemDetailForUpdateByProblemId(problemId); - }catch(Exception e){ - log.debug("exception : ", e); - resultDto.setStatus("500"); - resultDto.setMsg("문제가 발생했습니다."); - }finally{ - resultDto.setData(problem); - return resultDto; - } - } - - @Override - @Transactional(propagation = Propagation.REQUIRED) - public ResultDto updateProblem(ProblemForInsertDto problemForInsertDto) { - ResultDto resultDto = new ResultDto(); - resultDto.setMsg("문제정보가 정상적으로 업데이트 되었습니다."); - resultDto.setStatus("200"); - try{ - int update = mapper.updateProblemByProblemId(problemForInsertDto); - if(update == 0) throw new DataIntegrityViolationException("PK 오류"); - TagListDto tagListDto = new TagListDto(); - int problemId = problemForInsertDto.getProblemId(); - tagListDto.setProblemId(problemId); - tagListDto.setTagList(problemForInsertDto.getTagList()); - mapper.deleteProblemTagsByProblemId(problemId); - mapper.insertProblemTagList(tagListDto); - }catch(DataIntegrityViolationException e){ - log.debug("exception : {}", e); - resultDto.setStatus("404"); - resultDto.setMsg("해당하는 문제 정보를 찾을 수 없습니다."); - }catch(Exception e){ - log.debug("exception : {}", e); - resultDto.setStatus("500"); - resultDto.setMsg("문제 업데이트 도중 에러가 발생하였습니다."); - }finally { - return resultDto; - } - } - - @Override - public ResultDto updateProblemStatus(String problemId, HashMap params, HttpServletRequest request) { - ResultDto resultDto = new ResultDto(); - resultDto.setMsg("업데이트에 성공했습니다."); - resultDto.setStatus("200"); - try{ - if(problemId == null || "".equals(problemId)) throw new DataIntegrityViolationException("request problemId not found"); - params.put("problemId", problemId); - String token = request.getHeader("Authorization"); - if("".equals(token) || token == null || !jwtUtil.isAdmin(token)) throw new AuthenticationFailedException("권한이 없습니다."); - int update = mapper.updateProblemStatusByProblemId(params); - if(update != 1) throw new DataIntegrityViolationException("problem Not Found Exception"); - } catch(DataIntegrityViolationException e){ - log.debug("exception : {}", e); - resultDto.setStatus("404"); - resultDto.setMsg("problemId "+e.getMessage()); - }catch(AuthenticationFailedException e){ - log.debug("exception : {}", e); - resultDto.setStatus("403"); - resultDto.setMsg(e.getMessage()); - } catch(Exception e){ - log.debug("exception : {},", e); - resultDto.setStatus("500"); - resultDto.setMsg("문제 수정 도중 문제가 발생하였습니다."); - } finally{ - return resultDto; - } - - } - - @Override - public SolveAndUnsolveDto getSolveAndUnsolveList(String nickName) throws Exception{ - SolveAndUnsolveDto list = new SolveAndUnsolveDto(); - List solveList = null; - List unSolveList = null; - solveList = mapper.getSolveListByUserNickname(nickName); - unSolveList = mapper.getUnsolveListByUserNickname(nickName); - if(solveList == null) solveList = Collections.EMPTY_LIST; - if(unSolveList == null) unSolveList = Collections.EMPTY_LIST; - list.setSolveList(solveList); - list.setSolveCount(solveList.size()); - list.setUnSolveList(unSolveList); - list.setUnSolveCount(unSolveList.size()); - return list; - } - - @Override - public List getProblemCateList(String nickName) throws Exception { - List list = null; - list = mapper.getProblemCateByNickname(nickName); - if(list == null) list = Collections.EMPTY_LIST; - return list; - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/controller/ProfileController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/profile/controller/ProfileController.java deleted file mode 100644 index 8ec0b1d5..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/controller/ProfileController.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ssafy.codearena.profile.controller; - -import com.ssafy.codearena.profile.dto.S3ResultDto; -import com.ssafy.codearena.profile.service.S3FileUploadServiceImpl; -import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -@Slf4j -@RestController -@RequestMapping("/profile") -@RequiredArgsConstructor -public class ProfileController { - - private final S3FileUploadServiceImpl s3Servie; - - @GetMapping("/{userId}") - public ResponseEntity getProfile(@PathVariable String userId) { - return new ResponseEntity(s3Servie.getProfile(userId), HttpStatus.OK); - } - - @PutMapping("/upload/{userId}") - public ResponseEntity upload(HttpServletRequest request, @PathVariable String userId, @RequestBody MultipartFile file) { - return new ResponseEntity(s3Servie.upload(file, userId), HttpStatus.OK); - } - - @PutMapping("/upload/{userId}/default") - public ResponseEntity defaultImg(@PathVariable String userId) { - return new ResponseEntity(s3Servie.defaultImg(userId), HttpStatus.OK); - } -} \ No newline at end of file diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/dto/ProfileDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/profile/dto/ProfileDto.java deleted file mode 100644 index b319e4e8..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/dto/ProfileDto.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ssafy.codearena.profile.dto; - -import lombok.Data; - -@Data -public class ProfileDto { - private String profileUrl; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/dto/S3ResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/profile/dto/S3ResultDto.java deleted file mode 100644 index 98731857..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/dto/S3ResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.profile.dto; - -import lombok.Data; - -@Data -public class S3ResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/mapper/ProfileMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/profile/mapper/ProfileMapper.java deleted file mode 100644 index 15655b49..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/mapper/ProfileMapper.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.profile.mapper; - -import com.ssafy.codearena.profile.dto.ProfileDto; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; - -@Mapper -public interface ProfileMapper { - int putProfile(String url, String userId) throws SQLException; - ProfileDto getProfile(String userId) throws SQLException; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/service/S3FileUploadService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/profile/service/S3FileUploadService.java deleted file mode 100644 index d7de1b64..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/service/S3FileUploadService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.profile.service; - -import com.ssafy.codearena.profile.dto.S3ResultDto; -import org.springframework.web.multipart.MultipartFile; - -public interface S3FileUploadService { - S3ResultDto upload(MultipartFile file, String userId); - S3ResultDto defaultImg(String userId); - S3ResultDto getProfile(String userId); -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/service/S3FileUploadServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/profile/service/S3FileUploadServiceImpl.java deleted file mode 100644 index 4469674f..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/profile/service/S3FileUploadServiceImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.ssafy.codearena.profile.service; - - -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.model.ObjectMetadata; -import com.ssafy.codearena.profile.dto.ProfileDto; -import com.ssafy.codearena.profile.dto.S3ResultDto; -import com.ssafy.codearena.profile.mapper.ProfileMapper; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import java.util.*; - - -@Slf4j -@Service -@RequiredArgsConstructor -public class S3FileUploadServiceImpl implements S3FileUploadService { - - // 버킷 이름 동적 할당 - @Value("${cloud.aws.s3.bucket}") - private String bucket; - - // 버킷 주소 동적 할당 - @Value("${cloud.aws.s3.bucket.url}") - private String defaultUrl; - - @Value("${defaultImg}") - private String defaultImg; - - private final AmazonS3 amazonS3Client; - private final ProfileMapper mapper; - - public S3ResultDto upload(MultipartFile file, String userId){ - - S3ResultDto resultDto = new S3ResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("프로필 사진 저장 완료"); - resultDto.setData(null); - - try { - - ObjectMetadata metadata = new ObjectMetadata(); - metadata.setContentType(file.getContentType()); - metadata.setContentLength(file.getSize()); - - UUID uuid = UUID.randomUUID(); - - // 받은 uuid를 넣어준다. - amazonS3Client.putObject("codearena-bucket", uuid.toString(), file.getInputStream(), metadata); - - String profileUrl = "https://codearena-bucket.s3.ap-northeast-2.amazonaws.com/" + uuid.toString(); - - int result = mapper.putProfile(profileUrl, userId); - - if (result != 1) { - log.debug("[profile-upload] : {} , {}", profileUrl, userId); - resultDto.setStatus("404"); - resultDto.setMsg("해당 사람 없음"); - } - - } catch (Exception e) { - log.debug("[profile-upload] : ", e); - resultDto.setStatus("500"); - resultDto.setMsg("서버 에러 발생"); - } - - return resultDto; - } - - @Override - public S3ResultDto defaultImg(String userId) { - S3ResultDto resultDto = new S3ResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("기본 이미지로 변경하는데 성공했습니다."); - - try { - mapper.putProfile(defaultImg, userId); - } catch (Exception e ) { - resultDto.setStatus("404"); - resultDto.setMsg("해당 사용자가 없습니다."); - } - - return resultDto; - } - - @Override - public S3ResultDto getProfile(String userId) { - S3ResultDto resultDto = new S3ResultDto(); - resultDto.setStatus("200"); - resultDto.setMsg("사용자 이미지 리턴 성공"); - - try { - ProfileDto profileDto = mapper.getProfile(userId); - resultDto.setData(profileDto); - } catch (Exception e) { - resultDto.setStatus("404"); - resultDto.setMsg("해당 사용자가 없습니다."); - } - - return resultDto; - } -} \ No newline at end of file diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/controller/UserController.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/controller/UserController.java deleted file mode 100644 index 061c225c..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/controller/UserController.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.ssafy.codearena.user.controller; - -import com.ssafy.codearena.user.dto.*; -import com.ssafy.codearena.user.service.UserService; -import com.ssafy.codearena.util.JwtUtil; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.coyote.Response; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@RequiredArgsConstructor -@RequestMapping("/user") -@Slf4j -public class UserController { - - private final UserService userService; - - @PostMapping("/join") - public ResponseEntity join(@RequestBody UserJoinDto userJoinDto) { - return new ResponseEntity(userService.join(userJoinDto), HttpStatus.OK); - } - @GetMapping("/nick/duplicate") - public ResponseEntity checkDuplicatedNickname(@RequestParam String userNickname) { - return new ResponseEntity(userService.checkDuplicatedNickname(userNickname), HttpStatus.OK); - } - @GetMapping("/email/duplicate") - public ResponseEntity checkDuplicatedEmail(@RequestParam String userEmail) { - return new ResponseEntity(userService.checkDuplicatedEmail(userEmail), HttpStatus.OK); - } - @PostMapping("/login") - public ResponseEntity login(HttpServletResponse response, @RequestBody UserLoginDto userLoginDto) { - return new ResponseEntity(userService.login(response, userLoginDto), HttpStatus.OK); - } - @PostMapping("/logout") - public ResponseEntity logout(@RequestBody String userEmail) { - return new ResponseEntity(userService.logout(userEmail), HttpStatus.OK); - } - @PostMapping("/password/reissue") - public ResponseEntity issueVerificationCode(@RequestBody UserReissueDto userReissueDto) { - return new ResponseEntity(userService.issueVerificationCode(userReissueDto), HttpStatus.OK); - } - @PostMapping("/password/verification") - public ResponseEntity verifyCode(@RequestBody UserReissueDto userReissueDto) { - return new ResponseEntity(userService.checkVerificationCode(userReissueDto), HttpStatus.OK); - } - @GetMapping - public ResponseEntity searchUser(@RequestParam(value="from") String fromUserNickname, @RequestParam(value="to") String toUserNickname) { - UserSearchDto userSearchDto = new UserSearchDto(fromUserNickname, toUserNickname); - log.debug("{}", userSearchDto); - return new ResponseEntity(userService.searchUser(userSearchDto) ,HttpStatus.OK); - } - @GetMapping("/list") - public ResponseEntity searchUserList(@RequestParam String fromId, @RequestParam String toNickname) { - UserSearchListDto userSearchListDto = new UserSearchListDto(); - userSearchListDto.setFromId(fromId); - userSearchListDto.setToNickname(toNickname); - return new ResponseEntity(userService.searchUserList(userSearchListDto), HttpStatus.OK); - } - @PutMapping("/password") - public ResponseEntity changePassword(@RequestBody UserChangePasswordDto userChangePasswordDto) { - return new ResponseEntity(userService.changePassword(userChangePasswordDto), HttpStatus.OK); - } - @PutMapping - public ResponseEntity changeUserInfo(@RequestBody UserChangeInfoDto userChangeInfoDto) { - return new ResponseEntity(userService.changeUserInfo(userChangeInfoDto), HttpStatus.OK); - } - @PostMapping("/follow") - public ResponseEntity follow(@RequestBody UserFollowDto userFollowDto) { - return new ResponseEntity(userService.follow(userFollowDto), HttpStatus.OK); - } - @DeleteMapping("/follow") - public ResponseEntity unfollow(@RequestBody UserFollowDto userFollowDto) { - return new ResponseEntity(userService.unfollow(userFollowDto), HttpStatus.OK); - } - @GetMapping("/follow/{userId}") - public ResponseEntity getFollowList(@PathVariable String userId) { - return new ResponseEntity(userService.getFollowList(userId), HttpStatus.OK); - } - @GetMapping("/following/{userId}") - public ResponseEntity getFollowingList(@PathVariable String userId) { - return new ResponseEntity(userService.getFollowingList(userId), HttpStatus.OK); - } -// @GetMapping("/rating/{userNickname}") -// public ResponseEntity getUserRatingByNickname(@PathVariable String userNickname) -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/CntOfCate.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/CntOfCate.java deleted file mode 100644 index 608f6793..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/CntOfCate.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class CntOfCate { - private int bruteForce; - private int DP; - private int greedy; - private int impl; - private int string; - private int dataStructure; -} \ No newline at end of file diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/MailDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/MailDto.java deleted file mode 100644 index a7305ab8..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/MailDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class MailDto { - private String address; - private String title; - private String message; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/TokenDataDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/TokenDataDto.java deleted file mode 100644 index e3f8df4f..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/TokenDataDto.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -public class TokenDataDto { - private String userId; - private String userEmail; - private String userNickname; - private String speedRating; - private String effiRating; - private String userPassword; - private String userThumbnail; - private String userCoin; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserChangeInfoDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserChangeInfoDto.java deleted file mode 100644 index 5c4fec65..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserChangeInfoDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserChangeInfoDto { - private String userId; - private String userNickname; - private String userIntro; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserChangePasswordDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserChangePasswordDto.java deleted file mode 100644 index 9b7d2f83..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserChangePasswordDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserChangePasswordDto { - private String userEmail; - private String userPassword; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserDuplicatedDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserDuplicatedDto.java deleted file mode 100644 index 9e33cc41..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserDuplicatedDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserDuplicatedDto { - // true : 사용 가능, false : 사용 불가 - private boolean result; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowDto.java deleted file mode 100644 index 9608dd51..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserFollowDto { - private String fromId; - private String toId; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowInfoDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowInfoDto.java deleted file mode 100644 index 20b35e27..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowInfoDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserFollowInfoDto { - private String userId; - private String userNickname; - private String userEmail; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowNicknameDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowNicknameDto.java deleted file mode 100644 index b5567b48..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowNicknameDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserFollowNicknameDto { - private String fromNickname; - private String toNickname; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowingInfoDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowingInfoDto.java deleted file mode 100644 index 2516a048..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserFollowingInfoDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserFollowingInfoDto { - private String userId; - private String userNickname; - private String userEmail; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserInfoDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserInfoDto.java deleted file mode 100644 index 05f39c68..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserInfoDto.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserInfoDto { - private String userId; - private String userEmail; - private String userNickname; - private String userIntro; - private String speedRating; - private String effiRating; - private String userThumbnail; - private String userCoin; - private int isFollow; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserIsFollowDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserIsFollowDto.java deleted file mode 100644 index 7c6f3f3b..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserIsFollowDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserIsFollowDto { - private String fromId; - private String toId; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserJoinDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserJoinDto.java deleted file mode 100644 index fcb15ea6..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserJoinDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserJoinDto { - private String userEmail; - private String userPassword; - private String userNickname; - private String userIntro; - private String userThumbnail; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserLoginDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserLoginDto.java deleted file mode 100644 index 484560c4..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserLoginDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserLoginDto { - private String userEmail; - private String userPassword; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserProblemCateDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserProblemCateDto.java deleted file mode 100644 index b00b91a8..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserProblemCateDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserProblemCateDto { - private String problemCate; - private int problemCateCnt; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserProblemDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserProblemDto.java deleted file mode 100644 index e53f8b79..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserProblemDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserProblemDto { - private int problemId; - private String problemTitle; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserReissueDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserReissueDto.java deleted file mode 100644 index 990f0bf5..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserReissueDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserReissueDto { - private String userEmail; - private String tempCode; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserResultDto.java deleted file mode 100644 index 276baec5..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchDto.java deleted file mode 100644 index bd67a221..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class UserSearchDto { - private String fromUserNickname; - private String toUserNickname; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchListDto.java deleted file mode 100644 index 60a7db99..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchListDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserSearchListDto { - private String fromId; - private String toNickname; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchResultDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchResultDto.java deleted file mode 100644 index 657af37f..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchResultDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import com.ssafy.codearena.problem.dto.ProblemForInsertDto; -import lombok.Data; - -import java.util.List; - -@Data -public class UserSearchResultDto { - private UserInfoDto userInfoDto; - private List solvedProblem; - private List unsolvedProblem; - private List problemCateList; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchResultListDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchResultListDto.java deleted file mode 100644 index 30a54893..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserSearchResultListDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.Data; - -@Data -public class UserSearchResultListDto { - private String isFollow; - private String userNickname; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserTokenDto.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserTokenDto.java deleted file mode 100644 index a62a9757..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/dto/UserTokenDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.ssafy.codearena.user.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class UserTokenDto { - private String refreshToken; -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/mapper/UserMapper.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/mapper/UserMapper.java deleted file mode 100644 index d37337b3..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/mapper/UserMapper.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ssafy.codearena.user.mapper; - -import com.ssafy.codearena.user.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Map; - -@Mapper -public interface UserMapper { - void join(UserJoinDto userJoinDto) throws SQLException; - int checkNickname(String nickname) throws SQLException; - int checkEmail(String email) throws SQLException; - TokenDataDto login(UserLoginDto userLoginDto) throws SQLException; - int logout(String userEmail) throws SQLException; - int issueVerificationCode(UserReissueDto userReissueDto) throws SQLException; - int checkVerificationCode(UserReissueDto userReissueDto) throws SQLException; - UserInfoDto searchUser(String userNickname) throws SQLException; - ArrayList searchUserList(UserSearchListDto userSearchListDto) throws SQLException; - void saveRefreshToken(Map map) throws SQLException; - int changePassword(UserChangePasswordDto userChangePasswordDto) throws SQLException; - int changeUserInfo(UserChangeInfoDto userChangeInfoDto) throws SQLException; - void follow(UserFollowDto userFollowDto) throws SQLException; - void unfollow(UserFollowDto userFollowDto) throws SQLException; - ArrayList getFollowList(String userId) throws SQLException; - ArrayList getFollowingList(String userId) throws SQLException; - int isFollow(UserIsFollowDto userIsFollowDto) throws SQLException; - -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/service/UserService.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/service/UserService.java deleted file mode 100644 index 1f526a36..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/service/UserService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.codearena.user.service; - -import com.ssafy.codearena.user.dto.*; -import jakarta.servlet.http.HttpServletResponse; - -import java.net.http.HttpResponse; - -public interface UserService { - - UserResultDto join(UserJoinDto userJoinDto); - UserResultDto login(HttpServletResponse response, UserLoginDto userLoginDto); - UserResultDto logout(String userEmail); - UserResultDto checkDuplicatedNickname(String nickname); - UserResultDto checkDuplicatedEmail(String email); - UserResultDto issueVerificationCode(UserReissueDto userReissueDto); - UserResultDto checkVerificationCode(UserReissueDto userReissueDto); - UserResultDto searchUser(UserSearchDto userSearchDto); - UserResultDto searchUserList(UserSearchListDto userSearchListDto); - UserResultDto changePassword(UserChangePasswordDto userChangePasswordDto); - UserResultDto changeUserInfo(UserChangeInfoDto userChangeInfoDto); - UserResultDto follow(UserFollowDto userFollowDto); - UserResultDto unfollow(UserFollowDto userFollowDto); - UserResultDto getFollowList(String userNickname); - UserResultDto getFollowingList(String userNickname); -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/user/service/UserServiceImpl.java b/back-end/codearena/src/main/java/com/ssafy/codearena/user/service/UserServiceImpl.java deleted file mode 100644 index 967fd557..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/user/service/UserServiceImpl.java +++ /dev/null @@ -1,524 +0,0 @@ -package com.ssafy.codearena.user.service; - -import com.ssafy.codearena.problem.dto.ProblemForInsertDto; -import com.ssafy.codearena.problem.dto.SolveAndUnsolveDto; -import com.ssafy.codearena.problem.service.ProblemService; -import com.ssafy.codearena.user.dto.*; -import com.ssafy.codearena.user.mapper.UserMapper; -import com.ssafy.codearena.util.EncryptUtil; -import com.ssafy.codearena.util.JwtUtil; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.stereotype.Service; - -import java.net.http.HttpResponse; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Service -@RequiredArgsConstructor -@Slf4j -public class UserServiceImpl implements UserService{ - - private final ProblemService problemService; - private final UserMapper mapper; - private final JavaMailSender javaMailSender; - private final JwtUtil jwtUtil; - private final EncryptUtil encryptUtil; - private final String HEADER_AUTH = "Authorization"; - - @Value("${defaultImg}") - private String defaultImg; - - public void saveRefreshToken(String userEmail, String refreshToken) { - - Map map = new HashMap(); - - map.put("userEmail", userEmail); - map.put("refreshToken", refreshToken); - try { - mapper.saveRefreshToken(map); - } catch (Exception e) { - log.error("[UserServiceImpl] saveRefreshToken 저장 에러 : {}" , e.getMessage()); - } - } - - @Override - public UserResultDto join(UserJoinDto userJoinDto) { - - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("201"); - userResultDto.setMsg("회원가입 성공"); - userResultDto.setData(null); - - try { - String lowerEmail = userJoinDto.getUserEmail().toLowerCase(); - userJoinDto.setUserEmail(lowerEmail); - userJoinDto.setUserThumbnail(defaultImg); - - // 비밀번호 암호화 - String encryptedPassword = encryptUtil.Encrypt(userJoinDto.getUserPassword()); - - userJoinDto.setUserPassword(encryptedPassword); - - log.info("[encrypt] : {}", encryptedPassword); - - mapper.join(userJoinDto); - - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("회원가입 실패"); - userResultDto.setData(null); - } - - return userResultDto; - } - @Override - public UserResultDto login(HttpServletResponse response, UserLoginDto userLoginDto) { - - log.debug("login userEmail : {}", userLoginDto.getUserEmail()); - - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("200"); - userResultDto.setMsg("로그인 성공"); - userResultDto.setData(null); - - try { - String lowerEmail = userLoginDto.getUserEmail().toLowerCase(); - userLoginDto.setUserEmail(lowerEmail); - TokenDataDto tokenDataDto = mapper.login(userLoginDto); - - log.info("[UserLogin] : {}" , tokenDataDto); - - // 로그인 성공 시 - // encrypt 에서 비밀번호 맞춰보고 성공시 - if (encryptUtil.isMatch(userLoginDto.getUserPassword(), tokenDataDto.getUserPassword())) { - - String accessToken = jwtUtil.createAccessToken(tokenDataDto); - String refreshToken = jwtUtil.createRefreshToken(tokenDataDto); - - log.debug("access token : {}", accessToken); - log.debug("refresh token : {}", refreshToken); - - saveRefreshToken(userLoginDto.getUserEmail(), refreshToken); - - UserTokenDto userTokenDto = new UserTokenDto(refreshToken); - - response.setHeader(HEADER_AUTH, accessToken); - - userResultDto.setData(userTokenDto); - - } else { - userResultDto.setStatus("404"); - userResultDto.setMsg("ID, PW 미일치"); - userResultDto.setData(null); - } - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("로그인 실패"); - userResultDto.setData(null); - } - - return userResultDto; - } - - @Override - public UserResultDto logout(String userEmail) { - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setMsg("200"); - userResultDto.setMsg("로그아웃 성공"); - userResultDto.setData(null); - - try { - int result = mapper.logout(userEmail); - - if (result != 1) { - userResultDto.setStatus("404"); - userResultDto.setMsg("해당 유저 없음"); - } - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 에러 발생"); - } - - return userResultDto; - } - - - @Override - public UserResultDto checkDuplicatedNickname(String nickname) { - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("200"); - userResultDto.setMsg("닉네임 사용 가능"); - - UserDuplicatedDto userDuplicatedDto = new UserDuplicatedDto(); - userDuplicatedDto.setResult(true); - - try { - int result = mapper.checkNickname(nickname); - - if (result >= 1) { - userResultDto.setStatus("200"); - userResultDto.setMsg("이미 사용 중"); - userDuplicatedDto.setResult(false); - } - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러 발생"); - userDuplicatedDto.setResult(false); - } finally { - userResultDto.setData(userDuplicatedDto); - } - return userResultDto; - } - - public UserResultDto checkDuplicatedEmail(String email) { - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("200"); - userResultDto.setMsg("이메일 사용 가능"); - - UserDuplicatedDto userDuplicatedDto = new UserDuplicatedDto(); - userDuplicatedDto.setResult(true); - - try { - String lowerEmail = email.toLowerCase(); - int result = mapper.checkEmail(lowerEmail); - - if (result >= 1) { - userResultDto.setMsg("이미 사용 중"); - userDuplicatedDto.setResult(false); - } - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러 발생"); - userDuplicatedDto.setResult(false); - } finally { - userResultDto.setData(userDuplicatedDto); - } - return userResultDto; - } - - @Override - public UserResultDto issueVerificationCode(UserReissueDto userReissueDto) { - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("200"); - userResultDto.setMsg("인증코드 이메일 전송 완료"); - userResultDto.setData(null); - - try { - String tempCode = getTempCode(); - userReissueDto.setTempCode(tempCode); - - int result = mapper.issueVerificationCode(userReissueDto); - - if (result == 1) { - // 인증 코드를 DB에 넣었으면 임시 코드 이메일 전송 - MailDto mailDto = new MailDto(); - mailDto.setAddress(userReissueDto.getUserEmail()); - mailDto.setTitle("[Code Arena] 비밀번호 변경 인증"); - mailDto.setMessage("Code Arena 비밀번호 변경 인증 코드 발급 안내 이메일입니다. \n" + "인증 코드 [ " + tempCode + " ] 를 입력해주세요."); - - mailSend(mailDto); - - } else { - userResultDto.setStatus("404"); - userResultDto.setMsg("해당 유저 없음"); - } - - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("이메일 전송 실패"); - } - - return userResultDto; - } - - @Override - public UserResultDto checkVerificationCode(UserReissueDto userReissueDto) { - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("200"); - userResultDto.setMsg("인증 성공"); - userResultDto.setData(null); - - try { - int result = mapper.checkVerificationCode(userReissueDto); - - if (result == 1) { - userReissueDto.setTempCode(null); - mapper.issueVerificationCode(userReissueDto); - } else { - log.info("[checkVerificationCode] userReissueDto : {}", userReissueDto); - userResultDto.setStatus("404"); - userResultDto.setMsg("인증 코드 미일치"); - } - - - } catch (Exception e) { - log.debug("[checkVerificationCode] : ", e); - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러"); - } - - return userResultDto; - } - - // 비밀번호 랜덤 생성 로직 - public static String getTempCode(){ - char[] charSet = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', - 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; - - String str = ""; - - // 문자 배열 길이의 값을 랜덤으로 10개를 뽑아 구문을 작성함 - int idx = 0; - for (int i = 0; i < 10; i++) { - idx = (int) (charSet.length * Math.random()); - str += charSet[idx]; - } - return str; - } - - public void mailSend(MailDto mailDto) { - SimpleMailMessage message = new SimpleMailMessage(); - message.setTo(mailDto.getAddress()); - message.setSubject(mailDto.getTitle()); - message.setText(mailDto.getMessage()); - message.setFrom("timber3597@naver.com"); - message.setReplyTo("timber3597@naver.com"); - System.out.println("message"+message); - javaMailSender.send(message); - } - - @Override - public UserResultDto searchUser(UserSearchDto userSearchDto) { - - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("회원 정보 조회 성공"); - - try { - String userNickname = userSearchDto.getFromUserNickname(); - UserInfoDto fromUser = mapper.searchUser(userNickname); - userNickname = userSearchDto.getToUserNickname(); - UserInfoDto toUser = mapper.searchUser(userNickname); - - // 검색된 회원이 없을 시 - if ("".equals(fromUser.getUserId()) || fromUser.getUserId() == null || "".equals(toUser.getUserId()) || toUser.getUserId() == null) { - userResultDto.setStatus("404"); - userResultDto.setMsg("해당 이름의 회원 없음"); - userResultDto.setData(null); - } else { - // 푼 문제 가져오기 - // 못 푼 문제 가져오기 - UserSearchResultDto userSearchResultDto = new UserSearchResultDto(); - - SolveAndUnsolveDto solveAndUnsolveDto = problemService.getSolveAndUnsolveList(toUser.getUserNickname()); - List problemCateList = problemService.getProblemCateList(toUser.getUserNickname()); - - List solveListP = solveAndUnsolveDto.getSolveList(); - List unsolveListP = solveAndUnsolveDto.getUnSolveList(); - - List solveListU = new ArrayList<>(); - List unsolveListU = new ArrayList<>(); - - - for(ProblemForInsertDto p : solveListP) { - UserProblemDto dto = new UserProblemDto(); - dto.setProblemId(p.getProblemId()); - dto.setProblemTitle(p.getProblemTitle()); - solveListU.add(dto); - } - - for(ProblemForInsertDto p : unsolveListP) { - UserProblemDto dto = new UserProblemDto(); - dto.setProblemId(p.getProblemId()); - dto.setProblemTitle(p.getProblemTitle()); - unsolveListU.add(dto); - } - - UserIsFollowDto userIsFollowDto = new UserIsFollowDto(); - - userIsFollowDto.setFromId(fromUser.getUserId()); - userIsFollowDto.setToId(toUser.getUserId()); - - int isFollow = mapper.isFollow(userIsFollowDto); - toUser.setIsFollow(isFollow); - - log.debug("isFollow : {}", isFollow); - log.debug("toUser : {}", toUser); - - // 1. 검색 대상 기본 정보 넣기 - userSearchResultDto.setUserInfoDto(toUser); - // 2. 검색 대상이 푼 문제 리스트 넣기 - userSearchResultDto.setSolvedProblem(solveListU); - // 3. 검색 대상이 못 푼 문제 리스트 넣기 - userSearchResultDto.setUnsolvedProblem(unsolveListU); - // 4. 푼 문제들의 카테고리별 개수를 넣어 주기 - userSearchResultDto.setProblemCateList(problemCateList); - - userResultDto.setData(userSearchResultDto); - } - } catch (Exception e) { - log.debug("Error occured : {} ", e); - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러"); - userResultDto.setData(null); - } - return userResultDto; - } - - @Override - public UserResultDto searchUserList(UserSearchListDto userSearchListDto) { - ArrayList userSearchList = new ArrayList<>(); - - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("유저 리스트 검색 완료"); - - try { - userSearchList = mapper.searchUserList(userSearchListDto); - userResultDto.setData(userSearchList); - } catch (Exception e) { - log.debug("Exception : {}" , e); - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러"); - } - - userResultDto.setData(userSearchList); - return userResultDto; - } - - @Override - public UserResultDto changePassword(UserChangePasswordDto userChangePasswordDto) { - UserResultDto userResultDto = new UserResultDto(); - - userResultDto.setStatus("200"); - userResultDto.setMsg("비밀번호 변경 완료"); - userResultDto.setData(null); - - try { - String lowerEmail = userChangePasswordDto.getUserEmail().toLowerCase(); - userChangePasswordDto.setUserEmail(lowerEmail); - - // 비밀번호 암호화 해서 넣기 - String encryptedPassword = encryptUtil.Encrypt(userChangePasswordDto.getUserPassword()); - userChangePasswordDto.setUserPassword(encryptedPassword); - - int result = mapper.changePassword(userChangePasswordDto); - - if (result != 1) { - userResultDto.setStatus("404"); - userResultDto.setMsg("해당 사용자 없음!"); - } - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러 발생"); - } - return userResultDto; - } - - @Override - public UserResultDto changeUserInfo(UserChangeInfoDto userChangeInfoDto) { - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("변경사항 저장 완료"); - userResultDto.setData(null); - - try { - int result = mapper.changeUserInfo(userChangeInfoDto); - - if(result != 1) { - userResultDto.setStatus("404"); - userResultDto.setMsg("해당 ID의 유저 없음"); - } - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 에러 발생"); - } - - return userResultDto; - } - - @Override - public UserResultDto follow(UserFollowDto userFollowDto) { - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("회원 팔로우 성공"); - userResultDto.setData(null); - - try { - mapper.follow(userFollowDto); - } catch (Exception e) { - log.debug("Exception : {}", e); - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러"); - } - - return userResultDto; - } - - @Override - public UserResultDto unfollow(UserFollowDto userFollowDto) { - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("팔로우 취소 성공"); - userResultDto.setData(null); - - try { - mapper.unfollow(userFollowDto); - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 내부 에러"); - } - return userResultDto; - } - - @Override - public UserResultDto getFollowList(String userId) { - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("팔로우 목록 조회 성공"); - userResultDto.setData(null); - - try { - ArrayList result = mapper.getFollowList(userId); - - userResultDto.setData(result); - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("팔로우 목록 조회 실패"); - } - return userResultDto; - } - - @Override - public UserResultDto getFollowingList(String userId) { - UserResultDto userResultDto = new UserResultDto(); - userResultDto.setStatus("200"); - userResultDto.setMsg("팔로잉 목록 조회 성공"); - userResultDto.setData(null); - - try { - ArrayList result = mapper.getFollowingList(userId); - userResultDto.setData(result); - - } catch (Exception e) { - userResultDto.setStatus("500"); - userResultDto.setMsg("서버 에러 발생"); - } - - return userResultDto; - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/util/EncryptUtil.java b/back-end/codearena/src/main/java/com/ssafy/codearena/util/EncryptUtil.java deleted file mode 100644 index 1d102faf..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/util/EncryptUtil.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ssafy.codearena.util; - -import org.mindrot.jbcrypt.BCrypt; -import org.springframework.stereotype.Component; - -@Component -public class EncryptUtil { - public String Encrypt(String password) { - return BCrypt.hashpw(password, BCrypt.gensalt()); - } - - public boolean isMatch(String password, String hashed) { - return BCrypt.checkpw(password, hashed); - } -} diff --git a/back-end/codearena/src/main/java/com/ssafy/codearena/util/JwtUtil.java b/back-end/codearena/src/main/java/com/ssafy/codearena/util/JwtUtil.java deleted file mode 100644 index 8d2cc021..00000000 --- a/back-end/codearena/src/main/java/com/ssafy/codearena/util/JwtUtil.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.ssafy.codearena.util; - -import com.ssafy.codearena.user.dto.TokenDataDto; -import io.jsonwebtoken.*; -import jakarta.servlet.http.HttpServletRequest; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; - -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.Map; - - - -@Component -@Slf4j -public class JwtUtil { - - @Value("${jwt.salt}") - private String salt; - - @Value("${jwt.access-token.expiretime}") - private long accessTokenExpireTime; - - @Value("${jwt.refresh-token.expiretime}") - private long refreshTokenExpireTime; - - public String createAccessToken(TokenDataDto tokenDataDto) { - return create(tokenDataDto, "access-token", accessTokenExpireTime); - } - - // AccessToken에 비해 유효기간을 길게 설정. - public String createRefreshToken(TokenDataDto tokenDataDto) { - return create(tokenDataDto, "refresh-token", refreshTokenExpireTime); - } - - // Token 발급 -// key : Claim에 셋팅될 key 값 -// value : Claim에 셋팅 될 data 값 -// subject : payload에 sub의 value로 들어갈 subject값 -// expire : 토큰 유효기간 설정을 위한 값 -// jwt 토큰의 구성 : header + payload + signature - private String create(TokenDataDto tokenDataDto, String subject, long expireTime) { -// Payload 설정 : 생성일 (IssuedAt), 유효기간 (Expiration), -// 토큰 제목 (Subject), 데이터 (Claim) 등 정보 세팅. - Claims claims = Jwts.claims() - .setSubject(subject) // 토큰 제목 설정 ex) access-token, refresh-token - .setIssuedAt(new Date()) // 생성일 설정 - .setExpiration(new Date(System.currentTimeMillis() + expireTime)); // 만료일 설정 (유효기간) - -// 저장할 data의 key, value - claims.put("userEmail", tokenDataDto.getUserEmail()); - claims.put("userId" , tokenDataDto.getUserId()); - claims.put("userNickname", tokenDataDto.getUserNickname()); - claims.put("speed", tokenDataDto.getSpeedRating()); - claims.put("eff", tokenDataDto.getEffiRating()); - claims.put("userThumbnail", tokenDataDto.getUserThumbnail()); - claims.put("userCoin" , tokenDataDto.getUserCoin()); - - - String jwt = Jwts.builder() - .setHeaderParam("typ", "JWT").setClaims(claims) // Header 설정 : 토큰의 타입, 해쉬 알고리즘 정보 세팅. - .signWith(SignatureAlgorithm.HS256, this.generateKey()) // Signature 설정 : secret key를 활용한 암호화. - .compact(); // 직렬화 처리. - - return jwt; - } - - // Signature 설정에 들어갈 key 생성. - private byte[] generateKey() { - byte[] key = null; - try { -// charset 설정 안하면 사용자 플랫폼의 기본 인코딩 설정으로 인코딩 됨. - key = salt.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - if (log.isInfoEnabled()) { - e.printStackTrace(); - } else { - log.error("Making JWT Key Error ::: {}", e.getMessage()); - } - } - return key; - } - - // 토큰 검증 로직 : parseClaimsJws -> 문제없으면 return true 에러 발생 시 return false - public boolean checkToken(String token) { - try { -// Json Web Signature? 서버에서 인증을 근거로 인증정보를 서버의 private key로 서명 한것을 토큰화 한것 -// setSigningKey : JWS 서명 검증을 위한 secret key 세팅 -// parseClaimsJws : 파싱하여 원본 jws 만들기 - - Jws claims = Jwts.parser().setSigningKey(this.generateKey()).parseClaimsJws(token); -// Claims 는 Map의 구현체 형태 - log.debug("토큰 확인 성공 claims: {}", claims); - return true; - } catch(SecurityException | MalformedJwtException | SignatureException e) { - log.error("유효하지 않는 JWT signature 입니다."); - } catch (ExpiredJwtException e) { - log.error("만료된 JWT 토큰입니다."); - } catch (UnsupportedJwtException e) { - log.error("지원되지 않는 JWT 토큰입니다."); - } catch (IllegalArgumentException e) { - log.error("잘못된 JWT 토큰입니다."); - } - return false; - } - - public String getUserEmail(String authorization) { - Jws claims = null; - try { - claims = Jwts.parser().setSigningKey(this.generateKey()).parseClaimsJws(authorization); - } catch (Exception e) { - log.error(e.getMessage()); - } - Map value = claims.getBody(); - log.info("value : {}", value); - return (String) value.get("userEmail"); - } - - public boolean isAdmin(String token) throws JwtException{ - try { - // 토큰 유효성 검사 - Jws claims = Jwts.parser().setSigningKey(this.generateKey()).parseClaimsJws(token); - - String userId = (String) claims.getBody().get("userId"); - - if (!"1".equals(userId)) throw new Exception("토큰 에러 발생"); - - } catch (Exception e) { - log.debug("exception : {} ", e); - return false; - } - - return true; - } - - private Claims decodeToken(String token){ - Claims claims = null; - try{ - claims = Jwts.parser().setSigningKey(salt.getBytes()) - .parseClaimsJws(token) - .getBody(); - - }catch(SecurityException | MalformedJwtException | SignatureException e) { - claims = null; - log.error("유효하지 않는 JWT signature 입니다."); - } catch (ExpiredJwtException e) { - claims = null; - log.error("만료된 JWT 토큰입니다."); - } catch (UnsupportedJwtException e) { - claims = null; - log.error("지원되지 않는 JWT 토큰입니다."); - } catch (IllegalArgumentException e) { - claims = null; - log.error("잘못된 JWT 토큰입니다."); - } - return claims; - } - - public String getUserId(String token){ - Claims claims = decodeToken(token); - return (String) claims.get("userId"); - } -} diff --git a/back-end/codearena/src/main/resources/application.properties b/back-end/codearena/src/main/resources/application.properties deleted file mode 100644 index 461444d6..00000000 --- a/back-end/codearena/src/main/resources/application.properties +++ /dev/null @@ -1,60 +0,0 @@ -# spring.datasource. ? ?? ?? ????. -server.servlet.context-path=/api -server.port=8080 - -spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver -spring.datasource.hikari.jdbc-url=ENC(lIolm4EodyD8rtrnXtpsnigEiV8GD/2/1I/7ucF+gGEBgbB9r8GcnmzKaN9pdEyb0vwFqtsdp1QbDoPic+vJD8CFOhm9dtkGUH8dcKKtlNlZcg3Mt/cgrTOG5noUarwE76lOHx1GZXh1+tWbyTTEHg==) -spring.datasource.hikari.username=ENC(u2pZ0ldKEDL6po+p2UuafA==) -spring.datasource.hikari.password=ENC(6Tq8k8TDrL6pjWfHHRuFoqne6ntNi1j3) -spring.datasource.hikari.pool-name=Hikari Connection Pool -# hikariCP property setting -spring.datasource.hikari.maximum-pool-size=50 -spring.datasource.hikari.minimum-idle=50 -spring.datasource.hikari.connection-timeout=5000 -spring.datasource.hikari.connection-init-sql=SELECT 1 -spring.datasource.hikari.idle-timeout=600000 -spring.datasource.hikari.max-lifetime=1800000 -spring.datasource.hikari.auto-commit=true - -logging.level.com.ssafy.codearena=debug - - - -#Java Mail Sender (naver) -spring.mail.host=smtp.naver.com -spring.mail.port=465 -spring.mail.username=ENC(6kDCqpm/0XwovZd0Zk00Qp2RuXPw2C1b14m2viEPC1o=) -spring.mail.password=ENC(+/jgbovlaFidUZ5rkgB/wZR3WY3eIUL+) -spring.mail.properties.mail.smtp.auth=true -spring.mail.properties.mail.smtp.ssl.enable=true -spring.mail.properties.mail.smtp.ssl.trust=smtp.naver.com -spring.mail.properties.mail.smtp.starttls.enable=true - -judge.java.url=ENC(pt6D47W0QQJMUObzskxa1RXngqbNIRgvb8dq1oYSenHrYMRTUvG4sw==) -judge.cpp.url=ENC(kjWheQGIHVZh+nW+I/ZNdVjbw8D5H3UchezXEnZJ1ahXDqvbvztaMA==) -judge.python.url=ENC(HwlEw5ZTORhWvpf7SI381o/3ZNhM/5KPU5ynESOVXnhtHULJ4UTo6w==) - -# jwt setting -jwt.salt=ENC(N1Nr7S7EZmI3UL3I/ohGdav3Jfqrm5T4) -# 4 hours -jwt.access-token.expiretime=14400000 -# 10 days -jwt.refresh-token.expiretime=864000000 - -# Swagger -springdoc.swagger-ui.path=/swagger-ui.html - - - -cloud.aws.credentials.accessKey=ENC(ZNts3jpcy/53Ll088tBVAzn7Wt4VZTWl/6OcmC+DMmE=) -cloud.aws.credentials.secretKey=ENC(GGo2DbAO4O6pYI3EltMGH3IbqyT69EOhN7FUXhDpwPZrfAIUCGdKSDtH+kLyh0ikR1Alznnt38E=) -cloud.aws.stack.auto=false - -# AWS S3 Service bucket -cloud.aws.s3.bucket=codearena-bucket -cloud.aws.region.static=ap-northeast-2 - -# AWS S3 Bucket URL -cloud.aws.s3.bucket.url=https://s3.ap-northeast-2.amazonaws.com/codearena-bucket - -defaultImg=ENC(Mz2QUqKgYBcwrzrRtVc36PVHUTZGUavwl6Q1Osze4Bp/Htgzi14yFasTd8YXM6G4ceSo4wIo/KwkqmML265y+5gEqtNWGJ1FEHRVDJkd79Y=) \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/Alarm.xml b/back-end/codearena/src/main/resources/mapper/Alarm.xml deleted file mode 100644 index 8ce6895d..00000000 --- a/back-end/codearena/src/main/resources/mapper/Alarm.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - INSERT INTO alarm(alarm_type, to_id, from_id, alarm_msg, alarm_date, status) VALUES(${alarmType}, ${toId}, ${fromId}, "${alarmMsg}", now(), "${alarmStatus}"); - - - - - - - UPDATE alarm - SET is_read = true - WHERE alarm_id = "${alarmId}"; - - - - UPDATE alarm - SET status = "${alarmStatus}" - WHERE alarm_id = "${alarmId}"; - - - \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/Auth.xml b/back-end/codearena/src/main/resources/mapper/Auth.xml deleted file mode 100644 index 77445bc2..00000000 --- a/back-end/codearena/src/main/resources/mapper/Auth.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/Board.xml b/back-end/codearena/src/main/resources/mapper/Board.xml deleted file mode 100644 index b9eef05b..00000000 --- a/back-end/codearena/src/main/resources/mapper/Board.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - 검색조건에 관한 동적쿼리문 --> - - - - AND board_title LIKE CONCAT('%', '${word}', '%') - - - AND ${key} = ${word} - - - - - - 정렬에 관한 동적쿼리문 --> - - - - ORDER BY article_no DESC - - - ORDER BY board_date DESC - - - ORDER BY board_hit DESC - - - - - - - - AND board_type = ${boardType} - - - - - - AND board_lang = #{langType} - - - - - - - - INSERT INTO board(user_id, problem_id, board_title, board_type, board_lang, board_content, board_code, board_spoiler, board_date) - VALUES(#{userId}, #{problemId}, #{title}, #{type}, #{lang}, #{content}, #{code}, #{spoiler}, now()); - - - - DELETE - FROM board - WHERE article_no = ${boardId}; - - - - UPDATE board - SET problem_id = ${problemId}, board_title = "${title}", board_lang = "${lang}", board_content = "${content}", board_code = "${code}", board_spoiler = ${spoiler} - WHERE article_no = #{articleNo} AND user_id = #{userId}; - - - - - - - - UPDATE board - SET board_hit = board_hit + 1 - WHERE article_no = #{boardId} - - - - \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/Comment.xml b/back-end/codearena/src/main/resources/mapper/Comment.xml deleted file mode 100644 index 36241d15..00000000 --- a/back-end/codearena/src/main/resources/mapper/Comment.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - INSERT INTO comment(article_no, user_id, comment_content, code) - VALUES(#{articleNo}, #{userId}, #{comment}, #{code}); - - - - DELETE - FROM comment - WHERE comment_id = #{commentId}; - - - - UPDATE comment - SET comment_content = #{comment}, code = #{code} - WHERE comment_id = #{commentId}; - - - \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/Problem.xml b/back-end/codearena/src/main/resources/mapper/Problem.xml deleted file mode 100644 index ff360072..00000000 --- a/back-end/codearena/src/main/resources/mapper/Problem.xml +++ /dev/null @@ -1,423 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - select tid, input, output from ps_testcase where tid=${tid} - - - - - - - - - - - - - - - and p.problem_id = ${word} - - - and ${cate} like concat('%','${word}','%') - - - - - - - - - - and tag_name = '${tag}' - - - - - - - - left join ps_problem_tag as t - on p.problem_id = t.problem_id - - - - - - - - - - - - - order by ${orderBy} desc - - - - - - insert into ps_list ( user_id, problem_title, problem_content, problem_time, problem_mem, problem_ex_input, problem_ex_output, problem_input_desc, problem_output_desc, problem_validation_code, problem_validation_lang ) - values (${userId}, #{problemTitle}, #{problemContent}, '${problemTime}', '${problemMem}',#{problemExInput}, #{problemExOutput}, #{problemInputDesc}, #{problemOutputDesc}, #{problemValidationCode}, '${problemValidationLang}') - - select last_insert_id(); - - - - - insert into ps_testcase (problem_id, input, output) - values - - ('${problemId}' ,'${item.input}', '${item.output}' ) - - - - - insert into ps_problem_tag (problem_id, tag_name) values - - ('${problemId}', '${item.tagName}') - - - - - delete from ps_list where problem_id=${problemId} - - - - - - - insert into ps_submit - (problem_id, user_id, submit_lang, code, submit_status) - values - (${problemId}, '${userId}', '${submitLang}', #{code}, '${submitStatus}') - - select last_insert_id() - - - - - insert into ps_submit_tag - (submit_no, tag_name) - values - - ( ${submitNo}, '${item.tagName}' ) - - - - - - and u.user_nickname like concat('%','${userNickname}','%') - - - - - and problem_id=${problemId} - - - - - and submit_lang like concat('%', '${lang}', '%') - - - - - - order by ${orderBy} desc - - - order by ${orderBy} asc - - - - - - and submit_status like concat('%','맞았습니다.','%') - - - - - - - - - - - - - - - delete from ps_problem_tag where problem_id=${problemId} - - - - update - ps_list - set problem_title=#{problemTitle}, problem_content=#{problemContent}, - problem_input_desc=#{problemInputDesc}, problem_output_desc=#{problemOutputDesc}, - problem_validation_code=#{problemValidationCode}, problem_validation_lang='${problemValidationLang}', - problem_ex_input=#{problemExInput}, problem_ex_output=#{problemExOutput}, - problem_time='${problemTime}', problem_mem='${problemMem}' - where - problem_id=${problemId} - - - - update - ps_list - set problem_visibility='${change}' - where - problem_id=${problemId} - - - - - - - - - \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/Profile.xml b/back-end/codearena/src/main/resources/mapper/Profile.xml deleted file mode 100644 index ec0a3d28..00000000 --- a/back-end/codearena/src/main/resources/mapper/Profile.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - update user - set user_thumbnail=#{url} - where user_id=${userId}; - - - - - \ No newline at end of file diff --git a/back-end/codearena/src/main/resources/mapper/User.xml b/back-end/codearena/src/main/resources/mapper/User.xml deleted file mode 100644 index b2ad7370..00000000 --- a/back-end/codearena/src/main/resources/mapper/User.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - insert into user(user_email, user_password, user_nickname, user_intro, user_thumbnail) values("${userEmail}" ,"${userPassword}" , "${userNickname}", "${userIntro}", "${userThumbnail}"); - - - - - - - - - - update user - set refresh_token=NULL - where user_email=#{userEmail}; - - - - update user set verification_code="${tempCode}" where user_email="${userEmail}"; - - - - - - - - update user - set refresh_token=#{refreshToken} - where user_email=#{userEmail}; - - - - update user - set user_password=#{userPassword} - where user_email=#{userEmail}; - - - - update user - set user_nickname=#{userNickname}, user_intro=#{userIntro} - where user_id=#{userId}; - - - - insert into follow - values (#{fromId}, #{toId}); - - - - delete from follow - where from_id=#{fromId} and to_id=#{toId}; - - - - - - - - - - - \ No newline at end of file diff --git a/back-end/codearena/src/test/java/com/ssafy/codearena/CodearenaApplicationTests.java b/back-end/codearena/src/test/java/com/ssafy/codearena/CodearenaApplicationTests.java deleted file mode 100644 index 3aab312f..00000000 --- a/back-end/codearena/src/test/java/com/ssafy/codearena/CodearenaApplicationTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.codearena; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -class CodearenaApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/back-end/judge_cpp/.gitignore b/back-end/judge_cpp/.gitignore deleted file mode 100644 index e48b6be6..00000000 --- a/back-end/judge_cpp/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -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/ \ No newline at end of file diff --git a/back-end/judge_cpp/Dockerfile b/back-end/judge_cpp/Dockerfile deleted file mode 100644 index 07c58f61..00000000 --- a/back-end/judge_cpp/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM openjdk:17-jdk-alpine -RUN apk update && apk add g++ - -# FROM : 이미지 레이어의 최상단, alpine리눅스에 jdk 17을 사용한단 의미 - -WORKDIR /app -# WORKDIR : 스프링 부트 컨테이너 OS내에 어떤 디렉토리에서 jar을 실행 할 것인지 - -ARG JAR_FILE=build/libs/judge-0.0.1-SNAPSHOT.jar -# ARG : 변수지정, 변수에 적혀진 의미는 빌드 결과물 위치 - -COPY ${JAR_FILE} test.jar -# Auto Exctraction으로 압축된 파일을 해제하여 test.jar에 그 내용을 복사, 결국 스프링부트를 실행하는 컨테이너 내에는 test.jar가 있게 됨 - -ENTRYPOINT ["java", "-jar","test.jar","--encryptor.key=${ENV_KEY}"] -# ENTRYPOINT : 해당 컨테이너 시작할때 무조건 실행할 명령어 지정 \ No newline at end of file diff --git a/back-end/judge_cpp/build.gradle b/back-end/judge_cpp/build.gradle deleted file mode 100644 index 269db893..00000000 --- a/back-end/judge_cpp/build.gradle +++ /dev/null @@ -1,45 +0,0 @@ -plugins { - id 'java' - id 'org.springframework.boot' version '3.2.2' - id 'io.spring.dependency-management' version '1.1.4' -} - -group = 'com.codearena' -version = '0.0.1-SNAPSHOT' - -java { - sourceCompatibility = '17' -} - -configurations { - compileOnly { - extendsFrom annotationProcessor - } -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - developmentOnly 'org.springframework.boot:spring-boot-devtools' - compileOnly 'org.projectlombok:lombok' - annotationProcessor 'org.projectlombok:lombok' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - // mysql connector j - implementation group: 'com.mysql', name: 'mysql-connector-j', version: '8.0.33' - // https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter - implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '3.0.3' - //jasypt - implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' - //Swagger - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' - // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '3.2.2' - -} - -tasks.named('test') { - useJUnitPlatform() -} diff --git a/back-end/judge_cpp/gradle/wrapper/gradle-wrapper.jar b/back-end/judge_cpp/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/back-end/judge_cpp/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/back-end/judge_cpp/gradle/wrapper/gradle-wrapper.properties b/back-end/judge_cpp/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1af9e093..00000000 --- a/back-end/judge_cpp/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/back-end/judge_cpp/gradlew b/back-end/judge_cpp/gradlew deleted file mode 100644 index 1aa94a42..00000000 --- a/back-end/judge_cpp/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/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/subprojects/plugins/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/back-end/judge_cpp/gradlew.bat b/back-end/judge_cpp/gradlew.bat deleted file mode 100644 index 93e3f59f..00000000 --- a/back-end/judge_cpp/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@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. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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/back-end/judge_cpp/settings.gradle b/back-end/judge_cpp/settings.gradle deleted file mode 100644 index 2264abe1..00000000 --- a/back-end/judge_cpp/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'judge' diff --git a/back-end/judge_cpp/src/main/java/com/codearena/JudgeApplication.java b/back-end/judge_cpp/src/main/java/com/codearena/JudgeApplication.java deleted file mode 100644 index 64b3c4ea..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/JudgeApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.codearena; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class JudgeApplication { - - public static void main(String[] args) { - SpringApplication.run(JudgeApplication.class, args); - } - -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/config/DataBaseConfiguration.java b/back-end/judge_cpp/src/main/java/com/codearena/config/DataBaseConfiguration.java deleted file mode 100644 index 62f50172..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/config/DataBaseConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.codearena.config; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -import javax.sql.DataSource; - -@Configuration -@PropertySource("classpath:/application.properties") -@MapperScan(basePackages = {"com.codearena.*.mapper"}) -public class DataBaseConfiguration{ - - final ApplicationContext applicationContext; - // mapper.xml 위치를 Resource객체 로 들고오기 위해 - - public DataBaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - // ApplicationContext이 Bean을 관리하는 역할을 수행하고 - // SpringBootApplication이 실행될 때 @Configuration 어노테이션이 붙은 java파일을 설정정보로 등록한다. - // 이 때 @Bean으로 등록된 메서드들을 기반으로 빈 목록을 생성한다. - @ConfigurationProperties(prefix = "spring.datasource.hikari") - public HikariConfig hikariConfig() { - // application.properties 파일에서 spring.datasource.hikari로 시작하는 설정 값들을 가져와 Hikari 설정 객체를 반환한다. - return new HikariConfig(); - } - - @Bean - public DataSource dataSource() { - // HikariDataSource를 사용하기 위해 Hikari 설정 객체를 생성자로 넣은 HikariDataSource 객체 반환 - return new HikariDataSource(hikariConfig()); - } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { - // SqlSessionFactory는 Mybatis-spring 때 처럼 SqlSessionFactoryBean을 통해 생성되는데 - // 각종 typeAliase(DTO), mapperLocation(xml위치), DB접속정보(datasource)를 property를 통해 추가한다. - // 즉 setter를 통해 추가된다. - - SqlSessionFactoryBean session = new SqlSessionFactoryBean(); - session.setDataSource(dataSource); - session.setMapperLocations(applicationContext.getResources("classpath:mapper/**/*.xml")); - session.setTypeAliasesPackage("com.codearena.*.dto"); - return session.getObject(); - } - - @Bean - public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { - // SqlSessionTemplate은 SqlSession인터페이스 타입의 객체이며 - // 결국 SqlSessionFactory의 각종 설정 정보를 통해 만들어지므로 생성자로 넣게 된다. - return new SqlSessionTemplate(sqlSessionFactory); - } -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/config/JasyptConfig.java b/back-end/judge_cpp/src/main/java/com/codearena/config/JasyptConfig.java deleted file mode 100644 index 880ccd23..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/config/JasyptConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.codearena.config; - - -import org.jasypt.encryption.StringEncryptor; -import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class JasyptConfig { - - @Value("${encryptor.key}") - String KEY; - - private static final String ALGORITHM = "PBEWithMD5AndDES"; - - @Bean(name = "jasyptStringEncryptor") - public StringEncryptor stringEncryptor() { - PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); - SimpleStringPBEConfig config = new SimpleStringPBEConfig(); - - config.setPassword(KEY); //암호화 시 사용할 키 -> 이 키를 가지고 암호화 복호화 진행 - config.setAlgorithm(ALGORITHM); //사용할 알고리즘 - config.setKeyObtentionIterations("1000"); //반복할 해싱 회수 - config.setPoolSize("1"); //pool 크기 - config.setProviderName("SunJCE"); //사용할 암호화 라이브러리 - config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); //salt 생성 클래스 - config.setStringOutputType("base64"); //인코딩 방식 - encryptor.setConfig(config); //설정 주입 - - return encryptor; - - } -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/config/SwaggerConfig.java b/back-end/judge_cpp/src/main/java/com/codearena/config/SwaggerConfig.java deleted file mode 100644 index 74668ba0..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/config/SwaggerConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.codearena.config; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration // 스프링 실행시 설정파일 읽어드리기 위한 어노테이션 -public class SwaggerConfig { - - @Bean - public OpenAPI openAPI() { - return new OpenAPI() - .components(new Components()) - .info(apiInfo()); - } - - private Info apiInfo() { - return new Info() - .title("CodeArena Swagger") - .description("CodeArena 채점 서버에 대한 API") - .version("1.0.0"); - } -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/config/WebMvcConfiguration.java b/back-end/judge_cpp/src/main/java/com/codearena/config/WebMvcConfiguration.java deleted file mode 100644 index dbb8fbee..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/config/WebMvcConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.codearena.config; - -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@RequiredArgsConstructor -public class WebMvcConfiguration implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry - .addMapping("/**") -// .allowedOrigins("http://192.168.0.29:3000") - .allowedOriginPatterns("*") -// .allowedOrigins("http://localhost:5173", "http://localhost:5174") - .allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), - HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(), - HttpMethod.PATCH.name()) -// .allowedHeaders("Authorization") -// .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD") - .allowCredentials(true) - .exposedHeaders("Authorization") - .maxAge(1800); // Pre-flight Caching - } - -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/controller/JudgeController.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/controller/JudgeController.java deleted file mode 100644 index 4d1b8376..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/controller/JudgeController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.codearena.judge.controller; - -import com.codearena.judge.dto.*; -import com.codearena.judge.service.JudgeService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@Slf4j -@RequiredArgsConstructor -@RequestMapping("/judge") -public class JudgeController { - - private final JudgeService judgeService; - - // 검증용 로직 - // 코드, 테케 필요 - @PostMapping("/validation") - public ResponseEntity validationCheck(@RequestBody JudgeValidationCheckDto judgeValidationCheckDto) { - return new ResponseEntity(judgeService.validationCheck(judgeValidationCheckDto), HttpStatus.OK); - } - @PostMapping("/arena") - public ResponseEntity judgeArena(@RequestBody JudgeArenaDto judgeArenaDto) { - return new ResponseEntity(judgeService.judgeArena(judgeArenaDto), HttpStatus.OK); - } - @PostMapping("/normal") - public ResponseEntity judgeNormal(@RequestBody JudgeNormalDto judgeNormalDto) { - return new ResponseEntity(judgeService.judgeNormal(judgeNormalDto), HttpStatus.OK); - } - @PostMapping("/example") - public ResponseEntity judgeExample(@RequestBody JudgeExampleDto judgeExampleDto) { - return new ResponseEntity(judgeService.judgeExample(judgeExampleDto), HttpStatus.OK); - } -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java deleted file mode 100644 index 5d803db7..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeArenaDto { - private String submitNo; - private String problemId; - private String code; - private String gameType; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java deleted file mode 100644 index 71fe4f19..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeExampleDto { - private String code; - private String problemId; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java deleted file mode 100644 index 307725cb..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeNormalDto { - private String submitNo; - private String problemId; - private String code; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java deleted file mode 100644 index a69de64a..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class JudgeProblemInfoDto { - private Long problemTime; - private String problemMem; - private List testCaseList; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeResultDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeResultDto.java deleted file mode 100644 index 6b281325..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java deleted file mode 100644 index 1851c156..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeValidateResultDto { - private boolean isSolve; - private String submitNo; - private String msg; - private String time; - private String wrongTestCaseNo; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java deleted file mode 100644 index fe0cb116..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class JudgeValidationCheckDto { - private String problemValidationCode; - private String problemExInput; - private String problemExOutput; - private String problemTime; - private List testCase; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/TestCaseDto.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/TestCaseDto.java deleted file mode 100644 index a7d0cecd..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/dto/TestCaseDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -public class TestCaseDto { - private String input; - private String output; - private String tid; - private String problemTime; -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/mapper/JudgeMapper.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/mapper/JudgeMapper.java deleted file mode 100644 index f0f6054a..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/mapper/JudgeMapper.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.codearena.judge.mapper; - -import com.codearena.judge.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -@Mapper -public interface JudgeMapper { - void insertProblem(JudgeValidationCheckDto userInput) throws SQLException; - JudgeProblemInfoDto getProblemInfo(String problemId) throws SQLException; - List getTestCase(String problemId) throws SQLException; - void updatePsSubmit(JudgeValidateResultDto judgeValidateResultDto) throws SQLException; - void updateArenaSubmit(JudgeValidateResultDto judgeValidateResultDto) throws SQLException; - TestCaseDto getExTestCase(String problemId) throws SQLException; - -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/service/JudgeService.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/service/JudgeService.java deleted file mode 100644 index 8fb6292a..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/service/JudgeService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.service; - -import com.codearena.judge.dto.*; - -public interface JudgeService { - JudgeResultDto validationCheck(JudgeValidationCheckDto judgeValidationCheckDto); - JudgeResultDto judgeArena(JudgeArenaDto judgeArenaDto); - JudgeResultDto judgeNormal(JudgeNormalDto judgeNormalDto); - JudgeResultDto judgeExample(JudgeExampleDto judgeExampleDto); -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java b/back-end/judge_cpp/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java deleted file mode 100644 index 4640005b..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java +++ /dev/null @@ -1,248 +0,0 @@ -package com.codearena.judge.service; - -import com.codearena.judge.dto.*; -import com.codearena.judge.mapper.JudgeMapper; -import com.codearena.util.JudgeUtil; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Service -@Slf4j -@RequiredArgsConstructor -public class JudgeServiceImpl implements JudgeService{ - - private final JudgeMapper mapper; - private final JudgeUtil judgeUtil; - - @Override - public JudgeResultDto validationCheck(JudgeValidationCheckDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("문제 유효성 검사 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = new JudgeValidateResultDto(); - - log.info("{}", userInput.getProblemValidationCode()); - - // 시스템 콜 감지 - if(judgeUtil.checkSystemCallInCode(userInput.getProblemValidationCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - return judgeResultDto; - } - - try { - // problemExInput, Output 를 테스트케이스에 포함시킴 - List testCase = userInput.getTestCase(); - - TestCaseDto exTestCase = new TestCaseDto(); - exTestCase.setInput(userInput.getProblemExInput().replaceAll("\r", "")); - exTestCase.setOutput(userInput.getProblemExOutput().replaceAll("\r", "")); - - testCase.add(exTestCase); - - for (int i = 0 ; i < testCase.size() ; i ++) { - String str = testCase.get(i).getOutput().trim(); - testCase.get(i).setOutput(str); - } - // 테케 내용들 로그 출력 - for (int tc = 0; tc < testCase.size(); tc++) { - log.info("{}", testCase.get(tc)); - } - - long timeLimit = Long.parseLong(userInput.getProblemTime()); - - String path = UUID.randomUUID().toString(); - - String cmd = ""; - log.info("CMD : {}", cmd); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.cpp) - judgeUtil.createCodeFile(userInput.getProblemValidationCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, testCase, timeLimit, path); - log.info("[validationCheck] judgeValidationResult : {}" , result); - - } catch (Exception e) { - log.debug("[validationCheck] Exception : {}" , e); - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeArena(JudgeArenaDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("일반 문제 채점 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = null; - - // 시스템 콜 체크 - if(judgeUtil.checkSystemCallInCode(userInput.getCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - judgeResultDto.setData(null); - return judgeResultDto; - } - - try { - // 문제 정보 가져오기 - JudgeProblemInfoDto problemInfo = judgeUtil.getProblemInfo(userInput.getProblemId()); - - String path = UUID.randomUUID().toString(); - - String cmd = ""; - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.cpp) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, problemInfo.getTestCaseList(), problemInfo.getProblemTime(), path); - - log.info("[arena] judgeValidationResult : {}" , result); - - result.setSubmitNo(userInput.getSubmitNo()); - - // 효율전이면 - if("1".equals(userInput.getGameType())) - mapper.updateArenaSubmit(result); - - } catch (Exception e) { - log.debug("[arena] Exception : {}", e); - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeNormal(JudgeNormalDto userInput) { - - log.debug("[normal] userInput : {}", userInput); - - JudgeResultDto judgeResultDto = new JudgeResultDto(); - - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("일반 문제 채점 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = null; - - - -// 시스템 콜 체크 - if(judgeUtil.checkSystemCallInCode(userInput.getCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - judgeResultDto.setData(null); - return judgeResultDto; - } - - try { - // 문제 정보 가져오기 - JudgeProblemInfoDto problemInfo = judgeUtil.getProblemInfo(userInput.getProblemId()); - - String path = UUID.randomUUID().toString(); - - // validate 안에서 실행하도록 만듦 - String cmd = ""; - - log.debug("[normal] cmd : {}", cmd); - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.out) - judgeUtil.createCodeFile(userInput.getCode(), path); - - // 코드 검증하기 - result = judgeUtil.validate(cmd, problemInfo.getTestCaseList(), problemInfo.getProblemTime(), path); - log.info("[normal] judgeValidationResult : {}" , result); - - result.setSubmitNo(userInput.getSubmitNo()); - log.info("userInput : {}" , userInput); - log.info("result : {}" , result); - mapper.updatePsSubmit(result); - - } catch (Exception e) { - log.debug("Exception : {}", e); - - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeExample(JudgeExampleDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("예제 채점 성공"); - judgeResultDto.setData(null); - - try { - TestCaseDto exTestCase = mapper.getExTestCase(userInput.getProblemId()); - - log.info("[testcaseDto] , {} ", exTestCase); - - exTestCase.setInput(exTestCase.getInput().replaceAll("\r", "")); - exTestCase.setOutput(exTestCase.getInput().replaceAll("\r", "")); - - String ExInputStr = exTestCase.getInput().trim(); - exTestCase.setInput(ExInputStr); - - String ExOutputStr = exTestCase.getOutput().trim(); - exTestCase.setOutput(ExOutputStr); - - long timeLimit = Long.parseLong(exTestCase.getProblemTime()); - - String path = UUID.randomUUID().toString(); - - String cmd = "java " + path + "/Solution.java"; - log.info("CMD : {}", cmd); - - List exTestCaseList = new ArrayList<>(); - exTestCaseList.add(exTestCase); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - JudgeValidateResultDto result = judgeUtil.validate(cmd, exTestCaseList, timeLimit, path); - log.info("[validationCheck] judgeValidationResult : {}" , result); - - } catch (Exception e) { - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - log.debug("[JudgeExample] : {} ", e); - } - - return judgeResultDto; - } -} diff --git a/back-end/judge_cpp/src/main/java/com/codearena/util/JudgeUtil.java b/back-end/judge_cpp/src/main/java/com/codearena/util/JudgeUtil.java deleted file mode 100644 index f0f6fa11..00000000 --- a/back-end/judge_cpp/src/main/java/com/codearena/util/JudgeUtil.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.codearena.util; - -import com.codearena.judge.dto.JudgeProblemInfoDto; -import com.codearena.judge.dto.JudgeValidateResultDto; -import com.codearena.judge.dto.TestCaseDto; -import com.codearena.judge.mapper.JudgeMapper; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Configuration; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Configuration -@Slf4j -@RequiredArgsConstructor -public class JudgeUtil { - - private final JudgeMapper mapper; - - public void createFolder(String path) { - // 폴더 생성 - File Folder = new File(path); - - // 해당 디렉토리가 없을경우 디렉토리를 생성합니다. - if (!Folder.exists()) { - try{ - log.info("폴더가 생성되었습니다. {}" , Folder.mkdir()); - } - catch(Exception e){ - log.debug("createFolder Exception : {}", e); - } - }else { - log.debug("Exception : 이미 폴더가 생성되어 있습니다"); - } - } - - public void createCodeFile(String code, String path) throws IOException { - File file = new File(path, "Solution.cpp"); - - log.info("파일 생성 중. {}"); - log.info("path : {}" + path); - - if(file.createNewFile()); - - FileWriter fw = new FileWriter(file); - log.info("code : {}", code); - fw.write(code); - fw.close(); - } - - public boolean checkSystemCallInCode(String code) { - Pattern pattern = Pattern.compile("(? testCaseList = new ArrayList<>(); - - try { - judgeProblemInfoDto = mapper.getProblemInfo(problemId); - testCaseList = mapper.getTestCase(problemId); - judgeProblemInfoDto.setTestCaseList(testCaseList); - } catch (Exception e) { - log.debug("Exception : {} ", e); - } - - return judgeProblemInfoDto; - } - - /** - * - * @param cmd : 런타임에서 실행할 명령 - * @param testCase : 채점 테스트 케이스 - * @param timeLimit : 시간제한 - * @param path : 디렉토리 생성 경로 - * @return JudgeValidateResultDto - * @throws Exception - */ - public JudgeValidateResultDto validate(String cmd, - List testCase, - Long timeLimit, - String path) throws Exception { - - // 런타임 생성하기 - Runtime runtime = Runtime.getRuntime(); - - JudgeValidateResultDto result = new JudgeValidateResultDto(); - - result.setSolve(true); - // 실행 결과 담기 - String msg = "맞았습니다."; - // 시간의 총 합. - double timeSum = 0.0; - // 에러가 발생 했는지 - boolean isError = false; - - String wrongTC = null; - - cmd = "g++ -o ./" + path + "/Solution.out ./" + path +"/Solution.cpp"; - - Process process = runtime.exec(cmd); - process.waitFor(); - - cmd = "./" + path +"/Solution.out"; - - // TC 불러왔으면 검사하는 로직 수행하기 - for (int tc = 0; tc < testCase.size(); tc++) { - // 컴파일 하고 실행시키기 - process = runtime.exec(cmd); - - // BufferedWriter로 Output 스트림에 실행 결과를 담기 - // 실행 결과를 - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); - bw.write(testCase.get(tc).getInput()); - bw.flush(); - bw.close(); - - double beforeTime = System.currentTimeMillis(); - - if (!process.waitFor(timeLimit + 1000, TimeUnit.MILLISECONDS)) { - msg = "시간 초과"; - wrongTC = testCase.get(tc).getTid(); - isError = true; - break; - } - - double afterTime = System.currentTimeMillis(); - - BufferedReader bf = new BufferedReader(new InputStreamReader(process.getInputStream(), "MS949")); - StringBuilder sb = new StringBuilder(); - String str = null; - - while((str = bf.readLine()) != null) { - sb.append(str).append("\n"); - } - - timeSum += (afterTime - beforeTime) / 1000; - - log.info("tc : {} 시간 측정 결과 : {}\n", tc, (afterTime-beforeTime)/1000); - - BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); - log.info("processExitValue : {} (0 = 정상작동)", process.exitValue()); - - if (process.exitValue() != 0) { - String error = errorReader.readLine(); - log.info("errorMsg : {}", error); - - String[] frags = error.split(" "); - - isError = true; - wrongTC = testCase.get(tc).getTid(); - - msg = "컴파일 에러"; - - switch (frags[0]) { - case "warning": - log.debug("error : {}", error); - msg = "런타임 에러"; - break; - case "error:": - log.debug("error : {}", error); - msg = "컴파일 에러"; - break; - } - break; - } - String tcTrim = testCase.get(tc).getOutput(); - String sbTrim = sb.toString().trim(); - - tcTrim = tcTrim.replaceAll("\r", ""); - sbTrim = sbTrim.replaceAll("\r", ""); - - log.info("비교 결과 : {}" , tcTrim.equals(sbTrim)); - - if (!tcTrim.equals(sbTrim)) { - msg = "틀렸습니다"; - wrongTC = testCase.get(tc).getTid(); - isError = true; - break; - } - - log.info("errorReader.readLine() : {}", errorReader.readLine()); - log.info("ProcessExitValue : {}", process.exitValue()); - - // 결과 값 출력 & 저장 - log.info("str : {}", str); - } - - String timeResult; - - // 에러 발생 시 시간은 없음 - if (isError) { - result.setSolve(false); - timeResult = null; - - } else { - timeSum *= 1000; - timeSum /= testCase.size(); - timeSum = Math.floor(timeSum); - timeResult = (int)timeSum + ""; - } - - result.setMsg(msg); - result.setSolve(!isError); - result.setTime(timeResult); - result.setWrongTestCaseNo(wrongTC); - - File dirFile = new File(path); - File cppFile = new File(path, "Solution.cpp"); - File exeFile = new File(path, "Solution.out"); - - // 결과 반영 했으면 디렉토리 삭제하기 - // 내부 파일부터 삭제하고 디렉토리 삭제 - exeFile.delete(); - cppFile.delete(); - dirFile.delete(); - - return result; - } -} - diff --git a/back-end/judge_cpp/src/main/resources/application.properties b/back-end/judge_cpp/src/main/resources/application.properties deleted file mode 100644 index 8e2a4590..00000000 --- a/back-end/judge_cpp/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -# spring.datasource. ? ?? ?? ????. -server.servlet.context-path=/cpp -server.port=8080 - -spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver -spring.datasource.hikari.jdbc-url=ENC(BZivb1YebBXdnHbtZKRmFcsKFuuQD2id7f8+DeSTQV1BjBAisInx6udYyTiWvRXoJu33Dd5pyrXSQO2GRTmwn21QBFSlNLh69fLUmeUWKc1nZuLbWxfDeLsLHG7RBqKUqjdiPIxy3jIgXCoileJ6iw==) -spring.datasource.hikari.username=ENC(u2pZ0ldKEDL6po+p2UuafA==) -spring.datasource.hikari.password=ENC(GZ8loB1io9uhSlw1ko8OliT/qrwYkIYo) -spring.datasource.hikari.pool-name=Hikari Connection Pool -# hikariCP property setting -spring.datasource.hikari.maximum-pool-size=50 -spring.datasource.hikari.minimum-idle=50 -spring.datasource.hikari.connection-timeout=5000 -spring.datasource.hikari.connection-init-sql=SELECT 1 -spring.datasource.hikari.idle-timeout=600000 -spring.datasource.hikari.max-lifetime=1800000 -spring.datasource.hikari.auto-commit=true - -logging.level.com.codearena=debug diff --git a/back-end/judge_cpp/src/main/resources/mapper/Judge.xml b/back-end/judge_cpp/src/main/resources/mapper/Judge.xml deleted file mode 100644 index 79b9e6c4..00000000 --- a/back-end/judge_cpp/src/main/resources/mapper/Judge.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - update ps_submit - set submit_status=#{msg}, time_complexity=#{time}, tid=#{wrongTestCaseNo} - where submit_no=#{submitNo}; - - - - update arena_submit_status - set submit_status=#{msg}, time_complexity=#{time} - where submit_no=#{submitNo}; - - - - - \ No newline at end of file diff --git a/back-end/judge_cpp/src/test/java/com/codearena/judge/JudgeApplicationTests.java b/back-end/judge_cpp/src/test/java/com/codearena/judge/JudgeApplicationTests.java deleted file mode 100644 index b49b1eed..00000000 --- a/back-end/judge_cpp/src/test/java/com/codearena/judge/JudgeApplicationTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -class JudgeApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/back-end/judge_java/.gitignore b/back-end/judge_java/.gitignore deleted file mode 100644 index e48b6be6..00000000 --- a/back-end/judge_java/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -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/ \ No newline at end of file diff --git a/back-end/judge_java/Dockerfile b/back-end/judge_java/Dockerfile deleted file mode 100644 index 0cdaec9a..00000000 --- a/back-end/judge_java/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM openjdk:17-jdk-alpine -# FROM : 이미지 레이어의 최상단, alpine리눅스에 jdk 17을 사용한단 의미 - -WORKDIR /app -# WORKDIR : 스프링 부트 컨테이너 OS내에 어떤 디렉토리에서 jar을 실행 할 것인지 - -ARG JAR_FILE=build/libs/judge-0.0.1-SNAPSHOT.jar -# ARG : 변수지정, 변수에 적혀진 의미는 빌드 결과물 위치 - -COPY ${JAR_FILE} test.jar -# Auto Exctraction으로 압축된 파일을 해제하여 test.jar에 그 내용을 복사, 결국 스프링부트를 실행하는 컨테이너 내에는 test.jar가 있게 됨 - -ENTRYPOINT ["java", "-jar","test.jar","--encryptor.key=${ENV_KEY}"] -# ENTRYPOINT : 해당 컨테이너 시작할때 무조건 실행할 명령어 지정 \ No newline at end of file diff --git a/back-end/judge_java/build.gradle b/back-end/judge_java/build.gradle deleted file mode 100644 index 269db893..00000000 --- a/back-end/judge_java/build.gradle +++ /dev/null @@ -1,45 +0,0 @@ -plugins { - id 'java' - id 'org.springframework.boot' version '3.2.2' - id 'io.spring.dependency-management' version '1.1.4' -} - -group = 'com.codearena' -version = '0.0.1-SNAPSHOT' - -java { - sourceCompatibility = '17' -} - -configurations { - compileOnly { - extendsFrom annotationProcessor - } -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - developmentOnly 'org.springframework.boot:spring-boot-devtools' - compileOnly 'org.projectlombok:lombok' - annotationProcessor 'org.projectlombok:lombok' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - // mysql connector j - implementation group: 'com.mysql', name: 'mysql-connector-j', version: '8.0.33' - // https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter - implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '3.0.3' - //jasypt - implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' - //Swagger - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' - // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '3.2.2' - -} - -tasks.named('test') { - useJUnitPlatform() -} diff --git a/back-end/judge_java/gradle/wrapper/gradle-wrapper.jar b/back-end/judge_java/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/back-end/judge_java/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/back-end/judge_java/gradle/wrapper/gradle-wrapper.properties b/back-end/judge_java/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1af9e093..00000000 --- a/back-end/judge_java/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/back-end/judge_java/gradlew b/back-end/judge_java/gradlew deleted file mode 100644 index 1aa94a42..00000000 --- a/back-end/judge_java/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/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/subprojects/plugins/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/back-end/judge_java/gradlew.bat b/back-end/judge_java/gradlew.bat deleted file mode 100644 index 93e3f59f..00000000 --- a/back-end/judge_java/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@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. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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/back-end/judge_java/settings.gradle b/back-end/judge_java/settings.gradle deleted file mode 100644 index 2264abe1..00000000 --- a/back-end/judge_java/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'judge' diff --git a/back-end/judge_java/src/main/java/com/codearena/JudgeApplication.java b/back-end/judge_java/src/main/java/com/codearena/JudgeApplication.java deleted file mode 100644 index 64b3c4ea..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/JudgeApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.codearena; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class JudgeApplication { - - public static void main(String[] args) { - SpringApplication.run(JudgeApplication.class, args); - } - -} diff --git a/back-end/judge_java/src/main/java/com/codearena/config/DataBaseConfiguration.java b/back-end/judge_java/src/main/java/com/codearena/config/DataBaseConfiguration.java deleted file mode 100644 index 62f50172..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/config/DataBaseConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.codearena.config; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -import javax.sql.DataSource; - -@Configuration -@PropertySource("classpath:/application.properties") -@MapperScan(basePackages = {"com.codearena.*.mapper"}) -public class DataBaseConfiguration{ - - final ApplicationContext applicationContext; - // mapper.xml 위치를 Resource객체 로 들고오기 위해 - - public DataBaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - // ApplicationContext이 Bean을 관리하는 역할을 수행하고 - // SpringBootApplication이 실행될 때 @Configuration 어노테이션이 붙은 java파일을 설정정보로 등록한다. - // 이 때 @Bean으로 등록된 메서드들을 기반으로 빈 목록을 생성한다. - @ConfigurationProperties(prefix = "spring.datasource.hikari") - public HikariConfig hikariConfig() { - // application.properties 파일에서 spring.datasource.hikari로 시작하는 설정 값들을 가져와 Hikari 설정 객체를 반환한다. - return new HikariConfig(); - } - - @Bean - public DataSource dataSource() { - // HikariDataSource를 사용하기 위해 Hikari 설정 객체를 생성자로 넣은 HikariDataSource 객체 반환 - return new HikariDataSource(hikariConfig()); - } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { - // SqlSessionFactory는 Mybatis-spring 때 처럼 SqlSessionFactoryBean을 통해 생성되는데 - // 각종 typeAliase(DTO), mapperLocation(xml위치), DB접속정보(datasource)를 property를 통해 추가한다. - // 즉 setter를 통해 추가된다. - - SqlSessionFactoryBean session = new SqlSessionFactoryBean(); - session.setDataSource(dataSource); - session.setMapperLocations(applicationContext.getResources("classpath:mapper/**/*.xml")); - session.setTypeAliasesPackage("com.codearena.*.dto"); - return session.getObject(); - } - - @Bean - public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { - // SqlSessionTemplate은 SqlSession인터페이스 타입의 객체이며 - // 결국 SqlSessionFactory의 각종 설정 정보를 통해 만들어지므로 생성자로 넣게 된다. - return new SqlSessionTemplate(sqlSessionFactory); - } -} diff --git a/back-end/judge_java/src/main/java/com/codearena/config/JasyptConfig.java b/back-end/judge_java/src/main/java/com/codearena/config/JasyptConfig.java deleted file mode 100644 index 880ccd23..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/config/JasyptConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.codearena.config; - - -import org.jasypt.encryption.StringEncryptor; -import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class JasyptConfig { - - @Value("${encryptor.key}") - String KEY; - - private static final String ALGORITHM = "PBEWithMD5AndDES"; - - @Bean(name = "jasyptStringEncryptor") - public StringEncryptor stringEncryptor() { - PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); - SimpleStringPBEConfig config = new SimpleStringPBEConfig(); - - config.setPassword(KEY); //암호화 시 사용할 키 -> 이 키를 가지고 암호화 복호화 진행 - config.setAlgorithm(ALGORITHM); //사용할 알고리즘 - config.setKeyObtentionIterations("1000"); //반복할 해싱 회수 - config.setPoolSize("1"); //pool 크기 - config.setProviderName("SunJCE"); //사용할 암호화 라이브러리 - config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); //salt 생성 클래스 - config.setStringOutputType("base64"); //인코딩 방식 - encryptor.setConfig(config); //설정 주입 - - return encryptor; - - } -} diff --git a/back-end/judge_java/src/main/java/com/codearena/config/SwaggerConfig.java b/back-end/judge_java/src/main/java/com/codearena/config/SwaggerConfig.java deleted file mode 100644 index 74668ba0..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/config/SwaggerConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.codearena.config; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration // 스프링 실행시 설정파일 읽어드리기 위한 어노테이션 -public class SwaggerConfig { - - @Bean - public OpenAPI openAPI() { - return new OpenAPI() - .components(new Components()) - .info(apiInfo()); - } - - private Info apiInfo() { - return new Info() - .title("CodeArena Swagger") - .description("CodeArena 채점 서버에 대한 API") - .version("1.0.0"); - } -} diff --git a/back-end/judge_java/src/main/java/com/codearena/config/WebMvcConfiguration.java b/back-end/judge_java/src/main/java/com/codearena/config/WebMvcConfiguration.java deleted file mode 100644 index dbb8fbee..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/config/WebMvcConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.codearena.config; - -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@RequiredArgsConstructor -public class WebMvcConfiguration implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry - .addMapping("/**") -// .allowedOrigins("http://192.168.0.29:3000") - .allowedOriginPatterns("*") -// .allowedOrigins("http://localhost:5173", "http://localhost:5174") - .allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), - HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(), - HttpMethod.PATCH.name()) -// .allowedHeaders("Authorization") -// .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD") - .allowCredentials(true) - .exposedHeaders("Authorization") - .maxAge(1800); // Pre-flight Caching - } - -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/controller/JudgeController.java b/back-end/judge_java/src/main/java/com/codearena/judge/controller/JudgeController.java deleted file mode 100644 index 4d1b8376..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/controller/JudgeController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.codearena.judge.controller; - -import com.codearena.judge.dto.*; -import com.codearena.judge.service.JudgeService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@Slf4j -@RequiredArgsConstructor -@RequestMapping("/judge") -public class JudgeController { - - private final JudgeService judgeService; - - // 검증용 로직 - // 코드, 테케 필요 - @PostMapping("/validation") - public ResponseEntity validationCheck(@RequestBody JudgeValidationCheckDto judgeValidationCheckDto) { - return new ResponseEntity(judgeService.validationCheck(judgeValidationCheckDto), HttpStatus.OK); - } - @PostMapping("/arena") - public ResponseEntity judgeArena(@RequestBody JudgeArenaDto judgeArenaDto) { - return new ResponseEntity(judgeService.judgeArena(judgeArenaDto), HttpStatus.OK); - } - @PostMapping("/normal") - public ResponseEntity judgeNormal(@RequestBody JudgeNormalDto judgeNormalDto) { - return new ResponseEntity(judgeService.judgeNormal(judgeNormalDto), HttpStatus.OK); - } - @PostMapping("/example") - public ResponseEntity judgeExample(@RequestBody JudgeExampleDto judgeExampleDto) { - return new ResponseEntity(judgeService.judgeExample(judgeExampleDto), HttpStatus.OK); - } -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java deleted file mode 100644 index 5d803db7..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeArenaDto { - private String submitNo; - private String problemId; - private String code; - private String gameType; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java deleted file mode 100644 index 71fe4f19..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeExampleDto { - private String code; - private String problemId; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java deleted file mode 100644 index 307725cb..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeNormalDto { - private String submitNo; - private String problemId; - private String code; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java deleted file mode 100644 index a69de64a..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class JudgeProblemInfoDto { - private Long problemTime; - private String problemMem; - private List testCaseList; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeResultDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeResultDto.java deleted file mode 100644 index 6b281325..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java deleted file mode 100644 index 1851c156..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeValidateResultDto { - private boolean isSolve; - private String submitNo; - private String msg; - private String time; - private String wrongTestCaseNo; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java deleted file mode 100644 index fe0cb116..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class JudgeValidationCheckDto { - private String problemValidationCode; - private String problemExInput; - private String problemExOutput; - private String problemTime; - private List testCase; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/dto/TestCaseDto.java b/back-end/judge_java/src/main/java/com/codearena/judge/dto/TestCaseDto.java deleted file mode 100644 index a7d0cecd..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/dto/TestCaseDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -public class TestCaseDto { - private String input; - private String output; - private String tid; - private String problemTime; -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/mapper/JudgeMapper.java b/back-end/judge_java/src/main/java/com/codearena/judge/mapper/JudgeMapper.java deleted file mode 100644 index f0f6054a..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/mapper/JudgeMapper.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.codearena.judge.mapper; - -import com.codearena.judge.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -@Mapper -public interface JudgeMapper { - void insertProblem(JudgeValidationCheckDto userInput) throws SQLException; - JudgeProblemInfoDto getProblemInfo(String problemId) throws SQLException; - List getTestCase(String problemId) throws SQLException; - void updatePsSubmit(JudgeValidateResultDto judgeValidateResultDto) throws SQLException; - void updateArenaSubmit(JudgeValidateResultDto judgeValidateResultDto) throws SQLException; - TestCaseDto getExTestCase(String problemId) throws SQLException; - -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/service/JudgeService.java b/back-end/judge_java/src/main/java/com/codearena/judge/service/JudgeService.java deleted file mode 100644 index 8fb6292a..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/service/JudgeService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.service; - -import com.codearena.judge.dto.*; - -public interface JudgeService { - JudgeResultDto validationCheck(JudgeValidationCheckDto judgeValidationCheckDto); - JudgeResultDto judgeArena(JudgeArenaDto judgeArenaDto); - JudgeResultDto judgeNormal(JudgeNormalDto judgeNormalDto); - JudgeResultDto judgeExample(JudgeExampleDto judgeExampleDto); -} diff --git a/back-end/judge_java/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java b/back-end/judge_java/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java deleted file mode 100644 index d88fbbe0..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.codearena.judge.service; - -import com.codearena.judge.dto.*; -import com.codearena.judge.mapper.JudgeMapper; -import com.codearena.util.JudgeUtil; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Service -@Slf4j -@RequiredArgsConstructor -public class JudgeServiceImpl implements JudgeService{ - - private final JudgeMapper mapper; - private final JudgeUtil judgeUtil; - - @Override - public JudgeResultDto validationCheck(JudgeValidationCheckDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("문제 유효성 검사 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = new JudgeValidateResultDto(); - - log.info("{}", userInput.getProblemValidationCode()); - - // 시스템 콜 감지 - if(judgeUtil.checkSystemCallInCode(userInput.getProblemValidationCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - return judgeResultDto; - } - - try { - // problemExInput, Output 를 테스트케이스에 포함시킴 - List testCase = userInput.getTestCase(); - - TestCaseDto exTestCase = new TestCaseDto(); - exTestCase.setInput(userInput.getProblemExInput().replaceAll("\r", "")); - exTestCase.setOutput(userInput.getProblemExOutput().replaceAll("\r", "")); - - testCase.add(exTestCase); - - for (int i = 0 ; i < testCase.size() ; i ++) { - String str = testCase.get(i).getOutput().trim(); - testCase.get(i).setOutput(str); - } - - // 테케 내용들 로그 출력 - for (int tc = 0; tc < testCase.size(); tc++) { - log.info("{}", testCase.get(tc)); - } - - long timeLimit = Long.parseLong(userInput.getProblemTime()); - - String path = UUID.randomUUID().toString(); - - String cmd = "java " + path + "/Solution.java"; - log.info("CMD : {}", cmd); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getProblemValidationCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, testCase, timeLimit, path); - log.info("[validationCheck] judgeValidationResult : {}" , result); - - } catch (Exception e) { - log.debug("[validationCheck] Exception : {}" , e); - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeArena(JudgeArenaDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("일반 문제 채점 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = null; - - // 시스템 콜 체크 - if(judgeUtil.checkSystemCallInCode(userInput.getCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - judgeResultDto.setData(null); - return judgeResultDto; - } - - try { - // 문제 정보 가져오기 - JudgeProblemInfoDto problemInfo = judgeUtil.getProblemInfo(userInput.getProblemId()); - - String path = UUID.randomUUID().toString(); - - String cmd = "java " + path + "/Solution.java"; - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, problemInfo.getTestCaseList(), problemInfo.getProblemTime(), path); - - log.info("[arena] judgeValidationResult : {}" , result); - - result.setSubmitNo(userInput.getSubmitNo()); - - if("1".equals(userInput.getGameType())) - mapper.updateArenaSubmit(result); - - } catch (Exception e) { - log.debug("[arena] Exception : {}", e); - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeNormal(JudgeNormalDto userInput) { - - JudgeResultDto judgeResultDto = new JudgeResultDto(); - - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("일반 문제 채점 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = null; - -// 시스템 콜 체크 - if(judgeUtil.checkSystemCallInCode(userInput.getCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - judgeResultDto.setData(null); - return judgeResultDto; - } - - try { - // 문제 정보 가져오기 - JudgeProblemInfoDto problemInfo = judgeUtil.getProblemInfo(userInput.getProblemId()); - - String path = UUID.randomUUID().toString(); - - String cmd = "java " + path + "/Solution.java"; - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, problemInfo.getTestCaseList(), problemInfo.getProblemTime(), path); - log.info("[normal] judgeValidationResult : {}" , result); - - result.setSubmitNo(userInput.getSubmitNo()); - log.info("userInput : {}" , userInput); - log.info("result : {}" , result); - mapper.updatePsSubmit(result); - - } catch (Exception e) { - log.debug("Exception : {}", e); - - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeExample(JudgeExampleDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("예제 채점 성공"); - judgeResultDto.setData(null); - - try { - TestCaseDto exTestCase = mapper.getExTestCase(userInput.getProblemId()); - - log.info("[testcaseDto] , {} ", exTestCase); - - exTestCase.setInput(exTestCase.getInput().replaceAll("\r", "")); - exTestCase.setOutput(exTestCase.getInput().replaceAll("\r", "")); - - long timeLimit = Long.parseLong(exTestCase.getProblemTime()); - - String path = UUID.randomUUID().toString(); - - String cmd = "java " + path + "/Solution.java"; - log.info("CMD : {}", cmd); - - List exTestCaseList = new ArrayList<>(); - exTestCaseList.add(exTestCase); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - JudgeValidateResultDto result = judgeUtil.validate(cmd, exTestCaseList, timeLimit, path); - log.info("[validationCheck] judgeValidationResult : {}" , result); - - } catch (Exception e) { - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - log.debug("[JudgeExample] : {} ", e); - } - - return judgeResultDto; - } -} diff --git a/back-end/judge_java/src/main/java/com/codearena/util/JudgeUtil.java b/back-end/judge_java/src/main/java/com/codearena/util/JudgeUtil.java deleted file mode 100644 index aa9867e6..00000000 --- a/back-end/judge_java/src/main/java/com/codearena/util/JudgeUtil.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.codearena.util; - -import com.codearena.judge.dto.JudgeProblemInfoDto; -import com.codearena.judge.dto.JudgeValidateResultDto; -import com.codearena.judge.dto.TestCaseDto; -import com.codearena.judge.mapper.JudgeMapper; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Configuration; - -import java.io.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Configuration -@Slf4j -@RequiredArgsConstructor -public class JudgeUtil { - - private final JudgeMapper mapper; - - public void createFolder(String path) { - // 폴더 생성 - File Folder = new File(path); - - // 해당 디렉토리가 없을경우 디렉토리를 생성합니다. - if (!Folder.exists()) { - try{ - log.info("폴더가 생성되었습니다. {}" , Folder.mkdir()); - } - catch(Exception e){ - log.debug("createFolder Exception : {}", e); - } - }else { - log.debug("Exception : 이미 폴더가 생성되어 있습니다"); - } - } - - public void createCodeFile(String code, String path) throws IOException { - File file = new File(path, "Solution.java"); - - log.info("파일 생성 중. {}"); - log.info("path : {}" + path); - - if(file.createNewFile()); - - FileWriter fw = new FileWriter(file); - log.info("code : {}", code); - fw.write(code); - fw.close(); - } - - public boolean checkSystemCallInCode(String code) { - Pattern pattern = Pattern.compile("(? testCaseList = new ArrayList<>(); - - try { - judgeProblemInfoDto = mapper.getProblemInfo(problemId); - testCaseList = mapper.getTestCase(problemId); - - judgeProblemInfoDto.setTestCaseList(testCaseList); - } catch (Exception e) { - log.debug("Exception : {} ", e); - } - - return judgeProblemInfoDto; - } - - /** - * - * @param cmd : 런타임에서 실행할 명령 - * @param testCase : 채점 테스트 케이스 - * @param timeLimit : 시간제한 - * @param path : 디렉토리 생성 경로 - * @return JudgeValidateResultDto - * @throws Exception - */ - public JudgeValidateResultDto validate(String cmd, - List testCase, - Long timeLimit, - String path) throws Exception { - - - // 런타임 생성하기 - Runtime runtime = Runtime.getRuntime(); - - JudgeValidateResultDto result = new JudgeValidateResultDto(); - - result.setSolve(true); - // 실행 결과 담기 - String msg = "맞았습니다."; - // 시간의 총 합. - double timeSum = 0.0; - // 에러가 발생 했는지 - boolean isError = false; - - String wrongTC = null; - - // TC 불러왔으면 검사하는 로직 수행하기 - for (int tc = 0; tc < testCase.size(); tc++) { - // 컴파일 하고 실행시키기 - Process process = runtime.exec(cmd); - - // BufferedWriter로 Output 스트림에 실행 결과를 담기 - // 실행 결과를 - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); - bw.write(testCase.get(tc).getInput()); - bw.flush(); - bw.close(); - - double beforeTime = System.currentTimeMillis(); - - if (!process.waitFor(timeLimit + 4000 + 1600, TimeUnit.MILLISECONDS)) { - msg = "시간 초과"; - wrongTC = testCase.get(tc).getTid(); - isError = true; - break; - } - - double afterTime = System.currentTimeMillis(); - BufferedReader bf = new BufferedReader(new InputStreamReader(process.getInputStream(), "MS949")); - StringBuilder sb = new StringBuilder(); - String str = null; - - while((str = bf.readLine()) != null) { - sb.append(str).append("\n"); - } - - timeSum += (afterTime - beforeTime) / 1000; - - log.info("tc : {} 시간 측정 결과 : {}\n", tc, (afterTime-beforeTime)/1000); - - BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); - log.info("processExitValue : {} (0 = 정상작동)", process.exitValue()); - - if (process.exitValue() != 0) { - String error = errorReader.readLine(); - log.info("errorMsg : {}", error); - - String[] frags = error.split(" "); - - isError = true; - wrongTC = testCase.get(tc).getTid(); - - msg = "컴파일 에러"; - switch (frags[0]) { - case "Exception": - log.debug("error : {}", error); - msg = "Exception : " + frags[4]; - break; - case "error:": - log.debug("error : {}", error); - msg = "컴파일 에러"; - break; - } - break; - } - - String tcTrim = testCase.get(tc).getOutput(); - String sbTrim = sb.toString().trim(); - - tcTrim = tcTrim.replaceAll("\r", ""); - sbTrim = sbTrim.replaceAll("\r", ""); - - log.info("tcTrim : {} ", tcTrim); - log.info("sbTrim : {} ", sbTrim); - - log.info("비교 결과 : {}" , tcTrim.equals(sbTrim)); - - if (!tcTrim.equals(sbTrim)) { - msg = "틀렸습니다"; - wrongTC = testCase.get(tc).getTid(); - isError = true; - break; - } - - log.info("errorReader.readLine() : {}", errorReader.readLine()); - log.info("ProcessExitValue : {}", process.exitValue()); - - } - - String timeResult; - - // 에러 발생 시 시간은 없음 - if (isError) { - result.setSolve(false); - timeResult = null; - - } else { - timeSum *= 1000; - timeSum /= testCase.size(); - timeSum = Math.floor(timeSum); - timeResult = (int)timeSum + ""; - } - - result.setMsg(msg); - result.setSolve(!isError); - result.setTime(timeResult); - result.setWrongTestCaseNo(wrongTC); - - File dirFile = new File(path); - File javaFile = new File(path, "Solution.java"); - - // 결과 반영 했으면 디렉토리 삭제하기 - // 내부 파일부터 삭제하고 디렉토리 삭제 - javaFile.delete(); - dirFile.delete(); - - return result; - } -} diff --git a/back-end/judge_java/src/main/resources/application.properties b/back-end/judge_java/src/main/resources/application.properties deleted file mode 100644 index d21dc5f1..00000000 --- a/back-end/judge_java/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -# spring.datasource. ? ?? ?? ????. -server.servlet.context-path=/java -server.port=8080 - -spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver -spring.datasource.hikari.jdbc-url=ENC(BZivb1YebBXdnHbtZKRmFcsKFuuQD2id7f8+DeSTQV1BjBAisInx6udYyTiWvRXoJu33Dd5pyrXSQO2GRTmwn21QBFSlNLh69fLUmeUWKc1nZuLbWxfDeLsLHG7RBqKUqjdiPIxy3jIgXCoileJ6iw==) -spring.datasource.hikari.username=ENC(u2pZ0ldKEDL6po+p2UuafA==) -spring.datasource.hikari.password=ENC(GZ8loB1io9uhSlw1ko8OliT/qrwYkIYo) -spring.datasource.hikari.pool-name=Hikari Connection Pool -# hikariCP property setting -spring.datasource.hikari.maximum-pool-size=50 -spring.datasource.hikari.minimum-idle=50 -spring.datasource.hikari.connection-timeout=5000 -spring.datasource.hikari.connection-init-sql=SELECT 1 -spring.datasource.hikari.idle-timeout=600000 -spring.datasource.hikari.max-lifetime=1800000 -spring.datasource.hikari.auto-commit=true - -logging.level.com.codearena.judge=debug diff --git a/back-end/judge_java/src/main/resources/mapper/Judge.xml b/back-end/judge_java/src/main/resources/mapper/Judge.xml deleted file mode 100644 index 79b9e6c4..00000000 --- a/back-end/judge_java/src/main/resources/mapper/Judge.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - update ps_submit - set submit_status=#{msg}, time_complexity=#{time}, tid=#{wrongTestCaseNo} - where submit_no=#{submitNo}; - - - - update arena_submit_status - set submit_status=#{msg}, time_complexity=#{time} - where submit_no=#{submitNo}; - - - - - \ No newline at end of file diff --git a/back-end/judge_java/src/test/java/com/codearena/judge/JudgeApplicationTests.java b/back-end/judge_java/src/test/java/com/codearena/judge/JudgeApplicationTests.java deleted file mode 100644 index b49b1eed..00000000 --- a/back-end/judge_java/src/test/java/com/codearena/judge/JudgeApplicationTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -class JudgeApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/back-end/judge_python/.gitignore b/back-end/judge_python/.gitignore deleted file mode 100644 index e48b6be6..00000000 --- a/back-end/judge_python/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -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/ \ No newline at end of file diff --git a/back-end/judge_python/Dockerfile b/back-end/judge_python/Dockerfile deleted file mode 100644 index ab687761..00000000 --- a/back-end/judge_python/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM openjdk:17-jdk-alpine -RUN apk update && apk add python3 - -# FROM : 이미지 레이어의 최상단, alpine리눅스에 jdk 17을 사용한단 의미 - -WORKDIR /app -# WORKDIR : 스프링 부트 컨테이너 OS내에 어떤 디렉토리에서 jar을 실행 할 것인지 - -ARG JAR_FILE=build/libs/judge-0.0.1-SNAPSHOT.jar -# ARG : 변수지정, 변수에 적혀진 의미는 빌드 결과물 위치 - -COPY ${JAR_FILE} test.jar -# Auto Exctraction으로 압축된 파일을 해제하여 test.jar에 그 내용을 복사, 결국 스프링부트를 실행하는 컨테이너 내에는 test.jar가 있게 됨 - -ENTRYPOINT ["java", "-jar","test.jar","--encryptor.key=${ENV_KEY}"] -# ENTRYPOINT : 해당 컨테이너 시작할때 무조건 실행할 명령어 지정 \ No newline at end of file diff --git a/back-end/judge_python/build.gradle b/back-end/judge_python/build.gradle deleted file mode 100644 index 269db893..00000000 --- a/back-end/judge_python/build.gradle +++ /dev/null @@ -1,45 +0,0 @@ -plugins { - id 'java' - id 'org.springframework.boot' version '3.2.2' - id 'io.spring.dependency-management' version '1.1.4' -} - -group = 'com.codearena' -version = '0.0.1-SNAPSHOT' - -java { - sourceCompatibility = '17' -} - -configurations { - compileOnly { - extendsFrom annotationProcessor - } -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - developmentOnly 'org.springframework.boot:spring-boot-devtools' - compileOnly 'org.projectlombok:lombok' - annotationProcessor 'org.projectlombok:lombok' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - // mysql connector j - implementation group: 'com.mysql', name: 'mysql-connector-j', version: '8.0.33' - // https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter - implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '3.0.3' - //jasypt - implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' - //Swagger - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' - // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '3.2.2' - -} - -tasks.named('test') { - useJUnitPlatform() -} diff --git a/back-end/judge_python/gradle/wrapper/gradle-wrapper.jar b/back-end/judge_python/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/back-end/judge_python/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/back-end/judge_python/gradle/wrapper/gradle-wrapper.properties b/back-end/judge_python/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1af9e093..00000000 --- a/back-end/judge_python/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/back-end/judge_python/gradlew b/back-end/judge_python/gradlew deleted file mode 100644 index 1aa94a42..00000000 --- a/back-end/judge_python/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/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/subprojects/plugins/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/back-end/judge_python/gradlew.bat b/back-end/judge_python/gradlew.bat deleted file mode 100644 index 93e3f59f..00000000 --- a/back-end/judge_python/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@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. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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/back-end/judge_python/settings.gradle b/back-end/judge_python/settings.gradle deleted file mode 100644 index 2264abe1..00000000 --- a/back-end/judge_python/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'judge' diff --git a/back-end/judge_python/src/main/java/com/codearena/JudgeApplication.java b/back-end/judge_python/src/main/java/com/codearena/JudgeApplication.java deleted file mode 100644 index 64b3c4ea..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/JudgeApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.codearena; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class JudgeApplication { - - public static void main(String[] args) { - SpringApplication.run(JudgeApplication.class, args); - } - -} diff --git a/back-end/judge_python/src/main/java/com/codearena/config/DataBaseConfiguration.java b/back-end/judge_python/src/main/java/com/codearena/config/DataBaseConfiguration.java deleted file mode 100644 index 62f50172..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/config/DataBaseConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.codearena.config; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.SqlSessionTemplate; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -import javax.sql.DataSource; - -@Configuration -@PropertySource("classpath:/application.properties") -@MapperScan(basePackages = {"com.codearena.*.mapper"}) -public class DataBaseConfiguration{ - - final ApplicationContext applicationContext; - // mapper.xml 위치를 Resource객체 로 들고오기 위해 - - public DataBaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - // ApplicationContext이 Bean을 관리하는 역할을 수행하고 - // SpringBootApplication이 실행될 때 @Configuration 어노테이션이 붙은 java파일을 설정정보로 등록한다. - // 이 때 @Bean으로 등록된 메서드들을 기반으로 빈 목록을 생성한다. - @ConfigurationProperties(prefix = "spring.datasource.hikari") - public HikariConfig hikariConfig() { - // application.properties 파일에서 spring.datasource.hikari로 시작하는 설정 값들을 가져와 Hikari 설정 객체를 반환한다. - return new HikariConfig(); - } - - @Bean - public DataSource dataSource() { - // HikariDataSource를 사용하기 위해 Hikari 설정 객체를 생성자로 넣은 HikariDataSource 객체 반환 - return new HikariDataSource(hikariConfig()); - } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { - // SqlSessionFactory는 Mybatis-spring 때 처럼 SqlSessionFactoryBean을 통해 생성되는데 - // 각종 typeAliase(DTO), mapperLocation(xml위치), DB접속정보(datasource)를 property를 통해 추가한다. - // 즉 setter를 통해 추가된다. - - SqlSessionFactoryBean session = new SqlSessionFactoryBean(); - session.setDataSource(dataSource); - session.setMapperLocations(applicationContext.getResources("classpath:mapper/**/*.xml")); - session.setTypeAliasesPackage("com.codearena.*.dto"); - return session.getObject(); - } - - @Bean - public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { - // SqlSessionTemplate은 SqlSession인터페이스 타입의 객체이며 - // 결국 SqlSessionFactory의 각종 설정 정보를 통해 만들어지므로 생성자로 넣게 된다. - return new SqlSessionTemplate(sqlSessionFactory); - } -} diff --git a/back-end/judge_python/src/main/java/com/codearena/config/JasyptConfig.java b/back-end/judge_python/src/main/java/com/codearena/config/JasyptConfig.java deleted file mode 100644 index 880ccd23..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/config/JasyptConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.codearena.config; - - -import org.jasypt.encryption.StringEncryptor; -import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class JasyptConfig { - - @Value("${encryptor.key}") - String KEY; - - private static final String ALGORITHM = "PBEWithMD5AndDES"; - - @Bean(name = "jasyptStringEncryptor") - public StringEncryptor stringEncryptor() { - PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); - SimpleStringPBEConfig config = new SimpleStringPBEConfig(); - - config.setPassword(KEY); //암호화 시 사용할 키 -> 이 키를 가지고 암호화 복호화 진행 - config.setAlgorithm(ALGORITHM); //사용할 알고리즘 - config.setKeyObtentionIterations("1000"); //반복할 해싱 회수 - config.setPoolSize("1"); //pool 크기 - config.setProviderName("SunJCE"); //사용할 암호화 라이브러리 - config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); //salt 생성 클래스 - config.setStringOutputType("base64"); //인코딩 방식 - encryptor.setConfig(config); //설정 주입 - - return encryptor; - - } -} diff --git a/back-end/judge_python/src/main/java/com/codearena/config/SwaggerConfig.java b/back-end/judge_python/src/main/java/com/codearena/config/SwaggerConfig.java deleted file mode 100644 index 74668ba0..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/config/SwaggerConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.codearena.config; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration // 스프링 실행시 설정파일 읽어드리기 위한 어노테이션 -public class SwaggerConfig { - - @Bean - public OpenAPI openAPI() { - return new OpenAPI() - .components(new Components()) - .info(apiInfo()); - } - - private Info apiInfo() { - return new Info() - .title("CodeArena Swagger") - .description("CodeArena 채점 서버에 대한 API") - .version("1.0.0"); - } -} diff --git a/back-end/judge_python/src/main/java/com/codearena/config/WebMvcConfiguration.java b/back-end/judge_python/src/main/java/com/codearena/config/WebMvcConfiguration.java deleted file mode 100644 index dbb8fbee..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/config/WebMvcConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.codearena.config; - -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@RequiredArgsConstructor -public class WebMvcConfiguration implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry - .addMapping("/**") -// .allowedOrigins("http://192.168.0.29:3000") - .allowedOriginPatterns("*") -// .allowedOrigins("http://localhost:5173", "http://localhost:5174") - .allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), - HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(), - HttpMethod.PATCH.name()) -// .allowedHeaders("Authorization") -// .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD") - .allowCredentials(true) - .exposedHeaders("Authorization") - .maxAge(1800); // Pre-flight Caching - } - -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/controller/JudgeController.java b/back-end/judge_python/src/main/java/com/codearena/judge/controller/JudgeController.java deleted file mode 100644 index 4f4ca7be..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/controller/JudgeController.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.codearena.judge.controller; - -import com.codearena.judge.dto.*; -import com.codearena.judge.service.JudgeService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@Slf4j -@RequiredArgsConstructor -@RequestMapping("/judge") -public class JudgeController { - - private final JudgeService judgeService; - - // 검증용 로직 - // 코드, 테케 필요 - @PostMapping("/validation") - public ResponseEntity validationCheck(@RequestBody JudgeValidationCheckDto judgeValidationCheckDto) { - return new ResponseEntity(judgeService.validationCheck(judgeValidationCheckDto), HttpStatus.OK); - } - @PostMapping("/arena") - public ResponseEntity judgeArena(@RequestBody JudgeArenaDto judgeArenaDto) { - return new ResponseEntity(judgeService.judgeArena(judgeArenaDto), HttpStatus.OK); - } - @PostMapping("/normal") - public ResponseEntity judgeNormal(@RequestBody JudgeNormalDto judgeNormalDto) { - return new ResponseEntity(judgeService.judgeNormal(judgeNormalDto), HttpStatus.OK); - } - @PostMapping("/example") - public ResponseEntity judgeExample(@RequestBody JudgeExampleDto judgeExampleDto) { - return new ResponseEntity(judgeService.judgeExample(judgeExampleDto), HttpStatus.OK); - } - -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java deleted file mode 100644 index 5d803db7..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeArenaDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeArenaDto { - private String submitNo; - private String problemId; - private String code; - private String gameType; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java deleted file mode 100644 index 71fe4f19..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeExampleDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeExampleDto { - private String code; - private String problemId; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java deleted file mode 100644 index 307725cb..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeNormalDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeNormalDto { - private String submitNo; - private String problemId; - private String code; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java deleted file mode 100644 index a69de64a..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeProblemInfoDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class JudgeProblemInfoDto { - private Long problemTime; - private String problemMem; - private List testCaseList; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeResultDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeResultDto.java deleted file mode 100644 index 6b281325..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeResultDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeResultDto { - private String status; - private String msg; - private Object data; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java deleted file mode 100644 index 1851c156..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeValidateResultDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -@Data -public class JudgeValidateResultDto { - private boolean isSolve; - private String submitNo; - private String msg; - private String time; - private String wrongTestCaseNo; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java deleted file mode 100644 index fe0cb116..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/JudgeValidationCheckDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class JudgeValidationCheckDto { - private String problemValidationCode; - private String problemExInput; - private String problemExOutput; - private String problemTime; - private List testCase; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/dto/TestCaseDto.java b/back-end/judge_python/src/main/java/com/codearena/judge/dto/TestCaseDto.java deleted file mode 100644 index a7d0cecd..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/dto/TestCaseDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -public class TestCaseDto { - private String input; - private String output; - private String tid; - private String problemTime; -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/mapper/JudgeMapper.java b/back-end/judge_python/src/main/java/com/codearena/judge/mapper/JudgeMapper.java deleted file mode 100644 index f0f6054a..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/mapper/JudgeMapper.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.codearena.judge.mapper; - -import com.codearena.judge.dto.*; -import org.apache.ibatis.annotations.Mapper; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -@Mapper -public interface JudgeMapper { - void insertProblem(JudgeValidationCheckDto userInput) throws SQLException; - JudgeProblemInfoDto getProblemInfo(String problemId) throws SQLException; - List getTestCase(String problemId) throws SQLException; - void updatePsSubmit(JudgeValidateResultDto judgeValidateResultDto) throws SQLException; - void updateArenaSubmit(JudgeValidateResultDto judgeValidateResultDto) throws SQLException; - TestCaseDto getExTestCase(String problemId) throws SQLException; - -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/service/JudgeService.java b/back-end/judge_python/src/main/java/com/codearena/judge/service/JudgeService.java deleted file mode 100644 index 8fb6292a..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/service/JudgeService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.codearena.judge.service; - -import com.codearena.judge.dto.*; - -public interface JudgeService { - JudgeResultDto validationCheck(JudgeValidationCheckDto judgeValidationCheckDto); - JudgeResultDto judgeArena(JudgeArenaDto judgeArenaDto); - JudgeResultDto judgeNormal(JudgeNormalDto judgeNormalDto); - JudgeResultDto judgeExample(JudgeExampleDto judgeExampleDto); -} diff --git a/back-end/judge_python/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java b/back-end/judge_python/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java deleted file mode 100644 index ab8b98e2..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/judge/service/JudgeServiceImpl.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.codearena.judge.service; - -import com.codearena.judge.dto.*; -import com.codearena.judge.mapper.JudgeMapper; -import com.codearena.util.JudgeUtil; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Service -@Slf4j -@RequiredArgsConstructor -public class JudgeServiceImpl implements JudgeService{ - - private final JudgeMapper mapper; - private final JudgeUtil judgeUtil; - - @Override - public JudgeResultDto validationCheck(JudgeValidationCheckDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("문제 유효성 검사 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = new JudgeValidateResultDto(); - - log.info("{}", userInput.getProblemValidationCode()); - - // 시스템 콜 감지 - if(judgeUtil.checkSystemCallInCode(userInput.getProblemValidationCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - return judgeResultDto; - } - - try { - // problemExInput, Output 를 테스트케이스에 포함시킴 - List testCase = userInput.getTestCase(); - TestCaseDto exTestCase = new TestCaseDto(); - exTestCase.setInput(userInput.getProblemExInput().replaceAll("\r", "")); - exTestCase.setOutput(userInput.getProblemExOutput().replaceAll("\r", "")); - - testCase.add(exTestCase); - - for (int i = 0 ; i < testCase.size() ; i ++) { - String str = testCase.get(i).getOutput().trim(); - testCase.get(i).setOutput(str); - } - // 테케 내용들 로그 출력 - for (int tc = 0; tc < testCase.size(); tc++) { - log.info("{}", testCase.get(tc)); - } - - long timeLimit = Long.parseLong(userInput.getProblemTime()); - - String path = UUID.randomUUID().toString(); - - String cmd = "python3 ./" + path + "/Solution.py"; - log.info("CMD : {}", cmd); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getProblemValidationCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, testCase, timeLimit, path); - log.info("[validationCheck] judgeValidationResult : {}" , result); - - } catch (Exception e) { - log.debug("[validationCheck] Exception : {}" , e); - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeArena(JudgeArenaDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("일반 문제 채점 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = null; - - // 시스템 콜 체크 - if(judgeUtil.checkSystemCallInCode(userInput.getCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - judgeResultDto.setData(null); - return judgeResultDto; - } - - try { - // 문제 정보 가져오기 - JudgeProblemInfoDto problemInfo = judgeUtil.getProblemInfo(userInput.getProblemId()); - - String path = UUID.randomUUID().toString(); - - String cmd = "python3 ./" + path + "/Solution.py"; - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - result = judgeUtil.validate(cmd, problemInfo.getTestCaseList(), problemInfo.getProblemTime(), path); - - log.info("[arena] judgeValidationResult : {}" , result); - - result.setSubmitNo(userInput.getSubmitNo()); - - // 효율전이면 - if("1".equals(userInput.getGameType())) - mapper.updateArenaSubmit(result); - - } catch (Exception e) { - log.debug("[arena] Exception : {}", e); - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeNormal(JudgeNormalDto userInput) { - - JudgeResultDto judgeResultDto = new JudgeResultDto(); - - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("일반 문제 채점 완료"); - judgeResultDto.setData(null); - - JudgeValidateResultDto result = null; - -// 시스템 콜 체크 - if(judgeUtil.checkSystemCallInCode(userInput.getCode())) { - judgeResultDto.setStatus("404"); - judgeResultDto.setMsg("코드 내 시스템 콜 감지"); - judgeResultDto.setData(null); - return judgeResultDto; - } - - try { - // 문제 정보 가져오기 - JudgeProblemInfoDto problemInfo = judgeUtil.getProblemInfo(userInput.getProblemId()); - - String path = UUID.randomUUID().toString(); - - String cmd = "python3 ./" + path + "/Solution.py"; - - log.info("[normal] python debug cmd : {}", cmd); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.py) - judgeUtil.createCodeFile(userInput.getCode(), path); - - // 코드 검증하기 - result = judgeUtil.validate(cmd, problemInfo.getTestCaseList(), problemInfo.getProblemTime(), path); - log.info("[normal] judgeValidationResult : {}" , result); - - result.setSubmitNo(userInput.getSubmitNo()); - log.info("userInput : {}" , userInput); - log.info("result : {}" , result); - mapper.updatePsSubmit(result); - - } catch (Exception e) { - log.debug("Exception : {}", e); - - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - } - - judgeResultDto.setData(result); - - return judgeResultDto; - } - - @Override - public JudgeResultDto judgeExample(JudgeExampleDto userInput) { - JudgeResultDto judgeResultDto = new JudgeResultDto(); - judgeResultDto.setStatus("200"); - judgeResultDto.setMsg("예제 채점 성공"); - judgeResultDto.setData(null); - - try { - TestCaseDto exTestCase = mapper.getExTestCase(userInput.getProblemId()); - - exTestCase.setInput(exTestCase.getInput().replaceAll("\r", "")); - exTestCase.setOutput(exTestCase.getInput().replaceAll("\r", "")); - - String ExInputStr = exTestCase.getInput().trim(); - exTestCase.setInput(ExInputStr); - - String ExOutputStr = exTestCase.getOutput().trim(); - exTestCase.setOutput(ExOutputStr); - - long timeLimit = Long.parseLong(exTestCase.getProblemTime()); - - String path = UUID.randomUUID().toString(); - - String cmd = "python3 ./" + path + "/Solution.py"; - log.info("CMD : {}", cmd); - - List exTestCaseList = new ArrayList<>(); - exTestCaseList.add(exTestCase); - - // 폴더 생성하기 - judgeUtil.createFolder(path); - // 코드 파일 생성하기 (solution.java) - judgeUtil.createCodeFile(userInput.getCode(), path); - // 코드 검증하기 - JudgeValidateResultDto result = judgeUtil.validate(cmd, exTestCaseList, timeLimit, path); - log.info("[validationCheck] judgeValidationResult : {}" , result); - - } catch (Exception e) { - judgeResultDto.setStatus("500"); - judgeResultDto.setMsg("서버 내부 에러"); - log.debug("[JudgeExample] : {} ", e); - } - - return judgeResultDto; - } -} diff --git a/back-end/judge_python/src/main/java/com/codearena/util/JudgeUtil.java b/back-end/judge_python/src/main/java/com/codearena/util/JudgeUtil.java deleted file mode 100644 index 6b10416f..00000000 --- a/back-end/judge_python/src/main/java/com/codearena/util/JudgeUtil.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.codearena.util; - -import com.codearena.judge.dto.JudgeProblemInfoDto; -import com.codearena.judge.dto.JudgeValidateResultDto; -import com.codearena.judge.dto.TestCaseDto; -import com.codearena.judge.mapper.JudgeMapper; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Configuration; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Configuration -@Slf4j -@RequiredArgsConstructor -public class JudgeUtil { - - private final JudgeMapper mapper; - - public void createFolder(String path) { - // 폴더 생성 - File Folder = new File(path); - - // 해당 디렉토리가 없을경우 디렉토리를 생성합니다. - if (!Folder.exists()) { - try{ - log.info("폴더가 생성되었습니다. {}" , Folder.mkdir()); - } - catch(Exception e){ - log.debug("createFolder Exception : {}", e); - } - }else { - log.debug("Exception : 이미 폴더가 생성되어 있습니다"); - } - } - - public void createCodeFile(String code, String path) throws IOException { - File file = new File(path, "Solution.py"); - - log.info("파일 생성 중. {}"); - log.info("path : {}" + path); - - if(file.createNewFile()); - - FileWriter fw = new FileWriter(file); - log.info("code : {}", code); - fw.write(code); - fw.close(); - - } - - public boolean checkSystemCallInCode(String code) { - Pattern pattern = Pattern.compile("(? testCaseList = new ArrayList<>(); - - try { - judgeProblemInfoDto = mapper.getProblemInfo(problemId); - testCaseList = mapper.getTestCase(problemId); - judgeProblemInfoDto.setTestCaseList(testCaseList); - } catch (Exception e) { - log.debug("Exception : {} ", e); - } - - return judgeProblemInfoDto; - } - - /** - * - * @param cmd : 런타임에서 실행할 명령 - * @param testCase : 채점 테스트 케이스 - * @param timeLimit : 시간제한 - * @param path : 디렉토리 생성 경로 - * @return JudgeValidateResultDto - * @throws Exception - */ - public JudgeValidateResultDto validate(String cmd, - List testCase, - Long timeLimit, - String path) throws Exception { - - // 런타임 생성하기 - Runtime runtime = Runtime.getRuntime(); - - JudgeValidateResultDto result = new JudgeValidateResultDto(); - - result.setSolve(true); - // 실행 결과 담기 - String msg = "맞았습니다."; - // 시간의 총 합. - double timeSum = 0.0; - // 에러가 발생 했는지 - boolean isError = false; - - String wrongTC = null; - - // TC 불러왔으면 검사하는 로직 수행하기 - for (int tc = 0; tc < testCase.size(); tc++) { - // 컴파일 하고 실행시키기 - Process process = runtime.exec(cmd); - - // BufferedWriter로 Output 스트림에 실행 결과를 담기 - // 실행 결과를 - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); - bw.write(testCase.get(tc).getInput()); - bw.flush(); - bw.close(); - - double beforeTime = System.currentTimeMillis(); - - if (!process.waitFor(timeLimit + 4000 + 1000, TimeUnit.MILLISECONDS)) { - msg = "시간 초과"; - wrongTC = testCase.get(tc).getTid(); - isError = true; - break; - } - - double afterTime = System.currentTimeMillis(); - - BufferedReader bf = new BufferedReader(new InputStreamReader(process.getInputStream(), "MS949")); - StringBuilder sb = new StringBuilder(); - String str = null; - - while((str = bf.readLine()) != null) { - sb.append(str).append("\n"); - } - - timeSum += (afterTime - beforeTime) / 1000; - - log.info("tc : {} 시간 측정 결과 : {}\n", tc, (afterTime-beforeTime)/1000); - - BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); - log.info("processExitValue : {} (0 = 정상작동)", process.exitValue()); - - if (process.exitValue() != 0) { - String error = errorReader.readLine(); - log.info("errorMsg : {}", error); - - String[] frags = error.split(" "); - - isError = true; - wrongTC = testCase.get(tc).getTid(); - - msg = "컴파일 에러"; - - switch (frags[0]) { - case "warning": - log.debug("error : {}", error); - msg = "런타임 에러"; - break; - case "error:": - log.debug("error : {}", error); - msg = "컴파일 에러"; - break; - } - break; - } - - String tcTrim = testCase.get(tc).getOutput(); - String sbTrim = sb.toString().trim(); - - tcTrim = tcTrim.replaceAll("\r", ""); - sbTrim = sbTrim.replaceAll("\r", ""); - - log.info("비교 결과 : {}" , tcTrim.equals(sbTrim)); - - if (!tcTrim.equals(sbTrim)) { - msg = "틀렸습니다"; - wrongTC = testCase.get(tc).getTid(); - isError = true; - break; - } - - log.info("errorReader.readLine() : {}", errorReader.readLine()); - log.info("ProcessExitValue : {}", process.exitValue()); - - // 결과 값 출력 & 저장 - log.info("str : {}", str); - } - - String timeResult; - - // 에러 발생 시 시간은 없음 - if (isError) { - result.setSolve(false); - timeResult = null; - - } else { - timeSum *= 1000; - timeSum /= testCase.size(); - timeSum = Math.floor(timeSum); - timeResult = (int)timeSum + ""; - } - - result.setMsg(msg); - result.setSolve(!isError); - result.setTime(timeResult); - result.setWrongTestCaseNo(wrongTC); - - File dirFile = new File(path); - File pythonFile = new File(path, "Solution.py"); - - // 결과 반영 했으면 디렉토리 삭제하기 - // 내부 파일부터 삭제하고 디렉토리 삭제 - pythonFile.delete(); - dirFile.delete(); - - return result; - } -} diff --git a/back-end/judge_python/src/main/resources/application.properties b/back-end/judge_python/src/main/resources/application.properties deleted file mode 100644 index 7139c4ff..00000000 --- a/back-end/judge_python/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -# spring.datasource. ? ?? ?? ????. -server.servlet.context-path=/python -server.port=8080 - -spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver -spring.datasource.hikari.jdbc-url=ENC(BZivb1YebBXdnHbtZKRmFcsKFuuQD2id7f8+DeSTQV1BjBAisInx6udYyTiWvRXoJu33Dd5pyrXSQO2GRTmwn21QBFSlNLh69fLUmeUWKc1nZuLbWxfDeLsLHG7RBqKUqjdiPIxy3jIgXCoileJ6iw==) -spring.datasource.hikari.username=ENC(u2pZ0ldKEDL6po+p2UuafA==) -spring.datasource.hikari.password=ENC(GZ8loB1io9uhSlw1ko8OliT/qrwYkIYo) -spring.datasource.hikari.pool-name=Hikari Connection Pool -# hikariCP property setting -spring.datasource.hikari.maximum-pool-size=50 -spring.datasource.hikari.minimum-idle=50 -spring.datasource.hikari.connection-timeout=5000 -spring.datasource.hikari.connection-init-sql=SELECT 1 -spring.datasource.hikari.idle-timeout=600000 -spring.datasource.hikari.max-lifetime=1800000 -spring.datasource.hikari.auto-commit=true - -logging.level.com.codearena.judge=debug diff --git a/back-end/judge_python/src/main/resources/mapper/Judge.xml b/back-end/judge_python/src/main/resources/mapper/Judge.xml deleted file mode 100644 index 79b9e6c4..00000000 --- a/back-end/judge_python/src/main/resources/mapper/Judge.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - update ps_submit - set submit_status=#{msg}, time_complexity=#{time}, tid=#{wrongTestCaseNo} - where submit_no=#{submitNo}; - - - - update arena_submit_status - set submit_status=#{msg}, time_complexity=#{time} - where submit_no=#{submitNo}; - - - - - \ No newline at end of file diff --git a/back-end/judge_python/src/test/java/com/codearena/judge/JudgeApplicationTests.java b/back-end/judge_python/src/test/java/com/codearena/judge/JudgeApplicationTests.java deleted file mode 100644 index b49b1eed..00000000 --- a/back-end/judge_python/src/test/java/com/codearena/judge/JudgeApplicationTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.codearena.judge; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -class JudgeApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/back-end/match/.gitignore b/back-end/match/.gitignore deleted file mode 100644 index c2065bc2..00000000 --- a/back-end/match/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -HELP.md -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/**/build/ -!**/src/test/**/build/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr -out/ -!**/src/main/**/out/ -!**/src/test/**/out/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ diff --git a/back-end/match/Dockerfile b/back-end/match/Dockerfile deleted file mode 100644 index 4d4aeb43..00000000 --- a/back-end/match/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM openjdk:17-jdk-alpine -# FROM : 이미지 레이어의 최상단, alpine리눅스에 jdk 17을 사용한단 의미 - -WORKDIR /app -# WORKDIR : 스프링 부트 컨테이너 OS내에 어떤 디렉토리에서 jar을 실행 할 것인지 - -ARG JAR_FILE=build/libs/match-0.0.1-SNAPSHOT.jar -# ARG : 변수지정, 변수에 적혀진 의미는 빌드 결과물 위치 - -COPY ${JAR_FILE} test.jar -# Auto Exctraction으로 압축된 파일을 해제하여 test.jar에 그 내용을 복사, 결국 스프링부트를 실행하는 컨테이너 내에는 test.jar가 있게 됨 - -ENTRYPOINT ["java", "-jar","test.jar","--encryptor.key=${ENV_KEY}"] -# ENTRYPOINT : 해당 컨테이너 시작할때 무조건 실행할 명령어 지정 \ No newline at end of file diff --git a/back-end/match/build.gradle b/back-end/match/build.gradle deleted file mode 100644 index e8c761b3..00000000 --- a/back-end/match/build.gradle +++ /dev/null @@ -1,34 +0,0 @@ -plugins { - id 'java' - id 'org.springframework.boot' version '3.2.2' - id 'io.spring.dependency-management' version '1.1.4' -} - -group = 'com.ssafy' -version = '0.0.1-SNAPSHOT' - -java { - sourceCompatibility = '17' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter-data-redis' - implementation 'org.springframework.boot:spring-boot-starter-web' - compileOnly 'org.projectlombok:lombok:1.18.30' - annotationProcessor 'org.projectlombok:lombok:1.18.30' - implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux', version: '3.2.2' - testCompileOnly 'org.projectlombok:lombok:1.18.30' - testAnnotationProcessor 'org.projectlombok:lombok:1.18.30' - developmentOnly 'org.springframework.boot:spring-boot-devtools' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - implementation 'org.springframework.boot:spring-boot-starter-websocket' - implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' //jasypt -} - -tasks.named('test') { - useJUnitPlatform() -} diff --git a/back-end/match/gradle/wrapper/gradle-wrapper.jar b/back-end/match/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/back-end/match/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/back-end/match/gradle/wrapper/gradle-wrapper.properties b/back-end/match/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1af9e093..00000000 --- a/back-end/match/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/back-end/match/gradlew b/back-end/match/gradlew deleted file mode 100644 index 1aa94a42..00000000 --- a/back-end/match/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/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/subprojects/plugins/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/back-end/match/gradlew.bat b/back-end/match/gradlew.bat deleted file mode 100644 index 93e3f59f..00000000 --- a/back-end/match/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@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. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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/back-end/match/settings.gradle b/back-end/match/settings.gradle deleted file mode 100644 index 5cba13bf..00000000 --- a/back-end/match/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'match' diff --git a/back-end/match/src/main/java/com/ssafy/match/CommonMsg.java b/back-end/match/src/main/java/com/ssafy/match/CommonMsg.java deleted file mode 100644 index fd8a010f..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/CommonMsg.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.match; - - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Getter -@Setter -@ToString -public class CommonMsg { - String msg; - String matchId; -} diff --git a/back-end/match/src/main/java/com/ssafy/match/ExpressionException.java b/back-end/match/src/main/java/com/ssafy/match/ExpressionException.java deleted file mode 100644 index 64e0dc35..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/ExpressionException.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ssafy.match; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.web.socket.TextMessage; - -public class ExpressionException extends NullPointerException{ - public ExpressionException() { - super(); - } - - public ExpressionException(String s) { - super(s); - } - - static final ObjectMapper objectMapper = new ObjectMapper(); - static TextMessage TEXT_MESSAGE ; - - static{ - MessageDto messageDto = new MessageDto(); - messageDto.setType(MessageDto.MessageType.EXCEPTION); - messageDto.setContent("null 데이터가 들어왔습니다. 데이터를 확인해주세요"); - try { - TEXT_MESSAGE = new TextMessage(objectMapper.writeValueAsString(messageDto)); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - } - TextMessage getTextMessage(){ - return TEXT_MESSAGE; - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/JasyptConfig.java b/back-end/match/src/main/java/com/ssafy/match/JasyptConfig.java deleted file mode 100644 index ee647bb3..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/JasyptConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ssafy.match; - - -import org.jasypt.encryption.StringEncryptor; -import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; -import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class JasyptConfig { - - @Value("${encryptor.key}") - String KEY; - - private static final String ALGORITHM = "PBEWithMD5AndDES"; - - @Bean(name = "jasyptStringEncryptor") - public StringEncryptor stringEncryptor() { - PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); - SimpleStringPBEConfig config = new SimpleStringPBEConfig(); - - config.setPassword(KEY); //암호화 시 사용할 키 -> 이 키를 가지고 암호화 복호화 진행 - config.setAlgorithm(ALGORITHM); //사용할 알고리즘 - config.setKeyObtentionIterations("1000"); //반복할 해싱 회수 - config.setPoolSize("1"); //pool 크기 - config.setProviderName("SunJCE"); //사용할 암호화 라이브러리 - config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); //salt 생성 클래스 - config.setStringOutputType("base64"); //인코딩 방식 - encryptor.setConfig(config); //설정 주입 - - return encryptor; - - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MatchApplication.java b/back-end/match/src/main/java/com/ssafy/match/MatchApplication.java deleted file mode 100644 index 138252e6..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MatchApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ssafy.match; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MatchApplication { - - public static void main(String[] args) { - SpringApplication.run(MatchApplication.class, args); - } - -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MatchDto.java b/back-end/match/src/main/java/com/ssafy/match/MatchDto.java deleted file mode 100644 index fd44596b..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MatchDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.match; - - -import lombok.Data; - -@Data -public class MatchDto { - private String userId; - private Long enqueueTime; - private String userNickname; - private String queueKey; - private Boolean isOk; - private String matchId; -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MatchNotFoundException.java b/back-end/match/src/main/java/com/ssafy/match/MatchNotFoundException.java deleted file mode 100644 index 56163c59..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MatchNotFoundException.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ssafy.match; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.web.socket.TextMessage; - -public class MatchNotFoundException extends Exception { - static final ObjectMapper objectMapper = new ObjectMapper(); - static TextMessage TEXT_MESSAGE ; - - static{ - MessageDto messageDto = new MessageDto(); - messageDto.setType(MessageDto.MessageType.EXCEPTION); - messageDto.setContent("매치 Not Found Exception"); - try { - TEXT_MESSAGE = new TextMessage(objectMapper.writeValueAsString(messageDto)); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - } - TextMessage getTextMessage(){ - return TEXT_MESSAGE; - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MatchPlayerNotFoundException.java b/back-end/match/src/main/java/com/ssafy/match/MatchPlayerNotFoundException.java deleted file mode 100644 index 88ce1dd8..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MatchPlayerNotFoundException.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ssafy.match; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.web.socket.TextMessage; - -public class MatchPlayerNotFoundException extends Exception { - static final ObjectMapper objectMapper = new ObjectMapper(); - static TextMessage TEXT_MESSAGE ; - static MessageDto msg = new MessageDto(); - static{ - MessageDto messageDto = new MessageDto(); - messageDto.setType(MessageDto.MessageType.EXCEPTION); - messageDto.setContent("매치메이킹 플레이어 Not Found Exception"); - try { - TEXT_MESSAGE = new TextMessage(objectMapper.writeValueAsString(messageDto)); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - } - - TextMessage getTextMessage(){ - return TEXT_MESSAGE; - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MessageDto.java b/back-end/match/src/main/java/com/ssafy/match/MessageDto.java deleted file mode 100644 index c0f290ae..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MessageDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ssafy.match; - - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Getter -@Setter -@ToString -public class MessageDto { - public enum MessageType{ - ENQUEUE, POP, YES, NO, QUERY, EXCEPTION, RESPONSE, INGAME, CONTINUE - } - private String queueKey; - private String matchId; - private MessageType type; - private String userId; - private String userNickname; - private Integer rating; - private String gameMode; - private String lang; - private String content; - private String problemId; - private String gameId; - private String viduSession; -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MyController.java b/back-end/match/src/main/java/com/ssafy/match/MyController.java deleted file mode 100644 index 2e00fcf5..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MyController.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ssafy.match; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.HashMap; -import java.util.List; - -@RestController -@RequestMapping("/redis") -public class MyController { - private MyService service; - - @Autowired - public MyController(MyService service){ - this.service = service; - } - - @PostMapping - public String getRedis(@RequestBody RedisDto redisDto){ - return service.getRedis(redisDto); - } - - @PostMapping("/match") - public HashMap> match(@RequestBody UserDto userDto){ - return service.enqueue(userDto); - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MyService.java b/back-end/match/src/main/java/com/ssafy/match/MyService.java deleted file mode 100644 index 2e4e9c9f..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MyService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ssafy.match; - -import java.util.HashMap; -import java.util.List; - -public interface MyService { - String getRedis(RedisDto redisDto); - HashMap> enqueue(UserDto userDto); -} diff --git a/back-end/match/src/main/java/com/ssafy/match/MyServiceImpl.java b/back-end/match/src/main/java/com/ssafy/match/MyServiceImpl.java deleted file mode 100644 index e68c130d..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/MyServiceImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ssafy.match; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.ValueOperations; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.util.*; -import java.util.concurrent.TimeUnit; - -@Service -public class MyServiceImpl implements MyService{ - - private RedisTemplate redisTemplate; - - private Logger logger = LoggerFactory.getLogger(MyServiceImpl.class); - - @Autowired - public MyServiceImpl(RedisTemplate redisTemplate){ - this.redisTemplate = redisTemplate; - } - - @Override - public String getRedis(RedisDto redisDto) { - ValueOperations operations = redisTemplate.opsForValue(); - String result = (String) operations.get(redisDto.getKey()); - if(!StringUtils.hasText(result)){ - operations.set(redisDto.getKey(), redisDto.getValue(), 10, TimeUnit.MINUTES); - logger.info("redis save"); - result = redisDto.getValue(); - } - return result; - } - - @Override - public HashMap> enqueue(UserDto userDto) { - logger.info("get Dto : {}", userDto); - HashMap> match = new HashMap<>(); - String key = makeKey(userDto); - logger.info("key : {}", key); - redisTemplate.opsForZSet().add(key, userDto.getUserId(), System.currentTimeMillis()); - Set lv2Set = redisTemplate.opsForZSet().range(key,0,-1); - List lv2 = new ArrayList<>(lv2Set); - return match; - } - - public String makeKey(UserDto userDto){ - StringBuilder sb = new StringBuilder(); - StringBuilder t = sb.append(userDto.getGameMode()).append("-").append(userDto.getLang()).append("-"); - int rating = userDto.getRating(); - String lv = ""; - if(rating < 1200){ - lv = "lv1"; - }else if(rating >= 1200 && rating < 1400){ - lv = "lv2"; - }else if(rating >= 1400 && rating < 1600){ - lv = "lv3"; - }else if(rating >= 1600 && rating < 1800){ - lv = "lv4"; - }else{ - lv = "lv5"; - } - t.append(lv); - return t.toString(); - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/RedisConfigure.java b/back-end/match/src/main/java/com/ssafy/match/RedisConfigure.java deleted file mode 100644 index a94db0ae..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/RedisConfigure.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ssafy.match; - - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.connection.RedisStandaloneConfiguration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -@Configuration -public class RedisConfigure { - @Value("${redis.host}") - private String host; - @Value("${redis.port}") - private int port; - @Value("${redis.password}") - private String password; - - @Bean - public RedisConnectionFactory redisConnectionFactory(){ - final RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); - redisStandaloneConfiguration.setHostName(host); - redisStandaloneConfiguration.setPort(port); - redisStandaloneConfiguration.setPassword(password); - return new LettuceConnectionFactory(redisStandaloneConfiguration); - } - - @Bean - public RedisTemplate redisTemplate(){ - RedisTemplate redisTemplate = new RedisTemplate<>(); - redisTemplate.setConnectionFactory(redisConnectionFactory()); - redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setValueSerializer(new StringRedisSerializer()); - return redisTemplate; - } - -} diff --git a/back-end/match/src/main/java/com/ssafy/match/RedisDto.java b/back-end/match/src/main/java/com/ssafy/match/RedisDto.java deleted file mode 100644 index ba7f473e..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/RedisDto.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ssafy.match; - -public class RedisDto { - private String key; - private String value; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public String toString() { - return "RedisDto{" + - "key='" + key + '\'' + - ", value='" + value + '\'' + - '}'; - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/UserDto.java b/back-end/match/src/main/java/com/ssafy/match/UserDto.java deleted file mode 100644 index ac79423b..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/UserDto.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ssafy.match; - - -public class UserDto { - - String userId; - Integer rating; - String gameMode; - - String lang; - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public Integer getRating() { - return rating; - } - - public void setRating(Integer rating) { - this.rating = rating; - } - - public String getGameMode() { - return gameMode; - } - - public void setGameMode(String gameMode) { - this.gameMode = gameMode; - } - - public String getLang() { - return lang; - } - - public void setLang(String lang) { - this.lang = lang; - } - - @Override - public String toString() { - return "UserDto{" + - "userId='" + userId + '\'' + - ", rating=" + rating + - ", gameMode='" + gameMode + '\'' + - ", lang='" + lang + '\'' + - '}'; - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/WebMvcConfiguration.java b/back-end/match/src/main/java/com/ssafy/match/WebMvcConfiguration.java deleted file mode 100644 index 8aa2bece..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/WebMvcConfiguration.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ssafy.match; - -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebMvcConfiguration implements WebMvcConfigurer { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").maxAge(1000000); - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/WebSocketConfiguration.java b/back-end/match/src/main/java/com/ssafy/match/WebSocketConfiguration.java deleted file mode 100644 index 52a56906..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/WebSocketConfiguration.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ssafy.match; - -import lombok.AllArgsConstructor; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.socket.WebSocketHandler; -import org.springframework.web.socket.config.annotation.EnableWebSocket; -import org.springframework.web.socket.config.annotation.WebSocketConfigurer; -import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; - - -@Configuration -@EnableWebSocket -@RequiredArgsConstructor -public class WebSocketConfiguration implements WebSocketConfigurer { - - private final WebSocketHandler webSocketHandler; - - @Override - public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - registry.addHandler(webSocketHandler, "/matching").setAllowedOrigins("*"); - } - - -} diff --git a/back-end/match/src/main/java/com/ssafy/match/WebSocketHandler.java b/back-end/match/src/main/java/com/ssafy/match/WebSocketHandler.java deleted file mode 100644 index 31d73bd0..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/WebSocketHandler.java +++ /dev/null @@ -1,395 +0,0 @@ -package com.ssafy.match; - -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.ZSetOperations; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Component; -import org.springframework.web.reactive.function.client.WebClient; -import org.springframework.web.socket.CloseStatus; -import org.springframework.web.socket.TextMessage; -import org.springframework.web.socket.WebSocketSession; -import org.springframework.web.socket.handler.TextWebSocketHandler; - -import java.io.IOException; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -@Component -@Slf4j -public class WebSocketHandler extends TextWebSocketHandler { - private static final ConcurrentHashMap CLIENTS = new ConcurrentHashMap<>(); - private static final HashMap userWithSessionId = new HashMap<>(); - private static final HashMap> matchMap = new HashMap<>(); - private final RedisTemplate redisTemplate; - - @Value("${gameserver.url}") - private String gameserverUrl; - - @Value("${restserver.url}") - private String restUrl; - - @Override - public void afterConnectionEstablished(WebSocketSession session) throws Exception { - log.debug("connect : {}", session.getId()); - CLIENTS.put(session.getId(), session); - log.debug("connect session obj : {}", CLIENTS.get(session.getId())); - } - - @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { - CLIENTS.remove(session.getId()); - } - @Autowired - public WebSocketHandler(RedisTemplate redisTemplate){ - this.redisTemplate = redisTemplate; - } - @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) { - try { - ObjectMapper objectMapper = new ObjectMapper(); - MessageDto receive = objectMapper.readValue(message.getPayload(), MessageDto.class); - log.debug("받은 데이터 : {}", receive); - if (receive.getType() == MessageDto.MessageType.POP) { - CLIENTS.remove(session.getId()); - redisTemplate.opsForZSet().remove(receive.getQueueKey(), receive.getUserId() + " " + receive.getUserNickname()); - session.close(); - } else if (receive.getType() == MessageDto.MessageType.ENQUEUE) { - userWithSessionId.put(receive.getUserId() + " " + receive.getUserNickname(), session.getId()); - UserDto userDto = new UserDto(); - userDto.setUserId(receive.getUserId()); - userDto.setLang(receive.getLang()); - userDto.setGameMode(receive.getGameMode()); - userDto.setRating(receive.getRating()); - String key = makeKey(userDto); - redisTemplate.opsForZSet().add(key, userDto.getUserId() + " " + receive.getUserNickname(), System.currentTimeMillis()); - log.debug("매칭큐에 등록되었습니다. key : {}", key); - MessageDto dto = makeMessage(MessageDto.MessageType.RESPONSE, receive.getGameMode(), receive.getMatchId(), receive.getUserId(), receive.getLang(), null, "매칭큐에 등록되었습니다.", key, receive.getUserNickname(), null, null, null); - session.sendMessage(new TextMessage(objectMapper.writeValueAsString(dto))); - Long size = redisTemplate.opsForZSet().zCard(key); - if (size >= 2) { - log.debug(key + "의 큐 사이즈 2개됨"); - Set> set = redisTemplate.opsForZSet().popMin(key, 2); - ArrayList> list = new ArrayList<>(set); - ZSetOperations.TypedTuple player1 = list.get(0); - ZSetOperations.TypedTuple player2 = list.get(1); - String[] player1Infos = ((String) player1.getValue()).split(" "); - String player1userId = player1Infos[0]; - String player1userNickname = player1Infos[1]; - String[] player2Infos = ((String) player2.getValue()).split(" "); - String player2userId = player2Infos[0]; - String player2userNickname = player2Infos[1]; - String player1SessionId = userWithSessionId.get(player1.getValue()); - String player2SessionId = userWithSessionId.get(player2.getValue()); - log.debug("player1 : {} sessionId :{}, player2 : {}, sessionId : {}", player1.getValue(), player1SessionId, player2.getValue(), player2SessionId); - if (player1SessionId == null && player2SessionId != null) { - WebSocketSession p2Session = CLIENTS.get(player2SessionId); - if (p2Session != null) { - redisTemplate.opsForZSet().add(key, player2.getValue(), player2.getScore()); - } - } else if (player1SessionId != null && player2SessionId == null) { - WebSocketSession p1Session = CLIENTS.get(player1SessionId); - if (p1Session != null) { - redisTemplate.opsForZSet().add(key, player1.getValue(), player1.getScore()); - } - } else if (player1SessionId != null && player2SessionId != null) { - - WebSocketSession p2Session = CLIENTS.get(player2SessionId); - WebSocketSession p1Session = CLIENTS.get(player1SessionId); - if (p2Session == null && p1Session != null) { - redisTemplate.opsForZSet().add(key, player1.getValue(), player1.getScore()); - } else if (p2Session != null && p1Session == null) { - redisTemplate.opsForZSet().add(key, player2.getValue(), player2.getScore()); - } else if (p2Session != null && p1Session != null) { - UUID uuid = UUID.randomUUID(); - HashMap match = getMatchDtoHashMap(uuid, player1, player2, key); - WebClient client = getClient(restUrl); - HashMap player1Profile = (HashMap)(client.get().uri("/profile/"+player1userId).retrieve().bodyToMono(HashMap.class).block().get("data")); - HashMap player2Profile = (HashMap)(client.get().uri("/profile/"+player2userId).retrieve().bodyToMono(HashMap.class).block().get("data")); - - String player1ImgSrc = player1Profile != null ? player1Profile.get("profileUrl") : null; - String player2ImgSrc = player2Profile != null ? player2Profile.get("profileUrl") : null; - - matchMap.put(uuid.toString(), match); - HashMap serverMsg = new HashMap<>(); - serverMsg.put("type", "QUERY"); - serverMsg.put("gameMode", receive.getGameMode()); - serverMsg.put("matchId", uuid.toString()); - serverMsg.put("userId", player1userId); - serverMsg.put("userNickname", player1userNickname); - serverMsg.put("userImgSrc", player1ImgSrc); - serverMsg.put("lang", receive.getLang()); - serverMsg.put("enemyId", player2userId); - serverMsg.put("enemyNickname", player2userNickname); - serverMsg.put("enemyImgSrc", player2ImgSrc); - serverMsg.put("queueKey", key); - log.debug("[QUERY] server send to player send msg : {}", serverMsg); - p1Session.sendMessage(new TextMessage(objectMapper.writeValueAsString(serverMsg))); - serverMsg.put("userId", player2userId); - serverMsg.put("userNickname", player2userNickname); - serverMsg.put("userImgSrc", player2ImgSrc); - serverMsg.put("enemyId", player1userId); - serverMsg.put("enemyNickname", player1userNickname); - serverMsg.put("enemyImgSrc", player1ImgSrc); - log.debug("[QUERY] server send to player send msg : {}", serverMsg); - p2Session.sendMessage(new TextMessage(objectMapper.writeValueAsString(serverMsg))); - - } - } - } - } else if (receive.getType() == MessageDto.MessageType.YES) { - String recMatchId = receive.getMatchId(); - log.debug("user : {} 가 매칭 {} 을 수락함", receive.getUserId(), receive.getMatchId()); - MessageDto msg = null; - matchValidation(session, receive); - matchMap.get(recMatchId).get(receive.getUserId() + " " + receive.getUserNickname()).setIsOk(true); - Collection players = (Collection) matchMap.get(recMatchId).values(); - int OkCount = 0; - int nullCount = 0; - MatchDto aliveUser = null; - for (MatchDto player : players) { - if (player.getIsOk() == null) { - nullCount++; - continue; - } - if (!player.getIsOk()) { - matchMap.remove(recMatchId); - - } else { - OkCount++; - aliveUser = player; - } - } - if (OkCount == 2) { - String title = ""; - boolean isFirst = true; - String userRed = ""; - String userBlue = ""; - for (MatchDto player : players) { - if (isFirst) { - title = player.getUserNickname() + " vs "; - isFirst = false; - userRed = player.getUserId(); - } else { - title += player.getUserNickname(); - userBlue = player.getUserId(); - } - - } - WebClient client = getClient(gameserverUrl); - HashMap params = new HashMap<>(); - params.put("gameId", recMatchId); - params.put("title", title); - params.put("userRed", userRed); - params.put("userBlue", userBlue); - String mode = "0"; - if (receive.getGameMode().equals("eff")) { - mode = "1"; - } - params.put("gameMode", mode); - params.put("language", receive.getLang()); - HashMap> result = client.post().uri("/chat/gameroom").contentType(MediaType.APPLICATION_JSON).bodyValue(params).retrieve().bodyToMono(HashMap.class).block(); - - // 로직 생성 - log.debug("from gameserver data : {}", result); - String gameId = result.get("data").get("gameId"); - String viduSession = result.get("data").get("viduSession"); - String problemId = result.get("data").get("problemId"); - String startTime = result.get("data").get("startTime"); - for (Map.Entry entrySet : userWithSessionId.entrySet()) { - log.debug("key : {} sessionId : {}", entrySet.getKey(), entrySet.getValue()); - } - for (Map.Entry entrySet : CLIENTS.entrySet()) { - log.debug("sessionId : {} sessionObj : {}", entrySet.getKey(), entrySet.getValue()); - } - log.debug("매치속 플레이어 수 : {}", players.size()); - HashMap serverMsg = new HashMap<>(); - serverMsg.put("type", "INGAME"); - serverMsg.put("problemId", problemId); - serverMsg.put("gameMode", receive.getGameMode()); - serverMsg.put("lang", receive.getLang()); - serverMsg.put("gameId", gameId); - serverMsg.put("viduSession", viduSession); - serverMsg.put("startTime", startTime); - Iterator playerIterator = players.iterator(); - MatchDto player1 = playerIterator.next(); - MatchDto player2 = playerIterator.next(); - client = getClient(restUrl); - HashMap player1Profile = (HashMap)(client.get().uri("/profile/"+player1.getUserId()).retrieve().bodyToMono(HashMap.class).block().get("data")); - HashMap player2Profile = (HashMap)(client.get().uri("/profile/"+player2.getUserId()).retrieve().bodyToMono(HashMap.class).block().get("data")); - String player1ImgSrc = player1Profile != null ? player1Profile.get("profileUrl") : null; - String player2ImgSrc = player2Profile != null ? player2Profile.get("profileUrl") : null; - log.debug("player1ImgSrc : {}", player1ImgSrc); - log.debug("player2ImgSrc : {}", player2ImgSrc); - - WebSocketSession player1Session = CLIENTS.get(userWithSessionId.get(player1.getUserId() +" "+player1.getUserNickname())); - WebSocketSession player2Session = CLIENTS.get(userWithSessionId.get(player2.getUserId() +" "+player2.getUserNickname())); - serverMsg.put("userId", player1.getUserId()); - serverMsg.put("userNickname", player1.getUserNickname()); - serverMsg.put("userImgSrc", player1ImgSrc); - serverMsg.put("enemyId", player2.getUserId()); - serverMsg.put("enemyNickname", player2.getUserNickname()); - serverMsg.put("enemyImgSrc", player2ImgSrc); - log.debug("[INGAME] server send to player1 message : {} ", serverMsg); - player1Session.sendMessage(new TextMessage(objectMapper.writeValueAsString(serverMsg))); - serverMsg.put("userId", player2.getUserId()); - serverMsg.put("userNickname", player2.getUserNickname()); - serverMsg.put("userImgSrc", player2ImgSrc); - serverMsg.put("enemyId", player1.getUserId()); - serverMsg.put("enemyNickname", player1.getUserNickname()); - serverMsg.put("enemyImgSrc", player1ImgSrc); - log.debug("[INGAME] server send to player2 message : {} ", serverMsg); - player2Session.sendMessage(new TextMessage(objectMapper.writeValueAsString(serverMsg))); - - } else if (OkCount == 1 && nullCount != 1) { - matchMap.remove(receive.getMatchId()); - String[] frags = aliveUser.getQueueKey().split("-"); - String mode = frags[0]; - String lang = frags[1]; - MessageDto send = makeMessage(MessageDto.MessageType.CONTINUE, mode, null, aliveUser.getUserId(), lang, null, aliveUser.getUserNickname() + "은 매칭큐에 지속됩니다.", aliveUser.getQueueKey(), aliveUser.getUserNickname(), null, null, null); - log.debug("[CONTINUE] server send to player message : {}", send); - session.sendMessage(new TextMessage(objectMapper.writeValueAsString(send))); - redisTemplate.opsForZSet().add(aliveUser.getQueueKey(), aliveUser.getUserId() + " " + aliveUser.getUserNickname(), aliveUser.getEnqueueTime()); - } - - } else if (receive.getType() == MessageDto.MessageType.NO) { - String recMatchId = receive.getMatchId(); - matchMap.get(recMatchId).get(receive.getUserId() + " " + receive.getUserNickname()).setIsOk(false); - Collection players = (Collection) matchMap.get(recMatchId).values(); - - int noCount = 0; - int yesCount = 0; - for (MatchDto player : players) { - if (player.getIsOk() == null) continue; - if (player.getIsOk()) { - WebSocketSession okPlayer = CLIENTS.get(userWithSessionId.get(player.getUserId()+" "+player.getUserNickname())); - yesCount++; - if(okPlayer!= null && okPlayer.isOpen()){ - - String[] frags = player.getQueueKey().split("-"); - String mode = frags[0]; - String lang = frags[1]; - MessageDto send = makeMessage(MessageDto.MessageType.CONTINUE, mode, null, player.getUserId(), lang, null, player.getUserNickname() + "은 매칭큐에 지속됩니다.", player.getQueueKey(), player.getUserNickname(), null, null, null); - log.debug("[CONTINUE] server send to player message : {}", send); - okPlayer.sendMessage(new TextMessage(objectMapper.writeValueAsString(send))); - redisTemplate.opsForZSet().add(player.getQueueKey(), player.getUserId() + " " + player.getUserNickname(), player.getEnqueueTime()); - } - - - } else { - noCount++; - session.close(); - } - } - - if (yesCount + noCount == 2) { - if(recMatchId !=null && matchMap.containsKey(recMatchId)){ - matchMap.remove(recMatchId); - } - } - } - - }catch(Exception e) { - log.debug("exception : {} ", e); - sendException(session, e); - } - } - private void sendException(WebSocketSession session, Exception exception){ - try{ - if(exception instanceof MatchNotFoundException){ - session.sendMessage(((MatchNotFoundException) exception).getTextMessage()); - }else if(exception instanceof MatchPlayerNotFoundException){ - session.sendMessage(((MatchPlayerNotFoundException) exception).getTextMessage()); - }else if(exception instanceof NullPointerException){ - session.sendMessage(ExpressionException.TEXT_MESSAGE); - }else{ - HashMap message = new HashMap<>(); - message.put("content", "알수없는 오류가 발생했습니다."); - session.sendMessage(new TextMessage(new ObjectMapper().writeValueAsString(message))); - } - }catch(IOException e){ - log.debug("exception : {} ", e); - log.debug("session 혹은 sendMessage 오류가 발생했습니다."); - } - } - - - private WebClient getClient(String url){ - return WebClient.create(url); - } - private static HashMap getMatchDtoHashMap(UUID uuid, ZSetOperations.TypedTuple player1, ZSetOperations.TypedTuple player2, String queueKey) { - HashMap match = new HashMap<>(); - MatchDto player1MatchValue = new MatchDto(); - MatchDto player2MatchValue = new MatchDto(); - String [] player1Infos = ((String)player1.getValue()).split(" "); - String player1userId = player1Infos[0]; - String player1userNickname = player1Infos[1]; - String [] player2Infos = ((String)player2.getValue()).split(" "); - String player2userId = player2Infos[0]; - String player2userNickname = player2Infos[1]; - player1MatchValue.setMatchId(uuid.toString()); - player1MatchValue.setUserId(player1userId); - player1MatchValue.setEnqueueTime(player1.getScore().longValue()); - player1MatchValue.setIsOk(null); - player1MatchValue.setQueueKey(queueKey); - player1MatchValue.setUserNickname(player1userNickname); - player2MatchValue.setMatchId(uuid.toString()); - player2MatchValue.setUserId(player2userId); - player2MatchValue.setEnqueueTime(player2.getScore().longValue()); - player2MatchValue.setIsOk(null); - player2MatchValue.setQueueKey(queueKey); - player2MatchValue.setUserNickname(player2userNickname); - match.put((String) player1.getValue(), player1MatchValue); - match.put((String) player2.getValue(), player2MatchValue); - return match; - } - - public void matchValidation(WebSocketSession session, MessageDto receive) throws MatchNotFoundException, MatchPlayerNotFoundException { - String recMatchId = receive.getMatchId(); - if(recMatchId== null || "".equals(recMatchId) || !matchMap.containsKey(recMatchId)){ - throw new MatchNotFoundException(); - } - if(!matchMap.get(recMatchId).containsKey(receive.getUserId()+" "+receive.getUserNickname())){ - throw new MatchPlayerNotFoundException(); - } - } - public MessageDto makeMessage(MessageDto.MessageType msgType, String mode, String matchId, String userId, String lang, Integer rating, String content, String queueKey, String userNickname, String gameId, String viduSession, String problemId){ - MessageDto message = new MessageDto(); - message.setType(msgType); - message.setGameMode(mode); - message.setRating(rating); - message.setLang(lang); - message.setMatchId(matchId); - message.setUserId(userId); - message.setContent(content); - message.setQueueKey(queueKey); - message.setUserNickname(userNickname); - message.setGameId(gameId); - message.setProblemId(problemId); - message.setViduSession(viduSession); - return message; - } - - public String makeKey(UserDto userDto) throws NullPointerException{ - StringBuilder sb = new StringBuilder(); - StringBuilder t = sb.append(userDto.getGameMode()).append("-").append(userDto.getLang()).append("-"); - int rating = userDto.getRating(); - String lv = ""; - if(rating < 1200){ - lv = "lv1"; - }else if(rating >= 1200 && rating < 1400){ - lv = "lv2"; - }else if(rating >= 1400 && rating < 1600){ - lv = "lv3"; - }else if(rating >= 1600 && rating < 1800){ - lv = "lv4"; - }else{ - lv = "lv5"; - } - t.append(lv); - return t.toString(); - } -} diff --git a/back-end/match/src/main/java/com/ssafy/match/YesOrNoDto.java b/back-end/match/src/main/java/com/ssafy/match/YesOrNoDto.java deleted file mode 100644 index d7e72e8b..00000000 --- a/back-end/match/src/main/java/com/ssafy/match/YesOrNoDto.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ssafy.match; - -public class YesOrNoDto { - public enum MessageType{ - YES, NO - } - private MessageType type; -} diff --git a/back-end/match/src/main/resources/application.properties b/back-end/match/src/main/resources/application.properties deleted file mode 100644 index af613b9c..00000000 --- a/back-end/match/src/main/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -redis.port=ENC(kAZu9CNj/KG1/a7EFek7xQ==) -redis.host=ENC(P4WsrQuW6BxpID3WreT4RH/oeO9XnrqK) -redis.password=ENC(wvCCEMGWIqVdfNJKFoOjYg==) - - -gameserver.url=ENC(NmeRzHBCBGm19k/SzLUvtp0trBlJ34LCJbKi5r1Ad1DiYqD72KT9+g==) -restserver.url=ENC(6m+PDX/nXYjtIcRTdEkVmJIqz272E88Bvm1hV94hxAJdlAD1FCPaOw==) -logging.level.com.ssafy.match=debug \ No newline at end of file diff --git a/back-end/match/src/test/java/com/ssafy/match/MatchApplicationTests.java b/back-end/match/src/test/java/com/ssafy/match/MatchApplicationTests.java deleted file mode 100644 index fd8a90c1..00000000 --- a/back-end/match/src/test/java/com/ssafy/match/MatchApplicationTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ssafy.match; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -class MatchApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/front-end/Dockerfile b/front-end/Dockerfile index 209ca992..dfa6ab51 100644 --- a/front-end/Dockerfile +++ b/front-end/Dockerfile @@ -32,7 +32,7 @@ RUN rm /etc/nginx/conf.d/default.conf COPY nginx/nginx.conf /etc/nginx/conf.d # 컨테이너의 80번 포트를 열어준다. -EXPOSE 80 +EXPOSE 3000 ENV TZ=Asia/Seoul RUN apk add --no-cache tzdata && \ @@ -40,4 +40,4 @@ RUN apk add --no-cache tzdata && \ echo $TZ > /etc/timezone # nginx 서버를 실행하고 백그라운드로 동작하도록 한다. -CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file +CMD ["nginx", "-g", "daemon off;"] diff --git a/front-end/README.md b/front-end/README.md index de6c0e1a..f013ee62 100644 --- a/front-end/README.md +++ b/front-end/README.md @@ -1,6 +1,6 @@ # Getting Started with Create React App and Redux -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) template. +This project was bootstrappe with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) template.ddd ## Available Scripts diff --git a/front-end/nginx/nginx.conf b/front-end/nginx/nginx.conf index 32a78b77..40b6e118 100644 --- a/front-end/nginx/nginx.conf +++ b/front-end/nginx/nginx.conf @@ -1,5 +1,5 @@ server { - listen 80; + listen 3000; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { @@ -9,4 +9,4 @@ server { index index.html index.htm; try_files $uri $uri/ /index.html; } -} \ No newline at end of file +} diff --git a/front-end/package-lock.json b/front-end/package-lock.json index d63fd61f..bfa7655a 100644 --- a/front-end/package-lock.json +++ b/front-end/package-lock.json @@ -29,6 +29,7 @@ "react-image-crop": "^11.0.5", "react-intersection-observer": "^9.5.3", "react-modal": "^3.16.1", + "react-quill": "^2.0.0", "react-redux": "^8.1.3", "react-router-dom": "^6.21.3", "react-scripts": "5.0.1", @@ -5062,6 +5063,14 @@ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.11.tgz", "integrity": "sha512-oGk0gmhnEJK4Yyk+oI7EfXsLayXatCWPHary1MtcmbAifkobT9cM9yutG/hZKIseOU0MqbIwQ/u2nn/Gb+ltuQ==" }, + "node_modules/@types/quill": { + "version": "1.3.10", + "resolved": "https://registry.npmjs.org/@types/quill/-/quill-1.3.10.tgz", + "integrity": "sha512-IhW3fPW+bkt9MLNlycw8u8fWb7oO7W5URC9MfZYHBlA24rex9rs23D5DETChu1zvgVdc5ka64ICjJOgQMr6Shw==", + "dependencies": { + "parchment": "^1.1.2" + } + }, "node_modules/@types/range-parser": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", @@ -6879,6 +6888,14 @@ "wrap-ansi": "^7.0.0" } }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "engines": { + "node": ">=0.8" + } + }, "node_modules/clsx": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.0.tgz", @@ -9236,11 +9253,21 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, + "node_modules/fast-diff": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.1.2.tgz", + "integrity": "sha512-KaJUt+M9t1qaIteSvjc6P3RbMdXsNhK61GRftR6SNxqmhthcd9MGIi4T+o0jD8LUSpSnSKXE20nLtJ3fOHxQig==" + }, "node_modules/fast-equals": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.0.1.tgz", @@ -15729,6 +15756,11 @@ "tslib": "^2.0.3" } }, + "node_modules/parchment": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/parchment/-/parchment-1.1.4.tgz", + "integrity": "sha512-J5FBQt/pM2inLzg4hEWmzQx/8h8D0CiDxaG3vyp9rKrQRSDgBlhjdP5jQGgosEajXPSQouXGHOmVdgo7QmJuOg==" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -17433,6 +17465,75 @@ } ] }, + "node_modules/quill": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/quill/-/quill-1.3.7.tgz", + "integrity": "sha512-hG/DVzh/TiknWtE6QmWAF/pxoZKYxfe3J/d/+ShUWkDvvkZQVTPeVmUJVu1uE6DDooC4fWTiCLh84ul89oNz5g==", + "dependencies": { + "clone": "^2.1.1", + "deep-equal": "^1.0.1", + "eventemitter3": "^2.0.3", + "extend": "^3.0.2", + "parchment": "^1.1.4", + "quill-delta": "^3.6.2" + } + }, + "node_modules/quill-delta": { + "version": "3.6.3", + "resolved": "https://registry.npmjs.org/quill-delta/-/quill-delta-3.6.3.tgz", + "integrity": "sha512-wdIGBlcX13tCHOXGMVnnTVFtGRLoP0imqxM696fIPwIf5ODIYUHIvHbZcyvGlZFiFhK5XzDC2lpjbxRhnM05Tg==", + "dependencies": { + "deep-equal": "^1.0.1", + "extend": "^3.0.2", + "fast-diff": "1.1.2" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/quill-delta/node_modules/deep-equal": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.2.tgz", + "integrity": "sha512-5tdhKF6DbU7iIzrIOa1AOUt39ZRm13cmL1cGEh//aqR8x9+tNfbywRf0n5FD/18OKMdo7DNEtrX2t22ZAkI+eg==", + "dependencies": { + "is-arguments": "^1.1.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.5.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quill/node_modules/deep-equal": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.2.tgz", + "integrity": "sha512-5tdhKF6DbU7iIzrIOa1AOUt39ZRm13cmL1cGEh//aqR8x9+tNfbywRf0n5FD/18OKMdo7DNEtrX2t22ZAkI+eg==", + "dependencies": { + "is-arguments": "^1.1.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.5.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quill/node_modules/eventemitter3": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-2.0.3.tgz", + "integrity": "sha512-jLN68Dx5kyFHaePoXWPsCGW5qdyZQtLYHkxkg02/Mz6g0kYpDx4FyP6XfArhQdlOC4b8Mv+EMxPo/8La7Tzghg==" + }, "node_modules/raf": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz", @@ -17695,6 +17796,20 @@ "react-dom": "^0.14.0 || ^15.0.0 || ^16 || ^17 || ^18" } }, + "node_modules/react-quill": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/react-quill/-/react-quill-2.0.0.tgz", + "integrity": "sha512-4qQtv1FtCfLgoD3PXAur5RyxuUbPXQGOHgTlFie3jtxp43mXDtzCKaOgQ3mLyZfi1PUlyjycfivKelFhy13QUg==", + "dependencies": { + "@types/quill": "^1.3.10", + "lodash": "^4.17.4", + "quill": "^1.3.7" + }, + "peerDependencies": { + "react": "^16 || ^17 || ^18", + "react-dom": "^16 || ^17 || ^18" + } + }, "node_modules/react-redux": { "version": "8.1.3", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-8.1.3.tgz", diff --git a/front-end/package.json b/front-end/package.json index 4f91dcff..8ee25812 100644 --- a/front-end/package.json +++ b/front-end/package.json @@ -24,6 +24,7 @@ "react-image-crop": "^11.0.5", "react-intersection-observer": "^9.5.3", "react-modal": "^3.16.1", + "react-quill": "^2.0.0", "react-redux": "^8.1.3", "react-router-dom": "^6.21.3", "react-scripts": "5.0.1", diff --git a/front-end/src/App.jsx b/front-end/src/App.jsx index c1b76872..c1abae66 100644 --- a/front-end/src/App.jsx +++ b/front-end/src/App.jsx @@ -10,7 +10,7 @@ function App() { useEffect(()=> { const path = location.pathname - console.log(path); + // console.log(path); if (path.includes('game-list') && !(path === '/game-list/competition' || path === '/game-list/group') ) { setIsArena(true) } else { diff --git a/front-end/src/app/store.js b/front-end/src/app/store.js index 150391fa..66e450a6 100644 --- a/front-end/src/app/store.js +++ b/front-end/src/app/store.js @@ -1,4 +1,4 @@ -import { configureStore } from '@reduxjs/toolkit'; +import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'; import { combineReducers } from 'redux'; import { persistReducer, persistStore } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; @@ -28,7 +28,9 @@ const persistedReducer = persistReducer(persistConfig, rootReducer); export const store = configureStore({ reducer: persistedReducer, - + middleware: getDefaultMiddleware({ + serializableCheck: false, // 비직렬화 가능한 값 경고 비활성화 + }), }); export const persistor = persistStore(store); \ No newline at end of file diff --git a/front-end/src/components/arena/HotMatch.jsx b/front-end/src/components/arena/HotMatch.jsx index b1d571b0..fd533bf3 100644 --- a/front-end/src/components/arena/HotMatch.jsx +++ b/front-end/src/components/arena/HotMatch.jsx @@ -1,40 +1,25 @@ -import React, { useEffect, useRef, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; -// npm install styled-components 애니메이트 기능 구현 설치 라이브러리 import styled, { keyframes } from 'styled-components'; import axios from 'axios'; -// import Oh from '../../images/arena/HotMatch/oh.png' -// import Gwi from '../../images/arena/HotMatch/gwi.png' -// import Hae from '../../images/arena/HotMatch/hae.png' -// import Kim from '../../images/arena/HotMatch/kim.png' import View from '../../images/arena/HotMatch/View.png' import VS from '../../images/arena/HotMatch/VS.png' import Fighting from '../../images/arena/HotMatch/Fighting.gif' +const fadeIn = keyframes`from {opacity: 0; transform: translateX(-50px);} to {opacity: 1;}`; +const AnimatedHeader = styled.h1`animation: ${fadeIn} 0.5s ease-in-out forwards;`; export default function HotMatch() { - // Hot Match 애니메이트 - const fadeIn = keyframes`from {opacity: 0; transform: translateX(-50px);} to {opacity: 1;}`; - const AnimatedHeader = styled.h1`animation: ${fadeIn} 0.5s ease-in-out forwards;`; - const [hotMatchs, setHotMatchs] = useState([]) useEffect(()=> { axios.get('https://codearena.shop/game/chat/hotmatch') .then((res)=> { setHotMatchs(res.data) - console.log("Hot Match 확인 :", res.data); + // console.log("Hot Match 확인 :", res.data); }) },[]) - - - - - - - - return (

diff --git a/front-end/src/components/arena/Match/Competition/CompTopInfo.jsx b/front-end/src/components/arena/Match/Competition/CompTopInfo.jsx index 893c93ad..df6c16ac 100644 --- a/front-end/src/components/arena/Match/Competition/CompTopInfo.jsx +++ b/front-end/src/components/arena/Match/Competition/CompTopInfo.jsx @@ -34,22 +34,23 @@ export default function CompTopInfo({ gameExitId, problemId, game}) { return (
{/* 왼쪽 상단 (유저 정보) */} -
-
+
+
플레이어1 이미지
@@ -107,7 +108,6 @@ export default function CompTopInfo({ gameExitId, problemId, game}) {
- {/* 나가기 버튼 */} @@ -425,141 +375,128 @@ export default function CompetitionView() {
{/* 입력 폼 */} -
+
- - - - -
-
- {/* if there is a button in form, it will close the modal */} - -
-

배팅

-
-
-
- 플레이어1 이미지 + +
+
+ +
+

배팅

+
+
+
+ 플레이어1 이미지 +
+

{game?.userRedNickname}

-

{game?.userRedNickname}

-
-
- vs -
-
-
- 플레이어2 이미지 +
+ vs
-

{game?.userBlueNickname}

-
-
-
-
- -
-
-
- people - { - game?.gameMode === '1' ? -

{game?.userRedEffiRating}

- : -

{game?.userRedSpeedRating}

- } -
-
- people -

{betting.player1BatPeople}

-
-
- people -

{betting.player1MaxUserNickname || '-'}

-
-
- people -

{betting.player1MaxCoin || '-'}

-
-
-
-

{betting.player1Ratio}%

+
+
+ 플레이어2 이미지
+

{game?.userBlueNickname}

- - - - {!isBetting ? -
- - -
- : - null - }
-
- -
-
-

{betting.player2Ratio}%

-
-
-
- { - game?.gameMode === '1' ? -

{game?.userBlueEffiRating}

- : -

{game?.userBlueSpeedRating}

- } - people -
-
-

{betting.player2BatPeople}

- people -
-
-

{betting.player2MaxUserNickname || '-'}

- people -
-
-

{betting.player2MaxCoin || '-'}

- people +
+
+
+
+
+ people + { + game?.gameMode === '1' ? +

{game?.userRedEffiRating}

+ : +

{game?.userRedSpeedRating}

+ } +
+
+ people +

{betting.player1BatPeople}

+
+
+ people +

{betting.player1MaxUserNickname || '-'}

+
+
+ people +

{betting.player1MaxCoin || '-'}

+
+
+
+

{betting.player1Ratio}%

-
+
+ {!isBetting ? +
+ + +
+ : + null + }
- - {!isBetting ? -
- - +
+
+
+

{betting.player2Ratio}%

+
+
+
+ { + game?.gameMode === '1' ? +

{game?.userBlueEffiRating}

+ : +

{game?.userBlueSpeedRating}

+ } + people +
+
+

{betting.player2BatPeople}

+ people +
+
+

{betting.player2MaxUserNickname || '-'}

+ people +
+
+

{betting.player2MaxCoin || '-'}

+ people +
+
+
+ + {!isBetting ? +
+ + +
+ : + null + }
- : - null - }
-
-
- +
- -
); } \ No newline at end of file diff --git a/front-end/src/components/arena/Rank.jsx b/front-end/src/components/arena/Rank.jsx index d1711621..c98c1318 100644 --- a/front-end/src/components/arena/Rank.jsx +++ b/front-end/src/components/arena/Rank.jsx @@ -3,9 +3,10 @@ import { Link } from 'react-router-dom'; import axios from 'axios'; import styled, { keyframes } from 'styled-components'; +const fadeIn = keyframes`from {opacity: 0; transform: translateX(-50px);} to {opacity: 1;}`; +const AnimatedHeader = styled.h1`animation: ${fadeIn} 0.5s ease-in-out forwards;`; + export default function RankPage() { - const fadeIn = keyframes`from {opacity: 0; transform: translateX(-50px);} to {opacity: 1;}`; - const AnimatedHeader = styled.h1`animation: ${fadeIn} 0.5s ease-in-out forwards;`; const [CoinRanks, setCoinRanks] = useState([]) const [speedRanks, setSpeedRanks] = useState([]) @@ -14,16 +15,15 @@ export default function RankPage() { useEffect(()=> { axios.get('https://codearena.shop/game/rest/rank') .then((res)=> { - console.log(res); + // console.log(res); setSpeedRanks(res.data.data.speedRank) setEffRanks(res.data.data.effRank) setCoinRanks(res.data.data.pointRank) }) },[]) - // 각 모드별 전체 랭킹 리스트 - const renderRankingList = (mode, rankingList) => ( + const renderRankingList = ( mode, rankingList ) => (
{ mode === 'Speed' ? - rankingList.map((user, index) => renderRankingItem(user, index)) - : - rankingList.map((user, index) => renderRankingItem2(user, index)) + rankingList.map((user, index) => renderRankingItem(user, index)) + : + rankingList.map((user, index) => renderRankingItem2(user, index)) }
@@ -56,10 +56,9 @@ export default function RankPage() { // 각 모드별 랭킹 리스트 아이템 const renderRankingItem = (user, index) => ( -
+
@@ -71,10 +70,9 @@ export default function RankPage() { ); const renderRankingItem2 = (user, index) => ( -
+
@@ -85,8 +83,6 @@ export default function RankPage() {
); - - const BattingKingList = (mode, rankingList) => (
( -
+
@@ -127,9 +122,6 @@ export default function RankPage() {
); - - - return (
@@ -141,9 +133,6 @@ export default function RankPage() { {renderRankingList('Efficiency', effRanks)}
{/* 사이에 여백 */} {BattingKingList('Rich', CoinRanks)} - - -
); diff --git a/front-end/src/components/arena/Statsistics.jsx b/front-end/src/components/arena/Statsistics.jsx index 854369de..e1c6b6d5 100644 --- a/front-end/src/components/arena/Statsistics.jsx +++ b/front-end/src/components/arena/Statsistics.jsx @@ -32,8 +32,8 @@ export default function StatsisticsPage() { fontSize: '16px', }; - // 차트에 보이는 퍼센트 값을 직접 계산하여 표시하는 함수 - const formatPercent = (value) => `${(value * 100).toFixed(0)}%`; + // 차트에 보이는 퍼센트 값을 계산하여 표시하는 함수 + // const formatPercent = (value) => `${(value * 100).toFixed(0)}%`; useEffect(()=> { const headers = { @@ -46,7 +46,7 @@ export default function StatsisticsPage() { return {name:key.split('Count'), value:value} })) setMatchs(res.data.data.recentMatches) - console.log("record 확인 :", res.data.data.recentMatches) + // console.log("record 확인 :", res.data.data.recentMatches) }) .catch((err) => { console.log("에러!!! :", err) diff --git a/front-end/src/components/arena/TopBanner.jsx b/front-end/src/components/arena/TopBanner.jsx index a36847e6..5742c714 100644 --- a/front-end/src/components/arena/TopBanner.jsx +++ b/front-end/src/components/arena/TopBanner.jsx @@ -73,16 +73,15 @@ export default function TopBanner() { socket.current = new WebSocket('wss://codearena.shop/matching'); socket.current.addEventListener("open", function (event) { - console.log(event) + console.log("웹소켓 연결 확인", event) }) socket.current.addEventListener("message", function (event) { - console.log("Message from server ", event.data); - - const object = JSON.parse(event.data) - console.log("recive data :", object) - + // console.log("Message from server ", event.data); + const object = JSON.parse(event.data) + // console.log("recive data :", object) + if (object.type) { setType2(object.type) matchId.current = object.matchId; @@ -121,7 +120,7 @@ export default function TopBanner() { startTime: startTime.current, queueKey: queueKey.current, })); - console.log("setGameInfo를 찍었습니다 :", setGameInfo) + // console.log("setGameInfo 확인 :", setGameInfo) navigate(`/game-list/competition/play/${object.gameId}`) } @@ -145,7 +144,6 @@ export default function TopBanner() { if (socket.current.readyState === WebSocket.OPEN && type2) { startMatchingTimer(); } - }); socket.current.addEventListener("error", function (event) { @@ -158,19 +156,16 @@ export default function TopBanner() { } }; }; - - ////////////////// 위에서 websocket 통신 연결 ////////////////////////// // 1. 언어 3가지 중 하나 선택하기 const handleLanguageSelection = (lang) => { setSelectedLanguage(lang); - console.log("lang :", lang) + // console.log("lang :", lang) }; - // 2. 언어 선택 모달 활성화 const openLanguageModal = () => { - console.log('언어 선택 모달 호출함!!'); + // console.log('언어 선택 모달 호출함!!'); const languageModal = document.getElementById('language_modal'); const matchingModal = document.getElementById('matching_modal'); @@ -191,7 +186,7 @@ export default function TopBanner() { // 3. 매칭 진행 모달 const openMatchingModal = () => { - console.log('매칭 진행 모달 호출함!!'); + // console.log('매칭 진행 모달 호출함!!'); const languageModal = document.getElementById('language_modal'); const matchingModal = document.getElementById('matching_modal'); @@ -219,18 +214,16 @@ export default function TopBanner() { // 매칭 모달이 닫힐 때 타이머 중지 matchingModal.addEventListener('close', () => { - console.log("너가 아니길 빈다.... 머리아프다") clearInterval(timerInterval.current); // 타이머 중지 languageModal.close(); }); }; // 타이머 중지 - // let timerInterval/// const closeMatchingModalHandler = () => { - console.log('타이머 중지!!'); + // console.log('타이머 중지!!'); setType2(null) - console.log('진짜 마지막 타입 확인 :', type2) + // console.log('진짜 마지막 타입 확인 :', type2) // 선택된 언어 초기화 setSelectedLanguage(null); const matchingCompleteModal = document.getElementById('matching_complete_modal'); @@ -253,8 +246,6 @@ export default function TopBanner() { clearInterval(timerInterval.current); timerInterval.current = null; } - - // 언어 선택 모달 중복호출이 안되도록 }; // 4. 매칭이 돌아가면 타이머 소환 @@ -283,23 +274,16 @@ export default function TopBanner() { // 원하는 시간까지 진행 후 타이머 중지 // const desiredTimeInSeconds = 10; - console.log('Start Matching Timer type : ', type2) - + // console.log('Start Matching Timer type : ', type2) }; useEffect(()=> { - console.log('!!!!!!!!!!!!!!!타입2',type2); if (type2 && type2 === "QUERY") { const interval = timerInterval.current clearInterval(interval); timerInterval.current = interval; handleMatchingComplete(); // 수락&거절 모달 함수 호출 - } else if (type2 && type2 === 'RESPONSE') { - - } - // if (socket.current.readyState === WebSocket.OPEN && type2) { - // startMatchingTimer(); - // } + } },[type2]) const startQueryTimer = () => { @@ -313,12 +297,8 @@ export default function TopBanner() { // 타이머 초마다 상승하고 문자열로 표기 timerElements.textContent = `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`; - // if (type2 && type2 === 'CONTINUE') { - // clearInterval(timerInterval.current); // 초기화 - // } - if (seconds === 0) { - console.log("startQueryTimer의 타이머 확인@@") + // console.log("startQueryTimer의 타이머 확인@@") socket.current.send( JSON.stringify({ matchId: matchId.current, @@ -345,7 +325,7 @@ export default function TopBanner() { timerInterval.current = setInterval(updateTimer, 1000); } - // 5. "매칭 완료!" 문구와 동시에 "수락", "취소" 모달 띄우기 + // 5-1. "매칭 완료!" 문구와 동시에 "수락", "취소" 모달 띄우기 const handleMatchingComplete = () => { setMatchingState({ userImgSrc: userImgSrc.current, @@ -362,10 +342,10 @@ export default function TopBanner() { }, 1500); }; - // 5-1. 매칭 완료 후 띄워질 "수락", "취소" 마지막 모달 + // 5-2. 매칭 완료 후 띄워질 "수락", "취소" 마지막 모달 const openMatchingCompleteModal = () => { // MatchingCompleteModal 열기 - console.log("마지막 수락 거절 모달 호출되니?") + // console.log("마지막 수락 거절 모달 호출되니?") const matchingCompleteModal = document.getElementById('matching_complete_modal'); matchingCompleteModal.style.left = '50%'; matchingCompleteModal.style.top = '50%'; @@ -387,9 +367,9 @@ export default function TopBanner() { }); }; - // 마지막 모달에서 "거절" 모든 모달 닫기 (중복 호출 방지) + // 마지막 모달에서 "거절" 누를 시 모든 모달 닫기 (중복 호출 방지) const handleCancel = () => { - console.log("매칭을 거절했어요 !") + // console.log("매칭을 거절했어요 !") const send_obj = { matchId: matchId.current, userId: userId.current, @@ -429,9 +409,9 @@ export default function TopBanner() { } }; - // 마지막 "수락" 버튼을 눌렀을 때 호출될 함수.. + // 마지막 "수락" 버튼을 눌렀을 때 호출될 함수 const handleAccept = () => { - console.log("매칭을 수락했어요 !") + // console.log("매칭을 수락했어요 !") const send_obj = { matchId: matchId.current, userId: userId.current, @@ -447,23 +427,14 @@ export default function TopBanner() { type: 'YES', }; - console.log("수락 :", send_obj) - socket.current.send ( JSON.stringify (send_obj) ); - // clearInterval(timerInterval.current); - // 중복 호출 방지를 위한 선언 및 모든 모달 닫기 - // const matchingCompleteModal = document.getElementById('matching_complete_modal'); const languageModal = document.getElementById('language_modal'); const matchingModal = document.getElementById('matching_modal'); - // if (matchingCompleteModal && matchingCompleteModal.open) { - // matchingCompleteModal.close(); - // } - if (languageModal && languageModal.open) { languageModal.close(); } @@ -473,11 +444,6 @@ export default function TopBanner() { } }; - // 게임 생성 모달 닫기 - const closeModal = () => { - setIsModalOpen(false); - }; - return (
{/* 상단 배너 */}
{/* 경쟁 매칭 버튼*/} - + + > + 취 소 + -

언어를 선택하세요 !

+

언어를 선택하세요 !

{/* 언어 선택 옵션 3가지 -> 수정 */} -
+
{languageButtons.map(({ lang, label }) => ( -

매칭 중입니다...

-

잠시만 기다려주세요

+

매칭 중입니다...

+

잠시만 기다려주세요

{/* 타이머 00:00부터 1초씩 상승하기 */} -
+ +
@@ -626,37 +596,18 @@ export default function TopBanner() {
- - - {/* 게임 생성.. 자릅니다... */} - {/* - {} */} +
{/* 게임 찾기 */} - +
{/* 상단 배너 선 */}
{ axios.get(`https://codearena.shop/game/chat/enter?gameId=${competitionId}`) - .then(res=>console.log(res)) - .catch(err=>console.log(err)) + .then(res => console.log(res)) + .catch(err => console.log(err)) navigate( `/game-list/competition/view/${competitionId}`, diff --git a/front-end/src/components/arena/modal/Competition/CompabstentionModal.jsx b/front-end/src/components/arena/modal/Competition/CompabstentionModal.jsx index 5589c57a..382f1c82 100644 --- a/front-end/src/components/arena/modal/Competition/CompabstentionModal.jsx +++ b/front-end/src/components/arena/modal/Competition/CompabstentionModal.jsx @@ -1,9 +1,7 @@ -import React, { useEffect, useState, useRef } from "react"; +import React, { useRef } from "react"; import { useNavigate } from "react-router-dom" -import SockJS from 'sockjs-client'; -import { Stomp } from '@stomp/stompjs'; import { useDispatch, useSelector } from "react-redux"; -import { setStompClients, clearStompClient } from "../../../../features/arena/stompClientSlice"; +import { clearStompClient } from "../../../../features/arena/stompClientSlice"; export default function AbstentionModal() { const navigate = useNavigate(); @@ -16,18 +14,9 @@ export default function AbstentionModal() { gameId } = useSelector(state => state.game); const stompClient = useSelector(state => state.stompClient.stompClient); - - useEffect(()=> { - - console.log("useEffect stompClient :", stompClient) - - console.log("넘어온 problemId 번호 확인 :", problemId) - - },[gameId]) - // 기권할래요 동작 함수 const clickHandler = () => { - console.log('기권했어요', stompClient.send) + // console.log('기권했어요', stompClient.send) stompClient.send(`/pub/chat/leave`, {}, JSON.stringify({ gameId: gameId, userId: userId, @@ -35,7 +24,6 @@ export default function AbstentionModal() { mode : gameMode === 'speed' ? 0 : 1, type: 'PLAYER_EXIT', })) - stompClient.unsubscribe('/sub/chat/room/'+`${gameId}`); stompClient.unsubscribe('/pub/chat/leave'); stompClient.disconnect(); @@ -44,6 +32,11 @@ export default function AbstentionModal() { window.location.reload() } + // useEffect(()=> { + // console.log("useEffect stompClient :", stompClient) + // console.log("넘어온 problemId 번호 확인 :", problemId) + // },[gameId]) + return (
diff --git a/front-end/src/components/arena/modal/Main/BannerCreateModal.jsx b/front-end/src/components/arena/modal/Main/BannerCreateModal.jsx index 72584885..8c9e8c09 100644 --- a/front-end/src/components/arena/modal/Main/BannerCreateModal.jsx +++ b/front-end/src/components/arena/modal/Main/BannerCreateModal.jsx @@ -3,21 +3,16 @@ import axios from 'axios'; import { useSelector } from 'react-redux'; import { useNavigate } from 'react-router'; -// import ChatRoom from '../match/ChatRoom'; - export default function CreateModal({ closeModal, onRoomCreated }) { const navigate = useNavigate() const userId = useSelector(state => state.auth.userId) const [roomName, setRoomName] = useState(''); - const [mode, setMode] = useState(0) - const [chatrooms, setChatrooms] = useState([]); - const [selectedRoomId, setSelectedRoomId] = useState(null); const [gameMode, setGameMode] = useState(0) const [language, setLanguage] = useState('java') const createRoom = () => { if (roomName === '') { - alert('방 제목을 입력해 주십시요.'); + alert('방 제목을 입력해 주세요.'); return; } else { const data = { @@ -29,19 +24,15 @@ export default function CreateModal({ closeModal, onRoomCreated }) { axios.post('https://codearena.shop/game/chat/gameroom/private', data) .then(response => { if (response.data.status === '200'){ - alert(`${response.data.name} 방 개설에 성공하였습니다.`); - // onRoomCreated(response.data) - // closeModal(); // 모달 닫기 + // alert(`${response.data.name} 방 개설에 성공하였습니다.`); navigate(`/game-list/group/lobby/${response.data.data}`) } }) .catch(error => { - alert('채팅방 개설에 실패하였습니다.'); - console.error('채팅방 생성 중 오류 발생:', error); + // alert('채팅방 개설에 실패하였습니다.'); + console.error('방 생성 중 오류 발생:', error); }); } - - }; return ( diff --git a/front-end/src/components/arena/modal/Main/MatchingCompleteModal.jsx b/front-end/src/components/arena/modal/Main/MatchingCompleteModal.jsx index e3118a80..1060a2cb 100644 --- a/front-end/src/components/arena/modal/Main/MatchingCompleteModal.jsx +++ b/front-end/src/components/arena/modal/Main/MatchingCompleteModal.jsx @@ -3,63 +3,34 @@ import VS from '../../../../images/arena/HotMatch/VS.png' import { useSelector } from 'react-redux/es/hooks/useSelector'; export default function MatchingCompleteModal({ matchingState, onAccept, onCancel, type, socket}) { - const [userImgSrcs, setUserImgSrcs] = useState(''); const [enemyImgSrcs, setEnemyImgSrcs] = useState(''); const [userNicknames, setUserNicknames] = useState(''); const [enemyNicknames, setEnemyNicknames] = useState(''); const [waitingText, setWaitingText] = useState(""); const [buttonsVisible, setButtonsVisible] = useState(true); - // const [propsType, setPropsType] = useState(type); const queueKey = useSelector(state => state.game.queueKey); const userId = useSelector(state => state.game.userId); const userNickname = useSelector(state => state.game.userNickname); const rating = useSelector(state => state.game.rating); - // const propsType = type; // props 받은 타입 선언 - - // 수락했을 때 작동할 함수 - - // const checkPropsType = (msgType) => { - // // 거절당하고 다시 우선순위 큐에 들어감 - // if (msgType == 'CONTINUE') { - // // console.log("msgType 확인 :", msgType) - // changeText("상대가 매칭을 거절하여 새로운 매칭을 시도하겠습니다..."); - // setButtonsVisible(false); - // } - // // 상대방과 매칭 잡혔을 때 : QUERY - // else if (msgType == 'QUERY') { - // // console.log("좀 떠라") - // changeText(''); - // setButtonsVisible(true); - // // changeText("새 매칭을 잡았어요!"); - // } - // } - const handleAccept = () => { onAccept(); - // console.log("props받은 타입 확인111 :", type.current) changeText("상대방의 수락을 기다리고 있어요!"); setButtonsVisible(false); }; useEffect(()=>{ - console.log("props받은 type 확인000 :", type) - - // console.log("useEffect !!!!") - // 거절당하고 다시 우선순위 큐에 들어감 + // 거절당하면 다시 우선순위 큐에 진입 if (type == 'CONTINUE') { - // console.log("msgType 확인 :", msgType) changeText("상대가 매칭을 거절하여 새로운 매칭을 시도하겠습니다..."); setButtonsVisible(false); } // 상대방과 매칭 잡혔을 때 : QUERY else if (type == 'QUERY') { - // console.log("좀 떠라") changeText(''); setButtonsVisible(true); - // changeText("새 매칭을 잡았어요!"); } }, [type]) @@ -69,10 +40,6 @@ export default function MatchingCompleteModal({ matchingState, onAccept, onCance } const onHandleCancle = () => { - // console.log("queuekey 확인입니다!!!!!!!!!!!!!!!!!!! :", queueKey) - // console.log("userId 확인입니다!!!!!!!!!!!!!!!!!!! :", userId) - // console.log("rating 확인입니다!!!!!!!!!!!!!!!!!!! :", rating) - // console.log("userNickname 확인입니다!!!!!!!!!!!!!!!!!!! :", userNickname) socket.send( JSON.stringify ({ type : "POP", @@ -86,17 +53,8 @@ export default function MatchingCompleteModal({ matchingState, onAccept, onCance ); socket.close(); socket = null; - } - // 거절했을 때 작동할 함수 - // const handleReject = () => { - // onCancel(); - // setShowWaitingUI(false); // 거절 시 새로운 UI 보여줌 - // setWaitingText(''); - // setRejectingText("상대가 매칭을 거절하여 새로운 매칭을 시도하겠습니다..."); // 거절 후 매칭 재시도 문구 설정 - // }; - useEffect(() => { // console.log('내려받은 유저 닉네임, 이미지 확인 :', matchingState); setUserImgSrcs(matchingState.userImgSrc); diff --git a/front-end/src/components/community/CommentListItem.jsx b/front-end/src/components/community/CommentListItem.jsx index ae1bf9f0..70e08f68 100644 --- a/front-end/src/components/community/CommentListItem.jsx +++ b/front-end/src/components/community/CommentListItem.jsx @@ -8,100 +8,121 @@ import swal from 'sweetalert'; export default function CommentListItem(props) { // 코드에 아무것도 없는 null은 객체라서 오류나니깐 .. - const [code,setCode] = useState(props.commentItem.code || '') + const [code, setCode] = useState(props.commentItem.code || '') const userId = useSelector(state => state.auth.userId) const commentId = props.commentItem.writerId // 댓글작성자와 로그인한유저 검사하려고 const commentNo = props.commentItem.commentId // 댓글삭제하기위해 댓글commentId가져옴 - const [comment,setComment] = useState(props.commentItem.comment) + const [comment, setComment] = useState(props.commentItem.comment) const articleNo = props.commentItem.articleNo const navigate = useNavigate() + const [bgcolor, setBgcolor] = useState('#F4ECE4'); + const [showCodeMirror, setShowCodeMirror] = useState(false) - const commentDelete = () =>{ + + const colorChange = () => { + if (bgcolor === '#F4ECE4') { + setBgcolor('#ffffff') + setShowCodeMirror(true) + } else { + setBgcolor('#F4ECE4') + setShowCodeMirror(false) + } + } + + const commentDelete = () => { axios({ - url : `https://codearena.shop/api/comment/delete?commentId=${commentNo}`, - method : 'delete' - }) - .then((res)=>{ - console.log(res) - props.onDelete(commentNo) - swal("댓글삭제완료","","success") - }) - .catch((err)=>{ - console.log(err) + url: `https://codearena.shop/api/comment/delete?commentId=${commentNo}`, + method: 'delete' }) + .then((res) => { + console.log(res) + props.onDelete(commentNo) + swal("댓글삭제완료", "", "success") + }) + .catch((err) => { + console.log(err) + }) } const onChangeCode = useCallback((code, viewUpdate) => { setCode(code); }, []); - - const updateComment = () =>{ + + const updateComment = () => { axios({ - url : 'https://codearena.shop/api/comment/update', - method : 'put', - data : { - commentId : commentNo, - comment : comment, - code : code, + url: 'https://codearena.shop/api/comment/update', + method: 'put', + data: { + commentId: commentNo, + comment: comment, + code: code, } }) - .then((res)=>{ - console.log(res) - swal("댓글수정완료","","success") - navigate(`/community/${articleNo}/detail`) - }) - .catch((err)=>{ - console.log(err) - }) + .then((res) => { + console.log(res) + swal("댓글수정완료", "", "success") + navigate(`/community/${articleNo}/detail`) + }) + .catch((err) => { + console.log(err) + }) } - - return( + return (
-
-
-
-
작성자 : {props.commentItem.writerNickname}
-
-
-
- -
-
- {code && ( -
-
-
- +
+
+
{props.commentItem.writerNickname}
-
-
- )} - { userId === commentId && ( -
-
수정
- -
- +
+
- )} -
-
+ {code && ( +
+
+ +
+
+ )} + {showCodeMirror && ( +
+
+ +
+
+ )} + {userId === commentId && ( +
+
+ 수정 +
+ +
+ )} +
+
- + ) } diff --git a/front-end/src/components/main/AboutUs.jsx b/front-end/src/components/main/AboutUs.jsx index 6de77ed1..8a63d743 100644 --- a/front-end/src/components/main/AboutUs.jsx +++ b/front-end/src/components/main/AboutUs.jsx @@ -1,7 +1,6 @@ import React, { useState, useEffect } from 'react'; import styled, { keyframes } from 'styled-components'; import 'tailwindcss/tailwind.css'; - import Introduce from '../../images/main/AboutUs/Introduce.gif'; import We from '../../images/main/AboutUs/We.gif'; @@ -10,7 +9,6 @@ const frameInAnimation_gif = keyframes` opacity: 0; transform: translateX(-100%); } - 100%{ opacity: 1; transform: translateX(0%); @@ -22,7 +20,6 @@ const AnimateContainer_gif = styled.div` flex-direction: column; justify-content: center; align-items: center; - &.frame-in { animation: ${frameInAnimation_gif} 1s forwards; } @@ -33,7 +30,6 @@ const frameInAnimation_font = keyframes` opacity: 0; transform: translateX(100%); } - 100%{ opacity: 1; transform: translateX(0%); @@ -42,30 +38,22 @@ const frameInAnimation_font = keyframes` const AnimateContainer_font = styled.div` display: flex; - - &.frame-in { animation: ${frameInAnimation_font} 1s forwards; } `; export default function AboutUs({ fromRefFourElement }) { - const [animate, setAnimate] = useState(false); + const [animate, setAnimate] = useState(false); // 애니메이트 상태 관리 + useEffect(() => { const handleScroll = () => { - // 특정 조건을 확인하여 animate 상태 토글 - const shouldAnimate = window.scrollY > 1500; + const shouldAnimate = window.scrollY > 1500; // 특정 조건을 확인하여 animate 상태 토글 setAnimate(shouldAnimate); }; - - // 스크롤 이벤트 리스너 등록 window.addEventListener('scroll', handleScroll); - - // 컴포넌트가 마운트될 때 애니메이션을 트리거 setAnimate(true); - - // 클린업 함수에서 이벤트 리스너 제거 return () => { window.removeEventListener('scroll', handleScroll); }; @@ -73,13 +61,7 @@ export default function AboutUs({ fromRefFourElement }) { return (
- {/* 위쪽과 아래쪽만 보일 div */}
- {/* 위쪽의 선 */} -
-
-
- {/* 중앙 컨텐츠 영역 */}
{/* 왼쪽 - Introduce GIF */} @@ -96,7 +78,7 @@ export default function AboutUs({ fromRefFourElement }) { {/* 오른쪽 - About Us 문구 */}

About Us

@@ -107,7 +89,7 @@ export default function AboutUs({ fromRefFourElement }) { 실시간 코딩 배틀의 특별함을 더해 코딩에 흥미를 느껴보세요!

- 개발자들은 여기에서 서로의 실력을 겨루며, 문제 해결 능력을 향상시키고 새로운 아이디어를 찾아갈 수 있습니다. + 여기에서 서로의 실력을 겨루며, 문제 해결 능력을 향상시키고 새로운 아이디어를 찾아갈 수 있습니다.

함께 성장하고 발전하는 코딩 커뮤니티, 코드 아레나! diff --git a/front-end/src/components/main/FourElement.jsx b/front-end/src/components/main/FourElement.jsx index 58bdb83e..52b32ade 100644 --- a/front-end/src/components/main/FourElement.jsx +++ b/front-end/src/components/main/FourElement.jsx @@ -57,6 +57,7 @@ const AnimateContainer_AU = styled.div` export default function FourElement({ fromRefLogoHome, scrollToAboutUs }) { + const navigate = useNavigate(); const [isProblemSolveHovered, setIsProblemSolveHovered] = useState(false); const [isCodeArenaHovered, setIsCodeArenaHovered] = useState(false); const [isCommunityHovered, setIsCommunityHovered] = useState(false); @@ -72,23 +73,18 @@ export default function FourElement({ fromRefLogoHome, scrollToAboutUs }) { } }; - const navigate = useNavigate(); - const handleCodeArenaClick = () => { navigate('/arena'); }; useEffect(() => { const handleScroll = () => { - console.log('스크롤 애니메이트 이벤트 발생 확인'); - // 특정 조건을 확인하여 animate 상태 토글 const shouldAnimate = window.scrollY < 1550 && window.scrollY > 450; setAnimate_PS(shouldAnimate); setAnimate_CA(shouldAnimate); }; - // 스크롤 이벤트 리스너 등록 + window.addEventListener('scroll', handleScroll); - // 클린업 함수에서 이벤트 리스너 제거 return () => { window.removeEventListener('scroll', handleScroll); }; @@ -96,15 +92,12 @@ export default function FourElement({ fromRefLogoHome, scrollToAboutUs }) { useEffect(() => { const handleScroll = () => { - console.log('스크롤 애니메이트 이벤트 발생 확인22'); - // 특정 조건을 확인하여 animate 상태 토글 const shouldAnimate = window.scrollY < 1550 && window.scrollY > 450; setAnimate_CM(shouldAnimate); setAnimate_AU(shouldAnimate); }; - // 스크롤 이벤트 리스너 등록 + window.addEventListener('scroll', handleScroll); - // 클린업 함수에서 이벤트 리스너 제거 return () => { window.removeEventListener('scroll', handleScroll); }; diff --git a/front-end/src/components/main/LogoHome.jsx b/front-end/src/components/main/LogoHome.jsx index d20d7146..c98834d9 100644 --- a/front-end/src/components/main/LogoHome.jsx +++ b/front-end/src/components/main/LogoHome.jsx @@ -35,7 +35,8 @@ const AnimateContainer = styled.div` `; export default function LogoHome({ scrollToFourElement }) { - const [animate, setAnimate] = useState(false); + const [animate, setAnimate] = useState(false); // 스크롤 애니메이트 상태 관리 + const handleLogoClick = () => { if (scrollToFourElement) { @@ -45,23 +46,19 @@ export default function LogoHome({ scrollToFourElement }) { useEffect(() => { const handleScroll = () => { - console.log('Scroll event 발생'); - // 특정 조건을 확인하여 animate 상태 토글 const shouldAnimate = window.scrollY < 700; setAnimate(shouldAnimate); }; - // 스크롤 이벤트 리스너 등록 - window.addEventListener('scroll', handleScroll); + window.addEventListener('scroll', handleScroll); // 스크롤 이벤트 리스너 등록 - // 클린업 함수에서 이벤트 리스너 제거 return () => { - window.removeEventListener('scroll', handleScroll); + window.removeEventListener('scroll', handleScroll); // 클린업 함수에서 이벤트 리스너 제거 }; }, []); + // 최초 렌더링 시 initial fade-in 애니메이션 적용 useEffect(() => { - // 최초 렌더링 시 initial fade-in 애니메이션 적용 setAnimate(true); }, []); @@ -79,7 +76,7 @@ export default function LogoHome({ scrollToFourElement }) { />

-

지금 배틀에 참여하세요!

+

지금 배틀에 참여하세요!

); } \ No newline at end of file diff --git a/front-end/src/components/main/Policy.jsx b/front-end/src/components/main/Policy.jsx index 47745f6c..9d11c472 100644 --- a/front-end/src/components/main/Policy.jsx +++ b/front-end/src/components/main/Policy.jsx @@ -1,28 +1,22 @@ import React from 'react'; import 'tailwindcss/tailwind.css'; - import ssafy from '../../images/main/Policy/ssafy.png'; -const ImageAndText = ({ image, title, children }) => ( -
- {title} -
-

{title}

-
-
{children}
+export default function Policy() { + const ImageAndText = ({ image, title }) => ( +
+ {title} +
+

삼성 전자 한마음프라자

+

경북 구미시 3공단3로 302 (임수동)

+

{title}

+
); -export default function Policy() { return (
-
-

- 삼성전자한마음프라자 -

-

- 경북 구미시 3공단3로 302 (임수동) -

+
diff --git a/front-end/src/components/main/Summary.jsx b/front-end/src/components/main/Summary.jsx index f0878ada..045a8ae1 100644 --- a/front-end/src/components/main/Summary.jsx +++ b/front-end/src/components/main/Summary.jsx @@ -1,35 +1,24 @@ import React, { useState, useEffect } from 'react'; import 'tailwindcss/tailwind.css'; import styled, { keyframes } from 'styled-components'; -import Rank from '../../images/main/Summary/Rank.png'; import Hand from '../../images/main/Summary/hand.png'; import Plus from '../../images/main/Summary/Plus.png'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; -// 스크롤 애니메이트 이벤트 1 +// 스크롤 애니메이트 이벤트 - 텍스트 const frameInAnimation_text = keyframes` 0% {opacity: 0; transform: translateY(100%);} 100%{opacity: 1; transform: translateY(0%);} `; + const AnimateContainer_text = styled.div` &.ease-out { animation: ${frameInAnimation_text} 1s forwards; } `; -// 스크롤 애니메이트 이벤트 2 -// const frameInAnimation_rank = keyframes` -// 0% {opacity: 0; transform: translateY(50%);} -// 100%{opacity: 1; transform: translateY(0%);} -// `; -// const AnimateContainer_rank = styled.div` -// &.ease-out { -// animation: ${frameInAnimation_rank} 1.2s forwards; -// } -// `; - -// 스크롤 애니메이트 이벤트 3 +// 스크롤 애니메이트 이벤트 - 인기 질문 const frameInAnimation_que = keyframes` 0% {opacity: 0; transform: translateY(50%);} 100%{opacity: 1; transform: translateY(0%);} @@ -40,11 +29,12 @@ const AnimateContainer_que = styled.div` } `; -// 스크롤 애니메이트 이벤트 4 +// 스크롤 애니메이트 이벤트 - 최근 추가된 문제 const frameInAnimation_add = keyframes` 0% {opacity: 0; transform: translateY(50%);} - 100%{opacity: 1; transform: translateY(0%);} + 100% {opacity: 1; transform: translateY(0%);} `; + const AnimateContainer_add = styled.div` &.ease-out { animation: ${frameInAnimation_add} 1.2s forwards; @@ -53,129 +43,111 @@ const AnimateContainer_add = styled.div` export default function Summary() { const navigate = useNavigate() - const [animate_text, setAnimate_text] = useState(false); - // const [animate_rank, setAnimate_rank] = useState(false); - const [animate_que, setAnimate_que] = useState(false); - const [animate_add, setAnimate_add] = useState(false); - const [problemNum,setProblemNum] = useState('') - - useEffect(() => { - axios.get('https://codearena.shop/api/problem?orderBy=date&cate=&word=&pgno=1&spp=6&tag=') - .then((res)=> { - console.log(res); - console.log(res.data.data.problemWithSearch) - - setaddProblemSolve(res.data.data.problemWithSearch) - }).catch((err)=> { - console.log(err); - }) - axios.get("https://codearena.shop/api/board/list?sortType=hit&key=&word=&langType=&pgno=1&spp=5") - .then((res)=> { - console.log(res); - setPopularQuestions(res.data.data.articles) - }).catch((err)=> { - console.log(err); - }) + const [animate_text, setAnimate_text] = useState(false); // 텍스트 애니메이트 상태 관리 + const [animate_que, setAnimate_que] = useState(false); // 최근 추가된 문제 애니메이트 상태 관리 + const [animate_add, setAnimate_add] = useState(false); // 질문 관련 애니메이트 상태 관리 + const [popularQuestions, setPopularQuestions] = useState([]); // 질문 카드 상태 관리 + const [addProblemSolve, setaddProblemSolve] = useState([]) // 최근 추가된 문제 상태 관리 - - const handleScroll = () => { - console.log('스크롤 애니메이트 이벤트 발생 확인'); - // 특정 조건을 확인하여 animate 상태 토글 - const shouldAnimate = window.scrollY < 2000 && window.scrollY > 1150; - setAnimate_text(shouldAnimate); - // setAnimate_rank(shouldAnimate); - setAnimate_que(shouldAnimate); - setAnimate_add(shouldAnimate); - }; - // 스크롤 이벤트 리스너 등록 - window.addEventListener('scroll', handleScroll); - // 클린업 함수에서 이벤트 리스너 제거 - return () => { - window.removeEventListener('scroll', handleScroll); - }; - }, []); + // 이미지 + 제목 + const ImageAndText = ({ image, title, children }) => ( + + {title} +
+

{title}

+
+
{children}
+
+ ); // 인기 질문 카드 const QuestionCard = ({ question }) => ( {navigate(`/community/${question.articleNo}/detail`) - window.scrollTo({top:0,behavior:'smooth'})}} - > + onClick={() => { + navigate(`/community/${question.articleNo}/detail`) + window.scrollTo({ top:0, behavior:'smooth' }) + }} + >

{question.title}

{question.content}

); - // 추가된 문제 카드 + // 최근 추가된 문제 카드 const ProblemCard = ({ problem }) => ( {navigate(`/problem/${problem.problemId}/detail`)}} + onClick={()=>{ + navigate(`/problem/${problem.problemId}/detail`) + }} > -

#{problem.problemId}

+

#{problem.problemId}

{problem.problemTitle}

); - // 이미지+제목 - const ImageAndText = ({ image, title, children }) => ( - - {title} -
-

{title}

-
-
{children}
-
- ); + useEffect(() => { + // 최근 추가된 문제 조회 + axios.get('https://codearena.shop/api/problem?orderBy=date&cate=&word=&pgno=1&spp=6&tag=') + .then + ((res)=> { + setaddProblemSolve(res.data.data.problemWithSearch) + }).catch + ((err)=> { + console.log(err); + }) - // 아레나 랭크 연동하여 수정필요 - // const ArenaRank = [ - // { title : '1', description: 'Username1'}, - // { title : '2', description: 'Username2'}, - // { title : '3', description: 'Username3'}, - // { title : '4', description: 'Username4'}, - // { title : '5', description: 'Username5'}, - // ] + // 질문 리스트 조회 + axios.get("https://codearena.shop/api/board/list?sortType=hit&key=&word=&langType=&pgno=1&spp=5") + .then + ((res)=> { + setPopularQuestions(res.data.data.articles) + }).catch + ((err)=> { + console.log(err); + }) - // 질문게시판과 연동하여 수정필요 - const [popularQuestions, setPopularQuestions] = useState([]); - // 문제페이지와 연동하여 수정 필요 - const [addProblemSolve, setaddProblemSolve] = useState([]) + // 사용자 스크롤 관련 애니메이트 조절 + const handleScroll = () => { + const shouldAnimate = window.scrollY < 2000 && window.scrollY > 1150; // 특정 조건을 확인하여 animate 상태 토글 + setAnimate_text(shouldAnimate); // 텍스트 관리 + setAnimate_que(shouldAnimate); // 질문 리스트 관리 + setAnimate_add(shouldAnimate); // 추가 문제 관리 + }; + window.addEventListener('scroll', handleScroll); // 스크롤 이벤트 리스너 등록 + return () => { + window.removeEventListener('scroll', handleScroll); // 이벤트 후에 클린업 함수에서 이벤트 리스너 제거 + }; + }, []); return (
- {/* Arena Rank */} - - {/* 구분선 */} -
-
-
- - {/* Popular Question */} - -
+ {/* 인기 질문 */} + +
{popularQuestions.map((question, index) => ( ))}
+ {/* 구분선 */} -
-
+
+
- {/* The Last Addtion */} - -
+ {/* 최근 추가된 문제 */} + +
{addProblemSolve.map((problem, index) => ( ))} diff --git a/front-end/src/components/navBar/navBar.jsx b/front-end/src/components/navBar/navBar.jsx index 26059678..f2bc3f4f 100644 --- a/front-end/src/components/navBar/navBar.jsx +++ b/front-end/src/components/navBar/navBar.jsx @@ -1,19 +1,14 @@ -import { useState, Fragment, useEffect } from 'react' -import { Link,useNavigate, useLocation } from 'react-router-dom' +import { useState, Fragment } from 'react' +import { Link, useNavigate} from 'react-router-dom' import { Disclosure, Menu, Transition } from '@headlessui/react' import { BellIcon } from '@heroicons/react/24/outline' import Logo from '../../images/common/logo.png' -import Profile from '../../images/common/profile.png' import { useSelector,useDispatch } from 'react-redux' import { logout } from '../../features/login/authSlice' -import axios from 'axios' import { setAccessToken } from '../../features/login/accessSlice' -import { error, get } from 'jquery' import swal from 'sweetalert' import '../css/dropdown.css' - - const navigation = [ { name: 'Problem', href: '/problem'}, { name: 'Arena', href: '/arena'}, @@ -21,158 +16,154 @@ const navigation = [ { name: 'Login', href: '/login'}, ] - function classNames(...classes) { return classes.filter(Boolean).join(' ') } export default function NavBar() { - const location = useLocation() + // const location = useLocation() const isLogin = useSelector(state => state.auth.isLogin); const nickName = useSelector(state => state.auth.userNickname); const profileImg = useSelector(state => state.auth.userThumbnail) const dispatch = useDispatch(); const navigate = useNavigate() - - useEffect(()=> { - console.log(location); - },[location]) const filterNav = isLogin ? navigation.filter(item => item.name != 'Login') : navigation; - + const handleLogout = ()=>{ dispatch(logout()); dispatch(setAccessToken(null)); swal("로그아웃되었습니다", "", "success"); navigate('/') } - + const [showDropdown,setShowDropdown ] = useState(false) + + // useEffect(()=> { + // console.log(location); + // }, [location]) return ( {({ open }) => ( <> -
-
-
- - CodaArena - -
-
-
- {filterNav.map((item) => ( -
- setShowDropdown(item.name ==='Problem' ? true : false)} - onMouseLeave={() => setShowDropdown(false)} - > - {item.name} - - {/* // 드롭다운 메뉴위치 */} - - {item.name === 'Problem' && showDropdown && ( -
setShowDropdown(true)} - onMouseLeave={() => setShowDropdown(false)} - > - {/* Submit */} - Category -
+
+
+
+ + CodaArena + +
+
+
+ {filterNav.map((item) => ( +
+ setShowDropdown(item.name ==='Problem' ? true : false)} + onMouseLeave={() => setShowDropdown(false)} + > + {item.name} + + {/* // 드롭다운 메뉴위치 */} + + {item.name === 'Problem' && showDropdown && ( +
setShowDropdown(true)} + onMouseLeave={() => setShowDropdown(false)} + > + {/* Submit */} + Category
- ))} - - {/* 벨아이콘 알림함 */} - { isLogin && ( - )} - {/* 프로필 드롭다운위치 */} - {isLogin && ( - -
- - - -
- + ))} + + {/* 벨아이콘 알림함 */} + { isLogin && ( + + )} + {/* 프로필 드롭다운 위치 */} + {isLogin && ( + +
+ + + +
+ + + + {({ active }) => ( + + {nickName}님 환영합니다 + + )} + - - {({ active }) => ( - - Sign out - - )} - - - -
- )} -
+ + + {({ active }) => ( + + Profile + + )} + + + + + {({ active }) => ( + + Sign out + + )} + + + + + )}
-
+
diff --git a/front-end/src/features/useAuthCheck.js b/front-end/src/features/useAuthCheck.js index e6d0d8d2..85e36ca6 100644 --- a/front-end/src/features/useAuthCheck.js +++ b/front-end/src/features/useAuthCheck.js @@ -23,10 +23,10 @@ export function useAuthCheck() { const authCheck = async () => { try{ let value = await checkAccess(accessToken) - console.log(value); + // console.log(value); if (value.data.status === '302') { let value2 = await auseRefresh() - console.log(value2); + // console.log(value2); if (value2.data.status === '200') { dispatch(setAccessToken(value2.headers.authorization)) await checkAccess(value2.headers.authorization) diff --git a/front-end/src/index.css b/front-end/src/index.css index 7927bb23..0f8d85c3 100644 --- a/front-end/src/index.css +++ b/front-end/src/index.css @@ -3,7 +3,7 @@ @tailwind utilities; #root { - min-height: 735px; + min-height: 860px; margin: 0px; } @@ -13,7 +13,7 @@ body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-color: #F4F5F1; - min-height: 735px; + min-height: 860px; } /* code { diff --git a/front-end/src/pages/arena/match/index.jsx b/front-end/src/pages/arena/match/index.jsx index 720c9be9..27152567 100644 --- a/front-end/src/pages/arena/match/index.jsx +++ b/front-end/src/pages/arena/match/index.jsx @@ -2,11 +2,10 @@ import GroupList from "../../../components/arena/match/GroupList"; import CompetitionList from "../../../components/arena/match/CompetitionList"; export default function GameList() { - - return ( -
- - -
- ); + return ( +
+ + +
+ ); } \ No newline at end of file diff --git a/front-end/src/pages/community/detail/index.jsx b/front-end/src/pages/community/detail/index.jsx index 2308be20..6a563a8b 100644 --- a/front-end/src/pages/community/detail/index.jsx +++ b/front-end/src/pages/community/detail/index.jsx @@ -1,5 +1,5 @@ import { useNavigate, useParams } from "react-router-dom" -import { useState,useEffect,useCallback,useRef} from "react" +import { useState, useEffect, useCallback, useRef } from "react" import axios from "axios" import "../../css/problemdetail.css" import Editor from "@monaco-editor/react" @@ -11,128 +11,140 @@ import Pencil from '../../../images/common/pencil.png' -export default function CommunityDetail(){ +export default function CommunityDetail() { const monaco = useMonaco() const accessToken = useSelector(state => state.access.accessToken) - const [bgcolor,setBgcolor] = useState('#F4F2CA'); - const [showCodeMirror, setShowCodeMirror] = useState(true) + const [bgcolor, setBgcolor] = useState('#F4F2CA'); + const [showCodeMirror, setShowCodeMirror] = useState(false) + const [bgcolor2, setBgcolor2] = useState('#F4F2CA'); + const [showCodeMirrorComment, setShowCodeMirrorComment] = useState(false) const params = useParams(); const boardId = params.communityId const userId = useSelector(state => state.auth.userId) - const [articleId,setArticleId] = useState('') - const [board,setBoard] = useState({}) + const [articleId, setArticleId] = useState('') + const [board, setBoard] = useState({}) const navigate = useNavigate() - const [cate,setCate] = useState('') - const catedic = {'1':'질문','2':'시간복잡도','3':'공간복잡도','4':'반례 요청','5':'반례',} - const [comment,setComment] = useState('') - const [commentcode,setCommentCode] = useState('') - const [commentlist,setCommentList] = useState([]) - const [articleNickname,setArticleNickname] = useState('') + const [cate, setCate] = useState('') + const catedic = { '1': '질문', '2': '시간복잡도', '3': '공간복잡도', '4': '반례 요청', '5': '반례', } + const [comment, setComment] = useState('') + const [commentcode, setCommentCode] = useState('') + const [commentlist, setCommentList] = useState([]) + const [articleNickname, setArticleNickname] = useState('') - const colorChange = () =>{ - if (bgcolor === '#F4F2CA'){ + const colorChange = () => { + if (bgcolor === '#F4F2CA') { setBgcolor('#ffffff') setShowCodeMirror(true) - }else { + } else { setBgcolor('#F4F2CA') setShowCodeMirror(false) } } + const colorChange2 = () => { + if (bgcolor2 === '#F4F2CA') { + setBgcolor2('#ffffff') + setShowCodeMirrorComment(true) + } else { + setBgcolor2('#F4F2CA') + setShowCodeMirrorComment(false) + } + } + // 게시글상세조회 - useEffect(()=>{ + useEffect(() => { axios({ - url : `https://codearena.shop/api/board/detail/${boardId}`, - method : 'get', - headers : { - Authorization : accessToken + url: `https://codearena.shop/api/board/detail/${boardId}`, + method: 'get', + headers: { + Authorization: accessToken } }) - .then((res)=>{ - console.log(res.data.data) - console.log(res.data.data.spoiler) - console.log(res.data.data.isSolved) - - if (res.data.data.spoiler === 1) { - setShowCodeMirror(false) - if (res.data.data.isSolved === '1') { - setShowCodeMirror(true) - } else { + .then((res) => { + console.log(res.data.data) + console.log(res.data.data.spoiler) + console.log(res.data.data.isSolved) + + if (res.data.data.spoiler === 1) { setShowCodeMirror(false) + if (res.data.data.isSolved === '1') { + setShowCodeMirror(true) + } else { + setShowCodeMirror(false) + } } - } - - setBoard(res.data.data) - setCate(catedic[res.data.data.type]) - setArticleId(res.data.data.userId) - setArticleNickname(res.data.data.nickName) - }) - .catch((err)=>{ - console.log(err) - }) - - },[]) + + setBoard(res.data.data) + setCate(catedic[res.data.data.type]) + setArticleId(res.data.data.userId) + setArticleNickname(res.data.data.nickName) + }) + .catch((err) => { + console.log(err) + }) + + }, []) // 게시글삭제 - const boardDelete = ()=>{ + const boardDelete = () => { axios({ - url : `https://codearena.shop/api/board/delete/${boardId}`, - method : 'delete' - }) - .then((res)=>{ - console.log(res) - swal("게시글이 삭제완료","","success") - navigate('/community') - }) - .catch((err)=>{ - console.log(err) + url: `https://codearena.shop/api/board/delete/${boardId}`, + method: 'delete' }) + .then((res) => { + console.log(res) + swal("게시글이 삭제완료", "", "success") + navigate('/community') + }) + .catch((err) => { + console.log(err) + }) } //댓글작성 (댓글작성 후 새로고침되야함) - const createComment = () =>{ + const createComment = () => { axios({ - url : 'https://codearena.shop/api/comment/write', - method : 'post', - data : { - articleNo : boardId, - userId : userId, - comment : comment, - code : commentcode + url: 'https://codearena.shop/api/comment/write', + method: 'post', + data: { + articleNo: boardId, + userId: userId, + comment: comment, + code: commentcode } }) - .then((res)=>{ - console.log(res) - window.location.reload(); - }) - .catch((err)=>{ - console.log(err) - }) + .then((res) => { + console.log(res) + window.location.reload(); + }) + .catch((err) => { + console.log(err) + }) } //댓글 목록조회 - useEffect(()=>{ + useEffect(() => { axios({ - method : 'get', - url : `https://codearena.shop/api/comment/list?articleNo=${boardId}`, - }) - .then((res)=> { - console.log(res) - // console.log(res.data.data); - setCommentList(res.data.data) + method: 'get', + url: `https://codearena.shop/api/comment/list?articleNo=${boardId}`, }) - .catch((err)=> { - console.log(err); - }) - },[]) - + .then((res) => { + console.log(res) + // console.log(res.data.data); + setCommentList(res.data.data) + }) + .catch((err) => { + console.log(err); + }) + }, []) + const onDelete = (id) => { - const tmpArr = commentlist.filter((el)=>el.commentId !== id) + const tmpArr = commentlist.filter((el) => el.commentId !== id) setCommentList(tmpArr) // tmpArr에는 각요소들의 commentId와 id가 다른 요소들로만 이루어진 배열이됨 } - const goEdit = () =>{ + const goEdit = () => { navigate((`/community/${boardId}/edit`)); window.scrollTo(0, 0); } @@ -140,11 +152,11 @@ export default function CommunityDetail(){ const onChangeCode = useCallback((code, viewUpdate) => { setCommentCode(code); }, []); - - const goUp = () =>{ + + const goUp = () => { window.scrollTo({ - top : 0, - behavior : "smooth" + top: 0, + behavior: "smooth" }) } @@ -158,148 +170,185 @@ export default function CommunityDetail(){ }); } }, [monaco, bgcolor]); // monaco와 bgcolor가 변경될 때마다 테마를 다시 설정합니다. - + return (
- -

맨위로

-
- -
-
- + +

+ 맨위로 +

+
+ -
- -
+ + {/* 제목 */} +
+
+ + {/* 제목 input */} +
+ +
+
-
-
- - +
+
+ +
- - + +
- - + +
-
-
- -
-
+ {/* 내용 */} +
+ +
- -
-
-
-
- - - - {/* 댓글 모달창 */} - -
-
- -
+
+ + + {/* 댓글 모달창 */} + +
+
+ +
+
+ +
+ {showCodeMirrorComment && (
-
-
-
-
-
-
-
- -
-
+ >댓글작성
+ +
+ +
-
-
-
+
+
- { showCodeMirror && ( -
-
-
- +
+
-
)} - { articleId === userId &&( -
- - -
-
+ {articleId === userId && ( +
+ + +
)} -
- {/* 댓글 */} - +
+ {/* 댓글 */} + {commentlist.length > 0 && ( - commentlist.map((comment,index)=>{ - return( - - )}) + commentlist.map((comment, index) => { + return ( + + ) + }) )} {commentlist.length === 0 && ( -
+

댓글이 없습니다

@@ -307,7 +356,7 @@ export default function CommunityDetail(){
) - + } diff --git a/front-end/src/pages/main/index.jsx b/front-end/src/pages/main/index.jsx index ca7f67b7..04536c35 100644 --- a/front-end/src/pages/main/index.jsx +++ b/front-end/src/pages/main/index.jsx @@ -6,7 +6,6 @@ import Summary from '../../components/main/Summary'; import AboutUs from '../../components/main/AboutUs'; import Policy from '../../components/main/Policy'; - export default function Main() { const fromRefLogoHome = useRef(null); const fromRefFourElement = useRef(null); @@ -26,7 +25,7 @@ export default function Main() { }; return ( -
+
diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..c1f0889f --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "CodeArena", + "lockfileVersion": 3, + "requires": true, + "packages": {} +}