diff --git a/.gitignore b/.gitignore index d81f12ed..640ec444 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ -/target +/build /.idea +.gradle diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..c32aa768 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM openjdk:17-jdk-slim-buster + +# Set the working directory to /app +WORKDIR /cake-manager + +# Copy the build output from the host machine to the container +COPY build/libs/cake-manager-*.jar app.jar + +# Expose port 8080 +EXPOSE 8080 + +# Run the command to start the Spring Boot application when the container starts +CMD ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..215b4a32 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,31 @@ +pipeline { + agent any + environment { + // Update below details to push the image to docker repository + DOCKER_REGISTRY = "" + DOCKER_IMAGE_NAME = "cake-manager" + DOCKER_IMAGE_TAG = "latest" + USERNAME = "" + PASSWORD = "" + } + stages { + stage("Build") { + steps { + sh "./gradlew build" + sh "docker build -t ${DOCKER_REGISTRY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG} ." + } + } + stage("Test") { + steps { + sh "./gradlew test" + } + } + stage("Deploy") { + steps { + sh "docker login -u ${USERNAME} -p ${PASSWORD} ${DOCKER_REGISTRY}" + sh "docker push ${DOCKER_REGISTRY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}" + sh "docker-compose up -d" + } + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 00000000..e7470faa --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +## Overview + +### Endpoints +Cake-Manager service have the following functionalities: +1. Add a new cake +2. Update an existing cake +3. Delete an existing cake +4. Get an existing cake +5. Get all cakes + +Application uses H2 InMemory database. Data updates will be cleared when the application is restarted. + +### User access +Application uses InMemoryUserDetail for application authentication and authorisation. + +1. Below user can only access get APIs (Get All Cakes and Get Cake By Id) +``` + username: 'user', + password: 'password', + roles: 'USER' +``` + +2. Admin user have access to get, create, update, delete APIs +``` + username: 'admin', + password: 'password', + roles: ('USER', 'ADMIN') +``` + +### API Documentation +[Swagger UI](http://localhost:8080/swagger-ui/index.html) + +### Running the application + +1. Initial static data: Application loads the static data from json file to H2 database at the application startup [cakes.json](src%2Fmain%2Fresources%2Fstatic%2Fcakes.json) + +2. Run application locally in terminal + +```./gradlew bootRun``` + +3. Run the application in a docker container locally + +```docker-compose up -d``` + +4. Build the application using Jenkinsfile. Currently there are 3 stages setup in Jenkinsfile Build, Test and Deploy. +Docker registry details and user credentials for docker registry needs updatating in Jenkinsfile to execute the deploy stage. diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..cb87da31 --- /dev/null +++ b/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.0.3' + id 'io.spring.dependency-management' version '1.1.0' +} + +group = 'com.waracle' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + + +repositories { + mavenCentral() + jcenter() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.flywaydb:flyway-core' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2' + + compileOnly 'org.projectlombok:lombok' + compileOnly 'javax.servlet:javax.servlet-api:4.0.1' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' +} + +tasks.named('test') { + useJUnitPlatform() +} + +jar { + enabled = false +} + +bootJar { + enabled = true +} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..1e6dda1b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,13 @@ +version: '3.8' +services: + app: + platform: linux/amd64 + build: . + ports: + - "8080:8080" + environment: + SPRING_DATASOURCE_URL: jdbc:h2:mem:testdb + SPRING_DATASOURCE_USERNAME: sa + SPRING_DATASOURCE_PASSWORD: password + SPRING_H2_CONSOLE_ENABLED: "true" + SPRING_H2_CONSOLE_PATH: /h2-console diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..41d9927a Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..41dfb879 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pom.xml b/pom.xml deleted file mode 100644 index c8cbf9d5..00000000 --- a/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - 4.0.0 - com.waracle - cake-manager - war - 1.0-SNAPSHOT - cake-manager Maven Webapp - http://maven.apache.org - - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - - com.fasterxml.jackson.core - jackson-core - 2.8.0 - - - - - org.hibernate - hibernate-entitymanager - 4.3.6.Final - - - - - org.hsqldb - hsqldb - 2.3.4 - - - - - junit - junit - 4.1 - test - - - - - cake-manager - - - - maven-compiler-plugin - 2.3.2 - - 1.8 - 1.8 - - - - - org.eclipse.jetty - jetty-maven-plugin - - 10 - STOP - 8005 - - 8282 - - - - - - - diff --git a/src/main/java/com.waracle.cakemgr/CakeEntity.java b/src/main/java/com.waracle.cakemgr/CakeEntity.java deleted file mode 100644 index 7927bd5d..00000000 --- a/src/main/java/com.waracle.cakemgr/CakeEntity.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.waracle.cakemgr; - -import java.io.Serializable; - -import javax.persistence.*; - -@Entity -@org.hibernate.annotations.Entity(dynamicUpdate = true) -@Table(name = "Employee", uniqueConstraints = {@UniqueConstraint(columnNames = "ID"), @UniqueConstraint(columnNames = "EMAIL")}) -public class CakeEntity implements Serializable { - - private static final long serialVersionUID = -1798070786993154676L; - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "ID", unique = true, nullable = false) - private Integer employeeId; - - @Column(name = "EMAIL", unique = true, nullable = false, length = 100) - private String title; - - @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100) - private String description; - - @Column(name = "LAST_NAME", unique = false, nullable = false, length = 300) - private String image; - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getImage() { - return image; - } - - public void setImage(String image) { - this.image = image; - } - -} \ No newline at end of file diff --git a/src/main/java/com.waracle.cakemgr/CakeServlet.java b/src/main/java/com.waracle.cakemgr/CakeServlet.java deleted file mode 100644 index 9bd32f76..00000000 --- a/src/main/java/com.waracle.cakemgr/CakeServlet.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.waracle.cakemgr; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import org.hibernate.Session; -import org.hibernate.exception.ConstraintViolationException; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.net.URL; -import java.util.List; - -@WebServlet("/cakes") -public class CakeServlet extends HttpServlet { - - @Override - public void init() throws ServletException { - super.init(); - - System.out.println("init started"); - - - System.out.println("downloading cake json"); - try (InputStream inputStream = new URL("https://gist.githubusercontent.com/hart88/198f29ec5114a3ec3460/raw/8dd19a88f9b8d24c23d9960f3300d0c917a4f07c/cake.json").openStream()) { - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - - StringBuffer buffer = new StringBuffer(); - String line = reader.readLine(); - while (line != null) { - buffer.append(line); - line = reader.readLine(); - } - - System.out.println("parsing cake json"); - JsonParser parser = new JsonFactory().createParser(buffer.toString()); - if (JsonToken.START_ARRAY != parser.nextToken()) { - throw new Exception("bad token"); - } - - JsonToken nextToken = parser.nextToken(); - while(nextToken == JsonToken.START_OBJECT) { - System.out.println("creating cake entity"); - - CakeEntity cakeEntity = new CakeEntity(); - System.out.println(parser.nextFieldName()); - cakeEntity.setTitle(parser.nextTextValue()); - - System.out.println(parser.nextFieldName()); - cakeEntity.setDescription(parser.nextTextValue()); - - System.out.println(parser.nextFieldName()); - cakeEntity.setImage(parser.nextTextValue()); - - Session session = HibernateUtil.getSessionFactory().openSession(); - try { - session.beginTransaction(); - session.persist(cakeEntity); - System.out.println("adding cake entity"); - session.getTransaction().commit(); - } catch (ConstraintViolationException ex) { - - } - session.close(); - - nextToken = parser.nextToken(); - System.out.println(nextToken); - - nextToken = parser.nextToken(); - System.out.println(nextToken); - } - - } catch (Exception ex) { - throw new ServletException(ex); - } - - System.out.println("init finished"); - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - Session session = HibernateUtil.getSessionFactory().openSession(); - List list = session.createCriteria(CakeEntity.class).list(); - - resp.getWriter().println("["); - - for (CakeEntity entity : list) { - resp.getWriter().println("\t{"); - - resp.getWriter().println("\t\t\"title\" : " + entity.getTitle() + ", "); - resp.getWriter().println("\t\t\"desc\" : " + entity.getDescription() + ","); - resp.getWriter().println("\t\t\"image\" : " + entity.getImage()); - - resp.getWriter().println("\t}"); - } - - resp.getWriter().println("]"); - - } - -} diff --git a/src/main/java/com.waracle.cakemgr/HibernateUtil.java b/src/main/java/com.waracle.cakemgr/HibernateUtil.java deleted file mode 100644 index 41ef137b..00000000 --- a/src/main/java/com.waracle.cakemgr/HibernateUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.waracle.cakemgr; - -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; - -public class HibernateUtil { - - private static SessionFactory sessionFactory = buildSessionFactory(); - - private static SessionFactory buildSessionFactory() { - try { - if (sessionFactory == null) { - Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml")); - StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder(); - serviceRegistryBuilder.applySettings(configuration.getProperties()); - ServiceRegistry serviceRegistry = serviceRegistryBuilder.build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - } - return sessionFactory; - } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - throw new ExceptionInInitializerError(ex); - } - } - - public static SessionFactory getSessionFactory() { - return sessionFactory; - } - - public static void shutdown() { - getSessionFactory().close(); - } - -} diff --git a/src/main/java/com/waracle/cakemanager/CakeManagerApplication.java b/src/main/java/com/waracle/cakemanager/CakeManagerApplication.java new file mode 100644 index 00000000..c5a63a50 --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/CakeManagerApplication.java @@ -0,0 +1,15 @@ +package com.waracle.cakemanager; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@OpenAPIDefinition +public class CakeManagerApplication { + + public static void main(String[] args) { + SpringApplication.run(CakeManagerApplication.class, args); + } + +} diff --git a/src/main/java/com/waracle/cakemanager/api/CakeController.java b/src/main/java/com/waracle/cakemanager/api/CakeController.java new file mode 100644 index 00000000..d0e9d5cc --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/api/CakeController.java @@ -0,0 +1,99 @@ +package com.waracle.cakemanager.api; + +import com.waracle.cakemanager.entity.Cake; +import com.waracle.cakemanager.service.CakeService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/cakes") +@Slf4j +public class CakeController { + + @Autowired + private CakeService cakeService; + + @PostMapping + @PreAuthorize("hasRole('ADMIN')") + @Operation(summary = "Adds a new cake to database") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Cake added successfully", content = {@Content(mediaType = "application/json")}), + @ApiResponse(responseCode = "403", description = "Users other than Admins cannot add new cake", content = {@Content(mediaType = "application/json")}) + }) + public ResponseEntity addCake(@RequestBody Cake cake) { + log.info("Adding new cake" + cake.getName()); + Cake newCake = cakeService.addCake(cake); + return ResponseEntity.status(HttpStatus.CREATED).body(newCake); + } + + @PutMapping("/{id}") + @PreAuthorize("hasRole('ADMIN')") + @Operation(summary = "Updates cake details in database") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Cake updated successfully", content = {@Content(mediaType = "application/json")}), + @ApiResponse(responseCode = "404", description = "Cake not found to update", content = {@Content(mediaType = "application/json")}), + @ApiResponse(responseCode = "403", description = "Users other than Admins cannot update cake", content = {@Content(mediaType = "application/json")}) + }) + public ResponseEntity updateCake(@PathVariable Long id, @RequestBody Cake cake) { + log.info("Updating Cake Id: " + id); + Cake updatedCake = cakeService.updateCake(id, cake); + return ResponseEntity.ok(updatedCake); + } + + @DeleteMapping("/{id}") + @PreAuthorize("hasRole('ADMIN')") + @Operation(summary = "Deletes cake from database") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Cake deleted successfully", content = {@Content(mediaType = "application/json")}), + @ApiResponse(responseCode = "404", description = "Cake not found in database to update", content = {@Content(mediaType = "application/json")}), + @ApiResponse(responseCode = "403", description = "Users other than Admins cannot delete cake", content = {@Content(mediaType = "application/json")}) + }) + public ResponseEntity deleteCake(@PathVariable Long id) { + log.info("Deleting Cake Id: " + id); + cakeService.deleteCake(id); + return ResponseEntity.noContent().build(); + } + + @GetMapping("/{id}") + @PreAuthorize("hasRole('USER')") + @Operation(summary = "Gets cake details from database") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Cake details retrieved successfully", content = {@Content(mediaType = "application/json")}), + @ApiResponse(responseCode = "404", description = "Cake not found in database to retrieve", content = {@Content(mediaType = "application/json")}) + }) + public ResponseEntity getCake(@PathVariable Long id) { + log.info("Get Cake Details for Id: " + id); + Cake cake = cakeService.getCakeById(id); + return ResponseEntity.ok(cake); + } + + @GetMapping + @PreAuthorize("hasRole('USER')") + @Operation(summary = "Gets all cakes from database") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Cake details retrieved successfully", content = {@Content(mediaType = "application/json")}) + }) + public ResponseEntity> getAllCakes() { + log.info("Get All Cakes"); + List cakes = cakeService.getAllCakes(); + return ResponseEntity.ok(cakes); + } +} + diff --git a/src/main/java/com/waracle/cakemanager/config/CakesDataConfig.java b/src/main/java/com/waracle/cakemanager/config/CakesDataConfig.java new file mode 100644 index 00000000..32412eaf --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/config/CakesDataConfig.java @@ -0,0 +1,34 @@ +package com.waracle.cakemanager.config; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.waracle.cakemanager.entity.Cake; +import com.waracle.cakemanager.service.CakeService; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +@Configuration +public class CakesDataConfig { + @Bean + CommandLineRunner loadStaticData(CakeService cakeService) { + return args -> { + // read json and write to db + ObjectMapper mapper = new ObjectMapper(); + TypeReference> typeReference = new TypeReference<>() { + }; + InputStream inputStream = TypeReference.class.getResourceAsStream("/static/cakes.json"); + try { + List cakes = mapper.readValue(inputStream, typeReference); + cakes.forEach(cakeService::addCake); + System.out.println("Cakes Saved!"); + } catch (IOException e) { + System.out.println("Unable to save cakes: " + e.getMessage()); + } + }; + } +} diff --git a/src/main/java/com/waracle/cakemanager/config/WebSecurityConfig.java b/src/main/java/com/waracle/cakemanager/config/WebSecurityConfig.java new file mode 100644 index 00000000..c3ac2a1d --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/config/WebSecurityConfig.java @@ -0,0 +1,56 @@ +package com.waracle.cakemanager.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class WebSecurityConfig { + + @Bean + public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) { + UserDetails user = User.withUsername("user") + .password(passwordEncoder.encode("password")) + .roles("USER") + .build(); + + UserDetails admin = User.withUsername("admin") + .password(passwordEncoder.encode("password")) + .roles("USER", "ADMIN") + .build(); + + return new InMemoryUserDetailsManager(user, admin); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeHttpRequests().requestMatchers("v3/api-docs", "swagger-ui.html").permitAll() + .and() + .authorizeHttpRequests() + .anyRequest().authenticated() + .and() + .httpBasic(); + + return http.build(); + } +} + + + diff --git a/src/main/java/com/waracle/cakemanager/entity/Cake.java b/src/main/java/com/waracle/cakemanager/entity/Cake.java new file mode 100644 index 00000000..48b7d9d6 --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/entity/Cake.java @@ -0,0 +1,33 @@ +package com.waracle.cakemanager.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "cakes") +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Cake { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + @Column(nullable = false) + private String description; + + @Column(nullable = false) + private String image; +} + diff --git a/src/main/java/com/waracle/cakemanager/exceptions/NotFoundException.java b/src/main/java/com/waracle/cakemanager/exceptions/NotFoundException.java new file mode 100644 index 00000000..cd9025a4 --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/exceptions/NotFoundException.java @@ -0,0 +1,10 @@ +package com.waracle.cakemanager.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +public class NotFoundException extends ResponseStatusException { + public NotFoundException(String message) { + super(HttpStatus.NOT_FOUND, message); + } +} diff --git a/src/main/java/com/waracle/cakemanager/exceptions/RestExceptionHandler.java b/src/main/java/com/waracle/cakemanager/exceptions/RestExceptionHandler.java new file mode 100644 index 00000000..afae0597 --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/exceptions/RestExceptionHandler.java @@ -0,0 +1,46 @@ +package com.waracle.cakemanager.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.springframework.http.HttpStatus.FORBIDDEN; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; + +@ControllerAdvice +public class RestExceptionHandler { + + @ExceptionHandler(value = {Exception.class}) + protected ResponseEntity handleGenericException(Exception ex, WebRequest request) { + HttpStatus status = INTERNAL_SERVER_ERROR; + String message = "An error occurred while processing your request."; + + if (ex instanceof ResponseStatusException exception) { + status = HttpStatus.resolve(exception.getStatusCode().value()); + message = exception.getReason(); + } else if( ex instanceof AccessDeniedException) { + status = FORBIDDEN; + message = ex.getMessage(); + } + + // Create error response body + Map body = new LinkedHashMap<>(); + body.put("timestamp", LocalDateTime.now()); + body.put("status", status.value()); + body.put("error", status.getReasonPhrase()); + body.put("message", message); + body.put("path", ((ServletWebRequest) request).getRequest().getRequestURI()); + + return new ResponseEntity<>(body, status); + } +} + diff --git a/src/main/java/com/waracle/cakemanager/repository/CakeRepository.java b/src/main/java/com/waracle/cakemanager/repository/CakeRepository.java new file mode 100644 index 00000000..ab56e026 --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/repository/CakeRepository.java @@ -0,0 +1,10 @@ +package com.waracle.cakemanager.repository; + +import com.waracle.cakemanager.entity.Cake; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CakeRepository extends JpaRepository { +} + diff --git a/src/main/java/com/waracle/cakemanager/service/CakeService.java b/src/main/java/com/waracle/cakemanager/service/CakeService.java new file mode 100644 index 00000000..840869cb --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/service/CakeService.java @@ -0,0 +1,18 @@ +package com.waracle.cakemanager.service; + +import com.waracle.cakemanager.entity.Cake; + +import java.util.List; + +public interface CakeService { + + List getAllCakes(); + + Cake getCakeById(Long id); + + Cake addCake(Cake cake); + + Cake updateCake(Long id, Cake updatedCake); + + void deleteCake(Long id); +} diff --git a/src/main/java/com/waracle/cakemanager/service/CakeServiceImpl.java b/src/main/java/com/waracle/cakemanager/service/CakeServiceImpl.java new file mode 100644 index 00000000..7105eecc --- /dev/null +++ b/src/main/java/com/waracle/cakemanager/service/CakeServiceImpl.java @@ -0,0 +1,48 @@ +package com.waracle.cakemanager.service; + +import com.waracle.cakemanager.entity.Cake; +import com.waracle.cakemanager.exceptions.NotFoundException; +import com.waracle.cakemanager.repository.CakeRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@Slf4j +public class CakeServiceImpl implements CakeService { + + @Autowired + private CakeRepository cakeRepository; + + public List getAllCakes() { + log.info("Get All Cakes"); + return cakeRepository.findAll(); + } + + public Cake getCakeById(Long id) { + log.info("Get Cake Details for Id: " + id); + return cakeRepository.findById(id).orElseThrow(() -> new NotFoundException("Cake not found with id " + id)); + } + + public Cake addCake(Cake cake) { + log.info("Adding new cake: " + cake.getName()); + return cakeRepository.save(cake); + } + + public Cake updateCake(Long id, Cake updatedCake) { + log.info("Updating Cake Id: " + id); + Cake cake = getCakeById(id); + cake.setName(updatedCake.getName()); + cake.setDescription(updatedCake.getDescription()); + return cakeRepository.save(cake); + } + + public void deleteCake(Long id) { + log.info("Deleting Cake Id: " + id); + Cake cake = getCakeById(id); + cakeRepository.delete(cake); + } +} + diff --git a/src/main/resources/db/migration/V1__create_cake_table.sql b/src/main/resources/db/migration/V1__create_cake_table.sql new file mode 100644 index 00000000..79d1eb5d --- /dev/null +++ b/src/main/resources/db/migration/V1__create_cake_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE cakes ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(255) NOT NULL, + description VARCHAR(1000) NOT NULL, + image VARCHAR(1000) NOT NULL +); + diff --git a/src/main/resources/hibernate.cfg.xml b/src/main/resources/hibernate.cfg.xml deleted file mode 100644 index 0ae06d63..00000000 --- a/src/main/resources/hibernate.cfg.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - class,hbm - org.hibernate.dialect.HSQLDialect - true - org.hsqldb.jdbcDriver - sa - - jdbc:hsqldb:mem:db - create - - - \ No newline at end of file diff --git a/src/main/resources/static/cakes.json b/src/main/resources/static/cakes.json new file mode 100644 index 00000000..f9457904 --- /dev/null +++ b/src/main/resources/static/cakes.json @@ -0,0 +1,102 @@ +[ + { + "name": "Lemon cheesecake", + "description": "A cheesecake made of lemon", + "image": "https://s3-eu-west-1.amazonaws.com/s3.mediafileserver.co.uk/carnation/WebFiles/RecipeImages/lemoncheesecake_lg.jpg" + }, + { + "name": "victoria sponge", + "description": "sponge with jam", + "image": "http://www.bbcgoodfood.com/sites/bbcgoodfood.com/files/recipe_images/recipe-image-legacy-id--1001468_10.jpg" + }, + { + "name": "Carrot cake", + "description": "Bugs bunnys favourite", + "image": "http://www.villageinn.com/i/pies/profile/carrotcake_main1.jpg" + }, + { + "name": "Banana cake", + "description": "Donkey kongs favourite", + "image": "http://ukcdn.ar-cdn.com/recipes/xlarge/ff22df7f-dbcd-4a09-81f7-9c1d8395d936.jpg" + }, + { + "name": "Birthday cake", + "description": "a yearly treat", + "image": "http://cornandco.com/wp-content/uploads/2014/05/birthday-cake-popcorn.jpg" + }, + { + "name": "Lemon cheesecake", + "description": "A cheesecake made of lemon", + "image": "https://s3-eu-west-1.amazonaws.com/s3.mediafileserver.co.uk/carnation/WebFiles/RecipeImages/lemoncheesecake_lg.jpg" + }, + { + "name": "victoria sponge", + "description": "sponge with jam", + "image": "http://www.bbcgoodfood.com/sites/bbcgoodfood.com/files/recipe_images/recipe-image-legacy-id--1001468_10.jpg" + }, + { + "name": "Carrot cake", + "description": "Bugs bunnys favourite", + "image": "http://www.villageinn.com/i/pies/profile/carrotcake_main1.jpg" + }, + { + "name": "Banana cake", + "description": "Donkey kongs favourite", + "image": "http://ukcdn.ar-cdn.com/recipes/xlarge/ff22df7f-dbcd-4a09-81f7-9c1d8395d936.jpg" + }, + { + "name": "Birthday cake", + "description": "a yearly treat", + "image": "http://cornandco.com/wp-content/uploads/2014/05/birthday-cake-popcorn.jpg" + }, + { + "name": "Lemon cheesecake", + "description": "A cheesecake made of lemon", + "image": "https://s3-eu-west-1.amazonaws.com/s3.mediafileserver.co.uk/carnation/WebFiles/RecipeImages/lemoncheesecake_lg.jpg" + }, + { + "name": "victoria sponge", + "description": "sponge with jam", + "image": "http://www.bbcgoodfood.com/sites/bbcgoodfood.com/files/recipe_images/recipe-image-legacy-id--1001468_10.jpg" + }, + { + "name": "Carrot cake", + "description": "Bugs bunnys favourite", + "image": "http://www.villageinn.com/i/pies/profile/carrotcake_main1.jpg" + }, + { + "name": "Banana cake", + "description": "Donkey kongs favourite", + "image": "http://ukcdn.ar-cdn.com/recipes/xlarge/ff22df7f-dbcd-4a09-81f7-9c1d8395d936.jpg" + }, + { + "name": "Birthday cake", + "description": "a yearly treat", + "image": "http://cornandco.com/wp-content/uploads/2014/05/birthday-cake-popcorn.jpg" + }, + { + "name": "Lemon cheesecake", + "description": "A cheesecake made of lemon", + "image": "https://s3-eu-west-1.amazonaws.com/s3.mediafileserver.co.uk/carnation/WebFiles/RecipeImages/lemoncheesecake_lg.jpg" + }, + { + "name": "victoria sponge", + "description": "sponge with jam", + "image": "http://www.bbcgoodfood.com/sites/bbcgoodfood.com/files/recipe_images/recipe-image-legacy-id--1001468_10.jpg" + }, + { + "name": "Carrot cake", + "description": "Bugs bunnys favourite", + "image": "http://www.villageinn.com/i/pies/profile/carrotcake_main1.jpg" + }, + { + "name": "Banana cake", + "description": "Donkey kongs favourite", + "image": "http://ukcdn.ar-cdn.com/recipes/xlarge/ff22df7f-dbcd-4a09-81f7-9c1d8395d936.jpg" + }, + { + "name": "Birthday cake", + "description": "a yearly treat", + "image": "http://cornandco.com/wp-content/uploads/2014/05/birthday-cake-popcorn.jpg" + } +] \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index d004447f..00000000 --- a/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - Archetype Created Web Application - - diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp deleted file mode 100644 index c38169bb..00000000 --- a/src/main/webapp/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/src/test/java/com/waracle/cakemanager/CakeManagerApplicationTests.java b/src/test/java/com/waracle/cakemanager/CakeManagerApplicationTests.java new file mode 100644 index 00000000..74f2f158 --- /dev/null +++ b/src/test/java/com/waracle/cakemanager/CakeManagerApplicationTests.java @@ -0,0 +1,13 @@ +package com.waracle.cakemanager; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CakeManagerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/waracle/cakemanager/api/CakeControllerTest.java b/src/test/java/com/waracle/cakemanager/api/CakeControllerTest.java new file mode 100644 index 00000000..8f321942 --- /dev/null +++ b/src/test/java/com/waracle/cakemanager/api/CakeControllerTest.java @@ -0,0 +1,201 @@ +package com.waracle.cakemanager.api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.waracle.cakemanager.entity.Cake; +import com.waracle.cakemanager.exceptions.NotFoundException; +import com.waracle.cakemanager.service.CakeService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest +class CakeControllerTest { + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @MockBean + private CakeService cakeService; + + private final ObjectMapper objectMapper = new ObjectMapper(); + @BeforeEach + void setUp() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .apply(springSecurity()).build(); + } + + @Test + @WithMockUser + void getCakes_returnsOk() throws Exception { + Cake cake1 = createTestCake(); + + Cake cake2 = new Cake(); + cake2.setId(2L); + cake2.setName("Strawberry Cake"); + cake2.setDescription("A delicious strawberry cake"); + + when(cakeService.getAllCakes()).thenReturn(Arrays.asList(cake1, cake2)); + + mockMvc.perform(MockMvcRequestBuilders.get("/cakes")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value(cake1.getName())) + .andExpect(jsonPath("$[0].description").value(cake1.getDescription())) + .andExpect(jsonPath("$[1].name").value(cake2.getName())) + .andExpect(jsonPath("$[1].description").value(cake2.getDescription())); + + verify(cakeService).getAllCakes(); + } + + @Test + @WithMockUser + void getCake_returnsOk() throws Exception { + Cake cake = createTestCake(); + + when(cakeService.getCakeById(1L)).thenReturn(cake); + + mockMvc.perform(MockMvcRequestBuilders.get("/cakes/1")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name").value(cake.getName())) + .andExpect(jsonPath("$.description").value(cake.getDescription())); + + verify(cakeService).getCakeById(1L); + } + + @Test + @WithMockUser + void getCake_returnsNotFound() throws Exception { + when(cakeService.getCakeById(1L)).thenThrow(new NotFoundException("Cake not found with id 1")); + + mockMvc.perform(MockMvcRequestBuilders.get("/cakes/1")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("Cake not found with id 1")); + + verify(cakeService, times(1)).getCakeById(1L); + } + + @Test + @WithMockUser(roles = "ADMIN") + void addCake_returnsOk() throws Exception { + Cake cake = createTestCake(); + + when(cakeService.addCake(any(Cake.class))).thenReturn(cake); + + mockMvc.perform(MockMvcRequestBuilders.post("/cakes").with(csrf()) + .content(objectMapper.writeValueAsString(cake)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value(cake.getName())) + .andExpect(jsonPath("$.description").value(cake.getDescription())); + + verify(cakeService).addCake(any(Cake.class)); + } + + @Test + @WithMockUser(roles = "ADMIN") + void updateCake_returnsOk() throws Exception { + Cake cake = createTestCake(); + + when(cakeService.updateCake(eq(1L), any(Cake.class))).thenReturn(cake); + + mockMvc.perform(MockMvcRequestBuilders.put("/cakes/1") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(cake)) + .with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(cake.getId())) + .andExpect(jsonPath("$.name").value(cake.getName())) + .andExpect(jsonPath("$.description").value(cake.getDescription())); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Cake.class); + verify(cakeService, times(1)).updateCake(eq(1L), argumentCaptor.capture()); + assertEquals(1L, argumentCaptor.getValue().getId()); + assertEquals(cake.getName(), argumentCaptor.getValue().getName()); + assertEquals(cake.getDescription(), argumentCaptor.getValue().getDescription()); + } + + @Test + @WithMockUser(roles = "ADMIN") + void updateCake_returnsNotFound() throws Exception { + Cake cake = createTestCake(); + when(cakeService.updateCake(eq(1L), any(Cake.class))).thenThrow(new NotFoundException("Cake not found with id 1")); + + mockMvc.perform(MockMvcRequestBuilders.put("/cakes/1") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(cake)) + .with(csrf())) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("Cake not found with id 1")); + + verify(cakeService, times(0)).deleteCake(1L); + } + + @Test + @WithMockUser(roles = "ADMIN") + void deleteCake_returnsOk() throws Exception { + doNothing().when(cakeService).deleteCake(1L); + + mockMvc.perform(MockMvcRequestBuilders.delete("/cakes/1") + .with(csrf())) + .andExpect(status().isNoContent()); + + verify(cakeService, times(1)).deleteCake(1L); + } + + @Test + @WithMockUser + void deleteCake_returnsForbidden() throws Exception { + + mockMvc.perform(MockMvcRequestBuilders.delete("/cakes/1")) + .andExpect(status().isForbidden()); + + verify(cakeService, times(0)).deleteCake(1L); + } + + @Test + @WithMockUser(roles = "ADMIN") + void deleteCake_returnsNotFound() throws Exception { + doThrow(new NotFoundException("Cake not found with id 1")).when(cakeService).deleteCake(1L); + + mockMvc.perform(MockMvcRequestBuilders.delete("/cakes/1").with(csrf())) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("Cake not found with id 1")); + + verify(cakeService, times(1)).deleteCake(1L); + } + + + private Cake createTestCake() { + Cake cake = new Cake(); + cake.setId(1L); + cake.setName("Chocolate Cake"); + cake.setDescription("A delicious chocolate cake"); + + return cake; + } +} diff --git a/src/test/java/com/waracle/cakemanager/service/CakeServiceImplTest.java b/src/test/java/com/waracle/cakemanager/service/CakeServiceImplTest.java new file mode 100644 index 00000000..d9b62def --- /dev/null +++ b/src/test/java/com/waracle/cakemanager/service/CakeServiceImplTest.java @@ -0,0 +1,124 @@ +package com.waracle.cakemanager.service; + +import com.waracle.cakemanager.entity.Cake; +import com.waracle.cakemanager.exceptions.NotFoundException; +import com.waracle.cakemanager.repository.CakeRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CakeServiceImplTest { + + @Mock + private CakeRepository cakeRepository; + + @InjectMocks + private CakeService cakeService = new CakeServiceImpl(); + + @Test + public void getAllCakes_shouldReturnAllCakes() { + List expectedCakes = new ArrayList<>(); + expectedCakes.add(new Cake(1L, "Chocolate Cake", "A delicious chocolate cake", "https://example.com/chocolate-cake.jpg")); + expectedCakes.add(new Cake(2L, "Carrot Cake", "A delicious carrot cake", "https://example.com/carrot-cake.jpg")); + + when(cakeRepository.findAll()).thenReturn(expectedCakes); + + List actualCakes = cakeService.getAllCakes(); + + assertEquals(expectedCakes.size(), actualCakes.size()); + for (int i = 0; i < expectedCakes.size(); i++) { + assertEquals(expectedCakes.get(i), actualCakes.get(i)); + } + } + + @Test + public void getCakeById_shouldReturnCake() { + Cake expectedCake = getTestCake(); + + when(cakeRepository.findById(expectedCake.getId())).thenReturn(Optional.of(expectedCake)); + + Cake actualCake = cakeService.getCakeById(expectedCake.getId()); + + assertEquals(expectedCake, actualCake); + } + + @Test + public void getCakeById_shouldThrowNotFoundException_forNonExistentId() { + long nonExistentId = 123; + + when(cakeRepository.findById(nonExistentId)).thenReturn(Optional.empty()); + + assertThrows(NotFoundException.class, () -> cakeService.getCakeById(nonExistentId)); + } + + + @Test + public void shouldAddCake() { + Cake cakeToAdd = new Cake(null, "Chocolate Cake", "A delicious chocolate cake", "https://example.com/chocolate-cake.jpg"); + Cake expectedCake = new Cake(1L, "Chocolate Cake", "A delicious chocolate cake", "https://example.com/chocolate-cake.jpg"); + + when(cakeRepository.save(any(Cake.class))).thenReturn(expectedCake); + + Cake actualCake = cakeService.addCake(cakeToAdd); + + assertEquals(expectedCake, actualCake); + } + + @Test + public void shouldUpdateCake() { + Cake cakeToUpdate = getTestCake(); + Cake expectedCake = getTestCake(); + + when(cakeRepository.findById(cakeToUpdate.getId())).thenReturn(Optional.of(cakeToUpdate)); + when(cakeRepository.save(any(Cake.class))).thenReturn(expectedCake); + + Cake actualCake = cakeService.updateCake(cakeToUpdate.getId(), expectedCake); + + assertEquals(expectedCake, actualCake); + } + + @Test + public void updateCake_shouldThrowNotFoundException_forNonExistentId() { + long nonExistentId = 123; + Cake cakeToUpdate = new Cake(nonExistentId, "Chocolate Cake", "A delicious chocolate cake", "https://example.com/chocolate-cake.jpg"); + + when(cakeRepository.findById(nonExistentId)).thenReturn(Optional.empty()); + + assertThrows(NotFoundException.class, () -> cakeService.updateCake(nonExistentId, cakeToUpdate)); + } + + @Test + public void shouldDeleteCake() { + Cake cakeToDelete = getTestCake(); + + when(cakeRepository.findById(cakeToDelete.getId())).thenReturn(Optional.of(cakeToDelete)); + assertDoesNotThrow(() -> cakeService.deleteCake(cakeToDelete.getId())); + verify(cakeRepository, times(1)).delete(cakeToDelete); + } + + @Test + public void deleteCake_shouldThrowNotFoundException_forNonExistentId() { + long nonExistentId = 123; + when(cakeRepository.findById(nonExistentId)).thenReturn(Optional.empty()); + assertThrows(NotFoundException.class, () -> cakeService.deleteCake(nonExistentId)); + } + + private Cake getTestCake() { + return new Cake(1L, "Chocolate Cake", "A delicious chocolate cake", "https://example.com/chocolate-cake.jpg"); + } +} \ No newline at end of file