US01: Make it possible for the user to add a horse through the API

This commit is contained in:
2020-03-16 20:46:18 +01:00
commit 707487c236
80 changed files with 16073 additions and 0 deletions

14
backend/.editorconfig Normal file
View File

@@ -0,0 +1,14 @@
root = true
[*]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = false
charset = utf-8
indent_style = space
indent_size = 4
tab_width = 4
[{*.yml,*.yaml,*.json,*.sql}]
indent_style=space
indent_size=2

33
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
/target/
!.mvn/wrapper/maven-wrapper.jar
.DS_Store
### Log ###
/log/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### DB ###
*.db
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

BIN
backend/.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip

3
backend/ReadMe.md Normal file
View File

@@ -0,0 +1,3 @@
# Wendy's Friends
Please read the Individual Assignment Document.

285
backend/mvnw vendored Executable file
View File

@@ -0,0 +1,285 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# http://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

161
backend/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,161 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

84
backend/pom.xml Normal file
View File

@@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>at.ac.tuwien.sepm.assignment.individual</groupId>
<artifactId>e11777707</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wendys-friends</name>
<description>A backend system for managing wendy's friends</description>
<properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.surefire-plugin.version>2.22.2</maven.surefire-plugin.version>
<spring-boot.version>2.2.5.RELEASE</spring-boot.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.jupiter.version>5.6.0</junit.jupiter.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<type>pom</type>
<version>${spring-boot.version}</version>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven.surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,14 @@
package at.ac.tuwien.sepm.assignment.individual;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WendysRennpferdeApplication {
public static void main(String[] args) {
SpringApplication.run(WendysRennpferdeApplication.class, args);
}
}

View File

@@ -0,0 +1,14 @@
package at.ac.tuwien.sepm.assignment.individual.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "OPTION", "HEAD", "DELETE", "PUT", "PATCH");
}
}

View File

@@ -0,0 +1,61 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint;
import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.HorseDto;
import at.ac.tuwien.sepm.assignment.individual.endpoint.mapper.HorseMapper;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import at.ac.tuwien.sepm.assignment.individual.service.HorseService;
import at.ac.tuwien.sepm.assignment.individual.util.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.lang.invoke.MethodHandles;
@RestController
@RequestMapping(at.ac.tuwien.sepm.assignment.individual.endpoint.HorseEndpoint.BASE_URL)
public class HorseEndpoint {
static final String BASE_URL = "/horses";
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final HorseService horseService;
private final HorseMapper horseMapper;
@Autowired
public HorseEndpoint(HorseService horseService, HorseMapper horseMapper) {
this.horseService = horseService;
this.horseMapper = horseMapper;
}
@GetMapping(value = "/{id}")
public HorseDto getOneById(@PathVariable("id") Long id) {
LOGGER.info("GET " + BASE_URL + "/{}", id);
try {
return horseMapper.entityToDto(horseService.findOneById(id));
} catch (NotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error during reading horse", e);
}
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public HorseDto addHorse(@RequestBody HorseDto horse) {
LOGGER.info("POST " + BASE_URL);
try {
Horse horseEntity = horseMapper.dtoToEntity(horse);
return horseMapper.entityToDto(horseService.addHorse(horseEntity));
} catch (ValidationException e) {
LOGGER.error(e.getMessage());
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
"Error during adding new horse: " + e.getMessage(), e);
} catch (DataAccessException e) {
LOGGER.error(e.getMessage());
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
"Something went wrong during the communication with the database", e);
}
}
}

View File

@@ -0,0 +1,39 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint;
import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.OwnerDto;
import at.ac.tuwien.sepm.assignment.individual.endpoint.mapper.OwnerMapper;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import at.ac.tuwien.sepm.assignment.individual.service.OwnerService;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequestMapping(OwnerEndpoint.BASE_URL)
public class OwnerEndpoint {
static final String BASE_URL = "/owners";
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final OwnerService ownerService;
private final OwnerMapper ownerMapper;
@Autowired
public OwnerEndpoint(OwnerService ownerService, OwnerMapper ownerMapper) {
this.ownerService = ownerService;
this.ownerMapper = ownerMapper;
}
@GetMapping(value = "/{id}")
public OwnerDto getOneById(@PathVariable("id") Long id) {
LOGGER.info("GET " + BASE_URL + "/{}", id);
try {
return ownerMapper.entityToDto(ownerService.findOneById(id));
} catch (NotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error during reading owner", e);
}
}
}

View File

@@ -0,0 +1,70 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint.dto;
import java.time.LocalDateTime;
import java.util.Objects;
abstract class BaseDto {
private Long id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
protected BaseDto() {
}
public BaseDto(Long id, LocalDateTime createdAt, LocalDateTime updatedAt) {
this.id = id;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BaseDto)) return false;
BaseDto baseDto = (BaseDto) o;
return Objects.equals(id, baseDto.id) &&
Objects.equals(createdAt, baseDto.createdAt) &&
Objects.equals(updatedAt, baseDto.updatedAt);
}
@Override
public int hashCode() {
return Objects.hash(id, createdAt, updatedAt);
}
protected String fieldsString() {
return "id=" + id +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt;
}
@Override
public String toString() {
return "BaseDto{ " + fieldsString() + " }";
}
}

View File

@@ -0,0 +1,104 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint.dto;
import java.time.LocalDateTime;
import java.util.Objects;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class HorseDto extends BaseDto {
private String name;
private String description;
private short score;
private Date birthday;
private long owner;
public HorseDto() {}
public HorseDto(String name, String description, short score, Date birthday, Long owner) {
this.name = name;
this.description = description;
this.score = score;
this.birthday = birthday;
this.owner = owner;
}
public HorseDto(Long id, String name, String description, short score, Date birthday, LocalDateTime created, LocalDateTime updated, Long owner) {
super(id, created, updated);
this.name = name;
this.description = description;
this.score = score;
this.birthday = birthday;
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public short getScore() {
return score;
}
public void setScore(short score) {
this.score = score;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Long getOwner() {
return owner;
}
public void setOwner(Long owner) {
this.owner = owner;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HorseDto)) return false;
if (!super.equals(o)) return false;
HorseDto horseDto = (HorseDto) o;
return Objects.equals(name, horseDto.name);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name);
}
@Override
protected String fieldsString() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return super.fieldsString() + ", name='" + name + '\'' +
"description='" + description + '\'' +
"score='" + score + '\'' +
"birthday='" + df.format(birthday) + '\'' +
"owner_id='" + owner + '\'';
}
@Override
public String toString() {
return "HorseDto{ " + fieldsString() + " }";
}
}

View File

@@ -0,0 +1,54 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint.dto;
import java.time.LocalDateTime;
import java.util.Objects;
public class OwnerDto extends BaseDto {
private String name;
public OwnerDto() {
}
public OwnerDto(String name) {
this.name = name;
}
public OwnerDto(Long id, String name, LocalDateTime created, LocalDateTime updated) {
super(id, created, updated);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OwnerDto)) return false;
if (!super.equals(o)) return false;
OwnerDto ownerDto = (OwnerDto) o;
return Objects.equals(name, ownerDto.name);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name);
}
@Override
protected String fieldsString() {
return super.fieldsString() + ", name='" + name + '\'';
}
@Override
public String toString() {
return "OwnerDto{ " + fieldsString() + " }";
}
}

View File

@@ -0,0 +1,17 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint.mapper;
import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.HorseDto;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import org.springframework.stereotype.Component;
@Component
public class HorseMapper {
public HorseDto entityToDto(Horse horse) {
return new HorseDto(horse.getId(), horse.getName(), horse.getDescription(), horse.getScore(), horse.getBirthday(), horse.getCreatedAt(), horse.getUpdatedAt(), horse.getOwner());
}
public Horse dtoToEntity(HorseDto horse) {
return new Horse(horse.getId(), horse.getName(), horse.getDescription(), horse.getScore(), horse.getBirthday(), horse.getOwner());
}
}

View File

@@ -0,0 +1,15 @@
package at.ac.tuwien.sepm.assignment.individual.endpoint.mapper;
import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.OwnerDto;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import org.springframework.stereotype.Component;
@Component
public class OwnerMapper {
public OwnerDto entityToDto(Owner owner) {
return new OwnerDto(owner.getId(), owner.getName(), owner.getCreatedAt(), owner.getUpdatedAt());
}
}

View File

@@ -0,0 +1,74 @@
package at.ac.tuwien.sepm.assignment.individual.entity;
import java.time.LocalDateTime;
import java.util.Objects;
abstract class BaseEntity {
private Long id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
protected BaseEntity() {
}
protected BaseEntity(Long id) {
this.id = id;
}
protected BaseEntity(Long id, LocalDateTime createdAt, LocalDateTime updatedAt) {
this.id = id;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BaseEntity)) return false;
BaseEntity that = (BaseEntity) o;
return Objects.equals(id, that.id) &&
Objects.equals(createdAt, that.createdAt) &&
Objects.equals(updatedAt, that.updatedAt);
}
@Override
public int hashCode() {
return Objects.hash(id, createdAt, updatedAt);
}
protected String fieldsString() {
return "id=" + id +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt;
}
@Override
public String toString() {
return "BaseEntity{ " + fieldsString() + " }";
}
}

View File

@@ -0,0 +1,113 @@
package at.ac.tuwien.sepm.assignment.individual.entity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.sql.Date;
import java.util.Objects;
public class Horse extends BaseEntity {
private String name;
private String description;
private short score;
private Date birthday;
private Long owner;
public Horse() {}
public Horse(String name, String description, short score, Date birthday, Long owner) {
this.name = name;
this.description = description;
this.score = score;
this.birthday = birthday;
this.owner = owner;
}
public Horse(Long id, String name, String description, short score, Date birthday, Long owner) {
super(id);
this.name = name;
this.description = description;
this.score = score;
this.birthday = birthday;
this.owner = owner;
}
public Horse(Long id, String name, String description, short score, Date birthday, Long owner, LocalDateTime created, LocalDateTime updated) {
super(id, created, updated);
this.name = name;
this.description = description;
this.score = score;
this.birthday = birthday;
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public short getScore() {
return score;
}
public void setScore(short score) {
this.score = score;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Long getOwner() {
return owner;
}
public void setOwner(Long owner) {
this.owner = owner;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Horse)) return false;
if (!super.equals(o)) return false;
Horse Horse = (Horse) o;
return Objects.equals(name, Horse.name);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name);
}
@Override
protected String fieldsString() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return super.fieldsString() + ", name='" + name + '\'' +
"description='" + description + '\'' +
"score='" + score + '\'' +
"birthday='" + df.format(birthday) + '\'' +
"owner='" + owner + '\'';
}
@Override
public String toString() {
return "Horse{ " + fieldsString() + " }";
}
}

View File

@@ -0,0 +1,58 @@
package at.ac.tuwien.sepm.assignment.individual.entity;
import java.time.LocalDateTime;
import java.util.Objects;
public class Owner extends BaseEntity {
private String name;
public Owner() {
}
public Owner(String name) {
this.name = name;
}
public Owner(Long id, String name) {
super(id);
this.name = name;
}
public Owner(Long id, String name, LocalDateTime created, LocalDateTime updated) {
super(id, created, updated);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Owner)) return false;
if (!super.equals(o)) return false;
Owner owner = (Owner) o;
return Objects.equals(name, owner.name);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name);
}
@Override
protected String fieldsString() {
return super.fieldsString() + ", name='" + name + '\'';
}
@Override
public String toString() {
return "Owner{ " + fieldsString() +" }";
}
}

View File

@@ -0,0 +1,8 @@
package at.ac.tuwien.sepm.assignment.individual.exception;
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,39 @@
package at.ac.tuwien.sepm.assignment.individual.persistence;
import java.lang.invoke.MethodHandles;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
/**
* This component is only created, if the profile {@code datagen} is active
* You can activate this profile by adding {@code -Dspring.profiles.active=datagen} to your maven command line
*/
@Configuration
@Profile("datagen")
public class DataGeneratorBean {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private DataSource source;
public DataGeneratorBean(DataSource source) {
this.source = source;
}
/**
* Executed once when the component is instantiated. Inserts some dummy data.
*/
@PostConstruct
void insertDummyData() {
try {
ScriptUtils.executeSqlScript(source.getConnection(), new ClassPathResource("sql/insertData.sql"));
} catch (Exception e) {
LOGGER.error("Error inserting test data", e);
}
}
}

View File

@@ -0,0 +1,23 @@
package at.ac.tuwien.sepm.assignment.individual.persistence;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import org.springframework.dao.DataAccessException;
public interface HorseDao {
/**
* @param id of the horse to find.
* @return the horse with the specified id.
* @throws DataAccessException will be thrown if something goes wrong during the database access.
* @throws NotFoundException will be thrown if the horse could not be found in the database.
*/
Horse findOneById(Long id);
/**
* @param horse that specifies the horse to add
* @return the newly created horse
* @throws DataAccessException will be thrown if something goes wrong during the database access.
*/
Horse addHorse(Horse horse);
}

View File

@@ -0,0 +1,17 @@
package at.ac.tuwien.sepm.assignment.individual.persistence;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import org.springframework.dao.DataAccessException;
public interface OwnerDao {
/**
* @param id of the owner to find.
* @return the owner with the specified id.
* @throws DataAccessException will be thrown if something goes wrong during the database access.
* @throws NotFoundException will be thrown if the owner could not be found in the database.
*/
Owner findOneById(Long id);
}

View File

@@ -0,0 +1,104 @@
package at.ac.tuwien.sepm.assignment.individual.persistence.impl;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import at.ac.tuwien.sepm.assignment.individual.persistence.HorseDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import java.lang.invoke.MethodHandles;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.time.LocalDateTime;
import java.util.List;
@Repository
public class HorseJdbcDao implements HorseDao {
private static final String TABLE_NAME = "horse";
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final JdbcTemplate jdbcTemplate;
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public HorseJdbcDao(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public Horse findOneById(Long id) {
LOGGER.trace("Get horse with id {}", id);
final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE id=?";
List<Horse> horses = jdbcTemplate.query(sql, new Object[] { id }, this::mapRow);
if (horses.isEmpty()) throw new NotFoundException("Could not find horse with id " + id);
return horses.get(0);
}
@Override
public Horse addHorse(Horse horse) throws DataAccessException {
LOGGER.trace("Add horse {}", horse.toString());
String sql = "INSERT INTO " + TABLE_NAME + "(name, description, score, birthday, owner_id, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?)";
try {
LocalDateTime currentTime = LocalDateTime.now();
horse.setCreatedAt(currentTime);
horse.setUpdatedAt(currentTime);
// Create a key holder to get the key of the new record
KeyHolder keyHolder = new GeneratedKeyHolder();
int changes = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(1, horse.getName());
ps.setString(2, horse.getDescription());
ps.setInt(3, horse.getScore());
ps.setDate(4, horse.getBirthday());
if(horse.getOwner() == 0)
ps.setNull(5, Types.NULL);
else
ps.setObject(5, horse.getOwner());
ps.setObject(6, horse.getCreatedAt());
ps.setObject(7, horse.getUpdatedAt());
return ps;
}, keyHolder);
if (changes == 0)
throw new NotFoundException("Creating horse failed, no rows affected");
horse.setId(((Number)keyHolder.getKeys().get("id")).longValue());
return horse;
} catch (DataAccessException e) {
// We are doing this in order to not change the exception type
throw new DataAccessException("Adding new records failed", e) {};
} catch(NotFoundException e){
throw new DataRetrievalFailureException("No new records added", e);
}
}
private Horse mapRow(ResultSet resultSet, int i) throws SQLException {
final Horse horse = new Horse();
horse.setId(resultSet.getLong("id"));
horse.setName(resultSet.getString("name"));
horse.setDescription(resultSet.getString("description"));
horse.setScore(resultSet.getShort("score"));
horse.setBirthday(resultSet.getDate("birthday"));
horse.setOwner(resultSet.getLong("owner_id"));
return horse;
}
}

View File

@@ -0,0 +1,52 @@
package at.ac.tuwien.sepm.assignment.individual.persistence.impl;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import at.ac.tuwien.sepm.assignment.individual.persistence.OwnerDao;
import java.lang.invoke.MethodHandles;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class OwnerJdbcDao implements OwnerDao {
private static final String TABLE_NAME = "Owner";
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final JdbcTemplate jdbcTemplate;
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
public OwnerJdbcDao(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public Owner findOneById(Long id) {
LOGGER.trace("Get owner with id {}", id);
final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE id=?";
List<Owner> owners = jdbcTemplate.query(sql, new Object[] { id }, this::mapRow);
if (owners.isEmpty()) throw new NotFoundException("Could not find owner with id " + id);
return owners.get(0);
}
private Owner mapRow(ResultSet resultSet, int i) throws SQLException {
final Owner owner = new Owner();
owner.setId(resultSet.getLong("id"));
owner.setName(resultSet.getString("name"));
owner.setCreatedAt(resultSet.getTimestamp("created_at").toLocalDateTime());
owner.setUpdatedAt(resultSet.getTimestamp("updated_at").toLocalDateTime());
return owner;
}
}

View File

@@ -0,0 +1,22 @@
package at.ac.tuwien.sepm.assignment.individual.service;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
public interface HorseService {
/**
* @param id of the horse to find.
* @return the horse with the specified id.
* @throws RuntimeException will be thrown if something goes wrong during data processing.
* @throws NotFoundException will be thrown if the horse could not be found in the system.
*/
Horse findOneById(Long id);
/**
* @param horse to add.
* @return the horse with the specified id.
* @throws RuntimeException will be thrown if something goes wrong during data processing.
* @throws NotFoundException will be thrown if the horse could not be found in the system.
*/
Horse addHorse(Horse horse);
}

View File

@@ -0,0 +1,17 @@
package at.ac.tuwien.sepm.assignment.individual.service;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
public interface OwnerService {
/**
* @param id of the owner to find.
* @return the owner with the specified id.
* @throws RuntimeException will be thrown if something goes wrong during data processing.
* @throws NotFoundException will be thrown if the owner could not be found in the system.
*/
Owner findOneById(Long id);
}

View File

@@ -0,0 +1,40 @@
package at.ac.tuwien.sepm.assignment.individual.service.impl;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.persistence.HorseDao;
import at.ac.tuwien.sepm.assignment.individual.service.HorseService;
import at.ac.tuwien.sepm.assignment.individual.util.ValidationException;
import at.ac.tuwien.sepm.assignment.individual.util.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import java.lang.invoke.MethodHandles;
@Service
public class SimpleHorseService implements HorseService {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final HorseDao horseDao;
private final Validator validator;
@Autowired
public SimpleHorseService(HorseDao horseDao, Validator validator) {
this.horseDao = horseDao;
this.validator = validator;
}
@Override
public Horse findOneById(Long id) {
LOGGER.trace("findOneById({})", id);
return horseDao.findOneById(id);
}
@Override
public Horse addHorse(Horse horse) throws ValidationException, DataAccessException {
LOGGER.trace("addHorse({})", horse.toString());
this.validator.validateNewHorse(horse);
return horseDao.addHorse(horse);
}
}

View File

@@ -0,0 +1,32 @@
package at.ac.tuwien.sepm.assignment.individual.service.impl;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import at.ac.tuwien.sepm.assignment.individual.persistence.OwnerDao;
import at.ac.tuwien.sepm.assignment.individual.service.OwnerService;
import at.ac.tuwien.sepm.assignment.individual.util.Validator;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SimpleOwnerService implements OwnerService {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final OwnerDao ownerDao;
private final Validator validator;
@Autowired
public SimpleOwnerService(OwnerDao ownerDao, Validator validator) {
this.ownerDao = ownerDao;
this.validator = validator;
}
@Override
public Owner findOneById(Long id) {
LOGGER.trace("findOneById({})", id);
return ownerDao.findOneById(id);
}
}

View File

@@ -0,0 +1,9 @@
package at.ac.tuwien.sepm.assignment.individual.util;
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,23 @@
package at.ac.tuwien.sepm.assignment.individual.util;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
import org.springframework.stereotype.Component;
@Component
public class Validator {
public void validateNewOwner(Owner owner) throws ValidationException {
}
public void validateUpdateOwner(Owner owner) throws ValidationException {
}
public void validateNewHorse(Horse horse) throws ValidationException {
if(horse.getScore() > 5 || horse.getScore() < 1) {
throw new ValidationException("Score value " + horse.getScore() + " not allowed. The score must be an integer between 1 and 5");
}
}
}

View File

@@ -0,0 +1,19 @@
logging:
level:
root: INFO
file:
name: ./log/wendys-friends.log
spring:
application:
name: wendys-friends
datasource:
url: "jdbc:h2:./wendydb;INIT=RUNSCRIPT FROM 'classpath:sql/createSchema.sql'"
username: "sa"
password: ""
driver-class-name: "org.h2.Driver"
h2:
console:
enabled: true
server:
port: 8080

View File

@@ -0,0 +1,21 @@
CREATE TABLE IF NOT EXISTS owner
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS horse
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
score TINYINT NOT NULL CHECK(score >= 1 AND score <= 5),
birthday DATE NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
ALTER TABLE horse ADD IF NOT EXISTS owner_id BIGINT NULL;
ALTER TABLE horse ADD CONSTRAINT IF NOT EXISTS FL_OWNER FOREIGN KEY (owner_id) REFERENCES owner(id);

View File

@@ -0,0 +1,7 @@
-- insert initial test data
-- the id is hardcode to enable references between further test data
INSERT INTO owner (ID, NAME, CREATED_AT, UPDATED_AT)
VALUES (1, 'Fred', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()),
(2, 'Julia', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()),
(3, 'Kim', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP());

View File

@@ -0,0 +1,30 @@
package at.ac.tuwien.sepm.assignment.individual.base;
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
public interface TestData {
/**
* URI Data
*/
String BASE_URL = "http://localhost:";
String HORSE_URL = "/horses";
String OWNER_URL = "/owners";
/**
* Owner Data
*/
static Owner getNewOwner() {
return new Owner("Owner");
}
static Owner getNewOwner(String name) {
return new Owner(name);
}
static Owner getNewOwnerWithId() {
return new Owner(1L, "Owner");
}
}

View File

@@ -0,0 +1,40 @@
package at.ac.tuwien.sepm.assignment.individual.unit.persistence;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles("test")
public class OwnerDaoJdbcTest extends OwnerDaoTestBase {
@Autowired
PlatformTransactionManager txm;
TransactionStatus txstatus;
@BeforeEach
public void setupDBTransaction() {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
txstatus = txm.getTransaction(def);
assumeTrue(txstatus.isNewTransaction());
txstatus.setRollbackOnly();
}
@AfterEach
public void tearDownDBData() {
txm.rollback(txstatus);
}
}

View File

@@ -0,0 +1,23 @@
package at.ac.tuwien.sepm.assignment.individual.unit.persistence;
import static org.junit.jupiter.api.Assertions.*;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import at.ac.tuwien.sepm.assignment.individual.persistence.OwnerDao;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class OwnerDaoTestBase {
@Autowired
OwnerDao ownerDao;
@Test
@DisplayName("Finding owner by non-existing ID should throw NotFoundException")
public void findingOwnerById_nonExisting_shouldThrowNotFoundException() {
assertThrows(NotFoundException.class,
() -> ownerDao.findOneById(1L));
}
}