Browse Source

initial commit

master
kanimozhi 10 months ago
commit
40335c3ee2
  1. 27
      .gitignore
  2. 30
      HELP.md
  3. 295
      mvnw
  4. 189
      mvnw.cmd
  5. 120
      pom.xml
  6. 13
      src/main/java/com/gcc/election/ElectionApplication.java
  7. 102
      src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java
  8. 34
      src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java
  9. 69
      src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java
  10. 48
      src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java
  11. 137
      src/main/java/com/gcc/election/admindataentry/service/BatchService.java
  12. 139
      src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java
  13. 59
      src/main/java/com/gcc/election/admindataentry/service/TrainingService.java
  14. 16
      src/main/java/com/gcc/election/configuration/AppConfig.java
  15. 94
      src/main/java/com/gcc/election/configuration/DataSourceConfig.java
  16. 22
      src/main/java/com/gcc/election/configuration/JacksonConfiguration.java
  17. 89
      src/main/java/com/gcc/election/configuration/SecurityConfig.java
  18. 31
      src/main/java/com/gcc/election/configuration/ThymeleafConfig.java
  19. 74
      src/main/java/com/gcc/election/configuration/WebMvcConfig.java
  20. 470
      src/main/java/com/gcc/election/controller/APIController.java
  21. 148
      src/main/java/com/gcc/election/controller/AdminController.java
  22. 128
      src/main/java/com/gcc/election/controller/CustomErrorController.java
  23. 36
      src/main/java/com/gcc/election/controller/DateTimeUtil.java
  24. 74
      src/main/java/com/gcc/election/controller/FileController.java
  25. 37
      src/main/java/com/gcc/election/controller/MainController.java
  26. 167
      src/main/java/com/gcc/election/controller/MenuController.java
  27. 16
      src/main/java/com/gcc/election/controller/login.java
  28. 260
      src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java
  29. 108
      src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java
  30. 175
      src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java
  31. 214
      src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java
  32. 302
      src/main/java/com/gcc/election/dataentry/service/UpdationService.java
  33. 117
      src/main/java/com/gcc/election/entity/AppModuleAccessEntity.java
  34. 137
      src/main/java/com/gcc/election/entity/AppModuleEntity.java
  35. 156
      src/main/java/com/gcc/election/entity/AppUserEntity.java
  36. 112
      src/main/java/com/gcc/election/entity/AppUserGroupEntity.java
  37. 131
      src/main/java/com/gcc/election/entity/MenuItemAccessEntity.java
  38. 168
      src/main/java/com/gcc/election/entity/MenuItemEntity.java
  39. 146
      src/main/java/com/gcc/election/entity/SubMenuItemAccessEntity.java
  40. 181
      src/main/java/com/gcc/election/entity/SubMenuItemEntity.java
  41. 62
      src/main/java/com/gcc/election/entity/UserActivityLog.java
  42. 109
      src/main/java/com/gcc/election/entity/UserInfoEntity.java
  43. 321
      src/main/java/com/gcc/election/interceptor/AppInterceptor.java
  44. 55
      src/main/java/com/gcc/election/modeldata/ErrorResponse.java
  45. 41
      src/main/java/com/gcc/election/repository/AppModuleAccessRepository.java
  46. 30
      src/main/java/com/gcc/election/repository/AppModuleRepository.java
  47. 19
      src/main/java/com/gcc/election/repository/AppUserGroupRepository.java
  48. 28
      src/main/java/com/gcc/election/repository/AppUserRepository.java
  49. 41
      src/main/java/com/gcc/election/repository/MenuItemAccessRepository.java
  50. 31
      src/main/java/com/gcc/election/repository/MenuItemRepository.java
  51. 42
      src/main/java/com/gcc/election/repository/SubMenuItemAccessRepository.java
  52. 34
      src/main/java/com/gcc/election/repository/SubMenuItemRepository.java
  53. 19
      src/main/java/com/gcc/election/repository/UserActivityLogRepository.java
  54. 16
      src/main/java/com/gcc/election/repository/UserInfoRepository.java
  55. 37
      src/main/java/com/gcc/election/service/Base64Util.java
  56. 80
      src/main/java/com/gcc/election/service/CustomUserDetails.java
  57. 87
      src/main/java/com/gcc/election/service/CustomUserDetailsService.java
  58. 208
      src/main/java/com/gcc/election/service/LoginUserInfo.java
  59. 29
      src/main/java/com/gcc/election/service/UserActivityService.java
  60. 23
      src/main/java/com/gcc/election/service/UserActivityTimelineService.java
  61. 5
      src/main/resources/application-dev.properties
  62. 3
      src/main/resources/application-prod.properties
  63. 59
      src/main/resources/application.properties
  64. BIN
      src/main/resources/favicon.ico
  65. BIN
      src/main/resources/favicon.png
  66. BIN
      src/main/resources/static/Chennai_Corporation_Emblem.png
  67. BIN
      src/main/resources/static/assets/.DS_Store
  68. 584
      src/main/resources/static/assets/css/loginpage.css
  69. 4
      src/main/resources/static/assets/css/style.css
  70. BIN
      src/main/resources/static/assets/dist/.DS_Store
  71. 5989
      src/main/resources/static/assets/dist/css/theme.css
  72. 7
      src/main/resources/static/assets/dist/css/theme.css.map
  73. 5
      src/main/resources/static/assets/dist/css/theme.min.css
  74. 7
      src/main/resources/static/assets/dist/css/theme.min.css.map
  75. 0
      src/main/resources/static/assets/dist/img/.gitignore
  76. 13
      src/main/resources/static/assets/dist/img/brand-white.svg
  77. 14
      src/main/resources/static/assets/dist/img/brand.svg
  78. 6
      src/main/resources/static/assets/dist/img/down-arrow.svg
  79. 204
      src/main/resources/static/assets/dist/js/theme.js
  80. 1
      src/main/resources/static/assets/dist/js/theme.min.js
  81. BIN
      src/main/resources/static/assets/fonts/.DS_Store
  82. 3422
      src/main/resources/static/assets/fonts/iconsmind/iconsmind.css
  83. BIN
      src/main/resources/static/assets/fonts/iconsmind/iconsmind.eot
  84. 1141
      src/main/resources/static/assets/fonts/iconsmind/iconsmind.svg
  85. BIN
      src/main/resources/static/assets/fonts/iconsmind/iconsmind.ttf
  86. BIN
      src/main/resources/static/assets/fonts/iconsmind/iconsmind.woff
  87. BIN
      src/main/resources/static/assets/fonts/nunito/.DS_Store
  88. BIN
      src/main/resources/static/assets/fonts/nunito/v25/.DS_Store
  89. BIN
      src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t1R-tQKr51.woff2
  90. BIN
      src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t4R-tQKr51pE8.woff2
  91. BIN
      src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t6R-tQKr51pE8.woff2
  92. BIN
      src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t7R-tQKr51pE8.woff2
  93. BIN
      src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7txR-tQKr51pE8.woff2
  94. BIN
      src/main/resources/static/assets/images/.DS_Store
  95. BIN
      src/main/resources/static/assets/images/403.png
  96. BIN
      src/main/resources/static/assets/images/dog.png
  97. BIN
      src/main/resources/static/assets/images/donut-chart.png
  98. BIN
      src/main/resources/static/assets/images/error-bg-404.png
  99. BIN
      src/main/resources/static/assets/images/error-bg.png
  100. BIN
      src/main/resources/static/assets/images/hi_robo.gif

27
.gitignore

@ -0,0 +1,27 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
/target/
.project
/.settings

30
HELP.md

@ -0,0 +1,30 @@
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.5.7/maven-plugin)
* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.7/maven-plugin/build-image.html)
* [Spring Boot DevTools](https://docs.spring.io/spring-boot/3.5.7/reference/using/devtools.html)
* [Spring Data JDBC](https://docs.spring.io/spring-boot/3.5.7/reference/data/sql.html#data.sql.jdbc)
* [Thymeleaf](https://docs.spring.io/spring-boot/3.5.7/reference/web/servlet.html#web.servlet.spring-mvc.template-engines)
* [Spring Web](https://docs.spring.io/spring-boot/3.5.7/reference/web/servlet.html)
### Guides
The following guides illustrate how to use some features concretely:
* [Using Spring Data JDBC](https://github.com/spring-projects/spring-data-examples/tree/main/jdbc/basics)
* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/)
* [Handling Form Submission](https://spring.io/guides/gs/handling-form-submission/)
* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/)
* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/)
* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/)
### Maven Parent overrides
Due to Maven's design, elements are inherited from the parent POM to the project POM.
While most of the inheritance is fine, it also inherits unwanted elements like `<license>` and `<developers>` from the parent.
To prevent this, the project POM contains empty overrides for these elements.
If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides.

295
mvnw

@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
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"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
mvnw.cmd

@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

120
pom.xml

@ -0,0 +1,120 @@
<?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>
<!--<version>3.5.7</version>-->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gcc</groupId>
<artifactId>election</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>election</name>
<description>Project for Allocating polling persons</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
<bootstrap.version>4.0.0-2</bootstrap.version>
<webjars-locator.version>0.30</webjars-locator.version>
<lombok.version>1.18.2</lombok.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
<version>3.1.1.RELEASE</version> <!-- Replace with the appropriate version -->
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version> <!-- Replace with the appropriate version -->
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>in.gov.chennaicorporation</groupId>
<artifactId>gccoffice</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

13
src/main/java/com/gcc/election/ElectionApplication.java

@ -0,0 +1,13 @@
package com.gcc.election;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ElectionApplication {
public static void main(String[] args) {
SpringApplication.run(ElectionApplication.class, args);
}
}

102
src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java

@ -0,0 +1,102 @@
package com.gcc.election.admindataentry.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.election.admindataentry.service.BatchService;
@RestController
@RequestMapping("/election/api/dataentryadmin")
public class BatchApiController {
@Autowired
private BatchService batchService;
@GetMapping("/getalldepartments")
public List<Map<String, Object>> getDepartments() {
return batchService.getAllDepartment();
}
@GetMapping("/getallofficenames")
public List<Map<String, Object>> getofficebydept(@RequestParam int deptId) {
return batchService.getAllOfficenames(deptId);
}
// save the batch creation details
@PostMapping("/savebatchdeatils")
public ResponseEntity<String> saveBatch(
@RequestParam String receivedate,
@RequestParam int department,
@RequestParam int officename,
@RequestParam int noofapplication,
@RequestParam String userid) {
try {
String response = batchService.saveBatchDetails(receivedate, department, officename, noofapplication,userid);
return ResponseEntity.ok(response);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error saving data: " + e.getMessage());
}
}
// using data table
@GetMapping("/getallbatches")
public List<Map<String, Object>> getAllBatches() {
return batchService.getAllBatches();
}
// modal box data
@GetMapping("/getbatchbyId")
public ResponseEntity<?> getBatchById(@RequestParam int id) {
Map<String, Object> batch = batchService.getBatchById(id);
System.out.println("batch" + batch);
return ResponseEntity.ok(batch);
}
// update the batch details
@PostMapping("/updatebatch")
public ResponseEntity<?> updatebatch(
@RequestParam int id,
@RequestParam int noofapplication,
@RequestParam String userId) {
try {
batchService.updateBatch(id, noofapplication,userId);
return ResponseEntity.ok("Updated Successfully");
}
catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error updating batch: " + e.getMessage());
}
}
}

34
src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java

@ -0,0 +1,34 @@
package com.gcc.election.admindataentry.controller;
import com.gcc.election.admindataentry.service.ChecklistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/election/api/checklistadmin")
public class ChecklistApiController {
@Autowired
private ChecklistService checklistService;
@GetMapping("/getApplicants")
public ResponseEntity<?> getApplicants(@RequestParam(value = "batchNo", required = true) String batchNo,
@RequestParam(value = "fromSLno", required = true) String fromSLno,
@RequestParam(value = "toSLno", required = true) String toSLno,
@RequestParam(value = "mobileNo", required = true) String mobileNo,
@RequestParam(value = "category", required = true) String category,
@RequestParam(value = "officeName", required = true) String officeName,
@RequestParam(value = "notExist", required = true) String notExist){
return checklistService.getApplicants(batchNo, fromSLno, toSLno, mobileNo, category, officeName, notExist);
}
@PostMapping("/verifyApplicants")
public ResponseEntity<?> verifyApplicants(@RequestParam List<Integer> id) {
return checklistService.verifyApplicants(id);
}
}

69
src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java

@ -0,0 +1,69 @@
package com.gcc.election.admindataentry.controller;
import com.gcc.election.service.LoginUserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/election/dataentryadmin")
@Controller("electionDataentryAdminController")
public class Maincontroller {
@GetMapping("/dashboard")
public String dashboard(Model model) {
return "modules/dataentry_admin/dashboard";
}
@GetMapping("/batches")
public String batches(Model model) {
String loginUserId = LoginUserInfo.getLoginUserId();
if (loginUserId != null && !loginUserId.isEmpty()) {
System.out.println("String UserID: " + loginUserId);
}
model.addAttribute("loginUserId",loginUserId);
return "modules/dataentry_admin/batches";
}
@GetMapping("/updation")
public String updation(Model model) {
return "modules/dataentry_admin/updation";
}
@GetMapping("/verification")
public String verification(Model model) {
return "modules/dataentry_admin/verification";
}
@GetMapping("/training")
public String training(Model model) {
return "modules/dataentry_admin/training";
}
@GetMapping("/attendance")
public String attendance(Model model) {
return "modules/dataentry_admin/attendance";
}
@GetMapping("/others")
public String others(Model model) {
return "modules/dataentry_admin/others";
}
}

48
src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java

@ -0,0 +1,48 @@
package com.gcc.election.admindataentry.controller;
import com.gcc.election.admindataentry.service.TrainingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/election/api/trainingadmin")
public class TrainingApiController {
@Autowired
private TrainingService trainingService;
@GetMapping("getAllConstituency")
public List<Map<String, Object>> getAllConstituency() {
return trainingService.getAllConstituency();
}
@GetMapping("getAllCentre")
public List<Map<String, Object>> getAllCentre() {
return trainingService.getAllCentre();
}
@GetMapping("getAddressByCode")
public List<Map<String, Object>> getAddressByCode(int code) {
return trainingService.getAddressByCode(code);
}
@GetMapping("getAllCategory")
public List<Map<String, Object>> getAllCategory() {
return trainingService.getAllCategory();
}
}

137
src/main/java/com/gcc/election/admindataentry/service/BatchService.java

@ -0,0 +1,137 @@
package com.gcc.election.admindataentry.service;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
@Service
public class BatchService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getAllDepartment() {
String sql = " SELECT * FROM dept_master where is_active = '1' AND is_delete = '0' ORDER BY dept_name ASC ";
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAllOfficenames(Integer deptId) {
String sql = " SELECT id,office_name FROM office_details where dept_id = ? ";
return jdbcTemplate.queryForList(sql,deptId);
}
// batch creation service
public String saveBatchDetails(String receivedate, int department, int officename, int noofapplication,String userid) throws IOException {
String sql = "INSERT INTO batch_master " +
"(rec_date, dept_id, office_id, noof_application,created_by) " +
"VALUES (?, ?, ?, ?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
int result = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, receivedate);
ps.setInt(2, department);
ps.setInt(3, officename);
ps.setInt(4, noofapplication);
ps.setString(5,userid);
return ps;
}, keyHolder);
if (result > 0) {
int generatedId = keyHolder.getKey().intValue();
String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String refId = prefix + generatedId;
String updateSQL = "UPDATE batch_master SET batch_ref_id = ? WHERE id = ?";
jdbcTemplate.update(updateSQL, refId, generatedId);
return refId;
}
return "error";
}
public List<Map<String, Object>> getAllBatches() {
String sql = "select bm.id,DATE_FORMAT(bm.rec_date, '%d-%m-%Y') AS rec_date,bm.noof_application,od.office_name,dm.dept_name " +
" from batch_master bm " +
" LEFT JOIN dept_master dm ON dm.dept_id = bm.dept_id " +
" LEFT JOIN office_details od ON od.id = bm.office_id ";
System.out.println("sql " + sql);
return jdbcTemplate.queryForList(sql);
}
public Map<String, Object> getBatchById(int id) {
String sql = "SELECT bm.id, DATE_FORMAT(bm.rec_date, '%Y-%m-%d') AS rec_date, bm.noof_application,DATE_FORMAT(bm.rec_date, '%d-%m-%Y') AS received_date,om.id as office_id,dm.dept_id as dept_id, "
+ "dm.dept_name, "
+ "om.office_name "
+ "FROM batch_master bm "
+ "LEFT JOIN dept_master dm ON dm.dept_id = bm.dept_id "
+ "LEFT JOIN office_details om ON om.id = bm.office_id "
+ "WHERE bm.id = ?";
return jdbcTemplate.queryForMap(sql, id);
}
// update batch api
public void updateBatch(int id, int noofapplication,String userId) {
String insertHistorySql =
"INSERT INTO batch_master_log " +
"(batch_id,batch_ref_id, rec_date, dept_id, office_id, noof_application, from_slno, to_slno, dataentry_dt, " +
" photo_scanned_dt, noofphoto_missing, cklist_dt,cdate ,update_date, status,created_by) " +
"SELECT id, batch_ref_id, rec_date, dept_id, office_id, noof_application, from_slno, to_slno, dataentry_dt, " +
" photo_scanned_dt, noofphoto_missing, cklist_dt, cdate,update_date, status,created_by " +
"FROM batch_master WHERE id = ?";
System.out.println("insertHistorySql"+insertHistorySql);
jdbcTemplate.update(insertHistorySql, id);
String updateSql = "UPDATE batch_master SET noof_application = ? , updated_by = ? WHERE id = ?";
jdbcTemplate.update(updateSql, noofapplication, userId,id);
}
}

139
src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java

@ -0,0 +1,139 @@
package com.gcc.election.admindataentry.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ChecklistService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Transactional
public ResponseEntity<?> getApplicants(String batchNo, String fromSLno, String toSLno, String mobileNo, String category, String officeName, String notExist) {
Map<String, Object> result = new HashMap<>();
try {
StringBuilder sql = new StringBuilder("SELECT " +
" ppn.*, " +
" dm.*, " +
" d.*, " +
" od.*, " +
" CONCAT( " +
" COALESCE(od.address1, ''), " +
" ' ', " +
" COALESCE(od.address2, ''), " +
" ' ', " +
" COALESCE(od.address3, ''), " +
" ' ', " +
" COALESCE(od.pincode, '') " +
" ) AS address, " +
" ac_native.ac_name AS native_constituency, " +
" ac_reside.ac_name AS residential_constituency, " +
" ac_elector.ac_name AS elector_constituency, " +
" ac_work.ac_name AS working_constituency "+
"FROM poll_person_new ppn " +
"LEFT JOIN dept_master dm " +
" ON ppn.dept = dm.dept_id " +
"LEFT JOIN designation d " +
" ON ppn.designation_id = d.desig_id " +
"LEFT JOIN office_details od " +
" ON ppn.office_id = od.id " +
" LEFT JOIN ac_list_all ac_native " +
" ON ac_native.ac_no = ppn.native_ac_no " +
" LEFT JOIN ac_list_all ac_reside " +
" ON ac_reside.ac_no = ppn.reside_ac_no " +
"LEFT JOIN ac_list_all ac_elector " +
" ON ac_elector.ac_no = ppn.elector_ac_no " +
"LEFT JOIN ac_list_all ac_work " +
" ON ac_work.ac_no = od.work_ac_no " +
"WHERE 1=1 ");
List<Object> params = new ArrayList<>();
if(!batchNo.isEmpty()){
sql.append(" AND batch_no = ? ");
params.add(batchNo);
}
if (!fromSLno.isEmpty() && toSLno.isEmpty()) {
sql.append(" AND slno = ? ");
params.add(fromSLno);
}
if (!fromSLno.isEmpty() && !toSLno.isEmpty()) {
sql.append(" AND slno BETWEEN ? AND ? ");
params.add(fromSLno);
params.add(toSLno);
}
if (!mobileNo.isEmpty()) {
sql.append(" AND r_mobile_no = ? ");
params.add(mobileNo);
}
if (!category.isEmpty()) {
sql.append(" AND category_id = ? ");
params.add(category);
}
if (!officeName.isEmpty()) {
sql.append(" AND office_id = ? ");
params.add(officeName);
}
if (!notExist.isEmpty()) {
if(notExist.equalsIgnoreCase("voterid")) {
sql.append(" AND (elector_epic_no IS NULL OR elector_epic_no = '') ");
} else if (notExist.equalsIgnoreCase("mobile")) {
sql.append(" AND (r_mobile_no IS NULL OR r_mobile_no = '') ");
} else if (notExist.equalsIgnoreCase("both")) {
sql.append(" AND (r_mobile_no IS NULL OR r_mobile_no = '') AND (elector_epic_no IS NULL OR elector_epic_no = '') ");
}
}
List<Map<String, Object>> data = jdbcTemplate.queryForList(sql.toString(), params.toArray());
if (!data.isEmpty()) {
result.put("message", "success");
result.put("data", data);
} else {
result.put("message", "No Data Found");
result.put("data", "No Data Found");
}
return ResponseEntity.ok(result);
} catch (Exception e) {
e.printStackTrace();
result.put("Message", "Error");
result.put("Error", "Failed to fetch Checklist data: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
// verification of applicants
public ResponseEntity<String> verifyApplicants(List<Integer> ids) {
String sql = "UPDATE poll_person_new SET poll_person_verify = 1 WHERE id = ?";
for (Integer id : ids) {
jdbcTemplate.update(sql, id);
}
return ResponseEntity.ok("success");
}
}

59
src/main/java/com/gcc/election/admindataentry/service/TrainingService.java

@ -0,0 +1,59 @@
package com.gcc.election.admindataentry.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
@Service
public class TrainingService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getAllConstituency() {
String sql = " SELECT * FROM ac_list_all where dist_no = '2' ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAllCentre() {
String sql = " SELECT c_code,c_name FROM trgcen ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAddressByCode(int code) {
String sql = " SELECT c_address FROM trgcen where c_code=? ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql,code);
}
public List<Map<String, Object>> getAllCategory() {
String sql = " select distinct(category) from designation ORDER BY " +
" LENGTH(category)," +
" category; ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql);
}
}

16
src/main/java/com/gcc/election/configuration/AppConfig.java

@ -0,0 +1,16 @@
package com.gcc.election.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

94
src/main/java/com/gcc/election/configuration/DataSourceConfig.java

@ -0,0 +1,94 @@
package com.gcc.election.configuration;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
private static String host = "localhost:3306";
private static String dbpassword = "root";
// AWS
// private static String host = "gcc-facial-db-instance-1.cf48eqcciziq.ap-south-1.rds.amazonaws.com:3306";
// private static String dbpassword = "gcc-facial-password";
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "appEntityManagerFactory",
transactionManagerRef = "appTransactionManager",
basePackages = {"com.gcc.election.repository"})
public static class MysqlAppDataSourceConfig {
@Primary
@Bean(name = "mysqlAppDataSource")
public DataSource mysqlAppDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://"+host+"/gcc_election_apps");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
/*
@Bean(name = "mysqlAppJdbcTemplate")
public JdbcTemplate mysqlAppJdbcTemplate(@Qualifier("mysqlAppDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
*/
@Primary
@Bean(name="appEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier("mysqlAppDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("com.gcc.election.entity");
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
@Primary
@Bean(name = "appTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("appEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
//////////////////////////////(For GCC Election) ////////////////////////
@Bean(name = "mysqlGccElectionDataSource")
public DataSource mysqlMayorPetitionDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://"+host+"/gcc_election");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
}

22
src/main/java/com/gcc/election/configuration/JacksonConfiguration.java

@ -0,0 +1,22 @@
package com.gcc.election.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during serialization
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Serialize dates as Strings
objectMapper.registerModule(new JavaTimeModule()); // Register JavaTimeModule for Java 8 Date/Time support
return objectMapper;
}
}

89
src/main/java/com/gcc/election/configuration/SecurityConfig.java

@ -0,0 +1,89 @@
package com.gcc.election.configuration;
import javax.persistence.Basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.gcc.election.service.CustomUserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private final CustomUserDetailsService customUserDetailsService;
@Autowired
public SecurityConfig(CustomUserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**", "/assets/**", "/api/**","/images/**","/election/static/**", "/election/assets/**", "/election/api/**","/election/images/**","/election/files/**");
//.antMatchers("/election/static/**", "/election/assets/**", "/election/api/**","/election/images/**");
//.antMatchers("/assets/**", "/css/**", "/js/**", "/images/**", "/fonts/**"); // Add the paths to your static resources here
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
// Configure authorization (URL-based access control)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and() // Enable CORS
.csrf().disable() // Disable CSRF protection for simplicity (Enable if needed)
.authorizeRequests()
.antMatchers("/election/error").permitAll()
.antMatchers("/election/login").permitAll() // Add the login URL
.antMatchers("/election/admin/**").hasRole("ADMIN") // Add the admin URLs
.antMatchers("/election/**").hasAnyRole("ADMIN","USER") // Add other URLs
//.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/election/login") // Customize the login page URL
.defaultSuccessUrl("/election") // Include the success URL
.permitAll()
.and()
.logout()
.logoutUrl("/election/logout") // Include the logout URL
.logoutSuccessUrl("/election/login") // Include the success logout URL
.permitAll()
.and()
.sessionManagement()
.sessionFixation()
.migrateSession(); // or .none(), .newSession()
/*
// Print role values
http.authorizeRequests().anyRequest().authenticated().and().formLogin().successHandler((request, response, authentication) -> {
System.out.println("User Roles: ");
authentication.getAuthorities().forEach(authority -> System.out.println(authority.getAuthority()));
System.out.println();
response.sendRedirect("/election");
});
*/
}
@Basic
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

31
src/main/java/com/gcc/election/configuration/ThymeleafConfig.java

@ -0,0 +1,31 @@
package com.gcc.election.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
//@Configuration
//public class ThymeleafConfig {
//
// @Bean
// public ITemplateResolver templateResolver() {
// SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
// templateResolver.setPrefix("classpath:/templates/"); // Set your Thymeleaf templates prefix here
// templateResolver.setSuffix(".html");
// templateResolver.setTemplateMode(TemplateMode.HTML);
// templateResolver.setCacheable(false); // Disable template caching for development environment
// return templateResolver;
// }
//
// @Bean
// public SpringTemplateEngine templateEngine() {
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setTemplateResolver(templateResolver());
// return templateEngine;
// }
//
//}

74
src/main/java/com/gcc/election/configuration/WebMvcConfig.java

@ -0,0 +1,74 @@
package com.gcc.election.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.interceptor.AppInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
private final String uploadDirectory;
private AppModuleAccessRepository appModuleAccessRepository;
private MenuItemAccessRepository menuItemAccessRepository;
private SubMenuItemAccessRepository subMenuItemAccessRepository;
private AppModuleRepository appModuleRepository;
private MenuItemRepository menuItemRepository;
private SubMenuItemRepository subMenuItemRepository;
private final Environment environment;
@Autowired
public WebMvcConfig(
@Value("${file.upload.directory}") String uploadDirectory,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
Environment environment) {
this.uploadDirectory = uploadDirectory;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.environment = environment;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppInterceptor(
appModuleAccessRepository,
menuItemAccessRepository,
subMenuItemAccessRepository,
appModuleRepository,
menuItemRepository,
subMenuItemRepository,
environment));
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadDirectory +"/");
}
}

470
src/main/java/com/gcc/election/controller/APIController.java

@ -0,0 +1,470 @@
package com.gcc.election.controller;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.AppUserRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.repository.UserActivityLogRepository;
import com.gcc.election.service.LoginUserInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@RequestMapping("/election/api")
@RestController
public class APIController {
List<AppUserEntity> getAppUserEntities;
@Autowired
private HttpServletRequest request;
@Autowired
private AppUserRepository appUserRepository;
@Autowired
private LoginUserInfo loginUserInfo;
List<UserActivityLog> getActivityLogs;
@Autowired
private UserActivityLogRepository userActivityLogRepository;
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<MenuItemAccessEntity> getMenuItemAccessEntities;
List<SubMenuItemAccessEntity> getSubMenuItemAccessEntities;
@Autowired
private AppModuleAccessRepository appModuleAccessRepository;
@Autowired
private MenuItemAccessRepository menuItemAccessRepository;
@Autowired
private SubMenuItemAccessRepository subMenuItemAccessRepository;
List<AppModuleEntity> getAppModuleEntities;
List<MenuItemEntity> getMenuItemEntities;
List<SubMenuItemEntity> getSubMenuItemEntities;
@Autowired
private AppModuleRepository appModuleRepository;
@Autowired
private MenuItemRepository menuItemRepository;
@Autowired
private SubMenuItemRepository subMenuItemRepository;
@Autowired
public APIController(
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
UserActivityLogRepository userActivityLogRepository) {
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.userActivityLogRepository = userActivityLogRepository;
}
// Encode to Base64
@GetMapping(value="/encodeBase64")
public static String encodeBase64(@RequestParam String string) {
String value=string;
byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes());
return new String(encodedBytes);
}
// Decode from Base64
@GetMapping(value="/decodeBase64")
public static String decodeBase64(@RequestParam String string) {
String encodedValue=string;
byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
return new String(decodedBytes);
}
@GetMapping(value="/getAccessTree")
public String getAccessTreeHTML(@RequestParam String groupId,@RequestParam String groupName) {
getAppModuleEntities = appModuleRepository.showAll();
String accessHTML = "";
String accessTableHTML = "";
//String MenuHTML = "";
String isSelected = "";
//String subMenuHTML = "";
String groupNameHTML = "<span class=\"badge badge-pill badge-primary mb-1\">"+groupName+"</span>";
for (AppModuleEntity moduleName : getAppModuleEntities) {
// ID to check
Integer desiredId = moduleName.getId();
// Check if the ID exists in the list of entities
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId,desiredId.toString());
// Check Module Id Access
if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; }
accessHTML = accessHTML+"<li><input id=\"m"+moduleName.getId()+"\" type=\"checkbox\" data-type=\"parent\" value=\"m_"+desiredId+"\" "+isSelected+"/>&nbsp;<label for=\"m"+moduleName.getId()+"\" style=\"background-color:#000;color:#fff;\">&nbsp;&nbsp;<i class=\""+moduleName.getIcon()+"\"></i> "+moduleName.getName()+"&nbsp;&nbsp;</label>";
getMenuItemEntities = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItemEntities) {
String mmid = desiredId+"_"+menuItem.getId();
// Check if the ID exists in the list of entities
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString());
// Check Module Id Access
if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; }
if(menuItem.getHasSub()) {
getSubMenuItemEntities = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getSubMenuItemEntities) {
String isSelected2 = "";
String smid = desiredId+"_"+menuItem.getId()+"_"+subMenuItem.getId();
// Check if the ID exists in the list of entities
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString(),subMenuItem.getId().toString());
// Check Module Id Access
if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { isSelected2 = "checked"; } else { isSelected2 = ""; }
subSubMenuHTML = subSubMenuHTML+"<li><input id=\"sm"+subMenuItem.getId()+"\" type=\"checkbox\" data-type=\"sub-child\" value=\"sm_"+smid+"\" "+isSelected2+"/>&nbsp;<label for=\"sm"+subMenuItem.getId()+"\"><i class=\""+subMenuItem.getIcon()+"\"></i> "+subMenuItem.getName()+"</label></li>";
}
if(subSubMenuHTML.equals(""))
{
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" value=\"mm_"+mmid+"\" "+isSelected+"/>&nbsp;<label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" value=\"mm_"+mmid+"\" "+isSelected+"/>&nbsp;<label for=\"mm"+menuItem.getId()+"\">&nbsp;<i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label> <ul>"+subSubMenuHTML+"</ul></li>";
}
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" value=\"mm_"+mmid+"\" "+isSelected+"/>&nbsp;<label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
}
accessHTML = accessHTML+"<ul>"+subMenuHTML+"</ul></li>";
subMenuHTML = "";
}
accessTableHTML = groupNameHTML+"<ul id=\"tree\" class=\"checktree\" style=\"padding-left:25px;\" >"+accessHTML+"</ul>";
return accessTableHTML;
}
@PostMapping("/saveGroupAccessData")
public String saveGroupAccessData(@RequestBody Map<String, Object> requestBody) {
@SuppressWarnings("unchecked")
List<String> checkedData = (List<String>) requestBody.get("checkedData");
String groupId = (String) requestBody.get("groupId");
String dataType[]= {"","", "module","menu","submenu"};
if (groupId != null) {
System.out.println("groupid value: " + groupId);
// Set isActive = false based on groupId
appModuleAccessRepository.updateActiveStatus(false,groupId);
menuItemAccessRepository.updateActiveStatus(false,groupId);
subMenuItemAccessRepository.updateActiveStatus(false,groupId);
// Now update as per input data
if (checkedData != null) {
for (String data : checkedData) {
System.out.println(data);
// m_x -> Module Value (moduleId) -> 2
// mm_x_x -> Menu Value (moduleId,menuId) ->3
// sm_x_x_x -> SubMenu Value (moduleId, menuId, submenuId) ->4
String[] dataValue = data.split("_");
Integer dataLength = dataValue.length;
System.out.println(dataLength +" ==> "+dataType[dataLength]);
if(dataValue.length==2) { // Module
// Check if the ID exists in the list of entities
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, dataValue[1]);
if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) {
appModuleAccessRepository.update(true,groupId,dataValue[1]);
}
else {
appModuleAccessRepository.insert(groupId,dataValue[1]);
}
}
else if(dataValue.length==3) { // Menu
// Check if the ID exists in the list of entities
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2]);
if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) {
menuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2]);
}
else {
menuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2]);
}
}
else if(dataValue.length==4) { // SubMenu
// Check if the ID exists in the list of entities
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2], dataValue[3]);
if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) {
subMenuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2],dataValue[3]);
}
else {
subMenuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2],dataValue[3]);
}
}
}
}
}
return "";
}
@GetMapping(value="/getUserProfileBasic")
public String getUserProfileBasic(@RequestParam String userId) {
//String userHtml ="";
String userProfileHtml ="";
//String userProfileTimelineHtml ="";
getAppUserEntities = appUserRepository.showById(userId);
for (AppUserEntity appUserEntity : getAppUserEntities) {
userProfileHtml = ""
+ " "
+ " <div class='card mb-1'>"
+ " <div class='card-body'>"
+ " <div class='text-center'>"
+ " <img src='/assets/images/users/user.jpg' class='rounded' width='150'>\n"
+ " <h4 class='card-title mt-10'>"+appUserEntity.getUserid().getName()+"</h4>\n"
+ " <p class='text-muted'>Front End Developer</p>\n"
+ " </div>\n"
+ " </div>"
+ " <hr class='mb-0 mt-0'> \n"
+ " <div class='card-body'> \n"
+ " <small class='text-muted d-block'>Email address </small>\n"
+ " <h8>"+appUserEntity.getUserid().getEmail()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Phone</small>\n"
+ " <h8>"+appUserEntity.getUserid().getPhone()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Role</small>\n"
+ " <h8>"+appUserEntity.getRoles()+"</h8>\n"
+ " <small class='text-muted d-block pt-10'>Access Group</small>\n"
+ " <h8>"+appUserEntity.getUsergroup_id().getName()+"</h8>\n"
+ " </div>\n"
+ " </div>\n"
+ " ";
}
return userProfileHtml;
}
@GetMapping(value="/getUserProfile")
public String getUserProfile(@RequestParam String userId) {
String userHtml ="";
String userProfileHtml ="";
String userProfileTimelineHtml ="";
String userIp = getUserIP();
getAppUserEntities = appUserRepository.showById(userId);
for (AppUserEntity appUserEntity : getAppUserEntities) {
userProfileHtml = ""
+ " <div class='col-lg-4 col-md-5'>"
+ " <div class='card mb-1'>"
+ " <div class='card-body'>"
+ " <div class='text-center'>"
+ " <img src='/assets/images/users/user.jpg' class='rounded' width='150'>\n"
+ " <h4 class='card-title mt-10'>"+appUserEntity.getUserid().getName()+"</h4>\n"
+ " <p class='text-muted'>Front End Developer</p>\n"
+ " <p class='text-muted'>"+userIp+"</p>\n"
+ " </div>\n"
+ " </div>"
+ " <hr class='mb-0 mt-0'> \n"
+ " <div class='card-body'> \n"
+ " <small class='text-muted d-block'>Email address </small>\n"
+ " <h8>"+appUserEntity.getUserid().getEmail()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Phone</small>\n"
+ " <h8>"+appUserEntity.getUserid().getPhone()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Role</small>\n"
+ " <h8>"+appUserEntity.getRoles()+"</h8>\n"
+ " <small class='text-muted d-block pt-10'>Access Group</small>\n"
+ " <h8>"+appUserEntity.getUsergroup_id().getName()+"</h8>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>";
userProfileTimelineHtml = ""
+ "<div class='col-lg-8 col-md-7'>"
+ " <div class='card'>"
+ " <ul class='nav nav-pills custom-pills' id='pills-tab' role='tablist'>"
+ " <li class='nav-item'>"
+ " <a class='nav-link active' id='pills-timeline-tab' data-toggle='pill' href='#current-month' role='tab' aria-controls='pills-timeline' aria-selected='true'>Timeline</a>"
+ " </li>"
+ " <li class='nav-item'>"
+ " <a class='nav-link' id='pills-profile-tab' data-toggle='pill' href='#last-month' role='tab' aria-controls='pills-profile' aria-selected='false'>Profile</a>"
+ " </li>"
+ " </ul>"
+ " <div class='tab-content' id='pills-tabContent'>"
+ " <div class='tab-pane fade active show' id='current-month' role='tabpanel' aria-labelledby='pills-timeline-tab'>"
+ userTimeLine(appUserEntity.getUserid().getUserid().toString(),appUserEntity.getUserid().getName(),"user.jpg")
+ " </div>"
+ " </div>"
+ " </div>"
+ "</div>";
userHtml ="<div class='row'>" + userProfileHtml + userProfileTimelineHtml + "</div>";
}
return userHtml;
}
public String userTimeLine(String userid, String userName, String img) {
String userTimeLineHTML = "";
getActivityLogs = userActivityLogRepository.findByUserIdOrderByTimestampDesc(userid);
for (UserActivityLog userActivityLog : getActivityLogs) {
userTimeLineHTML += ""
+ " <div class='sl-item'>"
+ " <div class='sl-left'> "
+ " <img src='/assets/images/users/"+img+"' alt='user' class='rounded-circle'> "
+ " </div>"
+ " <div class='sl-right'>"
+ " <div>"
+ " <a href='javascript:void(0)' class='link'>"+userName+"</a> "
+ " <span class='sl-date'>"+dateFormat(userActivityLog.getTimestamp().toString())+"</span>"
+ " <blockquote class='mt-10'>"
+ " "+userActivityLog.getActivityType()
+ " </blockquote>"
+ " </div>"
+ " </div>"
+ " </div><hr>";
}
userTimeLineHTML = ""
+ "<div class='card-body'>"
+ " <div class='profiletimeline mt-0'>"
+ userTimeLineHTML
+ " </div>"
+ "</div>";
return userTimeLineHTML;
}
public String dateFormat(String timestampString) {
//String timestampString = "2023-12-28T16:21:24";
LocalDateTime timestamp = LocalDateTime.parse(timestampString, DateTimeFormatter.ISO_DATE_TIME);
// Define the desired date-time format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
// Format the timestamp
String formattedTimestamp = timestamp.format(formatter);
//System.out.println(formattedTimestamp);
return formattedTimestamp.toUpperCase();
}
public String getUserIP() {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
@GetMapping(value="/passwordGenerator")
public String passwordGenerator(@RequestParam(value = "password", required = false) String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String rawPassword = password;
String encodedPassword = passwordEncoder.encode(rawPassword);
return encodedPassword;
}
@PostMapping(value="/resetPassword")
public String resetPassword(
@RequestParam(value = "", required = false) String userid,
@RequestParam(value = "", required = false) String oldpassword,
@RequestParam(value = "", required = false) String newpassword
) {
System.out.println(userid+" : "+oldpassword+" : "+newpassword);
String oldPasswordTxt=oldpassword; //passwordGenerator(oldpassword);
String newPasswordTxt=newpassword; //passwordGenerator(newpassword);
String rawPasswordTxt=newpassword;
System.out.println(oldPasswordTxt+" : "+newPasswordTxt+" : "+rawPasswordTxt);
String response = loginUserInfo.resetPassword(userid,oldPasswordTxt,newPasswordTxt,rawPasswordTxt);
return response;
}
@PostMapping(value="/userCheck")
public List<Map<String, Object>> userCheck(
@RequestParam(value = "", required = false) String usernametxt,
@RequestParam(value = "", required = false) String passwordtxt
) {
System.out.println("HRM Service : "+usernametxt+" : "+passwordtxt);
List<Map<String, Object>> response = loginUserInfo.userCheck(usernametxt,passwordtxt);
return response;
}
// @GetMapping(value="/getDailyKural")
// public List getDailyKural() {
// return loginUserInfo.getDailyContent();
// }
}

148
src/main/java/com/gcc/election/controller/AdminController.java

@ -0,0 +1,148 @@
package com.gcc.election.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.election.entity.AppUserGroupEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.AppUserGroupRepository;
import com.gcc.election.repository.AppUserRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.service.LoginUserInfo;
@RequestMapping("/election/admin")
@Controller("electionAdminController")
public class AdminController {
private final AppUserRepository appUserRepository;
private final AppUserGroupRepository appUserGroupRepository;
private final AppModuleRepository appModuleRepository;
private final MenuItemRepository menuItemRepository;
private final SubMenuItemRepository subMenuItemRepository;
@Autowired
public AdminController(
AppUserRepository appUserRepository,
AppUserGroupRepository appUserGroupRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository) {
this.appUserRepository = appUserRepository;
this.appUserGroupRepository = appUserGroupRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
}
@GetMapping({"", "/", "/index"})
public String main(Model model) {
String userId = LoginUserInfo.getLoginUserId();
if (userId != null && !userId.isEmpty()) {
System.out.println("String UserID: " + userId);
}
return "modules/admin/index";
}
@GetMapping("/user-list")
public String userList(Model model) {
model.addAttribute("userlist",getUser());
return "modules/admin/user-list";
}
@GetMapping("/user-group-list")
public String userGroupList(Model model) {
model.addAttribute("userGroupList",getUserGroup());
return "modules/admin/user-group-list";
}
@GetMapping("/user-group-access")
public String userGroupAccess(Model model) {
String accessTableHTML = getAccessTreeHTML();
model.addAttribute("userGroupList",getUserGroup());
model.addAttribute("accessHTML",accessTableHTML);
return "modules/admin/user-group-access";
}
//////////////////////////////////////// (Functions) ////////////////////////////////////////
public List<AppUserEntity> getUser() {
List<AppUserEntity> appUserEntities;
appUserEntities = appUserRepository.showAll();
return appUserEntities;
}
public List<AppUserGroupEntity> getUserGroup() {
List<AppUserGroupEntity> appUserGroupEntities;
appUserGroupEntities = appUserGroupRepository.findAll();
return appUserGroupEntities;
}
public String getAccessTreeHTML() {
//List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
getAppModuleEntities = appModuleRepository.showAll();
String accessHTML = "";
String accessTableHTML = "";
//String MenuHTML = "";
//String subMenuHTML = "";
for (AppModuleEntity moduleName : getAppModuleEntities) {
accessHTML = accessHTML+"<li><input id=\"m"+moduleName.getId()+"\" type=\"checkbox\" data-type=\"parent\" value=\"\"/>&nbsp;<label for=\"m"+moduleName.getId()+"\" style=\"background-color:#000;color:#fff;\">&nbsp;&nbsp;<i class=\""+moduleName.getIcon()+"\"></i> "+moduleName.getName()+"&nbsp;&nbsp;</label>";
List<MenuItemEntity> getMenuItems;
getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItems) {
if(menuItem.getHasSub()) {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
subSubMenuHTML = subSubMenuHTML+"<li><input id=\"sm"+subMenuItem.getId()+"\" type=\"checkbox\" data-type=\"sub-child\"/> <label for=\"sm"+subMenuItem.getId()+"\"><i class=\""+subMenuItem.getIcon()+"\"></i> "+subMenuItem.getName()+"</label></li>";
}
if(subSubMenuHTML.equals(""))
{
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" /> <label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\"/> <label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label> <ul>"+subSubMenuHTML+"</ul></li>";
}
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\"/> <label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
}
accessHTML = accessHTML+"<ul>"+subMenuHTML+"</ul></li>";
subMenuHTML = "";
}
accessTableHTML = "<ul id=\"tree\" class=\"checktree\">"+accessHTML+"</ul>";
return accessTableHTML;
}
}

128
src/main/java/com/gcc/election/controller/CustomErrorController.java

@ -0,0 +1,128 @@
package com.gcc.election.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gcc.election.modeldata.ErrorResponse;
@Controller
public class CustomErrorController implements ErrorController{
private static final String ERROR_PATH = "/error";
private static final Map<Integer, String> PAGE_NAME_MAP = new HashMap<>();
public String getPageName(Integer statusCode) {
if (statusCode != null) {
return PAGE_NAME_MAP.getOrDefault(statusCode, "errorPage");
} else {
return "errorPage";
}
}
// Handle errors for web applications, return HTML error pages
@RequestMapping(value = ERROR_PATH, produces = "text/html")
public String handleWebError(HttpServletRequest request, Model model) {
// Retrieve error information from the request
// HttpStatus status = HttpStatus.valueOf((Integer) request.getAttribute("javax.servlet.error.status_code"));
//Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
// Retrieve error information from the request
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
// Add the error message to the model
model.addAttribute("errorStatus", "Error 403");
model.addAttribute("errorError", "403 - Access Denied");
model.addAttribute("errorMessage", "Oops, You don`t have permission to access this page.");
// Handle the case where the status code is null
// You may choose to set default values or redirect to a generic error page
return "error-403";
}
HttpStatus status = (statusCode != null) ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR;
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
// Add custom error handling logic for web applications here
String errorPage = "error";
Integer errorStatus = 404;
String errorError = "Internal Server Error";
String errorMessage = "An error occurred"; // Default error message
String pageName = new CustomErrorController().getPageName(status.value());
// Print error information to the console
if (status != null) {
errorStatus = status.value();
errorError = status.getReasonPhrase();
System.err.println("HTTP Status: " + status +"\n"
+"Status Code: "+status.value()+"\n"+ "Status Error: "
+status.getReasonPhrase()
+"Page Name: "+pageName);
// Check if the status code
if (status == HttpStatus.NOT_FOUND) {
errorPage = "error-404"; // 400 Error Page
}
else if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
errorPage = "error-500"; // 500 Error page
}
else {
errorPage = "error"; //// Other Error page
}
}
if (throwable != null) {
// Retrieve the exception message
errorMessage = throwable.getMessage();
throwable.printStackTrace();
}
// Add the error message to the model
model.addAttribute("errorStatus", errorStatus);
model.addAttribute("errorError", errorError);
model.addAttribute("errorMessage", errorMessage);
return errorPage; // Return the name of your custom HTML error page (without the .html extension)
}
// Handle errors for RESTful APIs, return JSON error responses
@RequestMapping(value = ERROR_PATH, produces = "application/json")
@ResponseBody
public ResponseEntity<ErrorResponse> handleApiError(HttpServletRequest request) {
// Retrieve error information from the request
HttpStatus status = HttpStatus.valueOf((Integer) request.getAttribute("javax.servlet.error.status_code"));
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
// Create an error response
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setStatus(status.value());
errorResponse.setError(status.getReasonPhrase());
errorResponse.setMessage("An error occurred");
if (throwable != null) {
errorResponse.setException(throwable.getMessage());
}
// Return a ResponseEntity with the custom JSON error response and HTTP status
return ResponseEntity.status(status).body(errorResponse);
}
@GetMapping(ERROR_PATH)
public String handleError() {
return "error-404"; // Return the name of your custom error page (without the .html extension)
}
}

36
src/main/java/com/gcc/election/controller/DateTimeUtil.java

@ -0,0 +1,36 @@
package com.gcc.election.controller;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Service
public class DateTimeUtil {
public static String getCurrentDateTime() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentYear() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentMonth() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentDay() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentDateTimeMysql() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
}

74
src/main/java/com/gcc/election/controller/FileController.java

@ -0,0 +1,74 @@
package com.gcc.election.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.HandlerMapping;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
@Controller
public class FileController {
@Value("${file.upload.directory}")
private String uploadDirectory;
@GetMapping("/election/files/{directoryPath}/**")
public ResponseEntity<Resource> serveFile(@PathVariable String directoryPath, HttpServletRequest request) {
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
System.out.println(fullPath.toString()+"\n"+directoryPath.length()+"\n directoryPath:"+directoryPath);
//String relativePath = fullPath.substring(directoryPath.length() + 1); // Adding 1 for the trailing '/'
String relativePath = fullPath.replace("/election/files", "");
String filePath = uploadDirectory + "/" + relativePath;
Path path = Paths.get(filePath).normalize();
System.out.println(path.toString());
Resource resource;
try {
resource = new UrlResource(path.toUri());
if (resource.exists() || resource.isReadable()) {
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
// Determine content type based on file extension
String fileName = resource.getFilename();
if (fileName != null) {
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
switch (fileExtension.toLowerCase()) {
case "jpg":
case "jpeg":
mediaType = MediaType.IMAGE_JPEG;
break;
case "png":
mediaType = MediaType.IMAGE_PNG;
break;
case "gif":
mediaType = MediaType.IMAGE_GIF;
break;
case "pdf":
mediaType = MediaType.APPLICATION_PDF;
break;
// Add more cases for other file types if needed
}
}
return ResponseEntity.ok()
.contentType(mediaType)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
//.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}

37
src/main/java/com/gcc/election/controller/MainController.java

@ -0,0 +1,37 @@
package com.gcc.election.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gcc.election.service.LoginUserInfo;
@RequestMapping("/election")
@Controller("electionMainController")
public class MainController {
private final LoginUserInfo loginUserInfo;
@Autowired
public MainController(LoginUserInfo loginUserInfo) {
this.loginUserInfo = loginUserInfo;
}
@GetMapping({"", "/", "/index"})
public String main(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
if (LoginUserId != null && !LoginUserId.isEmpty()) {
System.out.println("String UserID: " + LoginUserId);
}
model.addAttribute("LoginUserId",LoginUserId);
return "index";
}
@GetMapping("/widget-statistic")
public String widgetStatistic(Model model) {
return "widget-statistic";
}
}

167
src/main/java/com/gcc/election/controller/MenuController.java

@ -0,0 +1,167 @@
package com.gcc.election.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.service.LoginUserInfo;
@ControllerAdvice
public class MenuController {
private final AppModuleRepository appModuleRepository;
private final MenuItemRepository menuItemRepository;
private final SubMenuItemRepository subMenuItemRepository;
private final AppModuleAccessRepository appModuleAccessRepository;
private final MenuItemAccessRepository menuItemAccessRepository;
private final SubMenuItemAccessRepository subMenuItemAccessRepository;
@Autowired
public MenuController(AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository) {
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
}
@ModelAttribute("menuItemsHTML") // This will add the menuItems to the model for all requests
public String menuHTML() {
if(LoginUserInfo.getLoginUserId() == null || LoginUserInfo.getUserGroupId()==null) {
return "";
}
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
getAppModuleEntities = appModuleRepository.showAll();
}
else {
getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId());
String[] checkModuleId = new String[getAppModuleAccessEntities.size()];
int i=0;
for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) {
checkModuleId[i]=accessEntity.getModuleId().getId().toString();
i++;
}
getAppModuleEntities = appModuleRepository.showAllById(checkModuleId);
}
String menuHTML = "";
menuHTML = "<div class=\"nav-item\"><a href=\"/election\"><i class=\"ik ik-home\"></i><span>Dashboard</span></a></div>";
for (AppModuleEntity moduleName : getAppModuleEntities) {
menuHTML = menuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0)\"><i class=\""+moduleName.getIcon()+"\"></i><span>"+moduleName.getName()+"</span></a><div class=\"submenu-content\">";
List<MenuItemEntity> getMenuItems;
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
}
else {
List<MenuItemAccessEntity> getMenuItemAccess = menuItemAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId(), moduleName.getId().toString());
String[] checkMenuId = new String[getMenuItemAccess.size()];
int j=0;
for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) {
checkMenuId[j]=menuAccessEntity.getMenuItemId().getId().toString();
j++;
}
getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(moduleName.getId(),checkMenuId);
}
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItems) {
if(menuItem.getHasSub()) {
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if(subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML+"<a href=\""+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
else {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/election/"+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
}
if(subSubMenuHTML.equals(""))
{
subMenuHTML = subMenuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0);\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i>"+menuItem.getName()+"</a></div>";
}
else {
subMenuHTML = subMenuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0);\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i>"+menuItem.getName()+"</a><div class=\"submenu-content\">"+subSubMenuHTML+"</div></div>";
}
}
else {
List<SubMenuItemAccessEntity> getSubMenuItemAccess = subMenuItemAccessRepository.findByUserGroupIDAccess(LoginUserInfo.getUserGroupId(), moduleName.getId().toString(), menuItem.getId().toString());
String[] checkSubMenuId = new String[getSubMenuItemAccess.size()];
if(checkSubMenuId.length>0)
{
int k=0;
for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) {
checkSubMenuId[k]=subMenuItemAccessEntity.getSubMenuItemId().getId().toString();
k++;
}
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(menuItem.getId(),checkSubMenuId);
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if(subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML+"<a href=\""+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
else {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/election/"+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
}
subMenuHTML = subMenuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0);\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i>"+menuItem.getName()+"</a><div class=\"submenu-content\">"+subSubMenuHTML+"</div></div>";
}
else {
subMenuHTML = subMenuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0);\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i>"+menuItem.getName()+"</a></div>";
}
}
}
else {
if(menuItem.getOrderby()>0) {
subMenuHTML = subMenuHTML+"<a href=\"/election/"+menuItem.getUrl()+"\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i><span>"+menuItem.getName()+"</span></a>";
}
}
}
menuHTML = menuHTML+subMenuHTML+"</div></div>";
}
return menuHTML;
}
}

16
src/main/java/com/gcc/election/controller/login.java

@ -0,0 +1,16 @@
package com.gcc.election.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/election")
@Controller("electionLoginController")
public class login {
@GetMapping("/login")
public String home(Model model) {
return "login";
}
}

260
src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java

@ -0,0 +1,260 @@
package com.gcc.election.dataentry.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.election.dataentry.service.BatchAPIService;
@RestController
@RequestMapping("/election/api/dataentry/batch")
public class BatchAPIController {
@Autowired
private BatchAPIService batchAPIService;
// to get batch details for data entry screen (with count)
@GetMapping("/getBatchDetails")
public ResponseEntity<?> getBatchDetails() {
try {
List<Map<String, Object>> list = batchAPIService.getBatchDetails();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getbatchbyId")
public ResponseEntity<?> getBatchById(@RequestParam String id) {
try {
Map<String, Object> list = batchAPIService.getBatchById(id);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getAllDesignations")
public ResponseEntity<?> getAllDesignations(){
try {
List<Map<String, Object>> list = batchAPIService.getAllDesignations();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getPayDetails")
public ResponseEntity<?> getPayDetails(@RequestParam int DesgId) {
try {
Map<String, Object> list = batchAPIService.getPayDetailsByDesgId(DesgId);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getAllDistricts")
public ResponseEntity<?> getAllDistricts(){
try {
List<Map<String, Object>> list = batchAPIService.getAllDistricts();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getAllAclist")
public ResponseEntity<?> getAllAcList(){
try {
List<Map<String, Object>> list = batchAPIService.getAllAcList();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getOfficeDetailsById")
public ResponseEntity<?> getOfficeDetailsById(@RequestParam int officeId){
try {
List<Map<String, Object>> list = batchAPIService.getOfficeDetailsById(officeId);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@PostMapping("/savenewentry")
public ResponseEntity<Map<String, Object>> savenewentry(
@RequestParam String pBatchId, @RequestParam String pName,
@RequestParam (name="pAge", required = false) String pAge, @RequestParam String pGender,
@RequestParam String Designation, @RequestParam int DesignationId,
@RequestParam int DeptId, @RequestParam int officeId,
@RequestParam(name="address1", required = false) String address1,
@RequestParam(name="address2", required = false) String address2,
@RequestParam(name="address3", required = false) String address3,
@RequestParam(name="pincode", required = false) Integer pincode,
@RequestParam(name="policest", required = false) String policest,
@RequestParam(name="phoneno", required = false) String phoneno,
@RequestParam(name="mobileno", required = false) String mobileno,
@RequestParam(name="district", required = false) Integer district,
@RequestParam(name="nativeac", required = false) Integer nativeac,
@RequestParam(name="resideac", required = false) Integer resideac,
@RequestParam(name="electoracno", required = false) Integer electoracno,
@RequestParam(name="electorpartno", required = false) Integer partno,
@RequestParam(name="electorslno", required = false) Integer electorslno,
@RequestParam(name="epicno", required = false) String epicno,
@RequestParam String userid
){
//int mcount = 0;
int ecount = 0;
// if (mobileno != null && !mobileno.trim().isEmpty()) {
// mcount = batchAPIService.checkMobile(mobileno);
// }
if (epicno != null && !epicno.trim().isEmpty()) {
ecount = batchAPIService.checkEpicno(epicno);
}
// if (mcount > 0) {
// return ResponseEntity.ok(Map.of(
// "status", false,
// "message", "mobile number already entered",
// "description", "Duplicate entry (Mobile Number already entered)"
// ));
// }
if (ecount > 0) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "epic number already entered",
"description", "Duplicate entry (EPIC Number already entered)"
));
}
String saveStatus= batchAPIService.saveNewEntry(pBatchId,pName,pAge,pGender,Designation,DesignationId,DeptId,officeId,address1,address2,address3,
pincode,policest,phoneno,mobileno,district,nativeac,resideac,electoracno,partno,electorslno,epicno,
userid);
if (saveStatus == null || saveStatus.equals("error")) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Failed to save the details"
));
}
return ResponseEntity.ok(Map.of(
"status", true,
"message", "success",
"description", "Details Saved Successfully" ,
"unique_no", saveStatus
));
}
}

108
src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java

@ -0,0 +1,108 @@
package com.gcc.election.dataentry.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.gcc.election.dataentry.service.BatchAPIService;
import com.gcc.election.service.LoginUserInfo;
@RequestMapping("/election/dataentry")
@Controller("electionDataentryController")
public class Maincontroller {
@Autowired
private BatchAPIService batchService;
@GetMapping("/dashboard")
public String dashboard(Model model) {
return "modules/dataentry/dashboard";
}
@GetMapping("/batches")
public String batches(Model model) {
return "modules/dataentry/batches";
}
@GetMapping("/batchbyid")
public String batchById(@RequestParam String batchid, Model model) {
if (batchid == null || batchid.trim().isEmpty()) {
return "modules/dataentry/batches";
}
Map<String, Object> batchdetails = batchService.getBatchById(batchid);
Object pendingObj = batchdetails.get("pending");
int pending = 0;
if (pendingObj != null) {
try {
pending = Integer.parseInt(pendingObj.toString());
} catch (NumberFormatException e) {
pending = 0;
}
}
if (pending == 0) {
return "modules/dataentry/batches";
}
model.addAttribute("batchdetails", batchdetails);
return "modules/dataentry/batchbyid";
}
@GetMapping("/newentry")
public String newEntry(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId",LoginUserId);
return "modules/dataentry/newentry";
}
@GetMapping("/updation")
public String updation(Model model) {
return "modules/dataentry/updation";
}
@GetMapping("/updateform")
public String updateform(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId",LoginUserId);
return "modules/dataentry/updateform";
}
@GetMapping("/verification")
public String verification(Model model) {
return "modules/dataentry/verification";
}
@GetMapping("/notices")
public String notices(Model model) {
return "modules/dataentry/notices";
}
}

175
src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java

@ -0,0 +1,175 @@
package com.gcc.election.dataentry.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.gcc.election.dataentry.service.BatchAPIService;
import com.gcc.election.dataentry.service.UpdationService;
@RestController
@RequestMapping("/election/api/dataentry/update")
public class UpdationAPIController {
@Autowired
private UpdationService upservice;
@GetMapping("/getbymobanduniq")
public ResponseEntity<?> getbymobanduniq(
@RequestParam(name="mobilenum", required = false) String mobilenum,
@RequestParam(name="uniquenum", required = false) String uniquenum,
@RequestParam(name="batch_num", required = false) String batch_num
)
{
try {
List<Map<String, Object>> list=upservice.getbymobanduniq(mobilenum,uniquenum,batch_num);
Map<String, Object> response = new HashMap<>();
if(list.isEmpty()) {
response.put("status", "no_data");
response.put("data", "No Data Available");
}
else {
response.put("status", "success");
response.put("data", list);
}
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getPollingDetailsById")
public ResponseEntity<?> getPollingDetailsById(@RequestParam int id){
try {
List<Map<String, Object>> list = upservice.getPollingDetailsById(id);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@PostMapping("/updateppdetailsbyid")
public ResponseEntity<Map<String, Object>> updateppdetailsbyid(
@RequestParam String pBatchId, @RequestParam String pName,
@RequestParam (name="pAge", required = false) String pAge, @RequestParam String pGender,
@RequestParam String Designation, @RequestParam int DesignationId,
@RequestParam int DeptId, @RequestParam int officeId,
@RequestParam(name="address1", required = false) String address1,
@RequestParam(name="address2", required = false) String address2,
@RequestParam(name="address3", required = false) String address3,
@RequestParam(name="pincode", required = false) Integer pincode,
@RequestParam(name="policest", required = false) String policest,
@RequestParam(name="phoneno", required = false) String phoneno,
@RequestParam(name="mobileno", required = false) String mobileno,
@RequestParam(name="district", required = false) Integer district,
@RequestParam(name="nativeac", required = false) Integer nativeac,
@RequestParam(name="resideac", required = false) Integer resideac,
@RequestParam(name="electoracno", required = false) Integer electoracno,
@RequestParam(name="electorpartno", required = false) Integer partno,
@RequestParam(name="electorslno", required = false) Integer electorslno,
@RequestParam(name="epicno", required = false) String epicno,
@RequestParam String userid,
@RequestParam String nppid,
@RequestParam String slno,
@RequestParam (required = false)MultipartFile pp_image
){
int ecount = 0;
if (epicno != null && !epicno.trim().isEmpty()) {
ecount = upservice.checkEpicno(epicno,nppid);
}
if (ecount > 0) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "epic number already entered",
"description", "Duplicate entry (EPIC Number already entered)"
));
}
System.out.println("pp_image==="+pp_image);
if(pp_image!=null && !pp_image.isEmpty()) {
String filesave=upservice.fileUpload(nppid,pp_image,userid,slno);
if(filesave.equalsIgnoreCase("error")) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Error in Image Processing"
));
}
}
String logEntry=upservice.logentry(nppid);
if(logEntry.equalsIgnoreCase("success")) {
String saveStatus= upservice.updateppdetailsbyid(pBatchId,pName,pAge,pGender,Designation,DesignationId,DeptId,officeId,address1,address2,address3,
pincode,policest,phoneno,mobileno,district,nativeac,resideac,electoracno,partno,electorslno,epicno,
userid,nppid);
if (saveStatus == null || saveStatus.equals("error")) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Failed to Update the details"
));
}
return ResponseEntity.ok(Map.of(
"status", true,
"message", "success",
"description", "Details Updated Successfully"
));
}
else {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Failed to insert in log details"
));
}
}
}

214
src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java

@ -0,0 +1,214 @@
package com.gcc.election.dataentry.service;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.Query;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
@Service
public class BatchAPIService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getBatchDetails() {
String sql = "select b.id, date_format(b.rec_date, '%d-%m-%Y') as rec_date, dm.dept_name, od.office_name, "
+ " b.noof_application, count(ppn.batch_no) as completed, (b.noof_application - count(ppn.batch_no)) as pending from batch_master b"
+ " left join poll_person_new ppn on b.id = ppn.batch_no"
+ " left join dept_master dm on b.dept_id = dm.dept_id"
+ " left join office_details od on b.office_id = od.id"
+ " where b.is_active = 1"
+ " group by b.id, ppn.batch_no";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public Map<String, Object> getBatchById(String id) {
String sql = "SELECT bm.id, DATE_FORMAT(bm.rec_date, '%Y-%m-%d') AS rec_date, bm.noof_application,DATE_FORMAT(bm.rec_date, '%d-%m-%Y') AS received_date,om.id as office_id,dm.dept_id as dept_id, "
+ "dm.dept_name, "
+ "om.office_name ,count(ppn.batch_no) as completed,(bm.noof_application - count(ppn.batch_no)) as pending "
+ "FROM batch_master bm "
+ "LEFT JOIN dept_master dm ON dm.dept_id = bm.dept_id "
+ "LEFT JOIN office_details om ON om.id = bm.office_id "
+ " LEFT JOIN poll_person_new ppn on bm.id = ppn.batch_no "
+ "WHERE bm.id = ? AND bm.is_active = 1";
try {
return jdbcTemplate.queryForMap(sql, id);
} catch (Exception ex) {
ex.printStackTrace();
return new HashMap<>();
}
}
public List<Map<String, Object>> getAllDesignations() {
String sql="SELECT * FROM designation WHERE is_active=1 AND is_delete=0 ORDER BY new_designation";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public Map<String, Object> getPayDetailsByDesgId(int desgId) {
String sql = "SELECT * FROM designation WHERE desig_id = ? AND is_active = 1";
try {
return jdbcTemplate.queryForMap(sql, desgId);
}
catch (Exception e) {
e.printStackTrace();
return new HashMap<>();
}
}
public List<Map<String, Object>> getAllAcList() {
String sql="SELECT * FROM ac_list_all WHERE is_active=1 ORDER BY ac_name";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public List<Map<String, Object>> getAllDistricts() {
String sql="SELECT * FROM district_master WHERE is_active=1 ORDER BY dist_name";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public List<Map<String, Object>> getOfficeDetailsById(int officeId) {
String sql = "SELECT od.*,dm.dept_name as office_category,al.ac_name as office_assembly"
+ " FROM office_details od "
+ " LEFT JOIN dept_master dm ON dm.dept_id=od.dept_id "
+ " LEFT JOIN ac_list_all al ON al.ac_no = od.work_ac_no "
+ " WHERE od.id = ? AND od.is_active = 1";
try {
return jdbcTemplate.queryForList(sql,officeId);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public String saveNewEntry(String pBatchId, String pName, String pAge, String pGender, String designation,
int designationId, int deptId, int officeId, String address1, String address2, String address3,
Integer pincode, String policest, String phoneno, String mobileno, Integer district, Integer nativeac,
Integer resideac, Integer electoracno, Integer partno, Integer electorslno, String epicno,String userid) {
String pAgeVal = (pAge != null && !pAge.trim().isEmpty()) ? pAge : null;
String address1Val = (address1 != null && !address1.trim().isEmpty()) ? address1.toUpperCase() : null;
String address2Val = (address2 != null && !address2.trim().isEmpty()) ? address2.toUpperCase() : null;
String address3Val = (address3 != null && !address3.trim().isEmpty()) ? address3.toUpperCase() : null;
String policestVal = (policest != null && !policest.trim().isEmpty()) ? policest.toUpperCase() : null;
String phonenoVal = (phoneno != null && !phoneno.trim().isEmpty()) ? phoneno : null;
String mobilenoVal = (mobileno != null && !mobileno.trim().isEmpty()) ? mobileno : null;
String epicnoVal = (epicno != null && !epicno.trim().isEmpty()) ? epicno.toUpperCase() : null;
String sql = "INSERT INTO poll_person_new ("
+ " dept,name,age,sex,designation_id,office_id,r_address1,r_address2,r_address3,r_pincode,r_phone_no,r_mobile_no,"
+ " r_policest,home_dist,native_ac_no,reside_ac_no,elector_ac_no,elector_part_no,elector_sl_no,elector_epic_no,"
+ " batch_no,created_by "
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int result = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
ps.setInt(1, deptId);
ps.setString(2, pName);
ps.setString(3, pAgeVal);
ps.setString(4, pGender);
ps.setInt(5, designationId);
ps.setInt(6, officeId);
ps.setString(7, address1Val);
ps.setString(8, address2Val);
ps.setString(9, address3Val);
if (pincode != null) ps.setInt(10, pincode);
else ps.setNull(10, java.sql.Types.INTEGER);
ps.setString(11, phonenoVal);
ps.setString(12, mobilenoVal);
ps.setString(13, policestVal);
if (district != null) ps.setInt(14, district);
else ps.setNull(14, java.sql.Types.INTEGER);
if (nativeac != null) ps.setInt(15, nativeac);
else ps.setNull(15, java.sql.Types.INTEGER);
if (resideac != null) ps.setInt(16, resideac);
else ps.setNull(16, java.sql.Types.INTEGER);
if (electoracno != null) ps.setInt(17, electoracno);
else ps.setNull(17, java.sql.Types.INTEGER);
if (partno != null) ps.setInt(18, partno);
else ps.setNull(18, java.sql.Types.INTEGER);
if (electorslno != null) ps.setInt(19, electorslno);
else ps.setNull(19, java.sql.Types.INTEGER);
ps.setString(20,epicnoVal);
ps.setString(21,pBatchId);
ps.setString(22,userid);
return ps;
}, keyHolder);
//return keyHolder.getKey().intValue();
if (result > 0) {
int generatedId = keyHolder.getKey().intValue();
int slnoNumeric = 100000 + generatedId;
String slnoString = String.valueOf(slnoNumeric);
String updateSql = "UPDATE poll_person_new SET slno = ? WHERE id = ?";
jdbcTemplate.update(updateSql, slnoString, generatedId);
return slnoString;
}
//return "error";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
public int checkMobile(String mobileno) {
String sql="SELECT count(*) FROM poll_person_new WHERE r_mobile_no=? AND is_active=1";
return jdbcTemplate.queryForObject(sql, Integer.class, mobileno);
}
public int checkEpicno(String epicno) {
String sql="SELECT count(*) FROM poll_person_new WHERE elector_epic_no=? AND is_active=1";
return jdbcTemplate.queryForObject(sql, Integer.class, epicno);
}
}

302
src/main/java/com/gcc/election/dataentry/service/UpdationService.java

@ -0,0 +1,302 @@
package com.gcc.election.dataentry.service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import com.gcc.election.controller.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class UpdationService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Autowired
private Environment environment;
private String fileBaseUrl;
public UpdationService(Environment environment) {
this.fileBaseUrl = environment.getProperty("fileBaseUrl");
}
public List<Map<String, Object>> getbymobanduniq(String mobilenum, String uniquenum,String batch_num) {
StringBuilder sql = new StringBuilder("SELECT pp.*,CONCAT_WS(',',pp.r_address1,r_address2,r_address3,r_pincode) as res_address,dm.dept_name as dept_name,dg.new_designation as new_designation,od.office_name as office_name,CONCAT_WS(', ', od.address1, od.address2, od.address3, od.pincode) AS office_address,bm.id as batch_id,al.ac_name as res_assembly,al2.ac_name as native_assembly,al3.ac_name as enrolled_assembly,"
+ "dg.pay_scale as pay_scale,dg.grade_pay as grade_pay,dg.basic_pay as basic_pay,od.govt_type as govt_type,od.work_ac_no as work_ac_no,al4.ac_name as work_assembly,pm.image_path as raw_path, "
+ "CONCAT('" + fileBaseUrl + "', pm.image_path) AS img_full_path "
//+ " 'https://gccservices.in/gccofficialapp/files/asset_activity/2/2_after_725115_14112025105400_7760.jpeg' as img_full_path "
+ " FROM poll_person_new pp "
+ "LEFT JOIN dept_master dm ON dm.dept_id=pp.dept "
+ "LEFT JOIN designation dg ON dg.desig_id=pp.designation_id "
+ "LEFT JOIN ac_list_all al ON (al.ac_no = pp.reside_ac_no) "
+ "LEFT JOIN ac_list_all al2 ON (al2.ac_no = pp.native_ac_no) "
+ "LEFT JOIN ac_list_all al3 ON (al3.ac_no = pp.elector_ac_no) "
+ "LEFT JOIN office_details od ON od.id=pp.office_id "
+ "LEFT JOIN ac_list_all al4 ON (al4.ac_no = od.work_ac_no) "
+ "LEFT JOIN batch_master bm ON bm.id=pp.batch_no "
+ "LEFT JOIN poll_person_images pm ON pm.ppn_id=pp.id "
+ "WHERE pp.is_active = 1");
List<Object> params = new ArrayList<>();
// Add conditions dynamically
if (mobilenum != null && !mobilenum.trim().isEmpty()) {
sql.append(" AND pp.r_mobile_no = ?");
params.add(mobilenum);
}
if (uniquenum != null && !uniquenum.trim().isEmpty()) {
sql.append(" AND pp.slno = ?");
params.add(uniquenum);
}
if (batch_num != null && !batch_num.trim().isEmpty()) {
sql.append(" AND pp.batch_no = ?");
params.add(batch_num);
}
// Ensure at least one parameter is provided
if (params.isEmpty()) {
return new ArrayList<>(); // or throw exception
}
//System.out.println("sql==="+sql);
try {
return jdbcTemplate.queryForList(sql.toString(), params.toArray());
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>();
}
}
//
public List<Map<String, Object>> getPollingDetailsById(int id) {
String sql = "SELECT pp.*,pm.image_path as img_raw_path, "
+ "CONCAT('" + fileBaseUrl + "', pm.image_path) AS img_full_path "
//+ " 'https://gccservices.in/gccofficialapp/files/asset_activity/2/2_after_725115_14112025105400_7760.jpeg' as img_full_path "
+ " FROM poll_person_new pp "
+ " LEFT JOIN poll_person_images pm ON pm.ppn_id=pp.id "
+ " WHERE pp.id = ? AND pp.is_active = 1 AND pp.is_delete=0";
try {
return jdbcTemplate.queryForList(sql,id);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public String logentry(String nppid) {
String sql="INSERT INTO poll_person_new_log"
+ "(slno,dept,name,age,sex,designation_id,category_id,office_id,r_address1,r_address2,r_address3,r_pincode,r_std_code,"
+ "r_phone_no,r_mobile_no,r_policest,home_dist,native_ac_no,reside_ac_no,elector_ac_no,elector_part_no,elector_sl_no,elector_epic_no,"
+ "officiated,officiated_det,evm_experience,disqualified,category,status,allocation,allot_ac,team_code,allot_pc,allot_ps,c_code,record_no,"
+ "rnd_no,emp_no,designation,batch,old_c_code,hall_no,batch_no,taluk,user_sno,entry_batch,cdate,created_by,updated_by,is_active,is_delete) "
+ "SELECT slno,dept,name,age,sex,designation_id,category_id,office_id,r_address1,r_address2,r_address3,r_pincode,r_std_code,"
+ "r_phone_no,r_mobile_no,r_policest,home_dist,native_ac_no,reside_ac_no,elector_ac_no,elector_part_no,elector_sl_no,elector_epic_no,"
+ "officiated,officiated_det,evm_experience,disqualified,category,status,allocation,allot_ac,team_code,allot_pc,allot_ps,c_code,record_no,"
+ "rnd_no,emp_no,designation,batch,old_c_code,hall_no,batch_no,taluk,user_sno,entry_batch,cdate,created_by,updated_by,is_active,is_delete "
+ "FROM poll_person_new WHERE id=? ";
try {
jdbcTemplate.update(sql,nppid);
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "error";
}
}
public String updateppdetailsbyid(String pBatchId, String pName, String pAge, String pGender,
String designation, int designationId, int deptId, int officeId, String address1, String address2,
String address3, Integer pincode, String policest, String phoneno, String mobileno, Integer district,
Integer nativeac, Integer resideac, Integer electoracno, Integer partno, Integer electorslno,
String epicno, String userid, String nppid) {
String pAgeVal = (pAge != null && !pAge.trim().isEmpty()) ? pAge : null;
String address1Val = (address1 != null && !address1.trim().isEmpty()) ? address1.toUpperCase() : null;
String address2Val = (address2 != null && !address2.trim().isEmpty()) ? address2.toUpperCase() : null;
String address3Val = (address3 != null && !address3.trim().isEmpty()) ? address3.toUpperCase() : null;
String policestVal = (policest != null && !policest.trim().isEmpty()) ? policest.toUpperCase() : null;
String phonenoVal = (phoneno != null && !phoneno.trim().isEmpty()) ? phoneno : null;
String mobilenoVal = (mobileno != null && !mobileno.trim().isEmpty()) ? mobileno : null;
String epicnoVal = (epicno != null && !epicno.trim().isEmpty()) ? epicno.toUpperCase() : null;
String sql="UPDATE poll_person_new SET dept=?,name=?,age=?,sex=?,designation_id=?,office_id=?,r_address1=?,r_address2=?,r_address3=?,r_pincode=?,"
+ "r_phone_no=?,r_mobile_no=?,r_policest=?,home_dist=?,native_ac_no=?,reside_ac_no=?,elector_ac_no=?,elector_part_no=?,elector_sl_no=?,elector_epic_no=?,"
+ "batch_no=?,updated_by=?,updated_date=NOW() "
+ "WHERE id=? AND is_active=1 ";
try {
int update = jdbcTemplate.update(sql,
deptId,
pName,
pAgeVal,
pGender,
designationId,
officeId,
address1Val,
address2Val,
address3Val,
pincode != null ? pincode : null,
phonenoVal,
mobilenoVal,
policestVal,
district != null ? district : null,
nativeac != null ? nativeac : null,
resideac != null ? resideac : null,
electoracno != null ? electoracno : null,
partno != null ? partno : null,
electorslno != null ? electorslno : null,
epicnoVal,
pBatchId,
userid,
nppid
);
if (update > 0) {
return "success";
}
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
public int checkEpicno(String epicno,String nppid) {
String sql="SELECT count(*) FROM poll_person_new WHERE elector_epic_no=? AND id!=? AND is_active=1";
return jdbcTemplate.queryForObject(sql, Integer.class, epicno,nppid);
}
public String fileUpload(String nppid, MultipartFile pp_image, String userid, String slno) {
String sql = "SELECT image_path FROM poll_person_images WHERE ppn_id=? AND is_active=1 AND is_delete=0";
String existingpath = "";
try {
List<String> result = jdbcTemplate.query(
sql,
(rs, rowNum) -> rs.getString("image_path"),
nppid
);
existingpath = result.isEmpty() ? "" : result.get(0);
} catch (Exception e) {
e.printStackTrace();
return "error";
}
try {
String imgPath = saveimage(pp_image, "profile_img");
if ("error".equalsIgnoreCase(imgPath)) return "error";
if (existingpath.isEmpty()) {
String insertSql = "INSERT INTO poll_person_images (ppn_id, slno, image_path, created_by) VALUES (?, ?, ?, ?)";
jdbcTemplate.update(insertSql, nppid, slno, imgPath, userid);
return "success";
} else {
imgLog(nppid);
String updateSql = "UPDATE poll_person_images SET image_path=?, updated_by=?, updated_date=NOW() WHERE ppn_id=? AND is_active=1";
jdbcTemplate.update(updateSql, imgPath, userid, nppid);
return "success";
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
private void imgLog(String nppid) {
String sql="INSERT INTO poll_person_images_log (ppn_id,slno,image_path,is_active,is_delete,created_by,created_date,updated_by) "
+ "SELECT ppn_id,slno,image_path,is_active,is_delete,created_by,created_date,updated_by FROM poll_person_images WHERE ppn_id=? ";
try {
jdbcTemplate.update(sql, nppid);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
private String saveimage(MultipartFile file, String name) {
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("election_profile_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
uploadDirectory = uploadDirectory + serviceFolderName + "/" + year + "/" + month;
try {
// Create directory if it doesn't exist
Path directoryPath = Paths.get(uploadDirectory);
if (!Files.exists(directoryPath)) {
Files.createDirectories(directoryPath);
}
// Datetime string
String datetimetxt = DateTimeUtil.getCurrentDateTime();
// File name
String fileName = name + "_" + datetimetxt + "_" + file.getOriginalFilename();
fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename
String filePath = uploadDirectory + "/" + fileName;
String filepath_txt = "/" + serviceFolderName + "/" + year + "/" + month + "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
Files.write(path, bytes);
System.out.println(filePath);
System.out.println(" filepath_txt=="+ filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}

117
src/main/java/com/gcc/election/entity/AppModuleAccessEntity.java

@ -0,0 +1,117 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "modules_access")
public class AppModuleAccessEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppModuleAccessEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AppUserGroupEntity getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(AppUserGroupEntity userGroupId) {
this.userGroupId = userGroupId;
}
public AppModuleEntity getModuleId() {
return moduleId;
}
public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

137
src/main/java/com/gcc/election/entity/AppModuleEntity.java

@ -0,0 +1,137 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "modules")
public class AppModuleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "module_path",nullable = false)
private String modulePath;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppModuleEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModulePath() {
return modulePath;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public void setModulePath(String modulePath) {
this.modulePath = modulePath;
}
public Integer getOrderby() {
return orderby;
}
public void setOrderby(Integer orderby) {
this.orderby = orderby;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

156
src/main/java/com/gcc/election/entity/AppUserEntity.java

@ -0,0 +1,156 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "appusers")
public class AppUserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userid", referencedColumnName = "userid")
private UserInfoEntity userid;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity usergroup_id;
@Column(name = "username",nullable = false)
private String username;
@Column(name = "password",nullable = false)
private String password;
@Column(name = "roles",nullable = false)
private String roles;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppUserEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UserInfoEntity getUserid() {
return userid;
}
public void setUserid(UserInfoEntity userid) {
this.userid = userid;
}
public AppUserGroupEntity getUsergroup_id() {
return usergroup_id;
}
public void setUsergroup_id(AppUserGroupEntity usergroup_id) {
this.usergroup_id = usergroup_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

112
src/main/java/com/gcc/election/entity/AppUserGroupEntity.java

@ -0,0 +1,112 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "usergroup")
public class AppUserGroupEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppUserGroupEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

131
src/main/java/com/gcc/election/entity/MenuItemAccessEntity.java

@ -0,0 +1,131 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "menuitem_access")
public class MenuItemAccessEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@ManyToOne
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public MenuItemAccessEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AppUserGroupEntity getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(AppUserGroupEntity userGroupId) {
this.userGroupId = userGroupId;
}
public MenuItemEntity getMenuItemId() {
return menuItemId;
}
public void setMenuItemId(MenuItemEntity menuItemId) {
this.menuItemId = menuItemId;
}
public AppModuleEntity getModuleId() {
return moduleId;
}
public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

168
src/main/java/com/gcc/election/entity/MenuItemEntity.java

@ -0,0 +1,168 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "menuitem")
public class MenuItemEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "url",nullable = false)
private String url;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "ishassub",nullable = false, columnDefinition = "Boolean default false")
private Boolean hasSub;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public MenuItemEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AppModuleEntity getModuleId() {
return moduleId;
}
public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIcon() {
return icon;
}
public Integer getOrderby() {
return orderby;
}
public void setOrderby(Integer orderby) {
this.orderby = orderby;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Boolean getHasSub() {
return hasSub;
}
public void setHasSub(Boolean hasSub) {
this.hasSub = hasSub;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

146
src/main/java/com/gcc/election/entity/SubMenuItemAccessEntity.java

@ -0,0 +1,146 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "submenuitem_access")
public class SubMenuItemAccessEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "submenuitem_id", referencedColumnName = "id")
private SubMenuItemEntity subMenuItemId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public SubMenuItemAccessEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AppUserGroupEntity getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(AppUserGroupEntity userGroupId) {
this.userGroupId = userGroupId;
}
public SubMenuItemEntity getSubMenuItemId() {
return subMenuItemId;
}
public void setSubMenuItemId(SubMenuItemEntity subMenuItemId) {
this.subMenuItemId = subMenuItemId;
}
public AppModuleEntity getModuleId() {
return moduleId;
}
public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId;
}
public MenuItemEntity getMenuItemId() {
return menuItemId;
}
public void setMenuItemId(MenuItemEntity menuItemId) {
this.menuItemId = menuItemId;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

181
src/main/java/com/gcc/election/entity/SubMenuItemEntity.java

@ -0,0 +1,181 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "submenuitem")
public class SubMenuItemEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "url",nullable = false)
private String url;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@Column(name = "extenallink",nullable = false, columnDefinition = "Boolean default true")
private Boolean extenalLink;
public SubMenuItemEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AppModuleEntity getModuleId() {
return moduleId;
}
public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId;
}
public MenuItemEntity getMenuItemId() {
return menuItemId;
}
public void setMenuItemId(MenuItemEntity menuItemId) {
this.menuItemId = menuItemId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getOrderby() {
return orderby;
}
public void setOrderby(Integer orderby) {
this.orderby = orderby;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
public Boolean getExtenalLink() {
return extenalLink;
}
public void setExtenalLink(Boolean extenalLink) {
this.extenalLink = extenalLink;
}
}

62
src/main/java/com/gcc/election/entity/UserActivityLog.java

@ -0,0 +1,62 @@
package com.gcc.election.entity;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_activity_log")
public class UserActivityLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String activityType;
private LocalDateTime timestamp;
public UserActivityLog() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
}

109
src/main/java/com/gcc/election/entity/UserInfoEntity.java

@ -0,0 +1,109 @@
package com.gcc.election.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "userinfo")
public class UserInfoEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "userid",nullable = false)
private Integer userid;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "email")
private String email;
@Column(name = "phone")
private String phone;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public UserInfoEntity() {
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public String getcDate() {
return cDate;
}
public void setcDate(String cDate) {
this.cDate = cDate;
}
}

321
src/main/java/com/gcc/election/interceptor/AppInterceptor.java

@ -0,0 +1,321 @@
package com.gcc.election.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.service.LoginUserInfo;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AppInterceptor implements HandlerInterceptor{
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<MenuItemAccessEntity> getMenuItemAccessEntities;
List<SubMenuItemAccessEntity> getSubMenuItemAccessEntities;
private AppModuleAccessRepository appModuleAccessRepository;
private MenuItemAccessRepository menuItemAccessRepository;
private SubMenuItemAccessRepository subMenuItemAccessRepository;
List<AppModuleEntity> getAppModuleEntities;
List<MenuItemEntity> getMenuItemEntities;
List<SubMenuItemEntity> getSubMenuItemEntities;
private AppModuleRepository appModuleRepository;
private MenuItemRepository menuItemRepository;
private SubMenuItemRepository subMenuItemRepository;
private final Environment environment;
@Autowired
public AppInterceptor(AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
Environment environment) {
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.environment = environment;
}
private boolean isLoginPage(HttpServletRequest request) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/election/login");
return loginPageMatcher.matches(request);
}
private boolean isErrorPage(HttpServletRequest request) {
RequestMatcher errorPageMatcher = new AntPathRequestMatcher("/election/error");
return errorPageMatcher.matches(request);
}
private boolean isfavicon(HttpServletRequest request) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/favicon.ico");
return loginPageMatcher.matches(request);
}
public static String[] Split(String request,String patten) {
String path = request;
// Split the string by "/"
String[] parts = path.split(patten);
/*
// Display the parts
for (String part : parts) {
System.out.println(part);
}
*/
return parts;
}
private boolean hasModuleAccess(String moduleName) {
getAppModuleEntities = appModuleRepository.findByModulePath(moduleName);
//System.out.println("DataTable Size for the url ("+moduleName+"): "+getAppModuleEntities.size());
String moduleid = null;
if(getAppModuleEntities.size()>0) {
for ( AppModuleEntity appModuleEntity : getAppModuleEntities) {
moduleid = appModuleEntity.getId().toString();
}
if(moduleid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasModuleAccess : Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid);
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(userGroupId,moduleid);
//System.out.println("After Check in(hasModuleAccess):"+getAppModuleAccessEntities.size());
if(getAppModuleAccessEntities.size()>0) {
return true;
}
else {
System.out.println("hasModuleAccess : getAppModuleAccessEntities.size = " + getAppModuleAccessEntities.size());
}
}
}
return false;
}
private boolean hasMenuAccess(String url,String moduleName,String menuName) {
if(!hasModuleAccess(moduleName)) {return false; }
getMenuItemEntities = menuItemRepository.findByUrl(url);
//System.out.println("DataTable Size for the url ("+url+"): "+getMenuItemEntities.size());
String moduleid = null;
String menuid = null;
if(getMenuItemEntities.size()>0) {
for (MenuItemEntity MenuEntity : getMenuItemEntities) {
moduleid = MenuEntity.getModuleId().getId().toString();
menuid = MenuEntity.getId().toString();
}
if(moduleid != null && menuid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasMenuAccess : Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid);
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId,moduleid,menuid);
if(getMenuItemAccessEntities.size()>0) {
return true;
}
}
}
return false;
}
private boolean hasSubMenuAccess(String url,String moduleName,String menuName,String subMenuName) {
if(!hasModuleAccess(moduleName)) {return false; }
getSubMenuItemEntities = subMenuItemRepository.findByUrl(url);
//System.out.println("DataTable Size for the url ("+url+"): "+getSubMenuItemEntities.size());
String moduleid = null;
String menuid = null;
String submenuid = null;
if(getSubMenuItemEntities.size()>0) {
for (SubMenuItemEntity subMenuEntity : getSubMenuItemEntities) {
moduleid = subMenuEntity.getModuleId().getId().toString();
menuid = subMenuEntity.getMenuItemId().getId().toString();
submenuid = subMenuEntity.getId().toString();
}
if(moduleid != null && menuid != null && submenuid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasSubMenuAccess 1: Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid+"\n submenuid : "+submenuid);
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(userGroupId,moduleid,menuid,submenuid);
if(getSubMenuItemAccessEntities.size()>0) {
// Check Parent Menu Access (Menu Access)
if(moduleid != null && menuid != null) {
System.out.println("hasSubMenuAccess 2: Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid);
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId,moduleid,menuid);
if(getMenuItemAccessEntities.size()>0) {
return true;
}
}
}
}
}
return false;
}
private boolean hasAccess(String path) {
String userRole = LoginUserInfo.getUserRole();
if (userRole != null && userRole.equals("ADMIN")) {
return true;
}
/*
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
return true;
}
*/
String url = removeLeadingSlash(path);
url = removeStartingString(url); // Remove parent App url "gcc"
//System.out.println("Give URL : "+path+" After remove leading slash : "+url);
// If default home page
if(path.equals("/")) {
return true;
}
//continue for access check
String[] parts = Split(url, "/");
if(parts.length<=0) {return true;}
//System.out.println("Part Length:"+ parts.length);
if(parts.length>1) {
int j=0;
for (String part : parts) {
System.out.println(j+") URL SPLIT: "+part);
j++;
}
String moduleName = "";
String menuName = "";
String subMenuName = "";
if(parts.length==1) { // Check Only Module Access
moduleName = parts[0];
return hasModuleAccess(moduleName);
}
else if(parts.length==2) { // Check Module & Menu Access
moduleName = parts[0];
menuName = parts[1];
subMenuName = "";
return hasMenuAccess(url,moduleName,menuName);
}
else if(parts.length==3) { // Check Module , Menu & Sub-Menu Access
moduleName = parts[0];
menuName = parts[1];
subMenuName = parts[2];
return hasSubMenuAccess(url,moduleName,menuName,subMenuName);
}
}
return true;
}
public static String removeLeadingSlash(String input) {
if (input.startsWith("/")) {
return input.substring(1);
}
return input;
}
public static String removeStartingString(String input) {
if (input.startsWith("election")) {
return removeLeadingSlash(input.substring(8));
}
return input;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String assetsBaseUrl = environment.getProperty("assets.base-url");
request.setAttribute("assetsBaseUrl", assetsBaseUrl);
if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
String fullRequestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String path = fullRequestURI.substring(contextPath.length());
if(!hasAccess(path)) {
//Object principal = authentication.getPrincipal();
//UserDetails userDetails = (UserDetails) principal;
//System.out.println("1) Access Deny For --- " + userDetails.getAuthorities().toString());
// Redirect to the error page
//response.sendRedirect(request.getContextPath() + "/error");
request.getRequestDispatcher("/error").forward(request, response);
// response.sendRedirect(request.getContextPath() + "/election/error");
// return false;
}
}
}
// Continue with the request processing
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// Check if the current request matches the login or error page URLs
if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) {
if (modelAndView != null) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
request.setAttribute("assetsBaseUrl", assetsBaseUrl);
modelAndView.addObject("assetsBaseUrl", assetsBaseUrl);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
modelAndView.addObject("currentUserDetails", userDetails);
System.out.println(userDetails);
}
}
}
}
}
}

55
src/main/java/com/gcc/election/modeldata/ErrorResponse.java

@ -0,0 +1,55 @@
package com.gcc.election.modeldata;
public class ErrorResponse {
private int status;
private String error;
private String message;
private String exception;
// Constructors, getters, and setters for the above fields
public ErrorResponse(int status, String error, String message, String exception) {
this.status = status;
this.error = error;
this.message = message;
this.exception = exception;
}
public ErrorResponse() {
super();
// TODO Auto-generated constructor stub
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
}

41
src/main/java/com/gcc/election/repository/AppModuleAccessRepository.java

@ -0,0 +1,41 @@
package com.gcc.election.repository;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppModuleAccessEntity;
@Repository
@Transactional
public interface AppModuleAccessRepository extends JpaRepository<AppModuleAccessEntity,Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `modules_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true)
List<AppModuleAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id);
@Query(value = "SELECT * FROM `modules_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true)
List<AppModuleAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id);
@Modifying
@Query(value = "INSERT INTO `modules_access`(`module_id`, `usergroup_id`) VALUES (:module_id,:usergroup_id)", nativeQuery = true)
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id);
@Modifying
@Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id", nativeQuery = true)
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id);
@Modifying
@Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true)
void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id);
}

30
src/main/java/com/gcc/election/repository/AppModuleRepository.java

@ -0,0 +1,30 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppModuleEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface AppModuleRepository extends JpaRepository<AppModuleEntity,Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `modules` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`", nativeQuery = true)
List<AppModuleEntity> showAll();
@Query(value = "SELECT * FROM `modules` WHERE `id` IN (:checkModuleid) AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id`", nativeQuery = true)
List<AppModuleEntity> showAllById(String[] checkModuleid);
@Query(value = "SELECT * FROM `modules` WHERE (`module_path` = :module_path) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<AppModuleEntity> findByModulePath(String module_path);
}

19
src/main/java/com/gcc/election/repository/AppUserGroupRepository.java

@ -0,0 +1,19 @@
package com.gcc.election.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppUserGroupEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface AppUserGroupRepository extends JpaRepository<AppUserGroupEntity,Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
}

28
src/main/java/com/gcc/election/repository/AppUserRepository.java

@ -0,0 +1,28 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppUserEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface AppUserRepository extends JpaRepository<AppUserEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `appusers`", nativeQuery = true)
List<AppUserEntity> showAll();
@Query(value = "SELECT * FROM `appusers` WHERE (userid=:userId AND `isdelete`=0)", nativeQuery = true)
List<AppUserEntity> showById(String userId);
AppUserEntity findByUsername(String username);
}

41
src/main/java/com/gcc/election/repository/MenuItemAccessRepository.java

@ -0,0 +1,41 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.MenuItemAccessEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface MenuItemAccessRepository extends JpaRepository<MenuItemAccessEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true)
List<MenuItemAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id);
@Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<MenuItemAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id);
@Modifying
@Query(value = "INSERT INTO `menuitem_access`(`menuitem_id`, `module_id`, `usergroup_id`) VALUES (:menuitem_id,:module_id,:usergroup_id)", nativeQuery = true)
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id);
@Modifying
@Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id", nativeQuery = true)
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id);
@Modifying
@Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true)
void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id);
}

31
src/main/java/com/gcc/election/repository/MenuItemRepository.java

@ -0,0 +1,31 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.MenuItemEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface MenuItemRepository extends JpaRepository<MenuItemEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true)
List<MenuItemEntity> getMenuItemByModuleId(@Param("module_id") int module_id);
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`module_id`=:module_id AND `id` IN (:checkMenuid)) ORDER BY `orderby`", nativeQuery = true)
List<MenuItemEntity> getMenuItemByModuleIdAccess(@Param("module_id") int module_id, String[] checkMenuid);
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`url`=:url) LIMIT 0,1", nativeQuery = true)
List<MenuItemEntity> findByUrl(@Param("url") String url);
}

42
src/main/java/com/gcc/election/repository/SubMenuItemAccessRepository.java

@ -0,0 +1,42 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface SubMenuItemAccessRepository extends JpaRepository<SubMenuItemAccessEntity, Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `submenuitem_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true)
List<SubMenuItemAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id);
@Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true)
List<SubMenuItemAccessEntity> findByUserGroupIDAccess(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id);
@Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<SubMenuItemAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id,@Param("submenuitem_id") String submenuitem_id);
@Modifying
@Query(value = "INSERT INTO `submenuitem_access`(`submenuitem_id`, `menuitem_id`, `module_id`, `usergroup_id`) VALUES (:submenuitem_id, :menuitem_id, :module_id, :usergroup_id)", nativeQuery = true)
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id);
@Modifying
@Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id", nativeQuery = true)
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id);
@Modifying
@Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true)
void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id);
}

34
src/main/java/com/gcc/election/repository/SubMenuItemRepository.java

@ -0,0 +1,34 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.SubMenuItemEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface SubMenuItemRepository extends JpaRepository<SubMenuItemEntity, Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByModuleId(@Param("module_id") int module_id);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `menuitem_id`=:menuitem_id ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByMenuItemId(@Param("menuitem_id") int menuitem_id);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`menuitem_id`=:menuitem_id AND `id` IN (:checkSubMenuid)) ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByMenuItemIdAccess(@Param("menuitem_id") int menuitem_id,String[] checkSubMenuid);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`url`=:url) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<SubMenuItemEntity> findByUrl(@Param("url") String url);
}

19
src/main/java/com/gcc/election/repository/UserActivityLogRepository.java

@ -0,0 +1,19 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.UserActivityLog;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface UserActivityLogRepository extends JpaRepository<UserActivityLog, Long> {
List<UserActivityLog> findByUserIdOrderByTimestampDesc(String userId);
}

16
src/main/java/com/gcc/election/repository/UserInfoRepository.java

@ -0,0 +1,16 @@
package com.gcc.election.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface UserInfoRepository {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
}

37
src/main/java/com/gcc/election/service/Base64Util.java

@ -0,0 +1,37 @@
package com.gcc.election.service;
import java.util.Base64;
import org.springframework.stereotype.Service;
@Service
public class Base64Util {
// Encode to Base64
public static String encodeBase64(String value) {
if (value != null && !value.isEmpty()) {
byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes());
// Print the original value and its encoded version
// System.out.println(value + " : " + new String(encodedBytes));
return new String(encodedBytes);
} else {
return "";
}
}
// Decode from Base64
public static String decodeBase64(String encodedValue) {
if (encodedValue != null && !encodedValue.isEmpty()) {
try {
byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
return new String(decodedBytes);
} catch (IllegalArgumentException e) {
// Handle the exception, e.g., log it or return an error message
System.err.println("Error decoding Base64 string: " + e.getMessage());
return "error"; // Or return an error message string
}
} else {
return "";
}
}
}

80
src/main/java/com/gcc/election/service/CustomUserDetails.java

@ -0,0 +1,80 @@
package com.gcc.election.service;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
public class CustomUserDetails implements UserDetails, Serializable{
private static final long serialVersionUID = 1L;
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
private Map<String, Object> additionalAttributes;
public CustomUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities,
boolean accountNonExpired,
boolean accountNonLocked,
boolean credentialsNonExpired,
boolean enabled,
Map<String, Object> additionalAttributes) {
this.username = username;
this.password = password;
this.authorities = authorities;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.enabled = enabled;
this.additionalAttributes = additionalAttributes;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
// Getter for additional attributes
public Map<String, Object> getAdditionalAttributes() {
return additionalAttributes;
}
}

87
src/main/java/com/gcc/election/service/CustomUserDetailsService.java

@ -0,0 +1,87 @@
package com.gcc.election.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.election.repository.AppUserRepository;
@Service
public class CustomUserDetailsService implements UserDetailsService{
private final AppUserRepository appUserRepository;
private final UserActivityService userActivityService;
@Autowired
public CustomUserDetailsService(AppUserRepository appUserRepository,UserActivityService userActivityService ) {
this.appUserRepository = appUserRepository;
this.userActivityService = userActivityService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUserEntity appUserEntity = appUserRepository.findByUsername(username);
userActivityService.logUserActivity("0", "Trying to Login with Username: " + username);
//System.out.println(username);
if (appUserEntity == null) {
//System.out.println("User not found");
userActivityService.logUserActivity("0","User (" + username +") not found");
throw new UsernameNotFoundException("User not found");
}
/*
return org.springframework.security.core.userdetails.User.builder()
.username(appUserEntity.getUsername())
.password(appUserEntity.getPassword())
.roles(appUserEntity.getRoles())
.additionalAttributes(Map.of("userid", appUserEntity.getUserid()))
.build();
*/
String userRole = appUserEntity.getRoles();
// Ensure that the role starts with "ROLE_"
if (!userRole.startsWith("ROLE_")) {
userRole = "ROLE_" + userRole;
//System.out.println("User Role: "+userRole);
}
// Create a SimpleGrantedAuthority for the user role
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole);
// Create a list to hold the authority/role
List<GrantedAuthority> authorityList = new ArrayList<>();
authorityList.add(authority);
// Construct CustomUserDetails instance with custom attributes
CustomUserDetails userDetails = new CustomUserDetails(
appUserEntity.getUsername(),
appUserEntity.getPassword(),
authorityList,
true,
true,
true,
true,
Map.of("userid",appUserEntity.getUserid().getUserid(),
"usergroupid",appUserEntity.getUsergroup_id().getId(),
"userrole",appUserEntity.getRoles().toString()
)
);
userActivityService.logUserActivity(appUserEntity.getUserid().getUserid().toString(), "Login Success: <br>Username: "+appUserEntity.getUsername()
+"<br>Role: "+appUserEntity.getRoles().toString()
+"<br>Access Group: "+appUserEntity.getUsergroup_id().getName()
+"<br>Access Group ID: "+appUserEntity.getUsergroup_id().getId());
return userDetails;
}
}

208
src/main/java/com/gcc/election/service/LoginUserInfo.java

@ -0,0 +1,208 @@
package com.gcc.election.service;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Service
public class LoginUserInfo {
private JdbcTemplate jdbcAppTemplate;
private JdbcTemplate jdbcKuralTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource sosDataSource
) {
this.jdbcAppTemplate = new JdbcTemplate(sosDataSource);
}
public static UserDetails getCurrentUserDetails() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
return (UserDetails) principal;
}
}
return null;
}
public static String getLoginUserId() {
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
if (userDetails instanceof CustomUserDetails) {
//System.out.println("User Details : "+userDetails.toString());
CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes();
if (additionalAttributes != null) {
Object userId = additionalAttributes.get("userid");
Object groupId = additionalAttributes.get("groupid");
if (userId != null) {
return userId.toString();
}
}
/*
for (Map.Entry<String, Object> entry : additionalAttributes.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}*/
}
return null;
}
public static String getUserGroupId() {
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
if (userDetails instanceof CustomUserDetails) {
CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes();
if (additionalAttributes != null) {
Object userGroupId = additionalAttributes.get("usergroupid");
if (userGroupId != null) {
return userGroupId.toString();
}
}
}
return null;
}
public static String getUserRole() {
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
if (userDetails instanceof CustomUserDetails) {
CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes();
if (additionalAttributes != null) {
Object userRole = additionalAttributes.get("userrole");
if (userRole != null) {
return userRole.toString();
}
}
}
return null;
}
public String resetPassword(String userid, String oldPassword, String newPassword, String rawPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// Query to get the stored encoded password for the given user ID
String fetchPasswordQuery = "SELECT `password` FROM `appusers` WHERE `id` = ?";
List<Map<String, Object>> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{userid});
if (result.isEmpty()) {
// If no matching user is found, return an error message
return "User not found.";
}
String storedEncodedPassword = (String) result.get(0).get("password");
// Verify the old password against the stored encoded password
if (!passwordEncoder.matches(oldPassword, storedEncodedPassword)) {
// If the old password doesn't match, return an error message
return "Old password does not match.";
}
// Encode the new password using BCrypt
String encodedNewPassword = passwordEncoder.encode(newPassword);
// Update the password in the database
String updateQuery = "UPDATE `appusers` SET `password` = ?, `pwd_txt` = ? WHERE `id` = ?";
int rowsAffected = jdbcAppTemplate.update(updateQuery, new Object[]{encodedNewPassword, newPassword, userid});
if (rowsAffected > 0) {
// If the update is successful, return a success message
return "success";
} else {
// If the update fails, return an error message
return "Failed to reset the password. Please try again.";
}
}
public List<Map<String, Object>> userCheck(String username, String password) {
Integer statusCode=404;
String statusTxt="error";
String msgTxt="User not found.";
Map<String, Object> response = new HashMap<>();
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// Query to get the stored encoded password for the given user ID
String fetchPasswordQuery = "SELECT `id`, `roles`, `usergroup_id`, `isactive`, `dname`, `password` as saltref FROM `appusers` WHERE `username` = ? AND (`isactive`=1 AND `isdelete`=0)";
List<Map<String, Object>> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{username});
if (result.isEmpty()) {
System.out.println(fetchPasswordQuery);
// If no matching user is found, return an error message
msgTxt = "User not found.";
response.put("Data", Collections.emptyList());
}
else {
String storedEncodedPassword = (String) result.get(0).get("saltref");
// Verify the password against the stored encoded password
if (!passwordEncoder.matches(password, storedEncodedPassword)) {
msgTxt = "User not found.";
response.put("Data", Collections.emptyList());
}
else {
statusCode=200;
statusTxt="success";
msgTxt = "Login Successfully";
if (result.isEmpty()) {
} else {
response.put("Data", result);
}
}
}
response.put("statusCode", statusCode);
response.put("statusText", statusTxt);
response.put("message", msgTxt);
return Collections.singletonList(response);
}
// Dashboard : தினம் ஒரு திருக்குறள் // thirukkural
// public List<Map<String, Object>> getDailyContent() {
// // Query to get all content from the table
// String contentQuery = "SELECT * FROM kural"; // Replace content_table with your actual table name
// List<Map<String, Object>> contentList = jdbcKuralTemplate.queryForList(contentQuery);
//
// // Total number of records
// int totalRecords = contentList.size();
//
// if (totalRecords == 0) {
// // If there are no records, return an empty list
// return Collections.emptyList();
// }
//
// // Calculate the number of days since a specific start date (e.g., October 21, 2024)
// LocalDate startDate = LocalDate.of(2024, 10, 21);
// LocalDate currentDate = LocalDate.now();
// long daysSinceStart = ChronoUnit.DAYS.between(startDate, currentDate);
//
// // Get the content index for today (using modulo to cycle through the records)
// int contentIndex = (int) (daysSinceStart % totalRecords);
//
// // Return the content for today as a list
// return Collections.singletonList(contentList.get(contentIndex));
// }
}

29
src/main/java/com/gcc/election/service/UserActivityService.java

@ -0,0 +1,29 @@
package com.gcc.election.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.election.repository.UserActivityLogRepository;
import java.time.LocalDateTime;
@Service
public class UserActivityService {
private final UserActivityLogRepository userActivityLogRepository;
@Autowired
public UserActivityService(UserActivityLogRepository userActivityLogRepository) {
this.userActivityLogRepository = userActivityLogRepository;
}
public void logUserActivity(String userId, String activityType) {
UserActivityLog userActivityLog = new UserActivityLog();
userActivityLog.setUserId(userId);
userActivityLog.setActivityType(activityType);
userActivityLog.setTimestamp(LocalDateTime.now());
userActivityLogRepository.save(userActivityLog);
}
}

23
src/main/java/com/gcc/election/service/UserActivityTimelineService.java

@ -0,0 +1,23 @@
package com.gcc.election.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.election.repository.UserActivityLogRepository;
import java.util.List;
@Service
public class UserActivityTimelineService {
private final UserActivityLogRepository userActivityLogRepository;
@Autowired
public UserActivityTimelineService(UserActivityLogRepository userActivityLogRepository) {
this.userActivityLogRepository = userActivityLogRepository;
}
public List<UserActivityLog> getUserActivityTimeline(String userId) {
return userActivityLogRepository.findByUserIdOrderByTimestampDesc(userId);
}
}

5
src/main/resources/application-dev.properties

@ -0,0 +1,5 @@
assets.base-url=/assets/
fileBaseUrl=http://localhost:8080
#fileBaseUrl = D:/Projects/Election_Project/election_v1/gcc_election_uploads

3
src/main/resources/application-prod.properties

@ -0,0 +1,3 @@
assets.base-url=/election/assets/
fileBaseUrl=https://gccservices.in/files

59
src/main/resources/application.properties

@ -0,0 +1,59 @@
spring.profiles.active=dev
#spring.profiles.active=prod
# Spring properties
spring.application.name=election
spring.datasource.hikari.connection-timeout=30000
spring.jackson.time-zone=Asia/Kolkata
# Maximum file size
spring.servlet.multipart.max-file-size=20MB
# Maximum request size (including all files)
spring.servlet.multipart.max-request-size=20MB
# HTTP Server
server.port = 8080
#server.servlet.context-path=/gccoffice
server.error.include-stacktrace= on_param
# Hibernate logging
#logging.level.org.hibernate.SQL=DEBUG
#logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
# Enable CORS globally for all endpoints
spring.webmvc.cors.enabled=true
# Comma-separated list of allowed HTTP methods
spring.webmvc.cors.allowed-methods=GET,POST,PUT,DELETE
# Whether to include credentials such as cookies in CORS requests
spring.webmvc.cors.allow-credentials=true
# Maximum age (in seconds) of the CORS response cache
spring.webmvc.cors.max-age=3600
server.servlet.session.tracking-modes=COOKIE
#logging.level.root=DEBUG
file.upload.directory=${user.dir}/gccoffice_uploads/
file.upload.directory.mobile=${user.dir}/gcc_mobile_service_uploads/
#file.upload.directory.mobile=${user.dir}/election_mobile_service_uploads/
server.address=0.0.0.0
server.servlet.session.timeout=-1
server.servlet.session.cookie.name= ELECTIONONEPORTALSESSION
server.servlet.session.cookie.max-age=-1
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
#////////// For Election Polling Personnel Profile Images ////////////
election_profile_foldername=election_profile_files

BIN
src/main/resources/favicon.ico

BIN
src/main/resources/favicon.png

After

Width: 32  |  Height: 32  |  Size: 3.5 KiB

BIN
src/main/resources/static/Chennai_Corporation_Emblem.png

After

Width: 328  |  Height: 438  |  Size: 188 KiB

BIN
src/main/resources/static/assets/.DS_Store

584
src/main/resources/static/assets/css/loginpage.css

@ -0,0 +1,584 @@
html, body {
height: 100%;
margin: 0;
padding: 0;
}
body {
background-size: cover;
min-height: 100vh;
font-family: Inter, system-ui, Arial, sans-serif;
color: #fff;
}
body::before {
content: "";
position: fixed;
inset: 0;
background: rgba(0,0,0,0.50);
backdrop-filter: blur(2px);
z-index: -1;
}
@media (max-width: 768px) {
body::before {
background: rgba(0,0,0,0.45);
backdrop-filter: blur(6px); /* stronger blur */
-webkit-backdrop-filter: blur(6px);
}
}
/* FIXED VECTOR IMAGE TOP-RIGHT */
.vector-overlay {
position: absolute;
top: 0px;
right: 0px;
width: 700px;
z-index: 1;
opacity: 5.5;
pointer-events: none;
}
/* Page layout */
.page-wrap{
min-height:100vh;
display:flex;
flex-direction:column;
flex: 1}
.hero{
flex:1;
display:flex;
/* align-items:stretch */
margin-bottom: 15%;
}
/* Left column (login) */
.left-col{
flex:0 0 42%;
padding:48px;
position:relative;
}
.left-overlay{
position:absolute;
inset:0;
/* background:linear-gradient(180deg,rgba(1,1,1,0.45),rgba(1,1,1,0.6)); */
border-right:6px solid rgba(255,255,255,0.02)}
.login-card{
position:relative;
z-index:2;
max-width:420px;
/* margin:40px auto; */
/* background:rgba(255,255,255,0.04); */
/* background: rgba(255, 255, 255, 0.08); */ /* light transparent */
/* backdrop-filter: blur(8px); */ /* GLASS EFFECT */
/* -webkit-backdrop-filter: blur(8px); */
padding:40px;
/* border-radius:28px;
border: 1px solid rgba(255, 255, 255, 0.15); */
/* box-shadow:0 8px 30px rgba(0,0,0,0.5) */}
.role-toggle{
display:inline-flex;
gap:12px}
.role-toggle .btn{
border-radius:40px;
padding:8px 26px;
font-weight:700}
.login-card .form-control{background:transparent;
border:0;
border-bottom:1px solid white;
color:#fff;
border-radius:0;
margin-bottom: 20px;}
.login-card .form-control::placeholder{color:white;}
.input-eye{position:relative}
.input-eye .eye{position:absolute;
right:10px;
top:8px;
font-size:medium;
cursor:pointer;
color:white;}
.btn-login {
background: #ffffff;
color: black;
border-radius: 30px;
padding: 12px 36px;
font-weight: bold;
width: 100%;
height:20%;
border: none;
font-size: 20px;
transition: all 0.25s ease-in-out;
box-shadow: 0 4px 12px rgba(0,0,0,0.25);
margin-top: 6%;
}
.btn-login:hover {
/* background: rgba(0,0,0,0.5);
box-shadow: 0 6px 18px rgba(0,0,0,0.35);
transform: translateY(-1px); */
background: #07283d;
color:white;
}
.btn-login:active {
transform: scale(0.98);
box-shadow: 0 3px 10px rgba(0,0,0,0.3);
}
/* Right column (info/news) */
.right-col{
flex:1;
/* padding:28px 38px; */
padding-left:130px;
position:relative;
overflow:hidden;
z-index: 1}
.right-inner{
max-width:500px;
max-height:100vh;
/* margin-left:80px; */
color:rgba(255,255,255,0.95)
}
.info-box{
/* padding:16px;
border-radius:12px; */
margin-left:68px;
max-height:220px}
.news{
margin-left:68px;
margin-top:28px;
}
.news-list{
max-height:160px;
overflow:auto;
overflow-x: hidden;
padding-right:12px
}
.news-item {
position: relative;
padding-left: 40px; /* space for bullet */
}
/* Bullet point */
.news-item::before {
content: "";
position: absolute;
left: 0;
top: 18px;
width: 8px;
height: 8px;
background: #ffffff;
border-radius: 50%; /* round bullet */
opacity: 0.85;
}
/* Outer capsule background */
/* Outer capsule wrapper (transparent background) */
.election-header {
width: 100%;
padding: 20px 0;
display: flex;
justify-content: center;
background: transparent !important; /* <-- remove dark color */
}
.header-inner {
background: #0b4e8a;
border: 2px solid rgba(255, 255, 255, 0.4);
border-radius: 50px;
padding: 18px 40px;
width: 90%;
max-width: 1300px;
display: flex;
justify-content: space-between;
align-items: center;
color: #fff;
position: relative;
/* background-size: contain; // optional alternative */
z-index: 1;
}
/* LEFT */
.header-left {
display: flex;
align-items: center;
gap: 12px;
}
.gcc-logo {
height: 60px;
}
.gcc-text {
font-size: 14px;
font-weight: 700;
line-height: 1.2;
}
/* CENTER TITLE */
.header-center {
font-size: 24px;
font-weight: 700;
text-align: center;
}
/* RIGHT */
.header-right {
display: flex;
justify-content: flex-end;
}
.election-logo {
height: 60px;
object-fit: contain;
}
/* RESPONSIVE */
@media (max-width: 992px) {
.election-header {
padding: 10px 0 !important;
}
.header-inner {
width: 95%;
padding: 12px 16px;
display: grid !important;
grid-template-columns: auto 1fr auto;
align-items: center;
justify-content: center;
border-radius: 25px;
gap: 10px;
text-align: center;
}
/* GCC Logo */
.gcc-logo {
height: 40px !important;
}
.gcc-text {
font-size: 11px !important;
line-height: 1.1;
font-weight: 600;
text-align: left;
}
/* Middle title */
.header-center {
font-size: 16px !important;
font-weight: 700;
text-align: center;
white-space: nowrap;
}
/* Election logo */
.election-logo {
height: 38px !important;
}
/* Align left container horizontally */
.header-left {
display: flex;
align-items: center;
gap: 6px;
}
/* Hide unnecessary gaps from desktop mode */
.header-right {
display: flex;
align-items: center;
justify-content: flex-end;
}
}
/* FOOTER STYLING */
.site-footer {
background: #07283d;
padding: 32px 16px;
text-align: center;
color: rgba(255, 255, 255, 0.9);
border-top: 0px solid rgba(255,255,255,0.08);
position:inherit;
z-index: 5;
font-size: 15px;
line-height: 1.6;
display: flex;
flex-direction: column;
gap: 10px;
}
/* Visitor Box */
.site-footer .visitor {
display: inline-block;
padding: 12px 24px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
font-size: 16px;
font-weight: 600;
backdrop-filter: blur(4px);
box-shadow: 0 0 12px rgba(0,0,0,0.25);
}
/* Visitor number highlight */
.site-footer .visitor strong {
color: #ffffff;
font-weight: 700;
}
/* RESPONSIVE FOOTER */
@media (max-width: 576px) {
.site-footer {
padding: 26px 12px;
font-size: 14px;
}
.site-footer .visitor {
padding: 10px 18px;
font-size: 14px;
}
}
/* Simple scrollbar style */
.news-list::-webkit-scrollbar {
width: 8px;
background: white;
border-radius: 10px;
}
.news-list::-webkit-scrollbar-thumb {
border-radius: 10px;
background: #28548b;
}
@media (max-width: 768px) {
.news-list::-webkit-scrollbar-thumb {
background: #28548b;
border-radius: 10px;
}
.news-list::-webkit-scrollbar-track {
background: white;
border-radius: 10px;
}
}
/* ---------------------------------------------------
MOBILE VIEW – PORTRAIT (≤ 768px)
--------------------------------------------------- */
@media (max-width: 768px) {
/* --- Main Layout --- */
.hero {
flex-direction: column;
}
.left-col {
flex-basis: auto;
padding: 24px 20px 32px;
}
.login-card {
margin: 20px auto;
padding: 22px;
max-width: 92%;
}
.right-col {
padding: 20px 16px !important;
overflow: visible; /* required for news scroll */
}
.right-inner {
max-width: 100%;
margin: 10px auto;
min-height: 560px;
background: #063679;
border-radius: 10px;
}
.info-box {
max-height: none;
padding: 14px;
margin-left: 2%;
}
.news{
margin-left: 2%;
padding-left: 2%;
padding-right: 2%;
}
.news-list {
max-height: 300px;
}
/* ---------------------------------------------------
MOBILE HEADER
--------------------------------------------------- */
.election-header {
padding: 8px 0 !important;
width: 100%;
display: flex;
justify-content: center;
}
.header-inner {
width: 95%;
padding: 12px 18px;
/* 3-column grid layout */
display: grid !important;
grid-template-columns: auto 1fr auto;
align-items: center;
background: #0b4e8a;
border-radius: 30px;
border: 2px solid rgba(255,255,255,0.35);
gap: 10px;
text-align: center;
}
/* GCC Logo */
.gcc-logo {
height: 38px !important;
}
/* GCC Text */
.gcc-text {
font-size: 11px !important;
line-height: 1.1;
font-weight: 600;
text-align: left;
}
/* Combined left section */
.header-left {
display: flex;
align-items: center;
gap: 6px;
}
/* Center Title */
.header-center {
font-size: 16px !important;
font-weight: 700;
text-align: center;
white-space: nowrap;
}
/* Election Logo Right */
.election-logo {
height: 38px !important;
object-fit: contain;
}
.header-right {
display: flex;
justify-content: flex-end;
align-items: center;
}
}
@media (max-width: 992px) {
.vector-overlay {
position: absolute;
top: 0px;
right: 0px;
width: 600px;
z-index: 1;
opacity: 5.5;
pointer-events: none;
}
.right-col{
flex:1;
/* padding:28px 38px; */
padding-left:70px;
position:relative;
overflow:hidden;
z-index: 1
}
}
@media (max-width: 830px) {
.vector-overlay {
position: absolute;
top: 0px;
right: 0px;
width: 550px;
z-index: 1;
opacity: 5.5;
pointer-events: none;
}
.right-col{
flex:1;
/* padding:28px 38px; */
padding-left:20px;
position:relative;
overflow:hidden;
z-index: 1
}
}
@media (max-width: 768px) {
.vector-overlay {
display: none;
}
}

4
src/main/resources/static/assets/css/style.css

@ -0,0 +1,4 @@
#headings_center{
font-size: medium;
font-weight: bold;
}

BIN
src/main/resources/static/assets/dist/.DS_Store

5989
src/main/resources/static/assets/dist/css/theme.css
File diff suppressed because it is too large
View File

7
src/main/resources/static/assets/dist/css/theme.css.map
File diff suppressed because it is too large
View File

5
src/main/resources/static/assets/dist/css/theme.min.css
File diff suppressed because it is too large
View File

7
src/main/resources/static/assets/dist/css/theme.min.css.map
File diff suppressed because it is too large
View File

0
src/main/resources/static/assets/dist/img/.gitignore

13
src/main/resources/static/assets/dist/img/brand-white.svg

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 54.3 54" style="enable-background:new 0 0 54.3 54;" xml:space="preserve">
<style type="text/css">
.st0{fill:#FFFFFF;}
.st1{fill:#EF4153;}
</style>
<path class="st0" d="M20.1,13.8v5H13v20.9H7.7V18.8H0.6v-5H20.1z"/>
<path class="st0" d="M46.2,39.7h-6.6l-7.4-11.1l-3.9,4.3v6.8H23V13.8h5.3v12.3l10.5-12.3h6.9l-9.8,10.7L46.2,39.7z"/>
<path class="st1" d="M52.8,39c-0.7,0.6-1.5,1-2.5,1c-1,0-1.9-0.3-2.5-1c-0.7-0.6-1-1.5-1-2.5c0-1,0.3-1.8,1-2.5c0.7-0.7,1.5-1,2.5-1
c1,0,1.8,0.3,2.5,1c0.7,0.7,1,1.5,1,2.5C53.7,37.5,53.4,38.3,52.8,39z"/>
</svg>

14
src/main/resources/static/assets/dist/img/brand.svg

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 54.3 54" style="enable-background:new 0 0 54.3 54;" xml:space="preserve">
<style type="text/css">
.st0{fill:#EF4153;}
</style>
<g>
<path d="M20.1,13.8v5H13v20.9H7.7V18.8H0.6v-5H20.1z"/>
<path d="M46.2,39.7h-6.6l-7.4-11.1l-3.9,4.3v6.8H23V13.8h5.3v12.3l10.5-12.3h6.9l-9.8,10.7L46.2,39.7z"/>
<path class="st0" d="M52.8,39c-0.7,0.6-1.5,1-2.5,1c-1,0-1.9-0.3-2.5-1c-0.7-0.6-1-1.5-1-2.5c0-1,0.3-1.8,1-2.5
c0.7-0.7,1.5-1,2.5-1c1,0,1.8,0.3,2.5,1c0.7,0.7,1,1.5,1,2.5C53.7,37.5,53.4,38.3,52.8,39z"/>
</g>
</svg>

6
src/main/resources/static/assets/dist/img/down-arrow.svg

@ -0,0 +1,6 @@
<?xml version='1.0' encoding='utf-8'?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 129 129" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 129 129">
<g>
<path d="m121.3,34.6c-1.6-1.6-4.2-1.6-5.8,0l-51,51.1-51.1-51.1c-1.6-1.6-4.2-1.6-5.8,0-1.6,1.6-1.6,4.2 0,5.8l53.9,53.9c0.8,0.8 1.8,1.2 2.9,1.2 1,0 2.1-0.4 2.9-1.2l53.9-53.9c1.7-1.6 1.7-4.2 0.1-5.8z"/>
</g>
</svg>

204
src/main/resources/static/assets/dist/js/theme.js

@ -0,0 +1,204 @@
! function(e, s, i) {
"use strict";
i(s).ready(function() {
function a(e, s) {
e.children(".submenu-content").show().slideUp(200, function() {
i(this).css("display", ""), i(this).find(".menu-item").removeClass("is-shown"), e.removeClass("open"), s && s()
})
}
var n = i(".app-sidebar"),
t = i(".sidebar-content"),
l = i(".wrapper"),
o = s.querySelector(".sidebar-content");
new PerfectScrollbar(o, {
wheelSpeed: 10,
wheelPropagation: !0,
minScrollbarLength: 5
});
t.on("click", ".navigation-main .nav-item a", function() {
var e = i(this).parent(".nav-item");
if (e.hasClass("has-sub") && e.hasClass("open")) a(e);
else {
if (e.hasClass("has-sub") && function(e, s) {
var a = e.children(".submenu-content"),
n = a.children(".menu-item").addClass("is-hidden");
e.addClass("open"), a.hide().slideDown(200, function() {
i(this).css("display", ""), s && s()
}), setTimeout(function() {
n.addClass("is-shown"), n.removeClass("is-hidden")
}, 0)
}(e), t.data("collapsible")) return !1;
a(e.siblings(".open")), e.siblings(".open").find(".nav-item.open").removeClass("open")
}
}), i(".nav-toggle").on("click", function() {
var e = i(this).find(".toggle-icon");
"expanded" === e.attr("data-toggle") ? (l.addClass("nav-collapsed"), i(".nav-toggle").find(".toggle-icon").removeClass("ik-toggle-right").addClass("ik-toggle-left"), e.attr("data-toggle", "collapsed")) : (l.removeClass("nav-collapsed menu-collapsed"), i(".nav-toggle").find(".toggle-icon").removeClass("ik-toggle-left").addClass("ik-toggle-right"), e.attr("data-toggle", "expanded"))
}), n.on("mouseenter", function() {
if (l.hasClass("nav-collapsed")) {
l.removeClass("menu-collapsed");
var e = i(".navigation-main .nav-item.nav-collapsed-open");
e.children(".submenu-content").hide().slideDown(300, function() {
i(this).css("display", "")
}), t.find(".nav-item.active").parents(".nav-item").addClass("open"), e.addClass("open").removeClass("nav-collapsed-open")
}
}).on("mouseleave", function(e) {
if (l.hasClass("nav-collapsed")) {
l.addClass("menu-collapsed");
var s = i(".navigation-main .nav-item.open"),
a = s.children(".submenu-content");
s.addClass("nav-collapsed-open"), a.show().slideUp(300, function() {
i(this).css("display", "")
}), s.removeClass("open")
}
}), i(e).width() < 992 && (n.addClass("hide-sidebar"), l.removeClass("nav-collapsed menu-collapsed")), i(e).resize(function() {
i(e).width() < 992 && (n.addClass("hide-sidebar"), l.removeClass("nav-collapsed menu-collapsed")), i(e).width() > 992 && (n.removeClass("hide-sidebar"), "collapsed" === i(".toggle-icon").attr("data-toggle") && l.not(".nav-collapsed menu-collapsed") && l.addClass("nav-collapsed menu-collapsed"))
}), i(s).on("click", ".navigation li:not(.has-sub)", function() {
i(e).width() < 992 && n.addClass("hide-sidebar")
}), i(s).on("click", ".logo-text", function() {
i(e).width() < 992 && n.addClass("hide-sidebar")
}), i(".mobile-nav-toggle").on("click", function(e) {
e.stopPropagation(), n.toggleClass("hide-sidebar")
}), i("html").on("click", function(s) {
i(e).width() < 992 && (n.hasClass("hide-sidebar") || 0 !== n.has(s.target).length || n.addClass("hide-sidebar"))
}), i("#sidebarClose").on("click", function() {
n.addClass("hide-sidebar")
}), i('[data-toggle="tooltip"]').tooltip(), i("#checkbox_select_all").on("click", function() {
for (var e = s.getElementsByName("item_checkbox"), a = 0; a < e.length; a++) "checkbox" == e[a].type && (e[a].checked = !0), i(e).parent().parent().addClass("selected")
}), i("#checkbox_deselect_all").on("click", function() {
for (var e = s.getElementsByName("item_checkbox"), a = 0; a < e.length; a++) "checkbox" == e[a].type && (e[a].checked = !1), i(e).parent().parent().removeClass("selected")
}), i("#quick-search").keyup(function() {
var e = i(this).val().trim().toLowerCase();
i(".app-item").hide().filter(function() {
return -1 != i(this).html().trim().toLowerCase().indexOf(e)
}).show()
}), i(".list-item input:checkbox").change(function() {
i(this).is(":checked") ? i(this).parent().parent().addClass("selected") : i(this).parent().parent().removeClass("selected")
}), i("#navbar-fullscreen").on("click", function(e) {
"undefined" != typeof screenfull && screenfull.enabled && screenfull.toggle()
}), i("#selectall").click(function() {
i(this).is(":checked") ? i(".select_all_child:checkbox").attr("checked", !0) : i(".select_all_child:checkbox").attr("checked", !1)
}), i(".list-item-wrap .list-item .list-title a").on("click", function(e) {
i(".list-item.quick-view-opened").not(this).removeClass("quick-view-opened"), i(this).parents().parent(".list-item").toggleClass("quick-view-opened")
}), i(s).on("click", function(e) {
i(e.target).closest(".list-item").length || i(".list-item").removeClass("quick-view-opened")
}), "undefined" != typeof screenfull && screenfull.enabled && i(s).on(screenfull.raw.fullscreenchange, function() {
screenfull.isFullscreen ? i("#navbar-fullscreen").find("i").toggleClass("ik-minimize ik-maximize") : i("#navbar-fullscreen").find("i").toggleClass("ik-maximize ik-minimize")
}), i(".minimize-widget").on("click", function() {
var e = i(this),
s = i(e.parents(".widget"));
i(s).children(".widget-body").slideToggle();
i(this).toggleClass("ik-minus").fadeIn("slow"), i(this).toggleClass("ik-plus").fadeIn("slow")
}), i(".remove-widget").on("click", function() {
var e = i(this);
e.parents(".widget").animate({
opacity: "0",
"-webkit-transform": "scale3d(.3, .3, .3)",
transform: "scale3d(.3, .3, .3)"
}), setTimeout(function() {
e.parents(".widget").remove()
}, 800)
}), i(".card-header-right .card-option .action-toggle").on("click", function() {
var e = i(this);
e.hasClass("ik-chevron-right") ? e.parents(".card-option").animate({
width: "28px"
}) : e.parents(".card-option").animate({
width: "90px"
}), i(this).toggleClass("ik-chevron-right").fadeIn("slow")
}), i(".card-header-right .close-card").on("click", function() {
var e = i(this);
e.parents(".card").animate({
opacity: "0",
"-webkit-transform": "scale3d(.3, .3, .3)",
transform: "scale3d(.3, .3, .3)"
}), setTimeout(function() {
e.parents(".card").remove()
}, 800)
}), i(".card-header-right .minimize-card").on("click", function() {
var e = i(this),
s = i(e.parents(".card"));
i(s).children(".card-body").slideToggle();
i(this).toggleClass("ik-minus").fadeIn("slow"), i(this).toggleClass("ik-plus").fadeIn("slow")
}), i(".task-list").on("click", "li.list", function() {
i(this).toggleClass("completed")
}), i(".search-btn").on('click', function() {
i(".header-search").addClass('open');
i('.header-search .form-control').animate({
'width': '200px',
});
}), i(".search-close").on('click', function() {
i('.header-search .form-control').animate({
'width': '0',
});
setTimeout(function() {
i(".header-search").removeClass('open');
}, 300);
});
/*
var ps = new PerfectScrollbar(".right-sidebar", {
wheelSpeed: 10,
wheelPropagation: true,
minScrollbarLength: 5
});
var ps = new PerfectScrollbar(".messages", {
wheelSpeed: 10,
wheelPropagation: true,
minScrollbarLength: 5
});
$(".right-sidebar-toggle").on("click",function(e) {
this.classList.toggle('active');
$('.wrapper').toggleClass('right-sidebar-expand');
return false;
});
document.addEventListener('click', function(event) {
var $rightSidebar = document.getElementsByClassName('right-sidebar')[0],
$chatPanel = document.getElementsByClassName('chat-panel')[0];
var isInsideContainer = $rightSidebar.contains( event.target ) || $chatPanel.contains(event.target);
if( !isInsideContainer ) {
document.body.classList.remove('right-sidebar-expand');
var toggle = document.getElementsByClassName('right-sidebar-toggle');
for( var i = 0; i < toggle.length; i++ ) {
toggle[i].classList.remove('active');
}
$chatPanel.hidden = 'hidden';
}
});
var el = $('[data-plugin="chat-sidebar"]');
if( !el.length ) return;
var chatList = el.find('.chat-list');
chatList.each(function(index) {
var $this = $(this);
$(this).find('.list-group a').on('click', function() {
$this.find('.list-group a.active').removeClass('active');
$(this).addClass('active');
var el = $('.chat-panel');
if(!el.length) return;
el.removeAttr('hidden');
var messages = el.find('.messages');
messages[0].scrollTop = messages[0].scrollHeight;
if( messages[0].classList.contains('scrollbar-enabled') ) {
messages.perfectScrollbar('update');
}
el.find('.user-name').html( $(this).data('chat-user'));
});
});
var el = $('.chat-panel');
if(!el.length) return;
el.find('.close').on('click', function(){
el.attr('hidden', true);
el.find('.panel-body').removeClass('hide');
});
el.find('.minimize').on('click', function(){
el.find('.card-block').attr('hidden', !el.find('.card-block').attr('hidden') );
if( el.find('.card-block').attr('hidden') === 'hidden' )
$(this).find('.material-icons').html('expand_less');
else
$(this).find('.material-icons').html('expand_more');
});
*/
})
}(window, document, jQuery);

1
src/main/resources/static/assets/dist/js/theme.min.js
File diff suppressed because it is too large
View File

BIN
src/main/resources/static/assets/fonts/.DS_Store

3422
src/main/resources/static/assets/fonts/iconsmind/iconsmind.css
File diff suppressed because it is too large
View File

BIN
src/main/resources/static/assets/fonts/iconsmind/iconsmind.eot

1141
src/main/resources/static/assets/fonts/iconsmind/iconsmind.svg
File diff suppressed because it is too large
View File

BIN
src/main/resources/static/assets/fonts/iconsmind/iconsmind.ttf

BIN
src/main/resources/static/assets/fonts/iconsmind/iconsmind.woff

BIN
src/main/resources/static/assets/fonts/nunito/.DS_Store

BIN
src/main/resources/static/assets/fonts/nunito/v25/.DS_Store

BIN
src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t1R-tQKr51.woff2

BIN
src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t4R-tQKr51pE8.woff2

BIN
src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t6R-tQKr51pE8.woff2

BIN
src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7t7R-tQKr51pE8.woff2

BIN
src/main/resources/static/assets/fonts/nunito/v25/pe0TMImSLYBIv1o4X1M8ce2xCx3yop4tQpF_MeTm0lfGWVpNn64CL7U8upHZIbMV51Q42ptCp7txR-tQKr51pE8.woff2

BIN
src/main/resources/static/assets/images/.DS_Store

BIN
src/main/resources/static/assets/images/403.png

After

Width: 1000  |  Height: 1080  |  Size: 106 KiB

BIN
src/main/resources/static/assets/images/dog.png

After

Width: 512  |  Height: 512  |  Size: 30 KiB

BIN
src/main/resources/static/assets/images/donut-chart.png

After

Width: 512  |  Height: 512  |  Size: 19 KiB

BIN
src/main/resources/static/assets/images/error-bg-404.png

After

Width: 1024  |  Height: 587  |  Size: 64 KiB

BIN
src/main/resources/static/assets/images/error-bg.png

After

Width: 920  |  Height: 922  |  Size: 101 KiB

BIN
src/main/resources/static/assets/images/hi_robo.gif

After

Width: 600  |  Height: 600  |  Size: 2.9 MiB

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

Loading…
Cancel
Save