diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..869d741f --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ +.idea + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..668101a2 --- /dev/null +++ b/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group = 'com.sprint.mission' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation platform('org.junit:junit-bom:5.10.0') + testImplementation 'org.junit.jupiter:junit-jupiter' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..097e6523 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu May 29 10:24:19 KST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..1b6c7873 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..107acd32 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..84879dca --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = '1-sprint-mission' \ No newline at end of file diff --git a/src/main/java/com/sprint/mission/discodeit/JavaApplication.java b/src/main/java/com/sprint/mission/discodeit/JavaApplication.java new file mode 100644 index 00000000..044d60a7 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/JavaApplication.java @@ -0,0 +1,196 @@ +package com.sprint.mission.discodeit; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.service.ChannelService; + +import com.sprint.mission.discodeit.service.JCF.JCFChannelService; +import com.sprint.mission.discodeit.service.JCF.JCFMessageService; +import com.sprint.mission.discodeit.service.JCF.JCFUserService; +import com.sprint.mission.discodeit.service.MessageService; +import com.sprint.mission.discodeit.service.UserService; +import com.sprint.mission.discodeit.service.factory.JCFServiceFactory; + +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class JavaApplication { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + JCFServiceFactory factory = new JCFServiceFactory(); + UserService userService = factory.createUserService(); + MessageService messageService = factory.createMessageService(); + ChannelService channelService = factory.createChannelService(); + + try { + userService.registUser("홍길동"); + userService.registUser("토마스"); + userService.registUser("김첨지"); + channelService.registChannel("채널 1"); + channelService.registChannel("채널 2"); + channelService.registChannel("채널 3"); + + System.out.println("----모든 유저 출력---- "); + for (User u : userService.findUserByName("*")) { + //* 입력시 모든 유저 출력 + userService.showUserInfo(u); + } + + System.out.println(); + System.out.println("----이름이 \"홍길동\"인 유저 출력---- "); + userService.showUserInfo(userService.findUserByName("홍길동").get(0)); + + System.out.println(); + System.out.println("----\"홍길동\"의 계정 삭제 후 모든 유저 출력---- "); + userService.deleteUser(userService.findUserByName("홍길동").get(0).getUserId()); + for (User u : userService.findUserByName("*")) { + userService.showUserInfo(u); + } + + System.out.println(); + System.out.println("----모든 채널 출력----"); + for(Channel c : channelService.findChannelByName("*")) { + channelService.showChannelInfo(c); + } + + System.out.println(); + System.out.println("----\"채널 2\" 이름 \"새 채널 2\"로 변경 후 모든 채널 출력----"); + channelService.updateChannelName(channelService.findChannelByName("채널 2").get(0).getChannelId(),"새 채널 2"); + for(Channel c : channelService.findChannelByName("*")) { + channelService.showChannelInfo(c); + } + + + System.out.println(); + System.out.println("----\"새 채널 2\" 삭제 후 모든 채널 출력----"); + channelService.deleteChannel(channelService.findChannelByName("새 채널 2").get(0).getChannelId()); + for(Channel c : channelService.findChannelByName("*")) { + channelService.showChannelInfo(c); + } + + System.out.println(); + System.out.println("----이름이 \"채널 1\"인 모든 채널 출력----"); + for (Channel ch : channelService.findChannelByName("채널 1")) { + channelService.showChannelInfo(ch); + } + + Channel testChannel = channelService.findChannelByName("채널 1").get(0); + System.out.println("----\"채널 1\"에 \"토마스\"와 \"김첨지\" 입장 및 메세지 작성---- "); + messageService.sendMessage("hello", channelService.findChannelByName("채널 1").get(0), userService.findUserByName("김첨지").get(0)); + messageService.sendMessage("안녕", channelService.findChannelByName("채널 1").get(0), userService.findUserByName("토마스").get(0)); + messageService.sendMessage("배고프다", channelService.findChannelByName("채널 1").get(0), userService.findUserByName("김첨지").get(0)); + //메세지 추가 + + System.out.println(); + System.out.println("----\"김첨지\"가 작성한 모든 메세지 출력----"); + for(Message m: userService.getMessageList(userService.findUserByName("김첨지").get(0).getUserId())) { + messageService.showMessageInfo(m); + } + + System.out.println(); + System.out.println("----\"채널 1\"에 있는 모든 유저 출력----"); + for (User u : testChannel.getUsers()) { + userService.showUserInfo(u); + //채널 1에 있는 모든 유저 출력 + } + + System.out.println(); + System.out.println("----\"채널 1\"에서 \"김첨지\"를 강퇴시킨 후 채널의 모든 유저 및 메세지 출력----"); + channelService.KickUser(channelService.findChannelByName("채널 1").get(0).getChannelId(),userService.findUserByName("김첨지").get(0)); + for (User u : testChannel.getUsers()) { + userService.showUserInfo(u); + //채널 1에 있는 모든 유저 출력 + } + for (Message m : testChannel.getMessages()) { + messageService.showMessageInfo(m); + //채널 1에 있는 모든 유저 출력 + } + + System.out.println(); + System.out.println("----\"김첨지\"의 계정 삭제 후 \"채널 1\"의 모든 유저 및 메세지 출력----"); + userService.deleteUser(userService.findUserByName("김첨지").get(0).getUserId()); + for (User u : testChannel.getUsers()) { + userService.showUserInfo(u); + //채널 1에 있는 모든 유저 출력 + } + for (Message m : testChannel.getMessages()) { + messageService.showMessageInfo(m); + //채널 1에 있는 모든 유저 출력 + } + + + System.out.println(); + System.out.println("----이름이 \"토마스\"인 유저가 채널 3에 입장---- "); + userService.addNewChannel(userService.findUserByName("토마스").get(0).getUserId(),channelService.findChannelByName("채널 3").get(0)); + System.out.println("----이름이 \"토마스\"인 유저가 참여중인 채널 출력---- "); + for (Channel c:userService.getChannelsList(userService.findUserByName("토마스").get(0).getUserId())) { + channelService.showChannelInfo(c); + } + System.out.println(); + System.out.println("----\"채널 3\"에 있는 모든 유저 출력---- "); + for (User u : channelService.findChannelByName("채널 3").get(0).getUsers()) { + userService.showUserInfo(u); + //채널 1에 있는 모든 유저 출력 + } + + System.out.println(); + System.out.println("----\"토마스\"의 이름을 \"찰리\"로 변경---- "); + userService.changeUserName(userService.findUserByName("토마스").get(0).getUserId(),"찰리"); + System.out.println("----\"채널 3\"에 있는 모든 유저 출력---- "); + for (User u : channelService.findChannelByName("채널 3").get(0).getUsers()) { + userService.showUserInfo(u); + //채널 1에 있는 모든 유저 출력 + } + + System.out.println(); + System.out.println("----\"찰리\"의 상태를 Inactive로 변경 후 \"채널 3\"에 있는 모든 유저 출력---- "); + userService.setUserStatus(userService.findUserByName("찰리").get(0).getUserId(), User.Status.INACTIVE); + for (User u : channelService.findChannelByName("채널 3").get(0).getUsers()) { + userService.showUserInfo(u); + //채널 1에 있는 모든 유저 출력 + } + System.out.println(); + System.out.println("----Inactive 상태의 \"찰리\"가 글을 작성하려고 시도----"); + messageService.sendMessage("휴면중이지만 글 작성함",channelService.findChannelByName("채널 3").get(0),userService.findUserByName("찰리").get(0)); + + Message testMessage = messageService.findMessageByBody("hel").get(0); + //"hel" 이 들어간 모든 메세지 중 첫번째 메세지 + + System.out.println(); + System.out.println("----테스트 메세지 출력----"); + messageService.showMessageInfo(testMessage); + //메세지 출력 + messageService.fixMessage(testMessage.getMessageId(), "good bye"); + //메세지 내용 수정 + System.out.println(); + System.out.println("----테스트 메세지 수정 후 출력----"); + messageService.showMessageInfo(testMessage); + + System.out.println(); + System.out.println("----테스트 메세지 삭제----"); + messageService.deleteMessage(testMessage.getMessageId()); + //메세지 삭제 + messageService.showMessageInfo(testMessage); + } + + catch (NoSuchElementException e) { + System.out.println("에러 발생: " + e.getMessage()); + } catch (Exception e) { + // 기타 예외 처리 + System.out.println("알 수 없는 에러 발생: " + e.getMessage()); + } + + System.out.println(); + System.out.println("----존재하는 모든 메세지 출력---- "); + messageService.showAllMessage(); + + System.out.println(); + System.out.println("----채널 1 삭제후 존재하는 모든 메세지 출력---- "); + channelService.deleteChannel(channelService.findChannelByName("채널 1").get(0).getChannelId()); + messageService.showAllMessage(); + + } + +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Channel.java b/src/main/java/com/sprint/mission/discodeit/entity/Channel.java new file mode 100644 index 00000000..bfe75220 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/Channel.java @@ -0,0 +1,55 @@ +package com.sprint.mission.discodeit.entity; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class Channel extends baseEntity { + private UUID channelId; + private String channelName; + private List users; + private List messages; + + public Channel(String channelName) { + super(); + this.channelId = UUID.randomUUID(); + this.channelName = channelName; + messages = new ArrayList(); + users = new ArrayList(); + } + + public UUID getChannelId() { return channelId; } + + public String getChannelName() { return channelName ; } + + public List getUsers() { return users; } + + public List getMessages() { return messages; } + + public void addUser(User newUser) { + if(!users.contains(newUser)) { + users.add(newUser); + newUser.addChannel(this); + } + } + public void removeUser(User deletedUser) { + if(users.contains(deletedUser)) { + users.remove(deletedUser); + deletedUser.removeChannel(this); + } + } + + public void addMessage(Message m) { + this.messages.add(m); + } + + public void removeMessage(Message deletedMessage){ + this.messages.remove(deletedMessage); + } + + public void updateChannelName(String channelName) { + this.channelName = channelName; + } + + + +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/Message.java b/src/main/java/com/sprint/mission/discodeit/entity/Message.java new file mode 100644 index 00000000..a20b262e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/Message.java @@ -0,0 +1,48 @@ +package com.sprint.mission.discodeit.entity; +import java.util.UUID; + +public class Message extends baseEntity { + private UUID messageId; + private String messageBody; + private User user; + private Channel channel; + + private static final User deletedUser = new User("deletedUser"); + //작성자가 탈퇴한 경우 메세지의 작성자는 deletedUser로 바뀐다. + + public Message(String messageBody,User user,Channel channel) { + super(); + this.messageId = UUID.randomUUID(); + this.messageBody = messageBody; + this.user = user; + this.channel = channel; + } + + public UUID getMessageId() { + return messageId; + } + + public String getMessageBody() { + return messageBody; + } + + public User getUser() { + return user; + } + + public Channel getChannel() { + return channel; + } + + public void removeUser(){ + this.user = deletedUser; + //작성자가 탈퇴할 경우 메세지는 남아있지만 작성자의 이름은 deletedUser가 된다. + } + + public void updateMessageBody(String newMessageBody) { + this.messageBody = newMessageBody; + } + + + +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/User.java b/src/main/java/com/sprint/mission/discodeit/entity/User.java new file mode 100644 index 00000000..b6315951 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/User.java @@ -0,0 +1,73 @@ +package com.sprint.mission.discodeit.entity; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class User extends baseEntity{ + + public enum Status{ + ACTIVE, + INACTIVE, + DELETED; + } + + private UUID userId; + private String userName; + private List channels; + private List messages; + private Status status; + + public User(String userName) { + super(); + this.userId =UUID.randomUUID(); + this.userName = userName; + this.status = status.ACTIVE; + this.channels = new ArrayList<>(); + this.messages = new ArrayList<>(); + } + + public UUID getUserId() { + return userId; + } + + public String getUserName() { + return userName; + } + + public List getChannels() { + return channels; + } + + public List getMessages() { + return messages; + } + + public void updateUserName(String newUserName) { + this.userName = newUserName; + } + + public Status getStatus() { return status; } + + public void setStatus(Status status) { this.status = status; } + + public void addChannel(Channel newChannel){ + if(!channels.contains(newChannel)) { + channels.add(newChannel); + newChannel.addUser(this); + } + } + + public void removeChannel(Channel newChannel){ + if(channels.contains(newChannel)) { + channels.remove(newChannel); + newChannel.removeUser(this); + } + } + + public void addMessage(Message newMessage){ + this.messages.add(newMessage); + } + + public void removeMessage(Message m){ this.messages.remove(m); } + +} diff --git a/src/main/java/com/sprint/mission/discodeit/entity/baseEntity.java b/src/main/java/com/sprint/mission/discodeit/entity/baseEntity.java new file mode 100644 index 00000000..c89b1b58 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/entity/baseEntity.java @@ -0,0 +1,24 @@ +package com.sprint.mission.discodeit.entity; + +public abstract class baseEntity { + protected Long createdAt; + protected Long updatedAt; + + public baseEntity() { + createdAt = System.currentTimeMillis(); + updatedAt = createdAt; + } + + public void newUpdatedAt() + { + this.updatedAt = System.currentTimeMillis(); + } + + public Long getCreatedAt() { + return createdAt; + } + + public Long getUpdatedAt() { + return updatedAt; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java b/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java new file mode 100644 index 00000000..4096d20a --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/ChannelService.java @@ -0,0 +1,36 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import java.util.List; +import java.util.UUID; + +public interface ChannelService { + Channel registChannel(String channelName); + //신규 채널 등록 + + boolean deleteChannel(UUID channelId); + //채널 삭제 + + void showChannelInfo(Channel channel); + //선택한 채널 정보 출력 + + Channel findChannelById(UUID channelId); + //channelId로 채널 반환 + + List findChannelByName(String channelName); + //이름이 channelName인 모든 채널 리스트 반환 + + Channel updateChannelName(UUID channelId, String updateChannelName); + //채널 이름 수정 + + List getUserList(UUID channelId); + //채널 내 모든 유저 리스트 조회 + + boolean KickUser(UUID channelId, User user); + //채널 내 유저 강퇴 + + List getMessageList(UUID channelId); + //채널 내 모든 메세지 기록 조회 +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFChannelService.java b/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFChannelService.java new file mode 100644 index 00000000..778fd969 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFChannelService.java @@ -0,0 +1,152 @@ +package com.sprint.mission.discodeit.service.JCF; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.service.ChannelService; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.UUID; + +public class JCFChannelService implements ChannelService { + + //싱글톤으로 변경 + private static JCFChannelService instance; + private final List data; + private final JCFMessageService messageService; + //채널 삭제시 메세지도 같이 삭제되기 때문에 사용 + + private JCFChannelService(){ + data = new ArrayList<>(); + this.messageService = JCFMessageService.getInstance(); + } + + public static JCFChannelService getInstance() { + if (instance == null) { + instance = new JCFChannelService(); + } + return instance; + } + + //신규 채널 등록 + @Override + public Channel registChannel(String channelName){ + if(channelName == null || channelName.isEmpty() || channelName.equals("*")) { + //*은 모든 채널 검색에 사용되므로 채널 이름으로 사용 불가 + System.out.println("잘못된 입력입니다."); + return null; + } + //채널 이름이 공백이 아닐경우 새 채널 생성 + Channel newChannel = new Channel(channelName); + data.add(newChannel); + return newChannel; + } + + //채널 삭제 + @Override + public boolean deleteChannel(UUID channelId) { + Channel toDelete = findChannelById(channelId); + List messagesCopy = new ArrayList<>(toDelete.getMessages()); + //반복문 도중 리스트를 직접 수정하면 ConcurrentModificationException이 발생. 복사본 사용 + for (Message message : messagesCopy) { + messageService.deleteMessage(message.getMessageId()); + //채널이 삭제되면 채널 내 메세지도 전부 삭제된다 + //복사본 순회하며 삭제하는 채널 내 메세지 삭제 + } + for (User user : new ArrayList<>(toDelete.getUsers())) { + user.removeChannel(toDelete); + user.newUpdatedAt(); + } + data.remove(toDelete); + return true; + } + + //선택한 채널 정보 출력 + @Override + public void showChannelInfo(Channel channel) { + if(channel == null || !data.contains(channel)) { + System.out.println("해당 채널이 없습니다"); + return; + } + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime dateTime = Instant.ofEpochMilli(channel.getCreatedAt()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + + String createdDate = dateTime.format(formatter); + System.out.println("채널 이름: " + channel.getChannelName() + ", 채널 ID: " + channel.getChannelId() + ", 채널 생성 날짜: " + createdDate); + } + + //channelId로 채널 검색 + public Channel findChannelById(UUID channelId){ + return data.stream() + .filter(c -> c.getChannelId().equals(channelId)) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("존재하지 않는 채널입니다")); + } + + //검색한 이름의 모든 채널 리스트 반환 + public List findChannelByName(String channelName){ + if(channelName.equals("*")) { + return data; + //*입력시 모든 유저 반환 + } + List channelByName = data.stream() + .filter(c -> c.getChannelName().equals(channelName)) + .toList(); + + if(channelByName.isEmpty()) { + System.out.println("존재하지 않는 채널입니다"); + } + return channelByName; + } + + //채널 이름 수정 + public Channel updateChannelName(UUID channelId, String updateChannelName){ + if(updateChannelName == null || updateChannelName.isEmpty()) { + System.out.println("잘못된 입력입니다."); + return null; + } + //채널이 실존하고 새로운 채널명이 공백이 아닐경우 채널 이름 업데이트 + Channel channel = findChannelById(channelId); + channel.updateChannelName(updateChannelName); + channel.newUpdatedAt(); + return channel; + } + + //채널 내 모든 유저 리스트 조회 + public List getUserList(UUID channelId){ + Channel selectedChannel = findChannelById(channelId); + List usersInChannel = selectedChannel.getUsers(); + if(usersInChannel.isEmpty()) { + System.out.println("해당 채널에 참여하고 있는 유저가 없습니다."); + } + return usersInChannel; + } + + //채널 내 유저 강퇴 + public boolean KickUser(UUID channelId, User user){ + Channel selectedChannel = findChannelById(channelId); + selectedChannel.removeUser(user); + user.newUpdatedAt(); + selectedChannel.newUpdatedAt(); + return true; + } + + //채널 내 모든 메세지 기록 조회 + public List getMessageList(UUID channelId){ + Channel channel = findChannelById(channelId); + List messages = channel.getMessages(); + if(messages.isEmpty()) { + System.out.println("채널에 작성된 메세지가 없습니다."); + } + return messages; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFMessageService.java b/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFMessageService.java new file mode 100644 index 00000000..2a253b6e --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFMessageService.java @@ -0,0 +1,142 @@ +package com.sprint.mission.discodeit.service.JCF; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.service.MessageService; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.UUID; +import java.util.stream.Collectors; + +public class JCFMessageService implements MessageService { + + private static JCFMessageService instance; + private final List data; + + private JCFMessageService() { + data = new ArrayList<>(); + } + + public static JCFMessageService getInstance() { + if (instance == null) { + instance = new JCFMessageService(); + } + return instance; + } + + //메세지 작성 + @Override + public Message sendMessage(String messageBody, Channel channel, User user){ + if(channel == null || user == null) { + System.out.println("채널 또는 유저가 없습니다"); + return null; + } + if(user.getStatus()!= User.Status.ACTIVE) { + System.out.println("휴면중 혹은 탈퇴한 유저입니다"); + return null; + } + if(messageBody == null || messageBody.isEmpty()){ + System.out.println("메세지의 본문이 비었습니다"); + return null; + } + Message newMessage = new Message(messageBody, user, channel); + newMessage.getUser().addMessage(newMessage); + newMessage.getChannel().addMessage(newMessage); + //채널과 유저에 작성한 메세지 추가 + user.addChannel(channel); + //해당 채널에서 유저가 메세지를 작성했으므로 유저와 채널 연결 + data.add(newMessage); + return newMessage; + } + + //메세지 삭제 + @Override + public boolean deleteMessage(UUID messageId) { + Message deletedMessage = findMessageById(messageId); + deletedMessage.getUser().removeMessage(deletedMessage); + deletedMessage.getChannel().removeMessage(deletedMessage); + //채널과 유저에서 해당 메세지 제거 + data.remove(deletedMessage); + return true; + } + + //메세지 내용 수정 + @Override + public Message fixMessage(UUID messageId, String newBody){ + Message message = findMessageById(messageId); + + message.updateMessageBody(newBody); + return message; + } + + //Id로 메세지 정보 조회 + @Override + public Message findMessageById(UUID messageId){ + return data.stream() + .filter(m -> m.getMessageId().equals(messageId)) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("해당하는 메세지가 없습니다")); + } + + //메세지 내용으로 메세지 조회(검색한 내용을 포함하고 있는 전체 메세지 조회) + @Override + public List findMessageByBody(String messageBody){ + List messages = data.stream() + .filter(message -> message.getMessageBody().contains(messageBody)) + .collect(Collectors.toList()); + if(messages.isEmpty()){ + System.out.println("해당 내용을 포함하는 메세지가 없습니다."); + } + return messages; + } + + //선택한 메세지 정보 출력 + @Override + public void showMessageInfo(Message message) { + if(message == null || !data.contains(message)) { + System.out.println("해당 메세지가 없습니다"); + return; + } + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime dateTime = Instant.ofEpochMilli(message.getCreatedAt()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + + String createdDate = dateTime.format(formatter); + System.out.println("메세지 내용: " + message.getMessageBody() + + ", 작성자: " + message.getUser().getUserName() + + ", 채널: " + message.getChannel().getChannelName() + + ", 작성 날짜: " + createdDate); + } + + //서비스에 저장된 모든 메세지 출력 + @Override + public void showAllMessage() { + if(data.isEmpty()) { + System.out.println("메세지가 없습니다"); + return; + } + + for(Message message : data) { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime dateTime = Instant.ofEpochMilli(message.getCreatedAt()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + + String createdDate = dateTime.format(formatter); + System.out.println("메세지 내용: " + message.getMessageBody() + + ", 작성자: " + message.getUser().getUserName() + + ", 채널: " + message.getChannel().getChannelName() + + ", 작성 날짜: " + createdDate); + } + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFUserService.java b/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFUserService.java new file mode 100644 index 00000000..8596ef14 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/JCF/JCFUserService.java @@ -0,0 +1,196 @@ +package com.sprint.mission.discodeit.service.JCF; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import com.sprint.mission.discodeit.service.UserService; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +public class JCFUserService implements UserService { + + private static JCFUserService instance; + private final List data; + + private JCFUserService() { + data = new ArrayList<>(); + } + + public static JCFUserService getInstance() { + if (instance == null) { + instance = new JCFUserService(); + } + return instance; + } + //새 유저 등록 + @Override + public User registUser(String userName) { + if(userName == null || userName.isEmpty() || userName.equals("*")) { + //*은 모든 유저 검색에 사용되기 때문에 이름에 사용 불가 + System.out.println("잘못된 입력입니다."); + return null; + } + User newUser = new User(userName); + data.add(newUser); + return newUser; + } + + //유저 삭제 + @Override + public boolean deleteUser(UUID userId) { + User userToDelete = findUserById(userId); + + for (Channel c : userToDelete.getChannels()) { + c.removeUser(userToDelete); + c.newUpdatedAt(); + } + for (Message m : userToDelete.getMessages()) { + m.removeUser(); + m.newUpdatedAt(); + //유저를 삭제할 경우 메세지의 작성자는 deletedUser로 바뀐다. + } + userToDelete.setStatus(User.Status.DELETED); + return true; + } + + //선택한 유저 정보 출력 + @Override + public void showUserInfo(User user) { + if(user == null || !data.contains(user)) { + System.out.println("해당 유저가 없습니다"); + return; + } + + if(user.getStatus() == User.Status.DELETED) { + System.out.println("탈퇴한 유저입니다"); + return; + } + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime dateTime = Instant.ofEpochMilli(user.getCreatedAt()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + String createdDate = dateTime.format(formatter); + System.out.println("유저 이름: " + user.getUserName() + ", 유저 ID: " + user.getUserId() + ", 가입 날짜: " + createdDate+ ", 회원 상태: " + user.getStatus()); + } + + //UID로 유저 검색 후 반환 + @Override + public User findUserById(UUID userId) { + return data.stream() + .filter(user -> user.getUserId().equals(userId)&&user.getStatus() != User.Status.DELETED) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("존재하지 않는 유저입니다.")); + } + + //검색한 이름의 모든 유저 리스트 반환 + @Override + public List findUserByName(String userName) { + if(userName.equals("*")) { + return data; + //*입력시 탈퇴한 유저 포함 모든 유저 반환 + } + List usersByName = data.stream() + .filter(user -> user.getUserName().equals(userName)&&user.getStatus() != User.Status.DELETED) + .collect(Collectors.toList()); + + if(usersByName.isEmpty()) { + System.out.println("존재하지 않는 유저입니다."); + } + return usersByName; + } + + //유저 이름 변경 + @Override + public void changeUserName(UUID userId, String updateUserName) { + User user = findUserById(userId); + if(user.getStatus() == User.Status.INACTIVE) { + System.out.println("휴면중인 유저입니다"); + } + + if(updateUserName != null && !updateUserName.isEmpty()) { + user.updateUserName(updateUserName); + user.newUpdatedAt(); + } + } + + //유저 채널 리스트에 채널 추가 + @Override + public boolean addNewChannel(UUID userId, Channel channel) { + if(channel == null) { + System.out.println("해당 채널이 없습니다"); + return false; + } + + User user = findUserById(userId); + if(user.getStatus() == User.Status.INACTIVE) { + System.out.println("휴면중인 유저입니다"); + return false; + } + + //유저의 채널리스트에 채널 추가. + user.addChannel(channel); + user.newUpdatedAt(); + return true; + } + + //유저가 참여하고있는 채널 리스트 반환 + @Override + public List getChannelsList(UUID userId) { + User user = findUserById(userId); + + List foundChannels = user.getChannels(); + if(foundChannels.isEmpty()) { + System.out.println("해당 유저가 참여하고 있는 채널이 없습니다."); + } + return foundChannels; + } + + //해당 채널에서 퇴장 + @Override + public boolean exitFromChannel(UUID userId, Channel channel) { + if(channel == null) { + System.out.println("해당 채널이 없습니다"); + return false; + } + + User user = findUserById(userId); + + user.removeChannel(channel); + user.newUpdatedAt(); + channel.newUpdatedAt(); + return true; + } + + //해당 유저의 상태 변경 + @Override + public void setUserStatus(UUID userId,User.Status status) { + User user = findUserById(userId); + + if(status == User.Status.DELETED) { + System.out.println("상태 변경에서는 회원 탈퇴를 할 수 없습니다."); + //회원 탈퇴는 deleteUser에서만 가능 + return; + + } + else + user.setStatus(status); + } + + //유저가 작성한 모든 채팅 리스트 반환 + @Override + public List getMessageList(UUID userId) { + User user = findUserById(userId); + + List foundMessages = user.getMessages(); + if(foundMessages.isEmpty()) { + System.out.println("사용자가 작성한 메세지가 없습니다."); + } + return foundMessages; + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/MessageService.java b/src/main/java/com/sprint/mission/discodeit/service/MessageService.java new file mode 100644 index 00000000..dae420ef --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/MessageService.java @@ -0,0 +1,31 @@ +package com.sprint.mission.discodeit.service; + +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; +import java.util.List; +import java.util.UUID; + +public interface MessageService { + + Message sendMessage(String messageBody, Channel channel, User user); + //메세지 작성 + + boolean deleteMessage(UUID messageId); + //메세지 삭제 + + Message fixMessage(UUID messageId,String newBody); + //메세지 내용 수정 + + Message findMessageById(UUID messageId); + //Id로 메세지 반환 + + List findMessageByBody(String messageBody); + //해당 메세지 내용을 포함하고 있는 모든 메세지 리스트 반환 + + void showMessageInfo(Message message); + //선택한 메세지 정보 출력 + + public void showAllMessage(); + //서비스에 저장된 모든 메세지 출력 +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/UserService.java b/src/main/java/com/sprint/mission/discodeit/service/UserService.java new file mode 100644 index 00000000..b6f327f5 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/UserService.java @@ -0,0 +1,44 @@ +package com.sprint.mission.discodeit.service; + +import java.util.List; +import java.util.UUID; +import com.sprint.mission.discodeit.entity.Channel; +import com.sprint.mission.discodeit.entity.Message; +import com.sprint.mission.discodeit.entity.User; + +public interface UserService { + + User registUser(String userName); + //신규 유저 등록 + + boolean deleteUser(UUID userId); + //유저 정보 삭제 + + void showUserInfo(User user); + //선택한 유저 출력 + + User findUserById(UUID userId); + //userId로 유저 반환 + + List findUserByName(String userName); + //이름이 userName인 모든 유저 리스트 반환 + + void changeUserName(UUID userId, String updateUserName); + //유저 정보 수정 + + boolean addNewChannel(UUID userId, Channel channel); + //유저가 참여하고 았는 채널 추가 + + List getChannelsList(UUID userId); + //유저가 참여하고있는 채널 리스트 조회 + + boolean exitFromChannel(UUID userId, Channel channel); + //해당 채널에서 퇴장 + + void setUserStatus(UUID userId, User.Status status); + //해당 유저의 상태 변경 + + List getMessageList(UUID userId); + //유저가 작성한 모든 메세지 기록 조회. +} + diff --git a/src/main/java/com/sprint/mission/discodeit/service/factory/JCFServiceFactory.java b/src/main/java/com/sprint/mission/discodeit/service/factory/JCFServiceFactory.java new file mode 100644 index 00000000..9644c671 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/factory/JCFServiceFactory.java @@ -0,0 +1,23 @@ +package com.sprint.mission.discodeit.service.factory; + +import com.sprint.mission.discodeit.service.ChannelService; +import com.sprint.mission.discodeit.service.JCF.JCFChannelService; +import com.sprint.mission.discodeit.service.JCF.JCFMessageService; +import com.sprint.mission.discodeit.service.JCF.JCFUserService; +import com.sprint.mission.discodeit.service.MessageService; +import com.sprint.mission.discodeit.service.UserService; + +public class JCFServiceFactory implements ServiceFactory { + @Override + public UserService createUserService() { + return JCFUserService.getInstance(); + } + @Override + public MessageService createMessageService() { + return JCFMessageService.getInstance(); + } + @Override + public ChannelService createChannelService() { + return JCFChannelService.getInstance(); + } +} diff --git a/src/main/java/com/sprint/mission/discodeit/service/factory/ServiceFactory.java b/src/main/java/com/sprint/mission/discodeit/service/factory/ServiceFactory.java new file mode 100644 index 00000000..235c92a1 --- /dev/null +++ b/src/main/java/com/sprint/mission/discodeit/service/factory/ServiceFactory.java @@ -0,0 +1,11 @@ +package com.sprint.mission.discodeit.service.factory; + +import com.sprint.mission.discodeit.service.ChannelService; +import com.sprint.mission.discodeit.service.MessageService; +import com.sprint.mission.discodeit.service.UserService; + +public interface ServiceFactory { + UserService createUserService(); + MessageService createMessageService(); + ChannelService createChannelService(); +}