From 63e708151654d25f43253ab6d3c4c345726dc01d Mon Sep 17 00:00:00 2001 From: igor Date: Mon, 9 Dec 2024 20:59:06 +0600 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B2=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 40 + Jenkinsfile | 60 + mvnw | 308 ++ mvnw.cmd | 205 + org_ccalm_main.properties | 35 + pom.xml | 155 + qodana.yaml | 31 + .../org/ccalm/main/AcceptASDCController.java | 3421 +++++++++++++++++ src/main/java/org/ccalm/main/AcceptEXCEL.java | 402 ++ src/main/java/org/ccalm/main/AcceptJSON.java | 1478 +++++++ src/main/java/org/ccalm/main/DataJSON.java | 177 + .../java/org/ccalm/main/DownloadNDVI.java | 364 ++ .../java/org/ccalm/main/DownloadWeather.java | 441 +++ src/main/java/org/ccalm/main/GeoGSON.java | 251 ++ src/main/java/org/ccalm/main/Integration.java | 746 ++++ .../java/org/ccalm/main/MainApplication.java | 14 + .../java/org/ccalm/main/MainController.java | 326 ++ src/main/java/org/ccalm/main/Products.java | 1059 +++++ src/main/java/org/ccalm/main/QGIS.java | 491 +++ src/main/java/org/ccalm/main/SendMail.java | 481 +++ .../org/ccalm/main/SessionController.java | 41 + src/main/java/org/ccalm/main/TestFiles.java | 184 + .../org/ccalm/main/TranslationController.java | 151 + .../java/org/ccalm/main/WeatherDownload.java | 128 + .../ccalm/main/engine/EngineController.java | 528 +++ .../org/ccalm/main/login/LoginController.java | 72 + .../org/ccalm/main/recReq/ExistsType.java | 8 + .../java/org/ccalm/main/recReq/RecReq.java | 21 + src/main/java/tctable/Point.java | 14 + src/main/java/tctable/TCField.java | 574 +++ src/main/java/tctable/TCTable.java | 200 + src/main/java/tctable/TCTableTools.java | 74 + src/main/java/tctable/Tools.java | 2529 ++++++++++++ src/main/java/tools/DBTools.java | 89 + src/main/java/tools/EmailUtility.java | 65 + .../java/tools/PreparedStatementNamed.java | 218 ++ src/main/java/tools/STools.java | 39 + src/main/java/tools/Translation.java | 82 + src/main/java/tools/User.java | 45 + src/main/resources/logback-spring.xml | 31 + .../resources/templates/engine/index.html | 2020 ++++++++++ src/main/resources/templates/excel.html | 26 + src/main/resources/templates/index.html | 85 + src/main/resources/templates/json.html | 25 + src/main/resources/templates/login/login.html | 169 + src/main/resources/templates/privacy.html | 100 + src/main/resources/templates/redirect.html | 14 + src/main/resources/templates/test.html | 679 ++++ src/main/resources/templates/translation.html | 30 + .../org/ccalm/main/MainApplicationTests.java | 13 + 50 files changed, 18739 insertions(+) create mode 100644 .gitignore create mode 100644 Jenkinsfile create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 org_ccalm_main.properties create mode 100644 pom.xml create mode 100644 qodana.yaml create mode 100644 src/main/java/org/ccalm/main/AcceptASDCController.java create mode 100644 src/main/java/org/ccalm/main/AcceptEXCEL.java create mode 100644 src/main/java/org/ccalm/main/AcceptJSON.java create mode 100644 src/main/java/org/ccalm/main/DataJSON.java create mode 100644 src/main/java/org/ccalm/main/DownloadNDVI.java create mode 100644 src/main/java/org/ccalm/main/DownloadWeather.java create mode 100644 src/main/java/org/ccalm/main/GeoGSON.java create mode 100644 src/main/java/org/ccalm/main/Integration.java create mode 100644 src/main/java/org/ccalm/main/MainApplication.java create mode 100644 src/main/java/org/ccalm/main/MainController.java create mode 100644 src/main/java/org/ccalm/main/Products.java create mode 100644 src/main/java/org/ccalm/main/QGIS.java create mode 100644 src/main/java/org/ccalm/main/SendMail.java create mode 100644 src/main/java/org/ccalm/main/SessionController.java create mode 100644 src/main/java/org/ccalm/main/TestFiles.java create mode 100644 src/main/java/org/ccalm/main/TranslationController.java create mode 100644 src/main/java/org/ccalm/main/WeatherDownload.java create mode 100644 src/main/java/org/ccalm/main/engine/EngineController.java create mode 100644 src/main/java/org/ccalm/main/login/LoginController.java create mode 100644 src/main/java/org/ccalm/main/recReq/ExistsType.java create mode 100644 src/main/java/org/ccalm/main/recReq/RecReq.java create mode 100644 src/main/java/tctable/Point.java create mode 100644 src/main/java/tctable/TCField.java create mode 100644 src/main/java/tctable/TCTable.java create mode 100644 src/main/java/tctable/TCTableTools.java create mode 100644 src/main/java/tctable/Tools.java create mode 100644 src/main/java/tools/DBTools.java create mode 100644 src/main/java/tools/EmailUtility.java create mode 100644 src/main/java/tools/PreparedStatementNamed.java create mode 100644 src/main/java/tools/STools.java create mode 100644 src/main/java/tools/Translation.java create mode 100644 src/main/java/tools/User.java create mode 100644 src/main/resources/logback-spring.xml create mode 100644 src/main/resources/templates/engine/index.html create mode 100644 src/main/resources/templates/excel.html create mode 100644 src/main/resources/templates/index.html create mode 100644 src/main/resources/templates/json.html create mode 100644 src/main/resources/templates/login/login.html create mode 100644 src/main/resources/templates/privacy.html create mode 100644 src/main/resources/templates/redirect.html create mode 100644 src/main/resources/templates/test.html create mode 100644 src/main/resources/templates/translation.html create mode 100644 src/test/java/org/ccalm/main/MainApplicationTests.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a454ae --- /dev/null +++ b/.gitignore @@ -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 diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..f3e1264 --- /dev/null +++ b/Jenkinsfile @@ -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.' + } + } +} diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..66df285 --- /dev/null +++ b/mvnw @@ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/mvnw.cmd @@ -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% diff --git a/org_ccalm_main.properties b/org_ccalm_main.properties new file mode 100644 index 0000000..be669b4 --- /dev/null +++ b/org_ccalm_main.properties @@ -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/ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6816c9f --- /dev/null +++ b/pom.xml @@ -0,0 +1,155 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.4 + + + org.ccalm + main + 0.0.1-SNAPSHOT + main + main + + 21 + + + + + unidata + Unidata UCAR Repository + https://artifacts.unidata.ucar.edu/content/repositories/unidata-releases/ + + + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + 3.3.3 + + + org.springframework.boot + spring-boot-starter-web + 3.3.3 + + + org.springframework.boot + spring-boot-starter-test + test + 3.3.3 + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + org.postgresql + postgresql + runtime + + + org.json + json + 20231013 + + + javax.mail + mail + 1.4 + + + org.apache.commons + commons-io + 1.3.2 + + + + net.logstash.logback + logstash-logback-encoder + 6.6 + + + + edu.ucar + netcdfAll + 5.3.1 + + + org.gdal + gdal + 2.4.0 + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.7.1 + + + + io.jsonwebtoken + jjwt-api + 0.11.2 + + + io.jsonwebtoken + jjwt-impl + 0.11.2 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.2 + runtime + + + org.springframework + spring-jdbc + 6.1.12 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + org.ccalm.main.MainApplication + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + file:application.properties + + + + + + + + diff --git a/qodana.yaml b/qodana.yaml new file mode 100644 index 0000000..962f7de --- /dev/null +++ b/qodana.yaml @@ -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: + +#Disable inspections +#exclude: +# - name: +# paths: +# - + +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 can be found at https://plugins.jetbrains.com) + +#Specify Qodana linter for analysis (Applied in CI/CD pipeline) +linter: jetbrains/qodana-jvm:2024.3 diff --git a/src/main/java/org/ccalm/main/AcceptASDCController.java b/src/main/java/org/ccalm/main/AcceptASDCController.java new file mode 100644 index 0000000..32065c2 --- /dev/null +++ b/src/main/java/org/ccalm/main/AcceptASDCController.java @@ -0,0 +1,3421 @@ +package org.ccalm.main; + +import java.io.*; +//import java.io.FileInputStream; +import java.nio.charset.StandardCharsets; +//import java.io.OutputStream; +//import java.io.UnsupportedEncodingException; +//import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +//import java.util.zip.CRC32; +//import java.util.zip.Checksum; + +//import javax.servlet.ServletContext; +//import javax.servlet.http.HttpServletResponse; +//import javax.servlet.http.Part; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletResponse; +import org.ccalm.main.recReq.ExistsType; +import org.json.JSONObject; +//import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.FileSystemResource; +//import org.springframework.core.io.FileSystemResource; +import org.springframework.stereotype.Controller; +//import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.*; +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.Node; + +import org.xml.sax.InputSource; +import tctable.TCField; +import tctable.TCTable; +import tctable.TCTableTools; +import tctable.Tools; +import tools.PreparedStatementNamed; +import tools.STools; + +@Controller +public class AcceptASDCController implements ServletContextAware { + + private static final Logger logger = LoggerFactory.getLogger(AcceptASDCController.class); + private ServletContext context; + + public static final String md5(final String str) + { + try { + // Create MD5 Hash + MessageDigest digest = java.security.MessageDigest + .getInstance("MD5"); + digest.update(str.getBytes()); + byte messageDigest[] = digest.digest(); + + // Create Hex String + StringBuffer hexString = new StringBuffer(); + for (int i = 0; i < messageDigest.length; i++) { + String h = Integer.toHexString(0xFF & messageDigest[i]); + while (h.length() < 2) + h = "0" + h; + hexString.append(h); + } + return hexString.toString(); + + } catch (NoSuchAlgorithmException ex) { + logger.error("Error",ex); + } + return ""; + } + /*public String MD5(String md5) { + try { + java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); + byte[] array = md.digest(md5.getBytes()); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < array.length; ++i) { + sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); + } + return sb.toString(); + } catch (java.security.NoSuchAlgorithmException e) { + } + return ""; + }*/ + + private static List extractXMLDocuments(String content) { + List documents = new ArrayList<>(); + String startTag1 = ""; + String startTag2 = ""; + String endTag = ""; + + int startIndex = 0; + + while (true) { + int start1 = content.indexOf(startTag1, startIndex); + int start2 = content.indexOf(startTag2, startIndex); + int start = (start1 == -1) ? start2 : ((start2 == -1) ? start1 : Math.min(start1, start2)); + + if (start == -1) break; + + int end = content.indexOf(endTag, start) + endTag.length(); + if (end == -1) break; + + documents.add(content.substring(start, end)); + startIndex = end; + } + + return documents; + } + + //Update lon lat + @RequestMapping(value = "/update",method = { RequestMethod.GET }) + @ResponseBody + public Object update_lon_lat() { + JSONObject result = new JSONObject(); + result.put("error_code", 0); + result.put("error_message", ""); + + 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 ex) { + ex.printStackTrace(); + logger.error("Error load org_ccalm_main.properties",ex); + } + + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + try { + Statement sttTZ = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sttTZ.executeUpdate("SET TIME ZONE 'UTC';"); + sttTZ.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + // Чтение файла + BufferedReader reader = new BufferedReader(new FileReader("O:\\temp\\Новая папка\\errors.log")); + StringBuilder content = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + content.append(line); + content.append("\n"); + } + reader.close(); + + // Получаем список XML документов + List xmlDocuments = extractXMLDocuments(content.toString()); + + // Парсим каждый документ и выводим первый узел + for (String xml : xmlDocuments) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(new InputSource(new StringReader(xml))); + + Element reqNode = document.getDocumentElement(); + + String uid=getCdataValue(reqNode,"uid"); + System.out.println("uid = "+uid); + + String lat1=getCdataValue(reqNode, "lat1"); + if(lat1==null) { lat1=getCdataValue(reqNode, "lat"); } + String lon1=getCdataValue(reqNode, "lon1"); + if(lon1==null) { lon1=getCdataValue(reqNode, "lon"); } + + String lat_center=getCdataValue(reqNode, "lat_center"); + if(lat_center==null) { lat_center=lat1; } + String lon_center=getCdataValue(reqNode, "lon_center"); + if(lon_center==null) { lon_center=lon1; } + + if(lat_center!=null) { + String sql = "update main.frmlocust set lat_center=?,lon_center=? where lat_center is null and uid=?"; + PreparedStatement stmt = conn.prepareStatement(sql); + stmt.setDouble(1, Double.parseDouble(lat_center)); + stmt.setDouble(2, Double.parseDouble(lon_center)); + stmt.setString(3, uid); + try { + boolean isResultSet = stmt.execute(); + if (!isResultSet) { + int affectedRows = stmt.getUpdateCount(); + System.out.println("Number of affected rows: " + affectedRows); + } else { + System.out.println("The executed statement returned a ResultSet."); + } + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + stmt.close(); + } + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + } catch (Exception ex) { + ex.printStackTrace(); + logger.error("Error",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + }finally { + try{ if(conn!=null) conn.close(); }catch(Exception e){} + } + + return result.toString(); + } + + //Save or update your health questionnaire + @RequestMapping(value = "/asdc/frmlocusthealth/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/json") + @ResponseBody + public Object uploadFrmLocustHealth(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) { + JSONObject result = new JSONObject(); + result.put("error_code", 0); + result.put("error_message", ""); + + 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 ex) { + ex.printStackTrace(); + logger.error("Error load org_ccalm_main.properties",ex); + } + + String uid=null; + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + try { + Statement sttTZ = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sttTZ.executeUpdate("SET TIME ZONE 'UTC';"); + sttTZ.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + //Parse JSON request + String jsonStr = "{}"; + if(reqData!=null) + jsonStr = new String(reqData, StandardCharsets.UTF_8); + else + throw new Exception("No JSON input data!"); + + JSONObject jsonObj = new JSONObject(jsonStr); + + //Проверяю есть ли запись в базе данных + boolean exists=false; //Is there a record. + uid=jsonObj.getString("uid"); + logger.info("uid="+uid); + Statement st; + try { + st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery("select 1 from main.frmlocusthealth where uid='"+uid+"'"); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + return obj.toString(); + } + if(rs!=null) + { + if(rs.next()) + exists=true; + } + st.close(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + return obj.toString(); + } + + PreparedStatementNamed stmtn=null; + String sql=""; + if(exists) + { + sql= """ + update main.frmlocusthealth set + frmlocustdel_uid=main.strtouuid(${frmlocustdel_uid}), + device_id=${device_id}, + user_id=${user_id}, + observer=${observer}, + date=${date}, + lat_center=${lat_center}, + lon_center=${lon_center}, + frmlocustdel_filled=${frmlocustdel_filled}, + brigade_count=${brigade_count}, + brigade_count_trained=${brigade_count_trained}, + insecticide_part_number=${insecticide_part_number}, + insecticide_manufactured_date=${insecticide_manufactured_date}, + insecticide_container_state_id=${insecticide_container_state_id}, + spr_leak=${spr_leak}, + spr_leak_place=${spr_leak_place}, + spr_damage=${spr_damage}, + spr_damage_place=${spr_damage_place}, + spr_treated_area_check=${spr_treated_area_check}, + spr_fact_volume=${spr_fact_volume}, + spr_observation=${spr_observation}, + spr_description=${spr_description}, + calibr_consumption_check=${calibr_consumption_check}, + calibr_time=${calibr_time}, + calibr_volume=${calibr_volume}, + calibr_rate=${calibr_rate}, + calibr_precipitation=${calibr_precipitation}, + calibr_width_card=${calibr_width_card}, + calibr_wind_speed=${calibr_wind_speed}, + calibr_droplet_coating=${calibr_droplet_coating}, + calibr_passes_interval=${calibr_passes_interval}, + efficacy_control=${efficacy_control}, + efficacy_impact_type_id=${efficacy_impact_type_id}, + efficacy_mortality=${efficacy_mortality}, + efficacy_passed_time=${efficacy_passed_time}, + efficacy_mortality_method_id=${efficacy_mortality_method_id}, + hlth_safety_clothing_clean=${hlth_safety_clothing_clean}, + hlth_clothing_state=${hlth_clothing_state}, + hlth_clothing_reserve=${hlth_clothing_reserve}, + hlth_operator_passport=${hlth_operator_passport}, + hlth_filled_passport=${hlth_filled_passport}, + hlth_inhibition=${hlth_inhibition}, + hlth_description=${hlth_description}, + safety_observed_pollution=${safety_observed_pollution}, + safety_type_pollution=${safety_type_pollution}, + safety_non_target=${safety_non_target}, + safety_non_target_effect=${safety_non_target_effect}, + safety_non_target_effect_person=${safety_non_target_effect_person}, + safety_control=${safety_control}, + safety_control_actions=${safety_control_actions}, + map_treatment=${map_treatment}, + image_name1=${image_name1}, + image_name2=${image_name2}, + image_name3=${image_name3}, + image_name4=${image_name4}, + image_name5=${image_name5}, + risk_house=${risk_house}, + risk_house_distance=${risk_house_distance}, + risk_house_buffer_zones=${risk_house_buffer_zones}, + risk_house_impact=${risk_house_impact}, + risk_house_informed=${risk_house_informed}, + risk_water=${risk_water}, + risk_water_distance=${risk_water_distance}, + risk_water_buffer_zones=${risk_water_buffer_zones}, + risk_water_impact=${risk_water_impact}, + risk_apiary=${risk_apiary}, + risk_apiary_distance=${risk_apiary_distance}, + risk_apiary_informed=${risk_apiary_informed}, + risk_apiary_measure=${risk_apiary_measure}, + risk_apiary_impact=${risk_apiary_impact}, + risk_agricultural=${risk_agricultural}, + risk_agricultural_name=${risk_agricultural_name}, + risk_agricultural_phase=${risk_agricultural_phase}, + risk_agricultural_toxic=${risk_agricultural_toxic}, + risk_agricultural_inform=${risk_agricultural_inform}, + risk_silk=${risk_silk}, + risk_silk_distance=${risk_silk_distance}, + risk_silk_inform=${risk_silk_inform}, + risk_silk_trees_measure=${risk_silk_trees_measure}, + risk_silk_trees_impact=${risk_silk_trees_impact}, + risk_pastures=${risk_pastures}, + risk_pastures_inform=${risk_pastures_inform}, + risk_park=${risk_park}, + risk_park_type=${risk_park_type}, + risk_park_distance=${risk_park_distance}, + risk_park_buffer_zones=${risk_park_buffer_zones}, + risk_park_impact=${risk_park_impact}, + risk_probe_analysis=${risk_probe_analysis}, + risk_probe_analysis_name=${risk_probe_analysis_name}, + risk_probe_analysis_number=${risk_probe_analysis_number}, + test=${test}, + geom=ST_SetSRID(ST_GeomFromGeoJSON(${geom}),4326) + where uid=main.strtouuid(${uid}) + """; + }else + { + sql= """ + insert into main.frmlocusthealth( + uid, + frmlocustdel_uid, + device_id, + user_id, + observer, + date, + lat_center, + lon_center, + frmlocustdel_filled, + brigade_count, + brigade_count_trained, + insecticide_part_number, + insecticide_manufactured_date, + insecticide_container_state_id, + spr_leak, + spr_leak_place, + spr_damage, + spr_damage_place, + spr_treated_area_check, + spr_fact_volume, + spr_observation, + spr_description, + calibr_consumption_check, + calibr_time, + calibr_volume, + calibr_rate, + calibr_precipitation, + calibr_width_card, + calibr_wind_speed, + calibr_droplet_coating, + calibr_passes_interval, + efficacy_control, + efficacy_impact_type_id, + efficacy_mortality, + efficacy_passed_time, + efficacy_mortality_method_id, + hlth_safety_clothing_clean, + hlth_clothing_state, + hlth_clothing_reserve, + hlth_operator_passport, + hlth_filled_passport, + hlth_inhibition, + hlth_description, + safety_observed_pollution, + safety_type_pollution, + safety_non_target, + safety_non_target_effect, + safety_non_target_effect_person, + safety_control, + safety_control_actions, + map_treatment, + image_name1, + image_name2, + image_name3, + image_name4, + image_name5, + risk_house, + risk_house_distance, + risk_house_buffer_zones, + risk_house_impact, + risk_house_informed, + risk_water, + risk_water_distance, + risk_water_buffer_zones, + risk_water_impact, + risk_apiary, + risk_apiary_distance, + risk_apiary_informed, + risk_apiary_measure, + risk_apiary_impact, + risk_agricultural, + risk_agricultural_name, + risk_agricultural_phase, + risk_agricultural_toxic, + risk_agricultural_inform, + risk_silk, + risk_silk_distance, + risk_silk_inform, + risk_silk_trees_measure, + risk_silk_trees_impact, + risk_pastures, + risk_pastures_inform, + risk_park, + risk_park_type, + risk_park_distance, + risk_park_buffer_zones, + risk_park_impact, + risk_probe_analysis, + risk_probe_analysis_name, + risk_probe_analysis_number, + test, + geom + )values( + main.strtouuid(${uid}), + main.strtouuid(${frmlocustdel_uid}), + ${device_id}, + ${user_id}, + ${observer}, + ${date}, + ${lat_center}, + ${lon_center}, + ${frmlocustdel_filled}, + ${brigade_count}, + ${brigade_count_trained}, + ${insecticide_part_number}, + ${insecticide_manufactured_date}, + ${insecticide_container_state_id}, + ${spr_leak}, + ${spr_leak_place}, + ${spr_damage}, + ${spr_damage_place}, + ${spr_treated_area_check}, + ${spr_fact_volume}, + ${spr_observation}, + ${spr_description}, + ${calibr_consumption_check}, + ${calibr_time}, + ${calibr_volume}, + ${calibr_rate}, + ${calibr_precipitation}, + ${calibr_width_card}, + ${calibr_wind_speed}, + ${calibr_droplet_coating}, + ${calibr_passes_interval}, + ${efficacy_control}, + ${efficacy_impact_type_id}, + ${efficacy_mortality}, + ${efficacy_passed_time}, + ${efficacy_mortality_method_id}, + ${hlth_safety_clothing_clean}, + ${hlth_clothing_state}, + ${hlth_clothing_reserve}, + ${hlth_operator_passport}, + ${hlth_filled_passport}, + ${hlth_inhibition}, + ${hlth_description}, + ${safety_observed_pollution}, + ${safety_type_pollution}, + ${safety_non_target}, + ${safety_non_target_effect}, + ${safety_non_target_effect_person}, + ${safety_control}, + ${safety_control_actions}, + ${map_treatment}, + ${image_name1}, + ${image_name2}, + ${image_name3}, + ${image_name4}, + ${image_name5}, + ${risk_house}, + ${risk_house_distance}, + ${risk_house_buffer_zones}, + ${risk_house_impact}, + ${risk_house_informed}, + ${risk_water}, + ${risk_water_distance}, + ${risk_water_buffer_zones}, + ${risk_water_impact}, + ${risk_apiary}, + ${risk_apiary_distance}, + ${risk_apiary_informed}, + ${risk_apiary_measure}, + ${risk_apiary_impact}, + ${risk_agricultural}, + ${risk_agricultural_name}, + ${risk_agricultural_phase}, + ${risk_agricultural_toxic}, + ${risk_agricultural_inform}, + ${risk_silk}, + ${risk_silk_distance}, + ${risk_silk_inform}, + ${risk_silk_trees_measure}, + ${risk_silk_trees_impact}, + ${risk_pastures}, + ${risk_pastures_inform}, + ${risk_park}, + ${risk_park_type}, + ${risk_park_distance}, + ${risk_park_buffer_zones}, + ${risk_park_impact}, + ${risk_probe_analysis}, + ${risk_probe_analysis_name}, + ${risk_probe_analysis_number}, + ${test}, + ST_SetSRID(ST_GeomFromGeoJSON(${geom}),4326) + )"""; + } + + try { + stmtn = new PreparedStatementNamed(conn, sql); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql); + logger.error("Error",ex); + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + return obj.toString(); + } + + stmtn.setString("uid",uid); + + String value; + value = jsonObj.optString("frmlocustdel_uid",null); + stmtn.setString("frmlocustdel_uid",value); + value = jsonObj.optString("device_id",null); + stmtn.setString("device_id",value); + value = jsonObj.optString("user_id",null); + stmtn.setInt("user_id",value); + value = jsonObj.optString("observer",null); + stmtn.setString("observer",value); + + value = jsonObj.optString("date",null); + stmtn.setTimestamp("date",value); + + value = jsonObj.optString("lat_center",null); + stmtn.setDouble("lat_center",value); + value = jsonObj.optString("lon_center",null); + stmtn.setDouble("lon_center",value); + + value = jsonObj.optString("frmlocustdel_filled",null); + stmtn.setBoolean("frmlocustdel_filled",value); + value = jsonObj.optString("brigade_count",null); + stmtn.setInt("brigade_count",value); + value = jsonObj.optString("brigade_count_trained",null); + stmtn.setInt("brigade_count_trained",value); + value = jsonObj.optString("insecticide_part_number",null); + stmtn.setString("insecticide_part_number",value); + value = jsonObj.optString("insecticide_manufactured_date",null); + stmtn.setString("insecticide_manufactured_date",value); + value = jsonObj.optString("insecticide_container_state_id",null); + stmtn.setInt("insecticide_container_state_id",value); + + value = jsonObj.optString("spr_leak",null); + stmtn.setBoolean("spr_leak",value); + value = jsonObj.optString("spr_leak_place",null); + stmtn.setString("spr_leak_place",value); + value = jsonObj.optString("spr_damage",null); + stmtn.setBoolean("spr_damage",value); + value = jsonObj.optString("spr_damage_place",null); + stmtn.setString("spr_damage_place",value); + value = jsonObj.optString("spr_treated_area_check",null); + stmtn.setFloat("spr_treated_area_check",value); + value = jsonObj.optString("spr_fact_volume",null); + stmtn.setFloat("spr_fact_volume",value); + value = jsonObj.optString("spr_observation",null); + stmtn.setBoolean("spr_observation",value); + value = jsonObj.optString("spr_description",null); + stmtn.setString("spr_description",value); + value = jsonObj.optString("calibr_consumption_check",null); + stmtn.setBoolean("calibr_consumption_check",value); + value = jsonObj.optString("calibr_time",null); + stmtn.setInt("calibr_time",value); + value = jsonObj.optString("calibr_volume",null); + stmtn.setInt("calibr_volume",value); + value = jsonObj.optString("calibr_rate",null); + stmtn.setInt("calibr_rate",value); + value = jsonObj.optString("calibr_precipitation",null); + stmtn.setBoolean("calibr_precipitation",value); + value = jsonObj.optString("calibr_width_card",null); + stmtn.setFloat("calibr_width_card",value); + value = jsonObj.optString("calibr_wind_speed",null); + stmtn.setFloat("calibr_wind_speed",value); + value = jsonObj.optString("calibr_droplet_coating",null); + stmtn.setFloat("calibr_droplet_coating",value); + value = jsonObj.optString("calibr_passes_interval",null); + stmtn.setFloat("calibr_passes_interval",value); + value = jsonObj.optString("efficacy_control",null); + stmtn.setBoolean("efficacy_control",value); + value = jsonObj.optString("efficacy_impact_type_id",null); + stmtn.setInt("efficacy_impact_type_id",value); + value = jsonObj.optString("efficacy_mortality",null); + stmtn.setFloat("efficacy_mortality",value); + value = jsonObj.optString("efficacy_passed_time",null); + stmtn.setFloat("efficacy_passed_time",value); + value = jsonObj.optString("efficacy_mortality_method_id",null); + stmtn.setInt("efficacy_mortality_method_id",value); + + value = jsonObj.optString("hlth_safety_clothing_clean",null); + stmtn.setBoolean("hlth_safety_clothing_clean",value); + value = jsonObj.optString("hlth_clothing_state",null); + stmtn.setString("hlth_clothing_state",value); + value = jsonObj.optString("hlth_clothing_reserve",null); + stmtn.setBoolean("hlth_clothing_reserve",value); + value = jsonObj.optString("hlth_operator_passport",null); + stmtn.setInt("hlth_operator_passport",value); + value = jsonObj.optString("hlth_filled_passport",null); + stmtn.setInt("hlth_filled_passport",value); + value = jsonObj.optString("hlth_inhibition",null); + stmtn.setBoolean("hlth_inhibition",value); + value = jsonObj.optString("hlth_description",null); + stmtn.setString("hlth_description",value); + + value = jsonObj.optString("safety_observed_pollution",null); + stmtn.setBoolean("safety_observed_pollution",value); + value = jsonObj.optString("safety_type_pollution",null); + stmtn.setString("safety_type_pollution",value); + value = jsonObj.optString("safety_non_target",null); + stmtn.setBoolean("safety_non_target",value); + value = jsonObj.optString("safety_non_target_effect",null); + stmtn.setString("safety_non_target_effect",value); + value = jsonObj.optString("safety_non_target_effect_person",null); + stmtn.setString("safety_non_target_effect_person",value); + value = jsonObj.optString("safety_control",null); + stmtn.setBoolean("safety_control",value); + value = jsonObj.optString("safety_control_actions",null); + stmtn.setString("safety_control_actions",value); + + value = jsonObj.optString("map_treatment",null); + stmtn.setBoolean("map_treatment",value); + value = jsonObj.optString("image_name1",null); + stmtn.setString("image_name1",value); + value = jsonObj.optString("image_name2",null); + stmtn.setString("image_name2",value); + value = jsonObj.optString("image_name3",null); + stmtn.setString("image_name3",value); + value = jsonObj.optString("image_name4",null); + stmtn.setString("image_name4",value); + value = jsonObj.optString("image_name5",null); + stmtn.setString("image_name5",value); + + value = jsonObj.optString("risk_house",null); + stmtn.setBoolean("risk_house",value); + value = jsonObj.optString("risk_house_distance",null); + stmtn.setFloat("risk_house_distance",value); + value = jsonObj.optString("risk_house_buffer_zones",null); + stmtn.setBoolean("risk_house_buffer_zones",value); + value = jsonObj.optString("risk_house_impact",null); + stmtn.setBoolean("risk_house_impact",value); + value = jsonObj.optString("risk_house_informed",null); + stmtn.setBoolean("risk_house_informed",value); + + value = jsonObj.optString("risk_water",null); + stmtn.setBoolean("risk_water",value); + value = jsonObj.optString("risk_water_distance",null); + stmtn.setFloat("risk_water_distance",value); + value = jsonObj.optString("risk_water_buffer_zones",null); + stmtn.setBoolean("risk_water_buffer_zones",value); + value = jsonObj.optString("risk_water_impact",null); + stmtn.setBoolean("risk_water_impact",value); + + value = jsonObj.optString("risk_apiary",null); + stmtn.setBoolean("risk_apiary",value); + value = jsonObj.optString("risk_apiary_distance",null); + stmtn.setFloat("risk_apiary_distance",value); + value = jsonObj.optString("risk_apiary_informed",null); + stmtn.setBoolean("risk_apiary_informed",value); + value = jsonObj.optString("risk_apiary_measure",null); + stmtn.setString("risk_apiary_measure",value); + value = jsonObj.optString("risk_apiary_impact",null); + stmtn.setBoolean("risk_apiary_impact",value); + + value = jsonObj.optString("risk_agricultural",null); + stmtn.setBoolean("risk_agricultural",value); + value = jsonObj.optString("risk_agricultural_name",null); + stmtn.setString("risk_agricultural_name",value); + value = jsonObj.optString("risk_agricultural_phase",null); + stmtn.setString("risk_agricultural_phase",value); + value = jsonObj.optString("risk_agricultural_toxic",null); + stmtn.setBoolean("risk_agricultural_toxic",value); + value = jsonObj.optString("risk_agricultural_inform",null); + stmtn.setBoolean("risk_agricultural_inform",value); + + value = jsonObj.optString("risk_silk",null); + stmtn.setBoolean("risk_silk",value); + value = jsonObj.optString("risk_silk_distance",null); + stmtn.setFloat("risk_silk_distance",value); + value = jsonObj.optString("risk_silk_inform",null); + stmtn.setBoolean("risk_silk_inform",value); + value = jsonObj.optString("risk_silk_trees_measure",null); + stmtn.setString("risk_silk_trees_measure",value); + value = jsonObj.optString("risk_silk_trees_impact",null); + stmtn.setBoolean("risk_silk_trees_impact",value); + + value = jsonObj.optString("risk_pastures",null); + stmtn.setBoolean("risk_pastures",value); + value = jsonObj.optString("risk_pastures_inform",null); + stmtn.setBoolean("risk_pastures_inform",value); + + value = jsonObj.optString("risk_park",null); + stmtn.setBoolean("risk_park",value); + value = jsonObj.optString("risk_park_type",null); + stmtn.setString("risk_park_type",value); + value = jsonObj.optString("risk_park_distance",null); + stmtn.setFloat("risk_park_distance",value); + value = jsonObj.optString("risk_park_buffer_zones",null); + stmtn.setBoolean("risk_park_buffer_zones",value); + value = jsonObj.optString("risk_park_impact",null); + stmtn.setBoolean("risk_park_impact",value); + + value = jsonObj.optString("risk_probe_analysis",null); + stmtn.setBoolean("risk_probe_analysis",value); + value = jsonObj.optString("risk_probe_analysis_name",null); + stmtn.setString("risk_probe_analysis_name",value); + value = jsonObj.optString("risk_probe_analysis_number",null); + stmtn.setString("risk_probe_analysis_number",value); + + value = jsonObj.optString("test",null); + stmtn.setBoolean("test",value); + + value = jsonObj.optString("geom",null); + stmtn.setString("geom",value); + + //Execute SQL + try { + PreparedStatement stmt=stmtn.getPreparedStatement(); + stmt.execute(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + return obj.toString(); + } + + //Create temporary directory + String dataDir = data_dir; + String tmpDir = "temp"+File.separator; + try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + return obj.toString(); + } + + //If there are drawings, then copy them. + String imgDir="./data/frmlocusthealth/"; + try{ new File(dataDir+imgDir).mkdirs(); }catch (Exception exception) {} + if(jsonObj.optString("image_name1",null)!=null && !jsonObj.optString("image_name1","").isEmpty()) + { + String filename1=dataDir+tmpDir+jsonObj.optString("image_name1",""); + File f = new File(filename1); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+jsonObj.optString("image_name1",""))); + } + } + if(jsonObj.optString("image_name2",null)!=null && !jsonObj.optString("image_name2","").isEmpty()) + { + String filename2=dataDir+tmpDir+jsonObj.optString("image_name2",""); + File f = new File(filename2); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+jsonObj.optString("image_name2",""))); + } + } + if(jsonObj.optString("image_name3",null)!=null && !jsonObj.optString("image_name3","").isEmpty()) + { + String filename3=dataDir+tmpDir+jsonObj.optString("image_name3",""); + File f = new File(filename3); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+jsonObj.optString("image_name3",""))); + } + } + if(jsonObj.optString("image_name4",null)!=null && !jsonObj.optString("image_name4","").isEmpty()) + { + String filename3=dataDir+tmpDir+jsonObj.optString("image_name4",""); + File f = new File(filename3); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+jsonObj.optString("image_name4",""))); + } + } + if(jsonObj.optString("image_name5",null)!=null && !jsonObj.optString("image_name5","").isEmpty()) + { + String filename3=dataDir+tmpDir+jsonObj.optString("image_name5",""); + File f = new File(filename3); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+jsonObj.optString("image_name5",""))); + } + } + + JSONObject obj = new JSONObject(); + obj.put("error_code",0); + obj.put("error_message", ""); + obj.put("fn","frmlocusthealth"); + obj.put("uid",uid); + return obj.toString(); + + } catch (Exception ex) { + ex.printStackTrace(); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return result.toString(); + }finally { + try{ if(conn!=null) conn.close(); }catch(Exception e){} + } + //return result.toString(); закоментил: недостижимая строка + } + + // To authorize a tablet using a QR code from "ScanActivity" form + @RequestMapping(value = "/asdc/qrcode/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/json") + @ResponseBody + public Object uploadJSON(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) { + + JSONObject result = new JSONObject(); + result.put("error_code", 0); + result.put("error_message", ""); + + 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 ex) { + ex.printStackTrace(); + logger.error("Error load org_ccalm_main.properties",ex); + } + + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + try { + Statement sttTZ = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sttTZ.executeUpdate("SET TIME ZONE 'UTC';"); + sttTZ.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + //Parse JSON request + String jsonStr = "{}"; + if(reqData!=null) + jsonStr = new String(reqData, StandardCharsets.UTF_8); + else + throw new Exception("No JSON input data!"); + + JSONObject jsonObj = new JSONObject(jsonStr); + StringBuffer qrcode=new StringBuffer(jsonObj.getString("qrcode")); + String android_id = jsonObj.getString("android_id"); + String secret = jsonObj.getString("secret"); + if(secret.equals(md5(android_id+"_ASDC"))) { + + String unixTime=STools.CutBeforeFirst(qrcode,"_"); + String id=STools.CutBeforeFirst(qrcode,"_"); + + long time = System.currentTimeMillis() / 1000; + if(time-86400>Integer.parseInt(unixTime)) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", "QR code is outdated!"); + return obj.toString(); + } + + //Clear the serial number if it is in the database + String sql="update main.terminals set serial=null where serial=?"; + PreparedStatement stmt=null; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + try { + stmt.setString(1,android_id); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + try { + stmt.execute(); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + + sql="update main.terminals set serial=? where id=?"; + stmt=null; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + + try { + stmt.setString(1,android_id); + stmt.setInt(2,Integer.parseInt(id)); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + + try { + stmt.execute(); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + + //Select data + sql = "select t.id,t.name,t.country_id,t.company_id,cp.name as company_name,cr.name as country_name from main.terminals t left join main.companies cp on cp.id=t.company_id left join main.countries cr on cr.id=t.country_id where t.del=false and t.id="+id; + try { + Statement st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery(sql); + } catch( SQLException ex ) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + if(rs!=null) + { + while (rs.next()) + { + result.put("id",rs.getInt("id")); + result.put("country_id",rs.getInt("country_id")); + result.put("company_id",rs.getInt("company_id")); + result.put("country_name",rs.getString("country_name")); + result.put("company_name",rs.getString("company_name")); + result.put("name",rs.getString("name")); + } + } + st.close(); + } catch (SQLException ex) { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return obj.toString(); + } + }else { + JSONObject obj = new JSONObject(); + obj.put("error_code",1); + obj.put("error_message", "Secret code is invalid!"); + return obj.toString(); + } + + } catch (Exception ex) { + ex.printStackTrace(); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + logger.error("Error",ex); + return result.toString(); + }finally { + try{ if(conn!=null) conn.close(); }catch(Exception e){} + } + return result.toString(); + } + + @RequestMapping(value = "/get/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/xml; charset=utf-8") + @ResponseBody + public Object uploadXML(HttpServletResponse response, @RequestHeader(required=false,name="Content-Type") String contentType, @RequestBody(required=false) byte[] reqData) { + + if(contentType!=null) + logger.info("Content-Type = " + contentType); //INFO : kz.locust.CCALM.AcceptASDC - Content-Type = multipart/form-data; boundary=kTwyQRMc7R9JvmcYlXyvMEwX6B08jb + + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + response.setContentType("application/xml"); + String result=""; + //boolean error=false; + + 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 ex) { + ex.printStackTrace(); + logger.error("Error load org_ccalm_main.properties",ex); + } + + //Create temporary directory + String dataDir = data_dir; + String tmpDir = "temp"+File.separator; + try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + return result; + } + + //Connect to database + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + logger.info("Connect is OK!"); + try { + Statement sttTZ = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sttTZ.executeUpdate("SET TIME ZONE 'UTC';"); + sttTZ.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + /*Statement stt=null; + try { + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.info(ex.getMessage()); + }*/ + + //Set UTC time + Statement stm=null; + try { + stm = conn.createStatement(); + try { + stm.execute("SET timezone TO 'UTC';"); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + return result; + } + stm.close(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + return result; + } + + if(reqData!=null) + logRotate(data_dir+"errors.log","XML = "+(new String(reqData))); + else + throw new Exception("No JSON input data!"); + + //Parse incoming XML string + String fn=""; + Document doc = null; + Element reqNode = null; + if(reqData!=null && reqData.length!=0) { + + //Request data + InputStream body = new ByteArrayInputStream(reqData); + + try { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + doc = dBuilder.parse(body); + } catch (Exception ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + return result; + } + + if (doc != null) { + reqNode = doc.getDocumentElement(); + fn = reqNode.getAttribute("fn"); //Номер функции + } + } + if(fn==null) fn=""; + + if(fn.equals("4")) + { + boolean exists=false; //Is there a record. + String uid=getCdataValue(reqNode,"uid"); + logger.info("uid="+uid); + Statement st; + try { + st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery("select 1 from main.frmlocust where uid='"+uid+"'"); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=(""); + return result; + } + if(rs!=null) + { + if(rs.next()) + exists=true; + } + st.close(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=(""); + return result; + } + + PreparedStatement stmt=null; + if(exists) + { + String sql="update main.frmlocust set\n" + +" uid = ?,\n" + +" changed = false,\n" + +" user_id=?,\n" + +" device_id=?,\n" + +" image_name1=?,\n" + +" image_name2=?,\n" + +" image_name3=?,\n" + +" country_id=?,\n" + +" region_id=?,\n" + +" area=?,\n" + +" district=?,\n" + +" village=?,\n" + +" terrain=?,\n" + +" observer=?,\n" + +" date=?,\n" + +" timezone=?::interval,\n" + +" lat_center=?,\n" + +" lon_center=?,\n" + +" lat1=?,\n" + +" lon1=?,\n" + +" lat2=?,\n" + +" lon2=?,\n" + +" lat3=?,\n" + +" lon3=?,\n" + +" lat4=?,\n" + +" lon4=?,\n" + +" lat5=?,\n" + +" lon5=?,\n" + +" lat6=?,\n" + +" lon6=?,\n" + +" bio_hectare=?,\n" + +" bio_biotope_id=?,\n" + +" bio_greenery_id=?,\n" + +" bio_greenery_cover_id=?,\n" + +" bio_temperature=?,\n" + +" bio_wind=?,\n" + +" locust_have=?,\n" + +" locust_type_id=?,\n" + +" locust_populated=?,\n" + +" eggs_capsules_area=?,\n" + +" eggs_capsules_density=?,\n" + +" eggs_capsules_density_to=?,\n" + +" eggs_capsules=?,\n" + +" eggs_live=?,\n" + +" eggs_enemies_id=?,\n" + +" larva_born_id=?,\n" + +" larva_age_id=?,\n" + +" larva_painting_id=?,\n" + +" larva_behavior_id=?,\n" + +" larva_density=?,\n" + +" larva_density_to=?,\n" + +" kuliguli_age_id=?,\n" + +" kuliguli_density=?,\n" + +" kuliguli_density_to=?,\n" + +" kuliguli_size=?,\n" + +" kuliguli_count=?,\n" + +" kuliguli_action_id=?,\n" + +" imago_wing_id=?,\n" + +" imago_maturity=?,\n" + +" imago_phase_id=?,\n" + +" imago_action_id=?,\n" + +" imago_density=?,\n" + +" imago_density_ga=?,\n" + +" imago_feeding=?,\n" + +" imago_copulation=?,\n" + +" imago_laying=?,\n" + +" imago_flying=?,\n" + +" swarm_maturity=?,\n" + +" swarm_density_id=?,\n" + +" swarm_size=?,\n" + +" swarm_count=?,\n" + +" swarm_copulation=?,\n" + +" swarm_laying=?,\n" + +" swarm_flying_direction_id=?,\n" + +" swarm_height_id=?,\n" + +" description=?,\n" + +" geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" + +" test=?\n" + +" where uid='"+uid+"'"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql); + logger.error("Error",ex); + result=(""); + return result; + } + }else + { + String sql="insert into main.frmlocust(\n" + +" uid,\n" + +" changed,\n" + +" user_id,\n" + +" device_id,\n" + +" image_name1,\n" + +" image_name2,\n" + +" image_name3,\n" + +" country_id,\n" + +" region_id,\n" + +" area,\n" + +" district,\n" + +" village,\n" + +" terrain,\n" + +" observer,\n" + +" date,\n" + +" timezone,\n" + +" lat_center,\n" + +" lon_center,\n" + +" lat1,\n" + +" lon1,\n" + +" lat2,\n" + +" lon2,\n" + +" lat3,\n" + +" lon3,\n" + +" lat4,\n" + +" lon4,\n" + +" lat5,\n" + +" lon5,\n" + +" lat6,\n" + +" lon6,\n" + +" bio_hectare,\n" + +" bio_biotope_id,\n" + +" bio_greenery_id,\n" + +" bio_greenery_cover_id,\n" + +" bio_temperature,\n" + +" bio_wind,\n" + +" locust_have,\n" + +" locust_type_id,\n" + +" locust_populated,\n" + +" eggs_capsules_area,\n" + +" eggs_capsules_density,\n" + +" eggs_capsules_density_to,\n" + +" eggs_capsules,\n" + +" eggs_live,\n" + +" eggs_enemies_id,\n" + +" larva_born_id,\n" + +" larva_age_id,\n" + +" larva_painting_id,\n" + +" larva_behavior_id,\n" + +" larva_density,\n" + +" larva_density_to,\n" + +" kuliguli_age_id,\n" + +" kuliguli_density,\n" + +" kuliguli_density_to,\n" + +" kuliguli_size,\n" + +" kuliguli_count,\n" + +" kuliguli_action_id,\n" + +" imago_wing_id,\n" + +" imago_maturity,\n" + +" imago_phase_id,\n" + +" imago_action_id,\n" + +" imago_density,\n" + +" imago_density_ga,\n" + +" imago_feeding,\n" + +" imago_copulation,\n" + +" imago_laying,\n" + +" imago_flying,\n" + +" swarm_maturity,\n" + +" swarm_density_id,\n" + +" swarm_size,\n" + +" swarm_count,\n" + +" swarm_copulation,\n" + +" swarm_laying,\n" + +" swarm_flying_direction_id,\n" + +" swarm_height_id,\n" + +" description,\n" + +" geom,\n" + +" test\n" + +")values(\n" + +" ?,\n" //1 uid + +" false,\n" + +" ?,\n" //2 user_id + +" ?,\n" //3 device_id + +" ?,\n" //4 image_name1 + +" ?,\n" //5 image_name2 + +" ?,\n" //6 image_name3 + +" ?,\n" //7 country_id + +" ?,\n" //8 region_id + +" ?,\n" //9 area + +" ?,\n" //10 district + +" ?,\n" //11 village + +" ?,\n" //12 terrain + +" ?,\n" //13 observer + +" ?,\n" //14 date + +" ?::interval,\n" //15 timezone + +" ?,\n" //16 lat_center + +" ?,\n" //17 lon_center + +" ?,\n" //18 lat1 + +" ?,\n" //19 lon1 + +" ?,\n" //20 lat2 + +" ?,\n" //21 lon2 + +" ?,\n" //22 lat3 + +" ?,\n" //23 lon3 + +" ?,\n" //24 lat4 + +" ?,\n" //25 lon4 + +" ?,\n" //26 lat5 + +" ?,\n" //27 lon5 + +" ?,\n" //28 lat6 + +" ?,\n" //29 lon6 + +" ?,\n" //30 bio_hectare + +" ?,\n" //31 bio_biotope_id + +" ?,\n" //32 bio_greenery_id + +" ?,\n" //33 bio_greenery_cover_id + +" ?,\n" //34 bio_temperature + +" ?,\n" //35 bio_wind + +" ?,\n" //36 locust_have + +" ?,\n" //37 locust_type_id + +" ?,\n" //38 locust_populated + +" ?,\n" //39 eggs_capsules_area + +" ?,\n" //40 eggs_capsules_density + +" ?,\n" //41 eggs_capsules_density_to + +" ?,\n" //42 eggs_capsules + +" ?,\n" //43 eggs_live + +" ?,\n" //44 eggs_enemies_id + +" ?,\n" //45 larva_born_id + +" ?,\n" //46 larva_age_id + +" ?,\n" //47 larva_painting_id + +" ?,\n" //48 larva_behavior_id + +" ?,\n" //49 larva_density + +" ?,\n" //50 larva_density_to + +" ?,\n" //51 kuliguli_age_id + +" ?,\n" //52 kuliguli_density + +" ?,\n" //53 kuliguli_density_to + +" ?,\n" //54 kuliguli_size + +" ?,\n" //55 kuliguli_count + +" ?,\n" //56 kuliguli_action_id + +" ?,\n" //57 imago_wing_id + +" ?,\n" //58 imago_maturity + +" ?,\n" //59 imago_phase_id + +" ?,\n" //60 imago_action_id + +" ?,\n" //61 imago_density + +" ?,\n" //62 imago_density_ga + +" ?,\n" //63 imago_feeding + +" ?,\n" //64 imago_copulation + +" ?,\n" //65 imago_laying + +" ?,\n" //66 imago_flying + +" ?,\n" //67 swarm_maturity + +" ?,\n" //68 swarm_density_id + +" ?,\n" //69 swarm_size + +" ?,\n" //70 swarm_count + +" ?,\n" //71 swarm_copulation + +" ?,\n" //72 swarm_laying + +" ?,\n" //73 swarm_flying_direction_id + +" ?,\n" //74 swarm_height_id + +" ?,\n" //75 description + +" ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //76 geom + +" ?\n" //77 test + +")"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql); + logger.error("Error",ex); + result=(""); + return result; + } + } + + //String id=getCdataValue(reqNode, "id"); + //String uid=getCdataValue(reqNode, "uid"); + //String del=getCdataValue(reqNode, "del"); + //String seq=getCdataValue(reqNode, "seq"); + //String fix_date=getCdataValue(reqNode, "fix_date"); + //String changed=getCdataValue(reqNode, "changed"); + String user_id=getCdataValue(reqNode, "user_id"); + String device_id=getCdataValue(reqNode, "device_id"); + String image_name1=getCdataValue(reqNode, "image_name1"); + String image_name2=getCdataValue(reqNode, "image_name2"); + String image_name3=getCdataValue(reqNode, "image_name3"); + String country_id=getCdataValue(reqNode, "country_id"); + String region_id=getCdataValue(reqNode, "region_id"); + String area=getCdataValue(reqNode, "area"); + String district=getCdataValue(reqNode, "district"); + String village=getCdataValue(reqNode, "village"); + String terrain=getCdataValue(reqNode, "terrain"); + String observer=getCdataValue(reqNode, "observer"); + String date=getCdataValue(reqNode, "date"); + String timezone=getCdataValue(reqNode, "timezone"); + timezone=Tools.numConvert(timezone); + + String lat1=getCdataValue(reqNode, "lat1"); + if(lat1==null) { lat1=getCdataValue(reqNode, "lat"); } + String lon1=getCdataValue(reqNode, "lon1"); + if(lon1==null) { lon1=getCdataValue(reqNode, "lon"); } + + String lat_center=getCdataValue(reqNode, "lat_center"); + if(lat_center==null) { lat_center=lat1; } + String lon_center=getCdataValue(reqNode, "lon_center"); + if(lon_center==null) { lon_center=lon1; } + if(lat1==null) { lat1=lat_center; } + if(lon1==null) { lon1=lon_center; } + + String lat2=getCdataValue(reqNode, "lat2"); + String lon2=getCdataValue(reqNode, "lon2"); + String lat3=getCdataValue(reqNode, "lat3"); + String lon3=getCdataValue(reqNode, "lon3"); + String lat4=getCdataValue(reqNode, "lat4"); + String lon4=getCdataValue(reqNode, "lon4"); + String lat5=getCdataValue(reqNode, "lat5"); + String lon5=getCdataValue(reqNode, "lon5"); + String lat6=getCdataValue(reqNode, "lat6"); + String lon6=getCdataValue(reqNode, "lon6"); + String bio_hectare=getCdataValue(reqNode, "bio_hectare"); + String bio_biotope_id=getCdataValue(reqNode, "bio_biotope_id"); + String bio_greenery_id=getCdataValue(reqNode, "bio_greenery_id"); + String bio_greenery_cover_id=getCdataValue(reqNode, "bio_greenery_cover_id"); + String bio_temperature=getCdataValue(reqNode, "bio_temperature"); + String bio_wind=getCdataValue(reqNode, "bio_wind"); + String locust_have=getCdataValue(reqNode, "locust_have"); + String locust_type_id=getCdataValue(reqNode, "locust_type_id"); + String locust_populated=getCdataValue(reqNode, "locust_populated"); + String eggs_capsules_area=getCdataValue(reqNode, "eggs_capsules_area"); + String eggs_capsules_density=getCdataValue(reqNode, "eggs_capsules_density"); + String eggs_capsules_density_to=getCdataValue(reqNode, "eggs_capsules_density_to"); + String eggs_capsules=getCdataValue(reqNode, "eggs_capsules"); + String eggs_live=getCdataValue(reqNode, "eggs_live"); + String eggs_enemies_id=getCdataValue(reqNode, "eggs_enemies_id"); + String larva_born_id=getCdataValue(reqNode, "larva_born_id"); + String larva_age_id=getCdataValue(reqNode, "larva_age_id"); + String larva_painting_id=getCdataValue(reqNode, "larva_painting_id"); + String larva_behavior_id=getCdataValue(reqNode, "larva_behavior_id"); + String larva_density=getCdataValue(reqNode, "larva_density"); + String larva_density_to=getCdataValue(reqNode, "larva_density_to"); + String kuliguli_age_id=getCdataValue(reqNode, "kuliguli_age_id"); + String kuliguli_density=getCdataValue(reqNode, "kuliguli_density"); + String kuliguli_density_to=getCdataValue(reqNode, "kuliguli_density_to"); + String kuliguli_size=getCdataValue(reqNode, "kuliguli_size"); + String kuliguli_count=getCdataValue(reqNode, "kuliguli_count"); + String kuliguli_action_id=getCdataValue(reqNode, "kuliguli_action_id"); + String imago_wing_id=getCdataValue(reqNode, "imago_wing_id"); + String imago_maturity=getCdataValue(reqNode, "imago_maturity"); + String imago_phase_id=getCdataValue(reqNode, "imago_phase_id"); + String imago_action_id=getCdataValue(reqNode, "imago_action_id"); + String imago_density=getCdataValue(reqNode, "imago_density"); + String imago_density_ga=getCdataValue(reqNode, "imago_density_ga"); + String imago_feeding=getCdataValue(reqNode, "imago_feeding"); + String imago_copulation=getCdataValue(reqNode, "imago_copulation"); + String imago_laying=getCdataValue(reqNode, "imago_laying"); + String imago_flying=getCdataValue(reqNode, "imago_flying"); + String swarm_maturity=getCdataValue(reqNode, "swarm_maturity"); + String swarm_density_id=getCdataValue(reqNode, "swarm_density_id"); + String swarm_size=getCdataValue(reqNode, "swarm_size"); + String swarm_count=getCdataValue(reqNode, "swarm_count"); + String swarm_copulation=getCdataValue(reqNode, "swarm_copulation"); + String swarm_laying=getCdataValue(reqNode, "swarm_laying"); + String swarm_flying_direction_id=getCdataValue(reqNode, "swarm_flying_direction_id"); + String swarm_height_id=getCdataValue(reqNode, "swarm_height_id"); + String description=getCdataValue(reqNode, "description"); + String geom=getCdataValue(reqNode, "geom"); + String test=getCdataValue(reqNode, "test"); + if(test==null) test="0"; + + try { + //if(country_id==null) stmt.setNull(7, Types.INTEGER, null); else stmt.setInt(id); + stmt.setString(1,uid); + //stmt.setString(del); + //stmt.setString(seq); + //if(country_id==null) stmt.setNull(7, Types.INTEGER, null); else stmt.setInt(fix_date); + //if(country_id==null) stmt.setNull(7, Types.INTEGER, null); else stmt.setInt(changed); + if(user_id==null) stmt.setNull(2, Types.INTEGER, null); else stmt.setInt(2,Integer.parseInt(user_id)); + stmt.setString(3,device_id); + + stmt.setString(4,image_name1); + stmt.setString(5,image_name2); + stmt.setString(6,image_name3); + + if(country_id==null) stmt.setNull(7, Types.INTEGER, null); else stmt.setInt(7,Integer.parseInt(country_id)); + if(region_id==null) stmt.setNull(8, Types.INTEGER, null); else stmt.setInt(8,Integer.parseInt(region_id)); + stmt.setString(9,area); + stmt.setString(10,district); + + stmt.setString(11,village); + stmt.setString(12,terrain); + + stmt.setString(13,observer); + if(date==null) + { + stmt.setNull(14, Types.DATE, null); + }else + { + if(date.indexOf("-")==-1) //If old date format in UNIX time + { + int uDate=Integer.parseInt(date)+1; + java.sql.Timestamp tm=new java.sql.Timestamp((long)uDate*1000); + stmt.setTimestamp(14, 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(date).getTime()); + } catch (Exception ex) { + logger.error("Error",ex.getMessage()); + } + stmt.setTimestamp(14, tm); + } + } + + stmt.setString(15,timezone); + + if(lat_center==null) stmt.setNull(16, Types.DOUBLE, null); else stmt.setDouble(16,Double.parseDouble(lat_center)); + if(lon_center==null) stmt.setNull(17, Types.DOUBLE, null); else stmt.setDouble(17,Double.parseDouble(lon_center)); + if(lat1==null) stmt.setNull(18, Types.DOUBLE, null); else stmt.setDouble(18,Double.parseDouble(lat1)); + if(lon1==null) stmt.setNull(19, Types.DOUBLE, null); else stmt.setDouble(19,Double.parseDouble(lon1)); + if(lat2==null) stmt.setNull(20, Types.DOUBLE, null); else stmt.setDouble(20,Double.parseDouble(lat2)); + if(lon2==null) stmt.setNull(21, Types.DOUBLE, null); else stmt.setDouble(21,Double.parseDouble(lon2)); + if(lat3==null) stmt.setNull(22, Types.DOUBLE, null); else stmt.setDouble(22,Double.parseDouble(lat3)); + if(lon3==null) stmt.setNull(23, Types.DOUBLE, null); else stmt.setDouble(23,Double.parseDouble(lon3)); + if(lat4==null) stmt.setNull(24, Types.DOUBLE, null); else stmt.setDouble(24,Double.parseDouble(lat4)); + if(lon4==null) stmt.setNull(25, Types.DOUBLE, null); else stmt.setDouble(25,Double.parseDouble(lon4)); + if(lat5==null) stmt.setNull(26, Types.DOUBLE, null); else stmt.setDouble(26,Double.parseDouble(lat5)); + if(lon5==null) stmt.setNull(27, Types.DOUBLE, null); else stmt.setDouble(27,Double.parseDouble(lon5)); + if(lat6==null) stmt.setNull(28, Types.DOUBLE, null); else stmt.setDouble(28,Double.parseDouble(lat6)); + if(lon6==null) stmt.setNull(29, Types.DOUBLE, null); else stmt.setDouble(29,Double.parseDouble(lon6)); + + if(bio_hectare==null) stmt.setNull(30, Types.DOUBLE, null); else stmt.setDouble(30,Double.parseDouble(bio_hectare)); + if(bio_biotope_id==null) stmt.setNull(31, Types.INTEGER, null); else stmt.setInt(31,Integer.parseInt(bio_biotope_id)); + if(bio_greenery_id==null) stmt.setNull(32, Types.INTEGER, null); else stmt.setInt(32,Integer.parseInt(bio_greenery_id)); + if(bio_greenery_cover_id==null) stmt.setNull(33, Types.INTEGER, null); else stmt.setInt(33,Integer.parseInt(bio_greenery_cover_id)); + if(bio_temperature==null) stmt.setNull(34, Types.DOUBLE, null); else stmt.setDouble(34,Double.parseDouble(bio_temperature)); + if(bio_wind==null) stmt.setNull(35, Types.DOUBLE, null); else stmt.setDouble(35,Double.parseDouble(bio_wind)); + if(locust_have==null) stmt.setNull(36, Types.INTEGER, null); else stmt.setInt(36,Integer.parseInt(locust_have)); + if(locust_type_id==null) stmt.setNull(37, Types.INTEGER, null); else stmt.setInt(37,Integer.parseInt(locust_type_id)); + if(locust_populated==null) stmt.setNull(38, Types.DOUBLE, null); else stmt.setDouble(38,Double.parseDouble(locust_populated)); + + if(eggs_capsules_area==null) stmt.setNull(39, Types.DOUBLE, null); else stmt.setDouble(39,Double.parseDouble(eggs_capsules_area)); + if(eggs_capsules_density==null) stmt.setNull(40, Types.DOUBLE, null); else stmt.setDouble(40,Double.parseDouble(eggs_capsules_density)); + if(eggs_capsules_density_to==null) stmt.setNull(41, Types.DOUBLE, null); else stmt.setDouble(41,Double.parseDouble(eggs_capsules_density_to)); + if(eggs_capsules==null) stmt.setNull(42, Types.DOUBLE, null); else stmt.setDouble(42,Double.parseDouble(eggs_capsules)); + if(eggs_live==null) stmt.setNull(43, Types.DOUBLE, null); else stmt.setDouble(43,Double.parseDouble(eggs_live)); + if(eggs_enemies_id==null) stmt.setNull(44, Types.INTEGER, null); else stmt.setInt(44,Integer.parseInt(eggs_enemies_id)); + + if(larva_born_id==null) stmt.setNull(45, Types.INTEGER, null); else stmt.setInt(45,Integer.parseInt(larva_born_id)); + if(larva_age_id==null) stmt.setNull(46, Types.INTEGER, null); else stmt.setInt(46,Integer.parseInt(larva_age_id)); + if(larva_painting_id==null) stmt.setNull(47, Types.INTEGER, null); else stmt.setInt(47,Integer.parseInt(larva_painting_id)); + if(larva_behavior_id==null) stmt.setNull(48, Types.INTEGER, null); else stmt.setInt(48,Integer.parseInt(larva_behavior_id)); + + if(larva_density==null) stmt.setNull(49, Types.DOUBLE, null); else stmt.setDouble(49,Double.parseDouble(larva_density)); + if(larva_density_to==null) stmt.setNull(50, Types.DOUBLE, null); else stmt.setDouble(50,Double.parseDouble(larva_density_to)); + if(kuliguli_age_id==null) stmt.setNull(51, Types.INTEGER, null); else stmt.setInt(51,Integer.parseInt(kuliguli_age_id)); + + if(kuliguli_density==null) stmt.setNull(52, Types.DOUBLE, null); else stmt.setDouble(52,Double.parseDouble(kuliguli_density)); + if(kuliguli_density_to==null) stmt.setNull(53, Types.DOUBLE, null); else stmt.setDouble(53,Double.parseDouble(kuliguli_density_to)); + if(kuliguli_size==null) stmt.setNull(54, Types.DOUBLE, null); else stmt.setDouble(54,Double.parseDouble(kuliguli_size)); + if(kuliguli_count==null) stmt.setNull(55, Types.DOUBLE, null); else stmt.setDouble(55,Double.parseDouble(kuliguli_count)); + if(kuliguli_action_id==null) stmt.setNull(56, Types.INTEGER, null); else stmt.setInt(56,Integer.parseInt(kuliguli_action_id)); + if(imago_wing_id==null) stmt.setNull(57, Types.INTEGER, null); else stmt.setInt(57,Integer.parseInt(imago_wing_id)); + if(imago_maturity==null) stmt.setNull(58, Types.BOOLEAN, null); + else { + if(imago_maturity.equals("1")) stmt.setBoolean(58,true); + else stmt.setBoolean(58,false); + } + if(imago_phase_id==null) stmt.setNull(59, Types.INTEGER, null); else stmt.setInt(59,Integer.parseInt(imago_phase_id)); + if(imago_action_id==null) stmt.setNull(60, Types.INTEGER, null); else stmt.setInt(60,Integer.parseInt(imago_action_id)); + + if(imago_density==null) stmt.setNull(61, Types.DOUBLE, null); else stmt.setDouble(61,Double.parseDouble(imago_density)); + if(imago_density_ga==null) stmt.setNull(62, Types.DOUBLE, null); else stmt.setDouble(62,Double.parseDouble(imago_density_ga)); + if(imago_feeding==null) stmt.setNull(63, Types.BOOLEAN, null); + else { + if(imago_feeding.equals("1")) stmt.setBoolean(63,true); + else stmt.setBoolean(63,false); + } + if(imago_copulation==null) stmt.setNull(64, Types.BOOLEAN, null); + else { + if(imago_copulation.equals("1")) stmt.setBoolean(64,true); + else stmt.setBoolean(64,false); + } + if(imago_laying==null) stmt.setNull(65, Types.BOOLEAN, null); + else { + if(imago_laying.equals("1")) stmt.setBoolean(65,true); + else stmt.setBoolean(65,false); + } + if(imago_flying==null) stmt.setNull(66, Types.BOOLEAN, null); + else { + if(imago_flying.equals("1")) stmt.setBoolean(66,true); + else stmt.setBoolean(66,false); + } + if(swarm_maturity==null) stmt.setNull(67, Types.BOOLEAN, null); + else { + if(swarm_maturity.equals("1")) stmt.setBoolean(67,true); + else stmt.setBoolean(67,false); + } + if(swarm_density_id==null) stmt.setNull(68, Types.INTEGER, null); else stmt.setInt(68,Integer.parseInt(swarm_density_id)); + if(swarm_size==null) stmt.setNull(69, Types.DOUBLE, null); else stmt.setDouble(69,Double.parseDouble(swarm_size)); + if(swarm_count==null) stmt.setNull(70, Types.DOUBLE, null); else stmt.setDouble(70,Double.parseDouble(swarm_count)); + if(swarm_copulation==null) stmt.setNull(71, Types.BOOLEAN, null); + else { + if(swarm_copulation.equals("1")) stmt.setBoolean(71,true); + else stmt.setBoolean(71,false); + } + if(swarm_laying==null) stmt.setNull(72, Types.BOOLEAN, null); + else { + if(swarm_laying.equals("1")) stmt.setBoolean(72,true); + else stmt.setBoolean(72,false); + } + if(swarm_flying_direction_id==null) stmt.setNull(73, Types.INTEGER, null); else stmt.setInt(73,Integer.parseInt(swarm_flying_direction_id)); + if(swarm_height_id==null) stmt.setNull(74, Types.INTEGER, null); else stmt.setInt(74,Integer.parseInt(swarm_height_id)); //������(������- �������- �������) + + stmt.setString(75,description); + stmt.setString(76,geom); + if(test==null) stmt.setNull(77, Types.BOOLEAN, null); + else { + if(test.equals("1")) stmt.setBoolean(77,true); + else stmt.setBoolean(77,false); + } + + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=(""); + return result; + } + + //Execute SQL + try { + stmt.execute(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex.getMessage()); + result=(""); + return result; + } + + //If there are drawings, then copy them. + String imgDir="./data/frmlocust/"; + try{ new File(dataDir+imgDir).mkdirs(); }catch (Exception exception) {} + + if(image_name1!=null && !image_name1.equals("")) + { + String filename1=dataDir+tmpDir+image_name1; + File f = new File(filename1); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+image_name1)); + } + } + if(image_name2!=null && !image_name2.equals("")) + { + String filename2=dataDir+tmpDir+image_name2; + File f = new File(filename2); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+image_name2)); + } + } + if(image_name3!=null && !image_name3.equals("")) + { + String filename3=dataDir+tmpDir+image_name3; + File f = new File(filename3); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+image_name3)); + } + } + + result=""; + logRotate(data_dir+"errors.log","XML="+result); + return result; + + }else if(fn.equals("5")) + { + boolean exists=false; + String uid=getCdataValue(reqNode,"uid"); + logger.info("uid="+uid); + Statement st; + try { + st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery("select 1 from main.frmlocustdel where uid=main.strtouuid('"+uid+"')"); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex.getMessage()); + result=(""); + return result; + } + if(rs!=null) + { + if(rs.next()) + exists=true; + } + st.close(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.info("Error",ex); + result=(""); + return result; + } + + PreparedStatement stmt=null; + if(exists) + { + String sql="update main.frmlocustdel set \n" + +" uid=main.strtouuid(?),\n" + +" changed=false,\n" + +" user_id=?,\n" + +" device_id=?,\n" + +" image_name1=?,\n" + +" image_name2=?,\n" + +" image_name3=?,\n" + +" country_id=?,\n" + +" region_id=?,\n" + +" area=?,\n" + +" district=?,\n" + +" village=?,\n" + +" terrain=?,\n" + +" observer=?,\n" + +" date=?,\n" + +" timezone=?::interval,\n" + +" lat_center=?,\n" + +" lon_center=?,\n" + +" lat1=?,\n" + +" lon1=?,\n" + +" lat2=?,\n" + +" lon2=?,\n" + +" lat3=?,\n" + +" lon3=?,\n" + +" lat4=?,\n" + +" lon4=?,\n" + +" lat5=?,\n" + +" lon5=?,\n" + +" lat6=?,\n" + +" lon6=?,\n" + +" infested_area=?,\n" + +" treated_area=?,\n" + +" vegetation_type_id=?,\n" + +" vegetation_height=?,\n" + +" vegetation_crop=?,\n" + +" vegetation_cover_id=?,\n" + +" vegetation_damage=?,\n" + +" vegetation_damage_area=?,\n" + +" insecticide_name=?,\n" + +" insecticide_active_substance=?,\n" + +" insecticide_concentration=?,\n" + +" insecticide_formulation_id=?,\n" + +" insecticide_dose=?,\n" + +" insecticide_rate=?,\n" + +" insecticide_used_volume=?,\n" + +" insecticide_number_spores=?,\n" + +" insecticide_expiry_date=?,\n" + +" insecticide_mixed=?,\n" + +" insecticide_mixed_name=?,\n" + +" insecticide_mixed_ratio=?,\n" + + +" insecticide_diluted_id=?,\n" + +" insecticide_proportion=?,\n" + + +" weather_time_start=?,\n" + +" weather_time_end=?,\n" + +" weather_temperature_start=?,\n" + +" weather_temperature_end=?,\n" + +" weather_humidity_start=?,\n" + +" weather_humidity_end=?,\n" + +" weather_wind_speed_start=?,\n" + +" weather_wind_speed_end=?,\n" + +" weather_direction_start=?,\n" + +" weather_direction_end=?,\n" + +" weather_spray_direction_start=?,\n" + +" weather_spray_direction_end=?,\n" + +" locust_type_id=?,\n" + +" locust_hoppers_id=?,\n" + +" locust_imago=?,\n" + +" locust_density=?,\n" + +" locust_kuliguli=?,\n" + +" locust_swarm=?,\n" + +" locust_sparse=?,\n" + +" locust_phase_id=?,\n" + +" spray_platform=?,\n" + +" spray_platform_a=?,\n" + +" spray_platform_g=?,\n" + +" spray_platform_h=?,\n" + +" spray_capacity_id=?,\n" + +" spray_operatortype_id=?,\n" + +" spray_manufacturer_name=?,\n" + +" spray_model_name=?,\n" + +" spray_height=?,\n" + +" spray_width=?,\n" + +" spray_barrier=?,\n" + +" spray_barrier_width=?,\n" + +" spray_barrier_space=?,\n" + +" spray_speed=?,\n" + +" spray_gps=?,\n" + +" spray_marking_id=?,\n" + +" efficacy_mortality=?,\n" + +" efficacy_passed_time=?,\n" + +" efficacy_mortality_method=?,\n" + +" efficacy_impact_id=?,\n" + +" safety_clothing=?,\n" + +" safety_clothing_clean=?,\n" + +" safety_operator_health=?,\n" + +" description=?,\n" + +" safety_inform=?,\n" + +" safety_container=?,\n" + +" safety_non_target=?,\n" + +" safety_non_target_effect=?,\n" + +" safety_incident=?,\n" + +" safety_incident_effect=?,\n" + +" comments=?,\n" + +" geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" + +" locust_purpose_id=?,\n" //Чтобы много циферек не перебивать сделал внизу запроса + +" test=?\n" + +" where uid=main.strtouuid('"+uid+"')"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=(""); + return result; + } + }else + { + String sql="insert into main.frmlocustdel(\n" + +" uid,\n" + +" changed,\n" + +" user_id,\n" + +" device_id,\n" + +" image_name1,\n" + +" image_name2,\n" + +" image_name3,\n" + +" country_id,\n" + +" region_id,\n" + +" area,\n" + +" district,\n" + +" village,\n" + +" terrain,\n" + +" observer,\n" + +" date,\n" + +" timezone,\n" + +" lat_center,\n" + +" lon_center,\n" + +" lat1,\n" + +" lon1,\n" + +" lat2,\n" + +" lon2,\n" + +" lat3,\n" + +" lon3,\n" + +" lat4,\n" + +" lon4,\n" + +" lat5,\n" + +" lon5,\n" + +" lat6,\n" + +" lon6,\n" + +" infested_area,\n" + +" treated_area,\n" + +" vegetation_type_id,\n" + +" vegetation_height,\n" + +" vegetation_crop,\n" + +" vegetation_cover_id,\n" + +" vegetation_damage,\n" + +" vegetation_damage_area,\n" + +" insecticide_name,\n" + +" insecticide_active_substance,\n" + +" insecticide_concentration,\n" + +" insecticide_formulation_id,\n" + +" insecticide_dose,\n" + +" insecticide_rate,\n" + +" insecticide_used_volume,\n" + +" insecticide_number_spores,\n" + +" insecticide_expiry_date,\n" + +" insecticide_mixed,\n" + +" insecticide_mixed_name,\n" + +" insecticide_mixed_ratio,\n" + + +" insecticide_diluted_id,\n" + +" insecticide_proportion,\n" + + +" weather_time_start,\n" + +" weather_time_end,\n" + +" weather_temperature_start,\n" + +" weather_temperature_end,\n" + +" weather_humidity_start,\n" + +" weather_humidity_end,\n" + +" weather_wind_speed_start,\n" + +" weather_wind_speed_end,\n" + +" weather_direction_start,\n" + +" weather_direction_end,\n" + +" weather_spray_direction_start,\n" + +" weather_spray_direction_end,\n" + +" locust_type_id,\n" + +" locust_hoppers_id,\n" + +" locust_imago,\n" + +" locust_density,\n" + +" locust_kuliguli,\n" + +" locust_swarm,\n" + +" locust_sparse,\n" + +" locust_phase_id,\n" + +" spray_platform,\n" + +" spray_platform_a,\n" + +" spray_platform_g,\n" + +" spray_platform_h,\n" + +" spray_capacity_id,\n" + +" spray_operatortype_id,\n" + +" spray_manufacturer_name,\n" + +" spray_model_name,\n" + +" spray_height,\n" + +" spray_width,\n" + +" spray_barrier,\n" + +" spray_barrier_width,\n" + +" spray_barrier_space,\n" + +" spray_speed,\n" + +" spray_gps,\n" + +" spray_marking_id,\n" + +" efficacy_mortality,\n" + +" efficacy_passed_time,\n" + +" efficacy_mortality_method,\n" + +" efficacy_impact_id,\n" + +" safety_clothing,\n" + +" safety_clothing_clean,\n" + +" safety_operator_health,\n" + +" description,\n" + +" safety_inform,\n" + +" safety_container,\n" + +" safety_non_target,\n" + +" safety_non_target_effect,\n" + +" safety_incident,\n" + +" safety_incident_effect,\n" + +" comments,\n" + +" geom,\n" + +" locust_purpose_id,\n" + +" test\n" + +")values(\n" + +" main.strtouuid(?),\n" //1 uid + +" false,\n" + +" ?,\n" //2 user_id + +" ?,\n" //3 device_id + +" ?,\n" //4 image_name1 + +" ?,\n" //5 image_name2 + +" ?,\n" //6 image_name3 + +" ?,\n" //7 country_id + +" ?,\n" //8 region_id + +" ?,\n" //9 area + +" ?,\n" //10 district + +" ?,\n" //11 village + +" ?,\n" //12 terrain + +" ?,\n" //13 observer + +" ?,\n" //14 date + +" ?::interval,\n" //15 timezone + +" ?,\n" //16 lat_center + +" ?,\n" //17 lon_center + +" ?,\n" //18 lat1 + +" ?,\n" //19 lon1 + +" ?,\n" //20 lat2 + +" ?,\n" //21 lon2 + +" ?,\n" //22 lat3 + +" ?,\n" //23 lon3 + +" ?,\n" //24 lat4 + +" ?,\n" //25 lon4 + +" ?,\n" //26 lat5 + +" ?,\n" //27 lon5 + +" ?,\n" //28 lat6 + +" ?,\n" //29 lon6 + +" ?,\n" //30 infested_area + +" ?,\n" //31 treated_area + +" ?,\n" //32 vegetation_type_id + +" ?,\n" //33 vegetation_height + +" ?,\n" //34 vegetation_crop + +" ?,\n" //35 vegetation_cover_id + +" ?,\n" //36 vegetation_damage + +" ?,\n" //37 vegetation_damage_area + +" ?,\n" //38 insecticide_name + +" ?,\n" //39 insecticide_active_substance + +" ?,\n" //40 insecticide_concentration + +" ?,\n" //41 insecticide_formulation_id + +" ?,\n" //42 insecticide_dose + +" ?,\n" //43 insecticide_rate + +" ?,\n" //44 insecticide_used_volume + +" ?,\n" //45 insecticide_number_spores + +" ?,\n" //46 insecticide_expiry_date + +" ?,\n" //47 insecticide_mixed + +" ?,\n" //48 insecticide_mixed_name + +" ?,\n" //49 insecticide_mixed_ratio + +" ?,\n" //50 insecticide_diluted_id + +" ?,\n" //51 insecticide_proportion + +" ?,\n" //52 weather_time_start + +" ?,\n" //53 weather_time_end + +" ?,\n" //54 weather_temperature_start + +" ?,\n" //55 weather_temperature_end + +" ?,\n" //56 weather_humidity_start + +" ?,\n" //57 weather_humidity_end + +" ?,\n" //58 weather_wind_speed_start + +" ?,\n" //59 weather_wind_speed_end + +" ?,\n" //60 weather_direction_start + +" ?,\n" //61 weather_direction_end + +" ?,\n" //62 weather_spray_direction_start + +" ?,\n" //63 weather_spray_direction_end + +" ?,\n" //64 locust_type_id + +" ?,\n" //65 locust_hoppers_id + +" ?,\n" //66 locust_imago + +" ?,\n" //67 locust_density + +" ?,\n" //68 locust_kuliguli + +" ?,\n" //69 locust_swarm + +" ?,\n" //70 locust_sparse + +" ?,\n" //71 locust_phase_id + +" ?,\n" //72 spray_platform + +" ?,\n" //73 spray_platform_a + +" ?,\n" //74 spray_platform_g + +" ?,\n" //75 spray_platform_h + +" ?,\n" //76 spray_capacity_id + +" ?,\n" //77 spray_operatortype_id + +" ?,\n" //78 spray_manufacturer_name + +" ?,\n" //79 spray_model_name + +" ?,\n" //80 spray_height + +" ?,\n" //81 spray_width + +" ?,\n" //82 spray_barrier + +" ?,\n" //83 spray_barrier_width + +" ?,\n" //84 spray_barrier_space + +" ?,\n" //85 spray_speed + +" ?,\n" //86 spray_gps + +" ?,\n" //87 spray_marking_id + +" ?,\n" //88 efficacy_mortality + +" ?,\n" //89 efficacy_passed_time + +" ?,\n" //90 efficacy_mortality_method + +" ?,\n" //91 efficacy_impact_id + +" ?,\n" //92 safety_clothing + +" ?,\n" //93 safety_clothing_clean + +" ?,\n" //94 safety_operator_health + +" ?,\n" //95 description + +" ?,\n" //96 safety_inform + +" ?,\n" //97 safety_container_id + +" ?,\n" //98 safety_non_target + +" ?,\n" //99 safety_non_target_effect + +" ?,\n" //100 safety_incident + +" ?,\n" //101 safety_incident_effect + +" ?,\n" //102 comments + +" ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //103 geom + +" ?,\n" //104 locust_purpose_id + +" ?\n" //105 test + +")"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=(""); + return result; + } + } + + //String id=getCdataValue(reqNode, "id"); + //String uid=getCdataValue(reqNode, "uid"); //���� ������ + //String del=getCdataValue(reqNode, "del"); + //String seq=getCdataValue(reqNode, "seq"); + String user_id=getCdataValue(reqNode, "user_id"); + String device_id=getCdataValue(reqNode, "device_id"); + String image_name1=getCdataValue(reqNode, "image_name1"); + String image_name2=getCdataValue(reqNode, "image_name2"); + String image_name3=getCdataValue(reqNode, "image_name3"); + + String country_id=getCdataValue(reqNode, "country_id"); + String region_id=getCdataValue(reqNode, "region_id"); + String area=getCdataValue(reqNode, "area"); + String district=getCdataValue(reqNode, "district"); + String village=getCdataValue(reqNode, "village"); + String terrain=getCdataValue(reqNode, "terrain"); + String observer=getCdataValue(reqNode, "observer"); + String date=getCdataValue(reqNode, "date"); + String timezone=getCdataValue(reqNode, "timezone"); + timezone=Tools.numConvert(timezone); + String lat_center=getCdataValue(reqNode, "lat_center"); + String lon_center=getCdataValue(reqNode, "lon_center"); + String lat1=getCdataValue(reqNode, "lat1"); + String lon1=getCdataValue(reqNode, "lon1"); + String lat2=getCdataValue(reqNode, "lat2"); + String lon2=getCdataValue(reqNode, "lon2"); + String lat3=getCdataValue(reqNode, "lat3"); + String lon3=getCdataValue(reqNode, "lon3"); + String lat4=getCdataValue(reqNode, "lat4"); + String lon4=getCdataValue(reqNode, "lon4"); + String lat5=getCdataValue(reqNode, "lat5"); + String lon5=getCdataValue(reqNode, "lon5"); + String lat6=getCdataValue(reqNode, "lat6"); + String lon6=getCdataValue(reqNode, "lon6"); + String infested_area=getCdataValue(reqNode, "infested_area"); + String treated_area=getCdataValue(reqNode, "treated_area"); + String vegetation_type_id=getCdataValue(reqNode, "vegetation_type_id"); + String vegetation_height=getCdataValue(reqNode, "vegetation_height"); + String vegetation_crop=getCdataValue(reqNode, "vegetation_crop"); + String vegetation_cover_id=getCdataValue(reqNode, "vegetation_cover_id"); + String vegetation_damage=getCdataValue(reqNode, "vegetation_damage"); + String vegetation_damage_area=getCdataValue(reqNode, "vegetation_damage_area"); + String insecticide_name=getCdataValue(reqNode, "insecticide_name"); + String insecticide_active_substance=getCdataValue(reqNode, "insecticide_active_substance"); + String insecticide_concentration=getCdataValue(reqNode, "insecticide_concentration"); + String insecticide_formulation_id=getCdataValue(reqNode, "insecticide_formulation_id"); + String insecticide_dose=getCdataValue(reqNode, "insecticide_dose"); + String insecticide_rate=getCdataValue(reqNode, "insecticide_rate"); + String insecticide_used_volume=getCdataValue(reqNode, "insecticide_used_volume"); + String insecticide_number_spores=getCdataValue(reqNode, "insecticide_number_spores"); + String insecticide_expiry_date=getCdataValue(reqNode, "insecticide_expiry_date"); + String insecticide_mixed=getCdataValue(reqNode, "insecticide_mixed"); + String insecticide_mixed_name=getCdataValue(reqNode, "insecticide_mixed_name"); + String insecticide_mixed_ratio=getCdataValue(reqNode, "insecticide_mixed_ratio"); + String insecticide_diluted_id=getCdataValue(reqNode, "insecticide_diluted_id"); + String insecticide_proportion=getCdataValue(reqNode, "insecticide_proportion"); + String weather_time_start=getCdataValue(reqNode, "weather_time_start"); + String weather_time_end=getCdataValue(reqNode, "weather_time_end"); + String weather_temperature_start=getCdataValue(reqNode, "weather_temperature_start"); + String weather_temperature_end=getCdataValue(reqNode, "weather_temperature_end"); + String weather_humidity_start=getCdataValue(reqNode, "weather_humidity_start"); + String weather_humidity_end=getCdataValue(reqNode, "weather_humidity_end"); + String weather_wind_speed_start=getCdataValue(reqNode, "weather_wind_speed_start"); + String weather_wind_speed_end=getCdataValue(reqNode, "weather_wind_speed_end"); + String weather_direction_start=getCdataValue(reqNode, "weather_direction_start"); + String weather_direction_end=getCdataValue(reqNode, "weather_direction_end"); + String weather_spray_direction_start=getCdataValue(reqNode, "weather_spray_direction_start"); + String weather_spray_direction_end=getCdataValue(reqNode, "weather_spray_direction_end"); + String locust_type_id=getCdataValue(reqNode, "locust_type_id"); + String locust_hoppers_id=getCdataValue(reqNode, "locust_hoppers_id"); + String locust_imago=getCdataValue(reqNode, "locust_imago"); + String locust_density=getCdataValue(reqNode, "locust_density"); + String locust_kuliguli=getCdataValue(reqNode, "locust_kuliguli"); + String locust_swarm=getCdataValue(reqNode, "locust_swarm"); + String locust_sparse=getCdataValue(reqNode, "locust_sparse"); + String locust_phase_id=getCdataValue(reqNode, "locust_phase_id"); + String spray_platform=getCdataValue(reqNode, "spray_platform"); + String spray_platform_a=getCdataValue(reqNode, "spray_platform_a"); + String spray_platform_g=getCdataValue(reqNode, "spray_platform_g"); + String spray_platform_h=getCdataValue(reqNode, "spray_platform_h"); + String spray_capacity_id=getCdataValue(reqNode, "spray_capacity_id"); + String spray_operatortype_id=getCdataValue(reqNode, "spray_operatortype_id"); + String spray_manufacturer_name=getCdataValue(reqNode, "spray_manufacturer_name"); + String spray_model_name=getCdataValue(reqNode, "spray_model_name"); + String spray_height=getCdataValue(reqNode, "spray_height"); + String spray_width=getCdataValue(reqNode, "spray_width"); + String spray_barrier=getCdataValue(reqNode, "spray_barrier"); + String spray_barrier_width=getCdataValue(reqNode, "spray_barrier_width"); + String spray_barrier_space=getCdataValue(reqNode, "spray_barrier_space"); + String spray_speed=getCdataValue(reqNode, "spray_speed"); + String spray_gps=getCdataValue(reqNode, "spray_gps"); + String spray_marking_id=getCdataValue(reqNode, "spray_marking_id"); + String efficacy_mortality=getCdataValue(reqNode, "efficacy_mortality"); + String efficacy_passed_time=getCdataValue(reqNode, "efficacy_passed_time"); + String efficacy_mortality_method=getCdataValue(reqNode, "efficacy_mortality_method"); + String efficacy_impact_id=getCdataValue(reqNode, "efficacy_impact_id"); + String safety_clothing=getCdataValue(reqNode, "safety_clothing"); + String safety_clothing_clean=getCdataValue(reqNode, "safety_clothing_clean"); + String safety_operator_health=getCdataValue(reqNode, "safety_operator_health"); + String description=getCdataValue(reqNode, "description"); + String safety_inform=getCdataValue(reqNode, "safety_inform"); + + String safety_container_id=getCdataValue(reqNode, "safety_container_id"); + String safety_container=getCdataValue(reqNode, "safety_container"); + if(safety_container==null) safety_container=safety_container_id; + + String safety_non_target=getCdataValue(reqNode, "safety_non_target"); + String safety_non_target_effect=getCdataValue(reqNode, "safety_non_target_effect"); + + String safety_incident=getCdataValue(reqNode, "safety_incident"); + String safety_incident_effect=getCdataValue(reqNode, "safety_incident_effect"); + String comments=getCdataValue(reqNode, "comments"); + String geom=getCdataValue(reqNode, "geom"); + String locust_purpose_id=getCdataValue(reqNode, "locust_purpose_id"); + String test=getCdataValue(reqNode, "test"); + if(test==null) test="0"; + + //stmt.setString(':id', $id, PDO::PARAM_INT); + try { + stmt.setString(1,uid); + + //stmt.setInt(':del', del); + //stmt.setInt(':seq', seq); + //stmt.setInt(':changed', changed); + + if(user_id==null) + stmt.setNull(2, Types.INTEGER, null); + else + stmt.setInt(2,Integer.parseInt(user_id)); + + stmt.setString(3,device_id); + stmt.setString(4,image_name1); + stmt.setString(5,image_name2); + stmt.setString(6,image_name3); + if(country_id==null) stmt.setNull(7, Types.INTEGER, null); else stmt.setInt(7,Integer.parseInt(country_id)); + if(region_id==null) stmt.setNull(8, Types.INTEGER, null); else stmt.setInt(8,Integer.parseInt(region_id)); + stmt.setString(9,area); + stmt.setString(10,district); + stmt.setString(11,village); + stmt.setString(12,terrain); + stmt.setString(13,observer); + + if(date==null) + { + stmt.setNull(14, Types.DATE, null); + }else + { + if(date.indexOf("-")==-1) //If old date format in UNIX time + { + int uDate=Integer.parseInt(date)+1; + java.sql.Timestamp tm=new java.sql.Timestamp((long)uDate*1000); + stmt.setTimestamp(14, 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(date).getTime()); + } catch (Exception ex) { + logger.error("Error",ex.getMessage()); + } + stmt.setTimestamp(14, tm); + } + } + stmt.setString(15,timezone); + + if(lat_center==null) stmt.setNull(16, Types.DOUBLE, null); else stmt.setDouble(16,Double.parseDouble(lat_center)); + if(lon_center==null) stmt.setNull(17, Types.DOUBLE, null); else stmt.setDouble(17,Double.parseDouble(lon_center)); + if(lat1==null) stmt.setNull(18, Types.DOUBLE, null); else stmt.setDouble(18,Double.parseDouble(lat1)); + if(lon1==null) stmt.setNull(19, Types.DOUBLE, null); else stmt.setDouble(19,Double.parseDouble(lon1)); + if(lat2==null) stmt.setNull(20, Types.DOUBLE, null); else stmt.setDouble(20,Double.parseDouble(lat2)); + if(lon2==null) stmt.setNull(21, Types.DOUBLE, null); else stmt.setDouble(21,Double.parseDouble(lon2)); + if(lat3==null) stmt.setNull(22, Types.DOUBLE, null); else stmt.setDouble(22,Double.parseDouble(lat3)); + if(lon3==null) stmt.setNull(23, Types.DOUBLE, null); else stmt.setDouble(23,Double.parseDouble(lon3)); + if(lat4==null) stmt.setNull(24, Types.DOUBLE, null); else stmt.setDouble(24,Double.parseDouble(lat4)); + if(lon4==null) stmt.setNull(25, Types.DOUBLE, null); else stmt.setDouble(25,Double.parseDouble(lon4)); + if(lat5==null) stmt.setNull(26, Types.DOUBLE, null); else stmt.setDouble(26,Double.parseDouble(lat5)); + if(lon5==null) stmt.setNull(27, Types.DOUBLE, null); else stmt.setDouble(27,Double.parseDouble(lon5)); + if(lat6==null) stmt.setNull(28, Types.DOUBLE, null); else stmt.setDouble(28,Double.parseDouble(lat6)); + if(lon6==null) stmt.setNull(29, Types.DOUBLE, null); else stmt.setDouble(29,Double.parseDouble(lon6)); + + if(infested_area==null) stmt.setNull(30, Types.DOUBLE, null); else stmt.setDouble(30,Double.parseDouble(infested_area)); + if(treated_area==null) stmt.setNull(31, Types.DOUBLE, null); else stmt.setDouble(31,Double.parseDouble(treated_area)); + + if(vegetation_type_id==null) stmt.setNull(32, Types.INTEGER, null); else stmt.setInt(32,Integer.parseInt(vegetation_type_id)); + + if(vegetation_height==null) stmt.setNull(33, Types.DOUBLE, null); else stmt.setDouble(33,Double.parseDouble(vegetation_height)); + stmt.setString(34,vegetation_crop); + if(vegetation_cover_id==null) stmt.setNull(35, Types.INTEGER, null); else stmt.setInt(35,Integer.parseInt(vegetation_cover_id)); + if(vegetation_damage==null) stmt.setNull(36, Types.INTEGER, null); else stmt.setInt(36,Integer.parseInt(vegetation_damage)); + if(vegetation_damage_area==null) stmt.setNull(37, Types.DOUBLE, null); else stmt.setDouble(37,Double.parseDouble(vegetation_damage_area)); + + stmt.setString(38,insecticide_name); + stmt.setString(39,insecticide_active_substance); + stmt.setString(40,insecticide_concentration); //if(insecticide_concentration==null) stmt.setNull(39, Types.INTEGER, null); else stmt.setInt(39,Integer.parseInt(insecticide_concentration)); + if(insecticide_formulation_id==null) stmt.setNull(41, Types.INTEGER, null); else stmt.setInt(41,Integer.parseInt(insecticide_formulation_id)); + + if(insecticide_dose==null) stmt.setNull(42, Types.DOUBLE, null); else stmt.setDouble(42,Double.parseDouble(insecticide_dose)); + if(insecticide_rate==null) stmt.setNull(43, Types.DOUBLE, null); else stmt.setDouble(43,Double.parseDouble(insecticide_rate)); + if(insecticide_used_volume==null) stmt.setNull(44, Types.DOUBLE, null); else stmt.setDouble(44,Double.parseDouble(insecticide_used_volume)); + if(insecticide_number_spores==null) stmt.setNull(45, Types.DOUBLE, null); else stmt.setDouble(45,Double.parseDouble(insecticide_number_spores)); + if(insecticide_expiry_date==null) stmt.setNull(46, Types.INTEGER, null); else stmt.setInt(46,Integer.parseInt(insecticide_expiry_date)); + stmt.setString(47,insecticide_mixed); + stmt.setString(48,insecticide_mixed_name); + if(insecticide_mixed_ratio==null) stmt.setNull(49, Types.INTEGER, null); else stmt.setInt(49,Integer.parseInt(insecticide_mixed_ratio)); + + if(insecticide_diluted_id==null) stmt.setNull(50, Types.INTEGER, null); else stmt.setInt(50,Integer.parseInt(insecticide_diluted_id)); + if(insecticide_proportion==null) stmt.setNull(51, Types.DOUBLE, null); else stmt.setDouble(51,Double.parseDouble(insecticide_proportion)); + + if(weather_time_start==null) stmt.setNull(52, Types.DOUBLE, null); else stmt.setDouble(52,Double.parseDouble(weather_time_start)); + if(weather_time_end==null) stmt.setNull(53, Types.DOUBLE, null); else stmt.setDouble(53,Double.parseDouble(weather_time_end)); + if(weather_temperature_start==null) stmt.setNull(54, Types.DOUBLE, null); else stmt.setDouble(54,Double.parseDouble(weather_temperature_start)); + if(weather_temperature_end==null) stmt.setNull(55, Types.DOUBLE, null); else stmt.setDouble(55,Double.parseDouble(weather_temperature_end)); + if(weather_humidity_start==null) stmt.setNull(56, Types.DOUBLE, null); else stmt.setDouble(56,Double.parseDouble(weather_humidity_start)); + if(weather_humidity_end==null) stmt.setNull(57, Types.DOUBLE, null); else stmt.setDouble(57,Double.parseDouble(weather_humidity_end)); + if(weather_wind_speed_start==null) stmt.setNull(58, Types.DOUBLE, null); else stmt.setDouble(58,Double.parseDouble(weather_wind_speed_start)); + if(weather_wind_speed_end==null) stmt.setNull(59, Types.DOUBLE, null); else stmt.setDouble(59,Double.parseDouble(weather_wind_speed_end)); + + if(weather_direction_start==null) stmt.setNull(60, Types.INTEGER, null); else stmt.setInt(60,Integer.parseInt(weather_direction_start)); + if(weather_direction_end==null) stmt.setNull(61, Types.INTEGER, null); else stmt.setInt(61,Integer.parseInt(weather_direction_end)); + if(weather_spray_direction_start==null) stmt.setNull(62, Types.INTEGER, null); else stmt.setInt(62,Integer.parseInt(weather_spray_direction_start)); + if(weather_spray_direction_end==null) stmt.setNull(63, Types.INTEGER, null); else stmt.setInt(63,Integer.parseInt(weather_spray_direction_end)); + + if(locust_type_id==null) stmt.setNull(64, Types.INTEGER, null); else stmt.setInt(64,Integer.parseInt(locust_type_id)); + if(locust_hoppers_id==null) stmt.setNull(65, Types.INTEGER, null); else stmt.setInt(65,Integer.parseInt(locust_hoppers_id)); + if(locust_imago==null) stmt.setNull(66, Types.BOOLEAN, null); + else { if(locust_imago.equals("1")) stmt.setBoolean(66,true); else stmt.setBoolean(66,false); } + + if(locust_density==null) stmt.setNull(67, Types.DOUBLE, null); else stmt.setDouble(67,Double.parseDouble(locust_density)); + if(locust_kuliguli==null) stmt.setNull(68, Types.BOOLEAN, null); + else { + if(locust_kuliguli.equals("1")) stmt.setBoolean(68,true); + else stmt.setBoolean(68,false); + } + if(locust_swarm==null) stmt.setNull(69, Types.BOOLEAN, null); + else { + if(locust_swarm.equals("1")) stmt.setBoolean(69,true); + else stmt.setBoolean(69,false); + } + if(locust_sparse==null) stmt.setNull(70, Types.BOOLEAN, null); + else { + if(locust_sparse.equals("1")) stmt.setBoolean(70,true); + else stmt.setBoolean(70,false); + } + + if(locust_phase_id==null) stmt.setNull(71, Types.INTEGER, null); else stmt.setInt(71,Integer.parseInt(locust_phase_id)); + + + if(spray_platform==null) stmt.setNull(72, Types.INTEGER, null); else stmt.setInt(72,Integer.parseInt(spray_platform)); + if(spray_platform_a==null) stmt.setNull(73, Types.INTEGER, null); else stmt.setInt(73,Integer.parseInt(spray_platform_a)); + if(spray_platform_g==null) stmt.setNull(74, Types.INTEGER, null); else stmt.setInt(74,Integer.parseInt(spray_platform_g)); + if(spray_platform_h==null) stmt.setNull(75, Types.INTEGER, null); else stmt.setInt(75,Integer.parseInt(spray_platform_h)); + if(spray_capacity_id==null) stmt.setNull(76, Types.INTEGER, null); else stmt.setInt(76,Integer.parseInt(spray_capacity_id)); + if(spray_operatortype_id==null) stmt.setNull(77, Types.INTEGER, null); else stmt.setInt(77,Integer.parseInt(spray_operatortype_id)); + stmt.setString(78,spray_manufacturer_name); + stmt.setString(79,spray_model_name); + if(spray_height==null) stmt.setNull(80, Types.DOUBLE, null); else stmt.setDouble(80,Double.parseDouble(spray_height)); + if(spray_width==null) stmt.setNull(81, Types.DOUBLE, null); else stmt.setDouble(81,Double.parseDouble(spray_width)); + if(spray_barrier==null) stmt.setNull(82, Types.BOOLEAN, null); + else { + if(spray_barrier.equals("1")) stmt.setBoolean(82,true); + else stmt.setBoolean(82,false); + } + if(spray_barrier_width==null) stmt.setNull(83, Types.DOUBLE, null); else stmt.setDouble(83,Double.parseDouble(spray_barrier_width)); + if(spray_barrier_space==null) stmt.setNull(84, Types.DOUBLE, null); else stmt.setDouble(84,Double.parseDouble(spray_barrier_space)); + if(spray_speed==null) stmt.setNull(85, Types.DOUBLE, null); else stmt.setDouble(85,Double.parseDouble(spray_speed)); + if(spray_gps==null) stmt.setNull(86, Types.BOOLEAN, null); + else { + if(spray_gps.equals("1")) stmt.setBoolean(86,true); + else stmt.setBoolean(86,false); + } + if(spray_marking_id==null) stmt.setNull(87, Types.INTEGER, null); else stmt.setInt(87,Integer.parseInt(spray_marking_id)); + + if(efficacy_mortality==null) stmt.setNull(88, Types.DOUBLE, null); else stmt.setDouble(88,Double.parseDouble(efficacy_mortality)); + if(efficacy_passed_time==null) stmt.setNull(89, Types.DOUBLE, null); else stmt.setDouble(89,Double.parseDouble(efficacy_passed_time)); + if(efficacy_mortality_method==null) stmt.setNull(90, Types.INTEGER, null); else stmt.setInt(90,Integer.parseInt(efficacy_mortality_method)); + if(efficacy_impact_id==null) stmt.setNull(91, Types.INTEGER, null); else stmt.setInt(91,Integer.parseInt(efficacy_impact_id)); + stmt.setString(92,safety_clothing); + if(safety_clothing_clean==null) stmt.setNull(93, Types.BOOLEAN, null); + else { + if(safety_clothing_clean.equals("1")) stmt.setBoolean(93,true); + else stmt.setBoolean(93,false); + } + if(safety_operator_health==null) stmt.setNull(94, Types.BOOLEAN, null); + else { + if(safety_operator_health.equals("1")) stmt.setBoolean(94,true); + else stmt.setBoolean(94,false); + } + stmt.setString(95,description); + stmt.setString(96,safety_inform); + stmt.setString(97,safety_container); //Теперь набор id в виде строки, раньше было так: "if(safety_container_id==null) stmt.setNull(93, Types.INTEGER, null); else stmt.setInt(93,Integer.parseInt(safety_container_id));" + if(safety_non_target==null) stmt.setNull(98, Types.BOOLEAN, null); + else { + if(safety_non_target.equals("1")) stmt.setBoolean(98,true); + else stmt.setBoolean(98,false); + } + stmt.setString(99,safety_non_target_effect); + if(safety_incident==null) stmt.setNull(100, Types.BOOLEAN, null); + else { + if(safety_incident.equals("1")) stmt.setBoolean(100,true); + else stmt.setBoolean(100,false); + } + stmt.setString(101,safety_incident_effect); + stmt.setString(102,comments); + stmt.setString(103,geom); + + if(locust_purpose_id==null) + stmt.setNull(104, Types.INTEGER, null); + else + stmt.setInt(104,Integer.parseInt(locust_purpose_id)); + + if(test==null) stmt.setNull(105, Types.BOOLEAN, null); + else { + if(test.equals("1")) stmt.setBoolean(105,true); + else stmt.setBoolean(105,false); + } + + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + return result; + } + + //Execute SQL + try { + stmt.execute(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + return result; + } + + //If there are drawings, then copy them. + String imgDir="./data/frmlocustdel/"; + try{ new File(dataDir+imgDir).mkdirs(); }catch (Exception exception) {} + if(image_name1!=null && !image_name1.equals("")) + { + String filename1=dataDir+tmpDir+image_name1; + File f = new File(filename1); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+image_name1)); + } + } + if(image_name2!=null && !image_name2.equals("")) + { + String filename2=dataDir+tmpDir+image_name2; + File f = new File(filename2); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+image_name2)); + } + } + if(image_name3!=null && !image_name3.equals("")) + { + String filename3=dataDir+tmpDir+image_name3; + File f = new File(filename3); + if(f.exists() && !f.isDirectory()) { + f.renameTo(new File(dataDir+imgDir+image_name3)); + } + } + + result=""; + logRotate(data_dir+"errors.log","XML="+result); + return result; + + }else + { + result=""; + return result; + } + + } catch (Exception ex) { + //logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + }finally { + if(conn!=null){ try{ conn.close(); }catch(Exception e){} } + } + return result; + } + @RequestMapping(value = "/get/",params = {"fn"},method = { RequestMethod.GET, RequestMethod.POST }) + @ResponseBody + public Object uploadFILE(HttpServletResponse response,@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) String reqData,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="fn") String fn,@RequestParam(required=false,name="r") String reqR,@RequestParam(required=false,name="n") String reqN,@RequestParam(required=false,name="s") String reqS,@RequestParam(required=false,name="l") String reqL,@RequestParam(required=false,name="days",defaultValue = "0") int days,@RequestParam(required=false,name="country_id",defaultValue = "0") int country_id,@RequestParam(required=false,name="android_id",defaultValue = "") String device_id) { + + if(contentType!=null) + logger.info("Content-Type = " + contentType); //INFO : kz.locust.CCALM.AcceptASDC - Content-Type = multipart/form-data; boundary=kTwyQRMc7R9JvmcYlXyvMEwX6B08jb + + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + + String result=""; + if(fn==null || (!fn.equals("1") && !fn.equals("6"))) + { + response.setContentType("application/xml"); + return result; + } + + //String metadata_file = ""; + 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 ex) { + ex.printStackTrace(); + logger.error("Error load org_ccalm_main.properties",ex); + } + + + //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!"); + } else { + logger.info("An error occurred while connecting to the database!"); + } + //Set UTC time + Statement stm=null; + try { + stm = conn.createStatement(); + stm.execute("SET timezone TO 'UTC';"); + stm.close(); + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + response.setContentType("application/xml"); + return result; + } + + + //Send tables handbook(list) to client. + if(fn.equals("1")) + { + //int pR=0; + String pN=""; + int pS=0; + //int pL=0; + + String val; + val = reqR; + //if(val!=null) pR=Integer.parseInt(val); + pN = reqN; + val = reqS; + if(val!=null) pS=Integer.parseInt(val); + val = reqL; + //if(val!=null) pL=100; + + //return new FileSystemResource(file); + response.setContentType("application/octet-stream"); + response.setHeader("Content-Disposition","attachment; filename="+pN+".tbl"); + + String sql; + + if(pN.equals("frmlocustdel_locations") && days>0 && country_id>0){ + //sql = "select fldl.* from main.frmlocustdel_locations fldl join main.frmlocustdel fld on main.strtouuid(fld.uid)=main.strtouuid(fldl.frmlocustdel_uid) where fld.date>now()-interval '"+String.valueOf(days)+" days' and fld.country_id="+String.valueOf(country_id)+" and fldl.seq>"+pS+" and fld.device_id!='"+device_id+"' order by fldl.seq"; + sql = "select fldl.* from main.frmlocustdel_locations fldl join main.frmlocustdel fld on main.strtouuid(fld.uid)=main.strtouuid(fldl.frmlocustdel_uid) where fld.date>now()-interval '"+String.valueOf(days)+" days' and fld.country_id="+String.valueOf(country_id)+" and fldl.seq>"+pS+" order by fldl.seq"; //TODO удалить + }else + if(pN.equals("frmlocustdel") && days>0 && country_id>0){ + Map fields = TCTableTools.getTableSchema(conn, "main", "frmlocustdel"); + STools.delFromMapByValue(fields, "geometry"); //Исключаем поля с типом геометрия, SQLite в android их не понимает + //sql = "select "+String.join(", ", fields.keySet())+" from main.frmlocustdel where date>now()-interval '"+String.valueOf(days)+" days' and country_id="+String.valueOf(country_id)+" and seq>"+pS+" and device_id!='"+device_id+"' order by seq"; + sql = "select "+String.join(", ", fields.keySet())+" from main.frmlocustdel where date>now()-interval '"+String.valueOf(days)+" days' and country_id="+String.valueOf(country_id)+" and seq>"+pS+" order by seq"; //TODO удалить + }else + if(pN.equals("_translations")) + { + sql = "select t.* from main._translations t join main._translations_subsystems ts on ts.translation_id=t.id and ts.subsistem_id=2 where t.seq>"+pS+" order by seq"; + }else + { + Map fields = TCTableTools.getTableSchema(conn, "main", pN); + STools.delFromMapByValue(fields, "geometry"); //Исключаем поля с типом геометрия, SQLite в android их не понимает + sql = "select "+String.join(", ", fields.keySet())+" from main."+pN+" where seq>"+pS+" order by seq"; + } + + try { + Statement st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery(sql); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + response.setContentType("application/xml"); + return result; + } + + try { + if(rs!=null) + { + TCTable tbl=new TCTable(pN,123456); + logger.info("*** "+pN+" ***"); + + 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(response.getOutputStream()); + 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)); + //logger.info(String.valueOf(i)+") "+rs.getString(i)); + }else { + tbl.fields.get(i - 1).setValue(null); + } + } + //Save binary data to stream + tbl.getCol(response.getOutputStream()); + } + } + st.close(); + + //response.getOutputStream(); + response.flushBuffer(); + } catch (IOException e) { + } + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=""; + response.setContentType("application/xml"); + return result; + } + + return null; + + }else + if(fn.equals("6")) { + + //Create temporary directory + String dataDir = data_dir; + String tmpDir = "temp"+File.separator; + try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) { + logger.error("Error",ex); + result=""; + response.setContentType("application/xml"); + return result; + } + + deleteOldFiles(dataDir+tmpDir,24*60*60*10); //If the files are older than 10 days then delete them. + + String fileName = ""; + + if (file!=null && !file.isEmpty()) { + try { + + byte[] bytes = file.getBytes(); + fileName = file.getOriginalFilename(); + + File dir = new File(dataDir+tmpDir); + if (!dir.exists()) dir.mkdirs(); + + BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(dataDir+tmpDir+fileName))); + stream.write(bytes); + stream.flush(); + stream.close(); + logger.info("Uploaded Filename: " + dataDir+tmpDir+fileName); + + } catch (Exception ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + } + result=""; + }else + { + result=""; + } + } + response.setContentType("application/xml"); + + } catch (Exception ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + }finally { + if(conn!=null) {try { conn.close(); } catch (SQLException e) {} } + } + return result; + } + + /** + * Получить данные для вставки либо обновления (потом сделать универсальной функцией) + * @param contentType + * @param reqData + * @return + */ + @RequestMapping(value = "/asdc/tctable/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/octet-stream") + @ResponseBody + public Object uploadTCTable(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestParam(required=false,name="file") MultipartFile file) { + + System.out.println("/asdc/tctable/"); + + JSONObject result = new JSONObject(); + result.put("error_code", 0); + result.put("error_message", ""); + + byte[] reqData=null; + if(file!=null) { + try { + reqData = file.getBytes(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + if(reqData==null) + return "OK"; + + 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 ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + try { + Statement sttTZ = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sttTZ.executeUpdate("SET TIME ZONE 'UTC';"); + sttTZ.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + InputStream isRaw = null; + isRaw = new ByteArrayInputStream(reqData); + + TCTable tbl = new TCTable("", 0); + try { + if (tbl.OpenTableH(isRaw)) { + + if(tbl.name.equals("frmlocustdel_locations")) { + while (tbl.ReadNextRecord()) { + String uid=tbl.fields.get(0).getStrVal(); + if(uid==null || uid.isEmpty()) continue; //Для не пропуска переходных записей... + + boolean exists = false; //Is there a record. + Statement st; + try { + ResultSet rs = null; + st = conn.createStatement(); + try { + String sql = "select 1 from main.frmlocustdel_locations where uid=main.strtouuid('"+uid+"')"; + rs = st.executeQuery(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + if (rs != null) { + if (rs.next()) + exists = true; + } + st.close(); + + PreparedStatement stmt = null; + String sql = ""; + if (exists) { + sql = """ + update main.frmlocustdel_locations set + del=?, + seq=?, + frmlocustdel_uid=main.strtouuid(?), + pos=?, + lon=?, + lat=? + where + uid=main.strtouuid(?) + """; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + } else { + sql = """ + insert into main.frmlocustdel_locations( + del, + seq, + frmlocustdel_uid, + pos, + lon, + lat, + uid + )values( + ?, + ?, + main.strtouuid(?), + ?, + ?, + ?, + main.strtouuid(?) + ) + """; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + } + try { + stmt.setBoolean(1, tbl.fields.get(1).getBoolVal()); + stmt.setLong(2, tbl.fields.get(2).getUIntVal()); + stmt.setString(3, tbl.fields.get(3).getStrVal()); + stmt.setInt(4, tbl.fields.get(4).getIntVal()); + stmt.setDouble(5, tbl.fields.get(5).getDoubleVal()); + stmt.setDouble(6, tbl.fields.get(6).getDoubleVal()); + stmt.setString(7, tbl.fields.get(0).getStrVal()); + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + + //Выпоняю запрос на свтавку либо обновление + try { + stmt.execute(); + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + + } + }else{ + //Если это универсальная функция по обновлению данных (похожая функция есть в андроид приложении) + + //Проверка на существование полей в обеих таблицах + ExistsType[] fb=new ExistsType[tbl.fields.size()]; + Map col = TCTableTools.getTableSchema(conn, "main", tbl.name); + for(int i=0;i> iterator = col.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + if (entry.getKey().equalsIgnoreCase(col.get(i))) { + fb[i].exists=true; + fb[i].type=entry.getValue(); + break; + } + } + } + //Переписываем значения существующих полей и выполняем запросы + while(tbl.ReadNextRecord()) + { + String sql=null; + String[] par=null; + if(tbl.getRowByName("id")!=null && tbl.getRowByName("id").getStrVal()!=null){ + sql="select 1 from main."+tbl.name+" where id = ?"; + par = new String[] { tbl.getRowByName("id").getStrVal() }; + }else if(tbl.getRowByName("uid")!=null && tbl.getRowByName("id").getStrVal()!=null){ + sql="select 1 from main."+tbl.name+" where uid = main.strtouuid(?)"; + par = new String[] { tbl.getRowByName("uid").getStrVal() }; + } + if(sql==null) + continue; + + boolean exists=false; + ResultSet rs = null; + Statement st = conn.createStatement(); + try { + rs = st.executeQuery(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + logger.error("Error:",ex); + result.put("error_code",1); + result.put("error_message", ex.getMessage()); + return result.toString(); + } + if (rs != null) { + if (rs.next()) + exists = true; + } + st.close(); + + PreparedStatement stmt = null; + sql = ""; + if (exists) { + sql="update main."+tbl.name+" set "; + for(int i=0;iРезультат
"; + + 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 ex) { + ex.printStackTrace(); + logger.error("Error load org_ccalm_main.properties",ex); + } + + //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!"); + } else { + logRotate(data_dir+"errors.log","An error occurred while connecting to the database!"); + logger.info("An error occurred while connecting to the database!"); + } + try { + Statement sttTZ = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sttTZ.executeUpdate("SET TIME ZONE 'UTC';"); + sttTZ.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + int cnt=0; + String sql; + + sql = "select id,image_name1,image_name2,image_name3 from main.frmlocust where del=false order by id desc"; + try { + Statement st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery(sql); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=ex.getMessage(); + return result; + } + + //try { + if(rs!=null) + { + while (rs.next()) + { + if(rs.getString(2)!=null) + { + File file = new File(data_dir + "data/frmlocust/" + rs.getString(2)); + if(!file.exists()) + { + cnt++; + result+=cnt+") update main.frmlocust set image_name1=null where id="+rs.getString(1)+" and image_name1='"+rs.getString(2)+"';
"; + } + } + if(rs.getString(3)!=null) + { + File file = new File(data_dir + "data/frmlocust/" + rs.getString(3)); + if(!file.exists()) + { + cnt++; + result+=cnt+") update main.frmlocust set image_name2=null where id="+rs.getString(1)+" and image_name2='"+rs.getString(3)+"';
"; + } + } + if(rs.getString(4)!=null) + { + File file = new File(data_dir + "data/frmlocust/" + rs.getString(4)); + if(!file.exists()) + { + cnt++; + result+=cnt+") update main.frmlocust set image_name3=null where id="+rs.getString(1)+" and image_name3='"+rs.getString(4)+"';
"; + } + } + } + } + //st.close(); + //response.getOutputStream(); + //response.flushBuffer(); + //} catch (IOException e) { + //} + + + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=ex.getMessage(); + return result; + } + + result+="
"; + + sql = "select id,image_name1,image_name2,image_name3 from main.frmlocustdel where del=false order by id desc"; + try { + Statement st = conn.createStatement(); + ResultSet rs=null; + try { + rs = st.executeQuery(sql); + } catch( SQLException ex ) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=ex.getMessage(); + return result; + } + + //try { + if(rs!=null) + { + while (rs.next()) + { + if(rs.getString(2)!=null) + { + File file = new File(data_dir + "data/frmlocustdel/" + rs.getString(2)); + if(!file.exists()) + { + cnt++; + result+=cnt+") update main.frmlocustdel set image_name1=null where id="+rs.getString(1)+" and image_name1='"+rs.getString(2)+"';
"; + } + } + if(rs.getString(3)!=null) + { + File file = new File(data_dir + "data/frmlocustdel/" + rs.getString(3)); + if(!file.exists()) + { + cnt++; + result+=cnt+") update main.frmlocustdel set image_name2=null where id="+rs.getString(1)+" and image_name2='"+rs.getString(3)+"';
"; + } + } + if(rs.getString(4)!=null) + { + File file = new File(data_dir + "data/frmlocustdel/" + rs.getString(4)); + if(!file.exists()) + { + cnt++; + result+=cnt+") update main.frmlocustdel set image_name3=null where id="+rs.getString(1)+" and image_name3='"+rs.getString(4)+"';
"; + } + } + } + } + //st.close(); + //response.getOutputStream(); + //response.flushBuffer(); + //} catch (IOException e) { + //} + + + } catch (SQLException ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("Error",ex); + result=ex.getMessage(); + return result; + } + + result+=""; + + } catch (Exception ex) { + logRotate(data_dir+"errors.log",ex.getMessage()); + logger.error("error",ex); + }finally{ + if(conn!=null){ try{ conn.close(); }catch(Exception e){} } + } + return result; + } + + @Override + public void setServletContext(ServletContext context) { + this.context=context; + } + + public String getCdataValue(Element node,String name) + { + String result=""; + Node nextnode=node.getFirstChild(); + while(nextnode!=null) + { + if(nextnode.getNodeName().equals(name)) + { + Node cdata=nextnode.getFirstChild(); + if(cdata!=null) result=cdata.getNodeValue(); + break; + } + nextnode = nextnode.getNextSibling(); + } + if(result.equals("") || result.equals("null")) + return null; + else + return result; + } + + boolean deleteOldFiles(String dir,int sec) + { + boolean result=true; + try{ + File folder = new File(dir); + File[] listOfFiles = folder.listFiles(); + if(listOfFiles!=null) + { + for (int i = 0; i < listOfFiles.length; i++) + { if (listOfFiles[i].isFile()) + { + File file = listOfFiles[i]; + long time = (System.currentTimeMillis() - file.lastModified()) / 1000L; + if(time>sec) + listOfFiles[i].delete(); + } else if (listOfFiles[i].isDirectory()) + { //System.out.println("Directory " + listOfFiles[i].getName()); + } + } + } + }catch(Exception ex) + { + System.out.println(ex.getMessage()); + logger.error("Error",ex); + result=false; + } + return result; + } + + //Сохраняю лог в текстовый файл (для логирования ошибок) + void logRotate(String aFileName, String line) + { + try { + long fileSize = 0; + File file = new File(aFileName); + if (file.exists() || file.isFile()) + { + fileSize = file.length(); + } + if(fileSize>1024*1024*10) //Переименовываем файл если он привысил размер + { + + } + BufferedWriter writer = new BufferedWriter(new FileWriter(aFileName,true)); + writer.write(line); + writer.newLine(); + writer.close(); + } catch (IOException ex) { + logger.error("Error",ex); + } + } +} diff --git a/src/main/java/org/ccalm/main/AcceptEXCEL.java b/src/main/java/org/ccalm/main/AcceptEXCEL.java new file mode 100644 index 0000000..ea3c66d --- /dev/null +++ b/src/main/java/org/ccalm/main/AcceptEXCEL.java @@ -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+=""; + + //row+=""; + 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=""; + } + row+=""; + row+="\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 += "
Latitude (Широта)Longitude (Долгота)Oblast (область)District (Район)Сельский округХозяйство или местностьВид саранчиФазаЭПВЗаселено ГаДата
"+i+""+locust.lat+""+locust.lon+""+locust.region+" = "+locust.region_id+""+locust.district+" = "+locust.district_id+""+locust.terrain+""+locust.village+""; + + 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="
"+i+""+locust.lat+""+locust.lon+""+locust.region+" = "+locust.region_id+""+locust.district+" = "+locust.district_id+""+locust.terrain+""+locust.village+""+locust.locust+" = "+locust.locust_id+""+locust.phase+" = "+locust.locust_have+""+locust.evp+""+locust.size+""+locust.date+"
"; + + 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; //Дата + + } +} diff --git a/src/main/java/org/ccalm/main/AcceptJSON.java b/src/main/java/org/ccalm/main/AcceptJSON.java new file mode 100644 index 0000000..68c2032 --- /dev/null +++ b/src/main/java/org/ccalm/main/AcceptJSON.java @@ -0,0 +1,1478 @@ +//Согласно документу полученному от росийской стороны + +package org.ccalm.main; + +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.image.RenderedImage; +import java.io.*; +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 java.sql.Types; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.Year; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Base64; +import java.util.Properties; + +import javax.imageio.ImageIO; +//import javax.servlet.ServletContext; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import jakarta.servlet.ServletContext; +import org.json.JSONObject; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.ClassPathResource; +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.web.multipart.MultipartFile; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +//import com.google.common.io.CharStreams; + +//import jdk.nashorn.internal.parser.JSONParser; +//import kz.locust.CCALM.AcceptEXCEL.Locust; +//import sun.nio.cs.StandardCharsets; +//import kz.locust.CCALM.AcceptEXCEL.Locust; +//import kz.locust.CCALM.AcceptEXCEL.Locust; +import tctable.Tools; +import tools.User; + +@Controller +//@SessionAttributes( { "user" }) //Сесионный объект +public class AcceptJSON implements ServletContextAware { + + private static final Logger logger = LoggerFactory.getLogger(AcceptJSON.class); + + private ServletContext context; + private static final int BUFFER_SIZE = 4096; + + //If not created object "user", create him. + //@ModelAttribute("user") + //public User populatePerson() { + // return new User("none"); + //} + + @Override + public void setServletContext(ServletContext servletContext) { + this.context=servletContext; + } + + /** + * Скачивание анкет казахстан согласно документации из "FITO_v1.0.docx" + * Согласно документации скачивать можно раз в год и соответственно нет смысла автоматизировать, в коде ниже нужно проверять анкеты на пришедший год, и соответственно удалять + * @param user + * @param model + * @param file + * @param skip + * @return + */ + @ResponseBody + @RequestMapping(value = "/AcceptJSON_KAZ", method = { RequestMethod.GET, RequestMethod.POST }) + public String acceptJSON_KAZ(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) { + + //TODO add user verification: that he is authorized and that he is an administrator! + if(user.id==null || user.id.equals("null") || user.id.isBlank()) + return "Please log in!"; + + 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) { + ex.printStackTrace(); + } + + StringBuilder sb = new StringBuilder(); + try + { + String strURL="http://91.185.13.233:98/get_fito"; + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + hConn.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMyIsInVzZXJuYW1lIjoiQ0NBTE0iLCJyb2xlIjoidXNlciIsImlhdCI6MTcwNjc4NjQ0Nn0.bypDbAZYjbQu8hWrb6MnnAZ80AbO4ZifP3inEnpbabI"); + + hConn.connect(); + int responseCode = hConn.getResponseCode(); + if (responseCode / 100 == 2) //Code 206 is "Partial Content" + { + InputStreamReader inputStream = new InputStreamReader(hConn.getInputStream(), "UTF-8"); + int bytesRead; + char[] buffer = new char[BUFFER_SIZE]; + while ((bytesRead = inputStream.read(buffer)) != -1) { + sb.append(new String(buffer,0,bytesRead)); + } + inputStream.close(); + } + }catch (IOException e) + { + e.printStackTrace(); + } + + String content=sb.toString(); + + + int year=2024; + int cnt=0; + + if(content==null || content.equals("")) { + System.out.println("Content is null"); + }else { + System.out.println("Start"); + + String sql="delete from main.frmlocust where country_id=5 and eid=0 and extract(year from date)="+String.valueOf(year); + try{ + PreparedStatement stmt = conn.prepareStatement(sql); + int cont = stmt.executeUpdate(); + System.out.println("cnt: " + String.valueOf(cont)); + } catch (SQLException e) { + e.printStackTrace(); + } + + //System.out.println(content); + //Iterate over the elements of the array. + JSONObject jsonObject= new JSONObject(content); + JSONArray jsonArray = jsonObject.getJSONArray("data"); + for (Object o : jsonArray) { + JSONObject jsonObj = (JSONObject) o; + + //I don't miss other dates + ZonedDateTime dateTime = ZonedDateTime.parse(jsonObj.getString("examination_date"), DateTimeFormatter.ISO_ZONED_DATE_TIME); + if(dateTime.getYear()!=year) + continue; + + sql=""" + insert into main.frmlocust( + eid, --1 + lat_center, --2 + lon_center, --3 + lat1, --4 + lon1, --5 + date, --6 + village, --7 + terrain, --8 + district, --9 + country_id, --10 + region_id, --11 + locust_type_id, --12 + bio_hectare, --13 + locust_populated, --14 + description, --15 + eggs, --16 + hoppers, --17 + bands, --18 + adults, --19 + swarms --20 + )values( + ?, --1 eid + ?, --2 lat_center + ?, --3 lon_center + ?, --4 lat1 + ?, --5 lon1 + TO_TIMESTAMP(?, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), --6 date + LEFT(?, 100), --7 village + LEFT(?, 100), --8 terrain + LEFT(?, 100), --9 district + ?, --10 country_id + ?, --11 region_id + ?, --12 locust_type_id + ?, --13 bio_hectare + ?, --14 locust_populated + ?, --15 description + ?, --16 eggs CheckBox + ?, --17 hoppers CheckBox + ?, --18 bands CheckBox + ?, --19 adults CheckBox + ? --20 swarms CheckBox + )"""; + PreparedStatement stmt=null; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable","Error prepare 2"); + return "json"; + } + + String description=""; + description += "city: "+jsonObj.getString("city")+"\n"; + description += "message_type: "+jsonObj.getString("message_type")+"\n"; + if(jsonObj.has("development_stage") && !jsonObj.isNull("development_stage")) + description += "stage: "+jsonObj.getString("development_stage")+"\n"; + + try { + stmt.setLong(1, 0); + stmt.setDouble(2,jsonObj.getDouble("latitude")); + stmt.setDouble(3,jsonObj.getDouble("longitude")); + stmt.setDouble(4,jsonObj.getDouble("latitude")); + stmt.setDouble(5,jsonObj.getDouble("longitude")); + stmt.setString(6,jsonObj.getString("examination_date")); //2023-03-20T06:23:20.000Z + if(jsonObj.has("village") && !jsonObj.isNull("village")) + stmt.setString(7,jsonObj.getString("village")); + else + stmt.setNull(7, Types.VARCHAR); + if(jsonObj.has("farm") && !jsonObj.isNull("farm")) + stmt.setString(8,jsonObj.getString("farm")); + else + stmt.setNull(8, Types.VARCHAR); + if(jsonObj.has("district") && !jsonObj.isNull("district")) + stmt.setString(9,jsonObj.getString("district")); + else + stmt.setNull(9, Types.VARCHAR); + + stmt.setInt(10,5); //country_id + + + int region_id=-1; + switch (jsonObj.getString("region")) { + case "Туркестанская": //5 false -215739 1691403679 5 "Түркістан облысы (Туркестанская область)" + region_id=5; + break; + case "Жамбылская": //4 false -215722 1691403679 5 "Жамбыл облысы (Жамбылская область)" + region_id=4; + break; + case "Алматинская": //3 false -215718 1691403679 5 "Алматы облысы (Алматинская область)" + region_id=3; + break; + case "Карагандинская": //2 false -215776 1691403679 5 "Қарағанды облысы (Карагандинская область)" + region_id=2; + break; + case "Жетысу": //478 false -14312169 1691403679 5 "Жетісу облысы" + region_id=478; + break; + case "Кызылординская": //6 false -215727 1691403679 5 "Қызылорда облысы (Кызылординская область)" + region_id=6; + break; + case "Атырауская": //13 false -214834 1691403679 5 "Атырау облысы (Атырауская область)" + region_id=13; + break; + case "Западно-Казахстанская": //12 false -215441 1691403679 5 "Батыс Қазақстан облысы (Западно-Казахстанская область)" + region_id=12; + break; + case "Акмолинская": //10 false -215743 1691403679 5 "Ақмола облысы (Акмолинская область)" + region_id=10; + break; + case "Восточно-Казахстанская": //1 false -215699 1691403679 5 "Шығыс Қазақстан облысы (Восточно-Казахстанская область)" + region_id=1; + break; + case "Абай": //477 false -14243026 1691473439 5 "Абай облысы" + region_id=477; + break; + case "Костанайская": //8 false -1288730 1691403679 5 "Қостанай облысы (Костанайская область)" + region_id=8; + break; + case "Павлодарская": //11 false -215772 1691403679 5 "Павлодар облысы (Павлодарская область)" + region_id=11; + break; + case "Северо-Казахстанская": //9 false -215760 1691403679 5 "Солтүстік Қазақстан облысы (Северо-Казахстанская область)" + region_id=9; + break; + case "Актюбинская": //7 false -215683 1691403679 5 "Ақтөбе облысы (Актюбинская область)" + region_id=7; + break; + case "Мангистауская": //14 false -215686 1691403679 5 "Маңғыстау облысы (Мангистауская область)" + region_id=14; + break; + case "Улытау": //479 false -14312737 1691462768 5 "Ұлытау облысы" + region_id=14; + break; + default: + System.out.println(jsonObj.getString("region")); + } + if(region_id==-1) + stmt.setInt(11,region_id); //region_id + else + stmt.setNull(11, Types.INTEGER); + + //Вид саранчи + int locust_id=-1; + switch (jsonObj.getString("grasshopper_type")) { + case "Мароккская саранча": + locust_id=2; + break; + case "Итальянский прус": + locust_id=1; + break; + case "Азиатская саранча": + locust_id=3; + break; + default: + System.out.println(jsonObj.getString("grasshopper_type")); + } + stmt.setInt(12,locust_id); //locust_id + + //Обследованно + if(jsonObj.has("examination_area") && !jsonObj.isNull("examination_area")) + stmt.setDouble(13,Double.parseDouble(jsonObj.get("examination_area").toString())); + else + stmt.setNull(13, Types.DOUBLE); + + //Площадь заселения + if(jsonObj.has("settlement_area") && !jsonObj.isNull("settlement_area")) + stmt.setDouble(14,Double.parseDouble(jsonObj.get("settlement_area").toString())); + else + stmt.setNull(14, Types.DOUBLE); + + //Прочее описание + stmt.setString(15,description); //description + + boolean eggs=false; // Яйца + boolean hoppers=false; // Личинки + boolean bands=false; // Кулиги + boolean adults=false; // Имаго + boolean swarms=false; // Стаи + if(jsonObj.has("development_stage") && !jsonObj.isNull("development_stage")) { + if (jsonObj.getString("development_stage").equals("Яйца")) eggs = true; + if (jsonObj.getString("development_stage").equals("Личинки") || jsonObj.getString("development_stage").equals("Заселенность личинками") || jsonObj.getString("development_stage").equals("Личинка")) hoppers = true; + if (jsonObj.getString("development_stage").equals("Кулиги")) bands = true; + if (jsonObj.getString("development_stage").equals("Имаго")) adults = true; + if (jsonObj.getString("development_stage").equals("Стаи")) swarms = true; + } + if(eggs) + stmt.setBoolean(16,true); + else + stmt.setNull(16, Types.BOOLEAN); + if(hoppers) + stmt.setBoolean(17,true); + else + stmt.setNull(17, Types.BOOLEAN); + if(bands) + stmt.setBoolean(18,true); + else + stmt.setNull(18, Types.BOOLEAN); + if(adults) + stmt.setBoolean(19,true); + else + stmt.setNull(19, Types.BOOLEAN); + if(swarms) + stmt.setBoolean(20,true); + else + stmt.setNull(20, Types.BOOLEAN); + + if(region_id!=-1) { + stmt.execute(); + }else { + System.out.println("region: "+jsonObj.getString("region")); + } + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable","Error set data"); + return "json"; + } + cnt++; + } + System.out.println("Proc count = "+String.valueOf(cnt)); + } + return "Proc count = "+String.valueOf(cnt); + } + + /** + * Пример запроса: http://127.0.0.1:8081/AcceptJSON но в теле нужно поменять строку "Year y = Year.of(2024);" а также номер дня + * @param user + * @param model + * @param file + * @param skip + * @return + */ + @RequestMapping(value = "/AcceptJSON_RUS", 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) { + ex.printStackTrace(); + } + + //Set UTC time + Statement stm=null; + try { + stm = conn.createStatement(); + try { + stm.execute("SET timezone TO 'UTC';"); + } catch( SQLException ex ) { + ex.printStackTrace(); + } + stm.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + + String sqlData=""; + String table=""; + table+=""; + + //Выбираю максимальную дату проверяю что она меньше текущей минус 2 дня и пытаюсь загрузить её + LocalDate lastDate = null;// = LocalDate.parse("2018-05-05"); + Statement stt = null; + ResultSet rs = null; + try { + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = stt.executeQuery("select to_char(max(date), 'YYYY-MM-DD') as date from integration.days_ru"); + if (rs != null) { + try { + if (rs.next()) { + String value = rs.getString(1); + if(value!=null) + lastDate = LocalDate.parse(value); + } + rs.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + } catch (SQLException ex) { + ex.printStackTrace(); + }finally { + if(rs!=null) try{rs.close();}catch(SQLException ex){ ex.printStackTrace(); } + if(stt!=null) try{stt.close();}catch(SQLException ex){ ex.printStackTrace(); } + } + if(lastDate==null) lastDate = LocalDate.parse("2024-01-10"); + + + //By number of day downloading data and write result of downloading to database, try or false, after repair need repeat download + while(lastDate.isBefore(LocalDate.now().minusDays(3))){ + lastDate=lastDate.plusDays(1); + + String dateBegin=lastDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")); + String dateEnd=dateBegin; + + System.out.println( "date = " + dateEnd ); + + //Download JSON data from server + StringBuilder sb = new StringBuilder(); + try + { + String strURL="https://rscagex.ru/pmon/rest/getPhytomons?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&dateBegin="+dateBegin+"&dateEnd="+dateEnd; + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + hConn.connect(); + int responseCode = hConn.getResponseCode(); + if (responseCode / 100 == 2) //Code 206 is "Partial Content" + { + //InputStream inputStream = hConn.getInputStream(); + InputStreamReader inputStream = new InputStreamReader(hConn.getInputStream(), "UTF-8"); + int bytesRead; + char[] buffer = new char[BUFFER_SIZE]; + while ((bytesRead = inputStream.read(buffer)) != -1) { + sb.append(new String(buffer,0,bytesRead)); + } + inputStream.close(); + } + hConn.disconnect(); + } + catch (IOException e) + { + e.printStackTrace(); + } + String content=sb.toString(); + if(content!=null && !content.equals("")) { + + //byte[] data = sb.toByteArray(in); + //String content=new String(data, Charsets.UTF_8); + + //Iterate over the elements of the array. + int cntO = 1; + int cntV = 1; + JSONArray jsonArray = new JSONArray(content); + for (Object o : jsonArray) { + JSONObject jsonObj = (JSONObject) o; + Locust locust = new Locust(); + + locust.date = jsonObj.getString("date"); + + if (!jsonObj.isNull("regionName")) + locust.region = jsonObj.getString("regionName"); + else + locust.region = ""; + + if (!jsonObj.isNull("townName")) + locust.district = jsonObj.getString("townName"); + + if (!jsonObj.isNull("point")) { + locust.lon = jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(0); + locust.lat = jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(1); + } + + //Контур зоны распространения ВО Polygon (geoJSON) + locust.drawPolygon = null; + if (!jsonObj.isNull("drawPolygon")) { + locust.drawPolygon = jsonObj.getJSONObject("drawPolygon").toString(); + } + + //Площадь контура зоны распространения, в случае если специалист указал его + locust.size = "null"; + if (!jsonObj.isNull("polygonArea")) + locust.size = String.valueOf(jsonObj.getDouble("polygonArea")); + + //jsonObj.drawPolygon Краснодар + + if (locust.region.length() > 0) { + //Выбираю ID области + locust.region_id = ""; + //Statement stt = null; + //ResultSet rs = null; + try { + + 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) { + ex.printStackTrace(); + } + } + } catch (SQLException ex) { + ex.printStackTrace(); + } finally { + if (rs != null) try { + rs.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + if (stt != null) try { + stt.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + + /*if(locust.region_id.equals("")){ + if(locust.region.indexOf("Воронежс��ая область")>=0) locust.region_id="110"; + if(locust.region.indexOf("Кра��нодарский край")>=0) locust.region_id="164"; + if(locust.region.indexOf("Астраха��ская область")>=0) locust.region_id="68"; //dayOfYear: 97 at year: 2022 = 07.04.2022 + if(locust.region.indexOf("Астраханская област��")>=0) locust.region_id="68"; // dayOfYear: 101 at year: 2022 = 11.04.2022 + }*/ + + if (locust.region_id.length() > 0) { + //Выбираю id региона (main.countriesdistricts) + locust.district_id = ""; + 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.region_id = "210"; + 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 = "Сунженский район"; + if (locust.district.equals("Буденновский район")) + locust.district = "Будённовский район"; + if (locust.district.equals("Новоселовский район")) { + locust.district = "Новоселицкий район"; + locust.region_id = "168"; + } + 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 = "Новохопёрский район"; + 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) { + ex.printStackTrace(); + } + } + } catch (SQLException ex) { + ex.printStackTrace(); + } finally { + if (rs != null) try { + rs.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + if (stt != null) try { + stt.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + } + } + + String row = ""; + + if (!jsonObj.isNull("subjectList")) { + JSONArray jsonArraySub = jsonObj.getJSONArray("subjectList"); + + for (Object o2 : jsonArraySub) { + JSONObject jsonObjSub = (JSONObject) o2; + + locust.eid = jsonObjSub.getInt("id"); + locust.phytoType = jsonObjSub.getString("phytoType"); //"Вредители" или "Обработка" + if (locust.phytoType.equals("Обработка")) { + locust.insecticide_name = jsonObjSub.getString("nameSubject"); //Наименование действующего вещества + if (!jsonObjSub.isNull("nameLatSubject")) + locust.insecticide_active_substance = jsonObjSub.getString("nameLatSubject"); //Латинское наименование действующего вещества + if (!jsonObjSub.isNull("protectionDoze")) + locust.insecticide_dose = String.valueOf(jsonObjSub.getFloat("protectionDoze")); //Доза внесения препарата (л/га) + + if (!jsonObjSub.isNull("agroTreatmentType")) { + String agroTreatmentType = jsonObjSub.getString("agroTreatmentType"); //Тип обработки (Агротехнический, Авиационный, Наземный) + if (agroTreatmentType != null && !agroTreatmentType.equals("")) { + if (agroTreatmentType.equals("GROUND")) { + locust.spray_platform = "3"; + } else if (agroTreatmentType.equals("AGROTECHNICAL")) { + locust.spray_platform = "5"; + } else if (agroTreatmentType.equals("AVIATION")) { + locust.spray_platform = "1"; + } + } + if (locust.spray_platform == null || locust.spray_platform.equals("")) { + model.addAttribute("PreviewTable", "Error spray_platform"); + return "json"; + } + } + + //То что не знаю куда записывать записываю в description + locust.description = ""; + if (!jsonObjSub.isNull("agroTreatmentPercentage")) + locust.description += "Процент обработанной площади: " + String.valueOf(jsonObjSub.getFloat("agroTreatmentPercentage")) + "\n"; + if (!jsonObjSub.isNull("agroTreatmentPow")) + locust.description += "Степень обработки: " + jsonObjSub.getString("agroTreatmentPow") + "\n"; + + //Если записи не существует то вставляем если существует то обновляем + boolean exists = false; //Is there a record. + Statement st; + try { + st = conn.createStatement(); + //ResultSet rs=null; + try { + String sql = "select 1 from main.frmlocustdel where eid=" + String.valueOf(locust.eid); + rs = st.executeQuery(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error select"); + return "json"; + } + if (rs != null) { + if (rs.next()) + exists = true; + } + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error select 2"); + return "json"; + } + + PreparedStatement stmt = null; + String sql = ""; + if (exists) { + System.out.println(String.valueOf(cntV)+") update main.frmlocustdel"); + sql = "update main.frmlocustdel set\n" + + " eid=?,\n" + + " lat_center=?,\n" + + " lon_center=?,\n" + + " country_id=?,\n" + + " region_id=?,\n" + + " area=?,\n" + + " district=?,\n" + + " date=TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" + + " description=?,\n" + + " geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" + + + " insecticide_name=?,\n" + + " insecticide_active_substance=?,\n" + + " insecticide_dose=?,\n" + + " spray_platform=?\n" + + " where eid='" + locust.eid + "'"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error prepare 1"); + return "json"; + } + } else { + System.out.println(String.valueOf(cntV)+") insert into main.frmlocustdel"); + sql = "insert into main.frmlocustdel(\n" + + " eid,\n" //1 + + " lat_center,\n" //2 + + " lon_center,\n" //3 + + " country_id,\n" //4 + + " region_id,\n" //5 + + " area,\n" //6 + + " district,\n" //7 + + " date,\n" //8 + + " description,\n" //9 + + " geom,\n" //10 + + + " insecticide_name,\n" //11 + + " insecticide_active_substance,\n" //12 + + " insecticide_dose,\n" //13 + + " spray_platform\n" //14 + + + ")values(\n" + + " ?,\n" //1 eid + + " ?,\n" //2 lat1 + + " ?,\n" //3 lon1 + + " ?,\n" //4 country_id + + " ?,\n" //5 region_id + + " ?,\n" //6 district (area) + + " ?,\n" //7 district (area) + + " TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" //8 date + + " ?,\n" //9 description + + " ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //10 geom + + + " ?,\n" //11 insecticide_name + + " ?,\n" //12 insecticide_active_substance + + " ?,\n" //13 insecticide_dose + + " ?\n" //14 spray_platform + + ")"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error prepare 2"); + return "json"; + } + } + + try { + stmt.setInt(1, locust.eid); + stmt.setDouble(2, locust.lat); + stmt.setDouble(3, locust.lon); + stmt.setInt(4, 7); //country_id + stmt.setInt(5, Integer.parseInt(locust.region_id)); //region_id + stmt.setString(6, locust.district); //Пишу в поле "area" + stmt.setString(7, null); + stmt.setString(8, locust.date); //27.04.2020 09:17 + stmt.setString(9, locust.description); + stmt.setString(10, locust.drawPolygon); + + stmt.setString(11, locust.insecticide_name); + stmt.setString(12, locust.insecticide_active_substance); + if (locust.insecticide_dose == null || locust.insecticide_dose.equals("")) + stmt.setNull(13, Types.DOUBLE); + else + stmt.setDouble(13, Double.parseDouble(locust.insecticide_dose)); + + if (locust.spray_platform == null || locust.spray_platform.equals("")) + stmt.setNull(14, Types.INTEGER); + else + stmt.setInt(14, Integer.parseInt(locust.spray_platform)); + + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error set data"); + return "json"; + } + + //Выпоняю запрос на свтавку либо обновление + try { + stmt.execute(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error execute frmlocustdel"); + return "json"; + } + cntO++; + + } else if (locust.phytoType.equals("Вредители")) { + if (!jsonObjSub.isNull("nameSubject")) + locust.locust = jsonObjSub.getString("nameSubject"); + + //Вид саранчи + locust.locust_id = ""; + 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 = "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 = "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 = "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 = "3"; + if (locust.locust.equals("Итальянский прус")) locust.locust_id = "1"; + if (locust.locust.equals("Мароккская саранча, мароккская кобылка, марокканка")) + locust.locust_id = "2"; + + //фаза саранчи + if (!jsonObjSub.isNull("phaseEvolutionName")) + locust.phase = jsonObjSub.getString("phaseEvolutionName"); + + locust.locust_have = "3"; + if (locust.phase != null) { + if (locust.phase.equals("Кубышка")) locust.locust_have = "2"; //Кубышка = Яйца + if (locust.phase.equals("Гусеница")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 2-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 3-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 4-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 5-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Имаго")) locust.locust_have = "5"; + } + //Если эта анкета "Имаго" то записываем плотность имаго на m2 + if (locust.locust_have.equals("5")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.imago_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + //Если эта анкета "Кубышка"="Яйца" то записываем плотность кулиг на m2 + if (locust.locust_have.equals("2")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.eggs_capsules_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + //Если эта анкета "Кулиги" то записываем плотность кулиг на m2 + if (locust.locust_have.equals("4")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.kuliguli_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + //Если эта анкета "Личинок" то записываем плотность личинок на m2 + if (locust.locust_have.equals("3")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.larva_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + + //Биотоп + switch (jsonObjSub.getString("faoBiotopeName")) { + case "CIT степь": + locust.bio_biotope_id = "1"; + break; + case "CIT залежь": + locust.bio_biotope_id = "2"; + break; + case "CIT посевы": + locust.bio_biotope_id = "3"; + break; + case "CIT пастбища": + locust.bio_biotope_id = "11"; + break; + case "CIT холмы, горы": + locust.bio_biotope_id = "19"; + break; + case "DMA равнины": + locust.bio_biotope_id = "4"; + break; + case "DMA посевы": + locust.bio_biotope_id = "6"; + break; + case "DMA пастбища": + locust.bio_biotope_id = "13"; + break; + case "DMA холмы, горы": + locust.bio_biotope_id = "14"; + break; + case "LMI низкие сухие тростники": + locust.bio_biotope_id = "7"; + break; + case "LMI высокие влажные тростники": + locust.bio_biotope_id = "8"; + break; + case "LMI другое": + locust.bio_biotope_id = "10"; + break; + case "Другие саранчовые на посевах": + locust.bio_biotope_id = "15"; + break; + case "Другие саранчовые на равнине": + locust.bio_biotope_id = "16"; + break; + case "Другие саранчовые на холмах": + locust.bio_biotope_id = "17"; + break; + case "Другое": + locust.bio_biotope_id = "18"; + break; + default: + locust.bio_biotope_id = null; + break; + } + + //Если те виды что нам нужны + if (locust.region == null || locust.region.equals("") || locust.lat == 0 || locust.lon == 0 || locust.locust.equals("Совка ипсилон") || locust.locust.equals("Восточный майский хрущ") || locust.locust.equals("Кукурузный стеблевой мотылек") || locust.locust.equals("Картофельная, или болотная совка, лиловатая яровая совка") || locust.locust.equals("Луговой мотылёк") || locust.locust.equals("Хлопковая совка") || locust.locust.equals("Стеблевой кукурузный мотылек") || locust.locust.equals("Восточная луговая совка") || locust.locust.equals("Коричневая щитовка") || locust.locust.equals("Продолговатая (чайная) подушечница") || locust.locust.equals("Яблоневая запятовидная щитовка") || locust.locust.equals("Виноградная филлоксера") || locust.locust.equals("Бахчевая коровка")) { + + } else { + + if (locust.locust_id.equals("")) { + System.out.println("locust.locust = "+locust.locust); + model.addAttribute("PreviewTable", "locust.locust_id == 0 locust name = " + locust.locust); + logger.error("Error, not find locust.locust = "+locust.locust); + return "json"; + } + if (locust.region_id.equals("")) { + System.out.println("locust.region = "+locust.region); + model.addAttribute("PreviewTable", "locust.region_id == 0 region name = " + locust.region); + logger.error("Error, not find locust.region = "+locust.region); + return "json"; + } + + //Тех полей что нет в анкете вствляю в комментарии + try { + locust.description = ""; + + if (jsonObjSub.getBoolean("notFound")) + locust.description += "Вредитель не обнаружен: " + jsonObjSub.getString("nameSubject") + "\n"; + else + locust.description += "Вредитель обнаружен: " + jsonObjSub.getString("nameSubject") + "\n"; + + if (!jsonObjSub.isNull("phaseEvolutionName")) + locust.description += "Фаза: " + jsonObjSub.getString("phaseEvolutionName") + "\n"; //Так как фаза у росиян более подробная + if (!jsonObjSub.isNull("subPestCount")) { + locust.description += "Вредителей: " + jsonObjSub.getFloat("subPestCount"); + if (!jsonObjSub.isNull("unitName")) + locust.description += " " + jsonObjSub.getString("unitName"); + locust.description += "\n"; + } + + if (!jsonObj.isNull("cropCurrentType")) + locust.description += "Тип сева: " + jsonObj.getString("cropCurrentType") + "\n"; + if (!jsonObj.isNull("cropCurrentCulture")) + locust.description += "Наименование культуры: " + jsonObj.getString("cropCurrentCulture") + "\n"; + if (!jsonObj.isNull("cropCurrentCultureSort")) + locust.description += "Наименование сорта культуры: " + jsonObj.getString("cropCurrentCultureSort") + "\n"; + if (!jsonObj.isNull("cropCurrentGrowthPhase")) + locust.description += "Фаза роста культуры: " + jsonObj.getString("cropCurrentGrowthPhase") + "\n"; + if (!jsonObj.isNull("cropFieldArea")) { + locust.description += "Площадь поля: " + jsonObj.getFloat("cropFieldArea") + "\n"; + locust.bio_hectare = String.valueOf(jsonObj.getFloat("cropFieldArea")); + } + + + } catch (Exception ex) { + ex.printStackTrace(); + } + + locust.terrain = "null"; //У росиян нет сельского округа + + row = ""; + if (locust.region_id == null || locust.region_id.equals("") || locust.district_id == null || locust.district_id.equals("") || locust.locust_id == null || locust.locust_id.equals("")) { + row = ""; + } + row += ""; + row += "\n"; + + //Если записи не существует то вставляем если существует то обновляем + boolean exists = false; //Is there a record. + Statement st; + try { + st = conn.createStatement(); + //ResultSet rs=null; + try { + String sql = "select 1 from main.frmlocust where eid=" + String.valueOf(locust.eid); + rs = st.executeQuery(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error select"); + return "json"; + } + if (rs != null) { + if (rs.next()) + exists = true; + } + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error select 2"); + return "json"; + } + + PreparedStatement stmt = null; + String sql = ""; + if (exists) { + System.out.println(String.valueOf(cntV)+") update main.frmlocust"); + sql = "update main.frmlocust set\n" + + " eid=?,\n" + + " lat_center=?,\n" + + " lon_center=?,\n" + + " country_id=?,\n" + + " region_id=?,\n" + + " area=?,\n" + + " district=?,\n" + + " date=TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" + + " description=?,\n" + + " geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" + + " locust_type_id=?,\n" + + " imago_density=?,\n" + + " kuliguli_density=?,\n" + + " larva_density=?,\n" + + " bio_hectare=?\n," + + " eggs_capsules_density=?,\n" + + " bio_biotope_id=?\n" + + " where eid='" + locust.eid + "'"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error prepare 1"); + return "json"; + } + } else { + System.out.println(String.valueOf(cntV)+") insert into main.frmlocust"); + sql = "insert into main.frmlocust(\n" + + " eid,\n" //1 + + " lat_center,\n" //2 + + " lon_center,\n" //3 + + " country_id,\n" //4 + + " region_id,\n" //5 + + " area,\n" //6 + + " district,\n" //7 + + " date,\n" //8 + + " description,\n" //9 + + " geom,\n" //10 + + " locust_type_id,\n" //11 + + " imago_density,\n" //12 + + " kuliguli_density,\n" //13 + + " larva_density,\n" //14 + + " bio_hectare,\n" //15 + + " eggs_capsules_density,\n" //16 + + " bio_biotope_id\n" //17 + + ")values(\n" + + " ?,\n" //1 eid + + " ?,\n" //2 lat1 + + " ?,\n" //3 lon1 + + " ?,\n" //4 country_id + + " ?,\n" //5 region_id + + " ?,\n" //6 district (area) + + " ?,\n" //7 district (area) + + " TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" //8 date + + " ?,\n" //9 description + + " ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //10 geom + + " ?,\n" //11 locust_type_id + + " ?,\n" //12 imago_density + + " ?,\n" //13 kuliguli_density + + " ?,\n" //14 larva_density + + " ?,\n" //15 + + " ?,\n" //16 + + " ?\n" //17 + + ")"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error prepare 2"); + return "json"; + } + } + + try { + stmt.setInt(1, locust.eid); + stmt.setDouble(2, locust.lat); + stmt.setDouble(3, locust.lon); + stmt.setInt(4, 7); + stmt.setInt(5, Integer.parseInt(locust.region_id)); + stmt.setString(6, locust.district); //Пишу в поле "area" + stmt.setString(7, null); + stmt.setString(8, locust.date); //27.04.2020 09:17 + stmt.setString(9, locust.description); + stmt.setString(10, locust.drawPolygon); + stmt.setInt(11, Integer.parseInt(locust.locust_id)); + if (locust.imago_density != null) + stmt.setFloat(12, Float.parseFloat(locust.imago_density)); + else + stmt.setNull(12, Types.FLOAT); + if (locust.kuliguli_density != null) + stmt.setFloat(13, Float.parseFloat(locust.kuliguli_density)); + else + stmt.setNull(13, Types.FLOAT); + if (locust.larva_density != null) + stmt.setFloat(14, Float.parseFloat(locust.larva_density)); + else + stmt.setNull(14, Types.FLOAT); + if (locust.bio_hectare != null) + stmt.setFloat(15, Float.parseFloat(locust.bio_hectare)); + else + stmt.setNull(15, Types.FLOAT); + if (locust.eggs_capsules_density != null) + stmt.setFloat(16, Float.parseFloat(locust.eggs_capsules_density)); + else + stmt.setNull(16, Types.FLOAT); + if (locust.bio_biotope_id != null) + stmt.setFloat(17, Float.parseFloat(locust.bio_biotope_id)); + else + stmt.setNull(17, Types.INTEGER); + + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error set data"); + return "json"; + } + //Выпоняю запрос на свтавку либо обновление + try { + stmt.execute(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error execute 0"); + return "json"; + } + cntV++; + + //Скачиваю фотографию для анкеты + sb = new StringBuilder(); + try { + String strURL = "https://rscagex.ru/pmon/rest/getPhotosByParentId?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&parentId=" + locust.eid; + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + //hConn.setRequestProperty("Range","bytes=" + posStart + "-" + posEnd); + hConn.connect(); + int responseCode = hConn.getResponseCode(); + if (responseCode / 100 == 2) //Code 206 is "Partial Content" + { + InputStream inputStream = hConn.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); + sb.append(new String(buffer, 0, bytesRead)); + } + //outputStream.close(); + inputStream.close(); + } + hConn.disconnect(); + } catch (IOException e) { + e.printStackTrace(); + } + + String base64 = sb.toString(); + if (base64.length() > 10) { + //Так как мне присылаю неправильный jSOM то пытаюсь его поправить,. + base64 = base64.replace("[", "[\""); + base64 = base64.replace("]", "\"]"); + base64 = base64.replace(", ", "\",\""); + + String strFile = "O:\\temp\\CCALM\\ru_" + locust.eid; + int pos = 0; + + JSONArray jsonArrayIMGS = new JSONArray(base64); + for (Object oStr : jsonArrayIMGS) { + String jsonObjIMG = (String) oStr; + pos++; + if (pos > 3) break; + + //try { + // BufferedWriter writer = new BufferedWriter(new FileWriter(strFile)); + // writer.write(jsonObjIMG); + // writer.close(); + //} catch (IOException e1) { + // e1.printStackTrace(); + //} + + byte[] decodedString = null; + try { + decodedString = Base64.getDecoder().decode(jsonObjIMG); + } catch (Exception e) { + e.printStackTrace(); + model.addAttribute("PreviewTable", "Error decode"); + return "json"; + } + + if (decodedString != null) { + try { + FileUtils.writeByteArrayToFile(new File(strFile + "_" + pos + ".jpg"), decodedString); + } catch (IOException e) { + e.printStackTrace(); + } + } + decodedString = null; + + BufferedImage imageOnDisk = null; + try { + imageOnDisk = ImageIO.read(new File(strFile + "_" + pos + ".jpg")); + } catch (IOException e) { + e.printStackTrace(); + } + if (imageOnDisk != null) { + Image img; + BufferedImage buffered; + if (imageOnDisk.getWidth() > imageOnDisk.getHeight()) { + img = imageOnDisk.getScaledInstance(1024, 768, Image.SCALE_DEFAULT); + buffered = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB); + buffered.getGraphics().drawImage(img, 0, 0, null); + } else { + img = imageOnDisk.getScaledInstance(768, 1024, Image.SCALE_DEFAULT); + buffered = new BufferedImage(768, 1024, BufferedImage.TYPE_INT_RGB); + buffered.getGraphics().drawImage(img, 0, 0, null); + } + try { + //BufferedImage bIMG = toBufferedImage(img); + ImageIO.write(buffered, "jpg", new File(strFile + "_" + pos + ".jpg")); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + + if (pos > 3) { + break; + } else { + sql = ""; + if (pos == 1) { + sql = "update main.frmlocust set image_name1='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; + } + if (pos == 2) { + sql = "update main.frmlocust set image_name2='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; + } + if (pos == 3) { + sql = "update main.frmlocust set image_name3='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; + } + if (sql.length() > 0) { + try { + st = conn.createStatement(); + st.execute(sql); + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error update img"); + return "json"; + } + } + } + } + } + } + + } //equals("Вредители") + + } + + } + + table += row; + } + System.out.println("Обработка = "+String.valueOf(cntO)); + System.out.println("Вредители = "+String.valueOf(cntV)); + + + table += "
Ext idLatitude (Широта)Longitude (Долгота)Oblast (область)District (Район)Сельский округХозяйство или местностьВид саранчиФазаЭПВЗаселено ГаДата
" + String.valueOf(cntO+cntV) + "" + locust.eid + "" + locust.lat + "" + locust.lon + "" + locust.region + " = " + locust.region_id + "" + locust.district + " = " + locust.district_id + "" + locust.terrain + "" + locust.village + "" + locust.locust + " = " + locust.locust_id + "" + locust.phase + " = " + locust.locust_have + "" + locust.evp + "" + locust.size + " = " + locust.drawPolygon + "" + locust.date + "
"; + + //json=json.substring(0,json.length()-1); //Удаляю последнюю запятую + //json+="\n]}"; + + //Сохраняю lastDate в базу данных + try { + Statement st = conn.createStatement(); + st.execute("insert into integration.days_ru(date,count)values('" + lastDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "'," + String.valueOf(cntV+cntO) + ");"); + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error update img"); + return "json"; + } + } + } + model.addAttribute("PreviewTable",table); + //model.addAttribute("PreviewGEOJSON",json); + model.addAttribute("PreviewSQL",sqlData); + + return "json"; + } + //--------------------------------------------------------------------------- + public static BufferedImage toBufferedImage(Image img) + { + if (img instanceof BufferedImage) + { + return (BufferedImage) img; + } + + // Create a buffered image with transparency + BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); + + // Draw the image on to the buffered image + Graphics2D bGr = bimage.createGraphics(); + bGr.drawImage(img, 0, 0, null); + bGr.dispose(); + + // Return the buffered image + return bimage; + } + //--------------------------------------------------------------------------- + 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{ + int eid; //Внешний идентификатор + String phytoType; //Вредители либо обработка + + 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=null; //Фаза саранчи + String locust_have; //id Фазы саранчи + String evp; //ЭФП + String drawPolygon="null"; //Область обследования GeoGSON + String size; //Заселённая площадь (polygonArea Площадь контура зоны распространения, в случае если специалист указал его) + String date; //Дата + + String description=""; + + + String eggs_capsules_density=null; //Плотность яиц + String kuliguli_density=null; //Плотность кулиг на м² + String imago_density=null; //Плотность имаго (/м²)* + String larva_density=null; //Плотность личинок + + String bio_hectare=null; //Обследованная площадь + String bio_biotope_id=null; //Тип тиотопа + + //Ниже то что относиться только к обработке + String insecticide_name=null; + String insecticide_active_substance=null; + String insecticide_dose=null; + String spray_platform=null; + + } + +} diff --git a/src/main/java/org/ccalm/main/DataJSON.java b/src/main/java/org/ccalm/main/DataJSON.java new file mode 100644 index 0000000..1861f80 --- /dev/null +++ b/src/main/java/org/ccalm/main/DataJSON.java @@ -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; + } + +} \ No newline at end of file diff --git a/src/main/java/org/ccalm/main/DownloadNDVI.java b/src/main/java/org/ccalm/main/DownloadNDVI.java new file mode 100644 index 0000000..7e2fc88 --- /dev/null +++ b/src/main/java/org/ccalm/main/DownloadNDVI.java @@ -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!
"; + + + //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!
"; + }else + { + logger.info("
Connect is ERROR
"); + result+="Connect is ERROR!
"; + } + }catch(Exception e) + { + logger.info("
Connect Exception:"+e.getMessage()+"
"); + result+="Connect Exception:"+e.getMessage()+"
"; + } + + //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"+"
"; + + 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()+"
"; + } + 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"+"
"; + } + + 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 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 dims = gid.getDimensions(); + logger.info("dims.size() = " + dims.size()); + + Iterator 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()+"
"; + + int pos=0; + for(int nLat=0;nLat180) 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!
"; +*/ + 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; + } + +} diff --git a/src/main/java/org/ccalm/main/DownloadWeather.java b/src/main/java/org/ccalm/main/DownloadWeather.java new file mode 100644 index 0000000..fda8619 --- /dev/null +++ b/src/main/java/org/ccalm/main/DownloadWeather.java @@ -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!
"; + + 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!
"; + }else + { + logger.info("
Connect is ERROR
"); + result+="Connect is ERROR!
"; + } + }catch(Exception e) + { + logger.info("
Connect Exception:"+e.getMessage()+"
"); + result+="Connect Exception:"+e.getMessage()+"
"; + } + + //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"+"
"; + + 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()+"
"; + } + 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"+"
"; + } + + 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 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 dims = gid.getDimensions(); + logger.info("dims.size() = " + dims.size()); + + Iterator 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()+"
"; + + int pos=0; + for(int nLat=0;nLat180) 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!
"; + 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="
SQLException: "+ex.getMessage()+"
"; + } + + 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="
SQLException:"+ex.getMessage()+"
"; + } + } + return result; + } + //--------------------------------------------------------------------------- + +} diff --git a/src/main/java/org/ccalm/main/GeoGSON.java b/src/main/java/org/ccalm/main/GeoGSON.java new file mode 100644 index 0000000..d95d8a5 --- /dev/null +++ b/src/main/java/org/ccalm/main/GeoGSON.java @@ -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="
SQLException: "+ex.getMessage()+"
"; + } + + 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=""; + } + if(geom==null) geom=""; + result=geom; + } + } + st.close(); + conn.close(); + } catch (SQLException ex) { + result="
SQLException:"+ex.getMessage()+"
"; + } + } + + 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
"; + + 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+="
SQLException: "+ex.getMessage()+"
"; + } + + 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+="
SQLException:"+ex.getMessage()+"
"; + } + } + } + rsC.close(); + stC.close(); + conn.close(); + + } catch (SQLException ex) { + // TODO Auto-generated catch block + result+="
SQLException:"+ex.getMessage()+"
"; + } + + + + } + + return result; + } + +} diff --git a/src/main/java/org/ccalm/main/Integration.java b/src/main/java/org/ccalm/main/Integration.java new file mode 100644 index 0000000..88b50d5 --- /dev/null +++ b/src/main/java/org/ccalm/main/Integration.java @@ -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; + } + +} diff --git a/src/main/java/org/ccalm/main/MainApplication.java b/src/main/java/org/ccalm/main/MainApplication.java new file mode 100644 index 0000000..1cb170c --- /dev/null +++ b/src/main/java/org/ccalm/main/MainApplication.java @@ -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); + } + +} diff --git a/src/main/java/org/ccalm/main/MainController.java b/src/main/java/org/ccalm/main/MainController.java new file mode 100644 index 0000000..e57e971 --- /dev/null +++ b/src/main/java/org/ccalm/main/MainController.java @@ -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("\n" + + "\n" + + " \n" + + " https://ccalm.org\n" + + " \n" + + "\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("
Connect is ERROR
"); + } + }catch(Exception e) + { + System.out.println("
Connect Exception:"+e.getMessage()+"
"); + } + + 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("
SQLException:"+ex.getMessage()+"
"); + } + } + + //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("
SQLException:"+ex.getMessage()+"
"); + } + + 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("
SQLException:"+ex.getMessage()+"
"); + } + + //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 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("
Connect is ERROR
"); + } + }catch(Exception e) + { + System.out.println("
Connect Exception:"+e.getMessage()+"
"); + } + + 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(); + } + + +} diff --git a/src/main/java/org/ccalm/main/Products.java b/src/main/java/org/ccalm/main/Products.java new file mode 100644 index 0000000..bf04765 --- /dev/null +++ b/src/main/java/org/ccalm/main/Products.java @@ -0,0 +1,1059 @@ +package org.ccalm.main; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +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 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.ModelAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.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 org.json.JSONObject; +import org.json.JSONArray; +import org.json.JSONException; + +import tools.PreparedStatementNamed; +import tools.User; + +@Controller +//@SessionAttributes( { "user" }) //Сесионный объект +public class Products implements ServletContextAware { + + private static final Logger logger = LoggerFactory.getLogger(Products.class); + private ServletContext context; + + //If not created object "user", create him. + //@ModelAttribute("user") + //public User populatePerson() { + // return new User("none"); + //} + + @RequestMapping(value = "/get_survey",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public String getLocustSurvey(@ModelAttribute User user,@RequestBody(required=false) byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { + + int errorCode=0; + String errorMessage=""; + + //Load configuration from "config.xml" + 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); + } + + 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); + //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? + stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем раскоментил? может в начале поставить ещё TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ? + stt0.close(); + } catch (SQLException ex) { + logger.info(ex.getMessage()); + errorCode=1; + errorMessage+="Failed to execute SQL query!"; + } + + JSONObject doc=null; + InputStream body; + if(reqData!=null) { + + + body = new ByteArrayInputStream(reqData); + + String text=""; + try { + text = new String(body.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + logger.info(text); + + //JSONParser jsonParser = new JSONParser(); + //doc = (JSONObject)jsonParser.parse(text); + //doc = new JSONObject(body); + doc = new JSONObject(text); + } + + 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," + + " lat_center," + + " lon_center," + + " lat1," + + " lon1," + + " lat2," + + " lon2," + + " lat3," + + " lon3," + + " lat4," + + " lon4," + + " lat5," + + " lon5," + + " lat6," + + " lon6," + + " terrain," + + " locust_populated," + + " eggs_capsules_density," + + " eggs_capsules_density_to," + + " imago_density," + + " larva_density," + + " larva_density_to," + + " kuliguli_size," + + " CASE swarm_maturity WHEN true THEN 1 WHEN false THEN 0 ELSE null END as swarm_maturity," + + " swarm_density_id," + + " ST_AsGeoJSON(geom) as geom" + + " from main.frmlocust fl where" + + " fl.del=false" + + " and (${country_id} is null or (${country_id}=-1 and fl.country_id in (7,3,4,2)) or (${country_id}=-2 and fl.country_id in (7,1,5,6,8,9,10)) or ${country_id}=fl.country_id)" + + " and (${region_id} is null or ${region_id}=fl.region_id)" + + " and (${locust_type_id} is null or ${locust_type_id}=fl.locust_type_id)" + + " and (${date_start} is null or to_timestamp(${date_start})<=fl.date)" + + " and (${date_end} is null or to_timestamp(${date_end})>=fl.date)" + + " and (${device_id} is null or (${device_id} and fl.device_id is not null) or (not ${device_id} and fl.device_id is null))" + + " and (${registered} is null or (${registered} and (fl.device_id is null or fl.device_id in (select serial from main.terminals where del=false))) or (not ${registered} and (fl.device_id not in (select serial from main.terminals where del=false))))" + + " and ((${test} is null and (test!=true or test is null)) or ${test}=fl.test)" + + " order by fl.id desc;"; + + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + if(doc!=null) { + stmtn.setInt("_user_id", Integer.parseInt(user.id)); + + if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); + else stmtn.setInt("country_id",doc.getInt("country_id")); + + if(doc.isNull("region_id")) stmtn.setNULLInt("region_id"); + else stmtn.setInt("region_id",doc.getInt("region_id")); + + if(doc.isNull("locust_type_id")) stmtn.setNULLInt("locust_type_id"); + else stmtn.setInt("locust_type_id",doc.getInt("locust_type_id")); + + if(doc.isNull("date_start")) stmtn.setNULLInt("date_start"); + else stmtn.setInt("date_start",doc.getInt("date_start")); + + if(doc.isNull("date_end")) stmtn.setNULLInt("date_end"); + else stmtn.setInt("date_end",doc.getInt("date_end")); + + if(doc.isNull("device_id")) stmtn.setNULLBoolean("device_id"); + else stmtn.setBoolean("device_id",doc.getInt("device_id")); + + if(doc.isNull("registered")) stmtn.setNULLBoolean("registered"); + else stmtn.setBoolean("registered",doc.getInt("registered")); + + if(doc.isNull("test")) stmtn.setNULLBoolean("test"); + else stmtn.setBoolean("test",doc.getInt("test")); + } + 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("terrain")!=null) + obj.put("terrain", rs.getString("terrain")); + if(rs.getObject("locust_populated")!=null) + obj.put("locust_populated", rs.getFloat("locust_populated")); + if(rs.getObject("eggs_capsules_density")!=null) + obj.put("eggs_capsules_density", rs.getFloat("eggs_capsules_density")); + if(rs.getObject("eggs_capsules_density_to")!=null) + obj.put("eggs_capsules_density_to", rs.getFloat("eggs_capsules_density_to")); + if(rs.getObject("imago_density")!=null) + obj.put("imago_density", rs.getFloat("imago_density")); + if(rs.getObject("larva_density")!=null) + obj.put("larva_density", rs.getFloat("larva_density")); + if(rs.getObject("larva_density_to")!=null) + obj.put("larva_density_to", rs.getFloat("larva_density_to")); + if(rs.getObject("kuliguli_size")!=null) + obj.put("kuliguli_size", rs.getFloat("kuliguli_size")); + if(rs.getObject("swarm_maturity")!=null) + obj.put("swarm_maturity", rs.getString("swarm_maturity")); + if(rs.getObject("swarm_density_id")!=null) + obj.put("swarm_density_id", rs.getInt("swarm_density_id")); + + //obj.put("town_name", rs.getString("town_name")); //Район + //obj.put("date", rs.getString("date")); //Дата анкетирования + //obj.put("surveyed_area", rs.getDouble("surveyed_area")); //Обследованная площадь га + + + double lat=0; + double lon=0; + int cnt1=0; + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + lat+=rs.getDouble("lat1"); + lon+=rs.getDouble("lon1"); + cnt1++; + } + if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + lat+=rs.getDouble("lat2"); + lon+=rs.getDouble("lon2"); + cnt1++; + } + if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + lat+=rs.getDouble("lat3"); + lon+=rs.getDouble("lon3"); + cnt1++; + } + if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + lat+=rs.getDouble("lat4"); + lon+=rs.getDouble("lon4"); + cnt1++; + } + if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + lat+=rs.getDouble("lat5"); + lon+=rs.getDouble("lon5"); + cnt1++; + } + if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + lat+=rs.getDouble("lat6"); + lon+=rs.getDouble("lon6"); + cnt1++; + } + if(cnt1>0) { + lat=lat/cnt1; + lon=lon/cnt1; + }else{ + if(rs.getString("lat_center")!=null && rs.getString("lon_center")!=null && rs.getFloat("lat_center")!=0 && rs.getFloat("lon_center")!=0) { + lat=rs.getDouble("lat_center"); + lon=rs.getDouble("lon_center"); + } + } + obj.put("lat", lat); + obj.put("lon", lon); + boolean point=cnt1<=2; + + JSONObject geom = null; + if(rs.getString("geom")!=null) + { + try { + geom = new JSONObject(rs.getString("geom")); + }catch (JSONException err){ + + } + }else { + if(point) { + /*geom = new JSONObject(); + geom.put("type","Point"); + JSONArray crdSub=new JSONArray(); + crdSub.put(rs.getDouble("lon1")); + crdSub.put(rs.getDouble("lat1")); + geom.put("coordinates", crdSub);*/ + }else { + geom = new JSONObject(); + geom.put("type","Polygon"); + JSONArray crdMain=new JSONArray(); + JSONArray crdSub=new JSONArray(); + crdMain.put(crdSub); + + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + 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 && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + 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 && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + 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 && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + 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 && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + 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 && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon6")); + crd.put(rs.getDouble("lat6")); + crdSub.put(crd); + } + geom.put("coordinates", crdMain); + } + } + + if(geom!=null) + obj.put("geom", geom); + + 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+="Внутренняя ошибка сервера, запрос. "; + 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(); + } + + } + + @RequestMapping(value = "/get_spray",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public String getSprayMonitoring(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { + + int errorCode=0; + String errorMessage=""; + + //Load configuration from "config.xml" + 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); + } + + 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); + //st.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; + InputStream body; + if(reqData!=null) { + + + body = new ByteArrayInputStream(reqData); + + String text=""; + try { + text = new String(body.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + logger.info(text); + + //JSONParser jsonParser = new JSONParser(); + //doc = (JSONObject)jsonParser.parse(text); + //doc = new JSONObject(body); + doc = new JSONObject(text); + } + + 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," + + " lat_center," + + " lon_center," + + " lat1," + + " lon1," + + " lat2," + + " lon2," + + " lat3," + + " lon3," + + " lat4," + + " lon4," + + " lat5," + + " lon5," + + " lat6," + + " lon6," + + " terrain," + + " treated_area," + + " infested_area," + + " ST_AsGeoJSON(geom) as geom" + + " from main.frmlocustdel fld where" + + " fld.del=false" + + " and (${country_id} is null or (${country_id}=-1 and fld.country_id in (7,3,4,2)) or (${country_id}=-2 and fld.country_id in (7,1,5,6,8,9,10)) or ${country_id}=fld.country_id)" + + " and (${region_id} is null or ${region_id}=fld.region_id)" + + " and (${date_start} is null or to_timestamp(${date_start})<=fld.date)" + + " and (${date_end} is null or to_timestamp(${date_end})>=fld.date)" + + " and (${device_id} is null or (${device_id} and fld.device_id is not null) or (not ${device_id} and fld.device_id is null))" + + " and (${registered} is null or (${registered} and (fld.device_id is null or fld.device_id in (select serial from main.terminals where del=false))) or (not ${registered} and (fld.device_id not in (select serial from main.terminals where del=false))))" + + " and ((${test} is null and (test!=true or test is null)) or ${test}=fld.test)" + + " order by fld.id desc;"; + + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + if(doc!=null) { + stmtn.setInt("_user_id", Integer.parseInt(user.id)); + + if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); + else stmtn.setInt("country_id",doc.getInt("country_id")); + + if(doc.isNull("region_id")) stmtn.setNULLInt("region_id"); + else stmtn.setInt("region_id",doc.getInt("region_id")); + + if(doc.isNull("locust_type_id")) stmtn.setNULLInt("locust_type_id"); + else stmtn.setInt("locust_type_id",doc.getInt("locust_type_id")); + + if(doc.isNull("date_start")) stmtn.setNULLInt("date_start"); + else stmtn.setInt("date_start",doc.getInt("date_start")); + + if(doc.isNull("date_end")) stmtn.setNULLInt("date_end"); + else stmtn.setInt("date_end",doc.getInt("date_end")); + + if(doc.isNull("device_id")) stmtn.setNULLBoolean("device_id"); + else stmtn.setBoolean("device_id",doc.getInt("device_id")); + + if(doc.isNull("registered")) stmtn.setNULLBoolean("registered"); + else stmtn.setBoolean("registered",doc.getInt("registered")); + + if(doc.isNull("test")) stmtn.setNULLBoolean("test"); + else stmtn.setBoolean("test",doc.getInt("test")); + } + 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("terrain")!=null) + obj.put("terrain", rs.getString("terrain")); + if(rs.getObject("treated_area")!=null) + obj.put("treated_area", rs.getFloat("treated_area")); + if(rs.getObject("infested_area")!=null) + obj.put("infested_area", rs.getFloat("infested_area")); + + double lat=0; + double lon=0; + int cnt1=0; + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + lat+=rs.getDouble("lat1"); + lon+=rs.getDouble("lon1"); + cnt1++; + } + if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + lat+=rs.getDouble("lat2"); + lon+=rs.getDouble("lon2"); + cnt1++; + } + if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + lat+=rs.getDouble("lat3"); + lon+=rs.getDouble("lon3"); + cnt1++; + } + if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + lat+=rs.getDouble("lat4"); + lon+=rs.getDouble("lon4"); + cnt1++; + } + if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + lat+=rs.getDouble("lat5"); + lon+=rs.getDouble("lon5"); + cnt1++; + } + if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + lat+=rs.getDouble("lat6"); + lon+=rs.getDouble("lon6"); + cnt1++; + } + //lat=lat/cnt1; + //lon=lon/cnt1; + lat=rs.getDouble("lat_center"); + lon=rs.getDouble("lon_center"); + obj.put("lat", lat); + obj.put("lon", lon); + boolean point=cnt1<=2; + + JSONObject geom = null; + + if(rs.getString("geom")!=null) + { + try { + geom = new JSONObject(rs.getString("geom")); + }catch (JSONException err){ + + } + }else { + if(point) { + /*geom = new JSONObject(); + geom.put("type","Point"); + JSONArray crdSub=new JSONArray(); + crdSub.put(rs.getDouble("lon1")); + crdSub.put(rs.getDouble("lat1")); + geom.put("coordinates", crdSub);*/ + }else { + geom = new JSONObject(); + geom.put("type","Polygon"); + JSONArray crdMain=new JSONArray(); + JSONArray crdSub=new JSONArray(); + crdMain.put(crdSub); + + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + 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 && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + 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 && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + 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 && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + 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 && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + 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 && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon6")); + crd.put(rs.getDouble("lat6")); + crdSub.put(crd); + } + geom.put("coordinates", crdMain); + } + } + if(geom!=null) + obj.put("geom", geom); + + 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+="Внутренняя ошибка сервера, запрос. "; + 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", ""); + obj.put("data",array); + return obj.toString(); + } + } + + @RequestMapping(value = "/get_checkpoints",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public String getCheckpoints(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { + + int errorCode=0; + String errorMessage=""; + + //Load 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 { + 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); + //st.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; + InputStream body; + if(reqData!=null) { + + + body = new ByteArrayInputStream(reqData); + + String text=""; + try { + text = new String(body.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + logger.info(text); + + //JSONParser jsonParser = new JSONParser(); + //doc = (JSONObject)jsonParser.parse(text); + //doc = new JSONObject(body); + doc = new JSONObject(text); + } + + 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 + f.id, + f.country_id, + u.name as user_name, + f.lat, + f.lon, + f.radius, + f.name, + f.temperature + from + main.frmcheckpoints f + left join main._users u on u.id=f.user_id + where + f.del=false + and (${country_id} is null or (${country_id}=-1 and f.country_id in (7,3,4,2)) or (${country_id}=-2 and f.country_id in (7,1,5,6,8,9,10)) or ${country_id}=f.country_id) + order by f.id desc;"""; + + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + if(doc!=null) { + //stmtn.setInt("_user_id", Integer.parseInt(user.id)); + + if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); + else stmtn.setInt("country_id",doc.getInt("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")); + + double lat=0; + double lon=0; + lat=rs.getDouble("lat"); + lon=rs.getDouble("lon"); + obj.put("user_name", rs.getString("user_name")); + obj.put("name", rs.getString("name")); + obj.put("lat", lat); + obj.put("lon", lon); + obj.put("radius", rs.getFloat("radius")); + obj.put("temperature", rs.getFloat("temperature")); + 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, sampling. "; + 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", ""); + obj.put("data",array); + return obj.toString(); + } + } + + //Получить плотность личинок за последние 5 лет в заданном радиусе + @RequestMapping(value = "/get_density_larval",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public String getDensityLarval(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="id") Integer id,@RequestParam(required=false,name="lng") String language_id) { + int errorCode=0; + String errorMessage=""; + + //Load 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 { + 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!"; + } + + + 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.get_density_larval(${id}); + """; + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + stmtn.setInt("id",id); + PreparedStatement stmt=stmtn.getPreparedStatement(); + + rs = stmt.executeQuery(); + if (rs != null) { + try { + while(rs.next()) { + JSONObject obj = new JSONObject(); + obj.put("year", rs.getLong(1)); + obj.put("density", rs.getFloat(2)); + array.put(obj); + } + rs.close(); + } catch (SQLException ex) { + errorCode=1; + errorMessage+="Internal server error"; + ex.printStackTrace(); + logger.info(ex.getMessage()); + } + } + } catch (SQLException ex) { + errorCode=1; + errorMessage+="Internal server error"; + 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", "test"); + obj.put("data",array); + return obj.toString(); + } + } + + //Получить плотность имаго за последние 5 лет + @RequestMapping(value = "/get_density_imago",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public String getDensityImago(@ModelAttribute User user,@RequestParam(required=false,name="id") Integer id,@RequestParam(required=false,name="lng") String language_id) { + int errorCode=0; + String errorMessage=""; + + //Load 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 { + 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!"; + } + + + 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.get_density_imago(${id}); + """; + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + stmtn.setInt("id",id); + PreparedStatement stmt=stmtn.getPreparedStatement(); + + rs = stmt.executeQuery(); + if (rs != null) { + try { + while(rs.next()) { + JSONObject obj = new JSONObject(); + obj.put("year", rs.getLong(1)); + obj.put("density", rs.getFloat(2)); + array.put(obj); + } + rs.close(); + } catch (SQLException ex) { + errorCode=1; + errorMessage+="Internal server error"; + ex.printStackTrace(); + logger.info(ex.getMessage()); + } + } + } catch (SQLException ex) { + errorCode=1; + errorMessage+="Internal server error"; + 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", ""); + obj.put("data",array); + return obj.toString(); + } + } + + @Override + public void setServletContext(ServletContext servletContext) { + this.context=servletContext; + } + + +} diff --git a/src/main/java/org/ccalm/main/QGIS.java b/src/main/java/org/ccalm/main/QGIS.java new file mode 100644 index 0000000..e3d7fb2 --- /dev/null +++ b/src/main/java/org/ccalm/main/QGIS.java @@ -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 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<='"+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<='"+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(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; + } + +} diff --git a/src/main/java/org/ccalm/main/SendMail.java b/src/main/java/org/ccalm/main/SendMail.java new file mode 100644 index 0000000..f10a14b --- /dev/null +++ b/src/main/java/org/ccalm/main/SendMail.java @@ -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 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!
"; + }else + { + logger.info("
Connect is ERROR
"); + result+="Connect is ERROR!
"; + } + }catch(Exception e) + { + logger.info("
Connect Exception:"+e.getMessage()+"
"); + result+="Connect Exception:"+e.getMessage()+"
"; + } + + /*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+="
Exec Exception:"+ex.getMessage()+"
"; + } + + + if(rs1!=null) + { + try { + while (rs1.next()) //Пробегаюсь по странам и генерю сообщение + { + String html=""; + + String country_id=rs1.getString("id"); + String country_name=rs1.getString("name"); + m_locale=rs1.getString("language"); + String email = rs1.getString("email"); + + html="

"+country_name+"

"; + 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 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 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.dateExec Exception:"+ex.getMessage()+"
"; + } + + html+="

"+trt("Egg_pods_density")+"

"; + + //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+="
"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000)); + + html+=""; + html+=""; + + boolean exists=false; + if(rs!=null) + { + while (rs.next()) + { + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + + exists=true; + } + } + st.close(); + if(!exists) html+=""; + html+="
"+trt("Oblast")+"\"\""+trt("Number_forms")+" \""+trt("Danger")+"\"
("+trt("Egg_pods_density")+" > 1)
\"\""+trt("Number_forms")+" \""+trt("Attention")+"\"
("+trt("Egg_pods_density")+" <= 1)
\"\""+trt("Number_forms")+" \""+trt("Quietly")+"\"
("+trt("Egg_pods_density")+" = 0)
"+rs.getString("region_name")+""+rs.getString("danger")+""+rs.getString("attention")+""+rs.getString("quietly")+"
"+trt("No_data")+"
"; + html+=""+trt("Open_data_on_the_map")+""; + html+="

"; + + //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= 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= 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.dateExec Exception:"+ex.getMessage()+"
"; + } + + html+="

"+trt("Adult_density")+"

"; + + html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000)); + html+="
"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000)); + + html+=""; + html+=""; + + exists=false; + if(rs!=null) + { + while (rs.next()) + { + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + + exists=true; + } + } + st.close(); + if(!exists) html+=""; + html+="
"+trt("Oblast")+"\"\""+trt("Number_forms")+" \""+trt("Dangerous")+"\"
("+trt("Adult_density")+" >=5)
\"\""+trt("Number_forms")+" \""+trt("Attention")+"\"
("+trt("Adult_density")+" >=3 "+trt("and")+" <5)
\"\""+trt("Number_forms")+" \""+trt("Quietly")+"\"
("+trt("Adult_density")+" <=2)
"+rs.getString("region_name")+""+rs.getString("danger")+""+rs.getString("attention")+""+rs.getString("quietly")+"
"+trt("No_data")+"
"; + html+=""+trt("Open_data_on_the_map")+""; + html+="

"; + + + //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= 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= 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.dateExec Exception:"+ex.getMessage()+"
"; + } + + html+="

"+trt("Hopper_density")+"

"; + + html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000)); + html+="
"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000)); + + html+=""; + html+=""; + + exists=false; + if(rs!=null) + { + while (rs.next()) + { + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + + exists=true; + } + } + st.close(); + if(!exists) html+=""; + html+="
"+trt("Oblast")+"\"\""+trt("Number_forms")+" \""+trt("Dangerous")+"\"
("+trt("Hopper_density")+" >=5)
\"\""+trt("Number_forms")+" \""+trt("Attention")+"\"
("+trt("Hopper_density")+" >=3 "+trt("and")+" <5)
\"\""+trt("Number_forms")+" \""+trt("Quietly")+"\"
("+trt("Hopper_density")+" <=2)
"+rs.getString("region_name")+""+rs.getString("danger")+""+rs.getString("attention")+""+rs.getString("quietly")+"
"+trt("No_data")+"
"; + html+=""+trt("Open_data_on_the_map")+""; + html+="

"; + + 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= 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.dateExec Exception:"+ex.getMessage()+"
"; + } + + html+="

"+trt("Number_of_bands")+"

"; + html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000)); + html+="
"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000)); + + html+=""; + html+=""; + + exists=false; + if(rs!=null) + { + while (rs.next()) + { + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + + exists=true; + } + } + st.close(); + if(!exists) html+=""; + html+="
"+trt("Oblast")+"\"\""+trt("Number_forms")+" \""+trt("Dangerous")+"\"
("+trt("Number_of_bands")+" >=1)
\"\""+trt("Number_forms")+" \""+trt("Quietly")+"\"
("+trt("Number_of_bands")+" <1)
"+rs.getString("region_name")+""+rs.getString("danger")+""+rs.getString("quietly")+"
"+trt("No_data")+"
"; + html+=""+trt("Open_data_on_the_map")+""; + html+="

"; + + 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.dateto_timestamp("+start_t+") and fl.dateExec Exception:"+ex.getMessage()+"
"; + } + + html+="

"+trt("Number_of_swarms")+"

"; + html+=trt("From_date")+": "+sdf.format(new Date(Long.parseLong(start_t)*1000)); + html+="
"+trt("To_date")+": "+sdf.format(new Date(Long.parseLong(end_t)*1000)); + + html+=""; + html+=""; + + exists=false; + if(rs!=null) + { + while (rs.next()) + { + html+=""; + html+=""; + html+=""; + html+=""; + html+=""; + + exists=true; + } + } + st.close(); + if(!exists) html+=""; + html+="
"+trt("Oblast")+"\"\""+trt("Number_forms")+" \""+trt("Dangerous")+"\"
("+trt("Number_of_swarms")+" >=1)
\"\""+trt("Number_forms")+" \""+trt("Quietly")+"\"
("+trt("Number_of_swarms")+" <1)
"+rs.getString("region_name")+""+rs.getString("danger")+""+rs.getString("quietly")+"
"+trt("No_data")+"
"; + html+=""+trt("Open_data_on_the_map")+""; + html+="

"; + + 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+="
Exec Exception:"+ex.getMessage()+"
"; + } catch (SQLException ex) { + result+="
Exec Exception:"+ex.getMessage()+"
"; + } + } + + 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; + } + //--------------------------------------------------------------------------- + +} diff --git a/src/main/java/org/ccalm/main/SessionController.java b/src/main/java/org/ccalm/main/SessionController.java new file mode 100644 index 0000000..21dd961 --- /dev/null +++ b/src/main/java/org/ccalm/main/SessionController.java @@ -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(); + } + } diff --git a/src/main/java/org/ccalm/main/TestFiles.java b/src/main/java/org/ccalm/main/TestFiles.java new file mode 100644 index 0000000..17c6a88 --- /dev/null +++ b/src/main/java/org/ccalm/main/TestFiles.java @@ -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!
"; + }else + { + logger.info("
Connect is ERROR
"); + result+="Connect is ERROR!
"; + } + }catch(Exception e) + { + logger.info("
Connect Exception:"+e.getMessage()+"
"); + result+="Connect Exception:"+e.getMessage()+"
"; + } + + String sql; + Statement st; + ResultSet rs=null; + + result+="image_name1

"; + 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+="
Exec Exception:"+ex.getMessage()+"
"; + } + + 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")+"';"+"
"; + } + } + } + st.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + + result+="image_name2

"; + 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+="
Exec Exception:"+ex.getMessage()+"
"; + } + + 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")+"';"+"
"; + } + } + } + st.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + + + result+="image_name3

"; + 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+="
Exec Exception:"+ex.getMessage()+"
"; + } + + 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")+"';"+"
"; + } + } + } + st.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + + + return result; + } + //--------------------------------------------------------------------------- + @Override + public void setServletContext(ServletContext servletContext) { + this.context=servletContext; + } +} diff --git a/src/main/java/org/ccalm/main/TranslationController.java b/src/main/java/org/ccalm/main/TranslationController.java new file mode 100644 index 0000000..64f5b43 --- /dev/null +++ b/src/main/java/org/ccalm/main/TranslationController.java @@ -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("
Connect is ERROR
"); + } + }catch(Exception e) + { + System.out.println("
Connect Exception:"+e.getMessage()+"
"); + } + + 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("
SQLException:"+ex.getMessage()+"
"); + } + + 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("
SQLException:"+ex.getMessage()+"
"); + } + 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 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; + } + +} \ No newline at end of file diff --git a/src/main/java/org/ccalm/main/WeatherDownload.java b/src/main/java/org/ccalm/main/WeatherDownload.java new file mode 100644 index 0000000..b9ac6b6 --- /dev/null +++ b/src/main/java/org/ccalm/main/WeatherDownload.java @@ -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(); + } +} diff --git a/src/main/java/org/ccalm/main/engine/EngineController.java b/src/main/java/org/ccalm/main/engine/EngineController.java new file mode 100644 index 0000000..f29d5ea --- /dev/null +++ b/src/main/java/org/ccalm/main/engine/EngineController.java @@ -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 = 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 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 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 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 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 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 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+=" \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; + } + +} diff --git a/src/main/java/org/ccalm/main/login/LoginController.java b/src/main/java/org/ccalm/main/login/LoginController.java new file mode 100644 index 0000000..7574eca --- /dev/null +++ b/src/main/java/org/ccalm/main/login/LoginController.java @@ -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 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"; + } + +} diff --git a/src/main/java/org/ccalm/main/recReq/ExistsType.java b/src/main/java/org/ccalm/main/recReq/ExistsType.java new file mode 100644 index 0000000..0561d71 --- /dev/null +++ b/src/main/java/org/ccalm/main/recReq/ExistsType.java @@ -0,0 +1,8 @@ +package org.ccalm.main.recReq; + +import java.io.Serializable; + +public class ExistsType { + public boolean exists=false; + public String type=""; +} diff --git a/src/main/java/org/ccalm/main/recReq/RecReq.java b/src/main/java/org/ccalm/main/recReq/RecReq.java new file mode 100644 index 0000000..a50cc77 --- /dev/null +++ b/src/main/java/org/ccalm/main/recReq/RecReq.java @@ -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; + } + +} diff --git a/src/main/java/tctable/Point.java b/src/main/java/tctable/Point.java new file mode 100644 index 0000000..c212768 --- /dev/null +++ b/src/main/java/tctable/Point.java @@ -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; +} \ No newline at end of file diff --git a/src/main/java/tctable/TCField.java b/src/main/java/tctable/TCField.java new file mode 100644 index 0000000..1e9cb19 --- /dev/null +++ b/src/main/java/tctable/TCField.java @@ -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;i65535) len=65535; + value=new byte[len+2]; + value[0]=(byte) (len & 0x000000ff); + value[1]=(byte)((len & 0x0000ff00) >> 8); + for(int i=0;i> 8); + value[2]=(byte)((len & 0x00ff0000) >> 16); + value[3]=(byte)((len & 0xff000000) >> 24); + for(int i=0;i fields=new ArrayList(); //Список полей + + 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> 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 getTableSchema(Connection connection, String schemaName, String tableName) { + Map 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; + } + +} diff --git a/src/main/java/tctable/Tools.java b/src/main/java/tctable/Tools.java new file mode 100644 index 0000000..72e71f3 --- /dev/null +++ b/src/main/java/tctable/Tools.java @@ -0,0 +1,2529 @@ +package tctable; + +//import android.util.Log; + +import java.io.ByteArrayOutputStream; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.io.UnsupportedEncodingException; +import java.util.Calendar; +import java.util.TimeZone; + +public class Tools { + + + public static int countOccurrences(String str, char symbol) { + int count = 0; + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == symbol) { + count++; + } + } + return count; + } + + public static String readStringFromInputStream(InputStream inputStream) { + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int length; + try { + while ((length = inputStream.read(buffer)) != -1) { + result.write(buffer, 0, length); + } + } catch (IOException e1) { + e1.printStackTrace(); + } + // StandardCharsets.UTF_8.name() > JDK 7 + try { + return result.toString("UTF-8"); + } catch (UnsupportedEncodingException e) { + } + return ""; + } + + //Преобразовать арабские и индийские в современные цифры + public static String numConvert(String str) + { + if(str==null) return null; + String persian = "۰۱۲۳۴۵۶۷۸۹"; + String arabic = "٩٨٧٦٥٤٣٢١٠"; + String num = "0123456789"; + //Заменяю персидские + for(int i=0;i> pos)); + } + + public static String readUTF8_1(InputStream handle) throws IOException + { + byte[] tmp=new byte[handle.read()]; + handle.read(tmp); + return new String(tmp, "UTF8"); + } + + public static float readFloat(DataInputStream InStream) throws IOException + { + float f; + int ch1, ch2, ch3, ch4, count; + ch1 = InStream.readUnsignedByte(); + ch2 = InStream.readUnsignedByte(); + ch3 = InStream.readUnsignedByte(); + ch4 = InStream.readUnsignedByte(); + + count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1; + f = Float.intBitsToFloat(count); + return f; + } + + public static int readInt(DataInputStream InStream) throws IOException + { + int ch1, ch2, ch3, ch4, count; + ch1 = InStream.readUnsignedByte(); + ch2 = InStream.readUnsignedByte(); + ch3 = InStream.readUnsignedByte(); + ch4 = InStream.readUnsignedByte(); + + count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1; + return count; + } + + public static long readUInt(InputStream InStream) throws IOException + { + long count; + int ch1, ch2, ch3, ch4; + ch1 = InStream.read(); + ch2 = InStream.read(); + ch3 = InStream.read(); + ch4 = InStream.read(); + + count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1; + return count; + } + + //Прочитать 4 байта в unsigned int а так как unsigned нет в java то в long + public static long readUInt(byte[] mas,long pos) + { + byte[] rez = {0, 0, 0, 0, 0, 0, 0, 0}; + rez[4] = mas[(int)pos+3]; + rez[5] = mas[(int)pos+2]; + rez[6] = mas[(int)pos+1]; + rez[7] = mas[(int)pos+0]; + long result= ByteBuffer.wrap(rez).getLong(); + return result; + } + + public static short readShort(DataInputStream InStream) throws IOException + { + int ch1, ch2, count; + ch1 = InStream.readUnsignedByte(); + ch2 = InStream.readUnsignedByte(); + + count = (ch2 << 8) | ch1; + return (short)count; + } + + public static int readUShort(InputStream InStream) throws IOException + { + int ch1, ch2; + ch1 = InStream.read(); + ch2 = InStream.read(); + return (ch2 << 8) | ch1; + } + + //Записать 4 байта в поток + public static void writeInt(OutputStream out, int val) throws IOException + { + byte[] result = {0, 0, 0, 0}; + result[0] = (byte) (val >>> 24); + result[1] = (byte) (val >>> 16); + result[2] = (byte) (val >>> 8); + result[3] = (byte) (val >>> 0); + out.write(result); + } + + //Записать 4 байта в поток + public static void writeUInt(OutputStream out, long val) throws IOException + { + byte[] result = {0, 0, 0, 0}; + result[0] = (byte) (val >>> 24); + result[1] = (byte) (val >>> 16); + result[2] = (byte) (val >>> 8); + result[3] = (byte) (val >>> 0); + out.write(result); + } + + public static String afterLast(String str, String sub) { + int pos = str.lastIndexOf(sub); + if (pos == -1) { + return ""; + } + return str.substring(pos + sub.length()); + } + + public static String beforeLast(String str, String ch) + { + int i=str.lastIndexOf(ch); + if(i!=-1) + { + return str.substring(0,i); + } + return ""; + } + public static String beforeFirst(String str, String ch) + { + int i=str.indexOf(ch); + if(i!=-1) + { + return str.substring(0,i); + } + return ""; + } + + //узнать точку пересичений 2х линай если x=0 и y=0 то не пересиклась + public static Point getCrossingLine(Point PHead0, Point PTail0, Point PHead1, Point PTail1) + { + Point rezPoint = new Point(); + + double a0, b0, c0, a1, b1, c1; + boolean bRez = true; + a0 = PTail0.y - PHead0.y; + b0 = PHead0.x - PTail0.x; + c0 = PTail0.x * PHead0.y - PHead0.x * PTail0.y; + + a1 = PTail1.y - PHead1.y; + b1 = PHead1.x - PTail1.x; + c1 = PTail1.x * PHead1.y - PHead1.x * PTail1.y; + + if (b1 == 0) rezPoint.x = PHead1.x;//если перпендикулярна oy + else rezPoint.x = (-(b0 * c1 / b1) + c0) / ((b0 * a1 / b1) - a0); + if (a1 == 0) rezPoint.y = PHead1.y;//если перпендикулярна oy + else rezPoint.y = (-(c1 * a0 / a1) + c0) / ((a0 * b1 / a1) - b0); + //проверка на вхождение в отрезоки (с погрешностью 0.0000001 (зачем понадобилась погрешность?)) + //по x + if ((rezPoint.x < Math.min(PHead0.x, PTail0.x) - 0.0000001) || (rezPoint.x > Math.max(PHead0.x, PTail0.x) + 0.0000001)) + bRez = false; + if ((rezPoint.x < Math.min(PHead1.x, PTail1.x) - 0.0000001) || (rezPoint.x > Math.max(PHead1.x, PTail1.x) + 0.0000001)) + bRez = false; + //по y + if ((rezPoint.y < Math.min(PHead0.y, PTail0.y) - 0.0000001) || (rezPoint.y > Math.max(PHead0.y, PTail0.y) + 0.0000001)) + bRez = false; + if ((rezPoint.y < Math.min(PHead1.y, PTail1.y) - 0.0000001) || (rezPoint.y > Math.max(PHead1.y, PTail1.y) + 0.0000001)) + bRez = false; + + if (!bRez) + { + rezPoint.x = 0; + rezPoint.y = 0; + } + return rezPoint; + } + + public static Point getCrossingLine2(Point PHead0,Point PTail0,Point PHead1,Point PTail1) + { + boolean bRez=true; + Point rezPoint = new Point(); + rezPoint.x=0; + rezPoint.y=0; + + double a0,b0,c0,a1,b1,c1; + a0=PTail0.y-PHead0.y; + b0=PHead0.x-PTail0.x; + c0=PTail0.x*PHead0.y-PHead0.x*PTail0.y; + + a1=PTail1.y-PHead1.y; + b1=PHead1.x-PTail1.x; + c1=PTail1.x*PHead1.y-PHead1.x*PTail1.y; + + if (b1==0) rezPoint.x=PHead1.x;//если перпендикулярна oy + else rezPoint.x=(-(b0*c1/b1)+c0)/((b0*a1/b1)-a0); + if (a1==0) rezPoint.y=PHead1.y;//если перпендикулярна ox + else rezPoint.y=(-(c1*a0/a1)+c0)/((a0*b1/a1)-b0); + //по x + if (rezPoint.xMath.max(PHead0.x,PTail0.x)) + bRez=false; + if (rezPoint.xMath.max(PHead1.x,PTail1.x)) + bRez=false; + //по y + if (rezPoint.yMath.max(PHead0.y,PTail0.y)) + bRez=false; + if (rezPoint.yMath.max(PHead1.y,PTail1.y)) + bRez=false; + if (!bRez) + { + rezPoint.x=0; + rezPoint.y=0; + } + return rezPoint; + } + + //Так как в replaceAll много заморочек с регулярными выражениями + public static String replaceAll(String txt, String val, String rep) { + if(txt==null || val==null || rep==null) return txt; + return txt.replace(val,rep); + /*while(true) + { + String tmpstr=txt.replace(val, rep); + if(tmpstr.equals(txt)) + { + txt=tmpstr; + break; + }else + { + txt=tmpstr; + } + } + return txt;*/ + } + + public static byte[] subArray(byte[] b, int offset, int length) { + byte[] sub = new byte[length]; + for (int i = offset; i < offset + length; i++) { + try { + sub[i - offset] = b[i]; + } catch (Exception e) { + + } + } + return sub; + } + //---------------------------------------------------------------------------- + //ord - менять порядок байт + public static long hexStringToInt(String val, boolean ord) + { + if (ord) + { + return Long.parseLong(val, 16); + } + else + { + String tmp=""; + for(int i = 0; i < val.length() / 2; i++) + { + tmp = val.charAt(i * 2 + 1) + tmp; + tmp = val.charAt(i * 2) + tmp; + } + return Long.parseLong(val, 16); + } + } + public static long hexStringToInt(String val) + { + return hexStringToInt(val,true); + } + //------------------------------------------------------------------------------ + //Преобразовать HEX символ в число + public static int hexCharToInt(int input) + { + if(input >= '0' && input <= '9') + return input - '0'; + if(input >= 'A' && input <= 'F') + return input - 'A' + 10; + if(input >= 'a' && input <= 'f') + return input - 'a' + 10; + return 0; + } + //Из руского DOC в юникод + public static String fromDOStoASCII(byte[] str) + { + StringBuilder rez = new StringBuilder(); + for(int i=0; i '); break; + case (char)0x3f: rez.append('?'); break; + + case (char)0x40: rez.append('@'); break; + case (char)0x41: rez.append('A'); break; + case (char)0x42: rez.append('B'); break; + case (char)0x43: rez.append('C'); break; + case (char)0x44: rez.append('D'); break; + case (char)0x45: rez.append('E'); break; + case (char)0x46: rez.append('F'); break; + case (char)0x47: rez.append('G'); break; + case (char)0x48: rez.append('H'); break; + case (char)0x49: rez.append('I'); break; + case (char)0x4a: rez.append('J'); break; + case (char)0x4b: rez.append('K'); break; + case (char)0x4c: rez.append('L'); break; + case (char)0x4d: rez.append('M'); break; + case (char)0x4e: rez.append('N'); break; + case (char)0x4f: rez.append('O'); break; + + case (char)0x50: rez.append('P'); break; + case (char)0x51: rez.append('Q'); break; + case (char)0x52: rez.append('R'); break; + case (char)0x53: rez.append('S'); break; + case (char)0x54: rez.append('T'); break; + case (char)0x55: rez.append('U'); break; + case (char)0x56: rez.append('V'); break; + case (char)0x57: rez.append('W'); break; + case (char)0x58: rez.append('X'); break; + case (char)0x59: rez.append('Y'); break; + case (char)0x5a: rez.append('Z'); break; + case (char)0x5b: rez.append('['); break; + case (char)0x5c: rez.append('\\'); break; + case (char)0x5d: rez.append(']'); break; + case (char)0x5e: rez.append('^'); break; + case (char)0x5f: rez.append('_'); break; + + case (char)0x60: rez.append('`'); break; + case (char)0x61: rez.append('a'); break; + case (char)0x62: rez.append('b'); break; + case (char)0x63: rez.append('c'); break; + case (char)0x64: rez.append('d'); break; + case (char)0x65: rez.append('e'); break; + case (char)0x66: rez.append('f'); break; + case (char)0x67: rez.append('g'); break; + case (char)0x68: rez.append('h'); break; + case (char)0x69: rez.append('i'); break; + case (char)0x6a: rez.append('j'); break; + case (char)0x6b: rez.append('k'); break; + case (char)0x6c: rez.append('l'); break; + case (char)0x6d: rez.append('m'); break; + case (char)0x6e: rez.append('n'); break; + case (char)0x6f: rez.append('o'); break; + + case (char)0x70: rez.append('p'); break; + case (char)0x71: rez.append('q'); break; + case (char)0x72: rez.append('r'); break; + case (char)0x73: rez.append('s'); break; + case (char)0x74: rez.append('t'); break; + case (char)0x75: rez.append('u'); break; + case (char)0x76: rez.append('v'); break; + case (char)0x77: rez.append('w'); break; + case (char)0x78: rez.append('x'); break; + case (char)0x79: rez.append('y'); break; + case (char)0x7a: rez.append('z'); break; + case (char)0x7b: rez.append('{'); break; + case (char)0x7c: rez.append('|'); break; + case (char)0x7d: rez.append('}'); break; + case (char)0x7e: rez.append('~'); break; + case (char)0x7f: rez.append((char) 0xf5); break; //х + + case (char)0x80: rez.append((char) 0xc0); break; //А + case (char)0x81: rez.append((char) 0xC1); break; //Б + case (char)0x82: rez.append((char) 0xC2); break; //В + case (char)0x83: rez.append((char) 0xC3); break; //Г + case (char)0x84: rez.append((char) 0xC4); break; //Д + case (char)0x85: rez.append((char) 0xC5); break; //Е + case (char)0x86: rez.append((char) 0xC6); break; //Ж + case (char)0x87: rez.append((char) 0xC7); break; //З + case (char)0x88: rez.append((char) 0xC8); break; //И + case (char)0x89: rez.append((char) 0xC9); break; //Й + case (char)0x8a: rez.append((char) 0xCA); break; //К + case (char)0x8b: rez.append((char) 0xCB); break; //Л + case (char)0x8c: rez.append((char) 0xCC); break; //М + case (char)0x8D: rez.append((char) 0xCD); break; //Н + case (char)0x8E: rez.append((char) 0xCE); break; //О + case (char)0x8f: rez.append((char) 0xCF); break; //П + + case (char)0x90: rez.append((char) 0xD0); break; //Р + case (char)0x91: rez.append((char) 0xD1); break; //С + case (char)0x92: rez.append((char) 0xD2); break; //Т + case (char)0x93: rez.append((char) 0xD3); break; //У + case (char)0x94: rez.append((char) 0xD4); break; //Ф + case (char)0x95: rez.append((char) 0xD5); break; //Х + case (char)0x96: rez.append((char) 0xD6); break; //Ц + case (char)0x97: rez.append((char) 0xD7); break; //Ч + case (char)0x98: rez.append((char) 0xD8); break; //Ш + case (char)0x99: rez.append((char) 0xD9); break; //Щ + case (char)0x9a: rez.append((char) 0xDA); break; //Ъ + case (char)0x9b: rez.append((char) 0xDB); break; //Ы + case (char)0x9c: rez.append((char) 0xDC); break; //Ь + case (char)0x9D: rez.append((char) 0xDD); break; //Э + case (char)0x9E: rez.append((char) 0xDE); break; //Ю + case (char)0x9f: rez.append((char) 0xDF); break; //Я + + case (char)0xa0: rez.append((char) 0xE0); break; //а + case (char)0xA1: rez.append((char) 0xE1); break; //б + case (char)0xA2: rez.append((char) 0xE2); break; //в + case (char)0xA3: rez.append((char) 0xE3); break; //г + case (char)0xa4: rez.append((char) 0xE4); break; //д + case (char)0xA5: rez.append((char) 0xE5); break; //е + case (char)0xa6: rez.append((char) 0xE6); break; // + case (char)0xa7: rez.append((char) 0xE7); break; //з + case (char)0xa8: rez.append((char) 0xE8); break; //и + case (char)0xa9: rez.append((char) 0xE9); break; //й + case (char)0xAA: rez.append((char) 0xEA); break; //к + case (char)0xab: rez.append((char) 0xEB); break; //л + case (char)0xac: rez.append((char) 0xEC); break; //м + case (char)0xad: rez.append((char) 0xED); break; //н + case (char)0xae: rez.append((char) 0xEE); break; //о + case (char)0xAF: rez.append((char) 0xEF); break; //п + + case (char)0xb0: rez.append(' '); break; + case (char)0xb1: rez.append(' '); break; + case (char)0xb2: rez.append(' '); break; + case (char)0xb3: rez.append(' '); break; + case (char)0xB4: rez.append(' '); break; + case (char)0xb5: rez.append(' '); break; + case (char)0xb6: rez.append(' '); break; + case (char)0xb7: rez.append(' '); break; + case (char)0xb8: rez.append(' '); break; + case (char)0xb9: rez.append(' '); break; + case (char)0xBA: rez.append(' '); break; + case (char)0xbb: rez.append(' '); break; + case (char)0xBC: rez.append(' '); break; + case (char)0xBD: rez.append(' '); break; + case (char)0xBE: rez.append(' '); break; + case (char)0xBF: rez.append(' '); break; + + case (char)0xc0: rez.append(' '); break; + case (char)0xc1: rez.append(' '); break; + case (char)0xc2: rez.append(' '); break; + case (char)0xc3: rez.append(' '); break; + case (char)0xc4: rez.append(' '); break; + case (char)0xc5: rez.append(' '); break; + case (char)0xc6: rez.append(' '); break; + case (char)0xc7: rez.append(' '); break; + case (char)0xc8: rez.append(' '); break; + case (char)0xc9: rez.append(' '); break; + case (char)0xca: rez.append(' '); break; + case (char)0xcb: rez.append(' '); break; + case (char)0xcc: rez.append(' '); break; + case (char)0xcd: rez.append(' '); break; + case (char)0xce: rez.append(' '); break; + case (char)0xcf: rez.append(' '); break; + + case (char)0xd0: rez.append(' '); break; + case (char)0xd1: rez.append(' '); break; + case (char)0xd2: rez.append(' '); break; + case (char)0xd3: rez.append(' '); break; + case (char)0xd4: rez.append(' '); break; + case (char)0xd5: rez.append(' '); break; + case (char)0xd6: rez.append(' '); break; + case (char)0xd7: rez.append(' '); break; + case (char)0xd8: rez.append(' '); break; + case (char)0xd9: rez.append(' '); break; + case (char)0xda: rez.append(' '); break; + case (char)0xdb: rez.append(' '); break; + case (char)0xdc: rez.append(' '); break; + case (char)0xdd: rez.append(' '); break; + case (char)0xde: rez.append(' '); break; + case (char)0xdf: rez.append(' '); break; + + case (char)0xe0: rez.append((char) 0xF0); break; //р + case (char)0xe1: rez.append((char) 0xF1); break; //с + case (char)0xe2: rez.append((char) 0xF2); break; //т + case (char)0xe3: rez.append((char) 0xF3); break; //у + case (char)0xe4: rez.append((char) 0xF4); break; //ф + case (char)0xe5: rez.append((char) 0xF5); break; //х + case (char)0xe6: rez.append((char) 0xF6); break; //ц + case (char)0xe7: rez.append((char) 0xF7); break; //ч + case (char)0xe8: rez.append((char) 0xF8); break; //ш + case (char)0xe9: rez.append((char) 0xF9); break; //щ + case (char)0xea: rez.append((char) 0xFA); break; //ъ + case (char)0xeb: rez.append((char) 0xFB); break; //ы + case (char)0xec: rez.append((char) 0xFC); break; //ь + case (char)0xed: rez.append((char) 0xFD); break; //э + case (char)0xee: rez.append((char) 0xFE); break; //ю + case (char)0xef: rez.append((char) 0xFF); break; //я + + case (char)0xf0: rez.append(' '); break; + case (char)0xf1: rez.append(' '); break; + case (char)0xf2: rez.append(' '); break; + case (char)0xf3: rez.append(' '); break; + case (char)0xf4: rez.append(' '); break; + case (char)0xf5: rez.append(' '); break; + case (char)0xf6: rez.append(' '); break; + case (char)0xf7: rez.append(' '); break; + case (char)0xf8: rez.append(' '); break; + case (char)0xf9: rez.append(' '); break; + case (char)0xfa: rez.append(' '); break; + case (char)0xfb: rez.append(' '); break; + case (char)0xfc: rez.append(' '); break; + case (char)0xfd: rez.append(' '); break; + case (char)0xfe: rez.append(' '); break; + case (char)0xff: rez.append(' '); break; + default: + rez.append('?'); + } + } + return rez.toString(); + } + + public static byte[] fromASCIItoDOS(String str) + { + byte[] rez = new byte[str.length()]; + for(int i=0;i'; break; + case (char)0x3f: rez[i]=(byte)'?'; break; + + case (char)0x40: rez[i]=(byte)'@'; break; + case (char)0x41: rez[i]=(byte)'A'; break; + case (char)0x42: rez[i]=(byte)'B'; break; + case (char)0x43: rez[i]=(byte)'C'; break; + case (char)0x44: rez[i]=(byte)'D'; break; + case (char)0x45: rez[i]=(byte)'E'; break; + case (char)0x46: rez[i]=(byte)'F'; break; + case (char)0x47: rez[i]=(byte)'G'; break; + case (char)0x48: rez[i]=(byte)'H'; break; + case (char)0x49: rez[i]=(byte)'I'; break; + case (char)0x4a: rez[i]=(byte)'J'; break; + case (char)0x4b: rez[i]=(byte)'K'; break; + case (char)0x4c: rez[i]=(byte)'L'; break; + case (char)0x4d: rez[i]=(byte)'M'; break; + case (char)0x4e: rez[i]=(byte)'N'; break; + case (char)0x4f: rez[i]=(byte)'O'; break; + + case (char)0x50: rez[i]=(byte)'P'; break; + case (char)0x51: rez[i]=(byte)'Q'; break; + case (char)0x52: rez[i]=(byte)'R'; break; + case (char)0x53: rez[i]=(byte)'S'; break; + case (char)0x54: rez[i]=(byte)'T'; break; + case (char)0x55: rez[i]=(byte)'U'; break; + case (char)0x56: rez[i]=(byte)'V'; break; + case (char)0x57: rez[i]=(byte)'W'; break; + case (char)0x58: rez[i]=(byte)'X'; break; + case (char)0x59: rez[i]=(byte)'Y'; break; + case (char)0x5a: rez[i]=(byte)'Z'; break; + case (char)0x5b: rez[i]=(byte)'['; break; + case (char)0x5c: rez[i]=(byte)'\\'; break; + case (char)0x5d: rez[i]=(byte)']'; break; + case (char)0x5e: rez[i]=(byte)'^'; break; + case (char)0x5f: rez[i]=(byte)'_'; break; + + case (char)0x60: rez[i]=(byte)'`'; break; + case (char)0x61: rez[i]=(byte)'a'; break; + case (char)0x62: rez[i]=(byte)'b'; break; + case (char)0x63: rez[i]=(byte)'c'; break; + case (char)0x64: rez[i]=(byte)'d'; break; + case (char)0x65: rez[i]=(byte)'e'; break; + case (char)0x66: rez[i]=(byte)'f'; break; + case (char)0x67: rez[i]=(byte)'g'; break; + case (char)0x68: rez[i]=(byte)'h'; break; + case (char)0x69: rez[i]=(byte)'i'; break; + case (char)0x6a: rez[i]=(byte)'j'; break; + case (char)0x6b: rez[i]=(byte)'k'; break; + case (char)0x6c: rez[i]=(byte)'l'; break; + case (char)0x6d: rez[i]=(byte)'m'; break; + case (char)0x6e: rez[i]=(byte)'n'; break; + case (char)0x6f: rez[i]=(byte)'o'; break; + + case (char)0x70: rez[i]=(byte)'p'; break; + case (char)0x71: rez[i]=(byte)'q'; break; + case (char)0x72: rez[i]=(byte)'r'; break; + case (char)0x73: rez[i]=(byte)'s'; break; + case (char)0x74: rez[i]=(byte)'t'; break; + case (char)0x75: rez[i]=(byte)'u'; break; + case (char)0x76: rez[i]=(byte)'v'; break; + case (char)0x77: rez[i]=(byte)'w'; break; + case (char)0x78: rez[i]=(byte)'x'; break; + case (char)0x79: rez[i]=(byte)'y'; break; + case (char)0x7a: rez[i]=(byte)'z'; break; + case (char)0x7b: rez[i]=(byte)'{'; break; + case (char)0x7c: rez[i]=(byte)'|'; break; + case (char)0x7d: rez[i]=(byte)'}'; break; + case (char)0x7e: rez[i]=(byte)'~'; break; + case (char)0x7f: rez[i]=(byte)'×'; break; //127 + + case (char)0x80: rez[i]=(byte)' '; break; //128 + case (char)0x81: rez[i]=(byte)' '; break; + case (char)0x82: rez[i]=(byte)' '; break; + case (char)0x83: rez[i]=(byte)' '; break; + case (char)0x84: rez[i]=(byte)' '; break; + case (char)0x85: rez[i]=(byte)' '; break; + case (char)0x86: rez[i]=(byte)' '; break; + case (char)0x87: rez[i]=(byte)' '; break; + case (char)0x88: rez[i]=(byte)' '; break; + case (char)0x89: rez[i]=(byte)' '; break; + case (char)0x8a: rez[i]=(byte)' '; break; + case (char)0x8b: rez[i]=(byte)' '; break; + case (char)0x8c: rez[i]=(byte)' '; break; + case (char)0x8D: rez[i]=(byte)' '; break; + case (char)0x8E: rez[i]=(byte)' '; break; + case (char)0x8f: rez[i]=(byte)' '; break; + + case (char)0x90: rez[i]=(byte)' '; break; + case (char)0x91: rez[i]=(byte)' '; break; + case (char)0x92: rez[i]=(byte)' '; break; + case (char)0x93: rez[i]=(byte)' '; break; + case (char)0x94: rez[i]=(byte)' '; break; + case (char)0x95: rez[i]=(byte)' '; break; + case (char)0x96: rez[i]=(byte)' '; break; + case (char)0x97: rez[i]=(byte)' '; break; + case (char)0x98: rez[i]=(byte)' '; break; + case (char)0x99: rez[i]=(byte)' '; break; + case (char)0x9a: rez[i]=(byte)' '; break; + case (char)0x9b: rez[i]=(byte)' '; break; + case (char)0x9c: rez[i]=(byte)' '; break; + case (char)0x9D: rez[i]=(byte)' '; break; + case (char)0x9E: rez[i]=(byte)' '; break; + case (char)0x9f: rez[i]=(byte)' '; break; + + case (char)0xa0: rez[i]=(byte)' '; break; + case (char)0xA1: rez[i]=(byte)' '; break; + case (char)0xA2: rez[i]=(byte)' '; break; + case (char)0xA3: rez[i]=(byte)' '; break; + case (char)0xa4: rez[i]=(byte)' '; break; + case (char)0xA5: rez[i]=(byte)' '; break; + case (char)0xa6: rez[i]=(byte)' '; break; + case (char)0xa7: rez[i]=(byte)' '; break; + case (char)0xa8: rez[i]=(byte)' '; break; + case (char)0xa9: rez[i]=(byte)' '; break; + case (char)0xAA: rez[i]=(byte)' '; break; + case (char)0xab: rez[i]=(byte)' '; break; + case (char)0xac: rez[i]=(byte)' '; break; + case (char)0xad: rez[i]=(byte)' '; break; + case (char)0xae: rez[i]=(byte)' '; break; + case (char)0xAF: rez[i]=(byte)' '; break; + + case (char)0xb0: rez[i]=(byte)' '; break; + case (char)0xb1: rez[i]=(byte)' '; break; + case (char)0xb2: rez[i]=(byte)' '; break; + case (char)0xb3: rez[i]=(byte)' '; break; + case (char)0xB4: rez[i]=(byte)' '; break; + case (char)0xb5: rez[i]=(byte)' '; break; + case (char)0xb6: rez[i]=(byte)' '; break; + case (char)0xb7: rez[i]=(byte)' '; break; + case (char)0xb8: rez[i]=(byte)' '; break; + case (char)0xb9: rez[i]=(byte)' '; break; + case (char)0xBA: rez[i]=(byte)' '; break; + case (char)0xbb: rez[i]=(byte)' '; break; + case (char)0xBC: rez[i]=(byte)' '; break; + case (char)0xBD: rez[i]=(byte)' '; break; + case (char)0xBE: rez[i]=(byte)' '; break; + case (char)0xBF: rez[i]=(byte)' '; break; + + case (char)0xc0: rez[i]=(byte)0x80; break; + case (char)0xc1: rez[i]=(byte)0x81; break; + case (char)0xc2: rez[i]=(byte)0x82; break; + case (char)0xc3: rez[i]=(byte)0x83; break; + case (char)0xc4: rez[i]=(byte)0x84; break; + case (char)0xc5: rez[i]=(byte)0x85; break; + case (char)0xc6: rez[i]=(byte)0x86; break; + case (char)0xc7: rez[i]=(byte)0x87; break; + case (char)0xc8: rez[i]=(byte)0x88; break; + case (char)0xc9: rez[i]=(byte)0x89; break; + case (char)0xca: rez[i]=(byte)0x8a; break; + case (char)0xcb: rez[i]=(byte)0x8b; break; + case (char)0xcc: rez[i]=(byte)0x8c; break; + case (char)0xcd: rez[i]=(byte)0x8d; break; + case (char)0xce: rez[i]=(byte)0x8e; break; + case (char)0xcf: rez[i]=(byte)0x8f; break; + + case (char)0xd0: rez[i]=(byte)0x90; break; + case (char)0xd1: rez[i]=(byte)0x91; break; + case (char)0xd2: rez[i]=(byte)0x92; break; + case (char)0xd3: rez[i]=(byte)0x93; break; + case (char)0xd4: rez[i]=(byte)0x94; break; + case (char)0xd5: rez[i]=(byte)0x95; break; + case (char)0xd6: rez[i]=(byte)0x96; break; + case (char)0xd7: rez[i]=(byte)0x97; break; + case (char)0xd8: rez[i]=(byte)0x98; break; + case (char)0xd9: rez[i]=(byte)0x99; break; + case (char)0xda: rez[i]=(byte)0x9a; break; + case (char)0xdb: rez[i]=(byte)0x9b; break; + case (char)0xdc: rez[i]=(byte)0x9c; break; + case (char)0xdd: rez[i]=(byte)0x9d; break; + case (char)0xde: rez[i]=(byte)0x9e; break; + case (char)0xdf: rez[i]=(byte)0x9f; break; + + case (char)0xe0: rez[i]=(byte)0xa0; break; + case (char)0xe1: rez[i]=(byte)0xa1; break; + case (char)0xe2: rez[i]=(byte)0xa2; break; + case (char)0xe3: rez[i]=(byte)0xa3; break; + case (char)0xe4: rez[i]=(byte)0xa4; break; + case (char)0xe5: rez[i]=(byte)0xa5; break; + case (char)0xe6: rez[i]=(byte)0xa6; break; + case (char)0xe7: rez[i]=(byte)0xa7; break; + case (char)0xe8: rez[i]=(byte)0xa8; break; + case (char)0xe9: rez[i]=(byte)0xa9; break; + case (char)0xea: rez[i]=(byte)0xaa; break; + case (char)0xeb: rez[i]=(byte)0xab; break; + case (char)0xec: rez[i]=(byte)0xac; break; + case (char)0xed: rez[i]=(byte)0xad; break; + case (char)0xee: rez[i]=(byte)0xae; break; + case (char)0xef: rez[i]=(byte)0xaf; break; + + case (char)0xf0: rez[i]=(byte)0xe0; break; + case (char)0xf1: rez[i]=(byte)0xe1; break; + case (char)0xf2: rez[i]=(byte)0xe2; break; + case (char)0xf3: rez[i]=(byte)0xe3; break; + case (char)0xf4: rez[i]=(byte)0xe4; break; + case (char)0xf5: rez[i]=(byte)0xe5; break; + case (char)0xf6: rez[i]=(byte)0xe6; break; + case (char)0xf7: rez[i]=(byte)0xe7; break; + case (char)0xf8: rez[i]=(byte)0xe8; break; + case (char)0xf9: rez[i]=(byte)0xe9; break; + case (char)0xfa: rez[i]=(byte)0xea; break; + case (char)0xfb: rez[i]=(byte)0xeb; break; + case (char)0xfc: rez[i]=(byte)0xec; break; + case (char)0xfd: rez[i]=(byte)0xed; break; + case (char)0xfe: rez[i]=(byte)0xee; break; + case (char)0xff: rez[i]=(byte)0xef; break; + default: + rez[i]='?'; + } + } + return rez; + } + //--------------------------------------------------------------------------- + public static final String md5(final String str) + { + try { + // Create MD5 Hash + MessageDigest digest = MessageDigest + .getInstance("MD5"); + digest.update(str.getBytes()); + byte messageDigest[] = digest.digest(); + + // Create Hex String + StringBuffer hexString = new StringBuffer(); + for (int i = 0; i < messageDigest.length; i++) { + StringBuilder h = new StringBuilder(Integer.toHexString(0xFF & messageDigest[i])); + while (h.length() < 2) + h.insert(0, "0"); + hexString.append(h); + } + return hexString.toString(); + + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return ""; + } + //--------------------------------------------------------------------------- + //Отрезать от строки до указанного символа если не найден символ отрезается вся строка + 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; + } + //--------------------------------------------------------------------------- + public static int StdStrToInt(String str, boolean cutInt) + { + if(cutInt) + { + StringBuilder val= new StringBuilder(); + for(int i=0;i'); + break; + case 0x3f: + rez.append('?'); + break; + + case 0x40: + rez.append('@'); + break; + case 0x41: + rez.append('A'); + break; + case 0x42: + rez.append('B'); + break; + case 0x43: + rez.append('C'); + break; + case 0x44: + rez.append('D'); + break; + case 0x45: + rez.append('E'); + break; + case 0x46: + rez.append('F'); + break; + case 0x47: + rez.append('G'); + break; + case 0x48: + rez.append('H'); + break; + case 0x49: + rez.append('I'); + break; + case 0x4a: + rez.append('J'); + break; + case 0x4b: + rez.append('K'); + break; + case 0x4c: + rez.append('L'); + break; + case 0x4d: + rez.append('M'); + break; + case 0x4e: + rez.append('N'); + break; + case 0x4f: + rez.append('O'); + break; + + case 0x50: + rez.append('P'); + break; + case 0x51: + rez.append('Q'); + break; + case 0x52: + rez.append('R'); + break; + case 0x53: + rez.append('S'); + break; + case 0x54: + rez.append('T'); + break; + case 0x55: + rez.append('U'); + break; + case 0x56: + rez.append('V'); + break; + case 0x57: + rez.append('W'); + break; + case 0x58: + rez.append('X'); + break; + case 0x59: + rez.append('Y'); + break; + case 0x5a: + rez.append('Z'); + break; + case 0x5b: + rez.append('['); + break; + case 0x5c: + rez.append('\\'); + break; + case 0x5d: + rez.append(']'); + break; + case 0x5e: + rez.append('^'); + break; + case 0x5f: + rez.append('_'); + break; + + case 0x60: + rez.append('`'); + break; + case 0x61: + rez.append('a'); + break; + case 0x62: + rez.append('b'); + break; + case 0x63: + rez.append('c'); + break; + case 0x64: + rez.append('d'); + break; + case 0x65: + rez.append('e'); + break; + case 0x66: + rez.append('f'); + break; + case 0x67: + rez.append('g'); + break; + case 0x68: + rez.append('h'); + break; + case 0x69: + rez.append('i'); + break; + case 0x6a: + rez.append('j'); + break; + case 0x6b: + rez.append('k'); + break; + case 0x6c: + rez.append('l'); + break; + case 0x6d: + rez.append('m'); + break; + case 0x6e: + rez.append('n'); + break; + case 0x6f: + rez.append('o'); + break; + + case 0x70: + rez.append('p'); + break; + case 0x71: + rez.append('q'); + break; + case 0x72: + rez.append('r'); + break; + case 0x73: + rez.append('s'); + break; + case 0x74: + rez.append('t'); + break; + case 0x75: + rez.append('u'); + break; + case 0x76: + rez.append('v'); + break; + case 0x77: + rez.append('w'); + break; + case 0x78: + rez.append('x'); + break; + case 0x79: + rez.append('y'); + break; + case 0x7a: + rez.append('z'); + break; + case 0x7b: + rez.append('{'); + break; + case 0x7c: + rez.append('|'); + break; + case 0x7d: + rez.append('}'); + break; + case 0x7e: + rez.append('~'); + break; + case 0x7f: + rez.append('×'); + break; //127 + + case 0x80: + rez.append(' '); + break; + case 0x81: + rez.append('Ғ'); + break; + case 0x82: + rez.append(' '); + break; + case 0x83: + rez.append('ғ'); + break; + case 0x84: + rez.append(' '); + break; + case 0x85: + rez.append(' '); + break; + case 0x86: + rez.append(' '); + break; + case 0x87: + rez.append(' '); + break; + case 0x88: + rez.append(' '); + break; + case 0x89: + rez.append('№'); + break; + case 0x8a: + rez.append('Ә'); + break; + case 0x8b: + rez.append(' '); + break; + case 0x8c: + rez.append('Ң'); + break; + case 0x8D: + rez.append('Қ'); + break; + case 0x8E: + rez.append('Һ'); + break; + case 0x8f: + rez.append(' '); + break; + + case 0x90: + rez.append(' '); + break; + case 0x91: + rez.append(' '); + break; + case 0x92: + rez.append(' '); + break; + case 0x93: + rez.append(' '); + break; + case 0x94: + rez.append(' '); + break; + case 0x95: + rez.append(' '); + break; + case 0x96: + rez.append(' '); + break; + case 0x97: + rez.append(' '); + break; + case 0x98: + rez.append(' '); + break; + case 0x99: + rez.append(' '); + break; + case 0x9a: + rez.append('ә'); + break; + case 0x9b: + rez.append(' '); + break; + case 0x9c: + rez.append('ң'); + break; + case 0x9D: + rez.append('қ'); + break; + case 0x9E: + rez.append('һ'); + break; + case 0x9f: + rez.append(' '); + break; + case 0xa0: + rez.append(' '); + break; + case 0xA1: + rez.append('Ұ'); + break; + case 0xA2: + rez.append('ұ'); + break; + case 0xA3: + rez.append(' '); + break; + case 0xa4: + rez.append(' '); + break; + case 0xA5: + rez.append(' '); + break; + case 0xa6: + rez.append(' '); + break; + case 0xa7: + rez.append(' '); + break; + case 0xa8: + rez.append('Ё'); + break; + case 0xa9: + rez.append(' '); + break; + case 0xAA: + rez.append('Ө'); + break; + case 0xab: + rez.append(' '); + break; + case 0xac: + rez.append(' '); + break; + case 0xad: + rez.append(' '); + break; + case 0xae: + rez.append(' '); + break; + case 0xAF: + rez.append('Ү'); + break; + + case 0xb0: + rez.append(' '); + break; + case 0xb1: + rez.append(' '); + break; + case 0xb2: + rez.append('І'); + break; + case 0xb3: + rez.append('і'); + break; + case 0xB4: + rez.append(' '); + break; + case 0xb5: + rez.append(' '); + break; + case 0xb6: + rez.append(' '); + break; + case 0xb7: + rez.append(' '); + break; + case 0xb8: + rez.append('ё'); + break; + case 0xb9: + rez.append(' '); + break; + case 0xBA: + rez.append('ө'); + break; + case 0xbb: + rez.append(' '); + break; + case 0xBC: + rez.append(' '); + break; + case 0xBD: + rez.append(' '); + break; + case 0xBE: + rez.append(' '); + break; + case 0xBF: + rez.append('ү'); + break; + + case 0xc0: + rez.append('А'); + break; + case 0xc1: + rez.append('Б'); + break; + case 0xc2: + rez.append('В'); + break; + case 0xc3: + rez.append('Г'); + break; + case 0xc4: + rez.append('Д'); + break; + case 0xc5: + rez.append('Е'); + break; + case 0xc6: + rez.append('Ж'); + break; + case 0xc7: + rez.append('З'); + break; + case 0xc8: + rez.append('И'); + break; + case 0xc9: + rez.append('Й'); + break; + case 0xca: + rez.append('К'); + break; + case 0xcb: + rez.append('Л'); + break; + case 0xcc: + rez.append('М'); + break; + case 0xcd: + rez.append('Н'); + break; + case 0xce: + rez.append('О'); + break; + case 0xcf: + rez.append('П'); + break; + + case 0xd0: + rez.append('Р'); + break; + case 0xd1: + rez.append('С'); + break; + case 0xd2: + rez.append('Т'); + break; + case 0xd3: + rez.append('У'); + break; + case 0xd4: + rez.append('Ф'); + break; + case 0xd5: + rez.append('Х'); + break; + case 0xd6: + rez.append('Ц'); + break; + case 0xd7: + rez.append('Ч'); + break; + case 0xd8: + rez.append('Ш'); + break; + case 0xd9: + rez.append('Щ'); + break; + case 0xda: + rez.append('Ъ'); + break; + case 0xdb: + rez.append('Ы'); + break; + case 0xdc: + rez.append('Ь'); + break; + case 0xdd: + rez.append('Э'); + break; + case 0xde: + rez.append('Ю'); + break; + case 0xdf: + rez.append('Я'); + break; + + case 0xe0: + rez.append('а'); + break; + case 0xe1: + rez.append('б'); + break; + case 0xe2: + rez.append('в'); + break; + case 0xe3: + rez.append('г'); + break; + case 0xe4: + rez.append('д'); + break; + case 0xe5: + rez.append('е'); + break; + case 0xe6: + rez.append('ж'); + break; + case 0xe7: + rez.append('з'); + break; + case 0xe8: + rez.append('и'); + break; + case 0xe9: + rez.append('й'); + break; + case 0xea: + rez.append('к'); + break; + case 0xeb: + rez.append('л'); + break; + case 0xec: + rez.append('м'); + break; + case 0xed: + rez.append('н'); + break; + case 0xee: + rez.append('о'); + break; + case 0xef: + rez.append('п'); + break; + + case 0xf0: + rez.append('р'); + break; + case 0xf1: + rez.append('с'); + break; + case 0xf2: + rez.append('т'); + break; + case 0xf3: + rez.append('у'); + break; + case 0xf4: + rez.append('ф'); + break; + case 0xf5: + rez.append('х'); + break; + case 0xf6: + rez.append('ц'); + break; + case 0xf7: + rez.append('ч'); + break; + case 0xf8: + rez.append('ш'); + break; + case 0xf9: + rez.append('щ'); + break; + case 0xfa: + rez.append('ъ'); + break; + case 0xfb: + rez.append('ы'); + break; + case 0xfc: + rez.append('ь'); + break; + case 0xfd: + rez.append('э'); + break; + case 0xfe: + rez.append('ю'); + break; + case 0xff: + rez.append('я'); + break; + default: + rez.append('?'); + } + } + return rez.toString(); + } + + + public static byte[] toKAZASCII(String str) + { + byte[] rez = new byte[str.length()]; + for (int i = 0; i < str.length(); i++) + { + switch (str.charAt(i)) + { + case 0x00: + rez[i] = (byte) 0x00; + break; + case 0x01: + rez[i] = (byte) 0x01; + break; + case 0x02: + rez[i] = (byte) 0x02; + break; + case 0x03: + rez[i] = (byte) 0x03; + break; + case 0x04: + rez[i] = (byte) 0x04; + break; + case 0x05: + rez[i] = (byte) 0x05; + break; + case 0x06: + rez[i] = (byte) 0x06; + break; + case 0x07: + rez[i] = (byte) 0x07; + break; + case 0x08: + rez[i] = (byte) 0x08; + break; + case 0x09: + rez[i] = (byte) 0x09; + break; + case 0x0a: + rez[i] = (byte) 0x0a; + break; + case 0x0b: + rez[i] = (byte) 0x0b; + break; + case 0x0c: + rez[i] = (byte) 0x0c; + break; + case 0x0d: + rez[i] = (byte) 0x0d; + break; + case 0x0e: + rez[i] = (byte) 0x0e; + break; + case 0x0f: + rez[i] = (byte) 0x0f; + break; + case 0x10: + rez[i] = (byte) 0x10; + break; + case 0x11: + rez[i] = (byte) 0x11; + break; + case 0x12: + rez[i] = (byte) 0x12; + break; + case 0x13: + rez[i] = (byte) 0x13; + break; + case 0x14: + rez[i] = (byte) 0x14; + break; + case 0x15: + rez[i] = (byte) 0x15; + break; + case 0x16: + rez[i] = (byte) 0x16; + break; + case 0x17: + rez[i] = (byte) 0x17; + break; + case 0x18: + rez[i] = (byte) 0x18; + break; + case 0x19: + rez[i] = (byte) 0x19; + break; + case 0x1a: + rez[i] = (byte) 0x1a; + break; + case 0x1b: + rez[i] = (byte) 0x1b; + break; + case 0x1c: + rez[i] = (byte) 0x1c; + break; + case 0x1d: + rez[i] = (byte) 0x1d; + break; + case 0x1e: + rez[i] = (byte) 0x1e; + break; + case 0x1f: + rez[i] = (byte) 0x1f; + break; + case ' ': + rez[i] = (byte) 0x20; + break; + case '!': + rez[i] = (byte) 0x21; + break; + case '"': + rez[i] = (byte) 0x22; + break; + case '#': + rez[i] = (byte) 0x23; + break; + case '$': + rez[i] = (byte) 0x24; + break; + case '%': + rez[i] = (byte) 0x25; + break; + case '&': + rez[i] = (byte) 0x26; + break; + case '\'': + rez[i] = (byte) 0x27; + break; + case '(': + rez[i] = (byte) 0x28; + break; + case ')': + rez[i] = (byte) 0x29; + break; + case '*': + rez[i] = (byte) 0x2a; + break; + case '+': + rez[i] = (byte) 0x2b; + break; + case ',': + rez[i] = (byte) 0x2c; + break; + case '-': + rez[i] = (byte) 0x2d; + break; + case '.': + rez[i] = (byte) 0x2e; + break; + case '/': + rez[i] = (byte) 0x2f; + break; + case '0': + rez[i] = (byte) 0x30; + break; + case '1': + rez[i] = (byte) 0x31; + break; + case '2': + rez[i] = (byte) 0x32; + break; + case '3': + rez[i] = (byte) 0x33; + break; + case '4': + rez[i] = (byte) 0x34; + break; + case '5': + rez[i] = (byte) 0x35; + break; + case '6': + rez[i] = (byte) 0x36; + break; + case '7': + rez[i] = (byte) 0x37; + break; + case '8': + rez[i] = (byte) 0x38; + break; + case '9': + rez[i] = (byte) 0x39; + break; + case ':': + rez[i] = (byte) 0x3a; + break; + case ';': + rez[i] = (byte) 0x3b; + break; + case '<': + rez[i] = (byte) 0x3c; + break; + case '=': + rez[i] = (byte) 0x3d; + break; + case '>': + rez[i] = (byte) 0x3e; + break; + case '?': + rez[i] = (byte) 0x3f; + break; + case '@': + rez[i] = (byte) 0x40; + break; + case 'A': + rez[i] = (byte) 0x41; + break; + case 'B': + rez[i] = (byte) 0x42; + break; + case 'C': + rez[i] = (byte) 0x43; + break; + case 'D': + rez[i] = (byte) 0x44; + break; + case 'E': + rez[i] = (byte) 0x45; + break; + case 'F': + rez[i] = (byte) 0x46; + break; + case 'G': + rez[i] = (byte) 0x47; + break; + case 'H': + rez[i] = (byte) 0x48; + break; + case 'I': + rez[i] = (byte) 0x49; + break; + case 'J': + rez[i] = (byte) 0x4a; + break; + case 'K': + rez[i] = (byte) 0x4b; + break; + case 'L': + rez[i] = (byte) 0x4c; + break; + case 'M': + rez[i] = (byte) 0x4d; + break; + case 'N': + rez[i] = (byte) 0x4e; + break; + case 'O': + rez[i] = (byte) 0x4f; + break; + case 'P': + rez[i] = (byte) 0x50; + break; + case 'Q': + rez[i] = (byte) 0x51; + break; + case 'R': + rez[i] = (byte) 0x52; + break; + case 'S': + rez[i] = (byte) 0x53; + break; + case 'T': + rez[i] = (byte) 0x54; + break; + case 'U': + rez[i] = (byte) 0x55; + break; + case 'V': + rez[i] = (byte) 0x56; + break; + case 'W': + rez[i] = (byte) 0x57; + break; + case 'X': + rez[i] = (byte) 0x58; + break; + case 'Y': + rez[i] = (byte) 0x59; + break; + case 'Z': + rez[i] = (byte) 0x5a; + break; + case '[': + rez[i] = (byte) 0x5b; + break; + case '\\': + rez[i] = (byte) 0x5c; + break; + case ']': + rez[i] = (byte) 0x5d; + break; + case '^': + rez[i] = (byte) 0x5e; + break; + case '_': + rez[i] = (byte) 0x5f; + break; + case '`': + rez[i] = (byte) 0x60; + break; + case 'a': + rez[i] = (byte) 0x61; + break; + case 'b': + rez[i] = (byte) 0x62; + break; + case 'c': + rez[i] = (byte) 0x63; + break; + case 'd': + rez[i] = (byte) 0x64; + break; + case 'e': + rez[i] = (byte) 0x65; + break; + case 'f': + rez[i] = (byte) 0x66; + break; + case 'g': + rez[i] = (byte) 0x67; + break; + case 'h': + rez[i] = (byte) 0x68; + break; + case 'i': + rez[i] = (byte) 0x69; + break; + case 'j': + rez[i] = (byte) 0x6a; + break; + case 'k': + rez[i] = (byte) 0x6b; + break; + case 'l': + rez[i] = (byte) 0x6c; + break; + case 'm': + rez[i] = (byte) 0x6d; + break; + case 'n': + rez[i] = (byte) 0x6e; + break; + case 'o': + rez[i] = (byte) 0x6f; + break; + case 'p': + rez[i] = (byte) 0x70; + break; + case 'q': + rez[i] = (byte) 0x71; + break; + case 'r': + rez[i] = (byte) 0x72; + break; + case 's': + rez[i] = (byte) 0x73; + break; + case 't': + rez[i] = (byte) 0x74; + break; + case 'u': + rez[i] = (byte) 0x75; + break; + case 'v': + rez[i] = (byte) 0x76; + break; + case 'w': + rez[i] = (byte) 0x77; + break; + case 'x': + rez[i] = (byte) 0x78; + break; + case 'y': + rez[i] = (byte) 0x79; + break; + case 'z': + rez[i] = (byte) 0x7a; + break; + case '{': + rez[i] = (byte) 0x7b; + break; + case '|': + rez[i] = (byte) 0x7c; + break; + case '}': + rez[i] = (byte) 0x7d; + break; + case '~': + rez[i] = (byte) 0x7e; + break; + case '×': + rez[i] = (byte) 0x7f; + break; //? + //case L' ': rez[i]=(byte)0x80; break; + case 'Ғ': + rez[i] = (byte) 0x81; + break; + //case L' ': rez[i]=(byte)0x82; break; + case 'ғ': + rez[i] = (byte) 0x83; + break; + //case L' ': rez[i]=(byte)0x84; break; + //case L' ': rez[i]=(byte)0x85; break; + //case L' ': rez[i]=(byte)0x86; break; + //case L' ': rez[i]=(byte)0x87; break; + //case L' ': rez[i]=(byte)0x88; break; + case '№': + rez[i] = (byte) 0x89; + break; + case 'Ә': + rez[i] = (byte) 0x8a; + break; + //case L' ': rez[i]=(byte)0x8b; break; + case 'Ң': + rez[i] = (byte) 0x8c; + break; + case 'Қ': + rez[i] = (byte) 0x8D; + break; + case 'Һ': + rez[i] = (byte) 0x8E; + break; + //case L' ': rez[i]=(byte)0x8f; break; + //case L' ': rez[i]=(byte)0x90; break; + //case L' ': rez[i]=(byte)0x91; break; + //case L' ': rez[i]=(byte)0x92; break; + //case L' ': rez[i]=(byte)0x93; break; + //case L' ': rez[i]=(byte)0x94; break; + //case L' ': rez[i]=(byte)0x95; break; + //case L' ': rez[i]=(byte)0x96; break; + //case L' ': rez[i]=(byte)0x97; break; + //case L' ': rez[i]=(byte)0x98; break; + //case L' ': rez[i]=(byte)0x99; break; + case 'ә': + rez[i] = (byte) 0x9a; + break; + //case L' ': rez[i]=(byte)0x9b; break; + case 'ң': + rez[i] = (byte) 0x9c; + break; + case 'қ': + rez[i] = (byte) 0x9D; + break; + case 'һ': + rez[i] = (byte) 0x9E; + break; + //case L' ': rez[i]=(byte)0x9f; break; + //case L' ': rez[i]=(byte)0xa0; break; + case 'Ұ': + rez[i] = (byte) 0xA1; + break; + case 'ұ': + rez[i] = (byte) 0xA2; + break; + //case L' ': rez[i]=(byte)0xA3; break; + //case L' ': rez[i]=(byte)0xa4; break; + //case L' ': rez[i]=(byte)0xA5; break; + //case L' ': rez[i]=(byte)0xa6; break; + //case L' ': rez[i]=(byte)0xa7; break; + case 'Ё': + rez[i] = (byte) 0xa8; + break; + //case L' ': rez[i]=(byte)0xa9; break; + case 'Ө': + rez[i] = (byte) 0xAA; + break; + //case L' ': rez[i]=(byte)0xab; break; + //case L' ': rez[i]=(byte)0xac; break; + //case L' ': rez[i]=(byte)0xad; break; + //case L' ': rez[i]=(byte)0xae; break; + case 'Ү': + rez[i] = (byte) 0xAF; + break; + //case L' ': rez[i]=(byte)0xb0; break; + //case L' ': rez[i]=(byte)0xb1; break; + case 'І': + rez[i] = (byte) 0xb2; + break; + case 'і': + rez[i] = (byte) 0xb3; + break; + //case L' ': rez[i]=(byte)0xB4; break; + //case L' ': rez[i]=(byte)0xb5; break; + //case L' ': rez[i]=(byte)0xb6; break; + //case L' ': rez[i]=(byte)0xb7; break; + case 'ё': + rez[i] = (byte) 0xb8; + break; + //case L' ': rez[i]=(byte)0xb9; break; + case 'ө': + rez[i] = (byte) 0xBA; + break; + //case L' ': rez[i]=(byte)0xbb; break; + //case L' ': rez[i]=(byte)0xBC; break; + //case L' ': rez[i]=(byte)0xBD; break; + //case L' ': rez[i]=(byte)0xBE; break; + case 'ү': + rez[i] = (byte) 0xBF; + break; + case 'А': + rez[i] = (byte) 0xc0; + break; + case 'Б': + rez[i] = (byte) 0xc1; + break; + case 'В': + rez[i] = (byte) 0xc2; + break; + case 'Г': + rez[i] = (byte) 0xc3; + break; + case 'Д': + rez[i] = (byte) 0xc4; + break; + case 'Е': + rez[i] = (byte) 0xc5; + break; + case 'Ж': + rez[i] = (byte) 0xc6; + break; + case 'З': + rez[i] = (byte) 0xc7; + break; + case 'И': + rez[i] = (byte) 0xc8; + break; + case 'Й': + rez[i] = (byte) 0xc9; + break; + case 'К': + rez[i] = (byte) 0xca; + break; + case 'Л': + rez[i] = (byte) 0xcb; + break; + case 'М': + rez[i] = (byte) 0xcc; + break; + case 'Н': + rez[i] = (byte) 0xcd; + break; + case 'О': + rez[i] = (byte) 0xce; + break; + case 'П': + rez[i] = (byte) 0xcf; + break; + case 'Р': + rez[i] = (byte) 0xd0; + break; + case 'С': + rez[i] = (byte) 0xd1; + break; + case 'Т': + rez[i] = (byte) 0xd2; + break; + case 'У': + rez[i] = (byte) 0xd3; + break; + case 'Ф': + rez[i] = (byte) 0xd4; + break; + case 'Х': + rez[i] = (byte) 0xd5; + break; + case 'Ц': + rez[i] = (byte) 0xd6; + break; + case 'Ч': + rez[i] = (byte) 0xd7; + break; + case 'Ш': + rez[i] = (byte) 0xd8; + break; + case 'Щ': + rez[i] = (byte) 0xd9; + break; + case 'Ъ': + rez[i] = (byte) 0xda; + break; + case 'Ы': + rez[i] = (byte) 0xdb; + break; + case 'Ь': + rez[i] = (byte) 0xdc; + break; + case 'Э': + rez[i] = (byte) 0xdd; + break; + case 'Ю': + rez[i] = (byte) 0xde; + break; + case 'Я': + rez[i] = (byte) 0xdf; + break; + case 'а': + rez[i] = (byte) 0xe0; + break; + case 'б': + rez[i] = (byte) 0xe1; + break; + case 'в': + rez[i] = (byte) 0xe2; + break; + case 'г': + rez[i] = (byte) 0xe3; + break; + case 'д': + rez[i] = (byte) 0xe4; + break; + case 'е': + rez[i] = (byte) 0xe5; + break; + case 'ж': + rez[i] = (byte) 0xe6; + break; + case 'з': + rez[i] = (byte) 0xe7; + break; + case 'и': + rez[i] = (byte) 0xe8; + break; + case 'й': + rez[i] = (byte) 0xe9; + break; + case 'к': + rez[i] = (byte) 0xea; + break; + case 'л': + rez[i] = (byte) 0xeb; + break; + case 'м': + rez[i] = (byte) 0xec; + break; + case 'н': + rez[i] = (byte) 0xed; + break; + case 'о': + rez[i] = (byte) 0xee; + break; + case 'п': + rez[i] = (byte) 0xef; + break; + case 'р': + rez[i] = (byte) 0xf0; + break; + case 'с': + rez[i] = (byte) 0xf1; + break; + case 'т': + rez[i] = (byte) 0xf2; + break; + case 'у': + rez[i] = (byte) 0xf3; + break; + case 'ф': + rez[i] = (byte) 0xf4; + break; + case 'х': + rez[i] = (byte) 0xf5; + break; + case 'ц': + rez[i] = (byte) 0xf6; + break; + case 'ч': + rez[i] = (byte) 0xf7; + break; + case 'ш': + rez[i] = (byte) 0xf8; + break; + case 'щ': + rez[i] = (byte) 0xf9; + break; + case 'ъ': + rez[i] = (byte) 0xfa; + break; + case 'ы': + rez[i] = (byte) 0xfb; + break; + case 'ь': + rez[i] = (byte) 0xfc; + break; + case 'э': + rez[i] = (byte) 0xfd; + break; + case 'ю': + rez[i] = (byte) 0xfe; + break; + case 'я': + rez[i] = (byte) 0xff; + break; + default: + rez[i] = (byte) 0x20; + } + } + return rez; + } +} diff --git a/src/main/java/tools/DBTools.java b/src/main/java/tools/DBTools.java new file mode 100644 index 0000000..c9800b3 --- /dev/null +++ b/src/main/java/tools/DBTools.java @@ -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 { + + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + ObjectMapper objectMapper = new ObjectMapper(); + Map 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; + } + +} diff --git a/src/main/java/tools/EmailUtility.java b/src/main/java/tools/EmailUtility.java new file mode 100644 index 0000000..7bf90db --- /dev/null +++ b/src/main/java/tools/EmailUtility.java @@ -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); + } +} \ No newline at end of file diff --git a/src/main/java/tools/PreparedStatementNamed.java b/src/main/java/tools/PreparedStatementNamed.java new file mode 100644 index 0000000..f6830b6 --- /dev/null +++ b/src/main/java/tools/PreparedStatementNamed.java @@ -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 map, String value) { + Iterator> iterator = map.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + if (entry.getValue().equalsIgnoreCase(value)) { + iterator.remove(); + } + } + } + +} diff --git a/src/main/java/tools/Translation.java b/src/main/java/tools/Translation.java new file mode 100644 index 0000000..faae615 --- /dev/null +++ b/src/main/java/tools/Translation.java @@ -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; + } +} diff --git a/src/main/java/tools/User.java b/src/main/java/tools/User.java new file mode 100644 index 0000000..5e9ec22 --- /dev/null +++ b/src/main/java/tools/User.java @@ -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=""; + } +} + diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..921b29c --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,31 @@ + + + + + + + + ${LOGS}/${appName}.log + + {"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","message":"%msg"}%n + + + ${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log + 100MB + 30 + 3GB + + + + + + %d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'} | %level | %logger{36} | %msg%n + + + + + + + + + diff --git a/src/main/resources/templates/engine/index.html b/src/main/resources/templates/engine/index.html new file mode 100644 index 0000000..8180eaa --- /dev/null +++ b/src/main/resources/templates/engine/index.html @@ -0,0 +1,2020 @@ + + + + + + Automated_system_of_data_collection_ASDC + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + +
{{name}} {{patronymic}} {{surname}} ({{ roles.join(', ') }})Language + + Logconfighelpexit
+
+ + +
+ +
+ +
+ +
+ + +
+ + +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Locust_survey
Country
Region
Type_of_locust
From_date
To_date
Method_filling_form
PDA_registered
Displayed_data
Download_QGIS_project
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Spray_monitoring
Country
Region
From_date
To_date
Method_filling_form
PDA_registered
Download_QGIS_project
+
+ + +
+ + + + + + + + + + + + +
HH&Env
Country
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Distribution_of_locust
Country
Region
For_what_year
Kind_of_locust
Displayed_data + +
Download_QGIS_project
+
+ + +
+ + + + + + + + + + + + +
Checkpoints
Country
+
+ + +
+ + + +
+
+ + + + + + + + + + + + + + + + + + + +
Weather_forecast (Soil_temperature)
Country
Date +
+
Download_QGIS_project
+
+ + +
+ + + + + + + + + + + + + + + + + + + +
Air_temperature_2m_above_the_ground
Country
Date +
+
Download_QGIS_project
+
+ + +
+ + + + + + + + + + + + + + + + + + + +
Accumulated_precipitation_in_24_hours
Country
Date +
+
Download_QGIS_project
+
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + +
Hydrothermal_coefficient_of_Selyaninov
Country
Start_date +
+
End_date +
+
Download_QGIS_project
+
+ + + +
+ + + + + + + + + + + + + + + +
NDVI (Normalized_difference_vegetation_index)
Date + +
Download_QGIS_project
+
+ +
+ + + + + + + + + + + + + + + +
IVI (Integral_vegetation_index)
Year + +
Download_QGIS_project
+
+ +
+ + + + + + + + + + + + + + + + + + + +
NDWI (Normalized_difference_water_index)
Date + +
Compare_with + +
Download_QGIS_project
+
+ +
+ + + + + + + + + + + + + + + +
NDSI (Normalised_difference_snow_index)
Date + +
Download_QGIS_project
+
+ +
+ + + + + + + + + + + + + + + +
SMAP L4 9km (Soil_Moisture_Active_Passive)
Date + +
Download_QGIS_project
+
+ + + +
+ +
+ + + +
Reports
+ + + + +
Devices
+ + + +
Standard_survey_forms
+ + + + +
Companies
+ + +
Administration
+ + + + + + + +
Language
+ + + +
Weather
+ + + +
Lists
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ +
+ + + + + + + + +
+ + + + + + + + + + +
+ + + + + \ No newline at end of file diff --git a/src/main/resources/templates/excel.html b/src/main/resources/templates/excel.html new file mode 100644 index 0000000..32211f6 --- /dev/null +++ b/src/main/resources/templates/excel.html @@ -0,0 +1,26 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> + + + + Select the file with CSV to upload and parsing. + + + + +
+ Select CSV UTF-8 file to upload and export: +
+ Skip first line
+ +
+

+ + ${PreviewTable} + +


+ +


+ + + + \ No newline at end of file diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html new file mode 100644 index 0000000..9cf49ed --- /dev/null +++ b/src/main/resources/templates/index.html @@ -0,0 +1,85 @@ + + + + + Automated system of data collection + + + + + + + + + +
+ +
+ +
+

Caucasus and Central Asia Locusts Management system (CCALM)

+

+ + 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. +

+ + + +
+
+
Automated system of data collection (ASDC)
+
+
+
Caucasus and Central Asia Locusts Management system (CCALM)
+
+
+
+ +
+
For any questions contact us at tel./Fax 8(727)3967038, E-mail: info@ccalm.org.
+ +
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/json.html b/src/main/resources/templates/json.html new file mode 100644 index 0000000..ec2b237 --- /dev/null +++ b/src/main/resources/templates/json.html @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> + + + + Select the file with CSV to upload and parsing. + + + + +
+ Select CSV UTF-8 file to upload and export: +
+ +
+

+ + ${PreviewTable} + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/login/login.html b/src/main/resources/templates/login/login.html new file mode 100644 index 0000000..962c9eb --- /dev/null +++ b/src/main/resources/templates/login/login.html @@ -0,0 +1,169 @@ + + + + + + Authorization + + + + + + + + + + + + diff --git a/src/main/resources/templates/privacy.html b/src/main/resources/templates/privacy.html new file mode 100644 index 0000000..42cff98 --- /dev/null +++ b/src/main/resources/templates/privacy.html @@ -0,0 +1,100 @@ + + + + + Automated system of data collection + + + + + + + + + +
+ +

Политика конфиденциальности

+ +

Компания ДТОО "Институт космической техники и технологий" (в дальнейшем ИКТТ) заботится о конфиденциальности данных своих клиентов. Для этих целей была разработана политика конфиденциальности, включающая правила сбора, использования, раскрытия, передачи и хранения Вашей информации. Ознакомьтесь с нашими правилами соблюдения.

+ +

Сбор и использование личной информации

+ +

Личной информацией являются данные, которые можно использовать для установления личности человека или для связи с ним. + Если вы обратитесь в ИКТТ, вас могут попросить предоставить личную информацию. ИКТТ использует ее в соответствии с данной политикой конфиденциальности. Эти сведения могут быть объединены с другими в целях предоставления наших товаров, услуг, материалов и рекламы. Вы не обязаны предоставлять личную информацию, которую мы запросили, но если вы ее не предоставите, во многих случаях мы не сможем предоставить вам свои товары или услуги, а также ответить на ваши запросы. + Вот несколько примеров того, какую личную информацию может собирать и использовать ИКТТ.

+

Какую личную информацию мы собираем

+
    +
  • Когда вы создаете BFT ID, регистрируете свои продукты, обращаетесь для получения кредита, приобретаете продукт, связываетесь с нами или принимаете участие в онлайн-исследовании, мы можем собирать различные сведения, включая ваше имя, почтовый адрес, номер телефона, адрес электронной почты, предпочтительные способы связи, а также данные кредитной карты.
  • +
  • Когда вы отправляете подарочные сертификаты и товары, а также приглашаете других пользователей на форумы ИКТТ, мы можем собирать предоставленную вами информацию об этих людях, включая их имена, почтовые адреса, адреса электронной почты и номера телефонов.
  • +
  • Мы можем запросить данные удостоверения личности для рассмотрения возможности предоставления кредита или выставления платежного поручения для оплаты товаров через банковское отделение.
  • +
+ +

Как мы используем личную информацию

+
    +
  • Мы можем использовать личную информацию для внутренних целей, например при проведении аудита, анализа данных и исследований, направленных на улучшение продуктов и услуг, а также способов общения с клиентами.
  • +
  • Периодически мы используем собранную личную информацию для рассылки важных уведомлений, например сообщений о покупках и об изменениях в условиях и политиках.
  • +
  • Если вы принимаете участие в лотерее, конкурсе или аналогичном мероприятии, мы можем использовать предоставленную вами информацию при организации этих событий.
  • +
+ +

Сбор и использование информации, не являющейся личной

+

Мы также осуществляем сбор данных, которые не указывают непосредственно на конкретного человека. Мы можем собирать, использовать, передавать и раскрывать такие сведения с любой целью. Вот несколько примеров того, какую информацию, не являющуюся личной, мы собираем и используем.

+
    +
  • Для того чтобы лучше понимать поведение клиентов и улучшать наши продукты, услуги и рекламу, мы можем собирать такие сведения, как род деятельности, язык, почтовый индекс, телефонный код, идентификатор устройства, местоположение, в котором используется купленный товар.
  • +
  • Мы можем также собирать информацию о том, чем интересуются пользователи на нашем веб-сайте, на официальных социальных страницах компании. Данные сведения позволяют нам предоставлять клиентам более полезную информацию, а также понять, какие разделы веб-сайта, продукты и сервисы пользуются повышенным интересом. В контексте данной политики конфиденциальности обобщенные данные рассматриваются в качестве информации, не являющейся личной.
  • +
+

При объединении информации, не являющейся личной, с личной информацией объединенные данные будут считаться личными, пока они остаются объединенными.

+

Раскрытие информации третьим лицам

+

Эта информация не передается третьим лицам.

+

Поставщики услуг

+

ИКТТ обменивается личными данными пользователей с компаниями, которые предоставляют такие услуги, как обработка информации, выдача или продление срока кредита, выполнение заказов клиентов, доставка продуктов, управление данными клиентов и их расширение, обслуживание клиентов, оценка заинтересованности пользователей в наших продуктах и услугах, а также проведение исследований и опросов с целью определения степени удовлетворенности. Эти компании обязуются защищать ваши данные и могут быть расположены только на территории Республики Казахстан.

+

Прочее

+

Компания ИКТТ может быть обязана раскрыть вашу личную информацию в соответствии с законодательством, требованиями судопроизводства, судебного разбирательства или по запросу государственных органов страны вашего пребывания или других стран. Мы также можем раскрыть вашу личную информацию, если это будет необходимо в целях национальной безопасности, исполнения закона или в иных общественно важных целях.

+

Мы также можем раскрыть вашу личную информацию, если это будет необходимо для выполнения наших условий или защиты наших операций или пользователей. Кроме того, в случае реорганизации, слияния или продажи компаний мы можем передавать личные данные соответствующей третьей стороне.

+

Защита личной информации

+

ИКТТ очень серьезно относится к защите вашей личной информации. Онлайн-сервисы ИКТТ, такие как Корзина и Личный кабинет, защищают вашу личную информацию во время передачи при помощи шифрования, например по протоколу SSL. Для хранения вашей личной информации ИКТТ использует компьютерные системы с ограниченным доступом, расположенные в помещениях с физическими средствами охраны. Данные Личного кабинета хранятся в зашифрованном виде, в том числе при использовании сторонних хранилищ.

+

Когда вы пользуетесь некоторыми продуктами, услугами или приложениями Apple, публикуете сообщения в социальных сервисах, ведете переписку в чате, публикуемую вами личную информацию могут видеть, читать, собирать и использовать другие пользователи. Вы несете ответственность за то, какую информацию вы раскрываете в таких случаях. Например, если вы указываете свои имя и адрес электронной почты в обсуждении на форуме или блоге, такая информация становится общедоступной. Проявляйте осторожность в таких ситуациях.

+

Целостность и хранение личной информации

+

С помощью ИКТТ вы легко сможете обеспечить точность, полноту и актуальность своей личной информации. Мы будем хранить вашу личную информацию в течение срока, необходимого для исполнения обязательств, которые указаны в данной политике конфиденциальности, если иное не предусмотрено законом.

+

Доступ к личной информации

+

Вы можете помочь нам обеспечить точность, полноту и актуальность вашей контактной информации и личных предпочтений, выполнив вход в учетную запись на сайте ccalm.org. Что касается остальных данных, мы обеспечим вам доступ к вашей личной информации, чтобы вы, в частности, могли подать запрос об исправлении или удалении данных, кроме случаев, когда хранение информации предусмотрено законом или необходимо компании ИКТТ для осуществления деятельности в рамках действующего законодательства. Мы можем отказать в исполнении запросов, которые необоснованны либо обременительны, нарушают конфиденциальность других пользователей, не имеют смысла или доступ к которым в соответствии с локальным законодательством не является обязательным. Запросы на доступ к данным, исправление или удаление данных можно подать по электронной почте.

+

Глобальные обязательства по конфиденциальности

+

В целях защиты личной информации мы знакомим сотрудников ИКТТ с рекомендациями по безопасности и конфиденциальности и обеспечиваем их строгое исполнение в компании.

+

Вопросы о конфиденциальности

+

Если у вас возникли вопросы или сомнения по поводу политики конфиденциальности ИКТТ или обработки данных либо вы хотите сообщить о предполагаемом нарушении местных законов о конфиденциальности, свяжитесь с нами по почте info@ccalm.org. Вы можете в любой момент связаться с нами по телефону +7 (727) 229-44-81.

+

Мы проверяем все обращения и стараемся отвечать на них в кратчайшие сроки. Если вы недовольны полученным ответом, направьте жалобу в соответствующий регулятивный орган своей страны. Если вы хотите получить исчерпывающую информацию о способах подать жалобу, уместных в ваших обстоятельствах, обратитесь к нам.

+

Компания ИКТТ периодически обновляет политику конфиденциальности. При изменении политики мы размещаем уведомление об этом на нашем веб-сайте вместе с новым текстом политики конфиденциальности.

+

ДТОО "Институт космической техники и технологий", Almaty, Kazakhstan

+ +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/redirect.html b/src/main/resources/templates/redirect.html new file mode 100644 index 0000000..774db2d --- /dev/null +++ b/src/main/resources/templates/redirect.html @@ -0,0 +1,14 @@ + + + + + Redirect + + + +

Please wait, redirecting...

+

If redirection did not occur, click here.

+ + diff --git a/src/main/resources/templates/test.html b/src/main/resources/templates/test.html new file mode 100644 index 0000000..b33a5c6 --- /dev/null +++ b/src/main/resources/templates/test.html @@ -0,0 +1,679 @@ + + + + + Caucasus and Central Asia Locusts Management system (CCALM) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+ English Русский + +
+
+
+ +
+
+
+
Caucasus_and_Central_Asia_Locusts_Management_system (CCALM)
+ + + +
+ + + + + + + + + + + + +
ASDCCCALM
+
+
+ + + + + + +
+
+
+
+

Locust_Data with ___ to ___

+
+
+ +
+
+ + + + +
+
+
+ + + + + + + +
Adult
Hoppers
Egg_pod
Spraying
Not_infected
+
+
+ +
+
+ + + + + +
+ + +
+ + + +
+
+

ASDC_Field_Data

+
+
+
+
Locust_survey
+
+ +
+
+
Spray_monitoring
+
+
+
+
Safety_and_environment
+
+
+
+
+ +
+
+

CALM_and_other_data

+
+ +
+
+
Soil_temperature_at_a_depth_of_10_cm
+
+ +
+
+
Air_temperature_2m_above_the_ground
+
+ +
+
+
Accumulated_precipitation_in_24_hours
+
+ +
+
+
Hydrothermal_coefficient_of_Selyaninov
+
+ +
+
+
NDVI Normalized_difference_vegetation_index
+
+ +
+
+
IVI Integral_vegetation_index
+
+ +
+
+
NDWI Normalized_difference_water_index
+
+
+
+
NDSI Normalised_difference_snow_index
+
+ +
+
+
+ + + + +
+ + +
+ + + + + + +
+ +
+ + + + +
+ + +
+ + + + + \ No newline at end of file diff --git a/src/main/resources/templates/translation.html b/src/main/resources/templates/translation.html new file mode 100644 index 0000000..230bb8d --- /dev/null +++ b/src/main/resources/templates/translation.html @@ -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}]] +}; \ No newline at end of file diff --git a/src/test/java/org/ccalm/main/MainApplicationTests.java b/src/test/java/org/ccalm/main/MainApplicationTests.java new file mode 100644 index 0000000..2f607de --- /dev/null +++ b/src/test/java/org/ccalm/main/MainApplicationTests.java @@ -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() { + } + +}