diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..02565e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +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/ +/src/main/resources/application.yml diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..0e2ec78 --- /dev/null +++ b/build.gradle @@ -0,0 +1,44 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.5' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'Journey' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'mysql:mysql-connector-java:8.0.32' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'org.springframework.boot:spring-boot-starter-actuator' + runtimeOnly 'com.mysql:mysql-connector-j' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // S3 AWS + implementation("software.amazon.awssdk:bom:2.21.0") + implementation("software.amazon.awssdk:s3:2.21.0") + implementation 'org.apache.httpcomponents:httpclient:4.5.13' + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..2c56130 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Together' diff --git a/src/main/java/Journey/Together/ServerApplication.java b/src/main/java/Journey/Together/ServerApplication.java new file mode 100644 index 0000000..4de1c8a --- /dev/null +++ b/src/main/java/Journey/Together/ServerApplication.java @@ -0,0 +1,13 @@ +package Journey.Together; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerApplication.class, args); + } + +} diff --git a/src/main/java/Journey/Together/common/dto/ApiResponse.java b/src/main/java/Journey/Together/common/dto/ApiResponse.java new file mode 100644 index 0000000..25edee1 --- /dev/null +++ b/src/main/java/Journey/Together/common/dto/ApiResponse.java @@ -0,0 +1,36 @@ +package Journey.Together.common.dto; + +import Journey.Together.exception.Error; +import Journey.Together.exception.Success; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class ApiResponse { + + private final int code; + private final String message; + private T data; + + + public static ApiResponse success(Success success){ + return new ApiResponse<>(success.getHttpStatusCode(), success.getMessage()); + } + + public static ApiResponse success(Success success, T data){ + return new ApiResponse(success.getHttpStatusCode(), success.getMessage(), data); + } + + public static ApiResponse error(Error error){ + return new ApiResponse<>(error.getErrorCode(), error.getMessage()); + } + + public static ApiResponse error(Error error, String message){ + return new ApiResponse<>(error.getErrorCode(), message); + } +} diff --git a/src/main/java/Journey/Together/domain/BaseTimeEntity.java b/src/main/java/Journey/Together/domain/BaseTimeEntity.java new file mode 100644 index 0000000..3cb424a --- /dev/null +++ b/src/main/java/Journey/Together/domain/BaseTimeEntity.java @@ -0,0 +1,25 @@ +package Journey.Together.domain; + + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@MappedSuperclass +@Getter +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseTimeEntity { + + @CreatedDate // 현재시각으로 초기화해줌 + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime updateAt; + + +} diff --git a/src/main/java/Journey/Together/exception/Error.java b/src/main/java/Journey/Together/exception/Error.java new file mode 100644 index 0000000..7994c59 --- /dev/null +++ b/src/main/java/Journey/Together/exception/Error.java @@ -0,0 +1,53 @@ +package Journey.Together.exception; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public enum Error { + + /** + * 404 NOT FOUND + */ + NOT_FOUND(HttpStatus.NOT_FOUND, "찾을 수 없습니다."), + + /** + * 400 BAD REQUEST EXCEPTION + */ + BAD_REQUEST_VALIDATION(HttpStatus.BAD_REQUEST, "유효한 값으로 요청을 다시 보내주세요."), + + + /** + * 401 UNAUTHORIZED EXCEPTION + */ + TOKEN_TIME_EXPIRED_EXCEPTION(HttpStatus.UNAUTHORIZED, "만료된 토큰입니다."), + EXPIRED_APPLE_IDENTITY_TOKEN(HttpStatus.UNAUTHORIZED, "만료된 아이덴티티 토큰입니다."), + + /** + * 403 FORBIDDEN EXCEPTION + */ + UNAUTHORIZED_ACCESS(HttpStatus.FORBIDDEN, "리소스에 대한 권한이 없습니다."), + INVALID_USER_ACCESS(HttpStatus.FORBIDDEN, "접근 권한이 없는 유저입니다."), + + /** + * 422 UNPROCESSABLE_ENTITY + */ + UNPROCESSABLE_ENTITY_DELETE_EXCEPTION(HttpStatus.UNPROCESSABLE_ENTITY, "서버에서 요청을 이해해 삭제하려는 도중 문제가 생겼습니다."), + + + /** + * 500 INTERNAL_SERVER_ERROR + */ + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "알 수 없는 서버 에러가 발생했습니다"), + ; + + private final HttpStatus httpStatus; + private final String message; + + public int getErrorCode() { + return httpStatus.value(); + } +} diff --git a/src/main/java/Journey/Together/exception/Success.java b/src/main/java/Journey/Together/exception/Success.java new file mode 100644 index 0000000..d0538b1 --- /dev/null +++ b/src/main/java/Journey/Together/exception/Success.java @@ -0,0 +1,69 @@ +package Journey.Together.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum Success { + + /** + * 201 CREATED + */ + CREATE_TOAST_SUCCESS(HttpStatus.CREATED, "토스트 저장이 완료 되었습니다."), + CREATE_CATEGORY_SUCCESS(HttpStatus.CREATED, "새 카테고리 추가 성공"), + CREATE_TIMER_SUCCESS(HttpStatus.CREATED, "새 타이머 생성 성공"), + + /** + * 200 OK + */ + GET_USER_MAIN_SUCCESS(HttpStatus.OK, "메인 페이지 유저 정보 조회 성공"), + GET_MYPAGE_SUCCESS(HttpStatus.OK, "마이 페이지 조회 성공"), + GET_LINKS_SUCCESS(HttpStatus.OK, "이주의 링크 조회 성공"), + GET_SITES_SUCCESS(HttpStatus.OK, "추천 사이트 조회 성공"), + GET_SETTINGS_SUCCESS(HttpStatus.OK, "설정 페이지 조회 성공"), + + GET_CATEORIES_SUCCESS(HttpStatus.OK, "전체 카테고리 조회 성공"), + GET_CATEORY_SUCCESS(HttpStatus.OK, "세부 카테고리 조회 성공"), + GET_TIMER_SUCCESS(HttpStatus.OK, "타이머 조회 성공"), + GET_TIMER_PAGE_SUCCESS(HttpStatus.OK, "타이머 페이지 조회 성공"), + GET_DUPLICATED_SUCCESS(HttpStatus.OK, "중복 여부 체크 성공"), + + LOGIN_SUCCESS(HttpStatus.OK, "로그인 성공"), + RE_ISSUE_TOKEN_SUCCESS(HttpStatus.OK, "토큰 재발급 성공"), + SIGNOUT_SUCCESS(HttpStatus.OK, "로그아웃 성공"), + DELETE_USER_SUCCESS(HttpStatus.OK, "회원 탈퇴가 정상적으로 이루어졌습니다."), + DELETE_TOAST_SUCCESS(HttpStatus.OK, "토스트 삭제 성공"), + DELETE_CATEGORY_SUCCESS(HttpStatus.OK, "카테고리 삭제 성공"), + DELETE_TIMER_SUCCESS(HttpStatus.OK, "타이머 삭제 성공"), + SEARCH_SUCCESS(HttpStatus.OK, "검색 성공"), + PARSING_OG_SUCCESS(HttpStatus.OK, "og 데이터 파싱 결과입니다. 크롤링을 막은 페이지는 기본이미지가 나옵니다."), + UPDATE_PUSH_ALLOWED_SUCCESS(HttpStatus.OK, "푸시알림 수정 성공"), + UPDATE_TOAST_TITLE_SUCCESS(HttpStatus.OK, "토스트 제목 수정 성공"), + + UPDATE_ISREAD_SUCCESS(HttpStatus.OK, "열람여부 수정 완료"), + UPDATE_CATEGORY_TITLE_SUCCESS(HttpStatus.OK, "카테고리 수정 완료"), + UPDATE_TIMER_DATETIME_SUCCESS(HttpStatus.OK, "타이머 시간/날짜 수정 완료"), + UPDATE_TIMER_COMMENT_SUCCESS(HttpStatus.OK, "타이머 코멘트 수정 완료"), + CHANGE_TIMER_ALARM_SUCCESS(HttpStatus.OK, "타이머 알람여부 수정 완료"), + PUSH_ALARM_PERIODIC_SUCCESS(HttpStatus.OK, "푸시알림 활성에 성공했습니다."), + PUSH_ALARM_SUCCESS(HttpStatus.OK, "푸시알림 전송에 성공했습니다."), + CLEAR_SCHEDULED_TASKS_SUCCESS(HttpStatus.OK, "스케줄러에서 예약된 작업을 제거했습니다."), + + + /** + * 204 NO_CONTENT + */ + SEARCH_SUCCESS_BUT_IS_EMPTY(HttpStatus.NO_CONTENT, "검색에 성공했지만 조회된 내용이 없습니다.") + + ; + + private final HttpStatus httpStatus; + private final String message; + + public int getHttpStatusCode(){ + return httpStatus.value(); + } + +} diff --git a/src/main/java/Journey/Together/exception/model/BadRequestException.java b/src/main/java/Journey/Together/exception/model/BadRequestException.java new file mode 100644 index 0000000..5cbfeac --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/BadRequestException.java @@ -0,0 +1,9 @@ +package Journey.Together.exception.model; + +import Journey.Together.exception.Error; +public class BadRequestException extends CustomException{ + public BadRequestException(Error error, String message) { + super(error, message); + } + +} diff --git a/src/main/java/Journey/Together/exception/model/CustomException.java b/src/main/java/Journey/Together/exception/model/CustomException.java new file mode 100644 index 0000000..e475bab --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/CustomException.java @@ -0,0 +1,18 @@ +package Journey.Together.exception.model; + +import lombok.Getter; +import Journey.Together.exception.Error; + +@Getter +public class CustomException extends RuntimeException{ + private final Error error; + + public CustomException(Error error, String message) { + super(message); + this.error = error; + } + + public int getHttpStatus() { + return error.getErrorCode(); + } +} diff --git a/src/main/java/Journey/Together/exception/model/ForbiddenException.java b/src/main/java/Journey/Together/exception/model/ForbiddenException.java new file mode 100644 index 0000000..8fed0a5 --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/ForbiddenException.java @@ -0,0 +1,10 @@ +package Journey.Together.exception.model; + +import Journey.Together.exception.Error; + +public class ForbiddenException extends CustomException{ + public ForbiddenException(Error error, String message) { + super(error, message); + } + +} \ No newline at end of file diff --git a/src/main/java/Journey/Together/exception/model/NotFoundException.java b/src/main/java/Journey/Together/exception/model/NotFoundException.java new file mode 100644 index 0000000..b8386f0 --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/NotFoundException.java @@ -0,0 +1,8 @@ +package Journey.Together.exception.model; + +import Journey.Together.exception.Error; +public class NotFoundException extends CustomException { + public NotFoundException(Error error, String message) { + super(error, message); + } +} diff --git a/src/main/java/Journey/Together/exception/model/UnauthorizedException.java b/src/main/java/Journey/Together/exception/model/UnauthorizedException.java new file mode 100644 index 0000000..89724b6 --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/UnauthorizedException.java @@ -0,0 +1,9 @@ +package Journey.Together.exception.model; + +import Journey.Together.exception.Error; +public class UnauthorizedException extends CustomException{ + public UnauthorizedException(Error error, String message) { + super(error, message); + } + +} diff --git a/src/main/java/Journey/Together/exception/model/UnprocessableEntityException.java b/src/main/java/Journey/Together/exception/model/UnprocessableEntityException.java new file mode 100644 index 0000000..d7b4a17 --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/UnprocessableEntityException.java @@ -0,0 +1,9 @@ +package Journey.Together.exception.model; + +import Journey.Together.exception.Error; + +public class UnprocessableEntityException extends CustomException{ + public UnprocessableEntityException(Error error, String message) { + super(error, message); + } +} diff --git a/src/main/java/Journey/Together/exception/model/net/CustomJavaNetException.java b/src/main/java/Journey/Together/exception/model/net/CustomJavaNetException.java new file mode 100644 index 0000000..55310d2 --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/net/CustomJavaNetException.java @@ -0,0 +1,21 @@ +package Journey.Together.exception.model.net; + +import lombok.Getter; + +import java.io.IOException; +import Journey.Together.exception.Error; + +@Getter +public class CustomJavaNetException extends IOException { + private final Error error; + + public CustomJavaNetException(Error error, String message) { + super(message); + this.error = error; + } + + public int getHttpStatus() { + return error.getErrorCode(); + } + +} diff --git a/src/main/java/Journey/Together/exception/model/net/UnknownHostException.java b/src/main/java/Journey/Together/exception/model/net/UnknownHostException.java new file mode 100644 index 0000000..7fb08af --- /dev/null +++ b/src/main/java/Journey/Together/exception/model/net/UnknownHostException.java @@ -0,0 +1,8 @@ +package Journey.Together.exception.model.net; +import Journey.Together.exception.Error; +public class UnknownHostException extends CustomJavaNetException { + public UnknownHostException(Error error, String message) { + super(error, message); + } + +} diff --git a/src/main/java/Journey/Together/external/aws/AWSConfig.java b/src/main/java/Journey/Together/external/aws/AWSConfig.java new file mode 100644 index 0000000..3286735 --- /dev/null +++ b/src/main/java/Journey/Together/external/aws/AWSConfig.java @@ -0,0 +1,57 @@ +package Journey.Together.external.aws; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; + +@Configuration +public class AWSConfig { + + private static final String AWS_ACCESS_KEY_ID = "aws.accessKeyId"; + private static final String AWS_SECRET_ACCESS_KEY = "aws.secretAccessKey"; + + private final String accessKey; + private final String secretKey; + private final String regionString; + + public AWSConfig(@Value("${aws-property.access-key}") final String accessKey, + @Value("${aws-property.secret-key}") final String secretKey, + @Value("${aws-property.aws-region}") final String regionString) { + this.accessKey = accessKey; + this.secretKey = secretKey; + this.regionString = regionString; + } + + + @Bean + public SystemPropertyCredentialsProvider systemPropertyCredentialsProvider() { + System.setProperty(AWS_ACCESS_KEY_ID, accessKey); + System.setProperty(AWS_SECRET_ACCESS_KEY, secretKey); + return SystemPropertyCredentialsProvider.create(); + } + + @Bean + public Region getRegion() { + return Region.of(regionString); + } + + @Bean + public S3Client getS3Client() { + return S3Client.builder() + .region(getRegion()) + .credentialsProvider(systemPropertyCredentialsProvider()) + .build(); + } + + @Bean + public S3Presigner getS3Presigner() { + return S3Presigner.builder() + .region(getRegion()) + .credentialsProvider(systemPropertyCredentialsProvider()) + .build(); + } +} diff --git a/src/main/java/Journey/Together/external/aws/ImagePresignedUrlResponse.java b/src/main/java/Journey/Together/external/aws/ImagePresignedUrlResponse.java new file mode 100644 index 0000000..1968400 --- /dev/null +++ b/src/main/java/Journey/Together/external/aws/ImagePresignedUrlResponse.java @@ -0,0 +1,7 @@ +package Journey.Together.external.aws; + +public record ImagePresignedUrlResponse(String fileName, String preSignedUrl) { + public static ImagePresignedUrlResponse of(String fileName, String url){ + return new ImagePresignedUrlResponse(fileName, url); + } +} diff --git a/src/main/java/Journey/Together/external/aws/PresignedUrlVO.java b/src/main/java/Journey/Together/external/aws/PresignedUrlVO.java new file mode 100644 index 0000000..2443532 --- /dev/null +++ b/src/main/java/Journey/Together/external/aws/PresignedUrlVO.java @@ -0,0 +1,7 @@ +package Journey.Together.external.aws; + +public record PresignedUrlVO(String fileName, String url) { + public static PresignedUrlVO of(String fileName, String url){ + return new PresignedUrlVO(fileName, url); + } +} diff --git a/src/main/java/Journey/Together/external/aws/S3Service.java b/src/main/java/Journey/Together/external/aws/S3Service.java new file mode 100644 index 0000000..5f85f65 --- /dev/null +++ b/src/main/java/Journey/Together/external/aws/S3Service.java @@ -0,0 +1,188 @@ +package Journey.Together.external.aws; + +import Journey.Together.exception.Error; +import Journey.Together.exception.model.BadRequestException; +import Journey.Together.exception.model.CustomException; +import Journey.Together.exception.model.NotFoundException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetUrlRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; + +import java.io.IOException; +import java.net.URL; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Component +@Slf4j +public class S3Service { + private final String bucketName; + private final AWSConfig awsConfig; + + private static final Long MAX_FILE_SIZE = 5 * 1024 * 1024L; + private static final Long PRE_SIGNED_URL_EXPIRE_MINUTE = 1L; + + + + public S3Service(@Value("${aws-property.s3-bucket-name}") final String bucketName, AWSConfig awsConfig) { + this.bucketName = bucketName; + this.awsConfig = awsConfig; + } + + public String uploadImage(MultipartFile multipartFile, String folder) { + final String key = folder + createFileName(multipartFile.getOriginalFilename()); + final S3Client s3Client = awsConfig.getS3Client(); + + validateFileSize(multipartFile); + + PutObjectRequest request = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .contentType(multipartFile.getContentType()) + .contentLength(multipartFile.getSize()) + .contentDisposition("inline") + .build(); + + try { + RequestBody requestBody = RequestBody.fromBytes(multipartFile.getBytes()); + s3Client.putObject(request, requestBody); + return key; + } catch(IOException e) { + throw new NotFoundException(Error.NOT_FOUND_IMAGE_EXCEPTION, Error.NOT_FOUND_IMAGE_EXCEPTION.getMessage()); + } + } + + + public List uploadImages(List multipartFileList, String folder) { + final S3Client s3Client = awsConfig.getS3Client(); + List list = new ArrayList<>(); + for (int i = 0; i < multipartFileList.size(); i++) { + String key = folder + createFileName(multipartFileList.get(i).getOriginalFilename()); + PutObjectRequest request = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .contentType(multipartFileList.get(i).getContentType()) + .contentLength(multipartFileList.get(i).getSize()) + .contentDisposition("inline") + .build(); + + try { + RequestBody requestBody = RequestBody.fromBytes(multipartFileList.get(i).getBytes()); + s3Client.putObject(request, requestBody); + list.add(key); + } catch(IOException e) { + throw new NotFoundException(Error.NOT_FOUND_IMAGE_EXCEPTION, Error.NOT_FOUND_IMAGE_EXCEPTION.getMessage()); + } + } + return list; + } + + // 파일명 (중복 방지) + private String createFileName(String fileName) { + return UUID.randomUUID().toString().concat(getFileExtension(fileName)); + } + + // 파일 유효성 검사 + private String getFileExtension(String fileName) { + if (fileName.length() == 0) { + throw new NotFoundException(Error.NOT_FOUND_IMAGE_EXCEPTION, Error.NOT_FOUND_IMAGE_EXCEPTION.getMessage()); + } + ArrayList fileValidate = new ArrayList<>(); + fileValidate.add(".jpg"); + fileValidate.add(".jpeg"); + fileValidate.add(".png"); + fileValidate.add(".JPG"); + fileValidate.add(".JPEG"); + fileValidate.add(".PNG"); + System.out.println("여기여기기"); + String idxFileName = fileName.substring(fileName.lastIndexOf(".")); + if (!fileValidate.contains(idxFileName)) { + throw new BadRequestException(Error.BAD_REQUEST_FILE_EXTENSION, Error.BAD_REQUEST_FILE_EXTENSION.getMessage()); + } + System.out.println("여기기기기기ㅣ기"); + return fileName.substring(fileName.lastIndexOf(".")); + } + + // 이미지 삭제 + public void deleteImage(String key) throws IOException { + final S3Client s3Client = awsConfig.getS3Client(); + + s3Client.deleteObject((DeleteObjectRequest.Builder builder) -> + builder.bucket(bucketName) + .key(key) + .build() + ); + } + + public void deleteImages(List keys) throws IOException{ + final S3Client s3Client = awsConfig.getS3Client(); + for (String key : keys) { + s3Client.deleteObject((DeleteObjectRequest.Builder builder) -> + builder.bucket(bucketName) + .key(key) + .build() + ); + } + } + + private void validateFileSize(MultipartFile image) { + if (image.getSize() > MAX_FILE_SIZE) { + throw new BadRequestException(Error.BAD_REQUEST_FILE_SIZE, Error.BAD_REQUEST_FILE_SIZE.getMessage()); + } + } + + // 만료시간 1분 + + public PresignedUrlVO getUploadPreSignedUrl(final String filename, final String folder) { + final String fileName = createFileName(filename); + final String key = folder + fileName; + System.out.println("하이"); + log.info(fileName); + log.info(key); + + S3Presigner preSigner = awsConfig.getS3Presigner(); + + PutObjectRequest putObjectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + log.info("-----"); + PutObjectPresignRequest preSignedUrlRequest = PutObjectPresignRequest.builder() + .signatureDuration(Duration.ofMinutes(PRE_SIGNED_URL_EXPIRE_MINUTE)) + .putObjectRequest(putObjectRequest) + .build(); + log.info("-----"); + String url = preSigner.presignPutObject(preSignedUrlRequest).url().toString(); + + return PresignedUrlVO.of(fileName, url); + } + + public String getURL(String keyName) { + final S3Client s3Client = awsConfig.getS3Client(); + try { + GetUrlRequest request = GetUrlRequest.builder() + .bucket(bucketName) + .key(keyName) + .build(); + + URL url = s3Client.utilities().getUrl(request); + System.out.println("The URL for "+keyName +" is "+ url); + return "The URL for "+keyName +" is "+ url; + + } catch (S3Exception e) { + throw new CustomException(Error.UNPROCESSABLE_PRESIGNEDURL_EXCEPTION, Error.UNPROCESSABLE_PRESIGNEDURL_EXCEPTION.getMessage()); + // Exception을 뿌려준다!! 사진 제대로 안 올라갔으니까 다시 올려라 ... + } + } +} diff --git a/src/test/java/Journey/Together/ServerApplicationTests.java b/src/test/java/Journey/Together/ServerApplicationTests.java new file mode 100644 index 0000000..1be6924 --- /dev/null +++ b/src/test/java/Journey/Together/ServerApplicationTests.java @@ -0,0 +1,13 @@ +package Journey.Together; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ServerApplicationTests { + + @Test + void contextLoads() { + } + +}