├── .gitignore
├── .mvn
└── wrapper
│ ├── MavenWrapperDownloader.java
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── programming
│ │ └── techie
│ │ └── springredditclone
│ │ ├── SpringRedditCloneApplication.java
│ │ ├── config
│ │ ├── SecurityConfig.java
│ │ ├── SwaggerConfiguration.java
│ │ └── WebConfig.java
│ │ ├── controller
│ │ ├── AuthController.java
│ │ ├── CommentsController.java
│ │ ├── PostController.java
│ │ ├── SubredditController.java
│ │ └── VoteController.java
│ │ ├── dto
│ │ ├── AuthenticationResponse.java
│ │ ├── CommentsDto.java
│ │ ├── LoginRequest.java
│ │ ├── LogoutRequest.java
│ │ ├── PostRequest.java
│ │ ├── PostResponse.java
│ │ ├── RefreshTokenRequest.java
│ │ ├── RegisterRequest.java
│ │ ├── SubredditDto.java
│ │ └── VoteDto.java
│ │ ├── exceptions
│ │ ├── PostNotFoundException.java
│ │ ├── SpringRedditException.java
│ │ └── SubredditNotFoundException.java
│ │ ├── mapper
│ │ ├── CommentMapper.java
│ │ ├── PostMapper.java
│ │ └── SubredditMapper.java
│ │ ├── model
│ │ ├── Comment.java
│ │ ├── NotificationEmail.java
│ │ ├── Post.java
│ │ ├── RefreshToken.java
│ │ ├── Subreddit.java
│ │ ├── User.java
│ │ ├── VerificationToken.java
│ │ ├── Vote.java
│ │ └── VoteType.java
│ │ ├── repository
│ │ ├── CommentRepository.java
│ │ ├── PostRepository.java
│ │ ├── RefreshTokenRepository.java
│ │ ├── SubredditRepository.java
│ │ ├── UserRepository.java
│ │ ├── VerificationTokenRepository.java
│ │ └── VoteRepository.java
│ │ ├── security
│ │ ├── JwtAuthenticationFilter.java
│ │ └── JwtProvider.java
│ │ └── service
│ │ ├── AuthService.java
│ │ ├── CommentService.java
│ │ ├── MailContentBuilder.java
│ │ ├── MailService.java
│ │ ├── PostService.java
│ │ ├── RefreshTokenService.java
│ │ ├── SubredditService.java
│ │ ├── UserDetailsServiceImpl.java
│ │ └── VoteService.java
└── resources
│ ├── application-test.properties
│ ├── application.properties
│ ├── images
│ ├── create-post.PNG
│ ├── create-subreddit.PNG
│ ├── reddit-screenshot-updated.PNG
│ ├── spring-reddit-view-post.PNG
│ └── user-profile.PNG
│ ├── springblog.jks
│ └── templates
│ └── mailTemplate.html
└── test
├── java
└── com
│ └── programming
│ └── techie
│ └── springredditclone
│ ├── BaseTest.java
│ ├── controller
│ └── PostControllerTest.java
│ ├── repository
│ ├── PostRepositoryTest.java
│ ├── UserRepositoryTest.java
│ └── UserRepositoryTestEmbedded.java
│ └── service
│ ├── CommentServiceTest.java
│ └── PostServiceTest.java
└── resources
└── test-data.sql
/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**
5 | !**/src/test/**
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 |
30 | ### VS Code ###
31 | .vscode/
32 |
--------------------------------------------------------------------------------
/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | Licensed to the Apache Software Foundation (ASF) under one
3 | or more contributor license agreements. See the NOTICE file
4 | distributed with this work for additional information
5 | regarding copyright ownership. The ASF licenses this file
6 | to you under the Apache License, Version 2.0 (the
7 | "License"); you may not use this file except in compliance
8 | with the License. You may obtain a copy of the License at
9 |
10 | https://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing,
13 | software distributed under the License is distributed on an
14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | KIND, either express or implied. See the License for the
16 | specific language governing permissions and limitations
17 | under the License.
18 | */
19 |
20 | import java.io.File;
21 | import java.io.FileInputStream;
22 | import java.io.FileOutputStream;
23 | import java.io.IOException;
24 | import java.net.URL;
25 | import java.nio.channels.Channels;
26 | import java.nio.channels.ReadableByteChannel;
27 | import java.util.Properties;
28 |
29 | public class MavenWrapperDownloader {
30 |
31 | /**
32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
33 | */
34 | private static final String DEFAULT_DOWNLOAD_URL =
35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
36 |
37 | /**
38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
39 | * use instead of the default one.
40 | */
41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
42 | ".mvn/wrapper/maven-wrapper.properties";
43 |
44 | /**
45 | * Path where the maven-wrapper.jar will be saved to.
46 | */
47 | private static final String MAVEN_WRAPPER_JAR_PATH =
48 | ".mvn/wrapper/maven-wrapper.jar";
49 |
50 | /**
51 | * Name of the property which should be used to override the default download url for the wrapper.
52 | */
53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
54 |
55 | public static void main(String args[]) {
56 | System.out.println("- Downloader started");
57 | File baseDirectory = new File(args[0]);
58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
59 |
60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
61 | // wrapperUrl parameter.
62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
63 | String url = DEFAULT_DOWNLOAD_URL;
64 | if(mavenWrapperPropertyFile.exists()) {
65 | FileInputStream mavenWrapperPropertyFileInputStream = null;
66 | try {
67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
68 | Properties mavenWrapperProperties = new Properties();
69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
71 | } catch (IOException e) {
72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
73 | } finally {
74 | try {
75 | if(mavenWrapperPropertyFileInputStream != null) {
76 | mavenWrapperPropertyFileInputStream.close();
77 | }
78 | } catch (IOException e) {
79 | // Ignore ...
80 | }
81 | }
82 | }
83 | System.out.println("- Downloading from: : " + url);
84 |
85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
86 | if(!outputFile.getParentFile().exists()) {
87 | if(!outputFile.getParentFile().mkdirs()) {
88 | System.out.println(
89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
90 | }
91 | }
92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
93 | try {
94 | downloadFileFromURL(url, outputFile);
95 | System.out.println("Done");
96 | System.exit(0);
97 | } catch (Throwable e) {
98 | System.out.println("- Error downloading");
99 | e.printStackTrace();
100 | System.exit(1);
101 | }
102 | }
103 |
104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
105 | URL website = new URL(urlString);
106 | ReadableByteChannel rbc;
107 | rbc = Channels.newChannel(website.openStream());
108 | FileOutputStream fos = new FileOutputStream(destination);
109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
110 | fos.close();
111 | rbc.close();
112 | }
113 |
114 | }
115 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot Testing Tutorial Series
2 | This repository contains source code for the Spring Boot Testing Tutorial Series
3 |
4 | # spring-reddit-clone
5 | Reddit clone built using Spring Boot, Spring Security with JPA Authentication, Spring Data JPA with MySQL, Spring MVC. The frontend is built using Angular - You can find the frontend source code here - https://github.com/SaiUpadhyayula/angular-reddit-clone
6 |
7 | # Tutorial
8 | https://programmingtechie.com/2019/09/30/build-a-full-stack-reddit-clone-with-spring-boot-and-angular-part-1/
9 |
10 | # Front end code
11 | https://github.com/SaiUpadhyayula/angular-reddit-clone
12 |
13 | # Screenshots
14 | 1. Home Page
15 |
16 | 
17 |
18 | 2. View Post Page
19 |
20 | 
21 |
22 | 3. Create Post Page
23 |
24 | 
25 |
26 | 4. Create Subreddit Page
27 |
28 | 
29 |
30 | 5. User Profile Page
31 |
32 | 
33 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | ##########################################################################################
204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
205 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
206 | ##########################################################################################
207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
208 | if [ "$MVNW_VERBOSE" = true ]; then
209 | echo "Found .mvn/wrapper/maven-wrapper.jar"
210 | fi
211 | else
212 | if [ "$MVNW_VERBOSE" = true ]; then
213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
214 | fi
215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
216 | while IFS="=" read key value; do
217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
218 | esac
219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
220 | if [ "$MVNW_VERBOSE" = true ]; then
221 | echo "Downloading from: $jarUrl"
222 | fi
223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
224 |
225 | if command -v wget > /dev/null; then
226 | if [ "$MVNW_VERBOSE" = true ]; then
227 | echo "Found wget ... using wget"
228 | fi
229 | wget "$jarUrl" -O "$wrapperJarPath"
230 | elif command -v curl > /dev/null; then
231 | if [ "$MVNW_VERBOSE" = true ]; then
232 | echo "Found curl ... using curl"
233 | fi
234 | curl -o "$wrapperJarPath" "$jarUrl"
235 | else
236 | if [ "$MVNW_VERBOSE" = true ]; then
237 | echo "Falling back to using Java to download"
238 | fi
239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
240 | if [ -e "$javaClass" ]; then
241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
242 | if [ "$MVNW_VERBOSE" = true ]; then
243 | echo " - Compiling MavenWrapperDownloader.java ..."
244 | fi
245 | # Compiling the Java class
246 | ("$JAVA_HOME/bin/javac" "$javaClass")
247 | fi
248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
249 | # Running the downloader
250 | if [ "$MVNW_VERBOSE" = true ]; then
251 | echo " - Running MavenWrapperDownloader.java ..."
252 | fi
253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
254 | fi
255 | fi
256 | fi
257 | fi
258 | ##########################################################################################
259 | # End of extension
260 | ##########################################################################################
261 |
262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
263 | if [ "$MVNW_VERBOSE" = true ]; then
264 | echo $MAVEN_PROJECTBASEDIR
265 | fi
266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
267 |
268 | # For Cygwin, switch paths to Windows format before running java
269 | if $cygwin; then
270 | [ -n "$M2_HOME" ] &&
271 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
272 | [ -n "$JAVA_HOME" ] &&
273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
274 | [ -n "$CLASSPATH" ] &&
275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
276 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
278 | fi
279 |
280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
281 |
282 | exec "$JAVACMD" \
283 | $MAVEN_OPTS \
284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
287 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven2 Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
126 | )
127 |
128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
130 | if exist %WRAPPER_JAR% (
131 | echo Found %WRAPPER_JAR%
132 | ) else (
133 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
134 | echo Downloading from: %DOWNLOAD_URL%
135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
136 | echo Finished downloading %WRAPPER_JAR%
137 | )
138 | @REM End of extension
139 |
140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
141 | if ERRORLEVEL 1 goto error
142 | goto end
143 |
144 | :error
145 | set ERROR_CODE=1
146 |
147 | :end
148 | @endlocal & set ERROR_CODE=%ERROR_CODE%
149 |
150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
154 | :skipRcPost
155 |
156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
158 |
159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
160 |
161 | exit /B %ERROR_CODE%
162 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.1.8.RELEASE
9 |
10 |
11 | com.programming.techie
12 | spring-reddit-clone
13 | 0.0.1-SNAPSHOT
14 | spring-reddit-clone
15 | Demo project for Spring Boot
16 |
17 |
18 | 1.8
19 | 1.3.1.Final
20 |
21 |
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-data-jpa
26 |
27 |
28 | org.springframework.boot
29 | spring-boot-starter-mail
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-security
34 |
35 |
36 | org.springframework.boot
37 | spring-boot-starter-web
38 |
39 |
40 |
41 | mysql
42 | mysql-connector-java
43 | runtime
44 |
45 |
46 | org.projectlombok
47 | lombok
48 | 1.18.8
49 | compile
50 |
51 |
52 | org.springframework.boot
53 | spring-boot-starter-test
54 | test
55 |
56 |
57 | junit
58 | junit
59 |
60 |
61 |
62 |
63 | org.springframework.security
64 | spring-security-test
65 | test
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-starter-thymeleaf
70 |
71 |
72 |
73 | io.jsonwebtoken
74 | jjwt-api
75 | 0.10.5
76 |
77 |
78 | io.jsonwebtoken
79 | jjwt-impl
80 | runtime
81 | 0.10.5
82 |
83 |
84 | io.jsonwebtoken
85 | jjwt-jackson
86 | runtime
87 | 0.10.5
88 |
89 |
90 | org.mapstruct
91 | mapstruct
92 | ${org.mapstruct.version}
93 | compile
94 |
95 |
96 |
97 | io.springfox
98 | springfox-swagger2
99 | 2.9.2
100 |
101 |
102 | io.springfox
103 | springfox-swagger-ui
104 | 2.9.2
105 |
106 |
108 |
109 | com.github.marlonlom
110 | timeago
111 | 4.0.1
112 |
113 |
114 | org.jetbrains.kotlin
115 | kotlin-stdlib-jdk8
116 | ${kotlin.version}
117 |
118 |
119 | org.junit.jupiter
120 | junit-jupiter
121 | 5.6.2
122 | test
123 |
124 |
125 | org.assertj
126 | assertj-core
127 | 3.17.2
128 | test
129 |
130 |
131 | org.mockito
132 | mockito-all
133 | 1.10.19
134 | test
135 |
136 |
137 | org.mockito
138 | mockito-junit-jupiter
139 | test
140 |
141 |
142 | org.testcontainers
143 | mysql
144 | 1.14.3
145 | test
146 |
147 |
148 | org.testcontainers
149 | junit-jupiter
150 | 1.14.3
151 | test
152 |
153 |
154 | com.h2database
155 | h2
156 | 1.4.200
157 | test
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 | org.springframework.boot
167 | spring-boot-maven-plugin
168 |
169 |
170 | org.apache.maven.plugins
171 | maven-compiler-plugin
172 | 3.5.1
173 |
174 | 1.8
175 | 1.8
176 |
177 |
178 | org.mapstruct
179 | mapstruct-processor
180 | ${org.mapstruct.version}
181 |
182 |
183 | org.projectlombok
184 | lombok
185 | 1.18.8
186 |
187 |
188 |
189 |
190 |
191 | org.jetbrains.kotlin
192 | kotlin-maven-plugin
193 | ${kotlin.version}
194 |
195 |
196 | compile
197 | process-sources
198 |
199 | compile
200 |
201 |
202 |
203 | src/main/java
204 | target/generated-sources/annotations
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/SpringRedditCloneApplication.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone;
2 |
3 | import com.programming.techie.springredditclone.config.SwaggerConfiguration;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.context.annotation.Import;
7 | import org.springframework.scheduling.annotation.EnableAsync;
8 |
9 | @SpringBootApplication
10 | @EnableAsync
11 | @Import(SwaggerConfiguration.class)
12 | public class SpringRedditCloneApplication {
13 |
14 | public static void main(String[] args) {
15 | SpringApplication.run(com.programming.techie.springredditclone.SpringRedditCloneApplication.class, args);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/config/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.config;
2 |
3 | import com.programming.techie.springredditclone.security.JwtAuthenticationFilter;
4 | import lombok.AllArgsConstructor;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.http.HttpMethod;
8 | import org.springframework.security.authentication.AuthenticationManager;
9 | import org.springframework.security.config.BeanIds;
10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
12 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
13 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
14 | import org.springframework.security.core.userdetails.UserDetailsService;
15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
16 | import org.springframework.security.crypto.password.PasswordEncoder;
17 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
18 |
19 | @EnableWebSecurity
20 | @AllArgsConstructor
21 | public class SecurityConfig extends WebSecurityConfigurerAdapter {
22 |
23 | private final UserDetailsService userDetailsService;
24 | private final JwtAuthenticationFilter jwtAuthenticationFilter;
25 |
26 | @Bean(BeanIds.AUTHENTICATION_MANAGER)
27 | @Override
28 | public AuthenticationManager authenticationManagerBean() throws Exception {
29 | return super.authenticationManagerBean();
30 | }
31 |
32 | @Override
33 | public void configure(HttpSecurity httpSecurity) throws Exception {
34 | httpSecurity.cors().and()
35 | .csrf().disable()
36 | .authorizeRequests()
37 | .antMatchers("/api/auth/**")
38 | .permitAll()
39 | .antMatchers(HttpMethod.GET, "/api/subreddit")
40 | .permitAll()
41 | .antMatchers(HttpMethod.GET, "/api/posts/")
42 | .permitAll()
43 | .antMatchers(HttpMethod.GET, "/api/posts/**")
44 | .permitAll()
45 | .antMatchers("/v2/api-docs",
46 | "/configuration/ui",
47 | "/swagger-resources/**",
48 | "/configuration/security",
49 | "/swagger-ui.html",
50 | "/webjars/**")
51 | .permitAll()
52 | .anyRequest()
53 | .authenticated();
54 | httpSecurity.addFilterBefore(jwtAuthenticationFilter,
55 | UsernamePasswordAuthenticationFilter.class);
56 | }
57 |
58 | @Autowired
59 | public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
60 | authenticationManagerBuilder.userDetailsService(userDetailsService)
61 | .passwordEncoder(passwordEncoder());
62 | }
63 |
64 | @Bean
65 | PasswordEncoder passwordEncoder() {
66 | return new BCryptPasswordEncoder();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/config/SwaggerConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import springfox.documentation.builders.ApiInfoBuilder;
6 | import springfox.documentation.builders.PathSelectors;
7 | import springfox.documentation.builders.RequestHandlerSelectors;
8 | import springfox.documentation.service.ApiInfo;
9 | import springfox.documentation.service.Contact;
10 | import springfox.documentation.spi.DocumentationType;
11 | import springfox.documentation.spring.web.plugins.Docket;
12 | import springfox.documentation.swagger2.annotations.EnableSwagger2;
13 |
14 | @Configuration
15 | @EnableSwagger2
16 | public class SwaggerConfiguration {
17 | @Bean
18 | public Docket redditCloneApi() {
19 | return new Docket(DocumentationType.SWAGGER_2)
20 | .select()
21 | .apis(RequestHandlerSelectors.any())
22 | .paths(PathSelectors.any())
23 | .build()
24 | .apiInfo(getApiInfo());
25 | }
26 |
27 | private ApiInfo getApiInfo() {
28 | return new ApiInfoBuilder()
29 | .title("Reddit Clone API")
30 | .version("1.0")
31 | .description("API for Reddit Clone Application")
32 | .contact(new Contact("Sai Upadhyayula", "http://programmingtechie.com", "xyz@email.com"))
33 | .license("Apache License Version 2.0")
34 | .build();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/config/WebConfig.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.config;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.web.servlet.config.annotation.CorsRegistry;
5 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
6 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
8 |
9 | @Configuration
10 | @EnableWebMvc
11 | public class WebConfig implements WebMvcConfigurer {
12 |
13 | @Override
14 | public void addCorsMappings(CorsRegistry corsRegistry) {
15 | corsRegistry.addMapping("/**")
16 | .allowedOrigins("*")
17 | .allowedMethods("*")
18 | .maxAge(3600L)
19 | .allowedHeaders("*")
20 | .exposedHeaders("Authorization")
21 | .allowCredentials(true);
22 | }
23 |
24 | @Override
25 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
26 | registry.addResourceHandler("swagger-ui.html")
27 | .addResourceLocations("classpath:/META-INF/resources/");
28 |
29 | registry.addResourceHandler("/webjars/**")
30 | .addResourceLocations("classpath:/META-INF/resources/webjars/");
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/controller/AuthController.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.controller;
2 |
3 | import com.programming.techie.springredditclone.dto.AuthenticationResponse;
4 | import com.programming.techie.springredditclone.dto.LoginRequest;
5 | import com.programming.techie.springredditclone.dto.RefreshTokenRequest;
6 | import com.programming.techie.springredditclone.dto.RegisterRequest;
7 | import com.programming.techie.springredditclone.service.AuthService;
8 | import com.programming.techie.springredditclone.service.RefreshTokenService;
9 | import lombok.AllArgsConstructor;
10 | import org.springframework.http.ResponseEntity;
11 | import org.springframework.web.bind.annotation.*;
12 |
13 | import javax.validation.Valid;
14 |
15 | import static org.springframework.http.HttpStatus.OK;
16 |
17 | @RestController
18 | @RequestMapping("/api/auth")
19 | @AllArgsConstructor
20 | public class AuthController {
21 |
22 | private final AuthService authService;
23 | private final RefreshTokenService refreshTokenService;
24 |
25 | @PostMapping("/signup")
26 | public ResponseEntity signup(@RequestBody RegisterRequest registerRequest) {
27 | authService.signup(registerRequest);
28 | return new ResponseEntity<>("User Registration Successful",
29 | OK);
30 | }
31 |
32 | @GetMapping("accountVerification/{token}")
33 | public ResponseEntity verifyAccount(@PathVariable String token) {
34 | authService.verifyAccount(token);
35 | return new ResponseEntity<>("Account Activated Successfully", OK);
36 | }
37 |
38 | @PostMapping("/login")
39 | public AuthenticationResponse login(@RequestBody LoginRequest loginRequest) {
40 | return authService.login(loginRequest);
41 | }
42 |
43 | @PostMapping("/refresh/token")
44 | public AuthenticationResponse refreshTokens(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) {
45 | return authService.refreshToken(refreshTokenRequest);
46 | }
47 |
48 | @PostMapping("/logout")
49 | public ResponseEntity logout(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) {
50 | refreshTokenService.deleteRefreshToken(refreshTokenRequest.getRefreshToken());
51 | return ResponseEntity.status(OK).body("Refresh Token Deleted Successfully!!");
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/controller/CommentsController.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.controller;
2 |
3 | import com.programming.techie.springredditclone.dto.CommentsDto;
4 | import com.programming.techie.springredditclone.service.CommentService;
5 | import lombok.AllArgsConstructor;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.*;
8 |
9 | import java.util.List;
10 |
11 | import static org.springframework.http.HttpStatus.CREATED;
12 | import static org.springframework.http.HttpStatus.OK;
13 |
14 | @RestController
15 | @RequestMapping("/api/comments/")
16 | @AllArgsConstructor
17 | public class CommentsController {
18 | private final CommentService commentService;
19 |
20 | @PostMapping
21 | public ResponseEntity createComment(@RequestBody CommentsDto commentsDto) {
22 | commentService.save(commentsDto);
23 | return new ResponseEntity<>(CREATED);
24 | }
25 |
26 | @GetMapping("/by-post/{postId}")
27 | public ResponseEntity> getAllCommentsForPost(@PathVariable Long postId) {
28 | return ResponseEntity.status(OK)
29 | .body(commentService.getAllCommentsForPost(postId));
30 | }
31 |
32 | @GetMapping("/by-user/{userName}")
33 | public ResponseEntity> getAllCommentsForUser(@PathVariable String userName){
34 | return ResponseEntity.status(OK)
35 | .body(commentService.getAllCommentsForUser(userName));
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/controller/PostController.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.controller;
2 |
3 | import com.programming.techie.springredditclone.dto.PostRequest;
4 | import com.programming.techie.springredditclone.dto.PostResponse;
5 | import com.programming.techie.springredditclone.service.PostService;
6 | import lombok.AllArgsConstructor;
7 | import org.springframework.http.HttpStatus;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.web.bind.annotation.*;
10 |
11 | import java.util.List;
12 |
13 | import static org.springframework.http.ResponseEntity.status;
14 |
15 | @RestController
16 | @RequestMapping("/api/posts/")
17 | @AllArgsConstructor
18 | public class PostController {
19 |
20 | private final PostService postService;
21 |
22 | @PostMapping
23 | public ResponseEntity createPost(@RequestBody PostRequest postRequest) {
24 | postService.save(postRequest);
25 | return new ResponseEntity<>(HttpStatus.CREATED);
26 | }
27 |
28 | @GetMapping
29 | public ResponseEntity> getAllPosts() {
30 | return status(HttpStatus.OK).body(postService.getAllPosts());
31 | }
32 |
33 | @GetMapping("/{id}")
34 | public ResponseEntity getPost(@PathVariable Long id) {
35 | return status(HttpStatus.OK).body(postService.getPost(id));
36 | }
37 |
38 | @GetMapping("by-subreddit/{id}")
39 | public ResponseEntity> getPostsBySubreddit(Long id) {
40 | return status(HttpStatus.OK).body(postService.getPostsBySubreddit(id));
41 | }
42 |
43 | @GetMapping("by-user/{name}")
44 | public ResponseEntity> getPostsByUsername(String username) {
45 | return status(HttpStatus.OK).body(postService.getPostsByUsername(username));
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/controller/SubredditController.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.controller;
2 |
3 | import com.programming.techie.springredditclone.dto.SubredditDto;
4 | import com.programming.techie.springredditclone.service.SubredditService;
5 | import lombok.AllArgsConstructor;
6 | import lombok.extern.slf4j.Slf4j;
7 | import org.springframework.http.HttpStatus;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.web.bind.annotation.*;
10 |
11 | import java.util.List;
12 |
13 | @RestController
14 | @RequestMapping("/api/subreddit")
15 | @AllArgsConstructor
16 | @Slf4j
17 | public class SubredditController {
18 |
19 | private final SubredditService subredditService;
20 |
21 | @PostMapping
22 | public ResponseEntity createSubreddit(@RequestBody SubredditDto subredditDto) {
23 | return ResponseEntity.status(HttpStatus.CREATED)
24 | .body(subredditService.save(subredditDto));
25 | }
26 |
27 | @GetMapping
28 | public ResponseEntity> getAllSubreddits() {
29 | return ResponseEntity
30 | .status(HttpStatus.OK)
31 | .body(subredditService.getAll());
32 | }
33 |
34 | @GetMapping("/{id}")
35 | public ResponseEntity getSubreddit(@PathVariable Long id) {
36 | return ResponseEntity
37 | .status(HttpStatus.OK)
38 | .body(subredditService.getSubreddit(id));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/controller/VoteController.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.controller;
2 |
3 | import com.programming.techie.springredditclone.dto.VoteDto;
4 | import com.programming.techie.springredditclone.service.VoteService;
5 | import lombok.AllArgsConstructor;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.PostMapping;
9 | import org.springframework.web.bind.annotation.RequestBody;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | @RestController
14 | @RequestMapping("/api/votes/")
15 | @AllArgsConstructor
16 | public class VoteController {
17 |
18 | private final VoteService voteService;
19 |
20 | @PostMapping
21 | public ResponseEntity vote(@RequestBody VoteDto voteDto) {
22 | voteService.vote(voteDto);
23 | return new ResponseEntity<>(HttpStatus.OK);
24 | }
25 | }
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/AuthenticationResponse.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | import java.time.Instant;
9 |
10 | @Data
11 | @AllArgsConstructor
12 | @NoArgsConstructor
13 | @Builder
14 | public class AuthenticationResponse {
15 | private String authenticationToken;
16 | private String refreshToken;
17 | private Instant expiresAt;
18 | private String username;
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/CommentsDto.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import java.time.Instant;
8 |
9 | @Data
10 | @AllArgsConstructor
11 | @NoArgsConstructor
12 | public class CommentsDto {
13 | private Long id;
14 | private Long postId;
15 | private Instant createdDate;
16 | private String text;
17 | private String userName;
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/LoginRequest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | @Data
8 | @AllArgsConstructor
9 | @NoArgsConstructor
10 | public class LoginRequest {
11 |
12 | private String username;
13 | private String password;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/LogoutRequest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.validation.constraints.NotBlank;
8 |
9 | @Data
10 | @AllArgsConstructor
11 | @NoArgsConstructor
12 | public class LogoutRequest {
13 | @NotBlank
14 | private String refreshToken;
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/PostRequest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | @Data
8 | @AllArgsConstructor
9 | @NoArgsConstructor
10 | public class PostRequest {
11 | private Long postId;
12 | private String subredditName;
13 | private String postName;
14 | private String url;
15 | private String description;
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/PostResponse.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | @Data
8 | @AllArgsConstructor
9 | @NoArgsConstructor
10 | public class PostResponse {
11 | private Long id;
12 | private String postName;
13 | private String url;
14 | private String description;
15 | private String userName;
16 | private String subredditName;
17 | private Integer voteCount;
18 | private Integer commentCount;
19 | private String duration;
20 | private boolean upVote;
21 | private boolean downVote;
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/RefreshTokenRequest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.validation.constraints.NotBlank;
8 |
9 | @Data
10 | @AllArgsConstructor
11 | @NoArgsConstructor
12 | public class RefreshTokenRequest {
13 | @NotBlank
14 | private String refreshToken;
15 | private String username;
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/RegisterRequest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | @Data
8 | @AllArgsConstructor
9 | @NoArgsConstructor
10 | public class RegisterRequest {
11 | private String email;
12 | private String username;
13 | private String password;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/SubredditDto.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | @Data
9 | @AllArgsConstructor
10 | @NoArgsConstructor
11 | @Builder
12 | public class SubredditDto {
13 | private Long id;
14 | private String name;
15 | private String description;
16 | private Integer numberOfPosts;
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/dto/VoteDto.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.dto;
2 |
3 | import com.programming.techie.springredditclone.model.VoteType;
4 | import lombok.AllArgsConstructor;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | @Data
9 | @AllArgsConstructor
10 | @NoArgsConstructor
11 | public class VoteDto {
12 | private VoteType voteType;
13 | private Long postId;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/exceptions/PostNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.exceptions;
2 |
3 | public class PostNotFoundException extends RuntimeException {
4 | public PostNotFoundException(String message) {
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/exceptions/SpringRedditException.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.exceptions;
2 |
3 | public class SpringRedditException extends RuntimeException {
4 | public SpringRedditException(String exMessage, Exception exception) {
5 | super(exMessage, exception);
6 | }
7 |
8 | public SpringRedditException(String exMessage) {
9 | super(exMessage);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/exceptions/SubredditNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.exceptions;
2 |
3 | public class SubredditNotFoundException extends RuntimeException {
4 | public SubredditNotFoundException(String message) {
5 | super(message);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/mapper/CommentMapper.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.mapper;
2 |
3 | import com.programming.techie.springredditclone.dto.CommentsDto;
4 | import com.programming.techie.springredditclone.model.Comment;
5 | import com.programming.techie.springredditclone.model.Post;
6 | import com.programming.techie.springredditclone.model.User;
7 | import org.mapstruct.Mapper;
8 | import org.mapstruct.Mapping;
9 |
10 | @Mapper(componentModel = "spring")
11 | public interface CommentMapper {
12 | @Mapping(target = "id", ignore = true)
13 | @Mapping(target = "text", source = "commentsDto.text")
14 | @Mapping(target = "createdDate", expression = "java(java.time.Instant.now())")
15 | @Mapping(target = "post", source = "post")
16 | @Mapping(target = "user", source = "user")
17 | Comment map(CommentsDto commentsDto, Post post, User user);
18 |
19 | @Mapping(target = "postId", expression = "java(comment.getPost().getPostId())")
20 | @Mapping(target = "userName", expression = "java(comment.getUser().getUsername())")
21 | CommentsDto mapToDto(Comment comment);
22 | }
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/mapper/PostMapper.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.mapper;
2 |
3 | import com.github.marlonlom.utilities.timeago.TimeAgo;
4 | import com.programming.techie.springredditclone.dto.PostRequest;
5 | import com.programming.techie.springredditclone.dto.PostResponse;
6 | import com.programming.techie.springredditclone.model.*;
7 | import com.programming.techie.springredditclone.repository.CommentRepository;
8 | import com.programming.techie.springredditclone.repository.VoteRepository;
9 | import com.programming.techie.springredditclone.service.AuthService;
10 | import org.mapstruct.Mapper;
11 | import org.mapstruct.Mapping;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 |
14 | import java.util.Optional;
15 |
16 | import static com.programming.techie.springredditclone.model.VoteType.DOWNVOTE;
17 | import static com.programming.techie.springredditclone.model.VoteType.UPVOTE;
18 |
19 | @Mapper(componentModel = "spring")
20 | public abstract class PostMapper {
21 |
22 | @Autowired
23 | private CommentRepository commentRepository;
24 | @Autowired
25 | private VoteRepository voteRepository;
26 | @Autowired
27 | private AuthService authService;
28 |
29 |
30 | @Mapping(target = "createdDate", expression = "java(java.time.Instant.now())")
31 | @Mapping(target = "description", source = "postRequest.description")
32 | @Mapping(target = "subreddit", source = "subreddit")
33 | @Mapping(target = "voteCount", constant = "0")
34 | @Mapping(target = "user", source = "user")
35 | public abstract Post map(PostRequest postRequest, Subreddit subreddit, User user);
36 |
37 | @Mapping(target = "id", source = "postId")
38 | @Mapping(target = "subredditName", source = "subreddit.name")
39 | @Mapping(target = "userName", source = "user.username")
40 | @Mapping(target = "commentCount", expression = "java(commentCount(post))")
41 | @Mapping(target = "duration", expression = "java(getDuration(post))")
42 | @Mapping(target = "upVote", expression = "java(isPostUpVoted(post))")
43 | @Mapping(target = "downVote", expression = "java(isPostDownVoted(post))")
44 | public abstract PostResponse mapToDto(Post post);
45 |
46 | Integer commentCount(Post post) {
47 | return commentRepository.findByPost(post).size();
48 | }
49 |
50 | String getDuration(Post post) {
51 | return TimeAgo.using(post.getCreatedDate().toEpochMilli());
52 | }
53 |
54 | boolean isPostUpVoted(Post post) {
55 | return checkVoteType(post, UPVOTE);
56 | }
57 |
58 | boolean isPostDownVoted(Post post) {
59 | return checkVoteType(post, DOWNVOTE);
60 | }
61 |
62 | private boolean checkVoteType(Post post, VoteType voteType) {
63 | if (authService.isLoggedIn()) {
64 | Optional voteForPostByUser =
65 | voteRepository.findTopByPostAndUserOrderByVoteIdDesc(post,
66 | authService.getCurrentUser());
67 | return voteForPostByUser.filter(vote -> vote.getVoteType().equals(voteType))
68 | .isPresent();
69 | }
70 | return false;
71 | }
72 |
73 | }
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/mapper/SubredditMapper.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.mapper;
2 |
3 | import com.programming.techie.springredditclone.dto.SubredditDto;
4 | import com.programming.techie.springredditclone.model.Post;
5 | import com.programming.techie.springredditclone.model.Subreddit;
6 | import org.mapstruct.InheritInverseConfiguration;
7 | import org.mapstruct.Mapper;
8 | import org.mapstruct.Mapping;
9 |
10 | import java.util.List;
11 |
12 | @Mapper(componentModel = "spring")
13 | public interface SubredditMapper {
14 |
15 | @Mapping(target = "numberOfPosts", expression = "java(mapPosts(subreddit.getPosts()))")
16 | SubredditDto mapSubredditToDto(Subreddit subreddit);
17 |
18 | default Integer mapPosts(List numberOfPosts) {
19 | return numberOfPosts.size();
20 | }
21 |
22 | @InheritInverseConfiguration
23 | @Mapping(target = "posts", ignore = true)
24 | Subreddit mapDtoToSubreddit(SubredditDto subredditDto);
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/Comment.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.persistence.*;
8 | import javax.validation.constraints.NotEmpty;
9 | import java.time.Instant;
10 |
11 | import static javax.persistence.FetchType.LAZY;
12 | import static javax.persistence.GenerationType.IDENTITY;
13 |
14 | @Data
15 | @AllArgsConstructor
16 | @NoArgsConstructor
17 | @Entity
18 | public class Comment {
19 | @Id
20 | @GeneratedValue(strategy = IDENTITY)
21 | private Long id;
22 | @NotEmpty
23 | private String text;
24 | @ManyToOne(fetch = LAZY)
25 | @JoinColumn(name = "postId", referencedColumnName = "postId")
26 | private Post post;
27 | private Instant createdDate;
28 | @ManyToOne(fetch = LAZY)
29 | @JoinColumn(name = "userId", referencedColumnName = "userId")
30 | private User user;
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/NotificationEmail.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | @Data
8 | @AllArgsConstructor
9 | @NoArgsConstructor
10 | public class NotificationEmail {
11 | private String subject;
12 | private String recipient;
13 | private String body;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/Post.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 | import org.springframework.lang.Nullable;
8 |
9 | import javax.persistence.*;
10 | import javax.validation.constraints.NotBlank;
11 | import java.time.Instant;
12 |
13 | import static javax.persistence.FetchType.LAZY;
14 | import static javax.persistence.GenerationType.IDENTITY;
15 |
16 | @Data
17 | @Entity
18 | @Builder
19 | @AllArgsConstructor
20 | @NoArgsConstructor
21 | public class Post {
22 | @Id
23 | @GeneratedValue(strategy = IDENTITY)
24 | private Long postId;
25 | @NotBlank(message = "Post Name cannot be empty or Null")
26 | private String postName;
27 | @Nullable
28 | private String url;
29 | @Nullable
30 | @Lob
31 | private String description;
32 | private Integer voteCount = 0;
33 | @ManyToOne(fetch = LAZY)
34 | @JoinColumn(name = "userId", referencedColumnName = "userId")
35 | private User user;
36 | private Instant createdDate;
37 | @ManyToOne(fetch = LAZY)
38 | @JoinColumn(name = "id", referencedColumnName = "id")
39 | private Subreddit subreddit;
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/RefreshToken.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import java.time.Instant;
12 |
13 | @Data
14 | @Entity
15 | @AllArgsConstructor
16 | @NoArgsConstructor
17 | public class RefreshToken {
18 | @Id
19 | @GeneratedValue(strategy = GenerationType.IDENTITY)
20 | private Long id;
21 | private String token;
22 | private Instant createdDate;
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/Subreddit.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | import javax.persistence.*;
9 | import javax.validation.constraints.NotBlank;
10 | import java.time.Instant;
11 | import java.util.List;
12 |
13 | import static javax.persistence.FetchType.LAZY;
14 | import static javax.persistence.GenerationType.IDENTITY;
15 |
16 | @Data
17 | @AllArgsConstructor
18 | @NoArgsConstructor
19 | @Entity
20 | @Builder
21 | public class Subreddit {
22 | @Id
23 | @GeneratedValue(strategy = IDENTITY)
24 | private Long id;
25 | @NotBlank(message = "Community name is required")
26 | private String name;
27 | @NotBlank(message = "Description is required")
28 | private String description;
29 | @OneToMany(fetch = LAZY)
30 | private List posts;
31 | private Instant createdDate;
32 | @ManyToOne(fetch = LAZY)
33 | private User user;
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/User.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.Id;
10 | import javax.validation.constraints.Email;
11 | import javax.validation.constraints.NotBlank;
12 | import javax.validation.constraints.NotEmpty;
13 | import java.time.Instant;
14 |
15 | import static javax.persistence.GenerationType.IDENTITY;
16 |
17 | @Data
18 | @AllArgsConstructor
19 | @NoArgsConstructor
20 | @Entity
21 | public class User {
22 | @Id
23 | @GeneratedValue(strategy = IDENTITY)
24 | private Long userId;
25 | @NotBlank(message = "Username is required")
26 | private String username;
27 | @NotBlank(message = "Password is required")
28 | private String password;
29 | @Email
30 | @NotEmpty(message = "Email is required")
31 | private String email;
32 | private Instant created;
33 | private boolean enabled;
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/VerificationToken.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.persistence.*;
8 | import java.time.Instant;
9 |
10 | import static javax.persistence.FetchType.LAZY;
11 | import static javax.persistence.GenerationType.IDENTITY;
12 |
13 | @Data
14 | @AllArgsConstructor
15 | @NoArgsConstructor
16 | @Entity
17 | @Table(name = "token")
18 | public class VerificationToken {
19 |
20 | @Id
21 | @GeneratedValue(strategy = IDENTITY)
22 | private Long id;
23 | private String token;
24 | @OneToOne(fetch = LAZY)
25 | private User user;
26 | private Instant expiryDate;
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/Vote.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | import javax.persistence.*;
9 | import javax.validation.constraints.NotNull;
10 |
11 | import static javax.persistence.FetchType.LAZY;
12 | import static javax.persistence.GenerationType.IDENTITY;
13 |
14 | @Data
15 | @AllArgsConstructor
16 | @NoArgsConstructor
17 | @Entity
18 | @Builder
19 | public class Vote {
20 | @Id
21 | @GeneratedValue(strategy = IDENTITY)
22 | private Long voteId;
23 | private VoteType voteType;
24 | @NotNull
25 | @ManyToOne(fetch = LAZY)
26 | @JoinColumn(name = "postId", referencedColumnName = "postId")
27 | private Post post;
28 | @ManyToOne(fetch = LAZY)
29 | @JoinColumn(name = "userId", referencedColumnName = "userId")
30 | private User user;
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/model/VoteType.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.model;
2 |
3 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
4 |
5 | import java.util.Arrays;
6 |
7 | public enum VoteType {
8 | UPVOTE(1), DOWNVOTE(-1),
9 | ;
10 |
11 | private int direction;
12 |
13 | VoteType(int direction) {
14 | }
15 |
16 | public static VoteType lookup(Integer direction) {
17 | return Arrays.stream(VoteType.values())
18 | .filter(value -> value.getDirection().equals(direction))
19 | .findAny()
20 | .orElseThrow(() -> new SpringRedditException("Vote not found"));
21 | }
22 |
23 | public Integer getDirection() {
24 | return direction;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/CommentRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.Comment;
4 | import com.programming.techie.springredditclone.model.Post;
5 | import com.programming.techie.springredditclone.model.User;
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 | import org.springframework.stereotype.Repository;
8 |
9 | import java.util.List;
10 |
11 | @Repository
12 | public interface CommentRepository extends JpaRepository {
13 | List findByPost(Post post);
14 |
15 | List findAllByUser(User user);
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/PostRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.Post;
4 | import com.programming.techie.springredditclone.model.Subreddit;
5 | import com.programming.techie.springredditclone.model.User;
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 | import org.springframework.stereotype.Repository;
8 |
9 | import java.util.List;
10 |
11 | @Repository
12 | public interface PostRepository extends JpaRepository {
13 | List findAllBySubreddit(Subreddit subreddit);
14 |
15 | List findByUser(User user);
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/RefreshTokenRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.RefreshToken;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 |
6 | import java.util.Optional;
7 |
8 | public interface RefreshTokenRepository extends JpaRepository {
9 | Optional findByToken(String token);
10 |
11 | void deleteByToken(String token);
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/SubredditRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.Subreddit;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import org.springframework.stereotype.Repository;
6 |
7 | import java.util.Optional;
8 |
9 | @Repository
10 | public interface SubredditRepository extends JpaRepository {
11 |
12 | Optional findByName(String subredditName);
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.User;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import org.springframework.stereotype.Repository;
6 |
7 | import java.util.Optional;
8 |
9 | @Repository
10 | public interface UserRepository extends JpaRepository {
11 | Optional findByUsername(String username);
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/VerificationTokenRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.VerificationToken;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import org.springframework.stereotype.Repository;
6 |
7 | import java.util.Optional;
8 |
9 | @Repository
10 | public interface VerificationTokenRepository extends JpaRepository {
11 | Optional findByToken(String token);
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/repository/VoteRepository.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.Post;
4 | import com.programming.techie.springredditclone.model.User;
5 | import com.programming.techie.springredditclone.model.Vote;
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 | import org.springframework.stereotype.Repository;
8 |
9 | import java.util.Optional;
10 |
11 | @Repository
12 | public interface VoteRepository extends JpaRepository {
13 | Optional findTopByPostAndUserOrderByVoteIdDesc(Post post, User currentUser);
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/security/JwtAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.security;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
5 | import org.springframework.security.core.context.SecurityContextHolder;
6 | import org.springframework.security.core.userdetails.UserDetails;
7 | import org.springframework.security.core.userdetails.UserDetailsService;
8 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
9 | import org.springframework.stereotype.Component;
10 | import org.springframework.util.StringUtils;
11 | import org.springframework.web.filter.OncePerRequestFilter;
12 |
13 | import javax.servlet.FilterChain;
14 | import javax.servlet.ServletException;
15 | import javax.servlet.http.HttpServletRequest;
16 | import javax.servlet.http.HttpServletResponse;
17 | import java.io.IOException;
18 |
19 | @Component
20 | public class JwtAuthenticationFilter extends OncePerRequestFilter {
21 |
22 | @Autowired
23 | private JwtProvider jwtProvider;
24 | @Autowired
25 | private UserDetailsService userDetailsService;
26 |
27 | @Override
28 | protected void doFilterInternal(HttpServletRequest request,
29 | HttpServletResponse response,
30 | FilterChain filterChain) throws ServletException, IOException {
31 | String jwt = getJwtFromRequest(request);
32 |
33 | if (StringUtils.hasText(jwt) && jwtProvider.validateToken(jwt)) {
34 | String username = jwtProvider.getUsernameFromJwt(jwt);
35 |
36 | UserDetails userDetails = userDetailsService.loadUserByUsername(username);
37 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
38 | null, userDetails.getAuthorities());
39 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
40 |
41 | SecurityContextHolder.getContext().setAuthentication(authentication);
42 | }
43 | filterChain.doFilter(request, response);
44 | }
45 |
46 | private String getJwtFromRequest(HttpServletRequest request) {
47 | String bearerToken = request.getHeader("Authorization");
48 |
49 | if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
50 | return bearerToken.substring(7);
51 | }
52 | return bearerToken;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/security/JwtProvider.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.security;
2 |
3 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
4 | import io.jsonwebtoken.Claims;
5 | import io.jsonwebtoken.Jwts;
6 | import org.springframework.beans.factory.annotation.Value;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.security.core.userdetails.User;
9 | import org.springframework.stereotype.Service;
10 |
11 | import javax.annotation.PostConstruct;
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.security.*;
15 | import java.security.cert.CertificateException;
16 | import java.sql.Date;
17 | import java.time.Instant;
18 |
19 | import static io.jsonwebtoken.Jwts.parser;
20 | import static java.util.Date.from;
21 |
22 | @Service
23 | public class JwtProvider {
24 |
25 | private KeyStore keyStore;
26 | @Value("${jwt.expiration.time}")
27 | private Long jwtExpirationInMillis;
28 |
29 | @PostConstruct
30 | public void init() {
31 | try {
32 | keyStore = KeyStore.getInstance("JKS");
33 | InputStream resourceAsStream = getClass().getResourceAsStream("/springblog.jks");
34 | keyStore.load(resourceAsStream, "secret".toCharArray());
35 | } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
36 | throw new SpringRedditException("Exception occurred while loading keystore", e);
37 | }
38 |
39 | }
40 |
41 | public String generateToken(Authentication authentication) {
42 | User principal = (User) authentication.getPrincipal();
43 | return Jwts.builder()
44 | .setSubject(principal.getUsername())
45 | .setIssuedAt(from(Instant.now()))
46 | .signWith(getPrivateKey())
47 | .setExpiration(Date.from(Instant.now().plusMillis(jwtExpirationInMillis)))
48 | .compact();
49 | }
50 |
51 | public String generateTokenWithUserName(String username) {
52 | return Jwts.builder()
53 | .setSubject(username)
54 | .setIssuedAt(from(Instant.now()))
55 | .signWith(getPrivateKey())
56 | .setExpiration(Date.from(Instant.now().plusMillis(jwtExpirationInMillis)))
57 | .compact();
58 | }
59 |
60 | private PrivateKey getPrivateKey() {
61 | try {
62 | return (PrivateKey) keyStore.getKey("springblog", "secret".toCharArray());
63 | } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
64 | throw new SpringRedditException("Exception occured while retrieving public key from keystore", e);
65 | }
66 | }
67 |
68 | public boolean validateToken(String jwt) {
69 | parser().setSigningKey(getPublickey()).parseClaimsJws(jwt);
70 | return true;
71 | }
72 |
73 | private PublicKey getPublickey() {
74 | try {
75 | return keyStore.getCertificate("springblog").getPublicKey();
76 | } catch (KeyStoreException e) {
77 | throw new SpringRedditException("Exception occured while " +
78 | "retrieving public key from keystore", e);
79 | }
80 | }
81 |
82 | public String getUsernameFromJwt(String token) {
83 | Claims claims = parser()
84 | .setSigningKey(getPublickey())
85 | .parseClaimsJws(token)
86 | .getBody();
87 |
88 | return claims.getSubject();
89 | }
90 |
91 | public Long getJwtExpirationInMillis() {
92 | return jwtExpirationInMillis;
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/AuthService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.dto.AuthenticationResponse;
4 | import com.programming.techie.springredditclone.dto.LoginRequest;
5 | import com.programming.techie.springredditclone.dto.RefreshTokenRequest;
6 | import com.programming.techie.springredditclone.dto.RegisterRequest;
7 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
8 | import com.programming.techie.springredditclone.model.NotificationEmail;
9 | import com.programming.techie.springredditclone.model.User;
10 | import com.programming.techie.springredditclone.model.VerificationToken;
11 | import com.programming.techie.springredditclone.repository.UserRepository;
12 | import com.programming.techie.springredditclone.repository.VerificationTokenRepository;
13 | import com.programming.techie.springredditclone.security.JwtProvider;
14 | import lombok.AllArgsConstructor;
15 | import org.springframework.security.authentication.AnonymousAuthenticationToken;
16 | import org.springframework.security.authentication.AuthenticationManager;
17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
18 | import org.springframework.security.core.Authentication;
19 | import org.springframework.security.core.context.SecurityContextHolder;
20 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
21 | import org.springframework.security.crypto.password.PasswordEncoder;
22 | import org.springframework.stereotype.Service;
23 | import org.springframework.transaction.annotation.Transactional;
24 |
25 | import java.time.Instant;
26 | import java.util.Optional;
27 | import java.util.UUID;
28 |
29 | @Service
30 | @AllArgsConstructor
31 | @Transactional
32 | public class AuthService {
33 |
34 | private final PasswordEncoder passwordEncoder;
35 | private final UserRepository userRepository;
36 | private final VerificationTokenRepository verificationTokenRepository;
37 | private final MailService mailService;
38 | private final AuthenticationManager authenticationManager;
39 | private final JwtProvider jwtProvider;
40 | private final RefreshTokenService refreshTokenService;
41 |
42 | public void signup(RegisterRequest registerRequest) {
43 | User user = new User();
44 | user.setUsername(registerRequest.getUsername());
45 | user.setEmail(registerRequest.getEmail());
46 | user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
47 | user.setCreated(Instant.now());
48 | user.setEnabled(false);
49 |
50 | userRepository.save(user);
51 |
52 | String token = generateVerificationToken(user);
53 | mailService.sendMail(new NotificationEmail("Please Activate your Account",
54 | user.getEmail(), "Thank you for signing up to Spring Reddit, " +
55 | "please click on the below url to activate your account : " +
56 | "http://localhost:8080/api/auth/accountVerification/" + token));
57 | }
58 |
59 | @Transactional(readOnly = true)
60 | public User getCurrentUser() {
61 | org.springframework.security.core.userdetails.User principal = (org.springframework.security.core.userdetails.User) SecurityContextHolder.
62 | getContext().getAuthentication().getPrincipal();
63 | return userRepository.findByUsername(principal.getUsername())
64 | .orElseThrow(() -> new UsernameNotFoundException("User name not found - " + principal.getUsername()));
65 | }
66 |
67 | private void fetchUserAndEnable(VerificationToken verificationToken) {
68 | String username = verificationToken.getUser().getUsername();
69 | User user = userRepository.findByUsername(username).orElseThrow(() -> new SpringRedditException("User not found with name - " + username));
70 | user.setEnabled(true);
71 | userRepository.save(user);
72 | }
73 |
74 | private String generateVerificationToken(User user) {
75 | String token = UUID.randomUUID().toString();
76 | VerificationToken verificationToken = new VerificationToken();
77 | verificationToken.setToken(token);
78 | verificationToken.setUser(user);
79 |
80 | verificationTokenRepository.save(verificationToken);
81 | return token;
82 | }
83 |
84 | public void verifyAccount(String token) {
85 | Optional verificationToken = verificationTokenRepository.findByToken(token);
86 | fetchUserAndEnable(verificationToken.orElseThrow(() -> new SpringRedditException("Invalid Token")));
87 | }
88 |
89 | public AuthenticationResponse login(LoginRequest loginRequest) {
90 | Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
91 | loginRequest.getPassword()));
92 | SecurityContextHolder.getContext().setAuthentication(authenticate);
93 | String token = jwtProvider.generateToken(authenticate);
94 | return AuthenticationResponse.builder()
95 | .authenticationToken(token)
96 | .refreshToken(refreshTokenService.generateRefreshToken().getToken())
97 | .expiresAt(Instant.now().plusMillis(jwtProvider.getJwtExpirationInMillis()))
98 | .username(loginRequest.getUsername())
99 | .build();
100 | }
101 |
102 | public AuthenticationResponse refreshToken(RefreshTokenRequest refreshTokenRequest) {
103 | refreshTokenService.validateRefreshToken(refreshTokenRequest.getRefreshToken());
104 | String token = jwtProvider.generateTokenWithUserName(refreshTokenRequest.getUsername());
105 | return AuthenticationResponse.builder()
106 | .authenticationToken(token)
107 | .refreshToken(refreshTokenRequest.getRefreshToken())
108 | .expiresAt(Instant.now().plusMillis(jwtProvider.getJwtExpirationInMillis()))
109 | .username(refreshTokenRequest.getUsername())
110 | .build();
111 | }
112 |
113 | public boolean isLoggedIn() {
114 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
115 | return !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
116 | }
117 | }
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/CommentService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.dto.CommentsDto;
4 | import com.programming.techie.springredditclone.exceptions.PostNotFoundException;
5 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
6 | import com.programming.techie.springredditclone.mapper.CommentMapper;
7 | import com.programming.techie.springredditclone.model.Comment;
8 | import com.programming.techie.springredditclone.model.NotificationEmail;
9 | import com.programming.techie.springredditclone.model.Post;
10 | import com.programming.techie.springredditclone.model.User;
11 | import com.programming.techie.springredditclone.repository.CommentRepository;
12 | import com.programming.techie.springredditclone.repository.PostRepository;
13 | import com.programming.techie.springredditclone.repository.UserRepository;
14 | import lombok.AllArgsConstructor;
15 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
16 | import org.springframework.stereotype.Service;
17 |
18 | import java.util.List;
19 |
20 | import static java.util.stream.Collectors.toList;
21 |
22 | @Service
23 | @AllArgsConstructor
24 | public class CommentService {
25 | private static final String POST_URL = "";
26 | private final PostRepository postRepository;
27 | private final UserRepository userRepository;
28 | private final AuthService authService;
29 | private final CommentMapper commentMapper;
30 | private final CommentRepository commentRepository;
31 | private final MailContentBuilder mailContentBuilder;
32 | private final MailService mailService;
33 |
34 | public void save(CommentsDto commentsDto) {
35 | Post post = postRepository.findById(commentsDto.getPostId())
36 | .orElseThrow(() -> new PostNotFoundException(commentsDto.getPostId().toString()));
37 | Comment comment = commentMapper.map(commentsDto, post, authService.getCurrentUser());
38 | commentRepository.save(comment);
39 |
40 | String message = mailContentBuilder.build(authService.getCurrentUser() + " posted a comment on your post." + POST_URL);
41 | sendCommentNotification(message, post.getUser());
42 | }
43 |
44 | private void sendCommentNotification(String message, User user) {
45 | mailService.sendMail(new NotificationEmail(user.getUsername() + " Commented on your post", user.getEmail(), message));
46 | }
47 |
48 | public List getAllCommentsForPost(Long postId) {
49 | Post post = postRepository.findById(postId)
50 | .orElseThrow(() -> new PostNotFoundException(postId.toString()));
51 | return commentRepository.findByPost(post)
52 | .stream()
53 | .map(commentMapper::mapToDto).collect(toList());
54 | }
55 |
56 | public List getAllCommentsForUser(String userName) {
57 | User user = userRepository.findByUsername(userName)
58 | .orElseThrow(() -> new UsernameNotFoundException(userName));
59 | return commentRepository.findAllByUser(user)
60 | .stream()
61 | .map(commentMapper::mapToDto)
62 | .collect(toList());
63 | }
64 |
65 | public boolean containsSwearWords(String comment) {
66 | if (comment.contains("shit")) {
67 | throw new SpringRedditException("Comments contains unacceptable language");
68 | }
69 | return false;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/MailContentBuilder.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import lombok.AllArgsConstructor;
4 | import org.springframework.stereotype.Service;
5 | import org.thymeleaf.TemplateEngine;
6 | import org.thymeleaf.context.Context;
7 |
8 | @Service
9 | @AllArgsConstructor
10 | public class MailContentBuilder {
11 |
12 | private final TemplateEngine templateEngine;
13 |
14 | public String build(String message) {
15 | Context context = new Context();
16 | context.setVariable("message", message);
17 | return templateEngine.process("mailTemplate", context);
18 | }
19 | }
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/MailService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
4 | import com.programming.techie.springredditclone.model.NotificationEmail;
5 | import lombok.AllArgsConstructor;
6 | import lombok.extern.slf4j.Slf4j;
7 | import org.springframework.mail.MailException;
8 | import org.springframework.mail.javamail.JavaMailSender;
9 | import org.springframework.mail.javamail.MimeMessageHelper;
10 | import org.springframework.mail.javamail.MimeMessagePreparator;
11 | import org.springframework.scheduling.annotation.Async;
12 | import org.springframework.stereotype.Service;
13 |
14 | @Service
15 | @AllArgsConstructor
16 | @Slf4j
17 | class MailService {
18 |
19 | private final JavaMailSender mailSender;
20 | private final MailContentBuilder mailContentBuilder;
21 |
22 | @Async
23 | void sendMail(NotificationEmail notificationEmail) {
24 | MimeMessagePreparator messagePreparator = mimeMessage -> {
25 | MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
26 | messageHelper.setFrom("springreddit@email.com");
27 | messageHelper.setTo(notificationEmail.getRecipient());
28 | messageHelper.setSubject(notificationEmail.getSubject());
29 | messageHelper.setText(notificationEmail.getBody());
30 | };
31 | try {
32 | mailSender.send(messagePreparator);
33 | log.info("Activation email sent!!");
34 | } catch (MailException e) {
35 | log.error("Exception occurred when sending mail", e);
36 | throw new SpringRedditException("Exception occurred when sending mail to " + notificationEmail.getRecipient(), e);
37 | }
38 | }
39 |
40 | }
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/PostService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.dto.PostRequest;
4 | import com.programming.techie.springredditclone.dto.PostResponse;
5 | import com.programming.techie.springredditclone.exceptions.PostNotFoundException;
6 | import com.programming.techie.springredditclone.exceptions.SubredditNotFoundException;
7 | import com.programming.techie.springredditclone.mapper.PostMapper;
8 | import com.programming.techie.springredditclone.model.Post;
9 | import com.programming.techie.springredditclone.model.Subreddit;
10 | import com.programming.techie.springredditclone.model.User;
11 | import com.programming.techie.springredditclone.repository.PostRepository;
12 | import com.programming.techie.springredditclone.repository.SubredditRepository;
13 | import com.programming.techie.springredditclone.repository.UserRepository;
14 | import lombok.AllArgsConstructor;
15 | import lombok.extern.slf4j.Slf4j;
16 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
17 | import org.springframework.stereotype.Service;
18 | import org.springframework.transaction.annotation.Transactional;
19 |
20 | import java.util.List;
21 |
22 | import static java.util.stream.Collectors.toList;
23 |
24 | @Service
25 | @AllArgsConstructor
26 | @Slf4j
27 | @Transactional
28 | public class PostService {
29 |
30 | private final PostRepository postRepository;
31 | private final SubredditRepository subredditRepository;
32 | private final UserRepository userRepository;
33 | private final AuthService authService;
34 | private final PostMapper postMapper;
35 |
36 | public void save(PostRequest postRequest) {
37 | Subreddit subreddit = subredditRepository.findByName(postRequest.getSubredditName())
38 | .orElseThrow(() -> new SubredditNotFoundException(postRequest.getSubredditName()));
39 | postRepository.save(postMapper.map(postRequest, subreddit, authService.getCurrentUser()));
40 | }
41 |
42 | @Transactional(readOnly = true)
43 | public PostResponse getPost(Long id) {
44 | Post post = postRepository.findById(id)
45 | .orElseThrow(() -> new PostNotFoundException(id.toString()));
46 | return postMapper.mapToDto(post);
47 | }
48 |
49 | @Transactional(readOnly = true)
50 | public List getAllPosts() {
51 | return postRepository.findAll()
52 | .stream()
53 | .map(postMapper::mapToDto)
54 | .collect(toList());
55 | }
56 |
57 | @Transactional(readOnly = true)
58 | public List getPostsBySubreddit(Long subredditId) {
59 | Subreddit subreddit = subredditRepository.findById(subredditId)
60 | .orElseThrow(() -> new SubredditNotFoundException(subredditId.toString()));
61 | List posts = postRepository.findAllBySubreddit(subreddit);
62 | return posts.stream().map(postMapper::mapToDto).collect(toList());
63 | }
64 |
65 | @Transactional(readOnly = true)
66 | public List getPostsByUsername(String username) {
67 | User user = userRepository.findByUsername(username)
68 | .orElseThrow(() -> new UsernameNotFoundException(username));
69 | return postRepository.findByUser(user)
70 | .stream()
71 | .map(postMapper::mapToDto)
72 | .collect(toList());
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/RefreshTokenService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
4 | import com.programming.techie.springredditclone.model.RefreshToken;
5 | import com.programming.techie.springredditclone.repository.RefreshTokenRepository;
6 | import lombok.AllArgsConstructor;
7 | import org.springframework.stereotype.Service;
8 | import org.springframework.transaction.annotation.Transactional;
9 |
10 | import java.time.Instant;
11 | import java.util.UUID;
12 |
13 | @Service
14 | @AllArgsConstructor
15 | @Transactional
16 | public class RefreshTokenService {
17 |
18 | private final RefreshTokenRepository refreshTokenRepository;
19 |
20 | public RefreshToken generateRefreshToken() {
21 | RefreshToken refreshToken = new RefreshToken();
22 | refreshToken.setToken(UUID.randomUUID().toString());
23 | refreshToken.setCreatedDate(Instant.now());
24 |
25 | return refreshTokenRepository.save(refreshToken);
26 | }
27 |
28 | void validateRefreshToken(String token) {
29 | refreshTokenRepository.findByToken(token)
30 | .orElseThrow(() -> new SpringRedditException("Invalid refresh Token"));
31 | }
32 |
33 | public void deleteRefreshToken(String token) {
34 | refreshTokenRepository.deleteByToken(token);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/SubredditService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.dto.SubredditDto;
4 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
5 | import com.programming.techie.springredditclone.mapper.SubredditMapper;
6 | import com.programming.techie.springredditclone.model.Subreddit;
7 | import com.programming.techie.springredditclone.repository.SubredditRepository;
8 | import lombok.AllArgsConstructor;
9 | import lombok.extern.slf4j.Slf4j;
10 | import org.springframework.stereotype.Service;
11 | import org.springframework.transaction.annotation.Transactional;
12 |
13 | import java.util.List;
14 |
15 | import static java.util.stream.Collectors.toList;
16 |
17 | @Service
18 | @AllArgsConstructor
19 | @Slf4j
20 | public class SubredditService {
21 |
22 | private final SubredditRepository subredditRepository;
23 | private final SubredditMapper subredditMapper;
24 |
25 | @Transactional
26 | public SubredditDto save(SubredditDto subredditDto) {
27 | Subreddit save = subredditRepository.save(subredditMapper.mapDtoToSubreddit(subredditDto));
28 | subredditDto.setId(save.getId());
29 | return subredditDto;
30 | }
31 |
32 | @Transactional(readOnly = true)
33 | public List getAll() {
34 | return subredditRepository.findAll()
35 | .stream()
36 | .map(subredditMapper::mapSubredditToDto)
37 | .collect(toList());
38 | }
39 |
40 | public SubredditDto getSubreddit(Long id) {
41 | Subreddit subreddit = subredditRepository.findById(id)
42 | .orElseThrow(() -> new SpringRedditException("No subreddit found with ID - " + id));
43 | return subredditMapper.mapSubredditToDto(subreddit);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/UserDetailsServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.model.User;
4 | import com.programming.techie.springredditclone.repository.UserRepository;
5 | import lombok.AllArgsConstructor;
6 | import org.springframework.security.core.GrantedAuthority;
7 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
8 | import org.springframework.security.core.userdetails.UserDetails;
9 | import org.springframework.security.core.userdetails.UserDetailsService;
10 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
11 | import org.springframework.stereotype.Service;
12 | import org.springframework.transaction.annotation.Transactional;
13 |
14 | import java.util.Collection;
15 | import java.util.Optional;
16 |
17 | import static java.util.Collections.singletonList;
18 |
19 | @Service
20 | @AllArgsConstructor
21 | public class UserDetailsServiceImpl implements UserDetailsService {
22 | private final UserRepository userRepository;
23 |
24 | @Override
25 | @Transactional(readOnly = true)
26 | public UserDetails loadUserByUsername(String username) {
27 | Optional userOptional = userRepository.findByUsername(username);
28 | User user = userOptional
29 | .orElseThrow(() -> new UsernameNotFoundException("No user " +
30 | "Found with username : " + username));
31 |
32 | return new org.springframework.security
33 | .core.userdetails.User(user.getUsername(), user.getPassword(),
34 | user.isEnabled(), true, true,
35 | true, getAuthorities("USER"));
36 | }
37 |
38 | private Collection extends GrantedAuthority> getAuthorities(String role) {
39 | return singletonList(new SimpleGrantedAuthority(role));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/programming/techie/springredditclone/service/VoteService.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.dto.VoteDto;
4 | import com.programming.techie.springredditclone.exceptions.PostNotFoundException;
5 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
6 | import com.programming.techie.springredditclone.model.Post;
7 | import com.programming.techie.springredditclone.model.Vote;
8 | import com.programming.techie.springredditclone.repository.PostRepository;
9 | import com.programming.techie.springredditclone.repository.VoteRepository;
10 | import lombok.AllArgsConstructor;
11 | import org.springframework.stereotype.Service;
12 | import org.springframework.transaction.annotation.Transactional;
13 |
14 | import java.util.Optional;
15 |
16 | import static com.programming.techie.springredditclone.model.VoteType.UPVOTE;
17 |
18 | @Service
19 | @AllArgsConstructor
20 | public class VoteService {
21 |
22 | private final VoteRepository voteRepository;
23 | private final PostRepository postRepository;
24 | private final AuthService authService;
25 |
26 | @Transactional
27 | public void vote(VoteDto voteDto) {
28 | Post post = postRepository.findById(voteDto.getPostId())
29 | .orElseThrow(() -> new PostNotFoundException("Post Not Found with ID - " + voteDto.getPostId()));
30 | Optional voteByPostAndUser = voteRepository.findTopByPostAndUserOrderByVoteIdDesc(post, authService.getCurrentUser());
31 | if (voteByPostAndUser.isPresent() &&
32 | voteByPostAndUser.get().getVoteType()
33 | .equals(voteDto.getVoteType())) {
34 | throw new SpringRedditException("You have already "
35 | + voteDto.getVoteType() + "'d for this post");
36 | }
37 | if (UPVOTE.equals(voteDto.getVoteType())) {
38 | post.setVoteCount(post.getVoteCount() + 1);
39 | } else {
40 | post.setVoteCount(post.getVoteCount() - 1);
41 | }
42 | voteRepository.save(mapToVote(voteDto, post));
43 | postRepository.save(post);
44 | }
45 |
46 | private Vote mapToVote(VoteDto voteDto, Post post) {
47 | return Vote.builder()
48 | .voteType(voteDto.getVoteType())
49 | .post(post)
50 | .user(authService.getCurrentUser())
51 | .build();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/resources/application-test.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.driver-class-name=org.h2.Driver
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 | spring.datasource.username=sa
4 | spring.datasource.password=
5 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
6 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | ############# Database Properties ###########################################
2 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3 | spring.datasource.url=jdbc:mysql://localhost:3306/spring-reddit-clone?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
4 | spring.datasource.username=root
5 | spring.datasource.password=mysql
6 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
7 | spring.jpa.hibernate.ddl-auto=update
8 | spring.datasource.initialization-mode=always
9 | spring.jpa.show-sql=true
10 | ############# Mail Properties ###########################################
11 | spring.mail.host=smtp.mailtrap.io
12 | spring.mail.port=25
13 | spring.mail.username=
14 | spring.mail.password=
15 | spring.mail.protocol=smtp
16 | ############ JWT Properties #####################
17 | jwt.expiration.time=90000
18 |
--------------------------------------------------------------------------------
/src/main/resources/images/create-post.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/src/main/resources/images/create-post.PNG
--------------------------------------------------------------------------------
/src/main/resources/images/create-subreddit.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/src/main/resources/images/create-subreddit.PNG
--------------------------------------------------------------------------------
/src/main/resources/images/reddit-screenshot-updated.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/src/main/resources/images/reddit-screenshot-updated.PNG
--------------------------------------------------------------------------------
/src/main/resources/images/spring-reddit-view-post.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/src/main/resources/images/spring-reddit-view-post.PNG
--------------------------------------------------------------------------------
/src/main/resources/images/user-profile.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/src/main/resources/images/user-profile.PNG
--------------------------------------------------------------------------------
/src/main/resources/springblog.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaiUpadhyayula/spring-boot-testing-reddit-clone/3893cb52cd28121e32740a058469c2958da911af/src/main/resources/springblog.jks
--------------------------------------------------------------------------------
/src/main/resources/templates/mailTemplate.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/BaseTest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone;
2 |
3 | import org.testcontainers.containers.MySQLContainer;
4 |
5 | public abstract class BaseTest {
6 |
7 | static MySQLContainer mySQLContainer = (MySQLContainer) new MySQLContainer("mysql:latest")
8 | .withDatabaseName("spring-reddit-test-db")
9 | .withUsername("testuser")
10 | .withPassword("pass")
11 | .withReuse(true);
12 |
13 | static {
14 | mySQLContainer.start();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/controller/PostControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.controller;
2 |
3 | import com.programming.techie.springredditclone.dto.PostResponse;
4 | import com.programming.techie.springredditclone.security.JwtProvider;
5 | import com.programming.techie.springredditclone.service.PostService;
6 | import com.programming.techie.springredditclone.service.UserDetailsServiceImpl;
7 | import org.hamcrest.Matchers;
8 | import org.junit.jupiter.api.DisplayName;
9 | import org.junit.jupiter.api.Test;
10 | import org.mockito.Mock;
11 | import org.mockito.Mockito;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
14 | import org.springframework.boot.test.mock.mockito.MockBean;
15 | import org.springframework.http.MediaType;
16 | import org.springframework.test.web.servlet.MockMvc;
17 |
18 | import static java.util.Arrays.asList;
19 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
20 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
21 |
22 | @WebMvcTest(controllers = PostController.class)
23 | public class PostControllerTest {
24 |
25 | @MockBean
26 | private PostService postService;
27 | @MockBean
28 | private UserDetailsServiceImpl userDetailsService;
29 | @MockBean
30 | private JwtProvider jwtProvider;
31 |
32 | @Autowired
33 | private MockMvc mockMvc;
34 |
35 | @Test
36 | @DisplayName("Should List All Posts When making GET request to endpoint - /api/posts/")
37 | public void shouldCreatePost() throws Exception {
38 | PostResponse postRequest1 = new PostResponse(1L, "Post Name", "http://url.site", "Description", "User 1",
39 | "Subreddit Name", 0, 0, "1 day ago", false, false);
40 | PostResponse postRequest2 = new PostResponse(2L, "Post Name 2", "http://url2.site2", "Description2", "User 2",
41 | "Subreddit Name 2", 0, 0, "2 days ago", false, false);
42 |
43 | Mockito.when(postService.getAllPosts()).thenReturn(asList(postRequest1, postRequest2));
44 |
45 | mockMvc.perform(get("/api/posts/"))
46 | .andExpect(status().is(200))
47 | .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
48 | .andExpect(jsonPath("$.size()", Matchers.is(2)))
49 | .andExpect(jsonPath("$[0].id", Matchers.is(1)))
50 | .andExpect(jsonPath("$[0].postName", Matchers.is("Post Name")))
51 | .andExpect(jsonPath("$[0].url", Matchers.is("http://url.site")))
52 | .andExpect(jsonPath("$[1].url", Matchers.is("http://url2.site2")))
53 | .andExpect(jsonPath("$[1].postName", Matchers.is("Post Name 2")))
54 | .andExpect(jsonPath("$[1].id", Matchers.is(2)));
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/repository/PostRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.BaseTest;
4 | import com.programming.techie.springredditclone.model.Post;
5 | import org.junit.jupiter.api.Test;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
9 |
10 | import java.time.Instant;
11 |
12 | import static org.assertj.core.api.Assertions.assertThat;
13 |
14 | @DataJpaTest
15 | @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
16 | public class PostRepositoryTest extends BaseTest {
17 |
18 | @Autowired
19 | private PostRepository postRepository;
20 |
21 | @Test
22 | public void shouldSavePost() {
23 | Post expectedPostObject = new Post(null, "First Post", "http://url.site", "Test",
24 | 0, null, Instant.now(), null);
25 | Post actualPostObject = postRepository.save(expectedPostObject);
26 | assertThat(actualPostObject).usingRecursiveComparison()
27 | .ignoringFields("postId").isEqualTo(expectedPostObject);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/repository/UserRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.BaseTest;
4 | import com.programming.techie.springredditclone.model.User;
5 | import org.junit.jupiter.api.Test;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
9 | import org.testcontainers.containers.MySQLContainer;
10 |
11 | import java.time.Instant;
12 |
13 | import static org.assertj.core.api.Assertions.assertThat;
14 |
15 | @DataJpaTest
16 | @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
17 | public class UserRepositoryTest extends BaseTest {
18 |
19 | @Autowired
20 | private UserRepository userRepository;
21 |
22 | @Test
23 | public void shouldSavePost() {
24 | User expectedUserObject = new User(123L, "test user", "secret password", "user@email.com", Instant.now(), true);
25 | User actualUserObject = userRepository.save(expectedUserObject);
26 | assertThat(actualUserObject).usingRecursiveComparison()
27 | .ignoringFields("userId").isEqualTo(expectedUserObject);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/repository/UserRepositoryTestEmbedded.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.repository;
2 |
3 | import com.programming.techie.springredditclone.model.User;
4 | import org.junit.jupiter.api.Test;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
7 | import org.springframework.test.context.ActiveProfiles;
8 | import org.springframework.test.context.jdbc.Sql;
9 |
10 | import java.time.Instant;
11 | import java.util.Optional;
12 |
13 | import static org.assertj.core.api.Assertions.assertThat;
14 |
15 | @DataJpaTest
16 | @ActiveProfiles("test")
17 | public class UserRepositoryTestEmbedded {
18 |
19 | @Autowired
20 | private UserRepository userRepository;
21 |
22 | @Test
23 | public void shouldSaveUser() {
24 | User user = new User(null, "test user", "secret password", "user@email.com", Instant.now(), true);
25 | User savedUser = userRepository.save(user);
26 | assertThat(savedUser).usingRecursiveComparison().ignoringFields("userId").isEqualTo(user);
27 | }
28 |
29 | @Test
30 | @Sql("classpath:test-data.sql")
31 | public void shouldSaveUsersThroughSqlFile() {
32 | Optional test = userRepository.findByUsername("testuser_sql");
33 | assertThat(test).isNotEmpty();
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/service/CommentServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.exceptions.SpringRedditException;
4 | import org.junit.jupiter.api.DisplayName;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import static org.assertj.core.api.Assertions.assertThat;
8 | import static org.assertj.core.api.Assertions.assertThatThrownBy;
9 |
10 | public class CommentServiceTest {
11 |
12 | @Test
13 | @DisplayName("Test Should Pass When Comment do not Contains Swear Words")
14 | public void shouldNotContainSwearWordsInsideComment() {
15 | CommentService commentService = new CommentService(null, null, null, null, null, null, null);
16 | assertThat(commentService.containsSwearWords("This is a comment")).isFalse();
17 | }
18 |
19 | @Test
20 | @DisplayName("Should Throw Exception when Exception Contains Swear Words")
21 | public void shouldFailWhenCommentContainsSwearWords() {
22 | CommentService commentService = new CommentService(null, null, null, null, null, null, null);
23 |
24 | assertThatThrownBy(() -> {
25 | commentService.containsSwearWords("This is a shitty comment");
26 | }).isInstanceOf(SpringRedditException.class)
27 | .hasMessage("Comments contains unacceptable language");
28 | }
29 | }
30 |
31 |
32 |
--------------------------------------------------------------------------------
/src/test/java/com/programming/techie/springredditclone/service/PostServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.programming.techie.springredditclone.service;
2 |
3 | import com.programming.techie.springredditclone.dto.PostRequest;
4 | import com.programming.techie.springredditclone.dto.PostResponse;
5 | import com.programming.techie.springredditclone.mapper.PostMapper;
6 | import com.programming.techie.springredditclone.model.Post;
7 | import com.programming.techie.springredditclone.model.Subreddit;
8 | import com.programming.techie.springredditclone.model.User;
9 | import com.programming.techie.springredditclone.repository.PostRepository;
10 | import com.programming.techie.springredditclone.repository.SubredditRepository;
11 | import com.programming.techie.springredditclone.repository.UserRepository;
12 | import org.assertj.core.api.Assertions;
13 | import org.junit.jupiter.api.BeforeEach;
14 | import org.junit.jupiter.api.DisplayName;
15 | import org.junit.jupiter.api.Test;
16 | import org.junit.jupiter.api.extension.ExtendWith;
17 | import org.mockito.ArgumentCaptor;
18 | import org.mockito.Captor;
19 | import org.mockito.Mock;
20 | import org.mockito.Mockito;
21 | import org.mockito.junit.jupiter.MockitoExtension;
22 |
23 | import java.time.Instant;
24 | import java.util.Optional;
25 |
26 | import static java.util.Collections.emptyList;
27 |
28 | @ExtendWith(MockitoExtension.class)
29 | class PostServiceTest {
30 |
31 | @Mock
32 | private PostRepository postRepository;
33 | @Mock
34 | private SubredditRepository subredditRepository;
35 | @Mock
36 | private UserRepository userRepository;
37 | @Mock
38 | private AuthService authService;
39 | @Mock
40 | private PostMapper postMapper;
41 |
42 | @Captor
43 | private ArgumentCaptor postArgumentCaptor;
44 |
45 | private PostService postService;
46 |
47 | @BeforeEach
48 | public void setup() {
49 | postService = new PostService(postRepository, subredditRepository, userRepository, authService, postMapper);
50 | }
51 |
52 | @Test
53 | @DisplayName("Should Retrieve Post by Id")
54 | public void shouldFindPostById() {
55 | Post post = new Post(123L, "First Post", "http://url.site", "Test",
56 | 0, null, Instant.now(), null);
57 | PostResponse expectedPostResponse = new PostResponse(123L, "First Post", "http://url.site", "Test",
58 | "Test User", "Test Subredit", 0, 0, "1 Hour Ago", false, false);
59 |
60 | Mockito.when(postRepository.findById(123L)).thenReturn(Optional.of(post));
61 | Mockito.when(postMapper.mapToDto(Mockito.any(Post.class))).thenReturn(expectedPostResponse);
62 |
63 | PostResponse actualPostResponse = postService.getPost(123L);
64 |
65 | Assertions.assertThat(actualPostResponse.getId()).isEqualTo(expectedPostResponse.getId());
66 | Assertions.assertThat(actualPostResponse.getPostName()).isEqualTo(expectedPostResponse.getPostName());
67 | }
68 |
69 | @Test
70 | @DisplayName("Should Save Posts")
71 | public void shouldSavePosts() {
72 | User currentUser = new User(123L, "test user", "secret password", "user@email.com", Instant.now(), true);
73 | Subreddit subreddit = new Subreddit(123L, "First Subreddit", "Subreddit Description", emptyList(), Instant.now(), currentUser);
74 | Post post = new Post(123L, "First Post", "http://url.site", "Test",
75 | 0, null, Instant.now(), null);
76 | PostRequest postRequest = new PostRequest(null, "First Subreddit", "First Post", "http://url.site", "Test");
77 |
78 | Mockito.when(subredditRepository.findByName("First Subreddit"))
79 | .thenReturn(Optional.of(subreddit));
80 | Mockito.when(authService.getCurrentUser())
81 | .thenReturn(currentUser);
82 | Mockito.when(postMapper.map(postRequest, subreddit, currentUser))
83 | .thenReturn(post);
84 |
85 | postService.save(postRequest);
86 | Mockito.verify(postRepository, Mockito.times(1)).save(postArgumentCaptor.capture());
87 |
88 | Assertions.assertThat(postArgumentCaptor.getValue().getPostId()).isEqualTo(123L);
89 | Assertions.assertThat(postArgumentCaptor.getValue().getPostName()).isEqualTo("First Post");
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/test/resources/test-data.sql:
--------------------------------------------------------------------------------
1 | INSERT INTO user
2 | (`user_id`,
3 | `created`,
4 | `email`,
5 | `enabled`,
6 | `password`,
7 | `username`)
8 | VALUES
9 | (null ,
10 | null ,
11 | 'test@email.com',
12 | true,
13 | 's3cr3t',
14 | 'testuser_sql');
15 |
--------------------------------------------------------------------------------