первая

This commit is contained in:
2024-12-09 20:59:06 +06:00
parent 8ea4993263
commit 63e7081516
50 changed files with 18739 additions and 0 deletions

40
.gitignore vendored Normal file
View File

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

60
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,60 @@
pipeline {
agent any
environment {
GIT_URL = 'https://git.dirt.kz/igor/CCALM_main.git'
GIT_BRANCH = 'master'
MAVEN_OPTS = '-Dmaven.test.failure.ignore=true'
}
stages {
stage('Checkout') {
steps {
git branch: "${GIT_BRANCH}", url: "${GIT_URL}"
}
}
stage('Print Workspace') {
steps {
echo "Workspace directory is: ${env.WORKSPACE}"
// Если хотите использовать команду оболочки для вывода
bat 'echo Current workspace is %CD%'
}
}
stage('Build') {
steps {
script {
if (fileExists('pom.xml')) {
bat 'mvn clean package'
} else {
error 'No Maven project found!'
}
}
}
}
stage('Test') {
steps {
bat 'mvn test'
}
}
stage('Deploy') {
steps {
// Например, копирование артефакта на сервер
// bat 'copy target\\your-app.jar \\\\server\\path\\to\\deploy\\'
echo 'Deploy stage - no steps defined'
}
}
}
post {
success {
echo 'Build and tests succeeded!'
}
failure {
echo 'Build or tests failed.'
}
}
}

308
mvnw vendored Normal file
View File

@ -0,0 +1,308 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
done
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
exit 1
fi
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
exit 1
fi
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

205
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,205 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%

35
org_ccalm_main.properties Normal file
View File

@ -0,0 +1,35 @@
spring.application.name=org.ccalm.main
server.port=8081
logging.level.com.zaxxer.hikari=DEBUG
spring.datasource.url=jdbc:postgresql://91.201.214.156:5432/CCALM
spring.datasource.username=postgres
spring.datasource.password=PasSecrKey1
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.max-lifetime=1700000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT now()
spring.datasource.hikari.validation-timeout=60000
public.key=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzYLWgn7uUJYVn1PGyQKKC6F/m6PwEbL6FlCX+TaHZBjor83uS6rbuXquqbU/oFSiviBLI6Zg7BTzAhNglu8S2X4G7a1pkz3fn4kW9mf3zLnXnaNeuh+VhIEt/kw1ire1pCwP95KryKnQaLbi+ARDcGY+giIxjXRtNUTbAmgwP78U5M8fZ48+pH4AHWv/sG3TiTcIzUYCG/QMnnUE+Tir6kV3qrs66zig/cK5tTuJ7/JQOlhYOWBDElu0+lkSHgK2bEK9Wh7+qpIruO2K3gKX3RSFh8XfUIpwPVqyz2HVlzja+/scr6kuDB0iYfWZgrzLHPx3Bd0RyYBMIIgvBOoYmQIDAQAB
access.time=600
refresh.time=43200
captcha.key=PPExpv36jk4Vzda3NpYnXLfuHCLYXqaNrxlOH/Jr/1M=
captcha.time=600
mail.host=smtp.yandex.ru
mail.port=465
mail.login=info@ccalm.org
mail.password=fu2lpsoGPGiq1xlRm8ag
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=9F3/NKWeOjd815vkadT2DcgVHf6fEpVQXw==
data.dir=logs/

155
pom.xml Normal file
View File

@ -0,0 +1,155 @@
<?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>3.2.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.ccalm</groupId>
<artifactId>main</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>main</name>
<description>main</description>
<properties>
<java.version>21</java.version>
</properties>
<repositories>
<repository>
<id>unidata</id>
<name>Unidata UCAR Repository</name>
<url>https://artifacts.unidata.ucar.edu/content/repositories/unidata-releases/</url>
</repository>
<!--repository>
<id>boundless</id>
<name>Boundless Repository</name>
<url>https://repo.boundlessgeo.com/main/</url>
</repository-->
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>6.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/edu.ucar/netcdfAll -->
<dependency>
<groupId>edu.ucar</groupId>
<artifactId>netcdfAll</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.gdal</groupId>
<artifactId>gdal</artifactId>
<version>2.4.0</version>
</dependency>
<!-- Для загрузки новой версии плагина -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.1.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>org.ccalm.main.MainApplication</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemPropertyVariables>
<spring.config.location>file:application.properties</spring.config.location>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>

31
qodana.yaml Normal file
View File

@ -0,0 +1,31 @@
#-------------------------------------------------------------------------------#
# Qodana analysis is configured by qodana.yaml file #
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
#-------------------------------------------------------------------------------#
version: "1.0"
#Specify inspection profile for code analysis
profile:
name: qodana.starter
#Enable inspections
#include:
# - name: <SomeEnabledInspectionId>
#Disable inspections
#exclude:
# - name: <SomeDisabledInspectionId>
# paths:
# - <path/where/not/run/inspection>
projectJDK: "21" #(Applied in CI/CD pipeline)
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
#bootstrap: sh ./prepare-qodana.sh
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
#plugins:
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
linter: jetbrains/qodana-jvm:2024.3

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,402 @@
package org.ccalm.main;
import java.io.*;
//import java.io.FileInputStream;
//import java.io.OutputStream;
//import java.io.UnsupportedEncodingException;
//import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//import java.util.zip.CRC32;
//import java.util.zip.Checksum;
//import javax.servlet.ServletContext;
//import javax.servlet.http.Part;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
//import org.apache.commons.io.FileUtils;
//import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
//import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import tools.User;
@Controller
public class AcceptEXCEL implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(AcceptEXCEL.class);
private ServletContext context;
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
@RequestMapping(value = "/AcceptCSV", method = { RequestMethod.GET, RequestMethod.POST })
public String acceptCSV(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) {
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
} catch (Exception ex) {
}
String sqlData="";
String json="{\"type\": \"FeatureCollection\",\"features\":[";
String table="<table border=\"1\">";
table+="<tr style=\"background-color: #e0e0e0;\"><th>№</th><th>Latitude (Широта)</th><th>Longitude (Долгота)</th><th>Oblast (область)</th><th>District (Район)</th><th>Сельский округ</th><th>Хозяйство или местность</th><th>Вид саранчи</th><th>Фаза</th><th>ЭПВ</th><th>Заселено Га</th><th>Дата</th></tr>";
//row+="<td>"+i+"</td><td>"+locust.lat+"</td><td>"+locust.lon+"</td><td>"+locust.region+" = "+locust.region_id+"</td><td>"+locust.district+" = "+locust.district_id+"</td><td>"+locust.terrain+"</td><td>"+locust.village+"<td>";
if (file!=null && !file.isEmpty()) {
BufferedReader reader;
try {
int i=1; //for testing
reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
//reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
if(skip) line = reader.readLine();
while (line != null) {
StringBuffer data=new StringBuffer(line);
Boolean error=false;
Locust locust = new Locust();
try {
String lat=CutBeforeFirst(data,";");
if(lat.equals("46.3104.6")) lat="46.31046";
if(lat.equals("43.21303.")) lat="43.21303";
if(lat.equals("43.26067.")) lat="43.26067";
if(lat.equals("43.20181.")) lat="43.20181";
if(lat.equals("43.20181.")) lat="43.20181";
if(lat.equals("43.74691.")) lat="43.74691";
if(lat.equals("43.41954.")) lat="43.41954";
if(lat.equals("43.78288.")) lat="43.78288";
if(lat.equals("43.26260.")) lat="43.26260";
if(lat.equals("43.79702.")) lat="43.79702";
if(lat.equals("43.64891.")) lat="43.64891";
if(lat.equals("43.64891.")) lat="43.64891";
if(lat.equals("43.42271.")) lat="43.42271";
if(lat.equals("43.64891.")) lat="43.64891";
if(lat.equals("43.89990.")) lat="43.89990";
if(lat.equals("43.96273.")) lat="43.96273";
if(lat.equals("43.26907.")) lat="43.26907";
if(lat.equals("43.26630.")) lat="43.26630";
if(lat.equals("43.50605.")) lat="43.50605";
if(lat.equals("43.74965.")) lat="43.74965";
if(lat.equals("43.20813.")) lat="43.20813";
if(lat.equals("43.23298.")) lat="43.23298";
if(lat.equals("43.74774.")) lat="43.74774";
if(lat.equals("43.77144.")) lat="43.77144";
if(lat.equals("43.58847.")) lat="43.58847";
if(lat.equals("43.58944.")) lat="43.58944";
if(lat.equals("4342755.")) lat="43.42755";
if(lat.equals("43.80416.")) lat="43.80416";
if(lat.equals("43.79536.")) lat="43.79536";
if(lat.equals("50.75 767")) lat="50.75767";
if(lat.equals("50.77 542")) lat="50.77542";
if(lat.equals("50.85 140")) lat="50.85140";
if(lat.equals("50.79 773")) lat="50.79773";
if(lat.equals("50.63 469")) lat="50.63469";
if(lat.equals("51.23 130")) lat="51.23130";
if(lat.equals("51.03 220")) lat="51.03220";
if(lat.equals("51.38 922")) lat="51.38922";
if(lat.equals("51.06.940")) lat="51.06940";
if(lat.equals("51.08 273")) lat="51.08273";
if(lat.equals("50.96 705")) lat="50.96705";
if(lat.equals("51.03 021")) lat="51.03021";
if(lat.equals("51.01 764")) lat="51.01764";
if(lat.equals("50.99 388")) lat="50.99388";
if(lat.equals("50.50 509")) lat="50.50509";
if(lat.equals("43.109.94")) lat="43.10994";
if(lat.equals("50.11.926")) lat="50.11926";
if(lat.equals("50.04.966")) lat="50.04966";
if(lat.equals("49.26.385")) lat="49.26385";
if(lat.equals("49.26.251")) lat="49.26251";
if(lat.equals("49.25.307")) lat="49.25307";
if(lat.equals("44.4930.")) lat="49.25307";
locust.lat=Double.parseDouble(lat);
String lon=CutBeforeFirst(data,";");
if(lon.equals("51.25 560")) lon="51.25560";
if(lon.equals("51.25 099")) lon="51.25099";
if(lon.equals("51.26 378")) lon="51.26378";
if(lon.equals("51.25 235")) lon="51.25235";
if(lon.equals("51.83 107")) lon="51.83107";
if(lon.equals("51.71 702")) lon="51.71702";
if(lon.equals("52.21 390")) lon="52.21390";
if(lon.equals("52.10 873")) lon="52.10873";
if(lon.equals("51.85 606")) lon="51.85606";
if(lon.equals("52.41 085")) lon="52.41085";
if(lon.equals("52.36 125")) lon="52.36125";
if(lon.equals("51. 56 025")) lon="51.56025";
if(lon.equals("51.56 786")) lon="51.56786";
if(lon.equals("51.57 946")) lon="51.57946";
if(lon.equals("51.16 758")) lon="51.16758";
if(lon.equals("85.09.142")) lon="85.09142";
locust.lon=Double.parseDouble(lon);
}catch(Exception ex)
{
error=true;
}
locust.region=CutBeforeFirst(data,";");
//Выбираю ID области
Statement stt = null;
ResultSet rs = null;
try {
if(locust.region.equals("Алматинский")) locust.region="Алматинская";
if(locust.region.equals("Туркестанский")) locust.region="Туркестанская";
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sql_query = "select id from main.countriesregions where name like '%"+locust.region+"%';";
rs = stt.executeQuery(sql_query);
if (rs != null) {
try {
if (rs.next()) {
locust.region_id=rs.getString(1);
}
rs.close();
} catch (SQLException ex) {
}
}
} catch (SQLException ex) {
}finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.close();}catch(SQLException ex){}
}
//Выбираю id региона (main.countriesdistricts)
locust.district_id="";
locust.district=CutBeforeFirst(data,";");
stt = null;
rs = null;
try {
if(locust.district.equals("Сарканский ")) locust.district="Саркандский";
if(locust.district.equals("Уйгуский")) locust.district="Уйгурский";
if(locust.district.equals("г.Капшагай")) locust.district="Капчагайский городской округ";
if(locust.district.equals("Каратальскиий")) locust.district="Каратальский";
if(locust.district.equals("г. Талдыкорган")) locust.district="Талдыкорганский";
if(locust.district.equals("г Атырау ")) locust.district="Атырауский городской округ";
if(locust.district.equals("г. Атырау")) locust.district="Атырауский городской округ";
if(locust.district.equals("Кызылкуга")) locust.district="Кзылкогинский район";
if(locust.district.equals("Курчумский ")) locust.district="Куршимский район";
if(locust.district.equals("г.Семей")) locust.district="Семипалатинский городской округ";
if(locust.region_id.equals("4") && locust.district.equals("Жамбылский")) locust.district="Джамбулский район";
if(locust.district.equals("Т.Рыскуловский")) locust.district="Рыскуловский район";
if(locust.district.equals("Шуйский")) locust.district="Чуйский район";
if(locust.district.equals("Сарысуский")) locust.district="Сары-Суйский район";
if(locust.district.equals("Федоровский")) locust.district="Фёдоровский район";
if(locust.district.equals("Жангельдинский")) locust.district="Джангельдинский район";
if(locust.district.equals("Сырдария")) locust.district="Сырдарьинский район";
if(locust.district.equals("Кызылорда")) locust.district="Кызылординский городской округ";
if(locust.district.equals("к.Кызылорда")) locust.district="Кызылординский городской округ";
if(locust.district.equals("Аралский")) locust.district="Аральский район";
if(locust.district.equals("Шиелі")) locust.district="Шиелийский район";
if(locust.region_id.equals("11") && locust.district.equals("Аксуский")) locust.district="Аксуйский городской округ";
if(locust.region_id.equals("11") && locust.district.equals("Аксуский")) locust.district="Аксуйский городской округ";
if(locust.region_id.equals("11") && locust.district.equals("Ақсуский")) locust.district="Аксуйский городской округ";
if(locust.district.equals("Аққулы")) locust.district="Аккулинский район";
if(locust.district.equals("Аккулы")) locust.district="Аккулинский район";
if(locust.district.equals("Тереңкөл")) locust.district="Теренкольский";
if(locust.district.equals("г. Павлодар")) locust.district="Павлодарский городской округ";
if(locust.district.equals("Екибастузский")) locust.district="Экибастузский городской округ";
if(locust.district.equals("Шербактнский")) locust.district="Щербактинский район";
if(locust.district.equals("Толебиский ")) locust.district="Толебийский район";
if(locust.district.equals("г.Шымкент Абайский ")) locust.district="Шымкентский городской округ";
if(locust.district.equals("г.Шымкент Каратауский ")) locust.district="Шымкентский городской округ";
if(locust.district.equals("Баянауыл")) locust.district="Баянаул";
if(locust.district.equals("Екібастұз")) locust.district="Экибастуз";
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sql_query = "select id from main.countriesdistricts where region_id="+locust.region_id+" and name like '%"+locust.district+"%';";
rs = stt.executeQuery(sql_query);
if (rs != null) {
try {
if (rs.next()) {
locust.district_id=rs.getString(1);
}
rs.close();
} catch (SQLException ex) {
}
}
} catch (SQLException ex) {
}finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.close();}catch(SQLException ex){}
}
//Сельский округ
locust.terrain=CutBeforeFirst(data,";");
//Хозяйство или местность
locust.village=CutBeforeFirst(data,";");
//Вид саранчи
locust.locust=CutBeforeFirst(data,";");
locust.locust_id="";
if(locust.locust.equals(" итальянский прус")) locust.locust_id="1";
if(locust.locust.equals("итальянский прус")) locust.locust_id="1";
if(locust.locust.equals("Итальянский прус")) locust.locust_id="1";
if(locust.locust.equals("итальянский прус ")) locust.locust_id="1";
if(locust.locust.equals("Азиатская саранча")) locust.locust_id="3";
if(locust.locust.equals("азиатская саранча")) locust.locust_id="3";
if(locust.locust.equals("нестадные")) locust.locust_id="4";
if(locust.locust.equals("нестадные саранчовые")) locust.locust_id="4";
if(locust.locust.equals("Нестадные саранчевые")) locust.locust_id="4";
if(locust.locust.equals("Нестадная саранча ")) locust.locust_id="4";
if(locust.locust.equals("Нестадная саранча")) locust.locust_id="4";
if(locust.locust.equals("нестадная саранча")) locust.locust_id="4";
if(locust.locust.equals("Мароккская саранча")) locust.locust_id="2";
//фаза саранчи
locust.phase=CutBeforeFirst(data,";");
locust.locust_have="3";
if(locust.phase.equals("кубышки")) locust.locust_have="2";
if(locust.phase.equals("личинки")) locust.locust_have="3";
if(locust.phase.equals("имаго")) locust.locust_have="5";
locust.evp=CutBeforeFirst(data,";"); //ЭФП
locust.size=CutBeforeFirst(data,";"); //Заселённая площадь
locust.size=locust.size.replace(",",".");
locust.date=CutBeforeFirst(data,";"); //Дата
String row="<tr>";
if(error==true || locust.lat==0 || locust.lon==0 || locust.region_id.equals("") || locust.district_id.equals("") || locust.terrain.equals("") || locust.locust_id.equals("")) {
row="<tr style=\"background-color:red;\">";
}
row+="<td>"+i+"</td><td>"+locust.lat+"</td><td>"+locust.lon+"</td><td>"+locust.region+" = "+locust.region_id+"</td><td>"+locust.district+" = "+locust.district_id+"</td><td>"+locust.terrain+"</td><td>"+locust.village+"</td><td>"+locust.locust+" = "+locust.locust_id+"</td><td>"+locust.phase+" = "+locust.locust_have+"</td><td>"+locust.evp+"</td><td>"+locust.size+"</td><td>"+locust.date+"</td>";
row+="</tr>\n";
table += row;
i++;
json+=" \n{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":["+locust.lon+","+locust.lat+"]},\"properties\":{\"oblast\":\""+locust.region.replace("\"", "'")+"\",\"district\":\""+locust.district.replace("\"", "'")+"\",\"region\":\""+locust.terrain.replace("\"", "'")+"\",\"village\":\""+locust.village.replace("\"", "'")+"\",\"phase\":\""+locust.phase+"\",\"locust\":\""+locust.locust+"\",\"evp\": \""+locust.evp+"\",\"ga\": \""+locust.size+"\",\"date\": \""+locust.date+"\"}},";
sqlData+="insert into main.frmlocust(country_id,region_id,district,terrain,village,lon1,lat1,locust_type_id,locust_have,locust_populated,date)values(5,"+locust.region_id+",'"+locust.district.trim()+"','"+locust.terrain.trim()+"','"+locust.village.trim()+"',"+locust.lon+","+locust.lat+","+locust.locust_id+","+locust.locust_have+","+locust.size+",TO_DATE('"+locust.date+"','DD.MM.YYYY'));\n";
if(i>5000) break;
line=reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}else {
table="CSV file is empty! "+skip;
}
table += "</table>";
json=json.substring(0,json.length()-1); //Удаляю последнюю запятую
json+="\n]}";
model.addAttribute("PreviewTable",table);
model.addAttribute("PreviewGEOJSON",json);
model.addAttribute("PreviewSQL",sqlData);
return "excel";
}
//---------------------------------------------------------------------------
public static String CutBeforeFirst(StringBuffer str,String ch)
{
int pos=str.indexOf(ch);
String result="";
if(pos==-1)
{
result.concat(str.toString());
str.delete(0,str.length());
}else
{
result=str.substring(0,pos);
str.delete(0,pos+1);
}
return result;
}
//---------------------------------------------------------------------------
class Locust{
double lon;
double lat;
String region; //Область
String region_id;
String district; //Район
String district_id;
String terrain; //Название месности
String village; //Хозяйство или местность
String locust; //Вид саранчи
String locust_id; //Вид саранчи
String phase; //Фаза саранчи
String locust_have; //id Фазы саранчи
String evp; //ЭФП
String size; //Заселённая площадь
String date; //Дата
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,177 @@
package org.ccalm.main;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//import java.util.Iterator;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
//import org.apache.commons.fileupload.FileItem;
//import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.servlet.ServletFileUpload;
import jakarta.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import tctable.Tools;
import tools.PreparedStatementNamed;
import tools.User;
@Controller
//@SessionAttributes( { "user" })
public class DataJSON implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(DataJSON.class);
private ServletContext context;
//If not created object "user", create him.
//@ModelAttribute("user")
//public User populatePerson() {
// return new User("none");
//}
@RequestMapping(value = "/get_companies",method = {RequestMethod.POST,RequestMethod.GET}, produces = "application/json;charset=UTF-8")
@ResponseBody
public String getCompanies(@ModelAttribute User user,@RequestParam(required=false,name="country_id") String country_id,@RequestParam(required=false,name="lng") String language_id) {
int errorCode=0;
String errorMessage="";
//Load configuration
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
}
try {
Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stt0.executeUpdate("SET TIME ZONE 'UTC';");
//stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';");
stt0.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
errorCode=1;
errorMessage+="Failed to execute SQL query!";
}
JSONObject doc=null;
JSONArray array=new JSONArray(); //Результирующий набор данных
String sql_query = "";
Statement stt=null;
ResultSet rs=null;
try {
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
sql_query = "select id,name from main.companies where del=false and name is not null and name!='' and (${country_id} is null or country_id=${country_id})";
PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query);
if(country_id==null || country_id.equals(""))
stmtn.setNULLInt("country_id");
else
stmtn.setInt("country_id",Integer.parseInt(country_id));
PreparedStatement stmt=stmtn.getPreparedStatement();
rs = stmt.executeQuery();
if (rs != null) {
try {
while(rs.next()) {
JSONObject obj = new JSONObject();
obj.put("id", rs.getLong("id"));
if(rs.getObject("name")!=null)
obj.put("name", rs.getString("name"));
array.put(obj);
}
rs.close();
} catch (SQLException ex) {
errorCode=4;
errorMessage+="Internal server error, sampling.";
ex.printStackTrace();
logger.info(ex.getMessage());
}
}
} catch (SQLException ex) {
errorCode=5;
errorMessage+="Internal server error, query. ";
ex.printStackTrace();
logger.info(ex.getMessage());
}finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.close();}catch(SQLException ex){}
}
if(errorCode!=0) {
JSONObject obj = new JSONObject();
obj.put("error_code",errorCode);
obj.put("error_message", errorMessage);
return obj.toString();
}else {
JSONObject obj = new JSONObject();
obj.put("error_code",0);
obj.put("error_message", "");
if(doc!=null)
obj.put("indicator",doc.getString("indicator"));
obj.put("data",array);
return obj.toString();
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
}

View File

@ -0,0 +1,364 @@
package org.ccalm.main;
import jakarta.servlet.ServletContext;
import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconstConstants;
//import javax.servlet.ServletContext;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
/*import ucar.ma2.Array;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;*/
@Controller
public class DownloadNDVI implements ServletContextAware {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DownloadNDVI.class);
private ServletContext context;
@RequestMapping(value = "/DownloadNDVI",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxTamer(@RequestParam(required=false,name="forecast") String forecast) {
//String forecast = request.getParameter("forecast"); //Date like as "000".
//response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String result="";
result+="Start!<br>";
//http://gis-lab.info/forum/viewtopic.php?style=1&t=15764
gdal.AllRegister();
Dataset dataset=gdal.Open("O:\\Desctop\\NDVI_from_HDF\\1\\MOD13Q1.A2019049.h27v12.006.2019073153055.hdf" , gdalconstConstants.GA_ReadOnly);
Band o=(Band)dataset.GetRasterBand(1);
long flen=o.getXSize()*o.getYSize();
result+=flen;
/*
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
//Load DB configuration from "config.xml"
String db_url = "";
String db_login = "";
String db_password = "";
String data_dir = "";
try {
//String fullPath = context.getRealPath("/WEB-INF/config.xml");
//File fXmlFile = new File(fullPath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Document doc = dBuilder.parse(fXmlFile);
Document doc = dBuilder.parse(new ClassPathResource("config.xml").getInputStream());
Element nMain = doc.getDocumentElement();
NodeList nl = nMain.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeName().equals("db-url"))
db_url = nl.item(i).getTextContent();
if (nl.item(i).getNodeName().equals("db-login"))
db_login = nl.item(i).getTextContent();
if (nl.item(i).getNodeName().equals("db-password"))
db_password = nl.item(i).getTextContent();
if (nl.item(i).getNodeName().equals("data-dir"))
data_dir = nl.item(i).getTextContent();
}
} catch (Exception ex) {
logger.info(ex.getMessage());
}
data_dir+="temp"+File.separator;
File dir = new File(data_dir);
if (!dir.exists()) dir.mkdirs();
//response.getWriter().append("Served at: ").append(request.getContextPath());
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
//Example request: http://localhost:8080/CCALM/DownloadWeather?forecast=000
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String date=dateFormat.format(new Date()); //Date like as "20170327".
String time = "00"; //00 hours,06 hours,12 hours and 18 hours
//String forecast = request.getParameter("forecast"); //Date like as "000".
String measurement = "TSOIL:0-0.1 m below ground";
//String measurement = "TSOIL:0.1-0.4 m below ground";
//Build URL to download
String URL = "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs."+date+time+"/gfs.t"+time+"z.pgrb2.0p25.f"+forecast;
//URL = "http://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs.2017091200/gfs.t00z.pgrb2.0p25.f000";
WeatherDownload wd = new WeatherDownload();
if(wd.download(URL+".idx", data_dir+"text.idx", "0", ""))
{
result+="Download "+URL+".idx"+" to "+data_dir+"text.idx"+"<br>";
String strPos1="";
String strPos2="";
//Read file and find required line.
try {
BufferedReader br = new BufferedReader(new FileReader(data_dir+"text.idx"));
String line;
while ((line = br.readLine()) != null)
{
//if (line.contains("TSOIL:0-0.1 m below ground"))
if (line.contains(measurement))
{
strPos1=line;
strPos2=br.readLine();
break;
}
}
br.close();
} catch (IOException ex) {
logger.info(ex.getMessage());
result+=ex.getMessage()+"<br>";
}
if(!strPos1.equals(""))
{
//String strPos1 = "250:146339365:d=2017022818:TSOIL:0-0.1 m below ground:anl:"
StringBuffer answer1=new StringBuffer(strPos1);
CutBeforeFirst(answer1,":");
String posStart = CutBeforeFirst(answer1,":");
StringBuffer answer2=new StringBuffer(strPos2);
CutBeforeFirst(answer2,":");
String posEnd = CutBeforeFirst(answer2,":");
if(posEnd==null || posEnd.equals("")) posEnd=""; else
{
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
}
wd.download(URL, data_dir+"text.f000", String.valueOf(posStart), String.valueOf(posEnd));
}
}else
{
result+="Not download "+URL+".idx"+" to "+data_dir+"text.idx"+"<br>";
}
Array dataArrayLat=null;
Array dataArrayLon=null;
Array dataArrayTmp=null;
try {
// open netcdf/grib/grib2 file from argument
NetcdfDataset gid = NetcdfDataset.openDataset(data_dir+"text.f000");
//logger.info("Desc: " + gid.getDescription());
logger.info(gid.getDetailInfo());
//logger.info("Feature type: " + gid.getFeatureType().toString());
// get all grid tables in the file
List<Variable> variables = gid.getReferencedFile().getVariables();
for (int i = 0; i < variables.size(); i++)
{
System.out.print(variables.get(i).getName()+" ");
//LatLon_Projection, lat, lon, reftime, time, depth_below_surface_layer, depth_below_surface_layer_bounds, Soil_temperature_depth_below_surface_layer
if(variables.get(i).getName().equals("reftime"))
{
logger.info("");
logger.info("Description = "+variables.get(i).getDescription());
logger.info("DimensionsString = "+variables.get(i).getDimensionsString());
logger.info("DataType = "+variables.get(i).getDataType());
logger.info("UnitsString = "+variables.get(i).getUnitsString()); //Hour since 2017-02-28T18:00:00Z
}
if(variables.get(i).getName().equals("lon"))
{
dataArrayLon = variables.get(i).read();
}
if(variables.get(i).getName().equals("lat"))
{
dataArrayLat = variables.get(i).read();
}
if(variables.get(i).getName().equals("Soil_temperature_depth_below_surface_layer"))
{
//Section sec=new Section();
dataArrayTmp = variables.get(i).read();
//for(int j=0;j<dataArrayTmp.getSize();j++)
//{
// logger.info(j+") "+dataArrayTmp.getFloat(j)+",");
//}
}
}
logger.info("");
List<Dimension> dims = gid.getDimensions();
logger.info("dims.size() = " + dims.size());
Iterator<Dimension> dimIt = dims.iterator();
while( dimIt.hasNext()) {
Dimension dim = dimIt.next();
logger.info("Dim = " + dim);
logger.info("Dim name = "+dim.getName());
}
dimIt = null;
Statement st=null;
try {
st = conn.createStatement();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("BEGIN TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
result+="Size="+dataArrayLat.getSize()+"<br>";
int pos=0;
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
{
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
{
//WGS84 Bounds: -180.0000, -90.0000, 180.0000, 90.0000
//Projected Bounds: -180.0000, -90.0000, 180.0000, 90.0000
double lon = dataArrayLon.getFloat(nLon);
if(lon>180) lon=lon-360;
double lat = dataArrayLat.getFloat(nLat);
if(lat>29 && lat<67 && lon>17 && lon<180) //Central Asia
{
if(!Float.isNaN(dataArrayTmp.getFloat(pos))) //On the water none temperatyre.
{
String country_id="";
ResultSet rs=null;
try {
rs = st.executeQuery("select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1");
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if (rs != null) {
try {
if (rs.next())
country_id=rs.getString(1);
rs.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
{
//logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos));
try {
//String sql="insert into weather(weather_type_id,date,hours,val,geom)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326));";
//String sql="insert into main.weather(weather_type_id,date,hours,val,geom,country_id)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),(select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1));";
String sql="insert into main.weather(weather_type_id,date,hours,val,geom,country_id)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),"+country_id+");";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
}
}
pos++;
}
}
//Cut data pise for Russia
try {
//String sql="update weather w set country_id=null where country_id=7 and not ST_Contains((select geom from main.countriesregions where id=97),w.geom);";
String sql="update main.weather w set country_id=null where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),w.geom);";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete values where country_id is null
try {
String sql="delete from main.weather where country_id is null;";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete all old values
try {
String sql="delete from main.weather where date!=(select max(date) from main.weather limit 1);";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
try {
st.executeUpdate("END TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
gid.close();
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.print("ERROR!");
}
try {conn.close();} catch (SQLException ex) {logger.info(ex.getMessage());}
result+="End!<br>";
*/
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
//---------------------------------------------------------------------------
public static String CutBeforeFirst(StringBuffer str,String ch)
{
int pos=str.indexOf(ch);
String result="";
if(pos==-1)
{
result.concat(str.toString());
str.delete(0,str.length());
}else
{
result=str.substring(0,pos);
str.delete(0,pos+1);
}
return result;
}
}

View File

@ -0,0 +1,441 @@
package org.ccalm.main;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
//import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
//import main.DownloadFromHTTP;
import ucar.ma2.Array;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;
@Controller
public class DownloadWeather implements ServletContextAware {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DownloadWeather.class);
private ServletContext context;
@RequestMapping(value = "/DownloadWeather",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxTamer(@RequestParam(required=false,name="forecast") String forecast,@RequestParam(required=false,name="date") String date) {
//String forecast = request.getParameter("forecast"); //Date like as "000".
//response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String result="";
result+="Start!<br>";
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
//Load DB configuration from "config.xml"
String db_url="";
String db_login="";
String db_password="";
String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
data_dir+="temp"+File.separator;
File dir = new File(data_dir);
if (!dir.exists()) dir.mkdirs();
//response.getWriter().append("Served at: ").append(request.getContextPath());
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
//Example request: http://ccalm.org/DownloadWeather?forecast=000&date=20210531
//Example request: http://localhost:8080/CCALM/DownloadWeather?forecast=000
//Example request: http://127.0.0.1:8080/CCALM/DownloadWeather?forecast=000
if(date==null || date.equals(""))
{
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
date=dateFormat.format(new Date()); //Date like as "20170327".
}
String time = "00"; //00 hours,06 hours,12 hours and 18 hours
//String forecast = request.getParameter("forecast"); //Date like as "000".
String measurement = "TSOIL:0-0.1 m below ground";
//String measurement = "TSOIL:0.1-0.4 m below ground";
//Build URL to download
String URL = "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs."+date+"/"+time+"/atmos/gfs.t"+time+"z.pgrb2.0p25.f"+forecast;
File f = new File(data_dir+"text.idx");
if(f.exists()) {
if (!f.delete()) {
System.out.println("Failed to delete the file.");
}
}
WeatherDownload wd = new WeatherDownload();
if(wd.download(URL+".idx", data_dir+"text.idx", "0", ""))
{
result+="Download "+URL+".idx"+" to "+data_dir+"text.idx"+"<br>";
String strPos1="";
String strPos2="";
//Read file and find required line.
try {
BufferedReader br = new BufferedReader(new FileReader(data_dir+"text.idx"));
String line;
while ((line = br.readLine()) != null)
{
//if (line.contains("TSOIL:0-0.1 m below ground"))
if (line.contains(measurement))
{
strPos1=line;
strPos2=br.readLine();
break;
}
}
br.close();
} catch (IOException ex) {
logger.info(ex.getMessage());
result+=ex.getMessage()+"<br>";
}
if(!strPos1.equals(""))
{
//String strPos1 = "250:146339365:d=2017022818:TSOIL:0-0.1 m below ground:anl:"
StringBuffer answer1=new StringBuffer(strPos1);
CutBeforeFirst(answer1,":");
String posStart = CutBeforeFirst(answer1,":");
StringBuffer answer2=new StringBuffer(strPos2);
CutBeforeFirst(answer2,":");
String posEnd = CutBeforeFirst(answer2,":");
if(posEnd==null || posEnd.equals("")) posEnd=""; else
{
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
}
wd.download(URL, data_dir+"text.f000", String.valueOf(posStart), String.valueOf(posEnd));
}
}else
{
result+="Not download "+URL+".idx"+" to "+data_dir+"text.idx"+"<br>";
}
Array dataArrayLat=null;
Array dataArrayLon=null;
Array dataArrayTmp=null;
try {
// open netcdf/grib/grib2 file from argument
NetcdfDataset gid = NetcdfDataset.openDataset(data_dir+"text.f000");
//logger.info("Desc: " + gid.getDescription());
logger.info(gid.getDetailInfo());
//logger.info("Feature type: " + gid.getFeatureType().toString());
// get all grid tables in the file
List<Variable> variables = gid.getReferencedFile().getVariables();
for (int i = 0; i < variables.size(); i++)
{
System.out.print(variables.get(i).getName()+" ");
//LatLon_Projection, lat, lon, reftime, time, depth_below_surface_layer, depth_below_surface_layer_bounds, Soil_temperature_depth_below_surface_layer
if(variables.get(i).getName().equals("reftime"))
{
logger.info("");
logger.info("Description = "+variables.get(i).getDescription());
logger.info("DimensionsString = "+variables.get(i).getDimensionsString());
logger.info("DataType = "+variables.get(i).getDataType());
logger.info("UnitsString = "+variables.get(i).getUnitsString()); //Hour since 2017-02-28T18:00:00Z
}
if(variables.get(i).getName().equals("lon"))
{
dataArrayLon = variables.get(i).read();
}
if(variables.get(i).getName().equals("lat"))
{
dataArrayLat = variables.get(i).read();
}
if(variables.get(i).getName().equals("Soil_temperature_depth_below_surface_layer"))
{
//Section sec=new Section();
dataArrayTmp = variables.get(i).read();
/*for(int j=0;j<dataArrayTmp.getSize();j++)
{
logger.info(j+") "+dataArrayTmp.getFloat(j)+",");
}*/
}
}
logger.info("");
List<Dimension> dims = gid.getDimensions();
logger.info("dims.size() = " + dims.size());
Iterator<Dimension> dimIt = dims.iterator();
while( dimIt.hasNext()) {
Dimension dim = dimIt.next();
logger.info("Dim = " + dim);
logger.info("Dim name = "+dim.getName());
}
dimIt = null;
Statement st=null;
try {
st = conn.createStatement();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("BEGIN TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
result+="Size="+dataArrayLat.getSize()+"<br>";
int pos=0;
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
{
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
{
//WGS84 Bounds: -180.0000, -90.0000, 180.0000, 90.0000
//Projected Bounds: -180.0000, -90.0000, 180.0000, 90.0000
double lon = dataArrayLon.getFloat(nLon);
if(lon>180) lon=lon-360;
double lat = dataArrayLat.getFloat(nLat);
if(lat>29 && lat<67 && lon>17 && lon<180) //Central Asia
{
if(!Float.isNaN(dataArrayTmp.getFloat(pos))) //On the water none temperatyre.
{
String country_id="";
ResultSet rs=null;
try {
rs = st.executeQuery("select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1");
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if (rs != null) {
try {
if (rs.next())
country_id=rs.getString(1);
rs.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
{
//logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos));
try {
//String sql="insert into main.weather(weather_type_id,date,hours,val,geom)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326));";
//String sql="insert into main.weather(weather_type_id,date,hours,val,geom,country_id)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),(select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1));";
String sql="insert into main.weather(weather_type_id,date,hours,val,geom,country_id)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),"+country_id+");";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
}
}
pos++;
}
}
//Cut data piece from big country of Russia
try {
//String sql="update weather w set country_id=null where country_id=7 and not ST_Contains((select geom from main.countriesregions where id=97),w.geom);";
String sql="update main.weather w set country_id=null where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),w.geom);";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete values where country_id is null
try {
String sql="delete from main.weather where country_id is null;";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete all old values аnd not a multiple of 10.
try {
String sql="delete from main.weather where date!=(select max(date) from main.weather limit 1) and ((DATE_PART('doy',date)::INTEGER-1)%10!=0 or ((DATE_PART('doy',date)::INTEGER-1)%10=0 and hours=48));";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
try {
st.executeUpdate("END TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
gid.close();
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.print("ERROR!");
}
try {conn.close();} catch (SQLException ex) {logger.info(ex.getMessage());}
result+="End!<br>";
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
//---------------------------------------------------------------------------
public static String CutBeforeFirst(StringBuffer str,String ch)
{
int pos=str.indexOf(ch);
String result="";
if(pos==-1)
{
result.concat(str.toString());
str.delete(0,str.length());
}else
{
result=str.substring(0,pos);
str.delete(0,pos+1);
}
return result;
}
//---------------------------------------------------------------------------
//List of "Soil temperature" dates from database in JSON
@RequestMapping(value = "/WeatherSoilDates",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxSoilDates() {
boolean error=false;
String result="";
//Load DB configuration from "config.xml"
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
error=true;
result="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
error=true;
result="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st;
try {
st = conn.createStatement();
String sql = "SELECT to_char(date, 'YYYY-MM-DD') as date,hours as hour,DATE_PART('doy',date)-1 as day FROM main.weather group by date,hours order by date,hours";
ResultSet rs = st.executeQuery(sql);
if(rs!=null)
{
boolean exists=false;
result="[";
while (rs.next())
{
exists=true;
try {
result+= "{\"num\":\""+rs.getString("day")+"\", \"hour\":\""+rs.getString("hour")+"\", \"date\":\""+rs.getString("date")+"\"},";
} catch( Exception ex )
{
}
}
if(exists) {
result=result.substring(0, result.length()-1);
result+="]";
}else {
result="[]";
}
}
st.close();
conn.close();
} catch (SQLException ex) {
result="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
return result;
}
//---------------------------------------------------------------------------
}

View File

@ -0,0 +1,251 @@
package org.ccalm.main;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import tctable.TCField;
import tctable.TCTable;
@Controller
public class GeoGSON implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(GeoGSON.class);
private ServletContext context;
@RequestMapping(value = "/geojson", method = RequestMethod.GET)
@ResponseBody
public Object home(@RequestParam(required=false,name="table") String table,@RequestParam(required=false,name="id") String id)
{
boolean error=false;
String result="";
String db_url="";
String db_login="";
String db_password="";
String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
error=true;
result="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
error=true;
result="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st;
try {
st = conn.createStatement();
String sql="select id,name,ST_AsGeoJSON(geom,3,0) as geom from main."+table+" where id="+id+";";
ResultSet rs = st.executeQuery(sql);
if(rs!=null)
{
while (rs.next())
{
String geom=null;
try {
geom=rs.getString("geom");
} catch( Exception ex )
{
result="<metadata fn=\"-1\"><![CDATA[SQLException: "+ex.getMessage()+"]]></metadata>";
}
if(geom==null) geom="";
result=geom;
}
}
st.close();
conn.close();
} catch (SQLException ex) {
result="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
return result;
}
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
//For compilatin android project
//http://127.0.0.1:8080/CCALM/countriesregionspoints
@RequestMapping(value = "/countriesregionspoints", method = RequestMethod.GET)
@ResponseBody
public Object countriesregions()
{
boolean error=false;
String result="OK<br>";
String db_url="";
String db_login="";
String db_password="";
String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
error=true;
result+="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
error=true;
result+="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st,stC;
//Каждую геозонку области записываю в отдельный файл
String sql="select id from main.countriesregions where del=false";
try {
stC = conn.createStatement();
ResultSet rsC = stC.executeQuery(sql);
if(rsC!=null)
{
while (rsC.next())
{
sql="";
//sql+=" select t1.id as country_region_id,(ST_DumpPoints(geom)).path[1] as pos,cast(ST_X((ST_DumpPoints(geom)).geom) as real) lon,cast(ST_Y((ST_DumpPoints(geom)).geom) as real) lat from";
sql+=" select cast(ST_X((ST_DumpPoints(geom)).geom) as real) lon,cast(ST_Y((ST_DumpPoints(geom)).geom) as real) lat from";
sql+=" (";
sql+=" select id,name,ST_Area(t.gone) area,ST_ExteriorRing(gone) as geom from";
sql+=" (select id,name,ST_NumGeometries(geom),(ST_Dump(geom)).geom gone from main.countriesregions where del=false and id="+rsC.getString("id")+") t";
sql+=" )t1";
sql+=" ,";
sql+=" (select id,max(ST_Area(t.gone)) area from";
sql+=" (select id,name,ST_NumGeometries(geom),(ST_Dump(geom)).geom gone from main.countriesregions where del=false and id="+rsC.getString("id")+") t";
sql+=" group by id) t2";
sql+=" where";
sql+=" t1.id=t2.id";
sql+=" and t1.area=t2.area";
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
try {
if(rs!=null)
{
File targetFile = new File(data_dir+"region_"+rsC.getString("id")+".tbl"); //Андроид не разрешает ресурсы с циферки
OutputStream outStream = new FileOutputStream(targetFile);
TCTable tbl=new TCTable("crcountriesregionspoints",123456);
logger.info("countriesregionspoints");
ResultSetMetaData rsmd = rs.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();i++)
{
logger.info(i+") name="+rsmd.getColumnName(i)+" type="+rsmd.getColumnTypeName(i));
TCField field=new TCField(rsmd.getColumnName(i), rsmd.getColumnTypeName(i));
tbl.addField(field);
}
tbl.getHeader(outStream);
while (rs.next())
{
for(int i=1;i<=rsmd.getColumnCount();i++)
{
if(!rsmd.getColumnTypeName(i).equals("geometry"))
tbl.fields.get(i-1).setValue(rs.getString(i));
else
tbl.fields.get(i-1).setValue(null);
}
//Save binary data to stream
tbl.getCol(outStream);
}
outStream.flush();
outStream.close();
}
rs.close();
st.close();
//response.getOutputStream();
//response.flushBuffer();
} catch (IOException ex) {
result+="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
}
rsC.close();
stC.close();
conn.close();
} catch (SQLException ex) {
// TODO Auto-generated catch block
result+="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
return result;
}
}

View File

@ -0,0 +1,746 @@
package org.ccalm.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.Base64;
import java.util.Properties;
import tctable.Tools;
@Controller
public class Integration implements ServletContextAware {
private static final int BUFFER_SIZE = 4096;
private static final Logger logger = LoggerFactory.getLogger(Integration.class);
private ServletContext context;
@RequestMapping(value = "/integration/getByTime", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody
public Object getByTime(@RequestParam(required=true,name="token") String token,@RequestParam(required=true,name="timeBegin") String timeBegin,@RequestParam(required=false,name="timeEnd") String timeEnd,@RequestParam(required=false,name="type") String type)
{
if(type!=null && type.equals("del"))
return getDataDel(token,timeBegin,timeEnd,null,null);
else
return getData(token,timeBegin,timeEnd,null,null);
}
@RequestMapping(value = "/integration/getByDate", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody
public Object getByDate(@RequestParam(required=true,name="token") String token,@RequestParam(required=true,name="dateBegin") String dateBegin,@RequestParam(required=false,name="dateEnd") String dateEnd,@RequestParam(required=false,name="type") String type)
{
if(type!=null && type.equals("del"))
return getDataDel(token,null,null,dateBegin,dateEnd);
else
return getData(token,null,null,dateBegin,dateEnd);
}
//Prepare data for sending to integration servers.
String getData(String token, String timeBegin,String timeEnd,String dateBegin,String dateEnd) {
int errorCode=0;
String errorCodeDescription="";
if(!(
token.equals("DA46DCA8E49D52A12614D4FE4CF4") // RUS
|| token.equals("R5375VJERFJKFTGKT8235QFSJHDE") // HIH FAO
|| token.equals("QIWGHIEEEEEE732RUEWHDHREU92Z") //???
|| token.equals("BA46DCA8E49D52A12614D4FE4CF5") //Kazahstan
|| token.equals("Z1263ERF2H3E4JU6241L5D6Q7NGT") //Uzbekistan
)) { //Access only for Russians
JSONObject obj = new JSONObject();
obj.put("errorCode",1);
obj.put("errorCodeDescription", "Token is not correct!");
return obj.toString();
}
String db_url="";
String db_login="";
String db_password="";
String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
} catch (Exception ex) {
errorCode=3;
errorCodeDescription+="Внутренняя ошибка сервера, база. ";
ex.printStackTrace();
}
JSONArray array=new JSONArray(); //Результирующий набор данных
String sql_query = "";
Statement stt=null;
ResultSet rs=null;
try {
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
sql_query = "select * from main.integration_1(1,?::bigint,?::bigint,TO_TIMESTAMP(?,'YYYY-MM-DD HH24:MI')::timestamp,TO_TIMESTAMP(?,'YYYY-MM-DD HH24:MI')::timestamp);";
//String timeBegin,String timeEnd,String dateBegin,String dateEnd
PreparedStatement stmt=null;
stmt = conn.prepareStatement(sql_query);
stmt.setString(1,timeBegin);
stmt.setString(2,timeEnd);
stmt.setString(3,dateBegin);
stmt.setString(4,dateEnd);
//stmt.execute();
rs = stmt.executeQuery();
//rs = stt.executeQuery(sql_query);
if (rs != null) {
try {
while(rs.next()) {
JSONObject obj = new JSONObject();
obj.put("id", rs.getLong("id"));
obj.put("seq", rs.getLong("seq"));
obj.put("country_name", rs.getString("country_name")); //Страна
obj.put("region_name", rs.getString("region_name")); //Область
obj.put("town_name", rs.getString("town_name")); //Район
obj.put("date", rs.getString("date")); //Дата анкетирования
obj.put("surveyed_area", rs.getDouble("surveyed_area")); //Обследованная площадь га
int cnt1=0;
if(rs.getString("lat1")!=null && rs.getString("lon1")!=null) cnt1++;
if(rs.getString("lat2")!=null && rs.getString("lon2")!=null) cnt1++;
if(rs.getString("lat3")!=null && rs.getString("lon3")!=null) cnt1++;
if(rs.getString("lat4")!=null && rs.getString("lon4")!=null) cnt1++;
if(rs.getString("lat5")!=null && rs.getString("lon5")!=null) cnt1++;
if(rs.getString("lat6")!=null && rs.getString("lon6")!=null) cnt1++;
boolean point=cnt1<=2;
JSONObject geom = new JSONObject();
if(point) {
geom.put("type","Point");
JSONArray crdSub=new JSONArray();
crdSub.put(rs.getDouble("lon1"));
crdSub.put(rs.getDouble("lat1"));
geom.put("coordinates", crdSub);
}else {
geom.put("type","Polygon");
JSONArray crdMain=new JSONArray();
JSONArray crdSub=new JSONArray();
crdMain.put(crdSub);
if(rs.getString("lat1")!=null && rs.getString("lon1")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon1"));
crd.put(rs.getDouble("lat1"));
crdSub.put(crd);
}
if(rs.getString("lat2")!=null && rs.getString("lon2")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon2"));
crd.put(rs.getDouble("lat2"));
crdSub.put(crd);
}
if(rs.getString("lat3")!=null && rs.getString("lon3")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon3"));
crd.put(rs.getDouble("lat3"));
crdSub.put(crd);
}
if(rs.getString("lat4")!=null && rs.getString("lon4")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon4"));
crd.put(rs.getDouble("lat4"));
crdSub.put(crd);
}
if(rs.getString("lat5")!=null && rs.getString("lon5")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon5"));
crd.put(rs.getDouble("lat5"));
crdSub.put(crd);
}
if(rs.getString("lat6")!=null && rs.getString("lon6")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon6"));
crd.put(rs.getDouble("lat6"));
crdSub.put(crd);
}
geom.put("coordinates", crdMain);
}
obj.put("geom", geom);
//Экологическая информация
obj.put("biotope_type", rs.getString("biotope_type"));
obj.put("vegetation", rs.getString("vegetation"));
obj.put("vegetation_cover", rs.getString("vegetation_cover"));
obj.put("air_temperature", rs.getString("air_temperature"));
obj.put("wind_speed", rs.getString("wind_speed"));
//Информация о саранче в том числе кубышки
obj.put("subject_name", rs.getString("subject_name")); //Вид саранчи
obj.put("infested_area", rs.getDouble("infested_area"));//Зараженная область га
// Eggs
obj.put("eggs_bed_area", rs.getDouble("egg_bed_area")); // numeric, --Залежь кубышек
obj.put("eggs_pods_density_from_m2", rs.getDouble("egg_pods_density_from_m2")); // numeric, --Плотность кубышек м2 с
obj.put("eggs_pods_density_to_m2", rs.getDouble("egg_pods_density_to_m2")); // numeric, --Плотность кубышек м2 до
obj.put("eggs_average_number_egg_pod", rs.getDouble("eggs_average_number_egg_pod")); // numeric, --Яйца в среднем в кубышке
obj.put("eggs_viable", rs.getDouble("eggs_viable")); // numeric, --Яйца (% жизнеспособных)
obj.put("eggs_natural_enemies", rs.getString("eggs_natural_enemies")); // character varying, --Естественные враги
// Hoppers (scattered) Личинки (разряженные)
obj.put("hoppers_hatching", rs.getString("hoppers_hatching")); // character varying, --Отрождение
obj.put("hoppers_stages", rs.getString("hoppers_stages")); // character varying, --Возраст личинок
obj.put("hoppers_appearance", rs.getString("hoppers_appearance")); // character varying, --Фаза
obj.put("hoppers_spatial_distribution", rs.getString("hoppers_spatial_distribution")); // character varying, --Пространственное распределени е
obj.put("hoppers_density_from_m2", rs.getDouble("hoppers_density_from_m2")); // numeric, --Плотность личинок от м2
obj.put("hoppers_density_to_m2", rs.getDouble("hoppers_density_to_m2")); // numeric, --Плотность личинок до м2
// Bands Кулиги
obj.put("bands_density_from_m2", rs.getDouble("bands_density_from_m2")); // numeric, --Плотность минимальная в кулиге м2
obj.put("bands_density_to_m2", rs.getDouble("bands_density_to_m2")); // numeric, --Плотность максимальная в кулиге м2
obj.put("bands_sizes_m2", rs.getDouble("bands_sizes_m2")); // numeric, --Размер кулиг М2
obj.put("bands_number_in_ha", rs.getDouble("bands_number_in_ha")); // numeric, --Количество кулиг Га
obj.put("bands_behavior", rs.getString("bands_behavior")); // character varying, -- Поведение
obj.put("bands_stages", rs.getString("bands_stages")); // character varying, -- Возраст личинок
// Adults Имаго
obj.put("adults_fledging", rs.getString("adults_fledging")); // character varying, -- Окрыление
obj.put("adults_maturity", rs.getBoolean("adults_maturity")); // boolean, -- Половозрелость
obj.put("adults_phase", rs.getString("adults_phase")); // character varying, --Фаза
obj.put("adults_spatial_distribution", rs.getString("adults_spatial_distribution")); // character varying, --Пространственное распределение
obj.put("adults_density_ha", rs.getDouble("adults_density_ha")); // numeric, --Плотность имаго га
obj.put("adults_density_m2", rs.getDouble("adults_density_m2")); // numeric, --Плотность имаго м2
obj.put("adults_roosting", rs.getBoolean("adults_roosting")); // boolean, --Питпние и размещение на растениях
obj.put("adults_copulation", rs.getBoolean("adults_copulation")); // boolean, --Спаривание
obj.put("adults_laying", rs.getBoolean("adults_laying")); // boolean, --Яйцекладка
obj.put("adults_flying", rs.getBoolean("adults_flying")); // boolean, --Полёты
// Swarms Стаи
obj.put("swarms_maturity", rs.getBoolean("swarms_maturity")); // boolean, --Половозрелость
obj.put("swarms_density", rs.getString("swarms_density")); // character varying, --Плотность в стае
obj.put("swarms_size", rs.getDouble("swarms_size")); // numeric, --Размер стаи га
obj.put("swarms_count", rs.getDouble("swarms_count")); // numeric, --Число стай
obj.put("swarms_flying_direction", rs.getString("swarms_flying_direction")); // character varying, --Направление полёта
obj.put("swarms_height", rs.getString("swarms_height")); // character varying, --Высота полёта
// Comment
obj.put("description", rs.getString("description"));
//{"type":"Polygon","coordinates":[[[38.513140949068344,46.51316246698309],[38.51303118002319,46.5020304054714],[38.52109926473999,46.50204517540462],[38.521123203096664,46.513073865446586],[38.513140949068344,46.51316246698309]]]}
array.put(obj);
}
rs.close();
} catch (SQLException ex) {
errorCode=4;
errorCodeDescription+="Внутренняя ошибка сервера, выборка. ";
ex.printStackTrace();
logger.info(ex.getMessage());
}
}
} catch (SQLException ex) {
errorCode=5;
errorCodeDescription+="Внутренняя ошибка сервера, запрос. ";
ex.printStackTrace();
logger.info(ex.getMessage());
}finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.close();}catch(SQLException ex){}
}
if(errorCode!=0) {
JSONObject obj = new JSONObject();
obj.put("errorCode",errorCode);
obj.put("errorCodeDescription", errorCodeDescription);
return obj.toString();
}else {
return array.toString();
}
}
//Prepare data for sending to integration servers.
String getDataDel(String token, String timeBegin,String timeEnd,String dateBegin,String dateEnd) {
int errorCode=0;
String errorCodeDescription="";
if(!(
token.equals("DA46DCA8E49D52A12614D4FE4CF4") // RUS
|| token.equals("R5375VJERFJKFTGKT8235QFSJHDE") // HIH FAO
|| token.equals("QIWGHIEEEEEE732RUEWHDHREU92Z") //???
|| token.equals("BA46DCA8E49D52A12614D4FE4CF5") //Kzahstan
|| token.equals("Z1263ERF2H3E4JU6241L5D6Q7NGT") //Uzbekistan
)) { //Access only for Russians
JSONObject obj = new JSONObject();
obj.put("errorCode",1);
obj.put("errorCodeDescription", "Token is not correct!");
return obj.toString();
}
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
} catch (Exception ex) {
errorCode=3;
errorCodeDescription+="Внутренняя ошибка сервера, база. ";
ex.printStackTrace();
}
JSONArray array=new JSONArray(); //Результирующий набор данных
String sql_query = "";
Statement stt=null;
ResultSet rs=null;
try {
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
sql_query = "select * from main.integration_2(1,?::bigint,?::bigint,TO_TIMESTAMP(?,'YYYY-MM-DD HH24:MI')::timestamp,TO_TIMESTAMP(?,'YYYY-MM-DD HH24:MI')::timestamp);";
//String timeBegin,String timeEnd,String dateBegin,String dateEnd
PreparedStatement stmt=null;
stmt = conn.prepareStatement(sql_query);
stmt.setString(1,timeBegin);
stmt.setString(2,timeEnd);
stmt.setString(3,dateBegin);
stmt.setString(4,dateEnd);
//stmt.execute();
rs = stmt.executeQuery();
//rs = stt.executeQuery(sql_query);
if (rs != null) {
try {
while(rs.next()) {
JSONObject obj = new JSONObject();
obj.put("id", rs.getLong("id"));
obj.put("seq", rs.getLong("seq"));
obj.put("country_name", rs.getString("country_name")); //Страна
obj.put("region_name", rs.getString("region_name")); //Область
obj.put("town_name", rs.getString("town_name")); //Район
obj.put("date", rs.getString("date")); //Дата анкетирования
//obj.put("surveyed_area", rs.getDouble("surveyed_area")); //Обследованная площадь га
int cnt1=0;
//lat_center
if(rs.getString("lat1")!=null && rs.getString("lon1")!=null) cnt1++;
if(rs.getString("lat2")!=null && rs.getString("lon2")!=null) cnt1++;
if(rs.getString("lat3")!=null && rs.getString("lon3")!=null) cnt1++;
if(rs.getString("lat4")!=null && rs.getString("lon4")!=null) cnt1++;
if(rs.getString("lat5")!=null && rs.getString("lon5")!=null) cnt1++;
if(rs.getString("lat6")!=null && rs.getString("lon6")!=null) cnt1++;
boolean point=cnt1<=2;
JSONObject geom = new JSONObject();
if(point) {
geom.put("type","Point");
JSONArray crdSub=new JSONArray();
crdSub.put(rs.getDouble("lon_center"));
crdSub.put(rs.getDouble("lat_center"));
geom.put("coordinates", crdSub);
}else {
geom.put("type","Polygon");
JSONArray crdMain=new JSONArray();
JSONArray crdSub=new JSONArray();
crdMain.put(crdSub);
if(rs.getString("lat1")!=null && rs.getString("lon1")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon1"));
crd.put(rs.getDouble("lat1"));
crdSub.put(crd);
}
if(rs.getString("lat2")!=null && rs.getString("lon2")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon2"));
crd.put(rs.getDouble("lat2"));
crdSub.put(crd);
}
if(rs.getString("lat3")!=null && rs.getString("lon3")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon3"));
crd.put(rs.getDouble("lat3"));
crdSub.put(crd);
}
if(rs.getString("lat4")!=null && rs.getString("lon4")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon4"));
crd.put(rs.getDouble("lat4"));
crdSub.put(crd);
}
if(rs.getString("lat5")!=null && rs.getString("lon5")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon5"));
crd.put(rs.getDouble("lat5"));
crdSub.put(crd);
}
if(rs.getString("lat6")!=null && rs.getString("lon6")!=null) {
JSONArray crd=new JSONArray();
crd.put(rs.getDouble("lon6"));
crd.put(rs.getDouble("lat6"));
crdSub.put(crd);
}
geom.put("coordinates", crdMain);
}
obj.put("geom", geom);
obj.put("infested_area", rs.getDouble("infested_area")); //double precision,
obj.put("treated_area", rs.getDouble("treated_area")); //numeric,
obj.put("district", rs.getString("district")); //character varying,
obj.put("village", rs.getString("village")); //character varying,
obj.put("terrain", rs.getString("terrain")); //character varying,
obj.put("observer", rs.getString("observer")); //character varying,
obj.put("vegetation_type_name", rs.getString("vegetation_type_name")); //character varying,
obj.put("vegetation_height", rs.getDouble("vegetation_height")); //real,
obj.put("vegetation_cover_name", rs.getString("vegetation_cover_name")); //character varying,
obj.put("vegetation_crop", rs.getString("vegetation_crop")); //character varying,
obj.put("vegetation_damage_name", rs.getString("vegetation_damage_name")); //character varying,
obj.put("vegetation_damage_area", rs.getDouble("vegetation_damage_area")); //double precision,
obj.put("insecticide_name", rs.getString("insecticide_name")); //character varying,
obj.put("insecticide_active_substance", rs.getString("insecticide_active_substance")); //character varying,
obj.put("insecticide_concentration", rs.getString("insecticide_concentration")); //character varying,
obj.put("insecticide_formulation_name", rs.getString("insecticide_formulation_name")); //character varying,
obj.put("insecticide_dose", rs.getDouble("insecticide_dose")); //numeric,
obj.put("insecticide_rate", rs.getDouble("insecticide_rate")); //numeric,
obj.put("insecticide_used_volume", rs.getDouble("insecticide_used_volume")); //numeric,
obj.put("insecticide_number_spores", rs.getDouble("insecticide_number_spores")); //numeric,
obj.put("weather_time_start", rs.getDouble("weather_time_start")); //real,
obj.put("weather_time_end", rs.getDouble("weather_time_end")); //real,
obj.put("weather_temperature_start", rs.getDouble("weather_temperature_start")); //real,
obj.put("weather_temperature_end", rs.getDouble("weather_temperature_end")); //real,
obj.put("weather_humidity_start", rs.getDouble("weather_humidity_start")); //real,
obj.put("weather_humidity_end", rs.getDouble("weather_humidity_end")); //real,
obj.put("weather_wind_speed_start", rs.getDouble("weather_wind_speed_start")); //real,
obj.put("weather_wind_speed_end", rs.getDouble("weather_wind_speed_end")); //real,
obj.put("weather_direction_start", rs.getString("weather_direction_start")); //character varying,
obj.put("weather_direction_end", rs.getString("weather_direction_end")); //character varying,
obj.put("weather_spray_direction_start", rs.getString("weather_spray_direction_start")); //character varying,
obj.put("weather_spray_direction_end", rs.getString("weather_spray_direction_end")); //character varying,
obj.put("subject_name", rs.getString("subject_name")); //character varying,
obj.put("locust_hoppers_name", rs.getString("locust_hoppers_name")); //character varying,
obj.put("locust_imago", rs.getBoolean("locust_imago")); //boolean,
obj.put("locust_density", rs.getDouble("locust_density")); //real,
obj.put("locust_kuliguli", rs.getBoolean("locust_kuliguli")); //boolean,
obj.put("locust_swarm", rs.getBoolean("locust_swarm")); //boolean,
obj.put("locust_sparse", rs.getBoolean("locust_sparse")); //boolean,
obj.put("locust_phase_name", rs.getString("locust_phase_name")); //character varying,
obj.put("spray_platform_name", rs.getString("spray_platform_name")); //character varying,
obj.put("spray_platform_a_name", rs.getString("spray_platform_a_name")); //character varying,
obj.put("spray_platform_g_name", rs.getString("spray_platform_g_name")); //character varying,
obj.put("spray_platform_h_name", rs.getString("spray_platform_h_name")); //character varying,
obj.put("spray_capacity_name", rs.getString("spray_capacity_name")); //character varying,
obj.put("spray_manufacturer_name", rs.getString("spray_manufacturer_name")); //character varying,
obj.put("spray_model_name", rs.getString("spray_model_name")); //character varying,
obj.put("spray_height", rs.getDouble("spray_height")); //numeric,
obj.put("spray_barrier", rs.getBoolean("spray_barrier")); //boolean,
obj.put("spray_barrier_width", rs.getDouble("spray_barrier_width")); //real,
obj.put("spray_barrier_space", rs.getDouble("spray_barrier_space")); //real,
obj.put("spray_speed", rs.getDouble("spray_speed")); //numeric,
obj.put("spray_gps", rs.getBoolean("spray_gps")); //boolean,
obj.put("spray_marking_name", rs.getString("spray_marking_name")); //character varying,
obj.put("efficacy_mortality", rs.getDouble("efficacy_mortality")); //real,
obj.put("efficacy_passed_time", rs.getDouble("efficacy_passed_time")); //numeric,
obj.put("efficacy_mortality_method_name", rs.getString("efficacy_mortality_method_name")); //character varying,
obj.put("safety_clothing", rs.getString("safety_clothing")); //text,
obj.put("safety_clothing_clean", rs.getBoolean("safety_clothing_clean")); //boolean,
obj.put("safety_operator_health", rs.getBoolean("safety_operator_health")); //boolean,
obj.put("description", rs.getString("description")); //character varying,
obj.put("safety_inform", rs.getString("safety_inform")); //text,
obj.put("safety_container_name", rs.getString("safety_container_name")); //text,
obj.put("safety_non_target", rs.getBoolean("safety_non_target")); //boolean,
obj.put("safety_non_target_effect", rs.getString("safety_non_target_effect")); //character varying,
obj.put("safety_incident", rs.getBoolean("safety_incident")); //boolean,
obj.put("safety_incident_effect", rs.getString("safety_incident_effect")); //character varying,
obj.put("comments", rs.getString("comments")); //character varying
array.put(obj);
}
rs.close();
} catch (SQLException ex) {
errorCode=4;
errorCodeDescription+="Внутренняя ошибка сервера, выборка. ";
ex.printStackTrace();
logger.info(ex.getMessage());
}
}
} catch (SQLException ex) {
errorCode=5;
errorCodeDescription+="Внутренняя ошибка сервера, запрос. ";
ex.printStackTrace();
logger.info(ex.getMessage());
}finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.close();}catch(SQLException ex){}
}
if(errorCode!=0) {
JSONObject obj = new JSONObject();
obj.put("errorCode",errorCode);
obj.put("errorCodeDescription", errorCodeDescription);
return obj.toString();
}else {
return array.toString();
}
}
@RequestMapping(value = "/integration/getPhoto", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody
public Object getPhoto(@RequestParam(required=true,name="token") String token,@RequestParam(required=true,name="id") Long id)
{
int errorCode=0;
String errorCodeDescription="";
if(!(
token.equals("DA46DCA8E49D52A12614D4FE4CF4") // RUS
|| token.equals("R5375VJERFJKFTGKT8235QFSJHDE") // HIH FAO
|| token.equals("QIWGHIEEEEEE732RUEWHDHREU92Z") //???
|| token.equals("BA46DCA8E49D52A12614D4FE4CF5") //Казахстан
|| token.equals("Z1263ERF2H3E4JU6241L5D6Q7NGT") //Uzbekistan
)) {
JSONObject obj = new JSONObject();
obj.put("errorCode",1);
obj.put("errorCodeDescription", "Token is not correct!");
return obj.toString();
}
String db_url="";
String db_login="";
String db_password="";
String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
} catch (Exception ex) {
errorCode=3;
errorCodeDescription+="Внутренняя ошибка сервера, база. ";
ex.printStackTrace();
}
JSONArray array=new JSONArray(); //Результирующий набор данных
String image_name1=null,image_name2=null,image_name3=null;
String sql_query = "";
Statement stt=null;
ResultSet rs=null;
try {
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
sql_query = "select id,image_name1,image_name2,image_name3 from main.frmlocust where id="+String.valueOf(id);
rs = stt.executeQuery(sql_query);
if (rs != null) {
try {
while(rs.next()) {
image_name1=rs.getString("image_name1");
image_name2=rs.getString("image_name2");
image_name3=rs.getString("image_name3");
}
rs.close();
} catch (SQLException ex) {
errorCode=3;
errorCodeDescription+="Внутренняя ошибка сервера (поля). ";
ex.printStackTrace();
}
}
} catch (SQLException ex) {
errorCode=3;
errorCodeDescription+="Внутренняя ошибка сервера, запрос. ";
ex.printStackTrace();
}finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.close();}catch(SQLException ex){}
}
if(image_name1!=null) {
String data = getBase64FromFile(data_dir+"data/frmlocust/"+image_name1);
if(data!=null) { //Удалось найти файл локально
JSONObject obj = new JSONObject();
obj.put("name", image_name1);
obj.put("data", data);
array.put(obj);
}else { //Пытаемся найти на другом сервера
data=getBase64FromURL("http://data.ccalm.org/photo/?table=frmlocust&file="+image_name1);
if(data!=null) { //Если скачали с удаленного сервера
JSONObject obj = new JSONObject();
obj.put("name", image_name1);
obj.put("data", data);
array.put(obj);
}
}
}
if(image_name2!=null) {
String data = getBase64FromFile(data_dir+"data/frmlocust/"+image_name2);
if(data!=null) { //Удалось найти файл локально
JSONObject obj = new JSONObject();
obj.put("name", image_name1);
obj.put("data", data);
array.put(obj);
}else { //Пытаемся найти на другом сервера
data=getBase64FromURL("http://data.ccalm.org/photo/?table=frmlocust&file="+image_name2);
if(data!=null) { //Если скачали с удаленного сервера
JSONObject obj = new JSONObject();
obj.put("name", image_name1);
obj.put("data", data);
array.put(obj);
}
}
}
if(image_name3!=null) {
String data = getBase64FromFile(data_dir+"data/frmlocust/"+image_name3);
if(data!=null) { //Удалось найти файл локально
JSONObject obj = new JSONObject();
obj.put("name", image_name1);
obj.put("data", data);
array.put(obj);
}else { //Пытаемся найти на другом сервера
data=getBase64FromURL("http://data.ccalm.org/photo/?table=frmlocust&file="+image_name3);
if(data!=null) { //Если скачали с удаленного сервера
JSONObject obj = new JSONObject();
obj.put("name", image_name1);
obj.put("data", data);
array.put(obj);
}
}
}
if(errorCode!=0) {
JSONObject obj = new JSONObject();
obj.put("errorCode",errorCode);
obj.put("errorCodeDescription", errorCodeDescription);
return obj.toString();
}else {
return array.toString();
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
public String getBase64FromFile(String fName) {
String result=null;
File file = new File(fName);
if(file.exists()) {
try {
byte fileData[] = new byte[(int) file.length()];
try (FileInputStream imageInFile = new FileInputStream(file)) {
imageInFile.read(fileData);
}
result=Base64.getEncoder().encodeToString(fileData);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
return result;
}
public String getBase64FromURL(String strURL) {
String result=null;
try
{
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode / 100 == 2) //Code 206 is "Partial Content"
{
InputStream inputStream = conn.getInputStream();
int bytesRead;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
if(result==null) result="";
byte[] encoded = Base64.getEncoder().encode(Tools.subArray(buffer, 0, bytesRead));
result+=new String(encoded);
}
inputStream.close();
}
conn.disconnect();
}
catch (IOException e)
{
}
return result;
}
}

View File

@ -0,0 +1,14 @@
package org.ccalm.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication(scanBasePackages = {"org.ccalm.main", "dbms"})
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}

View File

@ -0,0 +1,326 @@
package org.ccalm.main;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.CacheControl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import tools.User;
/**
* Handles requests for the application home page.
*/
@Controller
//@SessionAttributes( { "user" })
public class MainController implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(MainController.class);
private ServletContext context;
private Properties m_props=null;
@Override
public void setServletContext(ServletContext context){
this.context=context;
}
//If not created object "user", create him.
//@ModelAttribute("user")
//public User populatePerson() {
// return new User("none");
//}
/**
* Simply selects the home view to render by returning its name.
*/
/*@RequestMapping(value = "/test", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
//Date date = new Date();
//DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
//String formattedDate = dateFormat.format(date);
//model.addAttribute("serverTime", formattedDate );
return "index";
}*/
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/privacy", method = RequestMethod.GET)
public String privacy(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
//Date date = new Date();
//DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
//String formattedDate = dateFormat.format(date);
//model.addAttribute("serverTime", formattedDate );*/
return "privacy";
}
@RequestMapping(value = "/robots.txt")
public void robots(HttpServletResponse response) {
try {
response.getWriter().write("User-agent: *\n");
response.getWriter().write("Disallow: /engine/\n");
response.getWriter().write("Disallow: /resources/\n");
response.getWriter().write("Disallow: /test\n");
response.getWriter().write("Sitemap: https://ccalm.org/sitemap.xml\n");
response.getWriter().write("Host: https://ccalm.org\n");
} catch (IOException e) {
logger.info(e.getMessage());
}
}
@RequestMapping(value = "/sitemap.xml")
public void sitemap(HttpServletResponse response) {
try {
response.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"
+ " <url>\n"
+ " <loc>https://ccalm.org</loc>\n"
+ " </url>\n"
+ "</urlset>\n");
} catch (IOException e) {
logger.info(e.getMessage());
}
}
/**
* Testing new main index page
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home2(@ModelAttribute User user, Model model,@CookieValue(value = "lng", defaultValue = "1") String language_id) {
//logger.info("Welcome home! The client locale is {}.", locale);
if(language_id!=null && !language_id.equals("")) user.language_id=language_id;
logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id);
String db_url="";
String db_login="";
String db_password="";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
//Get language from database
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
System.out.println("Connect is OK!");
}else
{
System.out.println("<br>Connect is ERROR<br>");
}
}catch(Exception e)
{
System.out.println("<br>Connect Exception:"+e.getMessage()+"<br>");
}
try {
Statement st = conn.createStatement();
ResultSet rs=null;
if(user.id!=null){
if(language_id!=null && !language_id.equals(""))
{
//Set the language for the current user if it is transferred.
user.language_id=language_id;
try {
st.execute("update main._users set language_id='"+user.language_id+"' where id="+user.id);
} catch( SQLException ex )
{
System.out.println("<br>SQLException:"+ex.getMessage()+"<br>");
}
}
//Select language for current user
try {
String sql="select language_id,country_id from main._users u where u.id="+String.valueOf(user.id)+";";
rs = st.executeQuery(sql);
} catch( SQLException ex )
{
System.out.println("<br>SQLException:"+ex.getMessage()+"<br>");
}
if(rs!=null)
{
while (rs.next())
{
user.language_id = rs.getString("language_id");
user.country_id = rs.getString("country_id");
}
}
}
st.close();
} catch( SQLException ex )
{
System.out.println("<br>SQLException:"+ex.getMessage()+"<br>");
}
//Send user name and role
model.addAttribute("uName",user.name+" ("+user.role+")");
model.addAttribute("m_locale",user.language_id);
model.addAttribute("country_id",user.country_id);
//Для перевода выбираю всё что под номером 1 в переводе
try {
m_props = new Properties();
Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sql_query = "select identifier,case when '"+user.language_id+"'='666' then translation||'''\"' else translation end as translation from main._translations t where t.del=false and (t.language_id='"+user.language_id+"' or ('"+user.language_id+"'='666' and t.language_id=1)) and translation_type_id=1;";
ResultSet rs = stt.executeQuery(sql_query);
if (rs != null) {
while (rs.next())
{
String identifier = rs.getString("identifier");
String translation = rs.getString("translation");
m_props.setProperty(identifier, translation);
}
rs.close();
}
stt.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
Set<Object> keys = m_props.keySet();
for(Object k:keys){
String key = (String)k;
String val="";
if(val.equals(""))
{
val = m_props.getProperty(key,"");
if(val.equals(""))
{
val = val.replaceAll("_", " ");
}
}
model.addAttribute(key,val);
}
try{ conn.close(); }catch(Exception e){}
//return "index";
return "test";
}
//Returns data for building a map on the first index page
@RequestMapping(value = "/dataindex",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=utf-8")
@ResponseBody
public Object ajaxIndexData(HttpServletResponse response,@ModelAttribute User user,@RequestParam(required=false,name="date_start",defaultValue = "null") String date_start,@RequestParam(required=false,name="date_end",defaultValue = "null") String date_end, @RequestParam(required=false,name="lng") String language_id) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
JSONObject result = new JSONObject();
JSONArray array=new JSONArray();
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
//Connect to database
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
System.out.println("Connect is OK!");
}else
{
System.out.println("<br>Connect is ERROR<br>");
}
}catch(Exception e)
{
System.out.println("<br>Connect Exception:"+e.getMessage()+"<br>");
}
String sql;
sql = "select * from main.p_dataindex(to_timestamp("+date_start+")::timestamp without time zone,to_timestamp("+date_end+")::timestamp without time zone);";
ResultSet rs = null;
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
ex.printStackTrace();
}
try {
while (rs.next()) {
JSONObject rsRez = new JSONObject();
rsRez.put("id",rs.getInt("id"));
rsRez.put("lon",rs.getDouble("lon"));
rsRez.put("lat",rs.getDouble("lat"));
rsRez.put("type",rs.getInt("type"));
rsRez.put("terrain",rs.getString("terrain"));
array.put(rsRez);
}
} catch (SQLException ex) {
logger.info(ex.getMessage());
ex.printStackTrace();
}
result.put("Error_code", "0");
result.put("Error_message", "");
result.put("data", array);
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
}
}
return result.toString();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,491 @@
package org.ccalm.main;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import tctable.Tools;
import tools.User;
@Controller
//@SessionAttributes( { "user" })
public class QGIS implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(QGIS.class);
private ServletContext context;
private Properties m_props=null;
private String m_props_loc="";
public String m_locale="ru";
//If not created object "user", create him.
//@ModelAttribute("user")
//public User populatePerson() {
// return new User("none");
//}
@RequestMapping(value = "/QGIS",method = RequestMethod.GET,produces = "application/octet-stream")
@ResponseBody
public HttpEntity<byte[]> ajaxTamer(@ModelAttribute User user, @RequestParam(required=false,name="day") String day, @RequestParam(required=false,name="name") String name, @RequestParam(required=false,name="time") String time, @RequestParam(required=false,name="time_start") String time_start, @RequestParam(required=false,name="time_end") String time_end, @RequestParam(required=false,name="country_id") String country_id, @RequestParam(required=false,name="locust_type_id") String locust_type_id, @RequestParam(required=false,name="date_start") String date_start, @RequestParam(required=false,name="date_end") String date_end, @RequestParam(required=false,name="registered") String registered, @RequestParam(required=false,name="year") String year, @RequestParam(required=false,name="region_id") String region_id, @RequestParam(required=false,name="country_name") String country_name, @RequestParam(required=false,name="lng") String language_id, HttpServletResponse response)
{
if(language_id!=null && !language_id.equals("")) user.language_id=language_id;
logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id);
m_locale=user.language_id;
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
}
} catch (Exception ex) {
logger.info(ex.getMessage());
}
//Return content QGIS file.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="+name+".qgs");
String fileAsString="";
//Pods (кубышки)
if(name!=null && (name.equals("frmlocust_pods_density") || name.equals("frmlocust_hoppers_density") || name.equals("frmlocust_bands") || name.equals("frmlocust_adults_density") || name.equals("frmlocust_swarms")))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//String country_id=request.getParameter("country_id");
//String locust_type_id=request.getParameter("locust_type_id");
//String date_start=request.getParameter("date_start");
//String date_end=request.getParameter("date_end");
//String registered=request.getParameter("registered");
//Make SQL
String sql = "1=1";
String sql2 = "1=1";
if(country_id!=null && !country_id.equals(""))
{
if(country_id.equals("-1"))
{
sql+=" and country_id in (7,3,4,2)";
sql2+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql+=" and country_id in (7,1,5,6,8,9,10)";
sql2+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql+=" and country_id="+country_id;
sql2+=" and country_id="+country_id;
}
}
if(locust_type_id!=null && !locust_type_id.equals(""))
{
sql+=" and locust_type_id="+locust_type_id;
}
if(date_start!=null && !date_start.equals(""))
{
sql+=" and date>='"+date_start+"'";
}
if(date_end!=null && !date_end.equals(""))
{
sql+=" and date&lt;='"+date_end+"'";
}
if(registered!=null && registered.equals("1"))
{
sql+=" and registered=true";
}else
if(registered!=null && registered.equals("0"))
{
sql+=" and registered=false";
}
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{sql\\}",sql);
fileAsString=fileAsString.replaceAll("\\$\\{sql2\\}",sql2);
}
if(name!=null && name.equals("frmlocustdel"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//String country_id=request.getParameter("country_id");
//String date_start=request.getParameter("date_start");
//String date_end=request.getParameter("date_end");
//String registered=request.getParameter("registered");
//Make SQL
String sql = "1=1";
String sql2 = "1=1";
if(country_id!=null && !country_id.equals(""))
{
//sql+=" and country_id="+country_id;
if(country_id.equals("-1"))
{
sql+=" and country_id in (7,3,4,2)";
sql2+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql+=" and country_id in (7,1,5,6,8,9,10)";
sql2+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql+=" and country_id="+country_id;
sql2+=" and country_id="+country_id;
}
}
if(date_start!=null && !date_start.equals(""))
{
sql+=" and date>='"+date_start+"'";
}
if(date_end!=null && !date_end.equals(""))
{
sql+=" and date&lt;='"+date_end+"'";
}
if(registered!=null && registered.equals("1"))
{
sql+=" and registered=true";
}else
if(registered!=null && registered.equals("0"))
{
sql+=" and registered=false";
}
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{sql\\}",sql);
fileAsString=fileAsString.replaceAll("\\$\\{sql2\\}",sql2);
}
if(name!=null && (name.equals("frmlocustinfo_p2") || name.equals("frmlocustinfo_p3") || name.equals("frmlocustinfo_p4")))
{
//String country_id=request.getParameter("country_id");
//String year=request.getParameter("year");
//String locust_type_id=request.getParameter("locust_type_id");
//Make SQL
String sql = "1=1";
if(country_id!=null && !country_id.equals(""))
{
if(country_id.equals("-1"))
{
sql+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql+=" and country_id="+country_id;
}
}
if(locust_type_id!=null && !locust_type_id.equals(""))
{
sql+=" and locust_type_id="+locust_type_id;
}
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{year\\}",year);
fileAsString=fileAsString.replaceAll("\\$\\{sql\\}",sql);
}
if(name!=null && (name.equals("frmlocustinfo_p2r") || name.equals("frmlocustinfo_p3r") || name.equals("frmlocustinfo_p4r")))
{
//String region_id=request.getParameter("region_id");
//String year=request.getParameter("year");
//String locust_type_id=request.getParameter("locust_type_id");
//Make SQL
String sql = "1=1";
if(region_id!=null && !region_id.equals(""))
{
sql+=" and region_id="+region_id;
}
if(locust_type_id!=null && !locust_type_id.equals(""))
{
sql+=" and locust_type_id="+locust_type_id;
}
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{year\\}",year);
fileAsString=fileAsString.replaceAll("\\$\\{sql\\}",sql);
}
if(name!=null && name.equals("soil_temperature"))
{
//Make SQL
String sql2 = "1=1";
if(country_id!=null && !country_id.equals(""))
{
if(country_id.equals("-1"))
{
sql2+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql2+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql2+=" and country_id="+country_id;
}
}
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{country\\}",country_name);
fileAsString=fileAsString.replaceAll("\\$\\{sql2\\}",sql2);
fileAsString=fileAsString.replaceAll("\\$\\{time\\}",time);
}
if(name!=null && name.equals("air_temperature"))
{
//Make SQL
String sql2 = "1=1";
if(country_id!=null && !country_id.equals(""))
{
if(country_id.equals("-1"))
{
sql2+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql2+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql2+=" and country_id="+country_id;
}
}
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{country\\}",country_name);
fileAsString=fileAsString.replaceAll("\\$\\{sql2\\}",sql2);
fileAsString=fileAsString.replaceAll("\\$\\{time\\}",time);
}
if(name!=null && name.equals("precipitation"))
{
//Make SQL
String sql2 = "1=1";
if(country_id!=null && !country_id.equals(""))
{
if(country_id.equals("-1"))
{
sql2+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql2+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql2+=" and country_id="+country_id;
}
}
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{country\\}",country_name);
fileAsString=fileAsString.replaceAll("\\$\\{sql2\\}",sql2);
fileAsString=fileAsString.replaceAll("\\$\\{time\\}",time);
}
if(name!=null && name.equals("htc_selyaninov"))
{
//Make SQL
String sql2 = "1=1";
if(country_id!=null && !country_id.equals(""))
{
if(country_id.equals("-1"))
{
sql2+=" and country_id in (7,3,4,2)";
}else if(country_id.equals("-2"))
{
sql2+=" and country_id in (7,1,5,6,8,9,10)";
}else
{
sql2+=" and country_id="+country_id;
}
}
fileAsString = fileToString(context.getRealPath("/resources/QGIS/" + name + ".qgs"));
//Apply variables to text
fileAsString=fileAsString.replaceAll("\\$\\{country\\}",country_name);
fileAsString=fileAsString.replaceAll("\\$\\{sql2\\}",sql2);
fileAsString=fileAsString.replaceAll("\\$\\{time_start\\}",time_start);
fileAsString=fileAsString.replaceAll("\\$\\{time_end\\}",time_end);
}
if(name!=null && name.equals("NDVI"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/NDVI.qgs"));
if(day!=null && day.length()>0)
fileAsString = fileAsString.replaceAll("\\$\\{day\\}",day+"_");
else
fileAsString = fileAsString.replaceAll("\\$\\{day\\}","");
}
if(name!=null && name.equals("NDWI"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/NDWI.qgs"));
if(day!=null && day.length()>0)
fileAsString = fileAsString.replaceAll("\\$\\{day\\}",day+"_");
else
fileAsString = fileAsString.replaceAll("\\$\\{day\\}","");
}
if(name!=null && name.equals("IVI"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/IVI.qgs"));
if(year!=null && year.length()>0)
fileAsString = fileAsString.replaceAll("\\$\\{year\\}",year+"_");
else
fileAsString = fileAsString.replaceAll("\\$\\{year\\}","");
}
if(name!=null && name.equals("NDWI_CMP"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/NDWI_CMP.qgs"));
if(day!=null && day.length()>0)
fileAsString = fileAsString.replaceAll("\\$\\{day\\}",day+"_");
else
fileAsString = fileAsString.replaceAll("\\$\\{day\\}","");
}
if(name!=null && name.equals("NDSI"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/NDSI.qgs"));
if(day!=null && day.length()>0)
fileAsString = fileAsString.replaceAll("\\$\\{day\\}",day+"_");
else
fileAsString = fileAsString.replaceAll("\\$\\{day\\}","");
}
if(name!=null && name.equals("SMAP"))
{
fileAsString = fileToString(context.getRealPath("/resources/QGIS/SMAP.qgs"));
if(day!=null && day.length()>0)
fileAsString = fileAsString.replaceAll("\\$\\{day\\}",day+"_");
else
fileAsString = fileAsString.replaceAll("\\$\\{day\\}","");
}
//Send data
fileAsString=getText(conn,fileAsString,user);
return new HttpEntity<byte[]>(fileAsString.getBytes(), headers);
}
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
public String fileToString(String fName)
{
StringBuilder sb = new StringBuilder();
try
{
InputStream is = new FileInputStream(fName);
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
while(line != null)
{
sb.append(line).append("\n");
line = buf.readLine();
}
buf.close();
}
catch (Exception e){
System.out.println("Error: "+e.getMessage());
}
return sb.toString();
}
public String trt(Connection conn,String key,User user)
{
String result="";
ResultSet rs=null;
Statement st = null;
try {
st = conn.createStatement();
String sql = "select case when '"+user.language_id+"'='666' then translation||'''\"' else translation end as translation from main._translations t where t.identifier='"+key+"' and (t.language_id='"+user.language_id+"' or ('"+user.language_id+"'='666' and t.language_id=1));";
rs = st.executeQuery(sql);
if(rs != null) {
if (rs.next()) {
result = rs.getString(1);
}
}
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}finally{
if(st!=null) try{st.close();}catch(SQLException ex) {}
if(rs!=null) try{rs.close();}catch(SQLException ex) {}
}
if(result.equals(""))
{
result = Tools.replaceAll(key,"_", " ");
}
return result;
}
//Translate text by patterns
public String getText(Connection conn,String text,User user) {
int pos1 = 0;
while (true) {
pos1 = text.indexOf("trt('", pos1);
if (pos1 == -1)
break;
int pos2 = text.indexOf("')", pos1);
if (pos2 == -1)
break;
text = text.substring(0, pos1) + trt(conn,text.substring(pos1 + 5, pos2),user) + text.substring(pos2 + 2);
}
return text;
}
}

View File

@ -0,0 +1,481 @@
package org.ccalm.main;
import java.io.FileInputStream;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import jakarta.servlet.ServletContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import tools.EmailUtility;
import tools.User;
//import javax.servlet.ServletContext;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.ServletContextAware;
@Controller
//@SessionAttributes( { "user" }) //Сесионный объект
public class SendMail implements ServletContextAware {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SendMail.class);
private ServletContext context;
private Connection m_conn = null;
private User m_user = null;
//private Properties m_props=null;
public String m_locale="en";
//private HashMap<String, Properties> m_props = new HashMap< String, Properties>();
//If not created object "user", create him.
//@ModelAttribute("user")
//public User populatePerson() {
// return new User("none");
//}
@RequestMapping(value = "/SendMail",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object send(@ModelAttribute User user,@RequestParam(required=false,name="lng") String language_id) {
m_user = user;
if(language_id!=null && !language_id.equals(""))
user.language_id=language_id;
logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id+" user.country_id="+user.country_id);
String result="";
//Load DB configuration from "config.xml"
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
String mail_host = "";
String mail_port = "";
String mail_login = "";
String mail_password = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
mail_host = prop.getProperty("mail.host");
mail_port = prop.getProperty("mail.port");
mail_login = prop.getProperty("mail.login");
mail_password = prop.getProperty("mail.password");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
//Connect to database
try{
Class.forName("org.postgresql.Driver");
m_conn = DriverManager.getConnection(db_url,db_login,db_password);
if(m_conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
/*String string = "2016-07-05";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(string);*/
//int Day_s,Day_e;
//int Month_s,Month_e;
//int Year_s,Year_e;
Calendar calendar_s = Calendar.getInstance();
//calendar_s.setTime(date);
calendar_s.set(Calendar.DATE, 1);
calendar_s.add(Calendar.MONTH, -1); //минус месяц
Calendar calendar_e = Calendar.getInstance();
//calendar_e.setTime(date);
calendar_e.set(Calendar.DATE, 1);
String start_t = String.valueOf(calendar_s.getTimeInMillis()/1000);
String end_t = String.valueOf(calendar_e.getTimeInMillis()/1000);
//Формирую сообщение для каждой страны потом присваиваю пользователям из данной страны
String sql1="select c.id,c.name,u.email,l.short_name as language from main.countries c join main._users u on u.country_id=c.id join main._languages l on l.id=u.language_id where u.del=false and u.mailing=true order by c.name;";
Statement st1;
ResultSet rs1=null;
try {
st1 = m_conn.createStatement();
rs1 = st1.executeQuery(sql1);
} catch (SQLException ex) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
if(rs1!=null)
{
try {
while (rs1.next()) //Пробегаюсь по странам и генерю сообщение
{
String html="<html><body>";
String country_id=rs1.getString("id");
String country_name=rs1.getString("name");
m_locale=rs1.getString("language");
String email = rs1.getString("email");
html="<h2>"+country_name+"</h2>";
result+=html+m_locale;
//Build HTML and send it to e-mail
String sql=""
+"select cr.name region_name,coalesce(t1.danger,0) danger,coalesce(t2.attention,0) attention,coalesce(t3.quietly,0) quietly from\n"
+" main.countriesregions cr\n"
+" left join (SELECT region_id,sum(1) as danger from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and COALESCE(fl.eggs_capsules_density, fl.eggs_capsules_density_to)::double precision + COALESCE(fl.eggs_capsules_density_to, fl.eggs_capsules_density)::double precision / 2::double precision > 1 group by region_id) t1 on cr.id=t1.region_id\n"
+" left join (SELECT region_id,sum(1) as attention from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and COALESCE(fl.eggs_capsules_density, fl.eggs_capsules_density_to)::double precision + COALESCE(fl.eggs_capsules_density_to, fl.eggs_capsules_density)::double precision / 2::double precision > 0 and COALESCE(fl.eggs_capsules_density, fl.eggs_capsules_density_to)::double precision + COALESCE(fl.eggs_capsules_density_to, fl.eggs_capsules_density)::double precision / 2::double precision <= 1 group by region_id) t2 on cr.id=t2.region_id\n"
+" left join (SELECT region_id,sum(1) as quietly from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and COALESCE(fl.eggs_capsules_density, fl.eggs_capsules_density_to)::double precision + COALESCE(fl.eggs_capsules_density_to, fl.eggs_capsules_density)::double precision / 2::double precision = 0 group by region_id) t3 on cr.id=t3.region_id\n"
+"where\n"
+" cr.del=false\n"
+" and (t1.danger is not null or t2.attention is not null or t3.quietly is not null)\n"
+" and cr.country_id="+country_id;
Statement st = m_conn.createStatement();
ResultSet rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
html+="<h3>"+trt("Egg_pods_density")+"</h3>";
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000));
html+="<br>"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000));
html+="<table border=\"1\" style=\"border-collapse: collapse;\">";
html+="<tr style=\"background-color:#dadada;\"><th>"+trt("Oblast")+"</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_r.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Danger")+"\"<br>("+trt("Egg_pods_density")+" > 1)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_y.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Attention")+"\"<br>("+trt("Egg_pods_density")+" <= 1)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_g.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Quietly")+"\"<br>("+trt("Egg_pods_density")+" = 0)</th></tr>";
boolean exists=false;
if(rs!=null)
{
while (rs.next())
{
html+="<tr>";
html+="<td>"+rs.getString("region_name")+"</td>";
html+="<td>"+rs.getString("danger")+"</td>";
html+="<td>"+rs.getString("attention")+"</td>";
html+="<td>"+rs.getString("quietly")+"</td>";
html+="</tr>";
exists=true;
}
}
st.close();
if(!exists) html+="<td colspan=\"4\" style=\"text-align:center;font-weight:bold;\">"+trt("No_data")+"</td>";
html+="</table>";
html+="<a target=\"_blank\" href=\"http://ccalm.org/engine/?&cmd=FrmLocust&country_id="+country_id+"&date_start="+sdf.format(new Date(Long.parseLong(start_t)*1000))+"&date_end="+sdf.format(new Date(Long.parseLong(end_t)*1000))+"&registered=1&indicator=1\">"+trt("Open_data_on_the_map")+"</a>";
html+="<br><br>";
//Adult_density
//плотности имаго
sql=""
+" select cr.name region_name,coalesce(t1.danger,0) danger,coalesce(t2.attention,0) attention,coalesce(t3.quietly,0) quietly from\n"
+" main.countriesregions cr\n"
+" left join (SELECT region_id,sum(1) as danger from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and imago_density >= 5 group by region_id) t1 on cr.id=t1.region_id\n"
+" left join (SELECT region_id,sum(1) as attention from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and imago_density >= 3 and imago_density < 5 group by region_id) t2 on cr.id=t2.region_id\n"
+" left join (SELECT region_id,sum(1) as quietly from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and imago_density <= 2 group by region_id) t3 on cr.id=t3.region_id\n"
+"where\n"
+" cr.del=false\n"
+" and (t1.danger is not null or t2.attention is not null or t3.quietly is not null)\n"
+" and cr.country_id="+country_id;
st = m_conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
html+="<h3>"+trt("Adult_density")+"</h3>";
html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000));
html+="<br>"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000));
html+="<table border=\"1\" style=\"border-collapse: collapse;\">";
html+="<tr style=\"background-color:#dadada;\"><th>"+trt("Oblast")+"</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_r.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Dangerous")+"\"<br>("+trt("Adult_density")+" >=5)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_y.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Attention")+"\"<br>("+trt("Adult_density")+" >=3 "+trt("and")+" <5)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_g.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Quietly")+"\"<br>("+trt("Adult_density")+" <=2)</th></tr>";
exists=false;
if(rs!=null)
{
while (rs.next())
{
html+="<tr>";
html+="<td>"+rs.getString("region_name")+"</td>";
html+="<td>"+rs.getString("danger")+"</td>";
html+="<td>"+rs.getString("attention")+"</td>";
html+="<td>"+rs.getString("quietly")+"</td>";
html+="</tr>";
exists=true;
}
}
st.close();
if(!exists) html+="<td colspan=\"5\" style=\"text-align:center;font-weight:bold;\">"+trt("No_data")+"</td>";
html+="</table>";
html+="<a target=\"_blank\" href=\"http://ccalm.org/engine/?&cmd=FrmLocust&country_id="+country_id+"&date_start="+sdf.format(new Date(Long.parseLong(start_t)*1000))+"&date_end="+sdf.format(new Date(Long.parseLong(end_t)*1000))+"&registered=1&indicator=4\">"+trt("Open_data_on_the_map")+"</a>";
html+="<br><br>";
//Hopper_density
sql=""
+" select cr.name region_name,coalesce(t1.danger,0) danger,coalesce(t2.attention,0) attention,coalesce(t3.quietly,0) quietly from\n"
+" main.countriesregions cr\n"
+" left join (SELECT region_id,sum(1) as danger from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and COALESCE(fl.larva_density, fl.larva_density_to)::double precision + COALESCE(fl.larva_density_to, fl.larva_density)::double precision / 2::double precision >= 5 group by region_id) t1 on cr.id=t1.region_id\n"
+" left join (SELECT region_id,sum(1) as attention from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and COALESCE(fl.larva_density, fl.larva_density_to)::double precision + COALESCE(fl.larva_density_to, fl.larva_density)::double precision / 2::double precision >= 3 and COALESCE(fl.larva_density, fl.larva_density_to)::double precision + COALESCE(fl.larva_density_to, fl.larva_density)::double precision / 2::double precision < 5 group by region_id) t2 on cr.id=t2.region_id\n"
+" left join (SELECT region_id,sum(1) as quietly from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and COALESCE(fl.larva_density, fl.larva_density_to)::double precision + COALESCE(fl.larva_density_to, fl.larva_density)::double precision / 2::double precision <= 2 group by region_id) t3 on cr.id=t3.region_id\n"
+"where\n"
+" cr.del=false\n"
+" and (t1.danger is not null or t2.attention is not null or t3.quietly is not null)\n"
+" and cr.country_id="+country_id;
st = m_conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
html+="<h3>"+trt("Hopper_density")+"</h3>";
html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000));
html+="<br>"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000));
html+="<table border=\"1\" style=\"border-collapse: collapse;\">";
html+="<tr style=\"background-color:#dadada;\"><th>"+trt("Oblast")+"</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_r.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Dangerous")+"\"<br>("+trt("Hopper_density")+" >=5)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_y.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Attention")+"\"<br>("+trt("Hopper_density")+" >=3 "+trt("and")+" <5)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_g.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Quietly")+"\"<br>("+trt("Hopper_density")+" <=2)</th></tr>";
exists=false;
if(rs!=null)
{
while (rs.next())
{
html+="<tr>";
html+="<td>"+rs.getString("region_name")+"</td>";
html+="<td>"+rs.getString("danger")+"</td>";
html+="<td>"+rs.getString("attention")+"</td>";
html+="<td>"+rs.getString("quietly")+"</td>";
html+="</tr>";
exists=true;
}
}
st.close();
if(!exists) html+="<td colspan=\"5\" style=\"text-align:center;font-weight:bold;\">"+trt("No_data")+"</td>";
html+="</table>";
html+="<a target=\"_blank\" href=\"http://ccalm.org/engine/?&cmd=FrmLocust&country_id="+country_id+"&date_start="+sdf.format(new Date(Long.parseLong(start_t)*1000))+"&date_end="+sdf.format(new Date(Long.parseLong(end_t)*1000))+"&registered=1&indicator=2\">"+trt("Open_data_on_the_map")+"</a>";
html+="<br><br>";
sql=""
+" select cr.name region_name,coalesce(t1.danger,0) danger,coalesce(t3.quietly,0) quietly from\n"
+" main.countriesregions cr\n"
+" left join (SELECT region_id,sum(1) as danger from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and (kuliguli_size >= 1 or kuliguli_density>=1 or kuliguli_density_to>=1) group by region_id) t1 on cr.id=t1.region_id\n"
+" left join (SELECT region_id,sum(1) as quietly from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and (kuliguli_size < 1 or kuliguli_size is null) group by region_id) t3 on cr.id=t3.region_id\n"
+" where\n"
+" cr.del=false\n"
+" and (t1.danger is not null or t3.quietly is not null)\n"
+" and cr.country_id="+country_id;
st = m_conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
html+="<h3>"+trt("Number_of_bands")+"</h3>";
html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000));
html+="<br>"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000));
html+="<table border=\"1\" style=\"border-collapse: collapse;\">";
html+="<tr style=\"background-color:#dadada;\"><th>"+trt("Oblast")+"</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_r.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Dangerous")+"\"<br>("+trt("Number_of_bands")+" >=1)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_g.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Quietly")+"\"<br>("+trt("Number_of_bands")+" <1)</th></tr>";
exists=false;
if(rs!=null)
{
while (rs.next())
{
html+="<tr>";
html+="<td>"+rs.getString("region_name")+"</td>";
html+="<td>"+rs.getString("danger")+"</td>";
html+="<td>"+rs.getString("quietly")+"</td>";
html+="</tr>";
exists=true;
}
}
st.close();
if(!exists) html+="<td colspan=\"3\" style=\"text-align:center;font-weight:bold;\">"+trt("No_data")+"</td>";
html+="</table>";
html+="<a target=\"_blank\" href=\"http://ccalm.org/engine/?&cmd=FrmLocust&country_id="+country_id+"&date_start="+sdf.format(new Date(Long.parseLong(start_t)*1000))+"&date_end="+sdf.format(new Date(Long.parseLong(end_t)*1000))+"&registered=1&indicator=3\">"+trt("Open_data_on_the_map")+"</a>";
html+="<br><br>";
sql=""
+" select cr.name region_name,coalesce(t1.danger,0) danger,coalesce(t3.quietly,0) quietly from\n"
+" main.countriesregions cr\n"
+" left join (SELECT region_id,sum(1) as danger from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and (swarm_maturity is not null or swarm_density_id is not null) group by region_id) t1 on cr.id=t1.region_id\n"
+" left join (SELECT region_id,sum(1) as quietly from main.frmlocust fl join main.terminals t on t.serial=fl.device_id where fl.del=false and t.del=false and (fl.date>to_timestamp("+start_t+") and fl.date<to_timestamp("+end_t+")) and (swarm_maturity is null and swarm_density_id is null) group by region_id) t3 on cr.id=t3.region_id\n"
+" where\n"
+" cr.del=false\n"
+" and (t1.danger is not null or t3.quietly is not null)\n"
+" and cr.country_id="+country_id;
st = m_conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
html+="<h3>"+trt("Number_of_swarms")+"</h3>";
html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000));
html+="<br>"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000));
html+="<table border=\"1\" style=\"border-collapse: collapse;\">";
html+="<tr style=\"background-color:#dadada;\"><th>"+trt("Oblast")+"</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_r.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Dangerous")+"\"<br>("+trt("Number_of_swarms")+" >=1)</th><th><img src=\"http://ccalm.org/resources/engine/images/icons/marker_g.png\" alt=\"\" align=\"left\">"+trt("Number_forms")+" \""+trt("Quietly")+"\"<br>("+trt("Number_of_swarms")+" <1)</th></tr>";
exists=false;
if(rs!=null)
{
while (rs.next())
{
html+="<tr>";
html+="<td>"+rs.getString("region_name")+"</td>";
html+="<td>"+rs.getString("danger")+"</td>";
html+="<td>"+rs.getString("quietly")+"</td>";
html+="</tr>";
exists=true;
}
}
st.close();
if(!exists) html+="<td colspan=\"5\" style=\"text-align:center;font-weight:bold;\">"+trt("No_data")+"</td>";
html+="</table>";
html+="<a target=\"_blank\" href=\"http://ccalm.org/engine/?&cmd=FrmLocust&country_id="+country_id+"&date_start="+sdf.format(new Date(Long.parseLong(start_t)*1000))+"&date_end="+sdf.format(new Date(Long.parseLong(end_t)*1000))+"&registered=1&indicator=5\">"+trt("Open_data_on_the_map")+"</a>";
html+="<br><br>";
html+="</body></html>";
/*String mail_host="";
String mail_port="";
String mail_login="";
String mail_password="";*/
try {
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, email, "Locust statistics", html);
//result = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
//result = "There were an error: " + ex.getMessage();
} finally {
//request.setAttribute("Message", resultMessage);
//getServletContext().getRequestDispatcher("/Result.jsp").forward(request, response);
}
html="";
}
} catch (NumberFormatException ex) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
} catch (SQLException ex) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
}
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
//---------------------------------------------------------------------------
public String trt(String key)
{
String result="";
if(m_conn!=null) {
ResultSet rs=null;
Statement st = null;
try {
st = m_conn.createStatement();
String sql = "select case when '"+m_user.language_id+"'='666' then translation||'''\"' else translation end as translation from main._translations t where t.identifier='"+key+"' and (t.language_id='"+m_user.language_id+"' or ('"+m_user.language_id+"'='666' and t.language_id=1));";
rs = st.executeQuery(sql);
if(rs != null) {
if (rs.next()) {
result = rs.getString(1);
}
}
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}finally{
if(st!=null) try{st.close();}catch(SQLException ex) {}
if(rs!=null) try{rs.close();}catch(SQLException ex) {}
}
}
if(result.equals(""))
{
result = key.replaceAll("_", " ");
}
return result;
}
//---------------------------------------------------------------------------
//Translate text by patterns
public String getText(String text) {
int pos1 = 0;
while (true) {
pos1 = text.indexOf("trt('", pos1);
if (pos1 == -1)
break;
int pos2 = text.indexOf("')", pos1);
if (pos2 == -1)
break;
text = text.substring(0, pos1) + trt(text.substring(pos1 + 5, pos2)) + text.substring(pos2 + 2);
}
return text;
}
//---------------------------------------------------------------------------
}

View File

@ -0,0 +1,41 @@
package org.ccalm.main;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.http.CacheControl;
import tools.User;
@Controller
//@SessionAttributes( { "user" })
public class SessionController {
//If not created object "user", create him.
//@ModelAttribute("user")
//public User populatePerson() {
// return new User("none");
//}
@RequestMapping(value = "/session", method = {RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
@ResponseBody
public Object ajaxTest(@ModelAttribute User user) {
//response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
JSONObject obj = new JSONObject();
if(user.id==null || user.id.equals("") || user.id.equals("null"))
obj.put("result", "ERROR");
else {
obj.put("result", "OK");
obj.put("user_id", user.id);
}
return obj.toString();
}
}

View File

@ -0,0 +1,184 @@
package org.ccalm.main;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
@Controller
public class TestFiles implements ServletContextAware {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SendMail.class);
private ServletContext context;
@RequestMapping(value = "/TestFiles",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxTamer()
{
String result="";
//Load DB configuration from "config.xml"
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
String mail_host = "";
String mail_port = "";
String mail_login = "";
String mail_password = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
mail_host = prop.getProperty("mail.host");
mail_port = prop.getProperty("mail.port");
mail_login = prop.getProperty("mail.login");
mail_password = prop.getProperty("mail.password");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
//Connect to database
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
String sql;
Statement st;
ResultSet rs=null;
result+="image_name1<br><br>";
sql="select image_name1 as name from main.frmlocustdel where image_name1 is not null";
try {
st = conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
if(rs!=null)
{
while (rs.next())
{
if(!(new File("/temp/CCALM/data/frmlocustdel/"+rs.getString("name"))).exists())
{
logger.info("update main.frmlocustdel set image_name1=null where image_name1=\""+rs.getString("name")+"\"");
result+="update main.frmlocustdel set image_name1=null where image_name1='"+rs.getString("name")+"';"+"<br>";
}
}
}
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
result+="image_name2<br><br>";
sql="select image_name2 as name from main.frmlocustdel where image_name2 is not null";
try {
st = conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
if(rs!=null)
{
while (rs.next())
{
if(!(new File("/temp/CCALM/data/frmlocustdel/"+rs.getString("name"))).exists())
{
logger.info("update main.frmlocustdel set image_name2=null where image_name2=\""+rs.getString("name")+"\"");
result+="update main.frmlocustdel set image_name2=null where image_name2='"+rs.getString("name")+"';"+"<br>";
}
}
}
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
result+="image_name3<br><br>";
sql="select image_name3 as name from main.frmlocustdel where image_name3 is not null";
try {
st = conn.createStatement();
rs=null;
try {
rs = st.executeQuery(sql);
} catch( SQLException ex ) {
result+="<br>Exec Exception:"+ex.getMessage()+"<br>";
}
if(rs!=null)
{
while (rs.next())
{
if(!(new File("/temp/CCALM/data/frmlocustdel/"+rs.getString("name"))).exists())
{
logger.info("update main.frmlocustdel set image_name3=null where image_name3=\""+rs.getString("name")+"\"");
result+="update main.frmlocustdel set image_name3=null where image_name3='"+rs.getString("name")+"';"+"<br>";
}
}
}
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
}

View File

@ -0,0 +1,151 @@
package org.ccalm.main;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Set;
//import javax.servlet.ServletContext;
import jakarta.servlet.ServletContext;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import tools.User;
/**
* Handles requests for the application home page.
*/
@Controller
//@SessionAttributes( { "user" })
public class TranslationController implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(TranslationController.class);
private ServletContext context;
/*@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String dbUsername;
@Value("${spring.datasource.password}")
private String dbPassword;*/
//If not created object "user", create him.
//@ModelAttribute("user")
//public User populatePerson() {
// return new User("none");
//}
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/translation", method = RequestMethod.GET)
@ResponseBody
public String home(@ModelAttribute User user/*, Locale locale*/, Model model) {
String db_url="";
String db_login="";
String db_password="";
//String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
db_url = prop.getProperty("spring.datasource.url");
db_login = prop.getProperty("spring.datasource.username");
db_password = prop.getProperty("spring.datasource.password");
//data_dir = prop.getProperty("data.dir");
} catch (Exception e) {
e.printStackTrace();
logger.error("Error load org_ccalm_main.properties",e);
}
//Get language from database
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
System.out.println("Connect is OK!");
}else
{
System.out.println("<br>Connect is ERROR<br>");
}
}catch(Exception e)
{
System.out.println("<br>Connect Exception:"+e.getMessage()+"<br>");
}
Properties props = new Properties();
try {
Statement st = conn.createStatement();
ResultSet rs=null;
try {
String sql_query = "select identifier,case when '"+user.language_id+"'='666' then translation||'''\"' else translation end as translation from main._translations t where t.del=false and (t.language_id='"+user.language_id+"' or ('"+user.language_id+"'='666' and t.language_id=1)) and translation_type_id=1 order by identifier;";
rs = st.executeQuery(sql_query);
} catch( SQLException ex )
{
System.out.println("<br>SQLException:"+ex.getMessage()+"<br>");
}
if(rs!=null)
{
while (rs.next())
{
if(rs.getString("translation")!=null)
props.setProperty(rs.getString("identifier"), rs.getString("translation"));
}
}
st.close();
} catch( SQLException ex )
{
System.out.println("<br>SQLException:"+ex.getMessage()+"<br>");
}
try{ conn.close(); }catch(Exception e){}
//Create JavaScript text
/*
InputStream utf8in = getClass().getClassLoader().getResourceAsStream("messages_"+user.lng+".properties");
Reader reader;
try {
reader = new InputStreamReader(utf8in, "UTF-8");
props.load(reader);
} catch (UnsupportedEncodingException e) {
}catch (IOException e) {
}*/
//Переписываю в JavaScript код
//JSONArray data = new JSONArray();
JSONObject data = new JSONObject();
String result="";
Set<Object> keys = props.keySet();
for(Object k:keys){
String key = ((String)k).trim();
String val = props.getProperty(key,"");
data.put(key,val);
//JSONObject obj = new JSONObject();
//obj.put(key,val);
//data.put(obj);
}
//model.addAttribute("keys",result);
//return "translation";
return "var g_translations = "+data.toString();
}
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
}

View File

@ -0,0 +1,128 @@
package org.ccalm.main;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* @author ivanov.i
*/
public class WeatherDownload {
private static final int BUFFER_SIZE = 4096;
public boolean download(String strURL,String strFile,String posStart,String posEnd)
{
boolean result=true;
String rez = null;
String inputLine = null;
/*try
{
rez = new String("".getBytes(), "utf-8");
inputLine = new String("".getBytes(), "utf-8");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}*/
try
{
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Range","bytes=" + posStart + "-" + posEnd);
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode / 100 == 2) //Code 206 is "Partial Content"
{
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(strFile);
int bytesRead;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
conn.disconnect();
}
catch (IOException e)
{
//e.printStackTrace();
result=false;
}
return result;
}
/**
* Downloads a file from a URL
* @param fileURL HTTP URL of the file to be downloaded
* @param saveDir path of the directory to save the file
* @throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}

View File

@ -0,0 +1,528 @@
package org.ccalm.main.engine;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Base64;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext;
import jakarta.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.apache.logging.log4j.LogManager;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import org.springframework.dao.DataAccessException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import tctable.Tools;
import tools.DBTools;
import tools.User;
/**
* Handles requests for the application home page.
*/
@Controller
public class EngineController implements ServletContextAware {
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(EngineController.class);
private ServletContext context;
private Properties m_props=null;
//private String m_props_loc="";
@Value("${public.key}")
String key_a_txt="";
private final NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
public EngineController(NamedParameterJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private PublicKey getPublicKey(){
try {
byte[] keyBytes = Base64.getDecoder().decode(key_a_txt);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(spec);
return key;
} catch (Exception e) {
logger.error(e);
}
return null;
}
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/engine", method = RequestMethod.GET)
public String home(
Model model,
HttpServletResponse response,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
String redirectUrl = "/login/login?msg=Please_log_in";
model.addAttribute("url", redirectUrl);
return "redirect";
}
//Проверяю подпись токена
Jws<Claims> claims = null;
PublicKey key_a = getPublicKey(); //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(env.getProperty("access.key")), "HmacSHA256");
try {
claims = Jwts.parserBuilder()
.setSigningKey(key_a)
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
String redirectUrl = "/login/login?msg=Please_log_in";
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
model.addAttribute("url", redirectUrl);
return "redirect";
}
//if(language_id!=null && !language_id.equals("")) user.language_id=language_id;
//logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id);
long country_id=0;
try {
String sql="""
select language_id,country_id from main._users where id=user_id
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("user_id", claims.getBody().get("user_id"));
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (int i = 0; i < ret.size(); i++) {
JSONObject obj = new JSONObject(ret.get(i));
country_id=obj.getLong("country_id");
}
} catch( DataAccessException ex )
{
logger.info(ex.getMessage());
}
//Send user name and role
model.addAttribute("uName",claims.getBody().get("sub").toString()/*+" ("+user.role+")"*/);
model.addAttribute("m_locale",language_id);
model.addAttribute("country_id",country_id);
//Send translation to user
/*InputStream utf8in = getClass().getClassLoader().getResourceAsStream("messages_"+user.lng+".properties");
if(utf8in!=null)
{
Properties props=new Properties();
Reader reader;
try {
reader = new InputStreamReader(utf8in, "UTF-8");
props.load(reader);
} catch (UnsupportedEncodingException e) {
}catch (IOException e) {
}
//Также подгружаю перевод из XML файла Android проекта
Translation.loadTranslationFromXML(props,getClass().getClassLoader().getResourceAsStream("strings_"+user.lng+".xml"));
Set<Object> keys = props.keySet();
for(Object k:keys){
String key = (String)k;
String val="";
//val = trt(conn,key,user); //Если есть то перевод беру из базы данных
if(val.equals(""))
{
val = props.getProperty(key,"");
if(val.equals(""))
{
val = val.replaceAll("_", " ");
}
}
model.addAttribute(key,val);
}
}*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//TODO удалить нужно только для копирования языков в базу (если там их нет)
/*InputStream isXML = getClass().getClassLoader().getResourceAsStream("strings_"+user.lng+".xml");
if(isXML!=null)
{
Document doc = null;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(isXML);
} catch (Exception ex) {
logger.info(ex.getMessage());
}
Node reqNode = doc.getDocumentElement();
Node nextnode=reqNode.getFirstChild();
while(nextnode!=null)
{
if(nextnode.getNodeName().equals("string"))
{
String name=nextnode.getAttributes().getNamedItem("name").getNodeValue();
String val="";
if(nextnode.getFirstChild()!=null)
val=nextnode.getFirstChild().getNodeValue();
//Если нет то добавляю
boolean exists=false;
try {
Statement st = conn.createStatement();
ResultSet rs=null;
try {
String sql="select t.id from main._translations t join main._languages l on l.id=t.language_id where t.del=false and identifier='"+name+"' and l.short_name='"+user.lng+"';";
rs = st.executeQuery(sql);
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
if(rs!=null)
{
while (rs.next())
{
exists=true;
}
}
st.close();
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
if(exists)
{
logger.info(name+" = "+val+" exists");
//Если идентификатор сушествует то проверяю совпадает ли сам перевод (просто для информации)
boolean equals=false;
try {
Statement st = conn.createStatement();
ResultSet rs=null;
try {
String sql="select t.id from main._translations t join main._languages l on l.id=t.language_id where t.del=false and t.identifier='"+name+"' and t.translation='"+val+"' and l.short_name='"+user.lng+"';";
rs = st.executeQuery(sql);
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
if(rs!=null)
{
while (rs.next())
{
equals=true;
}
}
st.close();
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
if(equals)
{
logger.info(name+" = "+val+" equals");
}else
{
logger.info(name+" = "+val+" not equals");
}
}else
{
logger.info(name+" = "+val+" not exists");
//Вставляю новую запись в базу
try {
Statement st = conn.createStatement();
try {
String sql="insert into main._translations(language_id,identifier,translation,translation_type_id) select (select l.id from main._languages l where l.del=false and l.short_name='"+user.lng+"'),'"+name+"' as identifier,'"+val+"' as translation,3 as translation_type_id;";
st.execute(sql);
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
}
}
nextnode = nextnode.getNextSibling();
}
}*/
//Читаю перевод из properties файлов и записываю в базу под номером 1
/*InputStream utf8in = getClass().getClassLoader().getResourceAsStream("messages_"+user.lng+".properties");
if(utf8in!=null)
{
Properties props=new Properties();
Reader reader;
try {
reader = new InputStreamReader(utf8in, "UTF-8");
props.load(reader);
} catch (UnsupportedEncodingException e) {
}catch (IOException e) {
}
//Также подгружаю перевод из XML файла Android проекта
//Translation.loadTranslationFromXML(props,getClass().getClassLoader().getResourceAsStream("strings_"+user.lng+".xml"));
Set<Object> keys = props.keySet();
for(Object k:keys){
String key = (String)k;
String val = props.getProperty(key,"");
//Если нет то добавляю
boolean exists=false;
try {
Statement st = conn.createStatement();
ResultSet rs=null;
try {
String sql="select t.id from main._translations t join main._languages l on l.id=t.language_id where t.del=false and identifier='"+key+"' and l.short_name='"+user.lng+"' and translation_type_id=1;";
rs = st.executeQuery(sql);
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
if(rs!=null)
{
while (rs.next())
{
exists=true;
}
}
st.close();
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
if(exists)
{
logger.info(key+" = "+val+" exists");
}else
{
logger.info(key+" = "+val+" not exists");
//Вставляю новую запись в базу
try {
Statement st = conn.createStatement();
try {
String sql="insert into main._translations(language_id,identifier,translation,translation_type_id) select (select l.id from main._languages l where l.del=false and l.short_name='"+user.lng+"'),'"+key+"' as identifier,'"+val+"' as translation,1 as translation_type_id;";
st.execute(sql);
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
} catch( SQLException ex )
{
logger.info(ex.getMessage());
}
}
}
}*/
//Для перевода выбираю всё что под номером 1 в переводе
try {
String sql="""
select identifier,translation from main._translations t where t.del=false and t.language_id=:language_id and translation_type_id=1
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("language_id", language_id);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (int i = 0; i < ret.size(); i++) {
JSONObject obj = new JSONObject(ret.get(i));
m_props.setProperty(obj.getString("identifier"), obj.getString("translation"));
}
} catch( DataAccessException ex )
{
logger.info(ex.getMessage());
}
Set<Object> keys = m_props.keySet();
for(Object k:keys){
String key = (String)k;
String val="";
if(val.equals(""))
{
val = m_props.getProperty(key,"");
if(val.equals(""))
{
val = val.replaceAll("_", " ");
}
}
model.addAttribute(key,val);
}
//Подложка Substrate_head Substrate_tail
String Substrate_head="";
String Substrate_tail="";
if(country_id>0)
{
try {
String sql="""
SELECT id,path,description,projection FROM main.layouts where del=false and country_id=:country_id order by description
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("country_id", country_id);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (int i = 0; i < ret.size(); i++) {
JSONObject obj = new JSONObject(ret.get(i));
//m_props.setProperty(obj.getString("identifier"), obj.getString("translation"));
Substrate_head+=" <option value=\""+obj.getString("id")+"\">"+obj.getString("description")+"</option>\n";
Substrate_tail+="g_Layouts[\""+obj.getString("id")+"\"] = new ol.source.XYZ({\n";
Substrate_tail+=" url: '"+obj.getString("path")+"',\n";
if(!obj.isNull("projection") && obj.getString("projection").indexOf("EPSG:")!=-1)
Substrate_tail+=" projection: '"+obj.getString("projection")+"',\n";
Substrate_tail+=" });\n";
}
} catch( DataAccessException ex )
{
logger.info(ex.getMessage());
}
}
model.addAttribute("Substrate_head",Substrate_head);
model.addAttribute("Substrate_tail",Substrate_tail);
//Выбираю дату получения NDVI данных по номеру дня
/*{
int maxNum=1;
try {
File folder = new File(ndvi_dir);
File[] listOfFiles = folder.listFiles();
if(listOfFiles!=null)
{
for (int i = 0; i < listOfFiles.length; i++)
{ if (listOfFiles[i].isFile())
{
if(Tools.afterLast(listOfFiles[i].getName(),".").equals("json"))
{
int num=1;
try {
num=1+Integer.valueOf(Tools.beforeLast(listOfFiles[i].getName(),"."));
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
if(num>maxNum) maxNum=num;
}
}
}
}
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
Year y = Year.of( Calendar.getInstance().get(Calendar.YEAR) ) ;
model.addAttribute("NDVI_DATE",y.atDay( maxNum ).toString());
model.addAttribute("NDVI_DAY",String.valueOf(maxNum));
}*/
//Выбираю дату получения NDWI данных по номеру дня
/*{
int maxNum=1;
try {
File folder = new File(ndwi_dir);
File[] listOfFiles = folder.listFiles();
if(listOfFiles!=null)
{
for (int i = 0; i < listOfFiles.length; i++)
{ if (listOfFiles[i].isFile())
{
if(Tools.afterLast(listOfFiles[i].getName(),".").equals("json"))
{
int num=1;
try {
num=1+Integer.valueOf(Tools.beforeLast(listOfFiles[i].getName(),"."));
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
if(num>maxNum) maxNum=num;
}
}
}
}
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
Year y = Year.of( Calendar.getInstance().get(Calendar.YEAR) ) ;
model.addAttribute("NDWI_DATE",y.atDay( maxNum ).toString());
model.addAttribute("NDWI_DAY",String.valueOf(maxNum));
}*/
return "engine/index";
}
@Override
public void setServletContext(jakarta.servlet.ServletContext servletContext) {
this.context=context;
}
//Перевести слово по идентификатору из базы а если в базе нет то из файлов перевода
public String trt(Connection conn,String key,User user)
{
String result="";
if(key.equals(""))
return result;
try {
Statement stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sql_query = "select case when '"+user.language_id+"'='666' then translation||'''\"' else translation end as translation from main._translations t where t.del=false and identifier='"+key+"' and (t.language_id='"+user.language_id+"' or ('"+user.language_id+"'='666' and t.language_id=1));";
ResultSet rs = stt.executeQuery(sql_query);
if (rs != null) {
try {
if (rs.next())
result=rs.getString(1);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
rs.close();
}
stt.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if(result.equals(""))
{
result = key.replaceAll("_", " ");
}
return result;
}
}

View File

@ -0,0 +1,72 @@
package org.ccalm.main.login;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.ServletContext;
import org.apache.logging.log4j.LogManager;
import org.ccalm.main.engine.EngineController;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import tctable.Tools;
import tools.DBTools;
import tools.User;
import java.io.FileInputStream;
import java.security.PublicKey;
import java.sql.*;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
@Controller
public class LoginController implements ServletContextAware {
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(EngineController.class);
private javax.servlet.ServletContext context;
private final NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
public LoginController(NamedParameterJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.context=context;
}
@RequestMapping(value = "/login/login", method = RequestMethod.GET)
public String home(
@ModelAttribute User user,
Model model,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@RequestParam(required=false,name="lng", defaultValue = "1") String language_id
) {
String sql = "select identifier,translation from main._translations t where t.del=false and t.language_id=:language_id";
try {
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("language_id", Integer.valueOf(language_id));
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (int i = 0; i < ret.size(); i++) {
JSONObject json = new JSONObject(ret.get(i));
model.addAttribute(json.getString("identifier"), json.getString("identifier"));
}
} catch (Exception ex) {
String uuid = UUID.randomUUID().toString();
logger.error(uuid, ex);
}
return "login/login";
}
}

View File

@ -0,0 +1,8 @@
package org.ccalm.main.recReq;
import java.io.Serializable;
public class ExistsType {
public boolean exists=false;
public String type="";
}

View File

@ -0,0 +1,21 @@
package org.ccalm.main.recReq;
import java.io.Serializable;
public class RecReq implements Serializable {
private static final long serialVersionUID = 1L;
public int fn;
public int cmd;
public int getFn()
{
return fn;
}
public int getCmd()
{
return cmd;
}
}

View File

@ -0,0 +1,14 @@
/**
* Created by IntelliJ IDEA.
* User: igor
* Date: 09.03.2007
* Time: 0:53:45
* To change this template use File | Settings | File Templates.
*/
package tctable;
public class Point
{
public double x=0;
public double y=0;
}

View File

@ -0,0 +1,574 @@
package tctable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
public class TCField
{
//Типы данных
public static final int BD_NULL = 1000; //Столбец со значением всегда NULL
public static final int BD_UINT1 = 0; //1 байт без знаковый
public static final int BD_UINT2 = 1; //2 байта без знаковый
public static final int BD_UINT4 = 3; //4 байта без знаковый
public static final int BD_UINT8 = 23; //8 байта без знаковый
public static final int BD_SUINT8 = 24; //Почти тоже самое что и BD_UTF8_1 но с строке передаётся число
public static final int BD_INT1 = 10; //1 байт со знаковый
public static final int BD_INT2 = 11; //2 байта со знаковый
public static final int BD_INT4 = 13; //4 байта со знаковый
public static final int BD_INT8 = 17; //8 байт со знаковый
public static final int BD_SINT8 = 25; //Почти тоже самое что и BD_UTF8_1 но с строке передаётся число
public static final int BD_FLOAT4 = 20; //4 байта
public static final int BD_FLOAT8 = 22; //8 байт double
public static final int BD_SFLOAT8 = 26; //Почти тоже самое что и BD_UTF8_1 но с строке передаётся число
public static final int BD_UTF8_1 = 100; //100 - utf8_1 string 1й байт размер строки в байтах
public static final int BD_UTF8_2 = 101; //101 - utf8_2 string 1х 2 байта размер строки в байтах
public static final int BD_UTF8_4 = 102; //102 - utf8_4 string 1х 4 байта размер строки в байтах
public static final int BD_BLOB_2 = 141;
public static final int BD_BLOB_4 = 143; //Двоичные данные uint4 количество байт
public String name=""; //Название столбца
public int type=-1; //Тип данных
public byte[] value=null; //Запакованые данные
public TCField(String name, int type)
{
this.name=name;
this.type=type;
}
public TCField(String name, String type)
{
this.name=name;
//this.type=type;
this.type= TCField.BD_UTF8_2; //Defalt type
//From PostgreSQL and MySQL
if(type.equals("null")) { this.type= TCField.BD_NULL; } else
if(type.equals("bool") || type.equals("tinyint")) { this.type= TCField.BD_UINT1; } else
if(type.equals("int4") || type.equals("int") || type.equals("serial") || type.equals("bigint")) { this.type= TCField.BD_INT4; } else //bigint немного неправильно потому что это 64 бита но для андрод приложения не сделал
if(type.equals("int8")) { this.type= TCField.BD_INT8; } else
if(type.equals("float4") || type.equals("float")) { this.type= TCField.BD_FLOAT4; } else
if(type.equals("float8") || type.equals("NUMBER")) { this.type= TCField.BD_FLOAT8; } else
if(type.equals("varchar") || type.equals("VARCHAR2")) { this.type= TCField.BD_UTF8_2; } else
if(type.equals("text")) { this.type= TCField.BD_UTF8_4; } else
if(type.equals("bytea") || type.equals("longblob")) { this.type= TCField.BD_BLOB_4; } else
if(type.equals("timestamptz")) { this.type= TCField.BD_UTF8_1; } else
if(type.equals("timestamp")) { this.type= TCField.BD_UTF8_1; } else
if(type.equals("date")) { this.type= TCField.BD_UTF8_1; }
}
private int byteArrayToInt(byte[] b, int start, int length)
{
int dt = 0;
if ((b[start] & 0x80) != 0)
dt = Integer.MAX_VALUE;
for (int i = 0; i < length; i++)
dt = (dt << 8) + (b[start++] & 255);
return dt;
}
/*
private byte[] intToByteArray(int n, int byteCount)
{
byte[] res = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
res[byteCount - i - 1] = (byte) ((n >> i * 8) & 255);
return res;
}
*/
//Прочитать значение из потока в соответствии с типом
public void ReadValue(InputStream fileHandle) throws IOException
{
if(this.type== TCField.BD_UINT1)
{
value=new byte[1];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UINT2)
{
value=new byte[2];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UINT4)
{
value=new byte[4];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UINT8)
{
value=new byte[8];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT1)
{
value=new byte[1];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT2)
{
value=new byte[2];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT4)
{
value=new byte[4];
fileHandle.read(value);
}else
if(this.type== TCField.BD_INT8)
{
value=new byte[8];
fileHandle.read(value);
}else
if(this.type== TCField.BD_FLOAT4)
{
value=new byte[4];
fileHandle.read(value);
}else
if(this.type== TCField.BD_FLOAT8)
{
value=new byte[8];
fileHandle.read(value);
}else
if(this.type== TCField.BD_UTF8_1 || this.type== TCField.BD_SUINT8 || this.type== TCField.BD_SINT8 || this.type== TCField.BD_SFLOAT8)
{
byte[] s=new byte[1];
fileHandle.read(s);
if(s[0]==0) value=null;
else
{
value=new byte[s[0]];
fileHandle.read(value);
}
}else
if(this.type== TCField.BD_UTF8_2)
{
int s=Tools.readUShort(fileHandle);
if(s==0) value=null;
else
{
value=new byte[s];
fileHandle.read(value);
}
}else
if(this.type== TCField.BD_UTF8_4)
{
long s=Tools.readUInt(fileHandle);
if(s==0) value=null;
else
{
value=new byte[(int)s];
fileHandle.read(value);
}
}else
if(this.type== TCField.BD_BLOB_4)
{
byte[] ss=new byte[4];
fileHandle.read(ss);
int s=byteArrayToInt(ss, 0, 4);
if(s==0) value=null;
else
{
value=new byte[s];
fileHandle.read(value);
}
}
}
public String getStrVal()
{
String result=null;
try
{
if(value==null) result = "";
if(type== TCField.BD_UINT1) result = String.valueOf(getUByteVal());
if(type== TCField.BD_UINT4) result = String.valueOf(getUIntVal());
if(type== TCField.BD_UINT8) result = String.valueOf(getULongVal());
if(type== TCField.BD_INT4) result = String.valueOf(getIntVal());
if(type== TCField.BD_INT8) result = String.valueOf(getLongVal());
if(type== TCField.BD_FLOAT4) result = String.valueOf(getFloatVal());
if(type== TCField.BD_FLOAT8) result = String.valueOf(getDoubleVal());
if(type== TCField.BD_UTF8_1 || type== TCField.BD_UTF8_2 || type== TCField.BD_UTF8_4 || type== TCField.BD_SUINT8 || type== TCField.BD_SINT8 || type== TCField.BD_SFLOAT8)
{
result = new String(value, "UTF8");
}
} catch (Exception e) {}
return result;
}
public boolean getBoolVal(){
String result=getStrVal();
if(result==null)
return false;
else {
result=result.toLowerCase();
if (result.equals("1") || result.equals("true") || result.equals("t"))
return true;
else
return false;
}
}
public int getIntVal()
{
int val=0;
if(type==BD_INT4) {
int i1 = value[0] & 0xff;
int i2 = value[1] & 0xff;
int i3 = value[2] & 0xff;
int i4 = value[3] & 0xff;
val = i4 << 24 | i3 << 16 | i2 << 8 | i1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Integer.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public long getLongVal()
{
long val=0;
if(type==BD_INT8) {
long ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8;
ch1 = value[0] & 0xff;
ch2 = value[1] & 0xff;
ch3 = value[2] & 0xff;
ch4 = value[3] & 0xff;
ch5 = value[4] & 0xff;
ch6 = value[5] & 0xff;
ch7 = value[6] & 0xff;
ch8 = value[7] & 0xff;
val = (ch8 << 56) | (ch7 << 48) | (ch6 << 40) | (ch5 << 32) | (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Long.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
/** Пока не использую но если буду использовать протестировать с большими числами */
public long getUIntVal()
{
long val=0;
if(type==BD_UINT4) {
long ch1, ch2, ch3, ch4;
ch1 = value[0] & 0xff;
ch2 = value[1] & 0xff;
ch3 = value[2] & 0xff;
ch4 = value[3] & 0xff;
val = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Long.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public long getULongVal()
{
long val=0;
if(type==BD_UINT8) {
long ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8;
ch1 = value[0] & 0xff;
ch2 = value[1] & 0xff;
ch3 = value[2] & 0xff;
ch4 = value[3] & 0xff;
ch5 = value[4] & 0xff;
ch6 = value[5] & 0xff;
ch7 = value[6] & 0xff;
ch8 = value[7] & 0xff;
val = (ch8 << 56) | (ch7 << 48) | (ch6 << 40) | (ch5 << 32) | (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Long.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public short getUByteVal()
{
short val=0;
if(type==BD_UINT1) {
val = (short) (value[0] & 0xff);
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Short.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public float getFloatVal()
{
float val=0;
if(type==BD_FLOAT4) {
int ch1, ch2, ch3, ch4, count;
ch1 = value[0] & 0xFF;
ch2 = value[1] & 0xFF;
ch3 = value[2] & 0xFF;
ch4 = value[3] & 0xFF;
count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
val = Float.intBitsToFloat(count);
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Float.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public double getDoubleVal()
{
double val=0;
if(type==BD_FLOAT8) {
int ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8;
long count;
ch1 = value[0] & 0xFF;
ch2 = value[1] & 0xFF;
ch3 = value[2] & 0xFF;
ch4 = value[3] & 0xFF;
ch5 = value[4] & 0xFF;
ch6 = value[5] & 0xFF;
ch7 = value[6] & 0xFF;
ch8 = value[7] & 0xFF;
count = ((long) ch8 << 56) |
((long) ch7 << 48) |
((long) ch6 << 40) |
((long) ch5 << 32) |
((long) ch4 << 24) |
((long) ch3 << 16) |
((long) ch2 << 8) |
ch1;
val = Double.longBitsToDouble(count);
}else{
String sVal = getStrVal();
if(sVal!=null) {
try {
val = Double.valueOf(sVal);
} catch (NumberFormatException e) {
}
}
}
return val;
}
public boolean setDoubleVal(Double v){
long iv= Double.doubleToLongBits(v);
value=new byte[8];
value[0] = (byte)((iv & 0x00000000000000ffl));
value[1] = (byte)((iv & 0x000000000000ff00l) >> 8);
value[2] = (byte)((iv & 0x0000000000ff0000l) >> 16);
value[3] = (byte)((iv & 0x00000000ff000000l) >> 24);
value[4] = (byte)((iv & 0x000000ff00000000l) >> 32);
value[5] = (byte)((iv & 0x0000ff0000000000l) >> 40);
value[6] = (byte)((iv & 0x00ff000000000000l) >> 48);
value[7] = (byte)((iv & 0xff00000000000000l) >> 56);
return true;
}
public boolean setValue(String val)
{
boolean result=true;
if(val==null)
{ value=null;
}else if(type== TCField.BD_UINT1)
{
if(val.equals("f") || val.equals("false")) val="0";
else if(val.equals("t") || val.equals("true")) val="1";
int v= Integer.parseInt(val);
if(v<0 || v>255) result=false;
value=new byte[1];
value[0]=(byte)v;
}else if(type== TCField.BD_UINT2)
{
int v= Integer.parseInt(val);
if(v<0 || v>65535) result=false;
value=new byte[2];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
}else if(type== TCField.BD_UINT4)
{
long v= Long.parseLong(val);
value=new byte[4];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
value[2] = (byte)((v & 0x00ff0000) >> 16);
value[3] = (byte)((v & 0xff000000) >> 24);
}else if(type== TCField.BD_UINT8)
{
long v= Long.parseLong(val);
value=new byte[8];
value[0] = (byte) (v & 0x00000000000000ffl);
value[1] = (byte)((v & 0x000000000000ff00l) >> 8);
value[2] = (byte)((v & 0x0000000000ff0000l) >> 16);
value[3] = (byte)((v & 0x00000000ff000000l) >> 24);
value[4] = (byte)((v & 0x000000ff00000000l) >> 32);
value[5] = (byte)((v & 0x0000ff0000000000l) >> 40);
value[6] = (byte)((v & 0x00ff000000000000l) >> 48);
value[7] = (byte)((v & 0xff00000000000000l) >> 56);
}else if(type== TCField.BD_INT1)
{
int v= Integer.parseInt(val);
value=new byte[1];
value[0]=(byte)v;
}else if(type== TCField.BD_INT2)
{
int v= Integer.parseInt(val);
value=new byte[2];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
}else if(type== TCField.BD_INT4)
{
long v= Long.parseLong(val);
value=new byte[4];
value[0] = (byte)((v & 0x000000ff));
value[1] = (byte)((v & 0x0000ff00) >> 8);
value[2] = (byte)((v & 0x00ff0000) >> 16);
value[3] = (byte)((v & 0xff000000) >> 24);
}else if(type== TCField.BD_INT8)
{
long v= Long.parseLong(val);
value=new byte[8];
value[0] = (byte) (v & 0x00000000000000ffl);
value[1] = (byte)((v & 0x000000000000ff00l) >> 8);
value[2] = (byte)((v & 0x0000000000ff0000l) >> 16);
value[3] = (byte)((v & 0x00000000ff000000l) >> 24);
value[4] = (byte)((v & 0x000000ff00000000l) >> 32);
value[5] = (byte)((v & 0x0000ff0000000000l) >> 40);
value[6] = (byte)((v & 0x00ff000000000000l) >> 48);
value[7] = (byte)((v & 0xff00000000000000l) >> 56);
}else if(type== TCField.BD_FLOAT4)
{
Float v= Float.parseFloat(val);
int iv= Float.floatToIntBits(v);
value=new byte[4];
value[0] = (byte)((iv & 0x000000ff));
value[1] = (byte)((iv & 0x0000ff00) >> 8);
value[2] = (byte)((iv & 0x00ff0000) >> 16);
value[3] = (byte)((iv & 0xff000000) >> 24);
}else if(type== TCField.BD_FLOAT8)
{
setDoubleVal(Double.parseDouble(val));
}else if(type== TCField.BD_UTF8_1 || this.type== TCField.BD_SUINT8 || this.type== TCField.BD_SINT8 || this.type== TCField.BD_SFLOAT8)
{
value=null;
if(val!=null && !val.equals(""))
{
byte[] b=null;
try {
b = val.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
result=false;
}
if(b!=null)
{
int len=b.length;
if(len>255) len=255;
value=new byte[len+1];
value[0]=(byte)len;
for(int i=0;i<len;i++)
{
value[i+1]=b[i];
}
}
}
}else if(type== TCField.BD_UTF8_2)
{
value=null;
if(val!=null && !val.equals(""))
{
byte[] b=null;
try {
b = val.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
result=false;
}
if(b!=null)
{
int len=b.length;
if(len>65535) len=65535;
value=new byte[len+2];
value[0]=(byte) (len & 0x000000ff);
value[1]=(byte)((len & 0x0000ff00) >> 8);
for(int i=0;i<len;i++)
{
value[i+2]=b[i];
}
}
}
}else if(type== TCField.BD_UTF8_4)
{
value=null;
if(val!=null && !val.equals(""))
{
byte[] b=null;
try {
b = val.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
result=false;
}
if(b!=null)
{
int len=b.length;
value=new byte[len+4];
value[0]=(byte) (len & 0x000000ff);
value[1]=(byte)((len & 0x0000ff00) >> 8);
value[2]=(byte)((len & 0x00ff0000) >> 16);
value[3]=(byte)((len & 0xff000000) >> 24);
for(int i=0;i<len;i++)
{
value[i+4]=b[i];
}
}
}
}
return result;
}
public boolean isNull() {
return value==null;
}
public BigDecimal getBigDecimalVal() {
BigDecimal val=new BigDecimal("0");
String sVal = getStrVal();
if(sVal!=null) {
try {
val = new BigDecimal(sVal);
} catch (NumberFormatException e) {
}
}
return val;
}
}

View File

@ -0,0 +1,200 @@
package tctable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class TCTable
{
public int id=0; //Идентификатор таблицы
public String name=""; //Название таблицы
public List<TCField> fields=new ArrayList<TCField>(); //Список полей
private int nc=0; //Байтов под NULL значения
private byte[] m_NULL=null; //NULL значения
private InputStream m_file;
/**
* Конструктор
* @param Строка name Название таблицы
* @param Целое id Идентификатор таблицы (обычно уникальный)
*/
public TCTable(String name, int id)
{ this.name=name;
this.id=id;
}
//Открыть таблицу по названию файла
/*function OpenTableF(file)
{
if(file_exists(file))
{
this.OpenTableH(fopen(file,'r'));
}
}*/
//Открыть таблицу из потока HANDLE
public boolean OpenTableH(InputStream handle) throws IOException
{
this.m_file=handle;
DataInputStream dis = new DataInputStream(handle);
if(Tools.readUShort(dis)!=65500) return false; //id файла
if(Tools.readUShort(dis)!=1) return false; //Версия файла
this.id= Tools.readInt(dis); //ID таблицы или запроса (4 байта можно сделать 2)
if(dis.readByte()!=0) return false; //Только плотные таблицы
//Считываем название таблицы
this.name = Tools.readUTF8_1(dis);
//Считываем столбцы
int count=dis.readUnsignedByte(); //Количество столбцов
for(int i=0;i<count;i++)
{
TCField field=new TCField(Tools.readUTF8_1(dis), dis.readUnsignedByte());
this.addField(field);
}
return true;
}
//Открыть таблицу из потока
//OpenTable
//Прочитать следующую запись из потока
public boolean ReadNextRecord()
{
Boolean result=true;
try
{
DataInputStream dis = new DataInputStream(m_file);
//if(m_file.available()) return false; //Неработает
if(dis.available()==0)
return false;
//Считываем NULL значения
if(m_NULL==null) m_NULL = new byte[nc];
for(int i=0;i<nc;i++)
{
m_NULL[i]=(byte)dis.readUnsignedByte();
}
clearRows();
for(int i=0;i<fields.size();i++)
{
if(Tools.getBit(m_NULL,i))
{
fields.get(i).ReadValue(m_file);
}
}
}catch(Exception e)
{
result=false;
}
return result;
}
//Добавить поле к таблице
public void addField(TCField field)
{ if(field!=null)
{ fields.add(field);
this.nc=(int) Math.ceil(fields.size()/8.0); //Байтов под NULL
m_NULL=new byte[nc];
}
}
//Получить заголовок плотной таблицы в виде двоичной строки
public boolean getHeader(OutputStream os)
{
boolean result=true;
try {
//File ID: 2 bytes.
os.write((65500 & 0x000000ff));
os.write((65500 & 0x0000ff00) >> 8);
//File version: 2 bytes.
os.write((1 & 0x000000ff));
os.write((1 & 0x0000ff00) >> 8);
//Table ID (or Request ID): 4 bytes.
os.write((this.id & 0x000000ff));
os.write((this.id & 0x0000ff00) >> 8);
os.write((this.id & 0x00ff0000) >> 16);
os.write((this.id & 0xff000000) >> 24);
//Table type: 1 byte (0- "Dense" 1- "Loose")
os.write(0);
//UTF8_1 String
byte[] ba = this.name.getBytes("UTF-8");
os.write(ba.length);
os.write(ba);
//Count of fields: 1 byte.
os.write(this.fields.size());
//Write name and type id
for(int i=0;i<this.fields.size();i++)
{
ba = this.fields.get(i).name.getBytes("UTF-8");
os.write(ba.length);
os.write(ba);
os.write(this.fields.get(i).type);
}
} catch (IOException e) {
result=false;
}
return result;
}
//Получить данные 1 записи в виде строки
public boolean getCol(OutputStream os)
{
boolean result=true;
//Запишем NULL значения побайтно (1-есть данные 0-нету данных)
int nc=(int) Math.ceil(fields.size()/8.0); //Байтов под NULL
byte[] fNULL=new byte[nc];
for(int i=0;i<nc*8;i++)
{
if(i<this.fields.size() && this.fields.get(i).value!=null)
{
Tools.setBit(fNULL,i);
}
}
//Write NULL fields
try {
os.write(fNULL);
} catch (IOException e1) {
result=false;
}
//Запишем сами данные в строку
for(int i=0;i<fields.size();i++)
{
try {
if(fields.get(i).value!=null)
os.write(fields.get(i).value);
} catch (IOException e) {
result=false;
}
}
return result;
}
//Row очистить запись
void clearRows()
{ for(int i=0;i<fields.size();i++)
{
fields.get(i).value=null;
}
}
//Получить обьект столбца по имени
public TCField getRowByName(String name)
{ for(int i=0;i<fields.size();i++)
{ if(fields.get(i).name.toUpperCase().equals(name.toUpperCase())) return fields.get(i);
}
return null;
}
//Получить объект столбца по номеру
TCField getRowByNum(int num)
{ return fields.get(num);
}
}

View File

@ -0,0 +1,74 @@
package tctable;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
//В андроид не используется данный класс
public class TCTableTools {
//Записать таблицу в OutputStream
public static boolean getTCTableFromResultSet(String name, int id, ResultSet rs, OutputStream os){
TCTable tbl=new TCTable(name,id);
try {
ResultSetMetaData rsmd = rs.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();i++)
{
TCField field = new TCField(rsmd.getColumnName(i), rsmd.getColumnTypeName(i));
tbl.addField(field);
}
tbl.getHeader(os);
while (rs.next())
{
for(int i=1;i<=rsmd.getColumnCount();i++)
{
if(rsmd.getColumnTypeName(i).equals("geometry")) { //Геометрию не сохраняю пока не знаю как лучьше сохранять
tbl.fields.get(i - 1).setValue(null);
}else {
tbl.fields.get(i - 1).setValue(rs.getString(i));
}
}
tbl.getCol(os);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
//Напиши функцию: Получить ассоциативный массив название полей таблицы и их тип
public static Map<String, String> getTableSchema(Connection connection, String schemaName, String tableName) {
Map<String, String> schemaMap = new HashMap<>();
String query = """
SELECT c.column_name,
CASE
WHEN t.typtype = 'e' THEN 'enum'
WHEN t.typname = 'USER-DEFINED' THEN
(SELECT pt.typname FROM pg_type pt WHERE pt.oid = c.udt_name::regtype::oid)
ELSE t.typname
END as data_type
FROM information_schema.columns c
JOIN pg_type t ON c.udt_name = t.typname
WHERE c.table_schema = ?
AND c.table_name = ?
""";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, schemaName);
statement.setString(2, tableName);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
String columnName = resultSet.getString("column_name");
String columnType = resultSet.getString("data_type");
schemaMap.put(columnName, columnType);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return schemaMap;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,89 @@
package tools;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.core.RowMapper;
import tctable.Tools;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DBTools {
public static class JsonRowMapper implements RowMapper<String> {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> resultMap = new HashMap<>();
// Получаем метаданные ResultSet для получения названий столбцов
int columnCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = rs.getMetaData().getColumnName(i);
Object columnValue = rs.getObject(i);
resultMap.put(columnName, columnValue);
}
// Преобразовываем Map в JSON строку
try {
return objectMapper.writeValueAsString(resultMap);
} catch (Exception e) {
throw new RuntimeException("Failed to convert Map to JSON", e);
}
}
}
public static boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
if (columnName.equalsIgnoreCase(metaData.getColumnName(i))) {
return true;
}
}
return false;
}
public static String getSQLValue(String t, String v) {
//if($t=='object' && (strtoupper($v)!='NULL' && gettype($v)=='string')) $t='string'; //Если id шники uuid
if (t.equals("object") || t.equals("uid")) {
if (v.equals(""))
v = "NULL";
} else if (t.equals("i4") || t.equals("integer")) {
if (v.equals(""))
v = "NULL";
} else if (t.equals("f8")) {
if (v.equals(""))
v = "NULL";
v = Tools.replaceAll(v,",", "."); //The decimal part: point.
} else if (t.equals("f4")) {
if (v.equals(""))
v = "NULL";
v = Tools.replaceAll(v,",", "."); //The decimal part: point.
} else if (t.equals("b")) {
if (v.equals(""))
v = "NULL";
else if (v.equals("1"))
v = "true";
else if (v.equals("0"))
v = "false";
} else if (t.equals("string") || t.equals("text") || t.equals("dateTime") || t.equals("date")) {
if (v.equals("")) {
v = "NULL";
} else {
v = Tools.replaceAll(v,"'", "''");
v = "'" + v + "'";
}
} else {
v = "'" + v + "'";
}
return v;
}
}

View File

@ -0,0 +1,65 @@
//From: http://www.codejava.net/java-ee/jsp/sending-e-mail-with-jsp-servlet-and-javamail
package tools;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* A utility class for sending e-mail messages
* @author www.codejava.net
*
*/
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException
{
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
//properties.put("mail.smtp.starttls.enable","true"); STARTTLS requested but already using SSL
properties.put("mail.smtp.EnableSSL.enable","true");
properties.put("mail.smtp.socketFactory.port", port);
properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
//properties.put("mail.debug", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
//creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
//msg.setText(message);
msg.setContent(message, "text/html; charset=utf-8");
// sends the e-mail
Transport.send(msg);
}
}

View File

@ -0,0 +1,218 @@
package tools;
//import org.ccalm.main.AcceptASDCController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PreparedStatementNamed {
private static final Logger logger = LoggerFactory.getLogger(PreparedStatementNamed.class);
private class HMap{
public String name = "";
public int pos = -1;
public HMap(String name,int pos) {
this.name = name;
this.pos = pos;
}
}
private List< HMap > fields = new ArrayList< HMap >();
private PreparedStatement m_prepStmt;
public PreparedStatementNamed(Connection conn, String sql) throws SQLException {
int cnt=0;
int pos = 0;
while((pos = sql.indexOf("${")) != -1) {
int end = sql.substring(pos).indexOf("}");
if (end == -1)
end = sql.length();
else
end += pos+1;
cnt++;
fields.add(new HMap(sql.substring(pos+2,end-1),cnt));
sql = sql.substring(0, pos) + "?" + sql.substring(end); //Removing a parameter from a string
}
m_prepStmt = conn.prepareStatement(sql);
}
public void setString(String name, String value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setString(fields.get(i).pos, value);
}
}
}
public void setNULLString(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.NULL);
}
}
}
public void setInt(String name, String value) throws SQLException {
if(value==null){
setNULLInt(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setInt(fields.get(i).pos, Integer.parseInt(value));
}
}
}
}
public void setInt(String name, int value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setInt(fields.get(i).pos, value);
}
}
}
public void setNULLInt(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.INTEGER);
}
}
}
public void setBoolean(String name, String value) throws SQLException {
if(value==null){
setNULLBoolean(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
if (value.equals("0") || value.equals("false") || value.equals(""))
m_prepStmt.setBoolean(fields.get(i).pos, false);
else
m_prepStmt.setBoolean(fields.get(i).pos, true);
}
}
}
}
public void setBoolean(String name, int value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
if(value==0)
m_prepStmt.setBoolean(fields.get(i).pos, false);
else
m_prepStmt.setBoolean(fields.get(i).pos, true);
}
}
}
public void setNULLBoolean(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.BOOLEAN);
}
}
}
/*private int getIndex(String name) {
size()
} */
public void setDouble(String name, String value) throws SQLException {
if(value==null){
setNULLDouble(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setDouble(fields.get(i).pos, Double.parseDouble(value));
}
}
}
}
public void setDouble(String name, double value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setDouble(fields.get(i).pos, value);
}
}
}
public void setNULLDouble(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.DOUBLE);
}
}
}
public void setFloat(String name, String value) throws SQLException {
if(value==null){
setNULLFloat(name);
}else {
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setDouble(fields.get(i).pos, Float.parseFloat(value));
}
}
}
}
public void setFloat(String name, float value) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setFloat(fields.get(i).pos, value);
}
}
}
public void setNULLFloat(String name) throws SQLException {
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.FLOAT);
}
}
}
public void setTimestamp(String name, String value) throws SQLException {
if(value==null){
for(int i=0;i<fields.size();i++) {
if(fields.get(i).name.equals(name)) {
m_prepStmt.setNull(fields.get(i).pos,Types.DATE, null);
}
}
}else {
if(value.matches("\\d+")) //If old date format in UNIX time
{
long uDate=Long.parseLong(value)+1;
java.sql.Timestamp tm=new java.sql.Timestamp(uDate*1000);
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setTimestamp(fields.get(i).pos, tm);
}
}
}else
{
java.sql.Timestamp tm=null;
DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //2016-05-29 18:00:01 in "GMT"
try{
tm = new java.sql.Timestamp(dfm.parse(value).getTime());
} catch (Exception ex) {
logger.error("Error",ex.getMessage());
}
for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) {
m_prepStmt.setTimestamp(fields.get(i).pos, tm);
}
}
}
}
}
public PreparedStatement getPreparedStatement() {
return m_prepStmt;
}
/*public ResultSet executeQuery() throws SQLException {
return m_prepStmt.executeQuery();
}
public void close() throws SQLException {
m_prepStmt.close();
}*/
}

View File

@ -0,0 +1,39 @@
package tools;
import java.util.Iterator;
import java.util.Map;
public class STools {
public static String CutBeforeFirst(StringBuffer str,String ch)
{
int pos=str.indexOf(ch);
String result="";
if(pos==-1)
{
result.concat(str.toString());
str.delete(0,str.length());
}else
{
result=str.substring(0,pos);
str.delete(0,pos+1);
}
return result;
}
/**
* Удалить из списка по значению
* @param map
* @param value
*/
public static void delFromMapByValue(Map<String, String> map, String value) {
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (entry.getValue().equalsIgnoreCase(value)) {
iterator.remove();
}
}
}
}

View File

@ -0,0 +1,82 @@
package tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
public class Translation {
private static final Logger logger = LoggerFactory.getLogger(Translation.class);
public int language_id;
//public NamedParameterJdbcTemplate jdbcTemplate;
public Connection conn;
public Translation(String lng, Connection conn){
language_id=1;
switch (lng) {
case "kz":
case "kk":
language_id = 2;
break;
case "en":
language_id = 3;
break;
case "uz":
language_id = 4;
break;
case "ru":
default:
language_id = 1;
break;
}
this.conn = conn;
}
public String trt(String text){
boolean find = false;
String sql = """
select
translation
from
main._translations
where
del=false
and language_id=${language_id}
and identifier=${identifier};
""";
PreparedStatementNamed stmtn=null;
try {
stmtn = new PreparedStatementNamed(conn, sql);
stmtn.setInt("language_id", language_id);
stmtn.setString("identifier", text);
} catch (SQLException e) {
logger.error("Error",e);
e.printStackTrace();
}
if(stmtn!=null){
PreparedStatement stmt=stmtn.getPreparedStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery();
while (rs.next()) {
text = rs.getString(1);
find = true;
}
} catch (SQLException e) {
logger.error("Error",e);
e.printStackTrace();
}finally{
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
}
}
if(!find){
text = text.replace("_", " ");
}
return text;
}
}

View File

@ -0,0 +1,45 @@
package tools;
public class User {
public String id; //User id from database
public String name; //Name Surname Patronymic
public String language_id; //User language
public String role; //User role
public String country_id; //User role
public User()
{
id="null"; //null так как заменяю в SQL строке строку вида ${_user_id} на цифровое значение
name="___";
language_id="1";
role="___";
country_id="";
}
public User(String name)
{
super();
id="null";
this.name=name;
language_id="1";
role="___";
country_id="";
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void Logout()
{
id="null";
name="___";
language_id="1";
role="___";
country_id="";
}
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOGS" value="logs" />
<springProperty scope="context" name="appName" source="spring.application.name"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/${appName}.log</file>
<encoder>
<pattern>{"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","message":"%msg"}%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
</appender>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'} | %level | %logger{36} | %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="FILE" />
<appender-ref ref="CONSOLE" />
</root>
</configuration>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Select the file with CSV to upload and parsing.</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<form action="./AcceptCSV" method="post" enctype="multipart/form-data">
Select CSV UTF-8 file to upload and export:
<input type="file" name="file" id="fileToUpload"><br>
<input type="checkbox" name="skip" value="1">Skip first line<Br>
<input type="submit" value="Upload" name="submit">
</form>
<br><br>
${PreviewTable}
<br><br><br>
<textarea style="width: 1000px;height: 1000px;">${PreviewGEOJSON}</textarea>
<br><br><br>
<textarea style="width: 1400px;height: 1000px;">${PreviewSQL}</textarea>
</body>
</html>

View File

@ -0,0 +1,85 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="./resources/favicon.ico" />
<title>Automated system of data collection</title>
<meta name="yandex-verification" content="2cb5374be0668fe9" />
<meta name="description" content="According to the implementation of the Road Map program to improve national and regional locust control in the Caucasus and Central Asia (CCA) developed a system of monitoring and analysis designed to control locusts in the CCA using a geographic information system and remote sensing technology">
<style type="text/css">
html,body
{
height:100%;
min-height:100%;
margin:0px;
padding:0px;
text-align:center;
background-color: #f0f0f0;
}
.content
{
max-width:960px;
height:100%;
min-height:100%;
margin:0 auto;
text-align:left;
background-color: #ffffff;
}
</style>
<script type="text/javascript">
function setCookie (name, value, expires, path, domain, secure)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + expires);
expires=exdate.toUTCString()
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
if(window.location.host.indexOf('locust.kz')>=0){
window.location.href = "ccalm.org";
}
</script>
</head>
<body>
<div class='content'>
<div style="padding: 5px; background-color: #ffa100;"><table cellspacing="0" cellpadding="0" border="0" style="width: 100%"><tr><td style="width: 50px;"><a href="/"><img src="./resources/images/locust.png" style="width: 70px;"></a></td><td style="text-align: right; vertical-align: top;"><!--a href="#" onclick="setCookie ('lng', 'en', 365, '', '', ''); window.location.reload();">English</a--></td></tr></table></div>
<div style="padding: 5px;">
<h1 style="text-align: center;">Caucasus and Central Asia Locusts Management system (CCALM)</h1>
<p style="font-size: 14pt; text-indent: 25px;">
<img src="./resources/images/locust.png" align="right" style="margin: 5px;">
According to the implementation of the Road Map "program to improve national and regional locust control in the Caucasus and Central Asia (CCA)" developed a system of monitoring and analysis designed to control locusts in the CCA using a geographic information system and remote sensing technology.
</p>
<!--p style="font-size: 14pt; text-indent: 25px;">
To use the "Automated system of data collection" you have to agree to the <a href="#">terms</a> and <a href="#">sign up</a>.
<p-->
<center>
<table border="0"><tr><td style="width: 300px; padding: 20px">
<a target="_blank" href="https://play.google.com/store/apps/details?id=kz.istt.locust"><center>Automated system of data collection (ASDC)<br>
<img src="./resources/images/google_android_download.png"></center></a>
</td><td style="width: 300px; padding: 20px">
<a href="#" onclick="window.open('./engine'); return false;"><center>Caucasus and Central Asia Locusts Management system (CCALM)<br>
<img src="./resources/images/flex.png"></center></a>
</td></tr></table>
</center>
<br>
<center>For any questions contact us at tel./Fax 8(727)3967038, E-mail: <a href="mailto:info@ccalm.org">info@ccalm.org</a>.</center>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,25 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Select the file with CSV to upload and parsing.</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<form action="./AcceptJSON" method="post" enctype="multipart/form-data">
Select CSV UTF-8 file to upload and export:
<input type="file" name="file" id="fileToUpload"><br>
<input type="submit" value="Upload" name="submit">
</form>
<br><br>
${PreviewTable}
<!--br><br><br>
<textarea style="width: 1000px;height: 1000px;">${PreviewGEOJSON}</textarea>
<br><br><br>
<textarea style="width: 1400px;height: 1000px;">${PreviewSQL}</textarea-->
</body>
</html>

View File

@ -0,0 +1,169 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title th:text="${Authorization}">Authorization</title>
<link rel="icon" href="../resources/favicon.ico" type="image/x-icon">
<script type="text/javascript" src="../resources/metadata/dbms/tools.js?v=14"></script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.login-container {
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
.login-container h2 {
text-align: center;
margin-bottom: 20px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
font-weight: bold;
display: block;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
font-size: 14px;
}
.form-group a {
font-size: 12px;
color: #007bff;
text-decoration: none;
}
.form-group a:hover {
text-decoration: underline;
}
.form-group .button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
.form-group .button:hover {
background-color: #0056b3;
}
.progress-bar {
display: none;
margin-top: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="login-container">
<h2 th:text="${Authorization}">Authorization</h2>
<div>
<div class="form-group">
<label for="login0"><span th:text="${Login}">Login</span> (E-mail):</label>
<input type="text" id="login0" name="login" maxlength="50" placeholder="Введите логин или email">
</div>
<div class="form-group">
<label for="password0">Пароль:</label>
<input type="password" id="password0" name="password" maxlength="33" placeholder="Введите пароль">
</div>
<div class="form-group">
<a href="#" onclick="showRestoreForm();">Восстановление пароля</a>
</div>
<div class="form-group">
<button id="loginBtn" class="button">Войти</button>
</div>
<div class="progress-bar" id="progressBar">
<span>Загрузка...</span>
</div>
</div>
</div>
<script>
// Функция для отправки данных на сервер
function postJsonData(url, data, callback) {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => callback(true, data))
.catch(error => {
console.error('Error:', error);
callback(false, { error_message: 'Что-то пошло не так. Попробуйте еще раз.' });
});
}
// Функция для обработки авторизации
function authorizeUser() {
const login = document.getElementById('login0').value;
const password = document.getElementById('password0').value;
const obj = {
login: login,
password: password,
appid: 'ccalm'
};
// Отправляем запрос на сервер для авторизации
postJsonData('/api/authorization/v02/login', obj, (ok, data) => {
if (ok) {
if (data.error_code == 0) {
window.location.href = "/engine";
} else {
alert2(trt('Alert'), data.error_message);
}
}else{
alert2(trt('Error'),data);
}
document.getElementById('progressBar').style.display = 'none'; // Скрываем прогресс-бар
});
document.getElementById('progressBar').style.display = 'block';
}
// Функция для восстановления пароля
function showRestoreForm() {
alert('Форма восстановления пароля будет здесь!');
}
// Обработчик клика на кнопку "Войти"
document.getElementById('loginBtn').onclick = authorizeUser;
</script>
</body>
</html>

View File

@ -0,0 +1,100 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="./resources/favicon.ico" />
<title>Automated system of data collection</title>
<meta name="yandex-verification" content="2cb5374be0668fe9" />
<meta name="description" content="According to the implementation of the Road Map program to improve national and regional locust control in the Caucasus and Central Asia (CCA) developed a system of monitoring and analysis designed to control locusts in the CCA using a geographic information system and remote sensing technology">
<style type="text/css">
html,body
{
height:100%;
width:100%;
margin:0px;
padding:0px;
text-align:center;
background-color: #f0f0f0;
}
.content
{
max-width:960px;
margin:0 auto;
padding:10px;
text-align:left;
background-color: #ffffff;
}
</style>
<script type="text/javascript">
if(window.location.host.indexOf('locust.kz')>=0){
window.location.href = "https://ccalm.org";
}
if(window.location.host.indexOf('ccalm.org')>=0 && location.protocol == 'http:'){
location.href = location.href.replace(/^http:/, 'https:')
}
</script>
</head>
<body>
<div class='content'>
<h1>Политика конфиденциальности</h1>
<p align="justify">Компания ДТОО "Институт космической техники и технологий" (в дальнейшем ИКТТ) заботится о конфиденциальности данных своих клиентов. Для этих целей была разработана политика конфиденциальности, включающая правила сбора, использования, раскрытия, передачи и хранения Вашей информации. Ознакомьтесь с нашими правилами соблюдения.</p>
<h2>Сбор и использование личной информации</h2>
<p align="justify">Личной информацией являются данные, которые можно использовать для установления личности человека или для связи с ним.
Если вы обратитесь в ИКТТ, вас могут попросить предоставить личную информацию. ИКТТ использует ее в соответствии с данной политикой конфиденциальности. Эти сведения могут быть объединены с другими в целях предоставления наших товаров, услуг, материалов и рекламы. Вы не обязаны предоставлять личную информацию, которую мы запросили, но если вы ее не предоставите, во многих случаях мы не сможем предоставить вам свои товары или услуги, а также ответить на ваши запросы.
Вот несколько примеров того, какую личную информацию может собирать и использовать ИКТТ.</p>
<h2>Какую личную информацию мы собираем</h2>
<ul>
<li style="text-align: justify;">Когда вы создаете BFT ID, регистрируете свои продукты, обращаетесь для получения кредита, приобретаете продукт, связываетесь с нами или принимаете участие в онлайн-исследовании, мы можем собирать различные сведения, включая ваше имя, почтовый адрес, номер телефона, адрес электронной почты, предпочтительные способы связи, а также данные кредитной карты.</li>
<li style="text-align: justify;">Когда вы отправляете подарочные сертификаты и товары, а также приглашаете других пользователей на форумы ИКТТ, мы можем собирать предоставленную вами информацию об этих людях, включая их имена, почтовые адреса, адреса электронной почты и номера телефонов.</li>
<li style="text-align: justify;">Мы можем запросить данные удостоверения личности для рассмотрения возможности предоставления кредита или выставления платежного поручения для оплаты товаров через банковское отделение.</li>
</ul>
<h2>Как мы используем личную информацию</h2>
<ul>
<li style="text-align: justify;">Мы можем использовать личную информацию для внутренних целей, например при проведении аудита, анализа данных и исследований, направленных на улучшение продуктов и услуг, а также способов общения с клиентами.</li>
<li style="text-align: justify;">Периодически мы используем собранную личную информацию для рассылки важных уведомлений, например сообщений о покупках и об изменениях в условиях и политиках.</li>
<li style="text-align: justify;">Если вы принимаете участие в лотерее, конкурсе или аналогичном мероприятии, мы можем использовать предоставленную вами информацию при организации этих событий.</li>
</ul>
<h2>Сбор и использование информации, не являющейся личной</h2>
<p align="justify">Мы также осуществляем сбор данных, которые не указывают непосредственно на конкретного человека. Мы можем собирать, использовать, передавать и раскрывать такие сведения с любой целью. Вот несколько примеров того, какую информацию, не являющуюся личной, мы собираем и используем.</p>
<ul>
<li style="text-align: justify;">Для того чтобы лучше понимать поведение клиентов и улучшать наши продукты, услуги и рекламу, мы можем собирать такие сведения, как род деятельности, язык, почтовый индекс, телефонный код, идентификатор устройства, местоположение, в котором используется купленный товар.</li>
<li style="text-align: justify;">Мы можем также собирать информацию о том, чем интересуются пользователи на нашем веб-сайте, на официальных социальных страницах компании. Данные сведения позволяют нам предоставлять клиентам более полезную информацию, а также понять, какие разделы веб-сайта, продукты и сервисы пользуются повышенным интересом. В контексте данной политики конфиденциальности обобщенные данные рассматриваются в качестве информации, не являющейся личной.</li>
</ul>
<p align="justify">При объединении информации, не являющейся личной, с личной информацией объединенные данные будут считаться личными, пока они остаются объединенными.</p>
<h2>Раскрытие информации третьим лицам</h2>
<p align="justify">Эта информация не передается третьим лицам.</p>
<h2>Поставщики услуг</h2>
<p align="justify">ИКТТ обменивается личными данными пользователей с компаниями, которые предоставляют такие услуги, как обработка информации, выдача или продление срока кредита, выполнение заказов клиентов, доставка продуктов, управление данными клиентов и их расширение, обслуживание клиентов, оценка заинтересованности пользователей в наших продуктах и услугах, а также проведение исследований и опросов с целью определения степени удовлетворенности. Эти компании обязуются защищать ваши данные и могут быть расположены только на территории Республики Казахстан.</p>
<h2>Прочее</h2>
<p align="justify">Компания ИКТТ может быть обязана раскрыть вашу личную информацию в соответствии с законодательством, требованиями судопроизводства, судебного разбирательства или по запросу государственных органов страны вашего пребывания или других стран. Мы также можем раскрыть вашу личную информацию, если это будет необходимо в целях национальной безопасности, исполнения закона или в иных общественно важных целях.</p>
<p align="justify">Мы также можем раскрыть вашу личную информацию, если это будет необходимо для выполнения наших условий или защиты наших операций или пользователей. Кроме того, в случае реорганизации, слияния или продажи компаний мы можем передавать личные данные соответствующей третьей стороне.</p>
<h2>Защита личной информации</h2>
<p align="justify">ИКТТ очень серьезно относится к защите вашей личной информации. Онлайн-сервисы ИКТТ, такие как Корзина и Личный кабинет, защищают вашу личную информацию во время передачи при помощи шифрования, например по протоколу SSL. Для хранения вашей личной информации ИКТТ использует компьютерные системы с ограниченным доступом, расположенные в помещениях с физическими средствами охраны. Данные Личного кабинета хранятся в зашифрованном виде, в том числе при использовании сторонних хранилищ.</p>
<p align="justify">Когда вы пользуетесь некоторыми продуктами, услугами или приложениями Apple, публикуете сообщения в социальных сервисах, ведете переписку в чате, публикуемую вами личную информацию могут видеть, читать, собирать и использовать другие пользователи. Вы несете ответственность за то, какую информацию вы раскрываете в таких случаях. Например, если вы указываете свои имя и адрес электронной почты в обсуждении на форуме или блоге, такая информация становится общедоступной. Проявляйте осторожность в таких ситуациях.</p>
<h2>Целостность и хранение личной информации</h2>
<p align="justify">С помощью ИКТТ вы легко сможете обеспечить точность, полноту и актуальность своей личной информации. Мы будем хранить вашу личную информацию в течение срока, необходимого для исполнения обязательств, которые указаны в данной политике конфиденциальности, если иное не предусмотрено законом.</p>
<h2>Доступ к личной информации</h2>
<p align="justify">Вы можете помочь нам обеспечить точность, полноту и актуальность вашей контактной информации и личных предпочтений, выполнив вход в учетную запись на сайте <a href="https://ccalm.org" target="_blank">ccalm.org</a>. Что касается остальных данных, мы обеспечим вам доступ к вашей личной информации, чтобы вы, в частности, могли подать запрос об исправлении или удалении данных, кроме случаев, когда хранение информации предусмотрено законом или необходимо компании ИКТТ для осуществления деятельности в рамках действующего законодательства. Мы можем отказать в исполнении запросов, которые необоснованны либо обременительны, нарушают конфиденциальность других пользователей, не имеют смысла или доступ к которым в соответствии с локальным законодательством не является обязательным. Запросы на доступ к данным, исправление или удаление данных можно подать по электронной почте.</p>
<h2>Глобальные обязательства по конфиденциальности</h2>
<p align="justify">В целях защиты личной информации мы знакомим сотрудников ИКТТ с рекомендациями по безопасности и конфиденциальности и обеспечиваем их строгое исполнение в компании.</p>
<h2>Вопросы о конфиденциальности</h2>
<p align="justify">Если у вас возникли вопросы или сомнения по поводу политики конфиденциальности ИКТТ или обработки данных либо вы хотите сообщить о предполагаемом нарушении местных законов о конфиденциальности, свяжитесь с нами по почте info@ccalm.org. Вы можете в любой момент связаться с нами по телефону +7 (727) 229-44-81.</p>
<p align="justify"><p align="justify">Мы проверяем все обращения и стараемся отвечать на них в кратчайшие сроки. Если вы недовольны полученным ответом, направьте жалобу в соответствующий регулятивный орган своей страны. Если вы хотите получить исчерпывающую информацию о способах подать жалобу, уместных в ваших обстоятельствах, обратитесь к нам.</p>
<p align="justify">Компания ИКТТ периодически обновляет политику конфиденциальности. При изменении политики мы размещаем уведомление об этом на нашем веб-сайте вместе с новым текстом политики конфиденциальности.</p>
<p>ДТОО "Институт космической техники и технологий", Almaty, Kazakhstan</p>
</div>
</body>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Redirect</title>
<script th:inline="javascript">
window.location.href = [[${url}]];
</script>
</head>
<body>
<h1>Please wait, redirecting...</h1>
<p>If redirection did not occur, <a th:href="@{${url}}">click here</a>.</p>
</body>
</html>

View File

@ -0,0 +1,679 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="./resources/favicon.ico" />
<title>Caucasus and Central Asia Locusts Management system (CCALM)</title>
<meta name="robots" content="noindex">
<meta name="description" content="According to the implementation of the Road Map program to improve national and regional locust control in the Caucasus and Central Asia (CCA) developed a system of monitoring and analysis designed to control locusts in the CCA using a geographic information system and remote sensing technology">
<meta name="yandex-verification" content="2cb5374be0668fe9" />
<script type="text/javascript" src="./resources/metadata/jquery.js"></script>
<script type="text/javascript" src="./translation?v=7"></script>
<script src="./resources/metadata/dbms/tools.js?v=9"></script>
<link rel="stylesheet" href="./resources/engine/css/buttons.css?v=7">
<link rel="stylesheet" href="./resources/engine/normalize.css?v=7">
<link rel="stylesheet" href="./resources/metadata/dbms/dbms.css?v=7"/>
<link rel="stylesheet" href="./resources/engine/index.css?v=7">
<script type="text/javascript" src="./resources/engine/popup.js?v=03"></script>
<script type="text/javascript" src="./resources/index.js?v=01"></script>
<link rel="stylesheet" href="./resources/engine/openlayers/ol.css" type="text/css">
<link rel="stylesheet" href="./resources/engine/openlayers/ol-ext.css" />
<script src="./resources/engine/openlayers/ol.js"></script>
<script src="./resources/engine/openlayers/proj4.js"></script>
<script src="./resources/engine/openlayers/ol-ext.js"></script>
<style>
html,body
{
height:100%;
min-height:100%;
margin:0px;
padding:0px;
text-align:center;
background-color: #f0f0f0;
}
h2{
font-size: 24px;
margin-block-start: 0.10em;
margin-block-end: 0.10em;
margin-bottom: 5px;
}
h3{
font-size: 20px;
margin-block-start: 0.10em;
margin-block-end: 0.10em;
margin-bottom: 5px;
}
table {
font-weight: inherit;
}
p{
text-indent: 25px;
text-align: justify;
margin-top: 5px;
}
.content
{
max-width:980px;
/*height:100%;*/
/*min-height:100%;*/
margin:0 auto;
text-align:left;
/*background-color: #ffffff;*/
}
.app {
display: grid;
grid-column-gap: 15px;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
}
.ol-scale-line {
left: 50%;
transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0)
}
.ol-full-screen{
left: .5em;
bottom: .5em;
right:inherit;
top:inherit
}
.ol-legend > div.ol-legend {
position: relative;
left: 50%;
}
</style>
<script type="text/javascript">
var date_start=getParam('date_start',window);
var date_end=getParam('date_end',window);
if(date_start=='') date_start=(Date.now()/1000)-2592000;
if(date_end=='') date_end=Date.now()/1000;
function setCookie (name, value, expires, path, domain, secure)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + expires);
expires=exdate.toUTCString()
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
if(window.location.host.indexOf('locust.kz')>=0){
window.location.href = "https://ccalm.org";
}
if(window.location.host.indexOf('ccalm.org')>=0 && location.protocol == 'http:'){
location.href = location.href.replace(/^http:/, 'https:')
}
var g_lng = /*[[${m_locale}]]*/ '';
var g_map=null;
var m_winPP=null;
function Configure(){
let win=new TWin(false,'./resources');
win.BuildGUI(pageX-100,pageY-100);
win.setSize(300,20);
win.setCaption(trt('Configure'));
//win.showProgressBar();
win.shadow = true;
let html='<table width="100%" border="0"><tbody><tr><td style="padding: 1px; white-space: nowrap;" width="1%">From date </td><td style="padding: 1px;"><table style="width: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse;" border="0"><tbody><tr><td style="width: 100%;"><input style="width: 100%;" name="date_start" value="" id="filter_first_date_start" type="text"></td><td style="width: 25px;"><img id="filter_first_date_start_trigger" src="../resources/engine/images/datepicker.jpg" style="margin-left: 1px; cursor: pointer;"></td></tr></tbody></table></td><td style="padding: 1px; white-space: nowrap;" width="1%">To date</td><td style="padding: 1px;"><table style="width: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse;" border="0"><tbody><tr><td style="width: 100%;"><input style="width: 100%;" name="date_end" value="" id="filter_first_date_end" type="text"></td><td style="width: 25px;"><img id="filter_first_date_end_trigger" src="../resources/engine/images/datepicker.jpg" style="cursor: pointer; margin-left: 1px;"></td></tr></tbody></table></td></tr></tbody></table>';
html+='<input class="button-secondary" id="btnApply" type="button" value="'+trt('Apply')+'" style="margin: 0px 1px 0px 0px;float:right;">';
win.setContent(html);
win.setCenter();
win.hide(false);
$("#btnApply").click(function() {
let date_start="";
let input = document.getElementById('filter_first_date_start');
if(input!=null)
{
let date = new Date(input.value.replace(/-/g, "/"));
date_start=date.getTime()/1000;// - date.getTimezoneOffset()*60;
if(isNaN(date_start)) date_start='';
}
let date_end="";
input = document.getElementById('filter_first_date_end');
if(input!=null)
{
let date = new Date(input.value.replace(/-/g, "/"));
date_end=date.getTime()/1000;// - date.getTimezoneOffset()*60;
if(isNaN(date_end)) date_end='';
}
let path="./?date_start="+date_start+"&date_end="+date_end;
window.open(path, "_self");
});
}
</script>
</head>
<body>
<div style="background-color: #2694bb;">
<div class="content" style="color: #ffffff; font-size: 16px; padding-top: 15px;padding-bottom: 15px;position: relative;">
<img id="idLogo_ru" src="./resources/images/logo_en.svg" alt="" style="height:60px;cursor:pointer;display: none;" onclick="window.open('https://www.fao.org/locusts-cca/ru/', '_blank');">
<img id="idLogo_en" src="./resources/images/logo_en.svg" alt="" style="height:60px;cursor:pointer;display:none;" onclick="window.open('https://www.fao.org/locusts-cca/en/', '_blank');">
<div style="display: inline-block; position:absolute; top:5px; right: 5px;">
<a href="./?lng=3" id="lng_3" style="color:#ffffff;text-decoration:none;margin-right:15px;font-weight: bold;">English</a> <a href="./?lng=1" id="lng_1" style="color:#ffffff;text-decoration:none;font-weight: bold;">Русский</a>
<script>
document.getElementById('lng_3').addEventListener('click', function(event) {
setCookie('lng','3',365,'/');
window.location.href = event.target.href;
});
document.getElementById('lng_1').addEventListener('click', function(event) {
setCookie('lng','1',365,'/');
window.location.href = event.target.href;
});
</script>
</div>
</div>
</div>
<div style="background-color: #37390d; background-image: url('./resources/images/head.jpg'); background-repeat: no-repeat; background-position: center; height: 400; align-items: center;">
<div class="content" style="height:100%; color: #ffffff; font-size: 34px; display: flex; align-items: center; justify-content: center; position: relative;">
<div style="width: 100%;">
<div><span th:text="${Caucasus_and_Central_Asia_Locusts_Management_system}">Caucasus_and_Central_Asia_Locusts_Management_system</span> (CCALM)</div>
<div id="idInitiative_en" style="font-size: 14px; font-style: italic; display: none;">An Initiative of the Food and Agriculture Organization of the United Nations</div>
<div id="idInitiative_ru" style="font-size: 14px; font-style: italic; display: none;">По инициативе Продовольственной и сельскохозяйственной организации Объединенных Наций</div>
<script>
if(g_lng=="1")
{
document.getElementById("idLogo_ru").style.display="block";
document.getElementById("idInitiative_ru").style.display="block";
}else{
document.getElementById("idLogo_en").style.display="block";
document.getElementById("idInitiative_en").style.display="block";
}
</script>
</div>
<table style="color: #ffffff; position: absolute; bottom: 8px; right: 8px; padding: 0px;">
<tr>
<td style="text-align: center;">ASDC</td>
<td style="width: 15px;"></td>
<td style="text-align: center;">CCALM</td>
</tr>
<tr>
<td style="text-align: center;"><a target="_blank" href="https://play.google.com/store/apps/details?id=kz.istt.locust"><img src="./resources/images/google_android_download.png" style="width: 64px; height: 64px"></a></td>
<td style="width: 15px;"></td>
<td style="text-align: center;"><a href="#" onclick="window.open('./engine'); return false;"><img src="./resources/images/flex.png" style="width: 64px; height: 64px"></a></td>
</tr>
</table>
</div>
</div>
<!--div style="background-color: #2694bb;">
<div id="idSituation_en" class="content" style="display:none;color: #ffffff; font-size: 16px; padding-top: 15px;padding-bottom: 15px;">
<h2>Hazard levels as June 2023</h2>
<div style="background-color: #ff0000;color:#000000;">Situation level: DANGER in Afghanistan and Tajikistan (DMA)</div>
<div style="background-color: #ffff99;color:#000000;">Situation level: CAUTION in Turkmenistan (DMA), Azerbaijan, Georgia, Kazakhstan, Kyrgyzstan and Uzbekistan (DMA and CIT), Russian Federation (DMA, CIT and LMI), Tajikistan (CIT)</div>
<div style="background-color: #ccffcc;color:#000000;">Situation level: CALM elsewhere or for the other locust pests</div>
</div>
<div id="idSituation_ru" class="content" style="display:none;color: #ffffff; font-size: 16px; padding-top: 15px;padding-bottom: 15px;">
<h2>Уровни опасности июнь 2023г.</h2>
<div style="background-color: #ff0000;color:#000000;">Ситуация: ОПАСНАЯ в Афганистане и Таджикистане </div>
<div style="background-color: #ffff99;color:#000000;">Ситуация: ВНИМАНИЕ в Туркменистане (DMA), Азербайджане, Грузии, Казахстане, Кыргызстане и Узбекистане (DMA и CIT), Российской Федерации (DMA, CIT и LMI), Таджикистане (CIT)</div>
<div style="background-color: #ccffcc;color:#000000;">Ситуация: СПОКОЙНАЯ в других странах и для других видов саранчовых вредителей</div>
</div>
</div-->
<script>
/*if(g_lng=="1")
{
document.getElementById("idSituation_ru").style.display="block";
}else{
document.getElementById("idSituation_en").style.display="block";
}*/
</script>
<div style="background-color: #2694bb;">
<div class="content" style="color: #ffffff; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<div>
<div style="display: inline-block;">
<h2 style="display: inline-block;"><span th:text="${Locust_Data}">Locust_Data</span> <span th:text="${with}">with</span> <span id="fromdate">___</span> <span th:text="${to}">to</span> <span id="todate">___</span></h2>
</div>
<div style="display: inline-block;float: right;">
<img src="./resources/images/config.svg" alt="" style="height:30px;cursor:pointer;" th:alt="${Configure}" th:title="${Configure}" onclick="Configure();">
</div>
</div>
<script>
document.getElementById("fromdate").innerHTML = (new Date(date_start * 1000)).toDateString();
document.getElementById("todate").innerHTML = (new Date(date_end * 1000)).toDateString();
</script>
<!--div id="mapdiv" style="color: #000000; font-size: 16px; background-color: Gray; width:100%; height:600px;"></div-->
<div id="cnt_mapdiv" style="width:100%; height:600px; background-color: Gray; overflow: hidden; position: relative;">
<div id="mapdiv" style="position: absolute; color: #000000; font-size: 16px; background-color: Gray; width:100%; height:100%;"></div>
<div style="font-weight: bold; color: #000000; position: absolute; background-color: #ffffff; opacity: 0.7; right: .5em; top: .5em; left:inherit; bottom:inherit">
<table style="margin: 5px;">
<!--tr><td><img src="./resources/images/stai.svg" alt="" height="16px" width="16px"/></td><td th:text="${Swarms}">Swarms</td></tr-->
<tr><td><img src="./resources/images/imago.svg" alt="" height="16px" width="16px"/></td><td th:text="${Adult}">Adult</td></tr>
<tr><td><img src="./resources/images/lichinki.svg" alt="" height="16px" width="16px"/></td><td th:text="${Hoppers}">Hoppers</td></tr><!--tr><td><img src="./resources/images/kuligi.svg" alt="" height="16px" width="16px"/></td><td th:text="${Bands}">Bands</td></tr-->
<tr><td><img src="./resources/images/eggs.svg" alt="" height="16px" width="16px"/></td><td th:text="${Egg_pod}">Egg_pod</td></tr>
<tr><td><img src="./resources/images/spraying.svg" alt="" height="16px" width="16px"/></td><td th:text="${Spraying}">Spraying</td></tr>
<tr><td><img src="./resources/images/point.svg" alt="" height="16px" width="16px"/></td><td th:text="${Not_infected}">Not_infected</td></tr>
</table>
</div>
</div>
</div>
</div>
<script>
// Style function
function getFeatureStyle (feature) {
var st= [];
// Shadow style
st.push (new ol.style.Style ({
image: new ol.style.Shadow ({
radius: 15
})
}));
var st1= [];
// Font style
st.push ( new ol.style.Style ({
image: new ol.style.FontSymbol({
form: "marker",
glyph: 'fa-car',
radius: 15,
offsetY: -15,
fontSize: .7,
color: '#fff',
fill: new ol.style.Fill ({
color: 'blue'
}),
stroke: new ol.style.Stroke ({
color: '#fff',
width: 2
})
}),
stroke: new ol.style.Stroke ({
width: 5,
color: '#f00'
}),
fill: new ol.style.Fill ({
color: [255, 0, 0, 0.6]
})
}));
return st;
}
var g_Layouts = new Object();
g_Layouts["OpenStreetMap"] = new ol.source.XYZ({
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
,attributions: [
'© OpenStreetMap',
'<a href="https://www.openstreetmap.org/copyright">Terms of Use.</a>'
]
});
var g_Tile = new ol.layer.Tile({source:g_Layouts["OpenStreetMap"]});
var g_vectorSource = new ol.source.Vector({});
var g_vectorLayer = new ol.layer.Vector({source: g_vectorSource,zIndex: 100});
g_map = new ol.Map({
interactions: ol.interaction.defaults({ doubleClickZoom:false, mouseWheelZoom:false }),
target: 'mapdiv',
controls: ol.control.defaults().extend([
new ol.control.ScaleLine(),
new ol.control.ZoomSlider(),
new ol.control.FullScreen()
]),
/*controls: ol.control.defaults({ attribution: false }).extend([attribution]),*/
layers: [
g_Tile,
g_vectorLayer,
],
view: new ol.View({
center: ol.proj.fromLonLat([55 ,45]),
zoom: 4
})
});
// Change mouse cursor when over marker
g_map.on('pointermove', function(evt)
{
let elm=g_map.getTargetElement();
if(elm!=null)
{
var feature = g_map.forEachFeatureAtPixel(evt.pixel,function(feature) {return feature;});
if (feature)
elm.style.cursor = 'pointer';
else
elm.style.cursor = '';
}
});
// display popup on click
g_map.on('click', function(evt){
let coordinate = evt.coordinate;
//var hdms = ol.coordinate.toStringHDMS(ol.proj.transform( coordinate, 'EPSG:3857', 'EPSG:4326'));
//$(element).popover('destroy');
//popup.setPosition(coordinate);
//$(popup.getElement()).show();
var feature = g_map.forEachFeatureAtPixel(evt.pixel,function(feature) {return feature;});
if(feature)
{
if(feature.userType==4)
{
if(m_winPP!=null) m_winPP.Close();
m_winPP=new TWin(false,'./resources');
m_winPP.BuildGUI(pageX-100,pageY-100);
m_winPP.setSize(640,200);
m_winPP.setCaption(trt("Spray_monitoring") + ' "' + feature.userName + '".');
m_winPP.setCenter();
callFrmLocustDelDataPopupInterface(feature.userID);
}else
{
if(m_winPP!=null) m_winPP.Close();
m_winPP=new TWin(false,'./resources');
m_winPP.BuildGUI(pageX-100,pageY-100);
m_winPP.setSize(640,200);
m_winPP.setCaption(trt("Locust_survey") + ' "' + feature.userName + '".');
m_winPP.setCenter();
callFrmLocustDataPopupInterface(feature.userID);
}
/*if(feature.userData !== undefined && (feature.userData.type=="Product2" || feature.userData.type=="Product3" || feature.userData.type=="Product2r" || feature.userData.type=="Product3r"))
{
if(feature.userData.percent!='')
new TChartFRMLocustInfo(feature.userData);
else
alert(trt('No_data')+'!');
}
if(feature.userData.type=="Product4" || feature.userData.type=="Product4r")
{
if(feature.userData.percent!='')
{
var win = new TWin(false,'./resources');
win.BuildGUI(pageX,pageY);
win.setCaption(trt('Data'));
win.setSize("220px","100px");
win.setCenter();
win.setContent(feature.userData.text);
win.hide(false);
}else
alert(trt('No_data')+'!');
}*/
}
});
/*
// Vector layer
var vector = new ol.layer.Vector({
source: new ol.source.Vector(),
style: getFeatureStyle
})
g_map.addLayer(vector);
f0 = new ol.Feature(new ol.geom.Point( [269914, 6248592]));
vector.getSource().addFeature(f0);
// Define a new legend
var legend = new ol.control.Legend({
title: 'Legend',
style: getFeatureStyle,
collapsed: false
});
g_map.addControl(legend);
legend.on('select', function(e) {
if (e.index >= 0) log.info('You click on row: '+e.title+' ('+e.index+')');
else log.info('You click on the title: '+e.title);
});
legend.addRow({ title: 'Car placemark', feature: f0 });
*/
//select id,locust_populated,ST_SetSRID(ST_MakePoint(lon1, lat1),4326) from main.frmlocust where del=false and locust_populated>0 and date>'2022-01-01'
callDataIndex(date_start,date_end);
</script>
<div style="background-color: #ffffff;">
<div id="idBulletin_en" class="content" style="display:none;color:#000000;font-size:24px;padding-top: 15px;padding-bottom: 15px;">
<h2>Regional monthly bulletins on locusts</h2>
<div style="cursor: pointer;" onclick="window.open('https://www.fao.org/locusts-cca/current-situation/en/', '_blank');">
<img src="./resources/images/byulleten.jpg" alt="Byulleten" style="width: 100px; float: left; box-shadow: 0 0 5px rgba(0,0,0,0.5);margin: 10px;">
<div style="color: #0d6cac;">No. 89 June, 2023</div>
<strong>General Situation during May 2023 Forecast for June 2023</strong>
<p>Moroccan Locust (DMA) fledging, mating and egglaying started in most areas of Central Asia (CA), with swarm flights, including across borders, reported in southern parts. The situation was critical in Afghanistan and Tajikistan in...</p>
<div style="text-align: right;"><a href="https://www.fao.org/locusts-cca/current-situation/en/" target="_blank"><span th:text="${Data_source}">Data_source</span> >>></a></div>
</div>
</div>
<div id="idBulletin_ru" class="content" style="display:none;color:#000000;font-size:24px;padding-top: 15px;padding-bottom: 15px;">
<h2>Региональные ежемесячные бюллетени по саранче</h2>
<div style="cursor: pointer;" onclick="window.open('https://www.fao.org/locusts-cca/bulletins/ru/', '_blank');">
<img src="./resources/images/byulleten.jpg" alt="Byulleten" style="width: 100px; float: left; box-shadow: 0 0 5px rgba(0,0,0,0.5);margin: 10px;">
<div style="color: #0d6cac;">№ 89 июнь 2023 г.</div>
<strong>Общая ситуация в мае 2023 г. Прогноз на июнь 2023 г.</strong>
<p>Окрыление, спаривание и яйцекладка мароккской саранчи (DMA) начались в большинстве районов Центральной Азии (ЦА), перелеты стай, в...</p>
<div style="text-align: right;"><a href="https://www.fao.org/locusts-cca/bulletins/ru/" target="_blank"><span th:text="${Data_source}">Data_source</span> >>></a></div>
</div>
</div>
</div>
<script>
if(g_lng=="1")
{
document.getElementById("idBulletin_ru").style.display="block";
}else{
document.getElementById("idBulletin_en").style.display="block";
}
</script>
<div style="background-color: #dedcdc;">
<div class="content" style="color: #000000; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<h2 th:text="${ASDC_Field_Data}">ASDC_Field_Data</h2>
<div class="app" style="font-size: 14px;text-align: center;">
<div style="cursor:pointer; height: 200px; margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpSurvey();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/swarms400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff;width:100%;height:50px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);" th:text="${Locust_survey}">Locust_survey</div></div>
</div>
<div style="cursor:pointer; height: 200px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpSpray();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/shell400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff;width:100%;height:50px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);" th:text="${Spray_monitoring}">Spray_monitoring</div></div>
</div>
<div style="cursor:pointer; height: 200px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpSafety();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/environment400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff;width:100%;height:50px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);" th:text="${Safety_and_environment}">Safety_and_environment</div></div>
</div>
</div>
</div>
</div>
<div style="background-color: #dedcdc;">
<div class="content" style="color: #000000; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<h2 th:text="${CALM_and_other_data}">CALM_and_other_data</h2>
<div class="app" style="font-size: 14px;text-align: center;">
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpSoil();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/soil400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;" th:text="${Soil_temperature_at_a_depth_of_10_cm}">Soil_temperature_at_a_depth_of_10_cm</div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpAir();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/air400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;" th:text="${Air_temperature_2m_above_the_ground}">Air_temperature_2m_above_the_ground</div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpPre();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/precipitation400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;" th:text="${Accumulated_precipitation_in_24_hours}">Accumulated_precipitation_in_24_hours</div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpSel();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/sel400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;" th:text="${Hydrothermal_coefficient_of_Selyaninov}">Hydrothermal_coefficient_of_Selyaninov</div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpNDVI();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/ndvi400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;"><strong>NDVI</strong> <span th="${Normalized_difference_vegetation_index}">Normalized_difference_vegetation_index</span></div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpIVI();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/ivi400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;"><strong>IVI</strong> <span th="${Integral_vegetation_index}">Integral_vegetation_index</span></div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpNDWI();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/ndwi400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;"><strong>NDWI</strong> <span th="${Normalized_difference_water_index}">Normalized_difference_water_index</span></div></div>
</div>
<div style="cursor:pointer; height: 210px; background-color: #ffffff;margin-top:5px;margin-bottom:5px;box-shadow: 0 0 10px rgba(0,0,0,0.5);border-radius: 10px;" onclick="showPopUpNDSI();">
<div style="border-radius: 10px 10px 0px 0px; background-color: #aaa9a9; background-image: url('./resources/images/ndsi400.jpg'); background-repeat: no-repeat; background-position: center; width: 100%; height: 150px;"></div>
<div style="border-radius: 0px 0px 10px 10px; background-color: #ffffff; width: 100%; height: 60px;position:relative;"><div style="position:absolute;top:50%;left:50%;-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width:100%;"><strong>NDSI</strong> <span th="${Normalised_difference_snow_index}">Normalised_difference_snow_index</span></div></div>
</div>
</div>
</div>
</div>
<!--div style="background-color: #ffffff;">
<div id="idCCALM_en" class="content" style="display:none;color:#000000;font-size:24px;padding-top: 15px;padding-bottom: 15px; height: 350;">
<iframe style="float: right;" width="560" height="315" src="https://www.youtube.com/embed/5kdXRocsOkQ?controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<div id="idCCALM_ru" class="content" style="display:none;color:#000000;font-size:24px;padding-top: 15px;padding-bottom: 15px; height: 350;">
<iframe style="float: right;" width="560" height="315" src="https://www.youtube.com/embed/qchZtE3atNA?controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div-->
<script>
if(g_lng=="1")
{
//document.getElementById("idCCALM_ru").style.display="block";
}else{
//document.getElementById("idCCALM_en").style.display="block";
}
</script>
<div style="background-color: #2694bb;">
<div id="idMain_en" class="content" style="display:none; color: #ffffff; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<p>A Locust Geographic Information System (GIS), entitled <strong>“Caucasus and Central Asia Locust Management system” (CCALM)</strong>, was developed to the benefit of the ten CCA countries participating in the FAO “Programme to improve national and regional locust management in Caucasus and Central Asia (CCA),” under Result 3 of its Roadmap “Locust issues and disasters better anticipated and mitigated” and more specifically Activity 3.3 “Develop monitoring and analyzing systems”. CCALM is filled using the Automated System for Data Collection (ASDC), satellite products and other sources. Its purpose is to improve data analysis as well as forecasting and reporting at the national and regional levels.</p>
<p>
<strong>The Automated System of Data Collection (ASDC)</strong>
<iframe style="float: right; border: 10px solid #2694bb;" width="460" height="260" src="https://www.youtube.com/embed/5kdXRocsOkQ?controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
was created in 2013 in order to facilitate collection and sharing of standardized locust data. It simulates the FAO standard “Locust Survey Form” and “Spray Monitoring Form” for CCA and serves as basic data for the locust GIS in CCA. After ASDC first testing by Georgia, Uzbekistan and Russia in 2014-2015, the system was endorsed by CCA countries (October 2015), finalized and made available in eleven languages (Armenian, Azeri, Dari, English, Georgian, Kazakh, Kyrgyz, Russian, Tajik, Turkmen and Uzbek) in 2016/2017 for use on tablets, smartphones and computers.
</p>
<p>CCALM basic functions (data import, query, display, output), i.e. the database and its management system, were developed by the Institute of Space Technique and Technologies (ISTT), Almaty, Kazakhstan, and launched in early 2016. Based on the technical specifications proposed by CCA Forecasting and FAO Experts, the advanced functions (summary, analysis and forecast algorithms) were developed by ISTT in line with the technical standards of FAO. They include a the set of output products for analyzing Italian (CIT), Moroccan (DMA) and Asian Migratory (LMI) locusts data and elaborating forecasts. Among them, there are maps of: (a) locust densities, (b) treated areas, (c) areas infested (or treated) with densities above the Economic Threshold (ET). CCALM is fully available since March 2017 in two languages, English and Russian, at ccalm.org.</p>
</div>
<div id="idMain_ru" class="content" style="display:none; color: #ffffff; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<p>Географическая Информационная Система (ГИС) по Саранчовым, озаглавленная как <strong>«Система управления саранчовыми на Кавказе и в Центральной Азии” (CCALM - Caucasus and Central Asia Locust Management system)</strong>, разрабатывается в интересах десяти стран КЦА, участвующих в программе ФАО по улучшению национальной и региональной борьбы с саранчой на Кавказе и в Центральной Азии (КЦА) по Результату 3 Дорожной карты реализации “Саранчовые вспышки лучше прогнозируются и их катастрофичность снижается" и, более конкретно, Мероприятию 3.3 “Разработать мониторинговые и анализирующие системы”. База данных CCALM наполняется при помощи Автоматизированной системы сбора данных (ASDC) и других источников спутниковой продукции. Ее цель - улучшить анализ данных, а также прогнозирование и отчетность на национальном и региональном уровнях.</p>
<p>
<strong>Автоматизированная Система Сбора Данных (ASDC Automated System for Data Collection)</strong>
<iframe style="float: right; border: 10px solid #2694bb;" width="460" height="260" src="https://www.youtube.com/embed/qchZtE3atNA?controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
была создана в 2013 году для облегчения сбора и совместного использования стандартизированных данных по саранчовым. Она имитирует стандартные формы ФАО для обследования угодий на заселенность и по борьбе с саранчой и служит основой создаваемой ГИС по Саранчовым в КЦА. После тестирования ASDC Грузией, Российской Федерацией и Узбекистаном в 2014-2015 гг., система была одобрена странами КЦА (октябрь 2015 г.), ее создание было завершено, и она стала доступна на одиннадцати языках (азербайджанском, английском, армянском, дари, грузинском, казахском, киргизском, русском, таджикском, туркменском и узбекском) в 2016-2017 гг. для использования на планшетах, смартфонах и компьютерах.
</p>
<p>CCALM основные функции (импорт данных, запрос, отображение, вывод), т.е. база данных и система управления базой данных были разработаны Институтом космической техники и технологий (ИКТТ), г. Алматы, Казахстан, и запущены в начале 2016 г. На основе технических спецификаций, разработанных и согласованных с экспертами КЦА по прогнозированию совместно с экспертами ФАО, расширенные функции (сводка, анализ, алгоритмы прогноза) были разработаны ИКТТ в соответствии с техническими стандартами ФАО. Они включают ряд выходных продуктов, предназначенных для анализа данных по итальянскому прусу (CIT), мароккской саранче (DMA) и азиатской перелетной саранче (LMI) и подготовки прогнозов. Среди них есть карты: (a) плотности саранчовых, (b) обработанных территорий, (c) территорий, заселенных (или обработанных) с плотностью выше экономического порога вредоносности (ЭПВ). CCALM полностью доступен с марта 2017 года на двух языках, английском и русском, по адресу ccalm.org.</p>
</div>
</div>
<script>
if(g_lng=="1")
{
document.getElementById("idMain_ru").style.display="block";
}else{
document.getElementById("idMain_en").style.display="block";
}
</script>
<div style="background-color: #dedcdc;">
<div class="content" style="color: #000000; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<table style="width: 100%;">
<tr>
<td style="text-align: center;">
<h3 th:text="ASDC_User_Guides">ASDC_User_Guides</h3>
<a href="./resources/engine/help/ASDC_for_Android_ENG.pdf" target="_blank">ASDC_for_Android_ENG_v2.23.pdf</a><br/>
<a href="./resources/engine/help/ASDC_for_Android_RUS.pdf" target="_blank">ASDC_for_Android_RUS_v2.23.pdf</a>
</td>
<td style="text-align: center;">
<h3 th:text="${CCALM_User_Guides}">CCALM_User_Guides</h3>
<a href="./resources/engine/help/CCALM_help_ENG.pdf" target="_blank">CCALM_help_ENG_v3.3.pdf</a><br/>
<a href="./resources/engine/help/CCALM_help_RUS.pdf" target="_blank">CCALM_help_RUS_v3.4.pdf</a>
</td>
</tr>
</table>
</div>
</div>
<!--div id="idAppeal_ru" style="background-color: #ffffff; display: none;">
<div class="content" style="color: #000000; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<h2>Призыв ФАО к быстрому реагированию</h2>
<p>Пустынная саранча представляет собой беспрецедентный риск для продовольственной безопасности и экономической ситуации. За последние несколько лет последовавшие друг за другом потрясения - в том числе засуха, наводнения, макроэкономические кризисы и вооруженные конфликты - способствовали значительному уровню дестабилизации. Необходимо приложить все усилия, чтобы нынешний всплеск не превратился в полноценное бедствие.</p>
<div style="text-align: right;"><a href="mailto:AGP-Director@fao.org?Subject=Donation%20for%20the%20Desert%20Locust%20Crisis" style="background-color: #B22222; color:white;padding: 10px;box-shadow: 0 0 5px rgba(0,0,0,0.5);" th:text="${Donate_Now}">Donate_Now</a></div>
<br>
</div>
</div>
<div id="idAppeal_en" style="background-color: #ffffff; display: none;">
<div class="content" style="color: #000000; font-size: 24px; padding-top: 15px;padding-bottom: 15px;">
<h2>FAO's Appeal for Rapid Response</h2>
<p>The Desert Locust poses an unprecedented risk to food security and economic conditions. Over the past several years, successive shocks - including droughts, floods, macroeconomic crises and armed conflicts - have contributed to significant levels of destabilization. Every effort must be made to ensure that the current surge does not turn into a full-fledged disaster.</p>
<div style="text-align: right;"><a href="mailto:AGP-Director@fao.org?Subject=Donation%20for%20the%20Desert%20Locust%20Crisis" style="background-color: #B22222; color:white;padding: 10px;box-shadow: 0 0 5px rgba(0,0,0,0.5);" th:text="${Donate_Now}">Donate_Now</a></div>
<br>
</div>
</div-->
<script>
/*
if(g_lng=="1")
{
document.getElementById("idAppeal_ru").style.display="block";
}else{
document.getElementById("idAppeal_en").style.display="block";
}
*/
</script>
<div style="background-color: #2694bb;">
<div id="idContact_en" class="content" style="display:none;color:#ffffff;font-size:16px;padding-top:15px;padding-bottom: 15px; text-align: center;">
For any questions, please contact us by email: <a href="mailto:info@ccalm.org" style="color: #fafaff;">info@ccalm.org</a>.
</div>
<div id="idContact_ru" class="content" style="display:none;color:#ffffff;font-size:16px; padding-top:15px;padding-bottom: 15px; text-align: center;">
По всем вопросам обращайтесь к нам по электронной почте: <a href="mailto:info@ccalm.org" style="color: #fafaff;">info@ccalm.org</a>.
</div>
</div>
<script>
if(g_lng=="1")
{
document.getElementById("idContact_ru").style.display="block";
}else{
document.getElementById("idContact_en").style.display="block";
}
</script>
</body>
</html>

View File

@ -0,0 +1,30 @@
//В tools.js функция trt(key) есть
function _(key)
{
if(key==null || key===undefined) return '';
let val=g_translations[key];
if(val==null || val===undefined)
{
for(let item in g_translations) {
if(item.toLowerCase()==key.toLowerCase())
{
val=g_translations[item];
break;
}
}
}
if(val==null || val===undefined) return key.replace(/_/g, ' ');
else return val;
}
function __(key)
{
var val=g_translations[key];
if(val===undefined) return key.replace(/_/g, ' ');
else return val;
}
var g_translations = {
'':''
[[${keys}]]
};

View File

@ -0,0 +1,13 @@
package org.ccalm.main;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MainApplicationTests {
@Test
void contextLoads() {
}
}