Add sge-backend foldery

This commit is contained in:
Ali Sadeghi
2025-07-18 21:16:29 +03:30
parent 25ae881c89
commit 28cc64a052
577 changed files with 833757 additions and 1 deletions

Submodule sge-backend deleted from 9eae0b7282

33
sge-backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.mvn/
### 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/

9
sge-backend/Dockerfile Normal file
View File

@@ -0,0 +1,9 @@
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/sgs-backend.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

316
sge-backend/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
sge-backend/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%

6
sge-backend/package-lock.json generated Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "sge-backend",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

133
sge-backend/pom.xml Normal file
View File

@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath />
</parent>
<groupId>com.sgs</groupId>
<artifactId>sgs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sgs</name>
<description>SGS project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>11.0.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>11.0.0</version>
</dependency>
<dependency>
<groupId>com.zhokhov.graphql</groupId>
<artifactId>graphql-datetime-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<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>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>sgs-backend</finalName>
</build>
</project>

BIN
sge-backend/src/.DS_Store vendored Normal file

Binary file not shown.

BIN
sge-backend/src/main/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,851 @@
package com.sgs;
import com.sgs.graphql.activitySubUnit.domain.ActivitySubUnit;
import com.sgs.graphql.activitySubUnit.service.ActivitySubUnitService;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.city.repo.CityRepo;
import com.sgs.graphql.city.service.CityService;
import com.sgs.graphql.consuptionUnit.domain.ConsuptionUnit;
import com.sgs.graphql.consuptionUnit.repo.ConsuptionUnitRepo;
import com.sgs.graphql.consuptionUnit.service.ConsuptionUnitService;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.country.repo.CountryRepo;
import com.sgs.graphql.country.service.CountryService;
import com.sgs.graphql.district.domain.District;
import com.sgs.graphql.district.repo.DistrictRepo;
import com.sgs.graphql.district.service.DistrictService;
import com.sgs.graphql.emissionScope.domain.EmissionScope;
import com.sgs.graphql.emissionScope.service.EmissionScopeService;
import com.sgs.graphql.emissionSource.domain.EmissionSource;
import com.sgs.graphql.emissionSource.repo.EmissionSourceRepo;
import com.sgs.graphql.emissionSource.service.EmissionSourceService;
import com.sgs.graphql.emissionSourceConvertUnits.domain.EmissionSourceConvertUnit;
import com.sgs.graphql.emissionSourceConvertUnits.service.EmissionSourceConvertUnitService;
import com.sgs.graphql.gpcReference.domain.GpcReference;
import com.sgs.graphql.gpcReference.service.GpcReferenceService;
import com.sgs.graphql.mail.domain.MailInfo;
import com.sgs.graphql.mail.service.MailInfoService;
import com.sgs.graphql.mcfType.domain.McfType;
import com.sgs.graphql.mcfType.service.McfTypeService;
import com.sgs.graphql.neighborhood.domain.Neighborhood;
import com.sgs.graphql.neighborhood.repo.NeighborhoodRepo;
import com.sgs.graphql.neighborhood.service.NeighborhoodService;
import com.sgs.graphql.organization.domain.Organization;
import com.sgs.graphql.organization.service.OrganizationService;
import com.sgs.graphql.permission.domain.Permission;
import com.sgs.graphql.permission.domain.PermissionDescription;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.graphql.permission.service.PermissionService;
import com.sgs.graphql.role.domain.Role;
import com.sgs.graphql.role.repo.RoleRepo;
import com.sgs.graphql.role.service.RoleService;
import com.sgs.graphql.sector.domain.Sector;
import com.sgs.graphql.sector.service.SectorService;
import com.sgs.graphql.solidWasteType.domain.SolidWasteType;
import com.sgs.graphql.solidWasteType.service.SolidWasteTypeService;
import com.sgs.graphql.subSector.domain.SubSector;
import com.sgs.graphql.subSector.repo.SubSectorRepo;
import com.sgs.graphql.subSector.service.SubSectorService;
import com.sgs.graphql.user.domain.User;
import com.sgs.graphql.user.service.UserService;
import com.sgs.graphql.wasteEmissionSource.domain.WasteEmissionSourceSupplement;
import com.sgs.graphql.wasteEmissionSource.service.WasteEmissionSourceSupplementService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
@SpringBootApplication
public class SgsApplication implements CommandLineRunner {
private final PermissionService permissionService;
private final RoleService roleService;
private final RoleRepo roleRepo;
private final NeighborhoodRepo neighborhoodRepo;
private final NeighborhoodService neighborhoodService;
private final CityService cityService;
private final CityRepo cityRepo;
private final DistrictRepo districtRepo;
private final DistrictService districtService;
private final CountryRepo countryRepo;
private final CountryService countryService;
private final OrganizationService organizationService;
private final UserService userService;
private final PasswordEncoder passwordEncoder;
private final SectorService sectorService;
private final SubSectorService subSectorService;
private final EmissionScopeService emissionScopeService;
private final GpcReferenceService gpcReferenceService;
private final SubSectorRepo subSectorRepo;
private final ActivitySubUnitService activitySubUnitService;
private final ConsuptionUnitService consuptionUnitService;
private final EmissionSourceService emissionSourceService;
private final EmissionSourceRepo emissionSourceRepo;
private final ConsuptionUnitRepo consuptionUnitRepo;
private final EmissionSourceConvertUnitService emissionSourceConvertUnitService;
private final SolidWasteTypeService solidWasteTypeService;
private final McfTypeService mcfTypeService;
private final WasteEmissionSourceSupplementService wasteEmissionSourceSupplementService;
private final MailInfoService mailInfoService;
@Value("${mail.hostname:mail.blc-css.com}")
private String mailHostname;
@Value("${mail.smtp.port:465}")
private int mailSmtpPort;
@Value("${mail.address:info@blc-css.com}")
private String mailAddress;
@Value("${mail.password:}")
private String mailPassword;
public static void main(String[] args) {
SpringApplication.run(SgsApplication.class, args);
}
@Autowired
public SgsApplication(RoleService roleService, PermissionService permissionService, RoleRepo roleRepo,
NeighborhoodRepo neighborhoodRepo, NeighborhoodService neighborhoodService, CityService cityService,
CityRepo cityRepo, DistrictRepo districtRepo, DistrictService districtService, CountryRepo countryRepo,
CountryService countryService, OrganizationService organizationService, UserService userService,
PasswordEncoder passwordEncoder, SectorService sectorService, SubSectorService subSectorService,
EmissionScopeService emissionScopeService, GpcReferenceService gpcReferenceService,
SubSectorRepo subSectorRepo, ActivitySubUnitService activitySubUnitService,
ConsuptionUnitService consuptionUnitService, EmissionSourceService emissionSourceService,
EmissionSourceRepo emissionSourceRepo, ConsuptionUnitRepo consuptionUnitRepo,
EmissionSourceConvertUnitService emissionSourceConvertUnitService,
SolidWasteTypeService solidWasteTypeService, McfTypeService mcfTypeService,
WasteEmissionSourceSupplementService wasteEmissionSourceSupplementService,
MailInfoService mailInfoService) {
this.roleService = roleService;
this.permissionService = permissionService;
this.roleRepo = roleRepo;
this.neighborhoodRepo = neighborhoodRepo;
this.neighborhoodService = neighborhoodService;
this.cityService = cityService;
this.cityRepo = cityRepo;
this.districtRepo = districtRepo;
this.districtService = districtService;
this.countryRepo = countryRepo;
this.countryService = countryService;
this.organizationService = organizationService;
this.userService = userService;
this.passwordEncoder = passwordEncoder;
this.sectorService = sectorService;
this.subSectorService = subSectorService;
this.emissionScopeService = emissionScopeService;
this.gpcReferenceService = gpcReferenceService;
this.subSectorRepo = subSectorRepo;
this.activitySubUnitService = activitySubUnitService;
this.consuptionUnitService = consuptionUnitService;
this.emissionSourceService = emissionSourceService;
this.emissionSourceRepo = emissionSourceRepo;
this.consuptionUnitRepo = consuptionUnitRepo;
this.emissionSourceConvertUnitService = emissionSourceConvertUnitService;
this.solidWasteTypeService = solidWasteTypeService;
this.mcfTypeService = mcfTypeService;
this.wasteEmissionSourceSupplementService = wasteEmissionSourceSupplementService;
this.mailInfoService = mailInfoService;
}
void createDefaultOrganization() {
Organization organization = new Organization();
organization.setTag("BLC");
organization.setDescription("BLC Communication and Security Systems");
organizationService.save(organization);
}
void createDefaultUser() {
Role role = roleRepo.findByTag("SUPER_ADMIN").orElse(null);
List<Permission> permissions = new ArrayList<>();
if (!permissionService.findAll().isEmpty()) {
permissions.addAll(permissionService.findAll());
}
role.setPermissions(permissions);
// List<Organization> organizations = organizationRepo.findByTag("BLC");
User admin = new User();
admin.setFirstName("Seda");
admin.setLastName("Kemikli");
admin.setEmail("seda.kemikli@blc-css.com");
admin.setPhoneNumber("11111111");
admin.setPassword(passwordEncoder.encode("admin"));
// if (organizations.size() == 1) {
// admin.setOrganizations(organizations);
// }
admin.setRole(role);
admin.setStatus("aktif");
userService.save(admin);
}
public void createDefaultPermission() {
Permission activities_get = new Permission();
activities_get.setTag(PermissionName.ACTIVITIES_GET);
activities_get.setDescription(PermissionDescription.ACTIVITIES_GET);
Permission paginate_user_histories = new Permission();
paginate_user_histories.setTag(PermissionName.PAGINATE_USER_HISTORIES);
paginate_user_histories.setDescription(PermissionDescription.PAGINATE_USER_HISTORIES);
Permission activity_sub_units_get = new Permission();
activity_sub_units_get.setTag(PermissionName.ACTIVITY_SUB_UNITS_GET);
activity_sub_units_get.setDescription(PermissionDescription.ACTIVITY_SUB_UNITS_GET);
Permission sub_sectors_get = new Permission();
sub_sectors_get.setTag(PermissionName.SUB_SECTORS_GET);
sub_sectors_get.setDescription(PermissionDescription.SUB_SECTORS_GET);
Permission sectors_get = new Permission();
sectors_get.setTag(PermissionName.SECTORS_GET);
sectors_get.setDescription(PermissionDescription.SECTORS_GET);
Permission deleted_items = new Permission();
deleted_items.setTag(PermissionName.GET_DELETED_ITEMS);
deleted_items.setDescription(PermissionDescription.GET_DELETED_ITEMS);
Permission user_create = new Permission();
user_create.setTag(PermissionName.USER_CREATE);
user_create.setDescription(PermissionDescription.USER_CREATE);
Permission user_update = new Permission();
user_update.setTag(PermissionName.USER_UPDATE);
user_update.setDescription(PermissionDescription.USER_UPDATE);
Permission user_delete = new Permission();
user_delete.setTag(PermissionName.USER_DELETE);
user_delete.setDescription(PermissionDescription.USER_DELETE);
Permission paginate_users_get = new Permission();
paginate_users_get.setTag(PermissionName.PAGINATE_USERS_GET);
paginate_users_get.setDescription(PermissionDescription.PAGINATE_USERS_GET);
Permission role_create = new Permission();
role_create.setTag(PermissionName.ROLE_CREATE);
role_create.setDescription(PermissionDescription.ROLE_CREATE);
Permission role_update = new Permission();
role_update.setTag(PermissionName.ROLE_UPDATE);
role_update.setDescription(PermissionDescription.ROLE_UPDATE);
Permission role_delete = new Permission();
role_delete.setTag(PermissionName.ROLE_DELETE);
role_delete.setDescription(PermissionDescription.ROLE_DELETE);
Permission paginate_roles_get = new Permission();
paginate_roles_get.setTag(PermissionName.PAGINATE_ROLES_GET);
paginate_roles_get.setDescription(PermissionDescription.PAGINATE_ROLES_GET);
Permission organization_create = new Permission();
organization_create.setTag(PermissionName.ORGANIZATION_CREATE);
organization_create.setDescription(PermissionDescription.ORGANIZATION_CREATE);
Permission organization_update = new Permission();
organization_update.setTag(PermissionName.ORGANIZATION_UPDATE);
organization_update.setDescription(PermissionDescription.ORGANIZATION_UPDATE);
Permission organization_delete = new Permission();
organization_delete.setTag(PermissionName.ORGANIZATION_DELETE);
organization_delete.setDescription(PermissionDescription.ORGANIZATION_DELETE);
Permission paginate_organizations_get = new Permission();
paginate_organizations_get.setTag(PermissionName.PAGINATE_ORGANIZATIONS_GET);
paginate_organizations_get.setDescription(PermissionDescription.PAGINATE_ORGANIZATIONS_GET);
Permission area_create = new Permission();
area_create.setTag(PermissionName.AREA_CREATE);
area_create.setDescription(PermissionDescription.AREA_CREATE);
Permission area_update = new Permission();
area_update.setTag(PermissionName.AREA_UPDATE);
area_update.setDescription(PermissionDescription.AREA_UPDATE);
Permission area_delete = new Permission();
area_delete.setTag(PermissionName.AREA_DELETE);
area_delete.setDescription(PermissionDescription.AREA_DELETE);
Permission paginate_areas_get = new Permission();
paginate_areas_get.setTag(PermissionName.PAGINATE_AREAS_GET);
paginate_areas_get.setDescription(PermissionDescription.PAGINATE_AREAS_GET);
Permission neighborhood_create = new Permission();
neighborhood_create.setTag(PermissionName.NEIGHBORHOOD_CREATE);
neighborhood_create.setDescription(PermissionDescription.NEIGHBORHOOD_CREATE);
Permission neighborhood_update = new Permission();
neighborhood_update.setTag(PermissionName.NEIGHBORHOOD_UPDATE);
neighborhood_update.setDescription(PermissionDescription.NEIGHBORHOOD_UPDATE);
Permission neighborhood_delete = new Permission();
neighborhood_delete.setTag(PermissionName.NEIGHBORHOOD_DELETE);
neighborhood_delete.setDescription(PermissionDescription.NEIGHBORHOOD_DELETE);
Permission paginate_neighborhoods_get = new Permission();
paginate_neighborhoods_get.setTag(PermissionName.PAGINATE_NEIGHBORHOODS_GET);
paginate_neighborhoods_get.setDescription(PermissionDescription.PAGINATE_NEIGHBORHOODS_GET);
Permission paginate_cities_get = new Permission();
paginate_cities_get.setTag(PermissionName.PAGINATE_CITIES_GET);
paginate_cities_get.setDescription(PermissionDescription.PAGINATE_CITIES_GET);
Permission paginate_districts_get = new Permission();
paginate_districts_get.setTag(PermissionName.PAGINATE_DISTRICTS_GET);
paginate_districts_get.setDescription(PermissionDescription.PAGINATE_DISTRICTS_GET);
Permission paginate_countries_get = new Permission();
paginate_countries_get.setTag(PermissionName.PAGINATE_COUNTRIES_GET);
paginate_countries_get.setDescription(PermissionDescription.PAGINATE_COUNTRIES_GET);
Permission emission_source_create = new Permission();
emission_source_create.setTag(PermissionName.EMISSION_SOURCE_CREATE);
emission_source_create.setDescription(PermissionDescription.EMISSION_SOURCE_CREATE);
Permission emission_source_update = new Permission();
emission_source_update.setTag(PermissionName.EMISSION_SOURCE_UPDATE);
emission_source_update.setDescription(PermissionDescription.EMISSION_SOURCE_UPDATE);
Permission emission_source_delete = new Permission();
emission_source_delete.setTag(PermissionName.EMISSION_SOURCE_DELETE);
emission_source_delete.setDescription(PermissionDescription.EMISSION_SOURCE_DELETE);
Permission paginate_emission_sources_get = new Permission();
paginate_emission_sources_get.setTag(PermissionName.PAGINATE_EMISSION_SOURCES_GET);
paginate_emission_sources_get.setDescription(PermissionDescription.PAGINATE_EMISSION_SOURCES_GET);
Permission dataset_create = new Permission();
dataset_create.setTag(PermissionName.DATASET_CREATE);
dataset_create.setDescription(PermissionDescription.DATASET_CREATE);
Permission dataset_update = new Permission();
dataset_update.setTag(PermissionName.DATASET_UPDATE);
dataset_update.setDescription(PermissionDescription.DATASET_UPDATE);
Permission dataset_delete = new Permission();
dataset_delete.setTag(PermissionName.DATASET_DELETE);
dataset_delete.setDescription(PermissionDescription.DATASET_DELETE);
Permission paginate_datasets_get = new Permission();
paginate_datasets_get.setTag(PermissionName.PAGINATE_DATASETS_GET);
paginate_datasets_get.setDescription(PermissionDescription.PAGINATE_DATASETS_GET);
Permission answer_create = new Permission();
answer_create.setTag(PermissionName.ANSWER_CREATE);
answer_create.setDescription(PermissionDescription.ANSWER_CREATE);
Permission answer_update = new Permission();
answer_update.setTag(PermissionName.ANSWER_UPDATE);
answer_update.setDescription(PermissionDescription.ANSWER_UPDATE);
Permission answer_delete = new Permission();
answer_delete.setTag(PermissionName.ANSWER_DELETE);
answer_delete.setDescription(PermissionDescription.ANSWER_DELETE);
Permission paginate_answers_get = new Permission();
paginate_answers_get.setTag(PermissionName.PAGINATE_ANSWERS_GET);
paginate_answers_get.setDescription(PermissionDescription.PAGINATE_ANSWERS_GET);
Permission question_create = new Permission();
question_create.setTag(PermissionName.QUESTION_CREATE);
question_create.setDescription(PermissionDescription.QUESTION_CREATE);
Permission question_update = new Permission();
question_update.setTag(PermissionName.QUESTION_UPDATE);
question_update.setDescription(PermissionDescription.QUESTION_UPDATE);
Permission question_delete = new Permission();
question_delete.setTag(PermissionName.QUESTION_DELETE);
question_delete.setDescription(PermissionDescription.QUESTION_DELETE);
Permission paginate_questions_get = new Permission();
paginate_questions_get.setTag(PermissionName.PAGINATE_QUESTIONS_GET);
paginate_questions_get.setDescription(PermissionDescription.PAGINATE_QUESTIONS_GET);
Permission undelete_items = new Permission();
undelete_items.setTag(PermissionName.UNDELETE_ITEMS);
undelete_items.setDescription(PermissionDescription.UNDELETE_ITEMS);
Permission published_survey_create = new Permission();
published_survey_create.setTag(PermissionName.PUBLISHED_SURVEY_CREATE);
published_survey_create.setDescription(PermissionDescription.PUBLISHED_SURVEY_CREATE);
Permission surveys_get = new Permission();
surveys_get.setTag(PermissionName.SURVEYS_GET);
surveys_get.setDescription(PermissionDescription.SURVEYS_GET);
Permission paginate_surveys_get = new Permission();
paginate_surveys_get.setTag(PermissionName.PAGINATE_SURVEYS_GET);
paginate_surveys_get.setDescription(PermissionDescription.PAGINATE_SURVEYS_GET);
Permission survey_update = new Permission();
survey_update.setTag(PermissionName.SURVEY_UPDATE);
survey_update.setDescription(PermissionDescription.SURVEY_UPDATE);
Permission survey_delete = new Permission();
survey_delete.setTag(PermissionName.SURVEY_DELETE);
survey_delete.setDescription(PermissionDescription.SURVEY_DELETE);
Permission survey_add = new Permission();
survey_add.setTag(PermissionName.SURVEY_ADD);
survey_add.setDescription(PermissionDescription.SURVEY_ADD);
Permission show_graphics = new Permission();
show_graphics.setTag(PermissionName.SHOW_GRAPHICS);
show_graphics.setDescription(PermissionDescription.SHOW_GRAPHICS);
Permission settings_access = new Permission();
settings_access.setTag(PermissionName.SETTINGS_ACCESS);
settings_access.setDescription(PermissionDescription.SETTINGS_ACCESS);
Permission data_center_create = new Permission();
data_center_create.setTag(PermissionName.DATA_CENTER_CREATE);
data_center_create.setDescription(PermissionDescription.DATA_CENTER_CREATE);
Permission data_center_delete = new Permission();
data_center_delete.setTag(PermissionName.DATA_CENTER_DELETE);
data_center_delete.setDescription(PermissionDescription.DATA_CENTER_DELETE);
Permission data_center_update = new Permission();
data_center_update.setTag(PermissionName.DATA_CENTER_UPDATE);
data_center_update.setDescription(PermissionDescription.DATA_CENTER_UPDATE);
Permission data_center_read = new Permission();
data_center_read.setTag(PermissionName.DATA_CENTER_READ);
data_center_read.setDescription(PermissionDescription.DATA_CENTER_READ);
permissionService.saveAll(List.of(
show_graphics, activities_get, paginate_user_histories, activity_sub_units_get, sub_sectors_get,
sectors_get, deleted_items, undelete_items, user_create, user_update, user_delete, paginate_users_get,
role_create, role_update, role_delete, paginate_roles_get,
organization_create, organization_update, organization_delete, paginate_organizations_get,
area_create, area_update, area_delete, paginate_areas_get,
neighborhood_create, neighborhood_update, neighborhood_delete, paginate_neighborhoods_get,
paginate_districts_get,
paginate_cities_get,
paginate_countries_get,
emission_source_create, emission_source_update, emission_source_delete, paginate_emission_sources_get,
dataset_create, dataset_update, dataset_delete, paginate_datasets_get,
answer_create, answer_delete, answer_update, paginate_answers_get,
question_create, question_delete, question_update, paginate_questions_get,
published_survey_create, surveys_get, paginate_surveys_get,
survey_add, survey_delete, survey_update, settings_access, data_center_create, data_center_delete,
data_center_update, data_center_read));
}
public void createDefaultRole() {
Role role = new Role();
role.setTag("SUPER_ADMIN");
role.setPermissions(permissionService.findAll());
roleService.save(role);
}
void createCountry() {
Country country = new Country();
country.setCountryCode("TR");
country.setName("Turkiye");
countryRepo.save(country);
}
public void createCitiesFromJson() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/cities.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String cityName = jsonObject.getString("name");
JSONArray cityCoordinates = jsonObject.getJSONArray("coordinates");
City city = new City();
city.setName(cityName);
city.setCoordinates(cityCoordinates.toString());
city.setCountry(countryService.findAll().get(0));
cityRepo.save(city);
}
}
public void createDistrictFromJson() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/districts.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String districtName = jsonObject.getString("name");
String cityName = jsonObject.getString("city");
JSONArray districtCoordinates = jsonObject.getJSONArray("coordinates");
City city = cityRepo.findByName(cityName);
District district = new District();
district.setName(districtName);
district.setCoordinates(districtCoordinates.toString());
district.setCity(city);
districtRepo.save(district);
}
}
void createNeighborhoodsFromJson() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/neighbourhoods.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String cityName = jsonObject.getString("city");
String districtName = jsonObject.getString("district");
String neighborhoodName = jsonObject.getString("name");
double minLong = jsonObject.getDouble("minLong");
double minLat = jsonObject.getDouble("minLat");
double maxLong = jsonObject.getDouble("maxLong");
double maxLat = jsonObject.getDouble("maxLat");
City city = cityRepo.findByName(cityName);
if (city != null) {
District district = city.getDistricts().stream()
.filter(d -> d.getName().equals(districtName))
.findFirst()
.orElse(null);
if (district != null) {
Neighborhood neighborhood = new Neighborhood();
neighborhood.setName(neighborhoodName);
neighborhood.setDistrict(district);
neighborhood.setMinLong(minLong);
neighborhood.setMinLat(minLat);
neighborhood.setMaxLong(maxLong);
neighborhood.setMaxLat(maxLat);
neighborhoodRepo.save(neighborhood);
}
}
}
}
void createSectorAndSubSectorFromJson() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/SectorsAndSubSectors.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("Sectors");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Sector sector = new Sector();
sector.setTag(jsonObject.getString("SectorName"));
sector.setSectorNo(jsonObject.getInt("SectorNo"));
sector.setDescription(jsonObject.getString("SectorName"));
sectorService.save(sector);
JSONArray subSectorsJson = jsonObject.getJSONArray("SubSectors");
for (int j = 0; j < subSectorsJson.length(); j++) {
JSONObject subSectorJson = subSectorsJson.getJSONObject(j);
SubSector subSector = new SubSector();
subSector.setSubSectorNo(subSectorJson.getInt("SubSectorNo"));
subSector.setTag(subSectorJson.getString("Name"));
subSector.setDescription(subSectorJson.getString("Name"));
subSector.setSector(sector);
subSectorService.save(subSector);
}
}
}
void createGpcReference() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/GpcReferenceNumbers.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
GpcReference gpcReference = new GpcReference();
gpcReference.setReferenceNumber(jsonArray.getString(i));
gpcReference.setDescription(jsonArray.getString(i));
gpcReferenceService.save(gpcReference);
}
}
void createConsuptionUnit() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/ConsuptionUnits.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("units");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject unitObject = jsonArray.getJSONObject(i);
String unitName = unitObject.getString("name");
String unitDescription = unitObject.getString("description");
ConsuptionUnit consuptionUnit = new ConsuptionUnit();
consuptionUnit.setTag(unitName);
consuptionUnit.setDescription(unitDescription);
consuptionUnitService.save(consuptionUnit);
}
}
void createEmissionSourceConvertUnit() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/EmissionSourceConvertUnit.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("Data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
List<EmissionSource> emissionSourceList = emissionSourceRepo.findByTag(obj.getString("EmissionSource"));
ConsuptionUnit consuptionUnit = consuptionUnitRepo.findByTag(obj.getString("ConsuptionUnit")).get(0);
for (EmissionSource emissionSource : emissionSourceList) {
if (consuptionUnit != null) {
emissionSource.setConvertUnitCheck(true);
EmissionSource updatedEmissionSource = emissionSourceService.update(emissionSource);
EmissionSourceConvertUnit unit = new EmissionSourceConvertUnit();
unit.setEmissionSource(updatedEmissionSource);
unit.setUnit(consuptionUnit);
unit.setValue(obj.getDouble("Amount"));
emissionSourceConvertUnitService.save(unit);
}
}
}
}
void createEmissionScope() {
for (int i = 1; i < 4; i++) {
EmissionScope emissionScope = new EmissionScope();
emissionScope.setTag("Kapsam-" + i);
emissionScope.setDescription("Kapsam-" + i);
emissionScopeService.save(emissionScope);
}
}
void createActivitySubUnit() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/ActivitySubUnits.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
List<String> tags = Arrays.asList("Konutlar", "Ticari ve Kurumsal Binalar", "İmalat Sanayi ve İnşaat Yapı",
"Tarım, Ormancılık, Balıılık Faaliyetleri ve Balık Çiftlikleri",
"Kömür Madenciliği, İşlenmesi, Depolanması ve Taşınmasından Kaynaklanan Kaçak Emisyonlar",
"Karayolu Taşımacılığı", "Havayolu Taşımacılığı", "Demiryolu Taşımacılığı", "Arazi Taşımacılığı",
"Denizyolu Taşımacılığı");
for (String tag : tags) {
JSONArray jsonArray = fullJson.getJSONArray(tag);
SubSector subSector = subSectorRepo.findByTag(tag);
for (int i = 0; i < jsonArray.length(); i++) {
ActivitySubUnit activitySubUnit = new ActivitySubUnit();
activitySubUnit.setTag(jsonArray.getString(i));
activitySubUnit.setDescription(jsonArray.getString(i));
activitySubUnit.setSubSector(subSector);
activitySubUnitService.save(activitySubUnit);
}
}
}
void createEmissionSourceFromJson(String filePath, String[] subSectorTags) throws IOException {
InputStream is = getClass().getResourceAsStream("/" + filePath);
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("Data");
String[] co2Tags = { "CO2", "CO2_1", "CO2_2", "CO2_3", "CO2_4" };
String[] ch4Tags = { "CH4 (CO2e)", "CH4 (CO2e)_1", "CH4 (CO2e)_2", "CH4 (CO2e)_3", "CH4 (CO2e)_4" };
String[] n20Tags = { "N20 (CO2e)", "N20 (CO2e)_1", "N20 (CO2e)_2", "N20 (CO2e)_3", "N20 (CO2e)_4" };
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag = jsonObject.getString("Emisyon Kaynağı");
String scope = jsonObject.optString("scope");
for (int j = 0; j < subSectorTags.length; j++) {
EmissionSource emissionSource = new EmissionSource();
emissionSource.setTag(tag);
emissionSource.setEmissionScope(scope);
emissionSource.setDescription(tag);
emissionSource.setCo2(jsonObject.getDouble(co2Tags[j]));
emissionSource.setCh4(jsonObject.getDouble(ch4Tags[j]));
emissionSource.setN2o(jsonObject.getDouble(n20Tags[j]));
emissionSource.setSubSector(subSectorRepo.findByTag(subSectorTags[j]));
EmissionSource savedEmissionSource = emissionSourceService.save(emissionSource);
EmissionSourceConvertUnit tjConvertUnit = new EmissionSourceConvertUnit();
tjConvertUnit.setEmissionSource(savedEmissionSource);
tjConvertUnit.setValue(1.0);
tjConvertUnit.setUnit(consuptionUnitRepo.findByTag("TJ").get(0));
EmissionSourceConvertUnit savedTjConvertUnit = emissionSourceConvertUnitService.save(tjConvertUnit);
}
}
}
void createWasteEmissionSourceFromJson(String filePath) throws IOException {
InputStream is = getClass().getResourceAsStream("/" + filePath);
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("Data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
WasteEmissionSourceSupplement wasteEmissionSourceSupplement = new WasteEmissionSourceSupplement();
wasteEmissionSourceSupplement.setDryWeightCH4(jsonObject.optDouble("dryWeightCH4", 0.0));
wasteEmissionSourceSupplement.setWetWeightCH4(jsonObject.optDouble("wetWeightCH4", 0.0));
wasteEmissionSourceSupplement.setDampWeightCH4(jsonObject.optDouble("dampWeightCH4", 0.0));
wasteEmissionSourceSupplement.setDryWeightN2O(jsonObject.optDouble("dryWeightN2O", 0.0));
wasteEmissionSourceSupplement.setWetWeightN2O(jsonObject.optDouble("wetWeightN2O", 0.0));
WasteEmissionSourceSupplement savedWasteEmissionSourceSupplement = wasteEmissionSourceSupplementService
.save(wasteEmissionSourceSupplement);
String tag = jsonObject.getString("Emisyon Kaynağı");
EmissionSource emissionSource = new EmissionSource();
emissionSource.setTag(tag);
emissionSource.setDescription(tag);
emissionSource.setCo2(0.0);
emissionSource.setCh4(0.0);
emissionSource.setN2o(0.0);
emissionSource.setConvertUnitCheck(true);
if (i < 2) {
emissionSource.setSubSector(subSectorRepo.findByTag("Atıkların Biyolojik Arıtılması"));
} else if (i < 10) {
emissionSource.setSubSector(subSectorRepo.findByTag("Atık Su Arıtma ve Deşarjı"));
} else if (i < 14) {
emissionSource.setSubSector(subSectorRepo.findByTag("Yakma ve Açık Yanma"));
}
emissionSource.setWasteEmissionSourceSupplement(savedWasteEmissionSourceSupplement);
emissionSourceService.save(emissionSource);
}
}
void createSolidWasteTypeFromJson() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/SolidWasteTypes.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("Data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String typeName = jsonObject.getString("TypeName");
double formulaCoefficient = jsonObject.getDouble("FormulaCoefficient");
SolidWasteType solidWasteType = new SolidWasteType();
solidWasteType.setTypeName(typeName);
solidWasteType.setFormulaCoefficient(formulaCoefficient);
solidWasteTypeService.save(solidWasteType);
}
}
void createMcfTypeFromJson() throws IOException {
InputStream is = getClass().getResourceAsStream("/XDataSetModuleFiles/MCFType.json");
String data = new String(is.readAllBytes(), StandardCharsets.UTF_8);
JSONObject fullJson = new JSONObject(data);
JSONArray jsonArray = fullJson.getJSONArray("Data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String typeName = jsonObject.getString("TypeName");
double value = jsonObject.getDouble("Value");
McfType mcfType = new McfType();
mcfType.setTypeName(typeName);
mcfType.setValue(value);
mcfTypeService.save(mcfType);
}
}
void createDefaultMailInfo() {
MailInfo mailInfo = new MailInfo();
mailInfo.setHostName(mailHostname);
mailInfo.setSmtpPort(mailSmtpPort);
mailInfo.setEmailAddress(mailAddress);
mailInfo.setEmailPassword(mailPassword);
mailInfo.setMainMail(true);
mailInfoService.save(mailInfo);
}
@Override
public void run(String... args) throws Exception {
if (mailInfoService.findAll().isEmpty()) {
createDefaultMailInfo();
}
if (consuptionUnitService.findAll().isEmpty()) {
createConsuptionUnit();
}
if (gpcReferenceService.findAll().isEmpty()) {
createGpcReference();
}
if (emissionScopeService.findAll().isEmpty()) {
createEmissionScope();
}
if (sectorService.findAll().isEmpty()) {
createSectorAndSubSectorFromJson();
}
if (activitySubUnitService.findAll().isEmpty()) {
createActivitySubUnit();
}
if (emissionSourceService.findAll().isEmpty()) {
createEmissionSourceFromJson("XDataSetModuleFiles/EmissionSourceYenilenebilirEnerjiEF.json",
new String[] { "Güneş Enerji Santrali", "Rüzgar Enerji Santrali", "Hidroelektrik Enerji Santrali",
"Biyokütle Enerji Santrali", "Jeotermal Enerji Santrali" });
createEmissionSourceFromJson("XDataSetModuleFiles/EmissionSourceSabitEnerjiEF.json",
new String[] { "Enerji Endüstrileri", "İmalat Sanayi ve İnşaat Yapı", "Ticari ve Kurumsal Binalar",
"Konutlar", "Tarım, Ormancılık, Balıılık Faaliyetleri ve Balık Çiftlikleri" });
createEmissionSourceFromJson("XDataSetModuleFiles/EmissionSourceUlasimEF.json",
new String[] { "Karayolu Taşımacılığı", "Denizyolu Taşımacılığı", "Demiryolu Taşımacılığı",
"Arazi Taşımacılığı", "Havayolu Taşımacılığı" });
createWasteEmissionSourceFromJson("XDataSetModuleFiles/EmissionSourceAtikEF.json");
createEmissionSourceConvertUnit();
}
if (solidWasteTypeService.findAll().isEmpty()) {
createSolidWasteTypeFromJson();
}
if (mcfTypeService.findAll().isEmpty()) {
createMcfTypeFromJson();
}
if (permissionService.findAll().isEmpty()) {
createDefaultPermission();
}
if (roleService.findAll().isEmpty()) {
createDefaultRole();
}
if (organizationService.findAll().isEmpty()) {
createDefaultOrganization();
}
if (userService.findAll().isEmpty()) {
createDefaultUser();
}
if (countryService.findAll().isEmpty()) {
createCountry();
}
if (cityService.findAll().isEmpty()) {
createCitiesFromJson();
}
if (districtService.findAll().isEmpty()) {
createDistrictFromJson();
}
if (neighborhoodService.findAll().isEmpty()) {
createNeighborhoodsFromJson();
}
// Add new permission if it doesn't exist
// [Remove Later]
if (permissionService.findAll().stream().noneMatch(p -> PermissionName.SETTINGS_ACCESS.equals(p.getTag()))) {
Permission settingsAccess = new Permission();
settingsAccess.setTag(PermissionName.SETTINGS_ACCESS);
settingsAccess.setDescription(PermissionDescription.SETTINGS_ACCESS);
settingsAccess.setDefault_permission(false);
settingsAccess.setDeleted(false);
permissionService.save(settingsAccess);
}
Permission settings_access = new Permission();
settings_access.setTag(PermissionName.SETTINGS_ACCESS);
settings_access.setDescription(PermissionDescription.SETTINGS_ACCESS);
}
}

View File

@@ -0,0 +1,32 @@
package com.sgs.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CORSConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:8080");
config.addAllowedHeader("*");
config.addAllowedOriginPattern("*");
config.addAllowedMethod(CorsConfiguration.ALL);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
public ObjectMapper singleQuoteObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
return mapper;
}
}

View File

@@ -0,0 +1,19 @@
package com.sgs.config;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
public static final String QUEUE_NAME = "tsstyqueue";
@Bean
public Queue queue() {
return new Queue(QUEUE_NAME,
true,
false,
false);
}
}

View File

@@ -0,0 +1,26 @@
package com.sgs.exception;
import org.springframework.http.HttpStatus;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final String message;
private final HttpStatus httpStatus;
public CustomException(String message, HttpStatus httpStatus) {
this.message = message;
this.httpStatus = httpStatus;
}
@Override
public String getMessage() {
return message;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}

View File

@@ -0,0 +1,11 @@
package com.sgs.exception;
public class FileStorageException extends RuntimeException {
public FileStorageException(String message) {
super(message);
}
public FileStorageException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,43 @@
package com.sgs.exception;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandlerController {
@ExceptionHandler(CustomException.class)
public void handleCustomException(HttpServletResponse res, CustomException ex) throws IOException {
res.sendError(ex.getHttpStatus().value(), ex.getMessage());
}
@ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(HttpServletResponse res) throws IOException {
res.sendError(HttpStatus.FORBIDDEN.value(), "Access denied.");
}
@ExceptionHandler(Exception.class)
public void handleException(HttpServletResponse res) throws IOException {
res.sendError(HttpStatus.BAD_REQUEST.value(), "Something went wrong, please try again.");
}
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
return super.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults().excluding(ErrorAttributeOptions.Include.EXCEPTION));
}
};
}
}

View File

@@ -0,0 +1,55 @@
package com.sgs.exception;
import graphql.ErrorType;
import graphql.GraphQLError;
import graphql.language.SourceLocation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GraphQLCustomError implements GraphQLError {
private final String errorCode;
private final String message;
private final List<SourceLocation> locations;
private final List<Object> path;
private final Map<String, Object> extensions;
public GraphQLCustomError(String errorCode, String message, List<SourceLocation> locations, List<Object> path,
Map<String, Object> extensions) {
this.errorCode = errorCode;
this.message = message;
this.locations = locations;
this.path = path;
this.extensions = extensions != null ? extensions : new HashMap<>();
}
@Override
public String getMessage() {
return message;
}
@Override
public List<SourceLocation> getLocations() {
return locations;
}
@Override
public List<Object> getPath() {
return path;
}
@Override
public Map<String, Object> getExtensions() {
return extensions;
}
@Override
public ErrorType getErrorType() {
return ErrorType.ValidationError;
}
public String getErrorCode() {
return errorCode;
}
}

View File

@@ -0,0 +1,36 @@
package com.sgs.exception;
import graphql.ErrorClassification;
import graphql.ErrorType;
import graphql.GraphQLError;
import graphql.language.SourceLocation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GraphQLCustomException extends RuntimeException implements GraphQLError {
private Map<String, Object> extensions = new HashMap<>();
public GraphQLCustomException(String message, String invalidField) {
super(message);
extensions.put("ErrorCode", message);
extensions.put("invalidField", invalidField);
}
@Override
public List<SourceLocation> getLocations() {
return null;
}
@Override
public Map<String, Object> getExtensions() {
return extensions;
}
@Override
public ErrorClassification getErrorType() {
return ErrorType.DataFetchingException;
}
}

View File

@@ -0,0 +1,61 @@
package com.sgs.exception;
import graphql.ExceptionWhileDataFetching;
import graphql.GraphQLError;
import graphql.kickstart.execution.error.GraphQLErrorHandler;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
@Primary // Mark this as the primary handler to resolve the conflict
public class GraphQLExceptionHandler implements GraphQLErrorHandler {
private static final Map<String, String> ERROR_MESSAGES = new HashMap<>();
static {
ERROR_MESSAGES.put("2040",
"Bu organizasyon bir veya daha fazla alanla ilişkilendirilmiş olduğu için silinemez. Önce ilişkili alanları kaldırın.");
ERROR_MESSAGES.put("2020",
"Bu organizasyon bir veya daha fazla kullanıcıyla ilişkilendirilmiş olduğu için silinemez. Önce ilişkili kullanıcıları kaldırın.");
ERROR_MESSAGES.put("2010", "Bu tag ile bir organizasyon zaten mevcut.");
ERROR_MESSAGES.put("2030", "Bu tag ile silinmiş bir organizasyon zaten mevcut.");
// Add other error codes and messages as needed
}
@Override
public List<GraphQLError> processErrors(List<GraphQLError> errors) {
return errors.stream()
.map(this::processError)
.collect(Collectors.toList());
}
private GraphQLError processError(GraphQLError error) {
if (error instanceof ExceptionWhileDataFetching exceptionError &&
exceptionError.getException() instanceof GraphQLCustomException customException) {
String errorCode = customException.getMessage();
// String errorCode = (String) customException.getExtensions().get("errorCode");
String errorMessage = ERROR_MESSAGES.getOrDefault(errorCode, "Bilinmeyen hata kodu: " + errorCode);
// Return a more informative error
return new GraphQLCustomError(
errorCode,
errorMessage,
error.getLocations(),
error.getPath(),
customException.getExtensions());
}
return error;
}
// Required by GraphQLErrorHandler interface
@Override
public boolean errorsPresent(List<GraphQLError> errors) {
return errors != null && !errors.isEmpty();
}
}

View File

@@ -0,0 +1,16 @@
package com.sgs.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class MyFileNotFoundException extends RuntimeException {
public MyFileNotFoundException(String message) {
super(message);
}
public MyFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,45 @@
package com.sgs.graphql.RelationOrganizationToOrganization.domain;
import com.sgs.graphql.organization.domain.Organization;
import com.sgs.lib.dao.domain.BaseDomain;
import javax.persistence.*;
@Entity
@Table(name = "relation_organization_to_organization")
public class OrganizationToOrganization extends BaseDomain {
private Organization parent;
private Organization child;
private boolean deleted;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id")
public Organization getParent() {
return parent;
}
public void setParent(Organization parent) {
this.parent = parent;
}
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "child_id")
public Organization getChild() {
return child;
}
public void setChild(Organization child) {
this.child = child;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}

View File

@@ -0,0 +1,10 @@
package com.sgs.graphql.RelationOrganizationToOrganization.repo;
import com.sgs.graphql.RelationOrganizationToOrganization.domain.OrganizationToOrganization;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
@Repository
public interface OrganizationToOrganizationRepo extends BaseRepo<OrganizationToOrganization> {
}

View File

@@ -0,0 +1,7 @@
package com.sgs.graphql.RelationOrganizationToOrganization.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
public class OrganizationToOrganizationCriteria extends BaseCriteria {
}

View File

@@ -0,0 +1,18 @@
package com.sgs.graphql.RelationOrganizationToOrganization.repo.criteria.spec;
import com.sgs.graphql.RelationOrganizationToOrganization.domain.OrganizationToOrganization;
import com.sgs.graphql.RelationOrganizationToOrganization.repo.criteria.OrganizationToOrganizationCriteria;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
@Component
public class OrganizationToOrganizationSpec extends BaseCriteriaSpec<OrganizationToOrganization, OrganizationToOrganizationCriteria> {
@Override
public Specification<OrganizationToOrganization> createForAll(OrganizationToOrganizationCriteria criteria) {
return null;
}
}

View File

@@ -0,0 +1,18 @@
package com.sgs.graphql.RelationOrganizationToOrganization.service;
import com.sgs.graphql.RelationOrganizationToOrganization.domain.OrganizationToOrganization;
import com.sgs.graphql.RelationOrganizationToOrganization.repo.OrganizationToOrganizationRepo;
import com.sgs.graphql.RelationOrganizationToOrganization.repo.criteria.OrganizationToOrganizationCriteria;
import com.sgs.graphql.RelationOrganizationToOrganization.repo.criteria.spec.OrganizationToOrganizationSpec;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrganizationToOrganizationService extends BaseService<OrganizationToOrganization, OrganizationToOrganizationRepo, OrganizationToOrganizationCriteria, OrganizationToOrganizationSpec> {
@Autowired
public OrganizationToOrganizationService(OrganizationToOrganizationRepo repository, OrganizationToOrganizationSpec criteriaSpec) {
super(repository, criteriaSpec);
}
}

View File

@@ -0,0 +1,56 @@
package com.sgs.graphql.RelationSurveyQuestion.domain;
import com.sgs.graphql.question.domain.Question;
import com.sgs.graphql.suvery.domain.Survey;
import com.sgs.lib.dao.domain.BaseDomain;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
@Entity
@Table(name = "relation_survey_question")
public class RelationSurveyQuestion extends BaseDomain {
private Survey survey;
private Question question;
private int orderNo;
private boolean isDeleted;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "survey_id")
public Survey getSurvey() {
return survey;
}
public void setSurvey(Survey survey) {
this.survey = survey;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "question_id")
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
@Column(name = "order_no")
public int getOrderNo() {
return orderNo;
}
public void setOrderNo(int orderNo) {
this.orderNo = orderNo;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
}

View File

@@ -0,0 +1,76 @@
package com.sgs.graphql.RelationSurveyQuestion.mutation;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.graphql.RelationSurveyQuestion.mutation.input.RelationSurveyQuestionCreateInput;
import com.sgs.graphql.RelationSurveyQuestion.mutation.input.RelationSurveyQuestionUpdateInput;
import com.sgs.graphql.RelationSurveyQuestion.mutation.mapper.RelationSurveyQuestionMapper;
import com.sgs.graphql.RelationSurveyQuestion.service.RelationSurveyQuestionService;
import graphql.kickstart.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.util.UUID;
@Validated
@Component
public class RelationSurveyQuestionMutation implements GraphQLMutationResolver {
private final RelationSurveyQuestionMapper relationSurveyQuestionMapper;
private final RelationSurveyQuestionService relationSurveyQuestionService;
@Autowired
public RelationSurveyQuestionMutation(RelationSurveyQuestionMapper relationSurveyQuestionMapper, RelationSurveyQuestionService relationSurveyQuestionService) {
this.relationSurveyQuestionMapper = relationSurveyQuestionMapper;
this.relationSurveyQuestionService = relationSurveyQuestionService;
}
public RelationSurveyQuestion addRelationSurveyQuestion(RelationSurveyQuestionCreateInput input) {
return relationSurveyQuestionService.save(relationSurveyQuestionMapper.toEntity(input));
}
public RelationSurveyQuestion updateRelationSurveyQuestion(UUID id, RelationSurveyQuestionUpdateInput input) {
return relationSurveyQuestionService.findById(id)
.map(relationSurveyQuestion -> relationSurveyQuestionService.update(relationSurveyQuestionMapper.updateEntity(relationSurveyQuestion, input)))
.orElseThrow(() -> new RuntimeException("No RelationSurveyQuestion found to update."));
}
public Boolean deleteRelationSurveyQuestion(UUID id) {
try {
RelationSurveyQuestion relationSurveyQuestion = relationSurveyQuestionService.findById(id)
.orElseThrow(() -> new RuntimeException("RelationSurveyQuestion not found ID: " + id));
if (relationSurveyQuestion != null) {
relationSurveyQuestion.setDeleted(true);
}
RelationSurveyQuestion updatedRelationSurveyQuestion = relationSurveyQuestionService.update(relationSurveyQuestion);
if (updatedRelationSurveyQuestion != null) {
return true;
}
} catch (Exception e) {
System.out.println("TODO");
}
return false;
}
// Anket içerisinde bir sorunun sıra numarasını günceller.
public RelationSurveyQuestion updateOrderNo( UUID surveyId, UUID questionId, int newOrderNo) {
// İlişkiyi veritabanından bul.
RelationSurveyQuestion relation = relationSurveyQuestionService.findBySurveyIdAndQuestionId(surveyId, questionId);
if (relation == null) {
throw new IllegalArgumentException("Relation not found");
}
relation.setOrderNo(newOrderNo);
return relation;
}
}

View File

@@ -0,0 +1,28 @@
package com.sgs.graphql.RelationSurveyQuestion.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseCreateInput;
import java.util.UUID;
public class RelationSurveyQuestionCreateInput extends BaseCreateInput {
private UUID question;
private int orderNo;
public int getOrderNo() {
return orderNo;
}
public void setOrderNo(int orderNo) {
this.orderNo = orderNo;
}
public UUID getQuestion() {
return question;
}
public void setQuestion(UUID question) {
this.question = question;
}
}

View File

@@ -0,0 +1,25 @@
package com.sgs.graphql.RelationSurveyQuestion.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseUpdateInput;
import java.util.UUID;
public class RelationSurveyQuestionUpdateInput extends BaseUpdateInput {
private UUID question;
private int orderNo;
public int getOrderNo() {
return orderNo;
}
public void setOrderNo(int orderNo) {
this.orderNo = orderNo;
}
public UUID getQuestion() {
return question;
}
public void setQuestion(UUID question) {
this.question = question;
}
}

View File

@@ -0,0 +1,39 @@
package com.sgs.graphql.RelationSurveyQuestion.mutation.mapper;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.graphql.RelationSurveyQuestion.mutation.input.RelationSurveyQuestionCreateInput;
import com.sgs.graphql.RelationSurveyQuestion.mutation.input.RelationSurveyQuestionUpdateInput;
import com.sgs.graphql.question.domain.Question;
import com.sgs.graphql.question.service.QuestionService;
import com.sgs.lib.dao.mutation.mapper.BaseCreateUpdateMapper;
import org.springframework.stereotype.Component;
@Component
public class RelationSurveyQuestionMapper extends BaseCreateUpdateMapper<RelationSurveyQuestion, RelationSurveyQuestionCreateInput, RelationSurveyQuestionUpdateInput> {
private final QuestionService questionService;
public RelationSurveyQuestionMapper(QuestionService questionService) {
this.questionService = questionService;
}
@Override
public RelationSurveyQuestion toEntity(RelationSurveyQuestionCreateInput input) {
RelationSurveyQuestion entity = new RelationSurveyQuestion();
entity.setOrderNo(input.getOrderNo());
Question question= questionService.findById(input.getQuestion()).orElse(null);
entity.setQuestion(question);
return entity;
}
@Override
public RelationSurveyQuestion updateEntity(RelationSurveyQuestion entity, RelationSurveyQuestionUpdateInput input) {
entity.setOrderNo(input.getOrderNo());
Question question= questionService.findById(input.getQuestion()).orElse(null);
entity.setQuestion(question);
return entity;
}
}

View File

@@ -0,0 +1,51 @@
package com.sgs.graphql.RelationSurveyQuestion.query;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.graphql.RelationSurveyQuestion.query.pagination.RelationSurveyQuestionPageable;
import com.sgs.graphql.RelationSurveyQuestion.repo.criteria.RelationSurveyQuestionCriteria;
import com.sgs.graphql.RelationSurveyQuestion.service.RelationSurveyQuestionService;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class RelationSurveyQuestionQueryResolver implements GraphQLQueryResolver {
private final RelationSurveyQuestionService relationSurveyQuestionService;
@Autowired
public RelationSurveyQuestionQueryResolver(RelationSurveyQuestionService relationSurveyQuestionService) {
this.relationSurveyQuestionService = relationSurveyQuestionService;
}
public RelationSurveyQuestion relationSurveyQuestion(UUID id){
return relationSurveyQuestionService.findById(id).orElse(null);
}
public List<RelationSurveyQuestion> relationSurveyQuestions(RelationSurveyQuestionCriteria criteria, List<SortBy> sortBy){
return relationSurveyQuestionService.filterWithSort(ObjectUtils.defaultIfNull(criteria, new RelationSurveyQuestionCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy,new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
}
public RelationSurveyQuestionPageable paginateRelationSurveyQuestions(Pagination pagination, RelationSurveyQuestionCriteria criteria , List<SortBy> sortBy){
return new RelationSurveyQuestionPageable(relationSurveyQuestionService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria,new RelationSurveyQuestionCriteria()),
Pagination.toPageRequest(pagination,sortBy)));
}
}

View File

@@ -0,0 +1,12 @@
package com.sgs.graphql.RelationSurveyQuestion.query.pagination;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class RelationSurveyQuestionPageable extends PaginationResult<RelationSurveyQuestion> {
public RelationSurveyQuestionPageable(Page<RelationSurveyQuestion> page) {
super(page);
}
}

View File

@@ -0,0 +1,14 @@
package com.sgs.graphql.RelationSurveyQuestion.repo;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
@Repository
public interface RelationSurveyQuestionRepo extends BaseRepo<RelationSurveyQuestion> {
}

View File

@@ -0,0 +1,16 @@
package com.sgs.graphql.RelationSurveyQuestion.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
public class RelationSurveyQuestionCriteria extends BaseCriteria {
private int orderNo;
public int getOrderNo() {
return orderNo;
}
public void setOrderNo(int orderNo) {
this.orderNo = orderNo;
}
}

View File

@@ -0,0 +1,17 @@
package com.sgs.graphql.RelationSurveyQuestion.repo.criteria.spec;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.graphql.RelationSurveyQuestion.repo.criteria.RelationSurveyQuestionCriteria;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
@Component
public class RelationSurveyQuestionSpec extends BaseCriteriaSpec<RelationSurveyQuestion, RelationSurveyQuestionCriteria> {
@Override
public Specification<RelationSurveyQuestion> createForAll(RelationSurveyQuestionCriteria criteria) {
return null;
}
}

View File

@@ -0,0 +1,38 @@
package com.sgs.graphql.RelationSurveyQuestion.service;
import com.sgs.graphql.RelationSurveyQuestion.domain.RelationSurveyQuestion;
import com.sgs.graphql.RelationSurveyQuestion.repo.RelationSurveyQuestionRepo;
import com.sgs.graphql.RelationSurveyQuestion.repo.criteria.RelationSurveyQuestionCriteria;
import com.sgs.graphql.RelationSurveyQuestion.repo.criteria.spec.RelationSurveyQuestionSpec;
import com.sgs.graphql.question.domain.Question;
import com.sgs.graphql.suvery.domain.Survey;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.UUID;
@Service
public class RelationSurveyQuestionService extends BaseService<RelationSurveyQuestion, RelationSurveyQuestionRepo, RelationSurveyQuestionCriteria, RelationSurveyQuestionSpec> {
@Autowired
public RelationSurveyQuestionService(RelationSurveyQuestionRepo repository, RelationSurveyQuestionSpec criteriaSpec) {
super(repository, criteriaSpec);
}
public RelationSurveyQuestion findBySurveyIdAndQuestionId(UUID surveyId, UUID questionId) {
RelationSurveyQuestion relation = findBySurveyIdAndQuestionId(surveyId, questionId);
return relation;
}
public Optional<RelationSurveyQuestion> findBySurveyAndQuestion(Survey survey, Question question) {
return findBySurveyAndQuestion(survey, question);
}
}

View File

@@ -0,0 +1,53 @@
package com.sgs.graphql.activitySubUnit.domain;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.sgs.graphql.subSector.domain.SubSector;
import com.sgs.lib.dao.domain.BaseDomain;
import javax.persistence.*;
@Entity
@Table(name = "activity_sub_unit")
public class ActivitySubUnit extends BaseDomain {
private String tag;
private String description;
private boolean deleted;
private SubSector subSector;
@Column(name = "tag", nullable = false)
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "is_deleted", nullable = false)
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
@ManyToOne(fetch = FetchType.EAGER)
@JsonBackReference
public SubSector getSubSector() {
return subSector;
}
public void setSubSector(SubSector subSector) {
this.subSector = subSector;
}
}

View File

@@ -0,0 +1,31 @@
package com.sgs.graphql.activitySubUnit.dto;
public class ActivitySubUnitDto {
private String tag;
private String description;
private boolean deleted;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}

View File

@@ -0,0 +1,49 @@
package com.sgs.graphql.activitySubUnit.query;
import com.sgs.graphql.activitySubUnit.query.pagination.ActivitySubUnitPageable;
import com.sgs.graphql.activitySubUnit.domain.ActivitySubUnit;
import com.sgs.graphql.activitySubUnit.repo.criteria.ActivitySubUnitCriteria;
import com.sgs.graphql.activitySubUnit.service.ActivitySubUnitService;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class ActivitySubUnitQueryResolver implements GraphQLQueryResolver {
private final ActivitySubUnitService activitySubUnitService;
@Autowired
public ActivitySubUnitQueryResolver(ActivitySubUnitService activitySubUnitService) {
this.activitySubUnitService = activitySubUnitService;
}
public ActivitySubUnit activitySubUnit(UUID id) {
return activitySubUnitService.findById(id).orElse(null);
}
@PreAuthorize("hasAuthority('" + PermissionName.ACTIVITY_SUB_UNITS_GET + "')")
public List<ActivitySubUnit> activitySubUnits(ActivitySubUnitCriteria criteria, List<SortBy> sortBy) {
return activitySubUnitService.filterWithSort(ObjectUtils.defaultIfNull(criteria, new ActivitySubUnitCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy, new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
}
public ActivitySubUnitPageable paginateActivitySubUnits(Pagination pagination, ActivitySubUnitCriteria criteria, List<SortBy> sortBy) {
return new ActivitySubUnitPageable(activitySubUnitService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria, new ActivitySubUnitCriteria()),
Pagination.toPageRequest(pagination, sortBy)));
}
}

View File

@@ -0,0 +1,11 @@
package com.sgs.graphql.activitySubUnit.query.pagination;
import com.sgs.graphql.activitySubUnit.domain.ActivitySubUnit;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class ActivitySubUnitPageable extends PaginationResult<ActivitySubUnit> {
public ActivitySubUnitPageable(Page<ActivitySubUnit> page) {
super(page);
}
}

View File

@@ -0,0 +1,12 @@
package com.sgs.graphql.activitySubUnit.repo;
import com.sgs.graphql.activitySubUnit.domain.ActivitySubUnit;
import com.sgs.graphql.subSector.domain.SubSector;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
@Repository
public interface ActivitySubUnitRepo extends BaseRepo<ActivitySubUnit> {
ActivitySubUnit findByTag(String tag);
ActivitySubUnit findByTagAndSubSector(String tag, SubSector subSector);
}

View File

@@ -0,0 +1,6 @@
package com.sgs.graphql.activitySubUnit.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
public class ActivitySubUnitCriteria extends BaseCriteria {
}

View File

@@ -0,0 +1,16 @@
package com.sgs.graphql.activitySubUnit.repo.criteria.spec;
import com.sgs.graphql.activitySubUnit.domain.ActivitySubUnit;
import com.sgs.graphql.activitySubUnit.repo.criteria.ActivitySubUnitCriteria;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
@Component
public class ActivitySubUnitCriteriaSpec extends BaseCriteriaSpec<ActivitySubUnit, ActivitySubUnitCriteria> {
@Override
public Specification<ActivitySubUnit> createForAll(ActivitySubUnitCriteria criteria) {
return null;
}
}

View File

@@ -0,0 +1,18 @@
package com.sgs.graphql.activitySubUnit.service;
import com.sgs.graphql.activitySubUnit.domain.ActivitySubUnit;
import com.sgs.graphql.activitySubUnit.repo.ActivitySubUnitRepo;
import com.sgs.graphql.activitySubUnit.repo.criteria.ActivitySubUnitCriteria;
import com.sgs.graphql.activitySubUnit.repo.criteria.spec.ActivitySubUnitCriteriaSpec;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ActivitySubUnitService extends BaseService<ActivitySubUnit, ActivitySubUnitRepo, ActivitySubUnitCriteria, ActivitySubUnitCriteriaSpec> {
@Autowired
public ActivitySubUnitService(ActivitySubUnitRepo repository, ActivitySubUnitCriteriaSpec criteriaSpec) {
super(repository, criteriaSpec);
}
}

View File

@@ -0,0 +1,78 @@
package com.sgs.graphql.answer.domain;
import com.sgs.graphql.relationQuestionAnswer.domain.RelationQuestionAnswer;
import com.sgs.lib.dao.domain.BaseDomain;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "answer")
public class Answer extends BaseDomain {
private String value;
private String answer;
private LocalDateTime createdAt;
private boolean isDeleted;
private boolean isDefault;
private List<RelationQuestionAnswer> relationQuestionAnswers = new ArrayList<>();
@OneToMany(mappedBy = "answer", cascade = CascadeType.ALL, orphanRemoval = true)
public List<RelationQuestionAnswer> getRelationQuestionAnswers() {
return relationQuestionAnswers;
}
public void setRelationQuestionAnswers(List<RelationQuestionAnswer> relationQuestionAnswers) {
this.relationQuestionAnswers = relationQuestionAnswers;
}
@Column(nullable = false)
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Column(
name = "answer",
columnDefinition = "text",
nullable = true
)
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
@Column(nullable = false)
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public boolean isDefault() {
return isDefault;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
@Column(nullable = false)
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
}

View File

@@ -0,0 +1,69 @@
package com.sgs.graphql.answer.mutation;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.graphql.answer.mutation.input.AnswerCreateInput;
import com.sgs.graphql.answer.mutation.input.AnswerUpdateInput;
import com.sgs.graphql.answer.mutation.mapper.AnswerMapper;
import com.sgs.graphql.answer.service.AnswerService;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.graphql.systemHistory.mutation.SystemLogger;
import graphql.kickstart.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.util.UUID;
@Validated
@Component
public class AnswerMutation implements GraphQLMutationResolver {
private final AnswerService answerService;
private final AnswerMapper answerMapper;
private SystemLogger systemLogger;
@Autowired
public AnswerMutation(AnswerService answerService, AnswerMapper answerMapper) {
this.answerService = answerService;
this.answerMapper = answerMapper;
}
@PreAuthorize("hasAuthority('" + PermissionName.ANSWER_CREATE + "')")
public Answer addAnswer(AnswerCreateInput input) {
return answerService.save(answerMapper.toEntity(input));
}
@PreAuthorize("hasAuthority('" + PermissionName.ANSWER_UPDATE + "')")
public Answer updateAnswer(UUID id, AnswerUpdateInput input) {
return answerService.findById(id)
.map(answer -> answerService.update(answerMapper.updateEntity(answer, input)))
.orElseThrow(() -> new RuntimeException("No answer found to update."));
}
@PreAuthorize("hasAuthority('" + PermissionName.ANSWER_DELETE + "')")
public Boolean deleteAnswer(UUID id) {
try {
Answer answer = answerService.findById(id)
.orElseThrow(() -> new RuntimeException("Answer not found ID: " + id));
if (answer != null) {
answer.setDeleted(true);
}
Answer updatedAnswer = answerService.update(answer);
if (updatedAnswer != null) {
return true;
}
} catch (Exception e) {
System.out.println("TODO");
}
return false;
}
}

View File

@@ -0,0 +1,30 @@
package com.sgs.graphql.answer.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseCreateInput;
import java.util.List;
import java.util.UUID;
public class AnswerCreateInput extends BaseCreateInput {
private String value;
private String answer;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}

View File

@@ -0,0 +1,27 @@
package com.sgs.graphql.answer.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseUpdateInput;
public class AnswerUpdateInput extends BaseUpdateInput {
private String value;
private String answer;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}

View File

@@ -0,0 +1,36 @@
package com.sgs.graphql.answer.mutation.mapper;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.graphql.answer.mutation.input.AnswerCreateInput;
import com.sgs.graphql.answer.mutation.input.AnswerUpdateInput;
import com.sgs.lib.dao.mutation.mapper.BaseCreateUpdateMapper;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
public class AnswerMapper extends BaseCreateUpdateMapper<Answer, AnswerCreateInput, AnswerUpdateInput> {
public AnswerMapper() {
}
@Override
public Answer toEntity(AnswerCreateInput input) {
Answer entity = new Answer();
entity.setValue(input.getValue());
entity.setAnswer(input.getAnswer());
entity.setCreatedAt(LocalDateTime.now());
return entity;
}
@Override
public Answer updateEntity(Answer entity, AnswerUpdateInput input) {
entity.setValue(input.getValue());
entity.setAnswer(input.getAnswer());
entity.setCreatedAt(LocalDateTime.now());
return entity;
}
}

View File

@@ -0,0 +1,53 @@
package com.sgs.graphql.answer.query;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.graphql.answer.query.pagination.AnswerPageable;
import com.sgs.graphql.answer.repo.criteria.AnswerCriteria;
import com.sgs.graphql.answer.service.AnswerService;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class AnswerQueryResolver implements GraphQLQueryResolver {
private final AnswerService answerService;
@Autowired
public AnswerQueryResolver(AnswerService answerService) {
this.answerService = answerService;
}
public Answer answer(UUID id) {
return answerService.findById(id).orElse(null);
}
public List<Answer> answers(AnswerCriteria criteria, List<SortBy> sortBy) {
return answerService.filterWithSort(ObjectUtils.defaultIfNull(criteria, new AnswerCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy, new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
}
@PreAuthorize("hasAuthority('" + PermissionName.PAGINATE_ANSWERS_GET + "')")
public AnswerPageable paginateAnswers(Pagination pagination, AnswerCriteria criteria, List<SortBy> sortBy) {
return new AnswerPageable(answerService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria, new AnswerCriteria()),
Pagination.toPageRequest(pagination, sortBy)));
}
}

View File

@@ -0,0 +1,12 @@
package com.sgs.graphql.answer.query.pagination;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class AnswerPageable extends PaginationResult<Answer> {
public AnswerPageable(Page<Answer> page) {
super(page);
}
}

View File

@@ -0,0 +1,10 @@
package com.sgs.graphql.answer.repo;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
@Repository
public interface AnswerRepo extends BaseRepo<Answer> {
}

View File

@@ -0,0 +1,15 @@
package com.sgs.graphql.answer.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
public class AnswerCriteria extends BaseCriteria {
private boolean deleted;
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}

View File

@@ -0,0 +1,19 @@
package com.sgs.graphql.answer.repo.criteria.spec;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.graphql.answer.repo.criteria.AnswerCriteria;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
@Component
public class AnswerCriteriaSpec extends BaseCriteriaSpec<Answer, AnswerCriteria> {
public static Specification<Answer> deleted(boolean deleted){
return (Specification<Answer>) (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("deleted"), deleted);
}
@Override
public Specification<Answer> createForAll(AnswerCriteria criteria) {
return Specification.where(deleted(criteria.isDeleted()));
}
}

View File

@@ -0,0 +1,16 @@
package com.sgs.graphql.answer.service;
import com.sgs.graphql.answer.domain.Answer;
import com.sgs.graphql.answer.repo.AnswerRepo;
import com.sgs.graphql.answer.repo.criteria.AnswerCriteria;
import com.sgs.graphql.answer.repo.criteria.spec.AnswerCriteriaSpec;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AnswerService extends BaseService<Answer, AnswerRepo, AnswerCriteria, AnswerCriteriaSpec> {
@Autowired
public AnswerService(AnswerRepo repository, AnswerCriteriaSpec criteriaSpec) {
super(repository, criteriaSpec);
}
}

View File

@@ -0,0 +1,137 @@
package com.sgs.graphql.area.domain;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.district.domain.District;
import com.sgs.graphql.neighborhood.domain.Neighborhood;
import com.sgs.graphql.organization.domain.Organization;
import com.sgs.graphql.dataCenter.domain.DataCenter;
import com.sgs.lib.dao.domain.BaseDomain;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
// import io.leangen.graphql.annotations.GraphQLQuery;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Entity
@Table(name = "areas")
public class Area extends BaseDomain {
private String tag;
private List<Country> countries = new ArrayList<>();
private List<City> cities = new ArrayList<>();
private List<District> districts = new ArrayList<>();
private List<Neighborhood> neighborhoods = new ArrayList<>();
private List<Organization> organizations;
private List<DataCenter> dataCenters;
private boolean isDeleted;
private boolean defaultArea;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
public List<Country> getCountries() {
return countries;
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "area_city")
@JsonManagedReference("area-city")
public List<City> getCities() {
return cities;
}
public void setCities(List<City> cities) {
this.cities = cities;
}
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "area_district")
@JsonManagedReference("area-district")
public List<District> getDistricts() {
return districts;
}
public void setDistricts(List<District> districts) {
this.districts = districts;
}
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
public List<Neighborhood> getNeighborhoods() {
return neighborhoods;
}
public void setNeighborhoods(List<Neighborhood> neighborhoods) {
this.neighborhoods = neighborhoods;
}
@JsonProperty("isDeleted")
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
@JsonProperty("defaultArea")
public boolean isDefaultArea() {
return defaultArea;
}
public void setDefaultArea(boolean defaultArea) {
this.defaultArea = defaultArea;
}
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "areas")
public List<Organization> getOrganizations() {
return organizations;
}
public void setOrganizations(List<Organization> organizations) {
this.organizations = organizations;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "area", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference("area-datacenter")
public List<DataCenter> getDataCenters() {
return dataCenters;
}
public void setDataCenters(List<DataCenter> dataCenters) {
this.dataCenters = dataCenters;
}
@Transient
public List<String> getCityNames() {
return cities == null ? new ArrayList<>() :
cities.stream().map(City::getName).collect(Collectors.toList());
}
@Transient
public List<String> getDistrictNames() {
return districts == null ? new ArrayList<>() :
districts.stream().map(District::getName).collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,63 @@
package com.sgs.graphql.area.mutation;
import com.sgs.graphql.area.mutation.mapper.AreaMapper;
import com.sgs.graphql.area.service.AreaService;
import com.sgs.graphql.area.domain.Area;
import com.sgs.graphql.area.mutation.input.AreaCreateInput;
import com.sgs.graphql.area.mutation.input.AreaUpdateInput;
import com.sgs.graphql.permission.domain.PermissionName;
import graphql.kickstart.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.UUID;
@Validated
@Component
public class AreaMutation implements GraphQLMutationResolver {
private final AreaService areaService;
private final AreaMapper areaMapper;
@Autowired
public AreaMutation(AreaService areaService, AreaMapper areaMapper) {
this.areaService = areaService;
this.areaMapper = areaMapper;
}
@PreAuthorize("hasAuthority('" + PermissionName.AREA_CREATE + "')")
public Area createArea(AreaCreateInput input) {
return areaService.save(areaMapper.toEntity(input));
}
@PreAuthorize("hasAuthority('" + PermissionName.AREA_UPDATE + "')")
public Area updateArea(UUID id, AreaUpdateInput input) {
return areaService.findById(id)
.map(area -> areaService.update(areaMapper.updateEntity(area, input)))
.orElseThrow(RuntimeException::new);
}
@PreAuthorize("hasAuthority('" + PermissionName.AREA_DELETE + "')")
public Boolean deleteArea(UUID id) {
try {
Area area = areaService.findById(id)
.orElseThrow(() -> new RuntimeException("Bulunamayan alan (Area) ID: " + id));
if (area != null) {
area.setDeleted(true);
}
Area updatedArea = areaService.update(area);
if (updatedArea != null) {
return true;
}
} catch (Exception e) {
System.out.println("TODO");
}
return false;
}
}

View File

@@ -0,0 +1,54 @@
package com.sgs.graphql.area.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseCreateInput;
import java.util.List;
import java.util.UUID;
public class AreaCreateInput extends BaseCreateInput {
private String tag;
private List<UUID> countries;
private List<UUID> cities;
private List<UUID> districts;
private List<UUID> neighborhoods;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public List<UUID> getCountries() {
return countries;
}
public void setCountries(List<UUID> countries) {
this.countries = countries;
}
public List<UUID> getCities() {
return cities;
}
public void setCities(List<UUID> cities) {
this.cities = cities;
}
public List<UUID> getDistricts() {
return districts;
}
public void setDistricts(List<UUID> districts) {
this.districts = districts;
}
public List<UUID> getNeighborhoods() {
return neighborhoods;
}
public void setNeighborhoods(List<UUID> neighborhoods) {
this.neighborhoods = neighborhoods;
}
}

View File

@@ -0,0 +1,53 @@
package com.sgs.graphql.area.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseUpdateInput;
import java.util.List;
import java.util.UUID;
public class AreaUpdateInput extends BaseUpdateInput {
private String tag;
private List<UUID> countries;
private List<UUID> cities;
private List<UUID> districts;
private List<UUID> neighborhoods;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public List<UUID> getCountries() {
return countries;
}
public void setCountries(List<UUID> countries) {
this.countries = countries;
}
public List<UUID> getCities() {
return cities;
}
public void setCities(List<UUID> cities) {
this.cities = cities;
}
public List<UUID> getDistricts() {
return districts;
}
public void setDistricts(List<UUID> districts) {
this.districts = districts;
}
public List<UUID> getNeighborhoods() {
return neighborhoods;
}
public void setNeighborhoods(List<UUID> neighborhoods) {
this.neighborhoods = neighborhoods;
}
}

View File

@@ -0,0 +1,122 @@
package com.sgs.graphql.area.mutation.mapper;
import com.sgs.graphql.area.mutation.input.AreaCreateInput;
import com.sgs.graphql.area.domain.Area;
import com.sgs.graphql.area.mutation.input.AreaUpdateInput;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.city.service.CityService;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.country.service.CountryService;
import com.sgs.graphql.district.domain.District;
import com.sgs.graphql.district.service.DistrictService;
import com.sgs.graphql.neighborhood.domain.Neighborhood;
import com.sgs.graphql.neighborhood.service.NeighborhoodService;
import com.sgs.lib.dao.mutation.mapper.BaseCreateUpdateMapper;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class AreaMapper extends BaseCreateUpdateMapper<Area, AreaCreateInput, AreaUpdateInput> {
private final CityService cityService;
private final NeighborhoodService neighborhoodService;
private final CountryService countryService;
private final DistrictService districtService;
public AreaMapper( CityService cityService, NeighborhoodService neighborhoodService, CountryService countryService, DistrictService districtService) {
this.cityService = cityService;
this.neighborhoodService = neighborhoodService;
this.countryService = countryService;
this.districtService = districtService;
}
@Override
public Area toEntity(AreaCreateInput input) {
Area entity = new Area();
entity.setTag(input.getTag());
if (input.getCountries() != null) {
List<Country> countries = new ArrayList<>();
for (int i = 0; i < input.getCountries().size(); i++) {
Country country = countryService.findById(input.getCountries().get(i)).orElse(null);
countries.add(country);
}
entity.setCountries(countries);
}
if (input.getCities() != null) {
List<City> cities = new ArrayList<>();
for (int i = 0; i < input.getCities().size(); i++) {
City city = cityService.findById(input.getCities().get(i)).orElse(null);
cities.add(city);
}
entity.setCities(cities);
}
if (input.getDistricts() != null) {
List<District> districts = new ArrayList<>();
for (int i = 0; i < input.getDistricts().size(); i++) {
District district = districtService.findById(input.getDistricts().get(i)).orElse(null);
districts.add(district);
}
entity.setDistricts(districts);
}
if (input.getNeighborhoods() != null) {
List<Neighborhood> neighborhoods = new ArrayList<>();
for (int i = 0; i < input.getNeighborhoods().size(); i++) {
Neighborhood neighborhood = neighborhoodService.findById(input.getNeighborhoods().get(i)).orElse(null);
neighborhoods.add(neighborhood);
}
entity.setNeighborhoods(neighborhoods);
}
return entity;
}
@Override
public Area updateEntity(Area entity, AreaUpdateInput input) {
//Area entity = new Area();
entity.setTag(input.getTag());
if (input.getCountries() != null) {
List<Country> countries = new ArrayList<>();
for (int i = 0; i < input.getCountries().size(); i++) {
Country country = countryService.findById(input.getCountries().get(i)).orElse(null);
countries.add(country);
}
entity.setCountries(countries);
}
if (input.getCities() != null) {
List<City> cities = new ArrayList<>();
for (int i = 0; i < input.getCities().size(); i++) {
City city = cityService.findById(input.getCities().get(i)).orElse(null);
cities.add(city);
}
entity.setCities(cities);
}
if (input.getDistricts() != null) {
List<District> districts = new ArrayList<>();
for (int i = 0; i < input.getDistricts().size(); i++) {
District district = districtService.findById(input.getDistricts().get(i)).orElse(null);
districts.add(district);
}
entity.setDistricts(districts);
}
if (input.getNeighborhoods() != null) {
List<Neighborhood> neighborhoods = new ArrayList<>();
for (int i = 0; i < input.getNeighborhoods().size(); i++) {
Neighborhood neighborhood = neighborhoodService.findById(input.getNeighborhoods().get(i)).orElse(null);
neighborhoods.add(neighborhood);
}
entity.setNeighborhoods(neighborhoods);
}
return entity;
}
}

View File

@@ -0,0 +1,53 @@
package com.sgs.graphql.area.query;
import com.sgs.graphql.area.query.pagination.AreaPageable;
import com.sgs.graphql.area.domain.Area;
import com.sgs.graphql.area.repo.criteria.AreaCriteria;
import com.sgs.graphql.area.service.AreaService;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.district.domain.District;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class AreaQueryResolver implements GraphQLQueryResolver {
private final AreaService areaService;
@Autowired
public AreaQueryResolver(AreaService areaService) {
this.areaService = areaService;
}
public Area area(UUID id) {
return areaService.findById(id).orElse(null);
}
public List<Area> areas(AreaCriteria criteria, List<SortBy> sortBy) {
return areaService.filterWithSort(ObjectUtils.defaultIfNull(criteria, new AreaCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy, new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
}
@PreAuthorize("hasAuthority('" + PermissionName.PAGINATE_AREAS_GET + "')")
public AreaPageable paginateAreas(Pagination pagination, AreaCriteria criteria, List<SortBy> sortBy) {
return new AreaPageable(areaService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria, new AreaCriteria()),
Pagination.toPageRequest(pagination, sortBy)));
}
}

View File

@@ -0,0 +1,12 @@
package com.sgs.graphql.area.query.pagination;
import com.sgs.graphql.area.domain.Area;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class AreaPageable extends PaginationResult<Area> {
public AreaPageable(Page<Area> page) {
super(page);
}
}

View File

@@ -0,0 +1,11 @@
package com.sgs.graphql.area.repo;
import com.sgs.graphql.area.domain.Area;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface AreaRepo extends BaseRepo<Area> {
Optional<Area> findByTag(String tag);
}

View File

@@ -0,0 +1,38 @@
package com.sgs.graphql.area.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
public class AreaCriteria extends BaseCriteria {
private String tag;
private UUID organizations;
private boolean deleted;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public UUID getOrganizations() {
return organizations;
}
public void setOrganizations(UUID organizations) {
this.organizations = organizations;
}
@JsonProperty("deleted")
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}

View File

@@ -0,0 +1,31 @@
package com.sgs.graphql.area.repo.criteria.spec;
import com.sgs.graphql.area.domain.Area;
import com.sgs.graphql.area.repo.criteria.AreaCriteria;
import com.sgs.graphql.organization.domain.Organization;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class AreaCriteriaSpec extends BaseCriteriaSpec<Area, AreaCriteria> {
public static Specification<Area> tag(String tag){
return (tag == null || tag.trim().length() == 0) ? null : (Specification<Area>) (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("tag"), "%" + tag + "%");
}
public static Specification<Area> organizations(UUID organizations) {
return (organizations == null) ? null : (Specification<Area>) (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.join("organizations").get("id"), organizations);
}
public static Specification<Area> deleted(boolean deleted) {
return (Specification<Area>) (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("deleted"), deleted);
}
@Override
public Specification<Area> createForAll(AreaCriteria criteria) {
return Specification.where(organizations(criteria.getOrganizations())).and(deleted(criteria.isDeleted()));
}
}

View File

@@ -0,0 +1,16 @@
package com.sgs.graphql.area.service;
import com.sgs.graphql.area.domain.Area;
import com.sgs.graphql.area.repo.AreaRepo;
import com.sgs.graphql.area.repo.criteria.AreaCriteria;
import com.sgs.graphql.area.repo.criteria.spec.AreaCriteriaSpec;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AreaService extends BaseService<Area, AreaRepo, AreaCriteria, AreaCriteriaSpec> {
@Autowired
public AreaService(AreaRepo repository, AreaCriteriaSpec criteriaSpec) {
super(repository, criteriaSpec);
}
}

View File

@@ -0,0 +1,72 @@
package com.sgs.graphql.auth.domain;
import com.sgs.graphql.role.domain.Role;
import com.sgs.graphql.user.domain.User;
import com.sgs.lib.dao.domain.BaseDomain;
import java.util.UUID;
public class JwtResponse extends BaseDomain {
private String accessToken;
private String type = "Bearer";
private UUID uid;
private Role role ;
private String email;
private String description;
private final User user;
public JwtResponse(String accessToken, UUID uid, Role role, String email, User user, String description) {
this.accessToken = accessToken;
this.uid = uid;
this.role = role;
this.email = email;
this.user = user;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getTokenType() {
return type;
}
public void setTokenType(String tokenType) {
this.type = tokenType;
}
public UUID getUid() {
return uid;
}
public void setUid(UUID uid) {
this.uid = uid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User getUser() {
return user;
}
}

View File

@@ -0,0 +1,42 @@
package com.sgs.graphql.auth.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final Map<String, Object> body = new HashMap<>();
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
body.put("error", "Unauthorized");
body.put("message", authException.getMessage());
body.put("path", request.getServletPath());
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
}
}

View File

@@ -0,0 +1,66 @@
package com.sgs.graphql.auth.jwt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
public class JwtAuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private JwtUserDetailsService userDetailsService;
private static final String BEARER = "Bearer";
private static final Logger logger = LoggerFactory.getLogger(JwtAuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
try {
String jwtToken = parseJwt(request);
if (StringUtils.hasText(jwtToken)&&jwtTokenProvider.validateToken(jwtToken)){
UUID userId = jwtTokenProvider.getUserIdFromJwt(jwtToken);
UserDetails userDetails = jwtTokenProvider.getUserDetailsFromJwt(jwtToken);
request.setAttribute("userId", userId);
request.setAttribute("token",jwtToken);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails,null,
userDetails.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring("Bearer".length()+1);
}
return null;
}
}

View File

@@ -0,0 +1,149 @@
package com.sgs.graphql.auth.jwt;
import com.sgs.graphql.role.domain.Role;
import com.sgs.graphql.user.domain.User;
import com.sgs.graphql.user.repo.UserRepo;
import graphql.kickstart.servlet.context.DefaultGraphQLServletContext;
import graphql.schema.DataFetchingEnvironment;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
public class JwtTokenProvider implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);
private final UserRepo userRepo;
@Value("${security.jwt.token.secret-key}")
private String APP_SECRET;
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
public JwtTokenProvider(UserRepo userRepo) {
this.userRepo = userRepo;
}
public String generateJwtAccessToken(Authentication authentication) {
JwtUserDetailsImpl userPrincipal = (JwtUserDetailsImpl) authentication.getPrincipal();
User user = userRepo.findByEmail(userPrincipal.getEmail()).orElse(null);
return Jwts.builder()
.setSubject(userPrincipal.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) //1 gün
.claim("id", user.getId().toString())
.claim("role", user.getRole().getTag())
.claim("user", user.getFirstName())
.signWith(SignatureAlgorithm.HS512, APP_SECRET)
.compact();
}
public String generateTokenFromUsername(String username) {
User user = userRepo.findByEmail(username).orElseThrow(() -> new RuntimeException("User not found "));
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) // 1 gün
.claim("id", user.getId().toString())
.claim("role", user.getRole().getTag())
.claim("user", user.getFirstName())
.signWith(SignatureAlgorithm.HS512, APP_SECRET)
.compact();
}
public String getUserNameFromJwt(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(APP_SECRET).setSigningKey(token);
return !isTokenExpired(token);
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
private boolean isTokenExpired(String token) {
Date expiration = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody().getExpiration();
return expiration.before(new Date());
}
public UUID getUserIdFromJwt(String jwtToken) {
Claims claim = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken).getBody();
return UUID.fromString(claim.get("id", String.class));
}
public List<Role> getRoleFromJwt(String jwtToken) {
Claims claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken).getBody();
return claims.get("roles", List.class);
}
public UserDetails getUserDetailsFromJwt(String jwtToken) {
String username = getUserNameFromJwt(jwtToken);
UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
return userDetails;
}
public static String getAttribute(DataFetchingEnvironment environment, String key) {
if (environment == null) {
return null;
}
DefaultGraphQLServletContext context = environment.getContext();
Object attribute = context.getHttpServletRequest().getAttribute(key);
return attribute != null ? attribute.toString() : null;
}
public static String getHeader(DataFetchingEnvironment environment, String key) {
if (environment == null) {
return null;
}
DefaultGraphQLServletContext context = environment.getContext();
return context.getHttpServletRequest().getHeader(key);
}
public static String getRemoteHost(DataFetchingEnvironment environment) {
if (environment == null) {
return null;
}
DefaultGraphQLServletContext context = environment.getContext();
return context.getHttpServletRequest().getRemoteHost();
}
}

View File

@@ -0,0 +1,104 @@
package com.sgs.graphql.auth.jwt;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sgs.graphql.user.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
public class JwtUserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private UUID id;
private String username;
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public JwtUserDetailsImpl(UUID id,
String email,
String password,
Collection<? extends GrantedAuthority> authorities){
this.id = id;
this.username = email;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static JwtUserDetailsImpl build(User user) {
List<GrantedAuthority> authorities = user.getRole().getPermissions()
.stream()
.map(permission -> new SimpleGrantedAuthority(permission.getAuthority()))
.collect(Collectors.toList());
return new JwtUserDetailsImpl(
user.getId(),
user.getEmail(),
user.getPassword(),
authorities);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public UUID getId() {
return id;
}
public String getEmail() {
return email;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
JwtUserDetailsImpl user = (JwtUserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}

View File

@@ -0,0 +1,30 @@
package com.sgs.graphql.auth.jwt;
import com.sgs.graphql.user.domain.User;
import com.sgs.graphql.user.repo.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class JwtUserDetailsService implements UserDetailsService {
private UserRepo userRepo;
@Autowired
public JwtUserDetailsService(UserRepo userRepo) {
this.userRepo = userRepo;
}
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return JwtUserDetailsImpl.build(user);
}
}

View File

@@ -0,0 +1,72 @@
package com.sgs.graphql.auth.mutation;
import com.sgs.exception.GraphQLCustomException;
import com.sgs.graphql.auth.domain.JwtResponse;
import com.sgs.graphql.auth.mutation.input.AuthLoginInput;
import com.sgs.graphql.user.domain.User;
import com.sgs.graphql.user.repo.UserRepo;
import com.sgs.graphql.auth.jwt.*;
import com.sgs.exception.CustomException;
import com.sgs.graphql.user.service.UserService;
import graphql.kickstart.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.time.LocalDateTime;
@Component
@Validated
public class AuthMutation implements GraphQLMutationResolver {
private final AuthenticationManager authenticationManager;
private final UserRepo userRepo;
private final UserService userService;
private final JwtTokenProvider jwtTokenProvider;
@Autowired
public AuthMutation(AuthenticationManager authenticationManager, UserRepo userRepo, UserService userService, JwtTokenProvider jwtTokenProvider) {
this.authenticationManager = authenticationManager;
this.userRepo = userRepo;
this.userService = userService;
this.jwtTokenProvider = jwtTokenProvider;
}
public JwtResponse login(AuthLoginInput input) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(input.getEmail(), input.getPassword());
Authentication authentication = authenticationManager.authenticate(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtTokenProvider.generateJwtAccessToken(authentication);
User user = userRepo.findByEmail(input.getEmail())
.orElseThrow(
() -> new CustomException(
String.format("User %s does not exist", input.getEmail()),
HttpStatus.BAD_REQUEST)
);
if (user.isDelete()) {
throw new GraphQLCustomException("1010", "Silinmiş kullanıcı");
}
JwtUserDetailsImpl userDetails = (JwtUserDetailsImpl) authentication.getPrincipal();
JwtResponse jwtResponse = new JwtResponse(
token,
userDetails.getId(),
user.getRole(),
userDetails.getEmail(),
user,
"Logged in");
if (!jwtResponse.getAccessToken().isEmpty()) {
user.setLastLoginTime(LocalDateTime.now());
userService.update(user);
}
return jwtResponse;
}
}

View File

@@ -0,0 +1,23 @@
package com.sgs.graphql.auth.mutation.input;
public class AuthLoginInput {
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@@ -0,0 +1,16 @@
package com.sgs.graphql.auth.service;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class AuthorizationService {
public boolean hasPermission(String permission) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(permission));
}
}

View File

@@ -0,0 +1,105 @@
package com.sgs.graphql.city.domain;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.sgs.graphql.area.domain.Area;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.district.domain.District;
import com.sgs.graphql.mainDataTable.domain.MainDataTable;
import com.sgs.lib.dao.domain.BaseDomain;
import javax.persistence.*;
import java.util.*;
@Entity
@Table(name = "city")
public class City extends BaseDomain {
private String name;
private Country country;
private String coordinates;
private boolean isDeleted = false;
private boolean defaultCity;
private Set<District> districts = new HashSet<>();
private List<Area> areas = new ArrayList<>();
private List<MainDataTable> mainDataTables = new ArrayList<>();
@OneToMany(mappedBy = "city", fetch = FetchType.EAGER)
@JsonManagedReference("city-districts")
public Set<District> getDistricts() {
return districts;
}
public void setDistricts(Set<District> districts) {
this.districts = districts;
}
@Column(nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(nullable = false)
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
@Column(nullable = false)
public boolean isDefaultCity() {
return defaultCity;
}
public void setDefaultCity(boolean defaultCity) {
this.defaultCity = defaultCity;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false)
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
@Column(columnDefinition = "text")
public String getCoordinates() {
return coordinates;
}
@Convert(converter = JsonToStringConverter.class)
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
@ManyToMany(mappedBy = "cities", fetch = FetchType.LAZY)
@JsonBackReference("area-city")
public List<Area> getAreas() {
return areas;
}
public void setAreas(List<Area> areas) {
this.areas = areas;
}
@OneToMany(mappedBy = "city", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public List<MainDataTable> getMainDataTables() {
return mainDataTables;
}
public void setMainDataTables(List<MainDataTable> mainDataTables) {
this.mainDataTables = mainDataTables;
}
}

View File

@@ -0,0 +1,29 @@
package com.sgs.graphql.city.domain;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class JsonToStringConverter implements AttributeConverter<Object, String> {
private final static ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Object attribute) {
try {
return objectMapper.writeValueAsString(attribute);
} catch (JsonProcessingException e) {
throw new RuntimeException("Error when serializing to json: " + attribute, e);
}
}
@Override
public Object convertToEntityAttribute(String dbData) {
try {
return objectMapper.readValue(dbData, Object.class);
} catch (JsonProcessingException e) {
throw new RuntimeException("Error when deserializing from json: " + dbData, e);
}
}
}

View File

@@ -0,0 +1,26 @@
package com.sgs.graphql.city.mutation;
import com.sgs.graphql.city.service.CityService;
import graphql.kickstart.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Validated
@Component
public class CityMutation implements GraphQLMutationResolver {
private final CityService cityService;
@Autowired
public CityMutation(CityService cityService) {
this.cityService = cityService;
}
}

View File

@@ -0,0 +1,26 @@
package com.sgs.graphql.city.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseCreateInput;
import java.util.UUID;
public class CityCreateInput extends BaseCreateInput {
private String name ;
private UUID country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getCountry() {
return country;
}
public void setCountry(UUID country) {
this.country = country;
}
}

View File

@@ -0,0 +1,27 @@
package com.sgs.graphql.city.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseUpdateInput;
import java.util.UUID;
public class CityUpdateInput extends BaseUpdateInput {
private String name ;
private UUID country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getCountry() {
return country;
}
public void setCountry(UUID country) {
this.country = country;
}
}

View File

@@ -0,0 +1,30 @@
package com.sgs.graphql.city.mutation.mapper;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.city.mutation.input.CityCreateInput;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.country.service.CountryService;
import com.sgs.lib.dao.mutation.mapper.BaseCreateMapper;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class CityMapper extends BaseCreateMapper<City, CityCreateInput> {
private final CountryService countryService;
public CityMapper( CountryService countryService) {
this.countryService = countryService;
}
@Override
public City toEntity(CityCreateInput input) {
City entity = new City();
entity.setName(input.getName());
Country country = countryService.findById(input.getCountry()).orElse(null);
entity.setCountry(country);
return entity;
}
}

View File

@@ -0,0 +1,77 @@
package com.sgs.graphql.city.query;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.city.query.pagination.CityPageable;
import com.sgs.graphql.city.repo.criteria.CityCriteria;
import com.sgs.graphql.city.service.CityService;
import com.sgs.graphql.district.domain.District;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class CityQueryResolver implements GraphQLQueryResolver {
private final CityService cityService;
@Autowired
public CityQueryResolver(CityService cityService) {
this.cityService = cityService;
}
@Transactional
public City city(UUID id) {
City city = cityService.findById(id).orElse(null);
if (city != null && city.getMainDataTables() != null) {
Hibernate.initialize(city.getMainDataTables());
if (city.getDistricts() != null) {
for (District district : city.getDistricts()) {
Hibernate.initialize(district.getMainDataTables());
}
}
}
return city;
}
@Transactional
public List<City> cities(CityCriteria criteria, List<SortBy> sortBy) {
List<City> cities = cityService.filterWithSort(ObjectUtils.defaultIfNull(criteria, new CityCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy, new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
if (cities.size() > 0) {
for (City city : cities) {
Hibernate.initialize(city.getMainDataTables());
}
}
return cities;
}
@Transactional
@PreAuthorize("hasAuthority('" + PermissionName.PAGINATE_CITIES_GET + "')")
public CityPageable paginateCities(Pagination pagination, CityCriteria criteria, List<SortBy> sortBy) {
CityPageable cityPageable = new CityPageable(cityService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria, new CityCriteria()),
Pagination.toPageRequest(pagination, sortBy)));
if (cityPageable.getContent().size() > 0) {
for (City city : cityPageable.getContent()) {
Hibernate.initialize(city.getMainDataTables());
}
}
return cityPageable;
}
}

View File

@@ -0,0 +1,12 @@
package com.sgs.graphql.city.query.pagination;
import com.sgs.graphql.city.domain.City;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class CityPageable extends PaginationResult<City> {
public CityPageable(Page<City> page) {
super(page);
}
}

View File

@@ -0,0 +1,18 @@
package com.sgs.graphql.city.repo;
import com.sgs.graphql.city.domain.City;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface CityRepo extends BaseRepo<City> {
City findByName(String name);
//City findById(City id);
}

View File

@@ -0,0 +1,26 @@
package com.sgs.graphql.city.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
public class CityCriteria extends BaseCriteria {
private String name;
private String year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}

View File

@@ -0,0 +1,26 @@
package com.sgs.graphql.city.repo.criteria.spec;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.city.repo.criteria.CityCriteria;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
@Component
public class CityCriteriaSpec extends BaseCriteriaSpec<City, CityCriteria> {
public static Specification<City> name(String name) {
return (name == null || name.trim().length() == 0) ? null : (Specification<City>) (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("name"), "%" + name + "%");
}
public static Specification<City> year(String year) {
return (year == null || year.trim().length() == 0) ? null : (Specification<City>) (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.join("mainDataTables").get("year"), year);
}
@Override
public Specification<City> createForAll(CityCriteria criteria) {
return Specification.where(name(criteria.getName()))
.and(year(criteria.getYear()));
}
}

View File

@@ -0,0 +1,36 @@
package com.sgs.graphql.city.service;
import com.sgs.graphql.city.domain.City;
import com.sgs.graphql.city.mutation.CityMutation;
import com.sgs.graphql.city.repo.CityRepo;
import com.sgs.graphql.city.repo.criteria.CityCriteria;
import com.sgs.graphql.city.repo.criteria.spec.CityCriteriaSpec;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CityService extends BaseService<City, CityRepo, CityCriteria, CityCriteriaSpec> {
@Autowired
public CityService(CityRepo repository, CityCriteriaSpec criteriaSpec) {
super(repository, criteriaSpec);
}
//
// public List<City> getCities() {
// return cities;
// }
// cityMutation.loadCitiesFromJson();
}

View File

@@ -0,0 +1,42 @@
package com.sgs.graphql.consuptionUnit.domain;
import com.sgs.lib.dao.domain.BaseDomain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "consuption_unit")
public class ConsuptionUnit extends BaseDomain {
private String tag;
private String description;
private boolean deleted;
@Column(name = "tag", nullable = false)
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "is_deleted", nullable = false)
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}

View File

@@ -0,0 +1,55 @@
package com.sgs.graphql.consuptionUnit.dto;
import java.util.UUID;
/**
* DTO for ConsuptionUnit entity.
* Represents units of consumption/measurement used in emission calculations.
*/
public class ConsuptionUnitDto {
private UUID id;
private String tag;
private String description;
private boolean isDeleted;
public ConsuptionUnitDto() {}
public ConsuptionUnitDto(UUID id, String tag, String description, boolean isDeleted) {
this.id = id;
this.tag = tag;
this.description = description;
this.isDeleted = isDeleted;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
}

View File

@@ -0,0 +1,46 @@
package com.sgs.graphql.consuptionUnit.query;
import com.sgs.graphql.consuptionUnit.query.pagination.ConsuptionUnitPageable;
import com.sgs.graphql.consuptionUnit.domain.ConsuptionUnit;
import com.sgs.graphql.consuptionUnit.repo.criteria.ConsuptionUnitCriteria;
import com.sgs.graphql.consuptionUnit.service.ConsuptionUnitService;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class ConsuptionUnitQueryResolver implements GraphQLQueryResolver {
private final ConsuptionUnitService consuptionUnitService;
@Autowired
public ConsuptionUnitQueryResolver(ConsuptionUnitService consuptionUnitService) {
this.consuptionUnitService = consuptionUnitService;
}
public ConsuptionUnit consuptionUnit(UUID id) {
return consuptionUnitService.findById(id).orElse(null);
}
public List<ConsuptionUnit> consuptionUnits(ConsuptionUnitCriteria criteria, List<SortBy> sortBy) {
return consuptionUnitService.filterWithSort(ObjectUtils.defaultIfNull(criteria, new ConsuptionUnitCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy, new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
}
public ConsuptionUnitPageable paginateConsuptionUnits(Pagination pagination, ConsuptionUnitCriteria criteria, List<SortBy> sortBy) {
return new ConsuptionUnitPageable(consuptionUnitService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria, new ConsuptionUnitCriteria()),
Pagination.toPageRequest(pagination, sortBy)));
}
}

View File

@@ -0,0 +1,11 @@
package com.sgs.graphql.consuptionUnit.query.pagination;
import com.sgs.graphql.consuptionUnit.domain.ConsuptionUnit;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class ConsuptionUnitPageable extends PaginationResult<ConsuptionUnit> {
public ConsuptionUnitPageable(Page<ConsuptionUnit> page) {
super(page);
}
}

View File

@@ -0,0 +1,12 @@
package com.sgs.graphql.consuptionUnit.repo;
import com.sgs.graphql.consuptionUnit.domain.ConsuptionUnit;
import com.sgs.lib.dao.repo.BaseRepo;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ConsuptionUnitRepo extends BaseRepo<ConsuptionUnit> {
List<ConsuptionUnit> findByTag(String tag);
}

View File

@@ -0,0 +1,6 @@
package com.sgs.graphql.consuptionUnit.repo.criteria;
import com.sgs.lib.dao.repo.criteria.BaseCriteria;
public class ConsuptionUnitCriteria extends BaseCriteria {
}

View File

@@ -0,0 +1,16 @@
package com.sgs.graphql.consuptionUnit.repo.criteria.spec;
import com.sgs.graphql.consuptionUnit.domain.ConsuptionUnit;
import com.sgs.graphql.consuptionUnit.repo.criteria.ConsuptionUnitCriteria;
import com.sgs.lib.dao.repo.criteria.spec.BaseCriteriaSpec;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
@Component
public class ConsuptionUnitCriteriaSpec extends BaseCriteriaSpec<ConsuptionUnit, ConsuptionUnitCriteria> {
@Override
public Specification<ConsuptionUnit> createForAll(ConsuptionUnitCriteria criteria) {
return null;
}
}

View File

@@ -0,0 +1,18 @@
package com.sgs.graphql.consuptionUnit.service;
import com.sgs.graphql.consuptionUnit.domain.ConsuptionUnit;
import com.sgs.graphql.consuptionUnit.repo.ConsuptionUnitRepo;
import com.sgs.graphql.consuptionUnit.repo.criteria.ConsuptionUnitCriteria;
import com.sgs.graphql.consuptionUnit.repo.criteria.spec.ConsuptionUnitCriteriaSpec;
import com.sgs.lib.dao.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConsuptionUnitService extends BaseService<ConsuptionUnit, ConsuptionUnitRepo, ConsuptionUnitCriteria, ConsuptionUnitCriteriaSpec> {
@Autowired
public ConsuptionUnitService(ConsuptionUnitRepo repository, ConsuptionUnitCriteriaSpec criteriaSpec) {
super(repository, criteriaSpec);
}
}

View File

@@ -0,0 +1,68 @@
package com.sgs.graphql.country.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sgs.graphql.area.domain.Area;
import com.sgs.lib.dao.domain.BaseDomain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "country")
public class Country extends BaseDomain {
private String countryCode;
private String name;
private boolean isDeleted = false;
private boolean defaultCountry;
private List<Area> areas = new ArrayList<>();
@Column(name = "country_code", nullable = false)
@JsonIgnore
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
@Column(nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(nullable = false)
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
this.isDeleted = deleted;
}
@Column(nullable = false)
public boolean isDefaultCountry() {
return defaultCountry;
}
public void setDefaultCountry(boolean defaultCountry) {
this.defaultCountry = defaultCountry;
}
@ManyToMany(mappedBy = "countries", fetch = FetchType.LAZY)
public List<Area> getAreas() {
return areas;
}
public void setAreas(List<Area> areas) {
this.areas = areas;
}
}

View File

@@ -0,0 +1,25 @@
package com.sgs.graphql.country.mutation;
import com.sgs.graphql.country.mutation.mapper.CountryMapper;
import com.sgs.graphql.country.service.CountryService;
import graphql.kickstart.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Validated
@Component
public class CountryMutation implements GraphQLMutationResolver {
private final CountryService countryService ;
private final CountryMapper countryMapper;
@Autowired
public CountryMutation(CountryService countryService, CountryMapper countryMapper) {
this.countryService = countryService;
this.countryMapper = countryMapper;
}
}

View File

@@ -0,0 +1,29 @@
package com.sgs.graphql.country.mutation.input;
import com.sgs.lib.dao.mutation.input.BaseCreateInput;
import java.util.List;
import java.util.UUID;
public class CountryCreateInput extends BaseCreateInput {
private String name;
// private List<UUID> areas;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// public List<UUID> getAreas() {
// return areas;
// }
//
// public void setAreas(List<UUID> areas) {
// this.areas = areas;
// }
}

View File

@@ -0,0 +1,29 @@
package com.sgs.graphql.country.mutation.mapper;
import com.sgs.graphql.area.service.AreaService;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.country.mutation.input.CountryCreateInput;
import com.sgs.lib.dao.mutation.mapper.BaseCreateMapper;
import org.springframework.stereotype.Component;
@Component
public class CountryMapper extends BaseCreateMapper<Country, CountryCreateInput> {
private final AreaService areaService;
public CountryMapper(AreaService areaService) {
this.areaService =areaService;
}
@Override
public Country toEntity(CountryCreateInput input) {
Country entity = new Country();
entity.setName(input.getName());
// Area areas = areaService.findById(input.getAreas().get(0)).orElse(null);
// entity.setAreas(input.getAreas());
return entity;
}
}

View File

@@ -0,0 +1,51 @@
package com.sgs.graphql.country.query;
import com.sgs.graphql.country.query.pagination.CountryPageable;
import com.sgs.graphql.country.service.CountryService;
import com.sgs.graphql.country.domain.Country;
import com.sgs.graphql.country.repo.criteria.CountryCriteria;
import com.sgs.graphql.permission.domain.PermissionName;
import com.sgs.lib.dao.query.pagination.Pagination;
import com.sgs.lib.dao.query.sort.SortBy;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class CountryQueryResolver implements GraphQLQueryResolver {
private final CountryService countryService;
@Autowired
public CountryQueryResolver( CountryService countryService) {
this.countryService = countryService;
}
public Country country(UUID id){
return countryService.findById(id).orElse(null);
}
@PreAuthorize("hasAuthority('"+ PermissionName.PAGINATE_COUNTRIES_GET +"')")
public List<Country> countries(CountryCriteria criteria, List<SortBy> sortBy){
return countryService.filterWithSort(ObjectUtils.defaultIfNull(criteria,new CountryCriteria()),
Sort.by(ObjectUtils.defaultIfNull(sortBy,new ArrayList<SortBy>())
.stream()
.map(SortBy::toOrder)
.collect(Collectors.toList())));
}
@PreAuthorize("hasAuthority('"+ PermissionName.PAGINATE_COUNTRIES_GET +"')")
public CountryPageable paginateCountries(Pagination pagination, CountryCriteria criteria, List<SortBy> sortBy){
return new CountryPageable(countryService.filterWithPaginate(ObjectUtils.defaultIfNull(criteria,new CountryCriteria()),
Pagination.toPageRequest(pagination,sortBy)));
}
}

View File

@@ -0,0 +1,11 @@
package com.sgs.graphql.country.query.pagination;
import com.sgs.graphql.country.domain.Country;
import com.sgs.lib.dao.query.pagination.PaginationResult;
import org.springframework.data.domain.Page;
public class CountryPageable extends PaginationResult<Country> {
public CountryPageable(Page<Country> page) {
super(page);
}
}

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