This commit is contained in:
Peter Rossa
2023-05-10 12:23:25 +02:00
commit af29efa0f3
131 changed files with 16889 additions and 0 deletions

4
.angulardoc.json Normal file
View File

@@ -0,0 +1,4 @@
{
"repoId": "8032f063-e179-4ac5-ab88-ac0b73c6d61d",
"lastSync": 0
}

14
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,14 @@
{
"configurations": [
{
"type": "java",
"name": "Spring Boot-ApiApplication<api>",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.rossa.api.ApiApplication",
"projectName": "api",
"args": "",
"envFile": "${workspaceFolder}/.env"
}
]
}

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"java.configuration.updateBuildConfiguration": "interactive"
}

33
api/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

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

Binary file not shown.

View File

@@ -0,0 +1,18 @@
# 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.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar

4
api/.postman/api Normal file
View File

@@ -0,0 +1,4 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
apis[] = {"apiId":"d6f5c611-f7b1-409a-803b-22b44637be76"}
configVersion = 1.0.0
type = api

View File

@@ -0,0 +1,18 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
configVersion = 1.0.0
type = apiEntityData
[config]
id = d6f5c611-f7b1-409a-803b-22b44637be76
[config.relations]
[config.relations.collections]
rootDirectory = postman/collections
[config.relations.collections.metaData]
[config.relations.apiDefinition]
rootDirectory = postman/schemas
[config.relations.apiDefinition.metaData]

316
api/mvnw vendored Normal file
View File

@@ -0,0 +1,316 @@
#!/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 /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
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="`\\unset -f command; \\command -v 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/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.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" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$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 \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

188
api/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,188 @@
@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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq 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%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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%
cmd /C exit /B %ERROR_CODE%

100
api/pom.xml Normal file
View File

@@ -0,0 +1,100 @@
<?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>
<groupId>com.rossa</groupId>
<artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>api</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- <version>2.1.0.RELEASE</version> -->
<version>2.7.2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- <dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
<build>
<finalName>api</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,39 @@
package com.rossa.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
// @SpringBootApplication(scanBasePackages = "com.rossa.api.controller")
public class ApiApplication extends SpringBootServletInitializer {
// @Override
// protected SpringApplicationBuilder configure(SpringApplicationBuilder
// builder) {
// return builder.sources(ApiApplication.class);
// }
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
// @Bean
// WebMvcConfigurer corsConfigurer() {
// return new WebMvcConfigurer() {
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**").allowedOrigins("http://localhost:4200",
// "http://192.168.178.21:8180/").maxAge(3000);
// // registry.addMapping("/**")
// // .allowedHeaders("*")
// // .allowedOrigins("*")
// // .maxAge(3000);
// }
// };
// }
}

View File

@@ -0,0 +1,13 @@
package com.rossa.api;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ApiApplication.class);
}
}

View File

@@ -0,0 +1,31 @@
package com.rossa.api.config;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest req,
HttpServletResponse resp,
AccessDeniedException ex) throws IOException, ServletException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
System.out.println("User '" + auth.getName()
+ "' attempted to access the protected URL: "
+ req.getRequestURI());
resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Forbidden");
} else {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
}

View File

@@ -0,0 +1,23 @@
package com.rossa.api.config;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = -772511716561421072L;
@Override
public void commence(HttpServletRequest arg0, HttpServletResponse arg1, AuthenticationException arg2)
throws IOException, ServletException {
arg1.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}

View File

@@ -0,0 +1,143 @@
package com.rossa.api.config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rossa.api.models.AuthUserInfo;
import com.rossa.api.security.UserAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.ExpiredJwtException;
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
private final String _authorizationKey = "authorization";
private final String _bearerTokenPrefix = "bearer ";
@Autowired
private UserAuthenticationService userAuthService;
@Autowired
private JwtTokenUtils<AuthUserInfo> jwtTokenUtils;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
System.out.println("--------------------------------");
System.out.println(request.getRequestURL().toString());
AuthUserInfo tokenUserInfo = null;
String jwtToken = getJwtTokenFromHeader(request);
System.out.println("Token: " + jwtToken);
if (StringUtils.hasText(jwtToken)) {
tokenUserInfo = extractJwtUserInfoFromToken(jwtToken);
if (tokenUserInfo != null) {
SecurityContextHolder.getContext().setAuthentication(null);
if (StringUtils.hasText(tokenUserInfo.getUserId())) {
AuthUserInfo userDetails = this.userAuthService.getUserById(tokenUserInfo.getUserId());
if (userDetails != null) {
if (jwtTokenUtils.validateToken(jwtToken, userDetails)) {
List<GrantedAuthority> allAuths = convertUserRolesToGrantedAuthorities(
userDetails.getUserRoles());
if (allAuths != null && allAuths.size() > 0) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, allAuths);
usernamePasswordAuthenticationToken
.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext()
.setAuthentication(usernamePasswordAuthenticationToken);
} else {
System.out.println("User has no roles associated with.");
SecurityContextHolder.getContext().setAuthentication(null);
}
} else {
System.out.println("User credential cannot be validated.");
SecurityContextHolder.getContext().setAuthentication(null);
}
} else {
System.out.println("No valid user credential available.");
SecurityContextHolder.getContext().setAuthentication(null);
}
} else {
System.out.println("Invalid user info detected. Authentication failed.");
SecurityContextHolder.getContext().setAuthentication(null);
}
} else {
System.out.println("Unable to get JWT Token");
SecurityContextHolder.getContext().setAuthentication(null);
}
} else {
System.out.println("JWT Token does not begin with Bearer String");
SecurityContextHolder.getContext().setAuthentication(null);
}
System.out.println("Try normal filtering");
chain.doFilter(request, response);
System.out.println("--------------------------------");
}
private String getJwtTokenFromHeader(HttpServletRequest request) {
String retVal = "";
if (request != null) {
final String requestTokenHeader = request.getHeader(_authorizationKey);
System.out.println("Found Auth Key: [" + requestTokenHeader + "]");
if (StringUtils.hasText(requestTokenHeader) && requestTokenHeader.startsWith(_bearerTokenPrefix)) {
retVal = requestTokenHeader.substring(_bearerTokenPrefix.length());
}
}
return retVal;
}
private AuthUserInfo extractJwtUserInfoFromToken(String tokenStrVal) {
AuthUserInfo retVal = null;
if (StringUtils.hasText(tokenStrVal)) {
try {
retVal = jwtTokenUtils.getUserInfoFromToken(tokenStrVal);
} catch (IllegalArgumentException ex) {
System.out.println("Unable to get JWT Token via token string decryption.");
retVal = null;
} catch (ExpiredJwtException ex) {
System.out.println("JWT Token has expired");
retVal = null;
}
}
return retVal;
}
private List<GrantedAuthority> convertUserRolesToGrantedAuthorities(List<String> allUserRoles) {
List<GrantedAuthority> retVal = new ArrayList<GrantedAuthority>();
if (allUserRoles != null && allUserRoles.size() > 0) {
for (String role : allUserRoles) {
if (StringUtils.hasText(role)) {
retVal.add(new SimpleGrantedAuthority(role));
}
}
}
return retVal;
}
}

View File

@@ -0,0 +1,190 @@
package com.rossa.api.config;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import com.rossa.api.models.AuthUserInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JwtTokenUtils<T extends Object> implements Serializable {
private static final long serialVersionUID = -2550185165626007488L;
public static final long JWT_TOKEN_VALIDITY = 15 * 60; // 15 minutes
@Value("${jwt.secret}")
private String secret;
public AuthUserInfo getUserInfoFromToken(String token) {
AuthUserInfo retVal = null;
String userInfoStr = getUserInfoStringFromToken(token);
if (!StringUtils.isEmpty(userInfoStr)) {
ObjectMapper mapper = new ObjectMapper();
try {
retVal = mapper.readValue(userInfoStr, AuthUserInfo.class);
} catch (Exception ex) {
System.out.println("Exception occurred. " + ex.getMessage());
ex.printStackTrace();
retVal = null;
}
}
return retVal;
}
public String getUserInfoStringFromToken(String token) {
String retVal = null;
if (!StringUtils.isEmpty(token)) {
retVal = getClaimFromToken(token, Claims::getSubject);
}
return retVal;
}
public Date getExpirationDateFromToken(String token) {
Date retVal = null;
if (!StringUtils.isEmpty(token)) {
retVal = getClaimFromToken(token, Claims::getExpiration);
}
return retVal;
}
public <K extends Object> K getClaimFromToken(String token,
Function<Claims, K> claimsResolver) {
if (!StringUtils.isEmpty(token)) {
Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
} else {
return null;
}
}
private Claims getAllClaimsFromToken(String token) {
if (!StringUtils.isEmpty(token)) {
if (!StringUtils.isEmpty(secret)) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
} else {
System.out.println("Secret key is null or empty, unable to decode claims from token.");
return null;
}
} else {
return null;
}
}
private Boolean isTokenExpired(String token) {
if (!StringUtils.isEmpty(token)) {
Date expiration = getExpirationDateFromToken(token);
if (expiration == null) {
System.out.println("Invalid expiration data. Invalid token detected.");
return false;
}
return expiration.before(new Date());
}
return false;
}
public String generateToken(T userInfo, Map<String, Object> claims, Date startTime, Date expirationTime) {
String userInfoStr = "";
String retVal = null;
if (claims == null) {
System.out.println("Claims object is null or empty, cannot createsecurity token.");
return retVal;
}
if (userInfo == null) {
System.out.println("userInfo object is null or empty, cannot createsecurity token.");
return retVal;
}
try {
ObjectMapper mapper = new ObjectMapper();
userInfoStr = mapper.writeValueAsString(userInfo);
retVal = doGenerateToken(claims, userInfoStr, startTime, expirationTime);
} catch (Exception ex) {
System.out.println("Exception occurred. " + ex.getMessage());
ex.printStackTrace();
retVal = null;
}
return retVal;
}
public String generateToken(T userDetails, Date startTime, Date expirationTime) {
Map<String, Object> emptyClaims = new HashMap<String, Object>();
return generateToken(userDetails, emptyClaims, startTime, expirationTime);
}
private String doGenerateToken(Map<String, Object> claims, String subject, Date startTime, Date expirationTime) {
String retVal = null;
if (StringUtils.isEmpty(secret)) {
System.out.println("Invalid secret key for token encryption.");
return retVal;
}
if (claims == null) {
System.out.println("Invalid token claims object.");
return retVal;
}
if (StringUtils.isEmpty(subject)) {
System.out.println("Invalid subject value for the security token.");
return retVal;
}
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(startTime)
.setExpiration(expirationTime)
.signWith(SignatureAlgorithm.HS512, secret).compact();
}
public Boolean validateToken(String token, AuthUserInfo userDetails) {
if (!StringUtils.isEmpty(token)) {
AuthUserInfo userInfo = getUserInfoFromToken(token);
if (userInfo != null) {
if (userDetails != null) {
String actualUserId = userInfo.getUserId();
if (!StringUtils.isEmpty(actualUserId) && actualUserId.equalsIgnoreCase(userDetails.getUserId())) {
if (userDetails.isUserActive()) {
return !isTokenExpired(token);
} else {
System.out.println(String.format("User with id [%s] is not active. Invalid token.",
userInfo.getUserId()));
return false;
}
} else {
System.out.println("User in the token has a different user id than expected. Invalid token.");
return false;
}
} else {
System.out.println("Expected user details object is invalid. Unable to verify token validity.");
return false;
}
} else {
System.out.println("Decrypted user details object is invalid. Invalid token.");
return false;
}
} else {
System.out.println("Invalid token string detected. Invalid token.");
return false;
}
}
}

View File

@@ -0,0 +1,60 @@
package com.rossa.api.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebAppSecurityConfig {
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
System.out.println("Security filter chain initialization...");
http.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/assets/**", "/public/**", "/authenticate", "/app/**").permitAll()
.anyRequest().authenticated().and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
String[] allowDomains = new String[2];
allowDomains[0] = "http://localhost:4200";
allowDomains[1] = "http://192.168.178.21:8180/";
System.out.println("CORS configuration....");
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins(allowDomains);
}
};
}
}

View File

@@ -0,0 +1,39 @@
INSERT INTO meters (name) VALUES ('1LOG');
INSERT INTO meters (name) VALUES ('1HEM');
INSERT INTO meters (name) VALUES ('WASSER');
INSERT INTO meters (name) VALUES ('ABWASSER');
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-12-31 00:00:00', 11546.00, 1);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-09-30 00:00:00', 10504.00, 1);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-08-30 00:00:00', 10193.00, 1);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-07-01 00:00:00', 9679.00, 1);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-12-31 00:00:00', 7787.00, 1);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-09-25 00:00:00', 7322.00, 1);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-12-31 00:00:00', 12398.00, 2);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2022-05-31 00:00:00', 10799.00, 2);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-12-31 00:00:00', 8758.00, 2);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-09-01 00:00:00', 7355.00, 2);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('ENERGY', '2021-06-01 00:00:00', 7163.00, 2);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-01-01 00:00:00', 288.00, 3);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-12-31 00:00:00', 464.00, 3);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-01-01 00:00:00', 153.00, 3);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-12-31 00:00:00', 288.00, 3);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-03-03 00:00:00', 153.00, 3);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-12-31 00:00:00', 288.00, 3);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-01-01 00:00:00', 116.00, 4);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2022-12-31 00:00:00', 189.00, 4);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-01-01 00:00:00', 81.00, 4);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2021-12-31 00:00:00', 116.00, 4);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-03-06 00:00:00', 0.00, 4);
INSERT INTO meter_data (type, date, amount, meter_id) VALUES ('WATER', '2020-12-31 00:00:00', 81.00, 4);
/***************
***************/

View File

@@ -0,0 +1,15 @@
CREATE TABLE meters (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE meter_data (
id INT NOT NULL AUTO_INCREMENT,
type ENUM('ENERGY', 'WATER') NOT NULL,
date DATETIME NOT NULL,
amount FLOAT NOT NULL,
meter_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (meter_id) REFERENCES meter(id)
);

View File

@@ -0,0 +1,16 @@
package com.rossa.api.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class AppContoller {
@RequestMapping(value = "/public/index", method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView retVal = new ModelAndView();
retVal.setViewName("indexPage");
return retVal;
}
}

View File

@@ -0,0 +1,19 @@
package com.rossa.api.controllers;
import com.rossa.api.models.AuthUserInfo;
import org.springframework.security.core.context.SecurityContextHolder;
public class ControllerBase {
protected AuthUserInfo getCurrentUser() {
AuthUserInfo retVal = null;
Object principal = SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
if (principal != null && principal instanceof AuthUserInfo) {
retVal = (AuthUserInfo) principal;
}
return retVal;
}
}

View File

@@ -0,0 +1,14 @@
package com.rossa.api.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String index() {
return "Greetings from Spring Boot!";
}
}

View File

@@ -0,0 +1,74 @@
package com.rossa.api.controllers;
import com.rossa.api.models.AuthUserInfo;
import com.rossa.api.models.LoginRequest;
import com.rossa.api.models.OpResponse;
import com.rossa.api.security.UserAuthenticationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController extends ControllerBase {
private UserAuthenticationService _authService;
public LoginController(UserAuthenticationService authService) {
_authService = authService;
}
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AuthUserInfo> login(@RequestBody LoginRequest loginReq) {
System.out.println("User Name: " + loginReq.getUserName());
System.out.println("User Pass: " + loginReq.getUserPass());
if (StringUtils.hasText(loginReq.getUserName()) && StringUtils.hasText(loginReq.getUserPass())) {
AuthUserInfo userFound = _authService.authenticateUser(loginReq.getUserName(), loginReq.getUserPass());
if (userFound != null) {
return ResponseEntity.ok(userFound);
} else {
return ResponseEntity.status(403).body((AuthUserInfo) null);
}
} else {
return ResponseEntity.status(403).body((AuthUserInfo) null);
}
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/signOut", method = RequestMethod.POST)
public ResponseEntity<OpResponse> signOut() {
ResponseEntity<OpResponse> retVal = null;
OpResponse resp = new OpResponse();
AuthUserInfo currUser = getCurrentUser();
if (currUser != null) {
String userId = currUser.getUserId();
boolean signoutSuccess = _authService.userSignOut(userId);
if (signoutSuccess) {
resp.setSuccessful(true);
resp.setStatus("Log out successful");
resp.setDetailMessage("You have successfully log out from this site.");
retVal = new ResponseEntity<OpResponse>(resp, HttpStatus.OK);
} else {
resp.setSuccessful(false);
resp.setStatus("Operation Failed");
resp.setDetailMessage("Unable to sin out user. Unknown error.");
retVal = new ResponseEntity<OpResponse>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
}
} else {
resp.setSuccessful(false);
resp.setStatus("Operation Failed");
resp.setDetailMessage("You cannot log out if you are not log in first.");
retVal = new ResponseEntity<OpResponse>(resp, HttpStatus.UNAUTHORIZED);
}
System.out.println("sign out called!");
return retVal;
}
}

View File

@@ -0,0 +1,44 @@
package com.rossa.api.controllers;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import com.rossa.api.exception.ResourceNotFoundException;
import com.rossa.api.models.Meter;
import com.rossa.api.repository.MeterRepository;
@RestController
@PreAuthorize("isAuthenticated()")
public class MeterController {
@Autowired
private MeterRepository meterRepository;
@RequestMapping(value = "/meters", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Meter> getAllEmployees() {
return meterRepository.findAll();
}
@RequestMapping(value = "/meters/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Meter> getEmployeeById(@PathVariable(value = "id") long meterId)
throws ResourceNotFoundException {
Meter meter = meterRepository.findById(meterId)
.orElseThrow(() -> new ResourceNotFoundException("Meter not found for this id :: " + meterId));
return ResponseEntity.ok().body(meter);
}
@RequestMapping(value = "/meters", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Meter createMeter(@Valid @RequestBody Meter meter) {
return meterRepository.save(meter);
}
}

View File

@@ -0,0 +1,107 @@
package com.rossa.api.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import com.rossa.api.exception.ResourceNotFoundException;
import com.rossa.api.models.MeterData;
import com.rossa.api.repository.MeterDataRepository;
@RestController
@PreAuthorize("isAuthenticated()")
// @CrossOrigin(origins = "http://localhost:4200, http://192.168.178.21/")
public class MeterDataController {
@Autowired
private MeterDataRepository meterDataRepository;
@RequestMapping(value = "/meter-data", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<com.rossa.api.models.MeterData> getAllMeterData() {
return meterDataRepository.findAll();
}
@RequestMapping(value = "/meter-data/meter/{meterId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<MeterData> getAllMeterDataByMeterId(@PathVariable(value = "meterId") long meterId) {
return meterDataRepository.findByMeterId(meterId);
}
@RequestMapping(value = "/meter-data/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MeterData> getMeterDataById(@PathVariable(value = "id") long meterDataId)
throws ResourceNotFoundException {
MeterData meterData = meterDataRepository.findById(meterDataId)
.orElseThrow(() -> new ResourceNotFoundException("Meter not found for this id :: " + meterDataId));
return ResponseEntity.ok().body(meterData);
}
@RequestMapping(value = "/meter-data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public MeterData createMeterData(@Valid @RequestBody MeterData meterData) {
return meterDataRepository.save(meterData);
}
// @PutMapping("/meter-data/{id}")
// public ResponseEntity < MeterData > updateMeterData(@PathVariable(value =
// "id") Long meterDataId,
// @Valid @RequestBody MeterData meterDataDetails) throws
// ResourceNotFoundException {
// MeterData meterData = meterDataRepository.findById(meterDataId)
// .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this
// id :: " + meterDataId));
// meterData.setAmount(meterDataDetails.getAmount());
// meterData.setDate(meterDataDetails.getDate());
// meterData.setMeter(meterDataDetails.getMeter());
// meterData.setType(meterDataDetails.getType());
// final MeterData updatedMeterData = meterDataRepository.save(meterData);
// return ResponseEntity.ok(updatedMeterData);
// }
@RequestMapping(value = "/meter-data/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MeterData> updateMeterData(@PathVariable(value = "id") Long meterDataId,
@Valid @RequestBody MeterData meterDataDetails) throws ResourceNotFoundException {
MeterData meterData = meterDataRepository.findById(meterDataId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + meterDataId));
if (meterDataDetails.getType() != null) {
meterData.setType(meterDataDetails.getType());
}
if (meterDataDetails.getDate() != null) {
meterData.setDate(meterDataDetails.getDate());
}
if (meterDataDetails.getAmount() != null) {
meterData.setAmount(meterDataDetails.getAmount());
}
if (meterDataDetails.getMeter() != null) {
meterData.setMeter(meterDataDetails.getMeter());
}
final MeterData updatedMeterData = meterDataRepository.save(meterData);
return ResponseEntity.ok(updatedMeterData);
}
@RequestMapping(value = "/meter-data/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Boolean> deleteMeterData(@PathVariable(value = "id") Long meterDataId)
throws ResourceNotFoundException {
MeterData meterData = meterDataRepository.findById(meterDataId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + meterDataId));
meterDataRepository.delete(meterData);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}

View File

@@ -0,0 +1,62 @@
package com.rossa.api.controllers;
import java.util.ArrayList;
import java.util.List;
import com.rossa.api.models.TitleModel;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SecureApiController {
public SecureApiController() {
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/secure/allGameTitles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<TitleModel>> allGameTitles() {
List<TitleModel> resp = new ArrayList<TitleModel>();
TitleModel titleToAdd = new TitleModel();
titleToAdd.setGameTitle("Cyberpunk 2077");
titleToAdd.setPublisher("Warnder Bros");
titleToAdd.setDevStudioName("CD Projekt Red");
titleToAdd.setPublishingYear((short) 2019);
titleToAdd.setRetailPrice(69.95f);
resp.add(titleToAdd);
titleToAdd = new TitleModel();
titleToAdd.setGameTitle("Final Fantasy XV");
titleToAdd.setPublisher("Square Enix");
titleToAdd.setDevStudioName("Square Enix");
titleToAdd.setPublishingYear((short) 2016);
titleToAdd.setRetailPrice(59.95f);
resp.add(titleToAdd);
titleToAdd = new TitleModel();
titleToAdd.setGameTitle("Fallout 4");
titleToAdd.setPublisher("Bethesda Softworks");
titleToAdd.setDevStudioName("Bethesda Game Studios");
titleToAdd.setPublishingYear((short) 2015);
titleToAdd.setRetailPrice(59.95f);
resp.add(titleToAdd);
titleToAdd = new TitleModel();
titleToAdd.setGameTitle("Dragon Quest XI");
titleToAdd.setPublisher("Square Enix");
titleToAdd.setDevStudioName("Square Enix");
titleToAdd.setPublishingYear((short) 2017);
titleToAdd.setRetailPrice(59.95f);
resp.add(titleToAdd);
return ResponseEntity.ok(resp);
}
}

View File

@@ -0,0 +1,14 @@
package com.rossa.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception{
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message){
super(message);
}
}

View File

@@ -0,0 +1,36 @@
package com.rossa.api.models;
import java.util.Date;
public class AuthToken
extends AuthUserInfo {
private Date sessionStartTime;
private Date sessionEndTime;
private String tokenValue;
public Date getSessionStartTime() {
return sessionStartTime;
}
public void setSessionStartTime(Date sessionStartTime) {
this.sessionStartTime = sessionStartTime;
}
public Date getSessionEndTime() {
return sessionEndTime;
}
public void setSessionEndTime(Date sessionEndTime) {
this.sessionEndTime = sessionEndTime;
}
public String getTokenValue() {
return tokenValue;
}
public void setTokenValue(String tokenValue) {
this.tokenValue = tokenValue;
}
}

View File

@@ -0,0 +1,75 @@
package com.rossa.api.models;
import java.util.List;
public class AuthUserInfo {
private String userId;
private String userName;
private String userPassword;
private String userNickName;
private boolean userActive;
private String userEmail;
private List<String> userRoles;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserNickName() {
return userNickName;
}
public void setUserNickName(String userNickName) {
this.userNickName = userNickName;
}
public boolean isUserActive() {
return userActive;
}
public void setUserActive(boolean userActive) {
this.userActive = userActive;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public List<String> getUserRoles() {
return userRoles;
}
public void setUserRoles(List<String> userRoles) {
this.userRoles = userRoles;
}
}

View File

@@ -0,0 +1,23 @@
package com.rossa.api.models;
public class LoginRequest {
private String userName;
private String userPass;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
}

View File

@@ -0,0 +1,40 @@
package com.rossa.api.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "meters")
public class Meter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name", nullable = false)
private String name;
public Meter() {
}
// getters and setters
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;
}
}

View File

@@ -0,0 +1,87 @@
package com.rossa.api.models;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "meterData")
public class MeterData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private UsageType type;
@Column(name = "date", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date date;
@Column(name = "amount", nullable = false)
private Float amount;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "meterId", nullable = false)
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
private Meter meter;
public MeterData() {
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public UsageType getType() {
return type;
}
public void setType(UsageType type) {
this.type = type;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
public Meter getMeter() {
return meter;
}
public void setMeter(Meter meter) {
this.meter = meter;
}
}

View File

@@ -0,0 +1,33 @@
package com.rossa.api.models;
public class OpResponse {
private boolean successful;
private String status;
private String detailMessage;
public boolean isSuccessful() {
return successful;
}
public void setSuccessful(boolean successful) {
this.successful = successful;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDetailMessage() {
return detailMessage;
}
public void setDetailMessage(String detailMessage) {
this.detailMessage = detailMessage;
}
}

View File

@@ -0,0 +1,53 @@
package com.rossa.api.models;
public class TitleModel {
private String gameTitle;
private String publisher;
private String devStudioName;
private short publishingYear;
private float retailPrice;
public String getGameTitle() {
return gameTitle;
}
public void setGameTitle(String titleValue) {
this.gameTitle = titleValue;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDevStudioName() {
return devStudioName;
}
public void setDevStudioName(String devStudioName) {
this.devStudioName = devStudioName;
}
public short getPublishingYear() {
return publishingYear;
}
public void setPublishingYear(short publishingYear) {
this.publishingYear = publishingYear;
}
public float getRetailPrice() {
return retailPrice;
}
public void setRetailPrice(float retailPrice) {
this.retailPrice = retailPrice;
}
}

View File

@@ -0,0 +1,25 @@
package com.rossa.api.models;
public enum UsageType {
ENERGY("ENERGY"),
WATER("WATER");
private final String value;
UsageType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static UsageType fromValue(String value) {
for (UsageType type : values()) {
if (type.value.equals(value)) {
return type;
}
}
throw new IllegalArgumentException("Invalid UsageType value: " + value);
}
}

View File

@@ -0,0 +1,11 @@
package com.rossa.api.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.rossa.api.models.MeterData;
public interface MeterDataRepository extends JpaRepository<MeterData, Long> {
List<MeterData> findByMeterId(long meterId);
}

View File

@@ -0,0 +1,9 @@
package com.rossa.api.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.rossa.api.models.Meter;
public interface MeterRepository extends JpaRepository<Meter, Long> {
}

View File

@@ -0,0 +1,9 @@
package com.rossa.api.repository;
import com.rossa.api.models.AuthUserInfo;
public interface UserRepository {
AuthUserInfo getUser(String userName, boolean userActive);
AuthUserInfo getUserById(String userId);
}

View File

@@ -0,0 +1,82 @@
package com.rossa.api.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.rossa.api.models.AuthUserInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class UserRepositoryImpl implements UserRepository {
private static List<AuthUserInfo> mockUsersList;
static {
mockUsersList = new ArrayList<AuthUserInfo>();
AuthUserInfo userToAdd = new AuthUserInfo();
userToAdd.setUserActive(true);
userToAdd.setUserId("00000001");
userToAdd.setUserEmail("testuser1@teststore.org");
userToAdd.setUserName("testuser1");
userToAdd.setUserNickName("Test User1");
userToAdd.setUserPassword("123test321");
List<String> adminRoles = new ArrayList<String>();
adminRoles.add("ROLE_SITE_ADMIN");
adminRoles.add("ROLE_SITE_SUPERUSER");
adminRoles.add("ROLE_SITE_USER");
userToAdd.setUserRoles(adminRoles);
mockUsersList.add(userToAdd);
userToAdd = new AuthUserInfo();
userToAdd.setUserActive(true);
userToAdd.setUserId("00000001");
userToAdd.setUserEmail("testuser1@teststore.org");
userToAdd.setUserName("testuser1");
userToAdd.setUserNickName("Test User1");
userToAdd.setUserPassword("123test321");
List<String> userRoles = new ArrayList<String>();
userRoles.add("ROLE_SITE_USER");
userToAdd.setUserRoles(userRoles);
mockUsersList.add(userToAdd);
}
@Override
public AuthUserInfo getUser(String userName, boolean userActive) {
AuthUserInfo retVal = null;
if (mockUsersList != null) {
Optional<AuthUserInfo> foundUser = mockUsersList.stream().filter(x -> {
String uname = x.getUserName();
return StringUtils.hasText(uname) && uname.equals(userName) && x.isUserActive() == userActive;
}).findFirst();
if (foundUser.isPresent()) {
retVal = foundUser.get();
}
}
return retVal;
}
@Override
public AuthUserInfo getUserById(String userId) {
AuthUserInfo retVal = null;
if (mockUsersList != null) {
Optional<AuthUserInfo> foundUser = mockUsersList.stream().filter(x -> {
String uid = x.getUserId();
return StringUtils.hasText(uid) && uid.equals(userId);
}).findFirst();
if (foundUser.isPresent()) {
retVal = foundUser.get();
}
}
return retVal;
}
}

View File

@@ -0,0 +1,12 @@
package com.rossa.api.security;
import com.rossa.api.models.AuthToken;
import com.rossa.api.models.AuthUserInfo;
public interface UserAuthenticationService {
AuthToken authenticateUser(String userName, String password);
AuthUserInfo getUserById(String userId);
boolean userSignOut(String userId);
}

View File

@@ -0,0 +1,86 @@
package com.rossa.api.security;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
import com.rossa.api.config.JwtTokenUtils;
import com.rossa.api.models.AuthToken;
import com.rossa.api.models.AuthUserInfo;
import com.rossa.api.repository.UserRepository;
@Service
public class UserAuthenticationServiceImpl
implements UserAuthenticationService {
public static final long JWT_TOKEN_VALIDITY = 15 * 60; // 15 minutes
private UserRepository userRepo;
private JwtTokenUtils<AuthUserInfo> jwtTknUtils;
public UserAuthenticationServiceImpl(UserRepository userRepo,
JwtTokenUtils<AuthUserInfo> jwtTknUtils) {
this.userRepo = userRepo;
this.jwtTknUtils = jwtTknUtils;
}
@Override
public AuthToken authenticateUser(String userName, String password) {
AuthToken retVal = null;
if (!StringUtils.hasText(userName)) {
throw new IllegalArgumentException("User name cannot be null or empty.");
}
if (!StringUtils.hasText(password)) {
throw new IllegalArgumentException("User password cannot be null or empty.");
}
AuthUserInfo foundUser = userRepo.getUser(userName, true);
if (foundUser != null) {
String userPass = foundUser.getUserPassword();
if (StringUtils.hasText(userPass) && userPass.equals(password)) {
long currTimeMillisec = System.currentTimeMillis();
Date dateNow = new Date(currTimeMillisec);
Date dateExpires = new Date(currTimeMillisec + JWT_TOKEN_VALIDITY * 1000);
retVal = new AuthToken();
retVal.setUserId(foundUser.getUserId());
retVal.setUserName(foundUser.getUserName());
retVal.setUserNickName(foundUser.getUserNickName());
retVal.setUserEmail(foundUser.getUserEmail());
retVal.setUserActive(foundUser.isUserActive());
retVal.setUserPassword(null);
retVal.setUserRoles(foundUser.getUserRoles());
String jwtTknVal = this.jwtTknUtils.generateToken(foundUser, dateNow, dateExpires);
retVal.setSessionStartTime(dateNow);
retVal.setSessionEndTime(dateExpires);
retVal.setTokenValue(jwtTknVal);
} else {
System.out.println("Unable to validate user credential. Authentication failed.");
retVal = null;
}
} else {
System.out.println("User not found. Authentication failed.");
retVal = null;
}
return retVal;
}
@Override
public AuthUserInfo getUserById(String userId) {
if (!StringUtils.hasText(userId)) {
throw new IllegalArgumentException("User id cannot be null or empty.");
}
AuthUserInfo retVal = userRepo.getUserById(userId);
return retVal;
}
@Override
public boolean userSignOut(String userId) {
// dud method.
return true;
}
}

View File

@@ -0,0 +1,34 @@
# # Database
# db.driver= com.mysql.jdbc.Driver
# db.url= jdbc:mysql://192.168.178.21:3306/rossa_tech_testing
# db.username=db_pezi
# db.password=Pe23Zi0484!_db
# # Hibernate
# hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
# hibernate.show_sql=true
# hibernate.hbm2ddl.auto=update
# entitymanager.packagesToScan=Model
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
jwt.secret=aquickfoxjumpsoverthelazydog
# Database
spring.datasource.url= jdbc:mysql://192.168.178.21:3306/rossa_tech_testing?useSSL=false
spring.datasource.username= db_pezi
spring.datasource.password= Pe23Zi0484!_db
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
#spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
#spring.jpa.hibernate.ddl-auto= update
# spring.security.user.name=pezi
# spring.security.user.password=Password123!
security.basic.enabled=false

View File

@@ -0,0 +1,26 @@
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Login</title>
<link rel="stylesheet" th:href="@{/assets/bootstrap/css/bootstrap.min.css}"/>
<link rel="stylesheet" th:href="@{/assets/bootstrap/css/bootstrap-theme.min.css}"/>
<link rel="stylesheet" th:href="@{/assets/css/index.css}"/>
<link rel="icon" type="image/png" th:href="@{/assets/images/favicon.png}">
</head>
<body>
<div class="container" ng-app="sampleApp">
<ui-view></ui-view>
</div>
<script type="text/javascript" th:src="@{/assets/jquery/js/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/bootstrap/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular-resource.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular-route.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/angularjs/1.7.5/angular-ui-router.min.js}"></script>
<script type="module" th:src="@{/assets/app/js/app.js}"></script>
</body>
</html>

30
rossa-tech webpage.txt Normal file
View File

@@ -0,0 +1,30 @@
- login (simple)
? - https://www.bezkoder.com/angular-12-jwt-auth/
? - https://martinelli.ch/angular-15-spring-boot-3-and-jwt/
- https://www.baeldung.com/spring-deprecated-websecurityconfigureradapter
CRUD: https://www.javatpoint.com/angular-spring-crud-example
backend url: http://192.168.178.21:8182/api-0.0.1-SNAPSHOT/hello
solution maybe root.jar: https://stackoverflow.com/questions/40714904/after-deployment-of-war-to-tomcat-docker-container-always-getting-404
- backend
- package is com.rossa with artifactName api
- addNumber(number, contract, date)
- wasser
- abwasser
- LWP
- hausstrom
- getEntries(contract)
- siehe oben
- add swagger api doku
- frontend
- overview energy
- details energy
- overview water
- details water
- add entry (for all)
- add angular material
todo: authentication https://www.javaguides.net/2019/04/spring-boot-spring-security-angular-example-tutorial.html

View File

@@ -0,0 +1,4 @@
{
"repoId": "5e4e3a72-7d12-4889-bf8d-e2b8ef628bba",
"lastSync": 0
}

View File

@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
rossa-tech-cli/.gitignore vendored Normal file
View File

@@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@@ -0,0 +1,6 @@
{
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"bracketSpacing": true
}

View File

@@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

20
rossa-tech-cli/.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "pwa-chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

1
rossa-tech-cli/.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1 @@
{}

42
rossa-tech-cli/.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

27
rossa-tech-cli/README.md Normal file
View File

@@ -0,0 +1,27 @@
# RossaTechCli
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 15.1.6.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.

107
rossa-tech-cli/angular.json Normal file
View File

@@ -0,0 +1,107 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"rossa-tech-cli": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/rossa-tech-cli",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
{
"glob": "mdi.svg",
"input": "./node_modules/@mdi/angular-material",
"output": "./assets"
}
],
"styles": ["src/styles.scss"],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "rossa-tech-cli:build",
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "rossa-tech-cli:build:production"
},
"development": {
"browserTarget": "rossa-tech-cli:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "rossa-tech-cli:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": ["zone.js", "zone.js/testing"],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": ["src/styles.scss"],
"scripts": []
}
}
}
}
}
}

12307
rossa-tech-cli/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,41 @@
{
"name": "rossa-tech-cli",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^15.1.0",
"@angular/cdk": "^15.2.4",
"@angular/common": "^15.1.0",
"@angular/compiler": "^15.1.0",
"@angular/core": "^15.1.0",
"@angular/forms": "^15.1.0",
"@angular/material": "^15.2.4",
"@angular/platform-browser": "^15.1.0",
"@angular/platform-browser-dynamic": "^15.1.0",
"@angular/router": "^15.1.0",
"@mdi/angular-material": "^7.2.96",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.12.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^15.1.6",
"@angular/cli": "~15.1.6",
"@angular/compiler-cli": "^15.1.0",
"@types/jasmine": "~4.3.0",
"jasmine-core": "~4.5.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~4.9.4"
}
}

View File

@@ -0,0 +1,18 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from 'src/app/components/dashboard/dashboard.component';
import { LoginComponent } from './components/login/login.component';
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: '**', redirectTo: '/dashboard', pathMatch: 'full' },
// { path: 'login', component: LoginComponent },
// { path: '', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}

View File

@@ -0,0 +1,3 @@
<app-loader></app-loader>
<app-header></app-header>
<router-outlet></router-outlet>

View File

@@ -0,0 +1,35 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'rossa-tech-cli'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('rossa-tech-cli');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('rossa-tech-cli app is running!');
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'rossa-tech-cli';
}

View File

@@ -0,0 +1,91 @@
import { NgModule } from '@angular/core';
import { BrowserModule, DomSanitizer } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatTableModule } from '@angular/material/table';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatToolbarModule } from '@angular/material/toolbar';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { MetersComponent } from './components/meters/meters.component';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatIconModule, MatIconRegistry } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { LoaderComponent } from './components/loader/loader.component';
import { HeaderComponent } from './components/header/header.component';
import { MeterDataListComponent } from './components/subcomponents/meter-data-list/meter-data-list.component';
import { MatGridListModule } from '@angular/material/grid-list';
import { ConsumptionLastYearComponent } from './components/subcomponents/consumption-last-year/consumption-last-year.component';
import { MeterDataWrapperComponent } from './components/subcomponents/meter-data-wrapper/meter-data-wrapper.component';
import { MeterDataAddDialogComponent } from './components/dialogs/meter-data-add-dialog/meter-data-add-dialog.component';
import { MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { LoginComponent } from './components/login/login.component';
import { LogoutComponent } from './components/logout/logout.component';
// import { HttpInterceptorService } from './components/interceptors/httpInterceptor.service';
@NgModule({
declarations: [
AppComponent,
DashboardComponent,
MetersComponent,
LoaderComponent,
HeaderComponent,
MeterDataListComponent,
ConsumptionLastYearComponent,
MeterDataWrapperComponent,
MeterDataAddDialogComponent,
LoginComponent,
LogoutComponent,
],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatTableModule,
MatProgressBarModule,
MatToolbarModule,
MatSidenavModule,
MatIconModule,
MatListModule,
MatGridListModule,
MatDialogModule,
MatButtonModule,
ReactiveFormsModule,
MatDatepickerModule,
MatNativeDateModule,
],
providers: [
MatDatepickerModule,
// {
// provide: HTTP_INTERCEPTORS,
// useClass: HttpInterceptorService,
// multi: true,
// },
],
bootstrap: [AppComponent],
})
export class AppModule {
constructor(matIconRegistry: MatIconRegistry, domSanitizer: DomSanitizer) {
matIconRegistry.addSvgIconSet(
domSanitizer.bypassSecurityTrustResourceUrl('./assets/mdi.svg')
);
}
}

View File

@@ -0,0 +1,21 @@
<div class="content">
<div class="content-header">
content header
<p>dashboard works!</p>
</div>
<button mat-raised-button color="primary" (click)="addMeterData()">addMeterData</button>
<mat-grid-list cols="2" rowHeight="400px">
<mat-grid-tile>
<app-meter-data-wrapper class="full-width" [meterData]="meterDataEnergyDTO"
[type]="usageTypes.ENERGY"></app-meter-data-wrapper>
</mat-grid-tile>
<mat-grid-tile>
<app-meter-data-wrapper class="full-width" [meterData]="meterDataWaterDTO"
[type]="usageTypes.WATER"></app-meter-data-wrapper>
</mat-grid-tile>
</mat-grid-list>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DashboardComponent } from './dashboard.component';
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ DashboardComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,113 @@
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { LoaderService } from 'src/app/components/loader/loader.service';
import { MeterDataAddDialogComponent } from 'src/app/components/dialogs/meter-data-add-dialog/meter-data-add-dialog.component';
import { DatabaseService } from 'src/app/services/database.service';
import { GlobalService } from 'src/app/services/global.service';
import { UsageType } from 'src/app/models/UsageType';
import { MeterData } from 'src/app/models/Meterdata';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent {
usageTypes = UsageType;
// meterDataEnergy1Hem: MeterData[] = [];
// meterDataEnergy1Log: MeterData[] = [];
meterDataEnergy: MeterData[] = [];
meterDataWater: MeterData[] = [];
// meterDataEnergyDTO1Log: MeterData[] = [];
// meterDataEnergyDTO1Hem: MeterData[] = [];
meterDataEnergyDTO: MeterData[] = [];
meterDataWaterDTO: MeterData[] = [];
energyAverageAmountLastYear1Log: number = 0;
energyAverageAmountLastYear1Hem: number = 0;
waterAverageAmountLastYear: number = 0;
displayedColumns: string[] = ['date', 'amount', 'meter'];
constructor(
private dataService: DatabaseService,
private loaderService: LoaderService,
private globalService: GlobalService,
private dialog: MatDialog
) {
this.loadMeterData();
}
loadMeterData(): void {
this.loaderService.show();
this.dataService.getMeterData().subscribe({
next: (data) => {
this.splitMeterData(data);
this.loaderService.hide();
console.log('Meter data:', data);
},
error: (err) => {
this.loaderService.hide();
console.error(err);
},
});
}
splitMeterData(meterData: MeterData[]): void {
if (meterData) {
meterData.forEach((data) => {
if (data.type === this.usageTypes.ENERGY) {
this.meterDataEnergy.push(data);
} else if (data.type === this.usageTypes.WATER) {
this.meterDataWater.push(data);
}
});
this.initEnergyMeterData();
this.initWaterMeterDate();
}
}
initEnergyMeterData(): void {
// this.meterDataEnergy1Log = this.globalService.sortMeterData(
// this.meterDataEnergy1Log
// );
// this.meterDataEnergy1Hem = this.globalService.sortMeterData(
// this.meterDataEnergy1Hem
// );
// this.meterDataEnergyDTO1Log = this.meterDataEnergy1Log;
// this.meterDataEnergyDTO1Hem = this.meterDataEnergy1Hem;
this.meterDataEnergy = this.globalService.sortMeterData(
this.meterDataEnergy
);
this.meterDataEnergyDTO = this.meterDataEnergy;
}
initWaterMeterDate(): void {
this.meterDataWater = this.globalService.sortMeterData(this.meterDataWater);
this.meterDataWaterDTO = this.meterDataWater;
}
addMeterData(): void {
const dialogRef = this.dialog.open(MeterDataAddDialogComponent);
dialogRef.afterClosed().subscribe((newMeterData: MeterData) => {
console.log({ newMeterData });
if (newMeterData) {
this.dataService.addMeterData(newMeterData).subscribe({
next: (meterData: MeterData) => {
console.log({ meterData });
},
error: (err) => {
console.log('add meterData error', { err });
},
});
}
});
}
}

View File

@@ -0,0 +1,25 @@
<h1 mat-dialog-title>Neuer Eintrag - Typ: {{usageType}}</h1>
<form [formGroup]="form">
<div mat-dialog-content>
<mat-form-field>
<input matInput [matDatepicker]="picker" formControlName="date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>Meter</mat-label>
<mat-select formControlName="meter" (valueChange)="setUsageType($event.name)">
<mat-option *ngFor="let el of meters" [value]="el">{{el.name}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<input matInput type="number" formControlName="amount">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-raised-button color="primary" (click)="submit()">Submit</button>
</div>
</form>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MeterDataAddDialogComponent } from './meter-data-add-dialog.component';
describe('MeterDataAddDialogComponent', () => {
let component: MeterDataAddDialogComponent;
let fixture: ComponentFixture<MeterDataAddDialogComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MeterDataAddDialogComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(MeterDataAddDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,66 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { Meter, Meters } from 'src/app/models/Meter';
import { MeterData } from 'src/app/models/Meterdata';
import { UsageType } from 'src/app/models/UsageType';
import { DatabaseService } from 'src/app/services/database.service';
@Component({
selector: 'app-meter-data-add-dialog',
templateUrl: './meter-data-add-dialog.component.html',
styleUrls: ['./meter-data-add-dialog.component.scss'],
})
export class MeterDataAddDialogComponent implements OnInit {
meters: Meter[];
usageTypes = UsageType;
usageType: UsageType;
form: FormGroup;
constructor(
private fb: FormBuilder,
private dialogRef: MatDialogRef<MeterDataAddDialogComponent>,
private dataService: DatabaseService
) {}
ngOnInit(): void {
this.form = this.fb.group({
date: [new Date(), Validators.required],
meter: ['', Validators.required],
amount: ['', Validators.required],
});
this.dataService.getMeters().subscribe({
next: (meters: Meter[]) => {
console.log({ meters });
this.meters = meters;
},
error: (err) => {
console.log('get meters error', { err });
},
});
}
submit() {
if (this.form.valid) {
const formValues = this.form.value;
const newMeterData: MeterData = {
amount: formValues.amount,
date: formValues.date,
meter: formValues.meter,
type: this.usageType,
};
this.dialogRef.close(newMeterData);
}
}
setUsageType(meterName: string): void {
if (meterName === Meters['1HEM'] || meterName === Meters['1LOG']) {
this.usageType = this.usageTypes.ENERGY;
} else if (meterName === Meters.ABWASSER || meterName === Meters.WASSER) {
this.usageType = this.usageTypes.WATER;
}
}
}

View File

@@ -0,0 +1,13 @@
<div class="header-wrapper">
<div class="logo">
rossa-tech
</div>
<div class="nav">
</div>
<div class="account">
<button mat-button>logout</button>
</div>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HeaderComponent } from './header.component';
describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HeaderComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent {
}

View File

@@ -0,0 +1,49 @@
// import {
// HttpInterceptor,
// HttpRequest,
// HttpHandler,
// HttpEvent,
// HttpHeaders,
// } from '@angular/common/http';
// import { Injectable } from '@angular/core';
// import { Observable } from 'rxjs';
// import { AuthenticationService } from 'src/app/services/auth.service';
// @Injectable()
// export class HttpInterceptorService implements HttpInterceptor {
// constructor(private authenticationService: AuthenticationService) {}
// intercept(
// req: HttpRequest<any>,
// next: HttpHandler
// ): Observable<HttpEvent<any>> {
// console.log(
// this.authenticationService.username,
// this.authenticationService.password
// );
// if (
// this.authenticationService.isUserLoggedIn() &&
// req.url.indexOf('basicauth') === -1
// ) {
// console.log('if');
// const authReq = req.clone({
// headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// Authorization: `Basic ${window.btoa('pezi:Password123!')}`,
// // headers: new HttpHeaders({
// // 'Content-Type': 'application/json',
// // Authorization: `Basic ${window.btoa(
// // this.authenticationService.username +
// // ':' +
// // this.authenticationService.password
// // )}`,
// }),
// });
// console.log(authReq);
// return next.handle(authReq);
// } else {
// console.log('else');
// return next.handle(req);
// }
// }
// }

View File

@@ -0,0 +1,3 @@
<div class="loading-indicator" *ngIf="loaderService.isLoading | async">
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>

View File

@@ -0,0 +1,21 @@
/* Absolute Center Spinner */
.loading-indicator {
position: fixed;
z-index: 999;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* Transparent Overlay */
.loading-indicator:before {
content: '';
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoaderComponent } from './loader.component';
describe('LoaderComponent', () => {
let component: LoaderComponent;
let fixture: ComponentFixture<LoaderComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ LoaderComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(LoaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,13 @@
import { Component } from '@angular/core';
import { LoaderService } from './loader.service';
@Component({
selector: 'app-loader',
templateUrl: './loader.component.html',
styleUrls: ['./loader.component.scss']
})
export class LoaderComponent {
constructor(public loaderService: LoaderService) {
}
}

View File

@@ -0,0 +1,25 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoaderService {
/* --- VARIABLEN --- */
public isLoading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(
false
);
/* --- CONSTRUCTOR --- */
constructor() {
}
/* --- FUNCTIONS --- */
show(): void {
this.isLoading.next(true);
}
hide(): void {
this.isLoading.next(false);
}
}

View File

@@ -0,0 +1,22 @@
<div class="container col-lg-6">
<h1 class="text-center">Login</h1>
<div class="card">
<div class="card-body">
<form class="form-group">
<div class="alert alert-warning" *ngIf='invalidLogin'>{{errorMessage}}</div>
<div class="alert alert-success" *ngIf='loginSuccess'>{{successMessage}}</div>
<div class="form-group">
<label for="email">User Name :</label>
<input type="text" class="form-control" id="username" [(ngModel)]="username" placeholder="Enter User Name"
name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" [(ngModel)]="password" id="password" placeholder="Enter password"
name="password">
</div>
<button (click)=handleLogin() class="btn btn-success">Login</button>
</form>
</div>
</div>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,42 @@
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthenticationService } from 'src/app/services/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
username: string;
password: string;
errorMessage = 'Invalid Credentials';
successMessage: string;
invalidLogin = false;
loginSuccess = false;
constructor(
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService
) {}
ngOnInit() {}
handleLogin() {
this.authenticationService
.authenticationService(this.username, this.password)
.subscribe(
(result) => {
this.invalidLogin = false;
this.loginSuccess = true;
this.successMessage = 'Login Successful.';
this.router.navigate(['/dashboard']);
},
() => {
this.invalidLogin = true;
this.loginSuccess = false;
}
);
}
}

View File

@@ -0,0 +1 @@
<p>logout works!</p>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LogoutComponent } from './logout.component';
describe('LogoutComponent', () => {
let component: LogoutComponent;
let fixture: ComponentFixture<LogoutComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ LogoutComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(LogoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-logout',
templateUrl: './logout.component.html',
styleUrls: ['./logout.component.scss']
})
export class LogoutComponent {
}

View File

@@ -0,0 +1 @@
<p>meters works!</p>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MetersComponent } from './meters.component';
describe('MetersComponent', () => {
let component: MetersComponent;
let fixture: ComponentFixture<MetersComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MetersComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(MetersComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-meters',
templateUrl: './meters.component.html',
styleUrls: ['./meters.component.scss']
})
export class MetersComponent {
}

View File

@@ -0,0 +1,20 @@
<ng-container *ngIf="type == usageTypes.ENERGY; else water">
<div style="display: flex; flex-direction: column">
<div>energy</div>
<div style="display: flex; flex-direction: row;">
<div>{{averageEnergy1Log}} kWh</div>
<div>{{averageEnergy1Hem}} kWh</div>
</div>
</div>
</ng-container>
<ng-template #water>
</ng-template>
<!-- <ng-container *ngIf="amount > 0; else noData">{{amount}} kWh</ng-container>
<ng-template #noData>keine Daten vorhanden</ng-template> -->

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ConsumptionLastYearComponent } from './consumption-last-year.component';
describe('ConsumptionLastYearComponent', () => {
let component: ConsumptionLastYearComponent;
let fixture: ComponentFixture<ConsumptionLastYearComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ConsumptionLastYearComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(ConsumptionLastYearComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,126 @@
import { Component, Input, OnChanges } from '@angular/core';
import { Meters } from 'src/app/models/Meter';
import { MeterData } from 'src/app/models/Meterdata';
import { UsageType } from 'src/app/models/UsageType';
import { GlobalService } from 'src/app/services/global.service';
@Component({
selector: 'app-consumption-last-year',
templateUrl: './consumption-last-year.component.html',
styleUrls: ['./consumption-last-year.component.scss'],
})
export class ConsumptionLastYearComponent implements OnChanges {
@Input() meterData: MeterData[];
@Input() type: UsageType;
usageTypes = UsageType;
meters = Meters;
meterDataEnergy1Hem: MeterData[] = [];
averageEnergy1Hem: number;
meterDataEnergy1Log: MeterData[] = [];
averageEnergy1Log: number;
meterDataWasser: MeterData[] = [];
averageWasser: number;
meterDataAbwasser: MeterData[] = [];
averageDirtyAbwasser: number;
constructor(private globalService: GlobalService) {}
ngOnChanges(): void {
if (this.type && this.type === this.usageTypes.ENERGY) {
console.log('count energy');
if (this.meterData) {
this.meterData.forEach((data) => {
if (data.meter.name === this.meters['1LOG']) {
this.meterDataEnergy1Log.push(data);
} else if (data.meter.name === this.meters['1HEM']) {
this.meterDataEnergy1Hem.push(data);
}
});
const currentYear = new Date().getFullYear();
this.meterDataEnergy1Log = this.globalService.sortMeterData(
this.meterDataEnergy1Log
);
this.averageEnergy1Log = this.countAverageAmountForYear(
this.meterDataEnergy1Log,
currentYear - 1
);
this.meterDataEnergy1Hem = this.globalService.sortMeterData(
this.meterDataEnergy1Hem
);
this.averageEnergy1Hem = this.countAverageAmountForYear(
this.meterDataEnergy1Hem,
currentYear - 1
);
}
} else if (this.type && this.type === this.usageTypes.WATER) {
console.log('count water');
if (this.meterData) {
this.meterData.forEach((data) => {
if (data.meter.name === this.meters['WASSER']) {
this.meterDataWasser.push(data);
} else if (data.meter.name === this.meters['ABWASSER']) {
this.meterDataAbwasser.push(data);
}
});
}
}
}
// countAverageAmountForLastYear(meterData: MeterData[]): number {
// const currentYear = new Date().getFullYear();
// let lastYear = meterData.filter(
// (data) => new Date(data.date).getFullYear() === currentYear - 1
// );
// lastYear = this.globalService.sortMeterData(lastYear);
// if (lastYear.length > 0) {
// const end = lastYear[0];
// const startIdx =
// meterData.findIndex((el) => el === lastYear[lastYear.length - 1]) + 1;
// const start = meterData[startIdx];
// console.log({ end: end.amount, startIdx, startAm: start.amount, start });
// return end.amount - start.amount;
// }
// return 0;
// }
/* FOR TEST*/
countAverageAmountForYear(meterData: MeterData[], year: number): number {
// const currentYear = new Date().getFullYear();
let filteredData = meterData.filter(
(data) => new Date(data.date).getFullYear() === year
);
filteredData = this.globalService.sortMeterData(filteredData);
if (filteredData.length > 0) {
const end = filteredData[0];
const startIdx =
meterData.findIndex(
(el) => el === filteredData[filteredData.length - 1]
) + 1;
const start = meterData[startIdx];
console.log({ end: end.amount, startIdx, startAm: start.amount, start });
return end.amount - start.amount;
}
return 0;
}
}

View File

@@ -0,0 +1,31 @@
<h2>{{type}}</h2>
<div class="meter-data-list-wrapper">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> id </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef> date </th>
<td mat-cell *matCellDef="let element"> {{element.date | date:
"dd.MM.y"}} </td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef> amount </th>
<td mat-cell *matCellDef="let element"> {{element.amount}} </td>
</ng-container>
<ng-container matColumnDef="meter">
<th mat-header-cell *matHeaderCellDef> meter </th>
<td mat-cell *matCellDef="let element"> {{element.meter.name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MeterDataListComponent } from './meter-data-list.component';
describe('MeterDataListComponent', () => {
let component: MeterDataListComponent;
let fixture: ComponentFixture<MeterDataListComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MeterDataListComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(MeterDataListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

Some files were not shown because too many files have changed in this diff Show More