42 Commits

Author SHA1 Message Date
adc7b4be65 Merge branch 'merge' 2022-02-11 05:41:44 +01:00
095dd861c5 Removed unused objects 2022-02-11 05:41:10 +01:00
898d2e9cf1 Added comments 2022-02-10 09:31:05 +01:00
5cdab5b434 Merge branch 'master' into merge 2022-02-07 11:28:06 +01:00
43c967638b Added equals methods 2022-02-07 11:26:49 +01:00
24794e2085 Create user on first login 2022-02-05 23:31:22 +01:00
fcfeaf0979 Fixed equals 2022-02-01 15:44:03 +01:00
3b711b5d9f Added equals methods 2022-02-01 14:05:58 +01:00
5066afbb92 Fixed user/edit 2022-01-31 21:16:19 +01:00
609c0353d0 Check isFullDay 2022-01-31 20:52:30 +01:00
2918bc46b5 Fixed user/edit 2022-01-31 20:51:04 +01:00
bba0b6d5d2 Fixed user/del 2022-01-29 11:55:57 +01:00
710b661b0d Fixed user/del endpoint 2022-01-29 09:55:06 +01:00
f22bdf3040 Improved user endpoints 2022-01-28 05:52:48 +01:00
3575dccf94 Changed all endpoints to post 2022-01-26 14:26:47 +01:00
8f04ac7ae8 Added userDAO 2022-01-25 19:17:41 +01:00
56919ab412 Cleanup 2022-01-25 19:16:58 +01:00
e3408d1566 Fixed auth 2022-01-23 21:23:30 +01:00
eea38d578b Sort events at query 2022-01-19 09:40:29 +01:00
031c1cea2a Added refactored /event/ endpoints 2022-01-18 23:32:57 +01:00
154617ce88 Added refactored /event/ endpoints 2022-01-18 22:27:57 +01:00
35e7350962 Fixed named query 2022-01-18 15:04:13 +01:00
37d275d537 Added named native query 2022-01-18 08:18:58 +01:00
3796afb712 Added auth to the /event/del endpoint 2022-01-17 05:57:44 +01:00
e05faab31e Added auth to the /event/del endpoint 2022-01-14 19:59:16 +01:00
d5b6d6357e Added auth to a lot of the endpoints 2022-01-14 17:53:42 +01:00
0531f868d0 Save token in DB
Check for unique logins
2022-01-13 17:34:20 +01:00
de1dcf7673 Added edit-endpoint 2022-01-13 17:32:58 +01:00
e062d9254f Fixed isAdmin at addNewUser endpoint 2022-01-11 17:08:09 +01:00
eeef96ffb6 Fixed Spring security 2022-01-10 13:25:52 +01:00
68eb7e5863 Refactor 2022-01-10 12:11:52 +01:00
8d6a850d30 Added login endpoint 2021-12-20 19:44:01 +01:00
bfbcd5c44b Added del-event endpoint 2021-11-28 18:20:17 +01:00
540d3a130f Fixed date conversion 2021-11-28 17:37:10 +01:00
8382b80e0e Get all relevant data form all-events 2021-11-28 15:14:11 +01:00
8ffaf525eb Changed date to PRIMARY KEY 2021-11-28 15:13:31 +01:00
f0e89184a4 Added column annotations to data classes 2021-11-27 19:23:44 +01:00
768c57a234 Added new native queries 2021-11-27 17:27:04 +01:00
2cec62c453 Successfully added native queries 2021-11-25 22:28:26 +01:00
281d2947cd Completely rebuild server-project with gradle 2021-11-22 07:01:01 +01:00
fcdaf2604f Added installation guide to the readme 2021-11-07 20:47:44 +01:00
e953055bce Added sql creation script 2021-11-07 20:47:09 +01:00
46 changed files with 2033 additions and 999 deletions

3
.gitignore vendored
View File

@@ -19,3 +19,6 @@ hs_err_pid*
# private file with login-data
application.properties
.idea/
.gradle/

View File

@@ -1,2 +1,31 @@
# VPR-Backend
This project includes the backend for the VPR-project.
# Installation and Getting Started
- To run the server you first have to install a MySQL database.
> For example MariaDB (https://mariadb.com/downloads/)
- Then you have to create a the database with the "create VPR-DB.sql"-file.
- Create a new user for the db e.g. named "springuser"
> The database should only be reachable from localhost to improve the security!
- Next create a "application.properties"-file in "vpr/src/main/resources". It should contain following content:
```
# "update" will automatically get the db-structure
# It can be "none", "update", "create", or "create-drop", but you have to start with "create" or "update" and should use "none" in production(for security).
# see https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl for more information.
spring.jpa.hibernate.ddl-auto=update
# Specify the database address, port and name
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/vpr
# Add the login-data
spring.datasource.username=<USERNAME>
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#spring.jpa.show-sql: true
```
You should now be able to start the application :D

91
create VPR-DB.sql Normal file
View File

@@ -0,0 +1,91 @@
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server Version: 10.6.4-MariaDB - mariadb.org binary distribution
-- Server Betriebssystem: Win64
-- HeidiSQL Version: 11.3.0.6295
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-- Exportiere Datenbank Struktur für vpr
CREATE DATABASE IF NOT EXISTS `vpr` /*!40100 DEFAULT CHARACTER SET utf8mb3 */;
USE `vpr`;
-- Exportiere Struktur von Tabelle vpr.event
CREATE TABLE IF NOT EXISTS `event` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '0',
`priority` tinyint(2) unsigned NOT NULL DEFAULT 0,
`is_full_day` bit(1) NOT NULL DEFAULT b'0',
`start` time DEFAULT NULL,
`end` time DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
-- Exportiere Daten aus Tabelle vpr.event: ~2 rows (ungefähr)
/*!40000 ALTER TABLE `event` DISABLE KEYS */;
INSERT INTO `event` (`id`, `name`, `priority`, `is_full_day`, `start`, `end`) VALUES
(1, 'TestEvent', 0, b'0', '00:00:00', '00:00:00'),
(2, 'Event 2', 1, b'0', NULL, NULL);
/*!40000 ALTER TABLE `event` ENABLE KEYS */;
-- Exportiere Struktur von Tabelle vpr.event_list
CREATE TABLE IF NOT EXISTS `event_list` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`event_id` int(10) unsigned NOT NULL,
`date` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `UID` (`user_id`) USING BTREE,
KEY `EID` (`event_id`) USING BTREE,
CONSTRAINT `event_id` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
-- Exportiere Daten aus Tabelle vpr.event_list: ~2 rows (ungefähr)
/*!40000 ALTER TABLE `event_list` DISABLE KEYS */;
INSERT INTO `event_list` (`id`, `user_id`, `event_id`, `date`) VALUES
(1, 1, 2, '2021-11-11'),
(2, 2, 1, '2021-12-24');
/*!40000 ALTER TABLE `event_list` ENABLE KEYS */;
-- Exportiere Struktur von Tabelle vpr.hibernate_sequence
CREATE TABLE IF NOT EXISTS `hibernate_sequence` (
`next_val` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-- Exportiere Daten aus Tabelle vpr.hibernate_sequence: ~1 rows (ungefähr)
/*!40000 ALTER TABLE `hibernate_sequence` DISABLE KEYS */;
INSERT INTO `hibernate_sequence` (`next_val`) VALUES
(3);
/*!40000 ALTER TABLE `hibernate_sequence` ENABLE KEYS */;
-- Exportiere Struktur von Tabelle vpr.user
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '0',
`forename` varchar(20) NOT NULL DEFAULT '0',
`password` varchar(50) NOT NULL DEFAULT '0',
`token` varchar(50) DEFAULT '0',
`is_admin` bit(1) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb3;
-- Exportiere Daten aus Tabelle vpr.user: ~3 rows (ungefähr)
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` (`id`, `name`, `forename`, `password`, `token`, `is_admin`) VALUES
(1, 'Beyer', 'Marc', 'test', 'test', b'1'),
(2, 'Kühn', 'Marco', 'test', 'test', b'0'),
(3, 'Rechtin', 'Alex', 'test', 'test', b'1');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;

View File

@@ -1,8 +1,9 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
@@ -12,12 +13,18 @@ target/
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
@@ -25,9 +32,6 @@ target/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

29
server/build.gradle Normal file
View File

@@ -0,0 +1,29 @@
plugins {
id 'org.springframework.boot' version '2.5.6'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.vpr'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// JSON web token
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2',
'io.jsonwebtoken:jjwt-jackson:0.11.2'
}
test {
useJUnitPlatform()
}

BIN
server/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
server/gradlew vendored Normal file
View File

@@ -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" "$@"

89
server/gradlew.bat vendored Normal file
View File

@@ -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

1
server/settings.gradle Normal file
View File

@@ -0,0 +1 @@
rootProject.name = 'server'

View File

@@ -0,0 +1,14 @@
//Marc Beyer//
package com.vpr.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}

View File

@@ -0,0 +1,16 @@
//Marco Kühn//
package com.vpr.server.controller;
import com.vpr.server.data.User;
import com.vpr.server.repository.UserRepository;
public class AuthController {
public User getAuthUserFromHeader(String authorizationHeader, UserRepository userRepository){
String[] splitAuthHeader = authorizationHeader.split("\\s");
if(splitAuthHeader.length == 2){
return userRepository.findByToken(splitAuthHeader[1]);
}
return null;
}
}

View File

@@ -0,0 +1,253 @@
//Marc Beyer//
package com.vpr.server.controller;
import com.vpr.server.dao.interfaces.EventDAO;
import com.vpr.server.data.Event;
import com.vpr.server.data.User;
import com.vpr.server.data.UserEvent;
import com.vpr.server.json.JSONMapper;
import com.vpr.server.json.Validator;
import com.vpr.server.repository.EventRepository;
import com.vpr.server.repository.UserEventRepository;
import com.vpr.server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping(path = "/event")
public class EventController {
@Autowired
private UserRepository userRepository;
@Autowired
private EventRepository eventRepository;
@Autowired
private UserEventRepository userEventRepository;
@Autowired
private EventDAO eventDAO;
/******************
* POST-ENDPOINTS *
******************/
@PostMapping(path = "/add")
public @ResponseBody
ResponseEntity<String> addEvent(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam long userId,
@RequestParam String date,
@RequestParam String name,
@RequestParam String start,
@RequestParam String end,
@RequestParam Integer priority,
@RequestParam Boolean isFullDay,
@RequestParam Boolean isPrivate
) {
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>("Du hast keine Rechte um den Termin zu erstellen", HttpStatus.UNAUTHORIZED);
}
ResponseEntity<String> BAD_REQUEST = createEventAndUserEvent(userId, date, name, start, end, priority, isFullDay, isPrivate);
if (BAD_REQUEST != null) return BAD_REQUEST;
return new ResponseEntity<>("", HttpStatus.OK);
}
@PostMapping(path = "/del")
public @ResponseBody
ResponseEntity<String> delEvent(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam long eventId,
@RequestParam long userId,
@RequestParam String date
) {
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>("Du hast keine Rechte um den Termin zu löschen", HttpStatus.UNAUTHORIZED);
}
eventRepository.deleteUserEventsById(userId, eventId, date);
if (eventDAO.getAllEventsWithId(eventId).size() == 0) {
eventRepository.deleteById(eventId);
}
return new ResponseEntity<>("", HttpStatus.OK);
}
@PostMapping(path = "/all")
public @ResponseBody
ResponseEntity<String> getAllEvents(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam String startDate,
@RequestParam String endDate
) {
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null) {
return new ResponseEntity<>("Bitte erneut einloggen", HttpStatus.UNAUTHORIZED);
}
List<Event> eventList = eventDAO.getAllEventsInTimespan(authUser.getId(), startDate, endDate);
return new ResponseEntity<>(JSONMapper.eventListToJSON(eventList), HttpStatus.OK);
}
@PostMapping(path = "/edit")
public @ResponseBody
ResponseEntity<String> editEvent(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam Long eventId,
@RequestParam Long userId,
@RequestParam String date,
@RequestParam String newDate,
@RequestParam String newName,
@RequestParam String newStart,
@RequestParam String newEnd,
@RequestParam Integer newPriority,
@RequestParam Boolean newIsFullDay,
@RequestParam Boolean newIsPrivate
) {
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>(
"Du hast keine Rechte um den Termin zu bearbeiten",
HttpStatus.UNAUTHORIZED
);
}
List<Event> eventList = eventDAO.getAllEventsWithIdAndDate(userId, eventId, date);
if (eventList == null || eventList.size() == 0) {
return new ResponseEntity<>("Der Termin exestiert nicht in der Datenbank", HttpStatus.BAD_REQUEST);
}
if (eventList.size() > 1) {
return new ResponseEntity<>(
"Der Termin ist doppelt vorhanden. " +
"(Um das zu lösen versuche den Termin zu löschen und erneut zu erstellen)",
HttpStatus.BAD_REQUEST
);
}
ResponseEntity<String> error = createEventAndUserEvent(
userId,
newDate,
newName,
newStart,
newEnd,
newPriority,
newIsFullDay,
newIsPrivate,
eventId
);
if (error != null) return error;
eventRepository.deleteUserEventsById(userId, eventId, date);
if (eventDAO.getAllEventsWithId(eventId).size() == 0) {
eventRepository.deleteById(eventId);
}
return new ResponseEntity<>("", HttpStatus.OK);
}
private ResponseEntity<String> createEventAndUserEvent(
long userId,
String date,
String name,
String start,
String end,
Integer priority,
Boolean isFullDay,
Boolean isPrivate
) {
return createEventAndUserEvent(
userId,
date,
name,
start,
end,
priority,
isFullDay,
isPrivate,
-1
);
}
private ResponseEntity<String> createEventAndUserEvent(
long userId,
String date,
String name,
String start,
String end,
Integer priority,
Boolean isFullDay,
Boolean isPrivate,
long oldEventId
) {
User user = userRepository.findById(userId);
if (user == null) {
return new ResponseEntity<>("UserId nicht korrekt", HttpStatus.BAD_REQUEST);
}
try {
Event event = new Event();
event.setName(Validator.ValidateEventName(name));
event.setStart(Validator.ValidateEventTime(start));
event.setEnd(Validator.ValidateEventTime(end));
event.setPriority(priority);
event.setFullDay(isFullDay);
event.setPrivate(isPrivate);
UserEvent userEvent = new UserEvent();
userEvent.setDate(Validator.ValidateEventDate(date));
userEvent.setEvent(event);
userEvent.setUser(user);
List<UserEvent> userEvents = userEventRepository.findByUserIdAndDate(user.getId(), userEvent.getDate());
boolean isFullDayButDayHasEvents = event.isFullDay() && userEvents.size() > 0;
boolean userEventIsSelf = userEvents.size() == 1 &&
isSelf(userEvent.getDate(), userId, oldEventId, userEvents.get(0));
if (isFullDayButDayHasEvents && !userEventIsSelf) {
return new ResponseEntity<>(
"Es gibt bereits Termine am " + userEvent.getDate(),
HttpStatus.BAD_REQUEST
);
} else {
for (UserEvent ue : userEvents) {
if (ue.getEvent().isFullDay() && !isSelf(userEvent.getDate(), userId, oldEventId, ue)) {
return new ResponseEntity<>(
"Der Tag " + userEvent.getDate() + " ist schon mit '"
+ ue.getEvent().getName() + "' belegt",
HttpStatus.BAD_REQUEST
);
}
}
}
eventRepository.save(event);
userEventRepository.save(userEvent);
} catch (IllegalArgumentException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
return null;
}
private boolean isSelf(Date date, long userId, long eventId, UserEvent userEvent){
return date.equals(userEvent.getDate()) &&
userId == userEvent.getUser().getId() &&
eventId == userEvent.getEvent().getId();
}
}

View File

@@ -0,0 +1,31 @@
//Marc Beyer//
package com.vpr.server.controller;
import com.vpr.server.repository.EventRepository;
import com.vpr.server.repository.UserEventRepository;
import com.vpr.server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.ResponseStatusException;
@Controller // This means that this class is a Controller
@RequestMapping(path = "/vpr") // This means URL's start with /demo (after Application path)
public class MainController {
@GetMapping(path = "/status-test")
public String statusTest(){
throw new ResponseStatusException(HttpStatus.I_AM_A_TEAPOT, "TestTestTest");
}
@PostMapping(path = "/header-test")
public ResponseEntity<String> headerTest(@RequestHeader("Authorization") String authorizationHeader){
System.out.println("authorizationHeader: " + authorizationHeader);
return new ResponseEntity<>(authorizationHeader, HttpStatus.OK);
}
}

View File

@@ -0,0 +1,232 @@
//Marc Beyer//
package com.vpr.server.controller;
import com.vpr.server.dao.interfaces.UserDAO;
import com.vpr.server.data.User;
import com.vpr.server.json.JSONMapper;
import com.vpr.server.repository.UserRepository;
import com.vpr.server.security.Hasher;
import com.vpr.server.security.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping(path = "/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private UserDAO userDAO;
private final AuthController authController;
public UserController() {
this.authController = new AuthController();
}
/******************
* POST-ENDPOINTS *
******************/
@PostMapping(path = "/add")
public @ResponseBody
ResponseEntity<String> addNewUser(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam String name,
@RequestParam String forename,
@RequestParam String login,
@RequestParam String password,
@RequestParam Boolean isAdmin
) {
User authUser = authController.getAuthUserFromHeader(authorizationHeader, userRepository);
if (authUser == null || !authUser.isAdmin()) {
return new ResponseEntity<>("Du hast keine Rechte um einen User an zu legen", HttpStatus.UNAUTHORIZED);
}
if (userRepository.findByLogin(login) != null) {
return new ResponseEntity<>("Login exestiert bereits", HttpStatus.BAD_REQUEST);
}
byte[] salt = Hasher.GenerateSalt();
byte[] hash;
try {
hash = Hasher.HashPassword(password, salt);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return new ResponseEntity<>("Fehler beim hashen", HttpStatus.INTERNAL_SERVER_ERROR);
}
User user = new User();
user.setName(name);
user.setForename(forename);
user.setLogin(login);
user.setPassword(hash);
user.setSalt(salt);
user.setToken("");
user.setAdmin(isAdmin);
userRepository.save(user);
return new ResponseEntity<>("" + user.getId(), HttpStatus.OK);
}
@PostMapping(path = "/login")
public @ResponseBody
ResponseEntity<String> login(
@RequestParam String login,
@RequestParam String password
) {
if(userRepository.findAllUsernames().length == 0){
byte[] salt = Hasher.GenerateSalt();
byte[] hash;
try {
hash = Hasher.HashPassword(password, salt);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return new ResponseEntity<>("Fehler beim hashen", HttpStatus.INTERNAL_SERVER_ERROR);
}
User user = new User();
user.setName("Admin");
user.setForename(login);
user.setLogin(login);
user.setPassword(hash);
user.setSalt(salt);
user.setToken("");
user.setAdmin(true);
userRepository.save(user);
}
System.out.println(login + " tries to login.");
User user = userRepository.findByLogin(login);
if (user == null) {
System.out.println("Login for " + login + " failed.");
return new ResponseEntity<>("Falscher login", HttpStatus.UNAUTHORIZED);
}
byte[] salt = user.getSalt();
byte[] hash;
try {
hash = Hasher.HashPassword(password, salt);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return new ResponseEntity<>("Fehler beim hashen", HttpStatus.INTERNAL_SERVER_ERROR);
}
if (Arrays.equals(user.getPassword(), hash)) {
String token = Token.Generate(user.getLogin());
user.setToken(token);
userRepository.save(user);
System.out.println(user.getLogin() + " is now logged in.");
System.out.println(Token.Verify(Token.Generate(user.getLogin()), user.getLogin()));
return new ResponseEntity<>(token + " " + user.getId(), HttpStatus.OK);
}
System.out.println(user.getLogin() + " failed to logged in.");
System.out.println("entered : " + javax.xml.bind.DatatypeConverter.printHexBinary(hash));
System.out.println("required: " + javax.xml.bind.DatatypeConverter.printHexBinary(user.getPassword()));
return new ResponseEntity<>("Falscher login", HttpStatus.UNAUTHORIZED);
}
@PostMapping(path = "/login-with-token")
public @ResponseBody
ResponseEntity<String> loginWithToken(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam long userId
) {
User authUser = authController.getAuthUserFromHeader(authorizationHeader, userRepository);
if (authUser == null || authUser.getId() != userId) {
return new ResponseEntity<>("Falscher auth-token", HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>("", HttpStatus.OK);
}
@PostMapping(path = "/del")
public @ResponseBody
ResponseEntity<String> deleteUser(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam long userId
) {
User authUser = authController.getAuthUserFromHeader(authorizationHeader, userRepository);
if (authUser == null || !authUser.isAdmin()) {
return new ResponseEntity<>("Du hast keine Rechte um den User zu löschen", HttpStatus.UNAUTHORIZED);
}
User user = userRepository.findById(userId);
if (user == null) {
return new ResponseEntity<>("User nicht in der Datenbank vorhanden", HttpStatus.BAD_REQUEST);
}
if(!userDAO.deleteAllUserEvents(user.getId())){
return new ResponseEntity<>("User konnte nicht gelöscht werden", HttpStatus.INTERNAL_SERVER_ERROR);
}
userRepository.delete(user);
return new ResponseEntity<>("", HttpStatus.OK);
}
@PostMapping(path = "/edit")
public @ResponseBody ResponseEntity<String> editUser(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam long userId,
@RequestParam String name,
@RequestParam String forename,
@RequestParam String login,
@RequestParam(required = false) String password,
@RequestParam Boolean isAdmin
) {
User authUser = authController.getAuthUserFromHeader(authorizationHeader, userRepository);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>("Du hast keine Rechte um den User zu editieren", HttpStatus.UNAUTHORIZED);
}
if(isAdmin && !authUser.isAdmin()){
return new ResponseEntity<>("Du hast keine Rechte um dich zum Admin zu machen", HttpStatus.UNAUTHORIZED);
}
User user = userRepository.findById(userId);
if (user == null) {
return new ResponseEntity<>("User nicht in der Datenbank vorhanden", HttpStatus.BAD_REQUEST);
}
User userWithLogin = userRepository.findByLogin(login);
if (userWithLogin != null && userWithLogin.getId() != userId) {
return new ResponseEntity<>("Login exestiert bereits", HttpStatus.BAD_REQUEST);
}
if(password != null){
byte[] salt = Hasher.GenerateSalt();
byte[] hash;
try {
hash = Hasher.HashPassword(password, salt);
user.setPassword(hash);
user.setSalt(salt);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return new ResponseEntity<>("Fehler beim hashen", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
user.setName(name);
user.setForename(forename);
user.setLogin(login);
user.setToken("");
user.setAdmin(isAdmin);
userRepository.save(user);
return new ResponseEntity<>("", HttpStatus.OK);
}
@PostMapping(path = "/all")
public @ResponseBody
ResponseEntity<String> getAllUser() {
List<User> userList = userDAO.getAllUser();
return new ResponseEntity<>(JSONMapper.userListToJSON(userList), HttpStatus.OK);
}
}

View File

@@ -0,0 +1,49 @@
//Marc Beyer//
package com.vpr.server.dao.implementation;
import com.vpr.server.dao.interfaces.EventDAO;
import com.vpr.server.data.Event;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class EventDAOImplementation implements EventDAO {
@PersistenceContext
private EntityManager manager;
@Override
public List<Event> getAllEvents() {
return manager.createNamedQuery("getAllEvents", Event.class).getResultList();
}
@Override
public List<Event> getAllEventsWithId(long eventId) {
return manager.createNamedQuery("getAllEventsWithId", Event.class)
.setParameter("eventId", eventId)
.getResultList();
}
@Override
public List<Event> getAllEventsInTimespan(long userId, String startDate, String endDate) {
return manager.createNamedQuery("getAllEventsInTimespan", Event.class)
.setParameter("userId", userId)
.setParameter("startDate", startDate)
.setParameter("endDate", endDate)
.getResultList();
}
@Override
public List<Event> getAllEventsWithIdAndDate(long userId, long eventId, String date) {
return manager.createNamedQuery("getAllEventsWithIdAndDate", Event.class)
.setParameter("userId", userId)
.setParameter("eventId", eventId)
.setParameter("date", date)
.getResultList();
}
}

View File

@@ -0,0 +1,37 @@
//Marc Beyer//
package com.vpr.server.dao.implementation;
import com.vpr.server.dao.interfaces.UserDAO;
import com.vpr.server.data.User;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class UserDAOImplementation implements UserDAO {
@PersistenceContext
private EntityManager manager;
@Override
public List<User> getAllUser() {
return manager.createNamedQuery("getAllUser", User.class).getResultList();
}
@Override
public boolean deleteAllUserEvents(long userId) {
try {
manager.createNamedQuery("deleteAllUserEvents", User.class)
.setParameter("userId", userId)
.executeUpdate();
return true;
}catch (Exception e){
return false;
}
}
}

View File

@@ -0,0 +1,17 @@
//Marc Beyer//
package com.vpr.server.dao.interfaces;
import com.vpr.server.data.Event;
import java.util.List;
public interface EventDAO {
List<Event> getAllEvents();
List<Event> getAllEventsInTimespan(long userId, String startDate, String endDate);
List<Event> getAllEventsWithIdAndDate(long userId, long eventId, String date);
List<Event> getAllEventsWithId(long eventId);
}

View File

@@ -0,0 +1,12 @@
//Marc Beyer//
package com.vpr.server.dao.interfaces;
import com.vpr.server.data.User;
import java.util.List;
public interface UserDAO {
List<User> getAllUser();
boolean deleteAllUserEvents(long userId);
}

View File

@@ -0,0 +1,119 @@
//Marc Beyer//
package com.vpr.server.data;
import java.sql.Date;
import java.sql.Time;
public class DateEvent {
private long userId;
private String userName;
private String userForename;
private Date date;
private String name;
private Integer priority;
private boolean isFullDay;
private Time start;
private Time end;
public DateEvent(UserEvent userEvent) {
this.userId = userEvent.getUser().getId();
this.userName = userEvent.getUser().getName();
this.userForename = userEvent.getUser().getForename();
this.date = userEvent.getDate();
this.name = userEvent.getEvent().getName();
this.priority = userEvent.getEvent().getPriority();
this.isFullDay = userEvent.getEvent().isFullDay();
this.start = userEvent.getEvent().getStart();
this.end = userEvent.getEvent().getEnd();
}
public DateEvent(long userId, String userName, String userForename, Date date, String name, Integer priority, boolean isFullDay, Time start, Time end) {
this.userId = userId;
this.userName = userName;
this.userForename = userForename;
this.date = date;
this.name = name;
this.priority = priority;
this.isFullDay = isFullDay;
this.start = start;
this.end = end;
}
/*********************
* Getter and Setter *
*********************/
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserForename() {
return userForename;
}
public void setUserForename(String userForename) {
this.userForename = userForename;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public boolean isFullDay() {
return isFullDay;
}
public void setFullDay(boolean fullDay) {
isFullDay = fullDay;
}
public Time getStart() {
return start;
}
public void setStart(Time start) {
this.start = start;
}
public Time getEnd() {
return end;
}
public void setEnd(Time end) {
this.end = end;
}
}

View File

@@ -0,0 +1,174 @@
//Marc Beyer//
package com.vpr.server.data;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Time;
import java.util.List;
@Entity(name = "Event") // @Entity creates a table out of this class with Hibernate
@Table(name = "event")
@NamedNativeQueries({
@NamedNativeQuery(
name = "getAllEvents",
query = "SELECT * FROM event",
resultClass = Event.class
),
@NamedNativeQuery(
name = "getAllEventsInTimespan",
query = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE (ue.user_id = :userId OR e.is_private = 0) " +
"AND ue.date >= :startDate " +
"AND ue.date < :endDate " +
"ORDER BY ue.date, e.priority DESC, e.start",
resultClass = Event.class
),
@NamedNativeQuery(
name = "getAllEventsWithIdAndDate",
query = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.user_id = :userId " +
"AND ue.event_id = :eventId " +
"AND ue.date = :date",
resultClass = Event.class
),
@NamedNativeQuery(
name = "getAllEventsWithId",
query = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.event_id = :eventId",
resultClass = Event.class
)
})
public class Event implements Serializable {
// Generate the primary key
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "priority", nullable = false)
private Integer priority;
@Column(name = "is_full_day", nullable = false)
private boolean isFullDay;
@Column(name = "is_private", nullable = false)
private boolean isPrivate;
@Column(name = "start")
private Time start;
@Column(name = "end")
private Time end;
@OneToMany(mappedBy = "event")
private List<UserEvent> userEvent;
/*********************
* Getter and Setter *
*********************/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public boolean isFullDay() {
return isFullDay;
}
public void setFullDay(boolean fullDay) {
isFullDay = fullDay;
}
public boolean isPrivate() {
return isPrivate;
}
public void setPrivate(boolean aPrivate) {
isPrivate = aPrivate;
}
public Time getStart() {
return start;
}
public void setStart(Time start) {
this.start = start;
}
public Time getEnd() {
return end;
}
public void setEnd(Time end) {
this.end = end;
}
public List<UserEvent> getUserEvent() {
return userEvent;
}
public void setUserEvent(List<UserEvent> userEvent) {
this.userEvent = userEvent;
}
// toString
@Override
public String toString() {
return "Event{" +
"id=" + id +
", name='" + name + '\'' +
", priority=" + priority +
", isFullDay=" + isFullDay +
", start=" + start +
", end=" + end +
", userEvent=" + userEvent +
'}';
}
@Override
public boolean equals(Object obj){
if(!(obj instanceof Event)){
return false;
}
Event event = (Event) obj;
System.out.println(event.getId() + " " + getId());
return event.getId() == getId();
}
@Override
public int hashCode(){
return (int)getId();
}
}

View File

@@ -0,0 +1,147 @@
//Marc Beyer//
package com.vpr.server.data;
import javax.persistence.*;
import java.util.List;
// @Entity creates a table out of this class with Hibernate
@Entity(name = "User")
@Table(name = "user")
@SqlResultSetMapping(name="deleteResult", columns = {
@ColumnResult(name = "count")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "getAllUser",
query = "SELECT * FROM user",
resultClass = User.class
),
@NamedNativeQuery(
name = "deleteAllUserEvents",
query = "DELETE FROM user_event WHERE user_id = :userId",
resultSetMapping = "deleteResult"
)
})
public class User {
// Generate the primary key
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="name", nullable=false)
private String name;
@Column(name="forename", nullable=false)
private String forename;
@Column(name="login", nullable=false)
private String login;
@Column(name="password", nullable=false)
private byte[] password;
@Column(name="salt", nullable=false)
private byte[] salt;
@Column(name="token")
private String token;
@Column(name="is_admin", nullable=false)
private boolean isAdmin;
@OneToMany(mappedBy = "user")
private List<UserEvent> userEvent;
/*********************
* Getter and Setter *
*********************/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public byte[] getPassword() {
return password;
}
public void setPassword(byte[] password) {
this.password = password;
}
public byte[] getSalt() {
return salt;
}
public void setSalt(byte[] salt) {
this.salt = salt;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
public List<UserEvent> getEventList() {
return userEvent;
}
public void setEventList(List<UserEvent> userEvent) {
this.userEvent = userEvent;
}
@Override
public boolean equals(Object obj){
if(!(obj instanceof User)){
return false;
}
User user = (User) obj;
return user.getId() == getId();
}
@Override
public int hashCode(){
return (int)getId();
}
}

View File

@@ -0,0 +1,101 @@
//Marc Beyer//
package com.vpr.server.data;
import javax.persistence.*;
import java.sql.Date;
// @Entity creates a table out of this class with Hibernate
// @Table defines the table-name
@Entity
@Table(name="user_event")
@IdClass(UserEventId.class)
public class UserEvent {
@Id
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
@Id
@ManyToOne
@JoinColumn(name = "event_id", referencedColumnName = "id")
private Event event;
@Id
@Column(name="date", columnDefinition = "DATE DEFAULT CURRENT_DATE", nullable = false)
private Date date;
/*********************
* Getter and Setter *
*********************/
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
// toString
@Override
public String toString() {
return "UserEvent{" +
"user=" + user.getId() +
", event=" + event.getId() +
", date=" + date +
'}';
}
@Override
public boolean equals(Object obj){
System.out.println("equals");
if(!(obj instanceof UserEvent)){
System.out.println("not an userevent");
return false;
}
UserEvent userEvent = (UserEvent) obj;
System.out.println("date " + userEvent.getDate().equals(getDate()));
System.out.println("user " + userEvent.getUser().equals(getUser()));
System.out.println("event " + userEvent.getEvent().equals(getEvent()));
return userEvent.getDate().equals(getDate()) &&
userEvent.getUser().equals(getUser()) &&
userEvent.getEvent().equals(getEvent());
}
@Override
public int hashCode(){
long hash = getUser().hashCode() +
getEvent().hashCode() +
getDate().hashCode();
return (int)hash;
}
}

View File

@@ -0,0 +1,39 @@
//Marc Beyer//
package com.vpr.server.data;
import java.io.Serializable;
import java.sql.Date;
public class UserEventId implements Serializable {
private long user;
private long event;
private Date date;
/*********************
* Getter and Setter *
*********************/
public long getUser() {
return user;
}
public void setUser(long user) {
this.user = user;
}
public long getEvent() {
return event;
}
public void setEvent(long event) {
this.event = event;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

View File

@@ -0,0 +1,80 @@
//Marco Kühn//
package com.vpr.server.json;
import com.vpr.server.data.Event;
import com.vpr.server.data.User;
import com.vpr.server.data.UserEvent;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
public class JSONMapper {
public static String userToJSON(User user) {
return "{" +
"\"userId\": " + user.getId() + ", " +
"\"forename\": \"" + user.getForename() + "\", " +
"\"name\": \"" + user.getName() + "\", " +
"\"login\": \"" + user.getLogin() + "\"," +
"\"admin\": " + user.isAdmin() +
"}";
}
public static String userListToJSON(List<User> userList) {
StringBuilder userListJSON = new StringBuilder();
for (User user : userList) {
userListJSON.append(", ");
userListJSON.append(userToJSON(user));
}
userListJSON.delete(0, 2);
return "[" + userListJSON + "]";
}
public static List<String> eventToJSON(Event event) {
List<String> eventListJSON = new ArrayList<>();
for (UserEvent userEvent : event.getUserEvent()) {
String eventJSON = "{" +
"\"ownerId\": " + userEvent.getUser().getId() + ", " +
"\"ownerName\": \"" + userEvent.getUser().getForename() + " " + userEvent.getUser().getName() + "\", " +
"\"date\": \"" + userEvent.getDate() + "\", " +
"\"id\": " + event.getId() + "," +
"\"name\": \"" + event.getName() + "\"," +
"\"priority\": " + event.getPriority() + "," +
"\"fullDay\": " + event.isFullDay() + "," +
"\"private\": " + event.isPrivate() + "," +
"\"start\": " + timeToJSON(event.getStart()) + "," +
"\"end\": " + timeToJSON(event.getEnd()) +
"}";
eventListJSON.add(eventJSON);
}
return eventListJSON;
}
public static String eventListToJSON(List<Event> eventList) {
StringBuilder eventListJSON = new StringBuilder();
for (Event event : eventList) {
List<String> eventsJSON = eventToJSON(event);
for (String eventJSON : eventsJSON) {
eventListJSON.append(", ");
eventListJSON.append(eventJSON);
}
}
eventListJSON.delete(0, 2);
return "[" + eventListJSON + "]";
}
public static String timeToJSON(Time time) {
if (time == null) {
return "null";
}
return "\"" + time + "\"";
}
}

View File

@@ -0,0 +1,44 @@
//Marc Beyer//
package com.vpr.server.json;
import java.sql.Date;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Validator {
public static String ValidateEventName(String name) throws IllegalArgumentException {
if (name.length() < 3) {
System.out.println("NAME TO SHORT");
throw new IllegalArgumentException("Der Name ist zu kurz");
}
Pattern pattern = Pattern.compile("[A-Za-z\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df0-9 =!?+*/$.:,;_<>()-]*");
Matcher matcher = pattern.matcher(name);
if(!matcher.matches()){
System.out.println("NAME HAS ILLEGALCHARS");
throw new IllegalArgumentException("Der Name enthält nicht erlaubte Zeichen");
}
return name;
}
public static Time ValidateEventTime(String time) throws IllegalArgumentException {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
long ms = simpleDateFormat.parse(time).getTime();
return new Time(ms);
} catch (Exception e) {
return null;
}
}
public static Date ValidateEventDate(String date) throws IllegalArgumentException {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return new Date(simpleDateFormat.parse(date).getTime());
} catch (Exception e) {
System.out.println("DATE FORMAT NOT CORRECT");
throw new IllegalArgumentException("Datumformat nicht korrekt");
}
}
}

View File

@@ -0,0 +1,75 @@
//Marc Beyer//
package com.vpr.server.repository;
import com.vpr.server.data.Event;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import javax.transaction.Transactional;
// This will be AUTO IMPLEMENTED by Spring into a Bean called eventRepository
// CRUD refers Create, Read, Update, Delete
public interface EventRepository extends CrudRepository<Event, Integer> {
@Query(
value = "SELECT e.id AS eid, e.name AS ename, e.start, e.end, e.priority , e.is_full_day, " +
"ue.date, " +
"u.id AS uid, u.forename, u.name AS uname " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"INNER JOIN user u " +
"ON ue.user_id = u.id " +
"WHERE u.id = ?1 " +
"OR e.is_private = 0",
nativeQuery = true
)
Object[] findAllVisibleByUserId(long id);
@Query(
value = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.user_id = ?1",
nativeQuery = true
)
Object[] findAllByUserId(long id);
@Query(
value = "SELECT ue.user_id as userId, ue.event_id as eventId, ue.date as date " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.event_id = ?1 " +
"AND ue.user_id = ?2 " +
"AND ue.date = ?3",
nativeQuery = true
)
UserEventInterface findUserEventByEventIdUserIdAndDate(long eventId, long userId, String date);
interface UserEventInterface{
long getEventId();
long getUserId();
long getDate();
}
@Modifying
@Transactional
@Query(
value = "DELETE ue FROM user_event ue WHERE ue.event_id = :eventId AND ue.user_id = :userId AND ue.date = :date",
nativeQuery = true
)
void deleteUserEventsById(long userId, long eventId, String date);
@Modifying
@Transactional
@Query(
value = "DELETE e FROM event e WHERE e.id = ?1",
nativeQuery = true
)
void deleteById(long id);
}

View File

@@ -0,0 +1,15 @@
//Marc Beyer//
package com.vpr.server.repository;
import com.vpr.server.data.UserEvent;
import org.springframework.data.repository.CrudRepository;
import java.sql.Date;
import java.util.List;
// This will be AUTO IMPLEMENTED by Spring into a Bean called eventListRepository
// CRUD refers Create, Read, Update, Delete
public interface UserEventRepository extends CrudRepository<UserEvent, Integer> {
List<UserEvent> findByUserIdAndDate(long userId, Date date);
}

View File

@@ -0,0 +1,26 @@
//Marc Beyer//
package com.vpr.server.repository;
import com.vpr.server.data.User;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Integer> {
@Query(value = "SELECT u.id, u.name, u.forename " +
"FROM user u",
nativeQuery = true)
Object[] findAllUsernames();
User findById(long id);
User findByLogin(String login);
User findByLoginAndPassword(String login, byte[] password);
void deleteById(long id);
User findByToken(String token);
}

View File

@@ -0,0 +1,29 @@
//Marc Beyer//
package com.vpr.server.security;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
public class Hasher {
public static byte[] HashPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Credit: https://www.baeldung.com/java-password-hashing
// Generate hash with PBKDF2
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return factory.generateSecret(spec).getEncoded();
}
public static byte[] GenerateSalt(){
// Credit: https://www.baeldung.com/java-password-hashing
// Create a salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
}

View File

@@ -0,0 +1,28 @@
//Marc Beyer//
package com.vpr.server.security;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
public class Token {
private static final Key KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
public static String Generate(String subject){
return Jwts.builder().setSubject(subject).signWith(KEY).compact();
}
public static boolean Verify(String jws, String subject){
try {
assert Jwts.parserBuilder().setSigningKey(KEY).build().parseClaimsJws(jws)
.getBody().getSubject().equals(subject);
return true;
} catch (JwtException e) {
return false;
}
}
}

View File

@@ -1,10 +1,10 @@
package com.mam.vpr;
package com.vpr.server;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class VprApplicationTests {
class ServerApplicationTests {
@Test
void contextLoads() {

View File

@@ -1,117 +0,0 @@
/*
* Copyright 2007-present the original author or 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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@@ -1,2 +0,0 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.3/apache-maven-3.8.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

310
vpr/mvnw vendored
View File

@@ -1,310 +0,0 @@
#!/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
#
# 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven 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
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
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 $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
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
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
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 "$@"

182
vpr/mvnw.cmd vendored
View File

@@ -1,182 +0,0 @@
@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 https://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 Maven 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 keystroke 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 by 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.5.6/maven-wrapper-0.5.6.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% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%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%

View File

@@ -1,50 +0,0 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mam</groupId>
<artifactId>vpr</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>vpr</name>
<description>vpr project with Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,15 +0,0 @@
package com.mam.vpr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@SpringBootApplication
public class VprApplication {
public static void main(String[] args) {
SpringApplication.run(VprApplication.class, args);
}
}

View File

@@ -1,74 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Time;
// @Entity creates a table out of this class with Hibernate
@Entity
public class Event {
// Generate the primary key
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer priority;
private boolean isFullDay;
private java.sql.Time start;
private java.sql.Time end;
/*********************
* Getter and Setter *
*********************/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public boolean isFullDay() {
return isFullDay;
}
public void setFullDay(boolean fullDay) {
isFullDay = fullDay;
}
public Time getStart() {
return start;
}
public void setStart(Time start) {
this.start = start;
}
public Time getEnd() {
return end;
}
public void setEnd(Time end) {
this.end = end;
}
}

View File

@@ -1,61 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import javax.persistence.*;
import java.sql.Date;
// @Entity creates a table out of this class with Hibernate
// @Table defines the table-name
@Entity
@Table(name="event_list")
public class EventList {
// Generate the primary key
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// Generate the foreign key
//@ManyToOne
//@JoinColumn(name = "user_id", referencedColumnName = "id")
private Integer userId;
//@ManyToOne
//@JoinColumn(name = "event_id", referencedColumnName = "id")
private Integer eventId;
private Date date;
/*********************
* Getter and Setter *
*********************/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

View File

@@ -1,11 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import org.springframework.data.repository.CrudRepository;
import com.mam.vpr.accessingdatamysql.EventList;
// This will be AUTO IMPLEMENTED by Spring into a Bean called eventListRepository
// CRUD refers Create, Read, Update, Delete
public interface EventListRepository extends CrudRepository<EventList, Integer> {
}

View File

@@ -1,12 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import org.springframework.data.repository.CrudRepository;
import com.mam.vpr.accessingdatamysql.Event;
// This will be AUTO IMPLEMENTED by Spring into a Bean called eventRepository
// CRUD refers Create, Read, Update, Delete
public interface EventRepository extends CrudRepository<Event, Integer> {
}

View File

@@ -1,69 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller // This means that this class is a Controller
@RequestMapping(path="/vpr") // This means URL's start with /demo (after Application path)
public class MainController {
// This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
@Autowired
private UserRepository userRepository;
@Autowired
private EventRepository eventRepository;
@Autowired
private EventListRepository eventListRepository;
// POST-request at /add with request parameter
// @ResponseBody means the returned String is the response, not a view name
@PostMapping(path="/add-user")
public @ResponseBody String addNewUser (
@RequestParam String name,
@RequestParam String forename,
@RequestParam String password,
@RequestParam String isAdmin
) {
User user = new User();
// TODO set correct token and password
user.setName(name);
user.setForename(forename);
user.setPassword(password);
user.setToken("test");
user.setAdmin(isAdmin.equals("1"));
userRepository.save(user);
return "Saved";
}
// GET-request at /all-users
// returns JSON-data
@GetMapping(path="/all-users")
public @ResponseBody Iterable<User> getAllUsers() {
return userRepository.findAll();
}
// GET-request at /all-events
// returns JSON-data
@GetMapping(path="/all-events")
public @ResponseBody Iterable<Event> getAllEvents() {
return eventRepository.findAll();
}
// GET-request at /all-event-lists
// returns JSON-data
@GetMapping(path="/all-event-lists")
public @ResponseBody Iterable<EventList> getAllEventLists() {
return eventListRepository.findAll();
}
}

View File

@@ -1,74 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
// @Entity creates a table out of this class with Hibernate
@Entity
public class User {
// Generate the primary key
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
private String forename;
private String password;
private String token;
private boolean isAdmin;
/*********************
* Getter and Setter *
*********************/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
}

View File

@@ -1,12 +0,0 @@
package com.mam.vpr.accessingdatamysql;
import org.springframework.data.repository.CrudRepository;
import com.mam.vpr.accessingdatamysql.User;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Integer> {
}